refactor(frontend): 拆 types.ts(871) / ws.ts::dispatchFrame(266)(纯搬移 + barrel)

执行方案 DevDocs/audit/_plan.md 阶段 0 · G0-D:
- lib/types.ts(871) → lib/types/ 11 个域文件 + 14 行 `export *` barrel(仿 lib/api.ts 先例)
  chat / ws / session / agent / flow / persona / api / admin(269) / adminWrite(176) / kook /
  notification
- lib/ws.ts(494) → 203 行入口 + lib/ws/handlers/ 8 文件;dispatchFrame(266 行) 改为按组
  分发链(7 个 handler 各持一组 case,命中 return true,未命中走原 default 兜底),
  33 个 case 标签一一守恒

机械证明:type 导出集 86 个守恒(拆后并集 diff 为空);去掉空行与 import/export 语句后
**784=784 行、排序 diff 为空**;dispatchFrame 的 case 标签集 33=33 守恒;ws.ts 的
scheduleReconnect 至文件尾与 HEAD 字节级一致。
65 个 lib/types 消费方 + 3 个 lib/ws 消费方**零改动**通过 —— tsc 0 错误正是这一点的强判据。

验证:npx tsc --noEmit 0 错误;npm run build 成功;9 个前端逻辑测试全绿(含真实驱动
拆后 dispatchFrame 的 messageSync 54 checks 与 personaSession 23 checks);
最大文件 admin.ts 269 行、最大函数 openSocket 72 行(均达标)。
This commit is contained in:
AskaEth committed 2026-10-04 10:54:06 +08:00
1 parent e9afca9b29
commit 6e0323b446
21 files changed
+1288 -1183

No files matched your search

+24 -315
View File
@@ -1,21 +1,15 @@
import { messageEventApplies, useAppStore } from "../store/useAppStore";
import { useAppStore } from "../store/useAppStore";
import { useModeStore } from "../store/useModeStore";
import { getAuthToken, isTokenExpired, onAuthExpired, setAuthToken } from "./api";
import {
parseAdminChannelMessage,
parseAgent,
parseAwakenTool,
parseBackthinkItem,
parseGraph,
parsePersistedMessage,
parseTool,
parseToolCall,
playVoiceAudio,
toRecord,
} from "./wsParse";
import { MODES, type AwakenState, type ChatMessage, type Mode, type WsUpEvent } from "./types";
import { sessionReadTarget } from "./sessionRead";
import { streamFrameApplies } from "./streamScope";
import { toRecord } from "./wsParse";
import type { WsUpEvent } from "./types";
import { handleStreamEvent } from "./ws/handlers/stream";
import { handleThinkingEvent } from "./ws/handlers/thinking";
import { handleToolEvent } from "./ws/handlers/tool";
import { handleMessageEvent } from "./ws/handlers/message";
import { handleAgentEvent } from "./ws/handlers/agent";
import { handleSessionEvent } from "./ws/handlers/session";
import { handleDeviceEvent } from "./ws/handlers/device";
/**
* Realtime client for `/ws/chat`. Reconnects with exponential backoff and
@@ -28,11 +22,6 @@ let shouldRun = false;
let reconnectTimer: number | null = null;
let attempt = 0;
/** Accumulator for a streamed thinking segment (thinking.* events). Reset on
* thinking.start so a mid-turn reconnect can rebuild the collapsed block
* without relying on prior state. */
let pendingThinking = "";
const MAX_BACKOFF = 30_000;
const BASE_BACKOFF = 1_000;
@@ -43,307 +32,27 @@ function wsUrl(): string {
return `${proto}://${window.location.host}/ws/chat${qs}`;
}
/** The fields of a `message_edited` payload the chat needs: the edited message's
* id and its new content. `sessionId` is carried inside the broadcast DTO (and on
* the frame envelope) so the frame can be filtered; `mode`/`mood` are optional —
* an edit never changes them, but the DTO carries them for completeness. */
interface MessageEdited {
id: string;
content: string;
sessionId?: string;
mode?: Mode;
mood?: string;
}
/** Narrow a `message_edited` payload (the updated message DTO), or null when it is
* unusable. `content` is required: an edit always carries the new text, and a
* frame without it must not blank out a rendered bubble. */
function parseMessageEdited(data: unknown): MessageEdited | null {
const r = toRecord(data);
if (!r || typeof r.id !== "string" || r.id === "" || typeof r.content !== "string") {
return null;
}
return {
id: r.id,
content: r.content,
sessionId: typeof r.sessionId === "string" ? r.sessionId : undefined,
mode:
typeof r.mode === "string" && MODES.includes(r.mode as Mode)
? (r.mode as Mode)
: undefined,
mood: typeof r.mood === "string" ? r.mood : undefined,
};
}
/** Route one decoded downstream frame into the store. Exported (with a `frame`
* shaped first argument) so the frame→store mapping can be exercised as a pure
* logic test without a browser: this project has no jsdom/test runner, so the
* socket lifecycle around it stays untested while the mapping does not have to. */
* socket lifecycle around it stays untested while the mapping does not have to.
* 帧按类型分组在 lib/ws/handlers/* 中处理:任一组命中(含组内主动丢弃)即结束,
* 全部未命中走下方未知帧兜底 —— 与拆分前的单个 switch 等价。 */
export function dispatchFrame(ev: { type: string; sessionId?: string; data: unknown }): void {
const s = useAppStore.getState();
const r = toRecord(ev.data);
switch (ev.type) {
case "stream_chunk": {
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
if (r && typeof r.delta === "string") s.appendChunk(r.delta);
break;
}
case "stream_end": {
// Another session's turn ending must not close the streaming bubble on
// screen or clear this conversation's busy badge (both are single-slot
// state: the last message's flag, and one shell-wide `sessionBusy`).
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
s.endStream();
// The assistant reply stopped streaming, so the immediate turn is over:
// close the busy/pending window so the badge does not stick. If the backend
// keeps a task/subagent running it re-emits session_busy (design/15 §5).
s.setSessionBusy(false, 0);
if (r && typeof r.stopReason === "string") {
s.setContext({ lastAgentMode: s.context.lastAgentMode });
}
break;
}
// Structured stream events (design/04 §1.1, aligned with OpenClaw). These
// arrive in place of the legacy stream_chunk when the loop streams events.
case "message.start": {
// The assistant bubble is already opened by useChat; nothing to do here.
break;
}
case "message.delta": {
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
if (r && typeof r.delta === "string") s.appendChunk(r.delta);
break;
}
case "message.end": {
// Body-text segment closed; the turn may continue with tool calls, so we
// do NOT end the stream here (stream_end owns that).
break;
}
case "message_persisted": {
// design/16 §4.2 — a user or assistant message was persisted and broadcast
// with its backend id. Only surface messages for the active session; the
// store dedups by id and adopts the local optimistic bubble (uid → backend
// id), so both the originating and remote browsers converge on one message.
const msg = parsePersistedMessage(r?.message);
if (msg && msg.sessionId === s.activeSessionId) {
s.appendOrUpdateMessage(msg);
}
break;
}
case "message_edited": {
// design/16 §4.2 (D3 edit path) — the stored message's content was changed
// and broadcast with the updated DTO. The backend row stays the single source
// of truth; this only re-renders the bubble, and only in the session it
// belongs to (same filter as message_persisted). Patch by id — an id we do not
// hold is another session's (or an already-gone) message, never a new row.
const edit = parseMessageEdited(ev.data);
if (!edit) break;
if (messageEventApplies(edit.sessionId ?? ev.sessionId, s.activeSessionId)) {
const patch: Partial<ChatMessage> = { content: edit.content };
if (edit.mode) patch.mode = edit.mode;
if (edit.mood) patch.mood = edit.mood;
s.updateMessageById(edit.id, patch);
}
break;
}
case "message_deleted": {
// design/16 §4.2 (D3 delete path) — the message was removed server-side, so
// drop it by id instead of waiting for a manual re-read. The id is globally
// unique; sessionId is advisory and, when present, must be the active one.
const id = r && typeof r.id === "string" ? r.id : "";
if (id && messageEventApplies(ev.sessionId, s.activeSessionId)) {
s.removeMessageById(id);
}
break;
}
case "channel_persisted": {
// design/16 §4.6 §4 — an isolated (group/stranger) channel message was
// persisted and broadcast for the IM adapter log page. The web chat has no
// handler for this type, so it never reaches the active conversation; the
// admin adapter log consumes it via `channelEvents` to append in realtime.
const msg = parseAdminChannelMessage(r?.message);
if (msg) s.pushChannelEvent(msg);
break;
}
case "backthink": {
// design/12 §4 — a background-think pass result was persisted. Head-insert into
// the store so the admin backthink panel appends it in realtime (rows keyed by
// id → React reconciles incrementally, no whole-page re-render).
const item = parseBackthinkItem(r);
if (item) s.addBackthink(item);
break;
}
case "thinking.start": {
// Guarded like the deltas: only the active conversation may reset the
// accumulator (which also bounds a switched-away session's stale text).
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
pendingThinking = "";
break;
}
case "thinking.delta": {
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
if (r && typeof r.delta === "string") {
pendingThinking += r.delta;
s.setThinking(pendingThinking);
}
break;
}
case "thinking.end": {
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
if (pendingThinking) s.setThinking(pendingThinking);
pendingThinking = "";
break;
}
case "tool_call.start":
case "tool_call.end": {
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
const tool = parseToolCall(ev.data);
if (tool) s.addTool(tool);
break;
}
case "tool_call.delta": {
// Argument fragments stream between start/end; the card is added at the
// boundary so mid-stream reconnects do not drop it.
break;
}
case "tool_execution.update": {
// Same card as tool_call.* — same guard.
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
const tool = parseToolCall(ev.data);
if (tool) s.addTool(tool);
break;
}
case "thinking": {
// Legacy single-shot CoT frame — renders into the same bubble.
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
if (typeof ev.data === "string") {
s.setThinking(ev.data);
} else if (r && typeof r.text === "string") {
s.setThinking(r.text);
}
break;
}
case "mood": {
// Role-scoped (design/22 §4.6): the frame names the persona the change
// belongs to and carries no sessionId, so the bucket key is personaId —
// each role's mood stays with its own conversations. A legacy string frame
// has nowhere to put it, so it lands in the unscoped "" bucket.
if (typeof ev.data === "string") {
s.setMood(ev.data);
} else if (r && typeof r.mood === "string") {
s.setMood(r.mood, typeof r.personaId === "string" ? r.personaId : "");
}
break;
}
case "tool_used": {
// Legacy tool echo — same card as tool_call.*.
if (!streamFrameApplies(ev, r, s.activeSessionId)) break;
const tool = parseTool(ev.data);
if (tool) s.addTool(tool);
break;
}
case "subagent_event": {
const agent = parseAgent(ev.data ?? r);
if (agent) s.upsertAgent(agent);
break;
}
case "graph_update": {
const g = parseGraph(ev.data);
if (g) s.setFlowGraph(g);
break;
}
case "task_output": {
if (r) {
const taskId = typeof r.taskId === "string" ? r.taskId : "main";
const output =
typeof r.output === "string"
? r.output
: typeof r.line === "string"
? r.line
: typeof ev.data === "string"
? ev.data
: JSON.stringify(ev.data);
s.appendTaskLog(taskId, output + "\n");
}
break;
}
case "device_update": {
if (typeof ev.data === "string") s.addDeviceUpdate(ev.data);
else if (r && typeof r.message === "string") s.addDeviceUpdate(r.message);
break;
}
case "reminder": {
if (typeof ev.data === "string") s.addDeviceUpdate(`提醒:${ev.data}`);
else if (r && typeof r.message === "string") s.addDeviceUpdate(`提醒:${r.message}`);
break;
}
case "error": {
const msg = r && typeof r.message === "string" ? r.message : "未知错误";
s.addDeviceUpdate(`WS 错误:${msg}`);
break;
}
case "auth": {
// handshake acknowledgement; nothing to persist yet.
break;
}
case "mode_switch": {
// The agent drives the behavior mode (design/01 §3). Apply it to the shell
// so newly begun message bubbles render per that mode.
if (r && typeof r.mode === "string") {
const m = r.mode as Mode;
if (MODES.includes(m)) useModeStore.getState().setMode(m);
}
break;
}
case "voice_output": {
// Voice turn reply: the backend sends back the synthesized audio plus the
// recognized transcript and the assistant reply. Playback is best-effort
// (autoplay may be blocked); the transcript/reply is surfaced as a log line.
playVoiceAudio(ev.data);
if (r && typeof r.reply === "string") {
s.addDeviceUpdate(`语音回复:${r.reply}`);
} else if (r && typeof r.text === "string") {
s.addDeviceUpdate(`语音识别:${r.text}`);
}
break;
}
case "capacity_awaken": {
// design/14 §5 — 能力点亮:静息 → 唤醒 → 全能 + 本轮点亮工具。前端据此更新唤醒徽标/唤醒路径。
const fromState =
typeof r?.fromState === "string"
? (r.fromState as AwakenState)
: undefined;
const toState =
(typeof r?.toState === "string" ? (r.toState as AwakenState) : undefined) ??
"quiet";
s.setAwaken(fromState, toState, parseAwakenTool(r?.tool));
break;
}
case "session_busy":
case "session_pending": {
// design/15 §5 — 她忙/有挂起消息时的轻状态(不阻塞输入框)。两者同构:都是 {busy, pendingCount}。
const busy = typeof r?.busy === "boolean" ? r.busy : true;
const pendingCount =
typeof r?.pendingCount === "number" ? r.pendingCount : s.pendingCount;
s.setSessionBusy(busy, pendingCount);
break;
}
case "session_read": {
// 协同 B3/D4 — one end marked the conversation read, so the unread badge goes
// out on every end. Only the addressed session is touched (a frame naming
// another conversation must not clear the dot of the one on screen), and an
// unattributable frame is dropped rather than guessed.
const id = sessionReadTarget(ev.sessionId, r);
if (id) s.clearUnread(id);
break;
}
default: {
// Unknown future event: keep it in the context log so no frame is lost.
const text = typeof ev.data === "string" ? ev.data : JSON.stringify(ev.data);
s.addDeviceUpdate(`[${ev.type}] ${text}`);
}
}
if (handleStreamEvent(ev, r, s)) return;
if (handleThinkingEvent(ev, r, s)) return;
if (handleToolEvent(ev, r, s)) return;
if (handleMessageEvent(ev, r, s)) return;
if (handleAgentEvent(ev, r, s)) return;
if (handleSessionEvent(ev, r, s)) return;
if (handleDeviceEvent(ev, r, s)) return;
// Unknown future event: keep it in the context log so no frame is lost.
const text = typeof ev.data === "string" ? ev.data : JSON.stringify(ev.data);
s.addDeviceUpdate(`[${ev.type}] ${text}`);
}
function scheduleReconnect(): void {