@njuptlzf/agent-chat-web 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/AgentChat.d.ts +7 -1
  2. package/dist/AgentChat.js +35 -5
  3. package/dist/AgentChatApp.d.ts +4 -1
  4. package/dist/AgentChatApp.js +2 -2
  5. package/dist/PersonasPage.js +8 -0
  6. package/dist/adapter.d.ts +9 -0
  7. package/dist/adapter.js +15 -0
  8. package/dist/mount.d.ts +7 -1
  9. package/dist/mount.js +2 -2
  10. package/dist/styles.css +1505 -1478
  11. package/dist/suggestions.d.ts +41 -0
  12. package/dist/suggestions.js +98 -0
  13. package/dist/ui/FollowUpSuggestions.d.ts +9 -0
  14. package/dist/ui/FollowUpSuggestions.js +13 -0
  15. package/dist/ui/Icon.d.ts +8 -0
  16. package/dist/ui/Icon.js +26 -0
  17. package/dist/ui/MemberCards.d.ts +15 -0
  18. package/dist/ui/MemberCards.js +13 -0
  19. package/dist/ui/icons.d.ts +19 -0
  20. package/dist/ui/icons.js +25 -0
  21. package/dist/ui/members.d.ts +42 -0
  22. package/dist/ui/members.js +53 -0
  23. package/dist/ui/slots.d.ts +29 -0
  24. package/dist/ui/slots.js +14 -0
  25. package/package.json +71 -72
  26. package/src/App.tsx +13 -13
  27. package/src/agent-chat/AgentChat.tsx +741 -692
  28. package/src/agent-chat/AgentChatApp.tsx +211 -206
  29. package/src/agent-chat/DockPanel.tsx +73 -73
  30. package/src/agent-chat/PersonasPage.tsx +705 -678
  31. package/src/agent-chat/adapter.ts +293 -272
  32. package/src/agent-chat/app-def-check.ts +215 -215
  33. package/src/agent-chat/app.tsx +327 -327
  34. package/src/agent-chat/auth.ts +83 -83
  35. package/src/agent-chat/dock.ts +161 -161
  36. package/src/agent-chat/docs.ts +179 -179
  37. package/src/agent-chat/index.ts +17 -17
  38. package/src/agent-chat/mount.tsx +130 -123
  39. package/src/agent-chat/qual.ts +55 -55
  40. package/src/agent-chat/sse.ts +104 -104
  41. package/src/agent-chat/suggestions.ts +127 -0
  42. package/src/agent-chat/theme.ts +23 -23
  43. package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -29
  44. package/src/agent-chat/ui/ConfirmCard.tsx +32 -32
  45. package/src/agent-chat/ui/FollowUpSuggestions.tsx +28 -0
  46. package/src/agent-chat/ui/Icon.tsx +53 -0
  47. package/src/agent-chat/ui/Lightbox.tsx +32 -32
  48. package/src/agent-chat/ui/MemberCards.tsx +46 -0
  49. package/src/agent-chat/ui/QueueBar.tsx +70 -70
  50. package/src/agent-chat/ui/Splitter.tsx +81 -81
  51. package/src/agent-chat/ui/ThemeToggle.tsx +25 -25
  52. package/src/agent-chat/ui/TierPicker.tsx +112 -112
  53. package/src/agent-chat/ui/UIPromptCard.tsx +68 -68
  54. package/src/agent-chat/ui/icons.ts +31 -0
  55. package/src/agent-chat/ui/members.ts +106 -0
  56. package/src/agent-chat/ui/slots.tsx +41 -0
  57. package/src/agent-chat/ui/timefmt.ts +110 -110
  58. package/src/agent-chat/ui/useNarrow.ts +20 -20
  59. package/src/fake-product/entry.tsx +63 -54
  60. package/src/main.tsx +8 -8
  61. package/src/styles.css +1505 -1478
@@ -1,272 +1,293 @@
1
- import type { ChatAttachment, ChatEvent, ChatImage, ChatRequest, TokenUsage } from "@njuptlzf/agent-chat-protocol";
2
- import type { ChatModelAdapter, MessageTiming, ThreadAssistantMessagePart } from "@assistant-ui/react";
3
- import type { ToolCallMessagePart } from "@assistant-ui/react";
4
- import { postJson, streamChat } from "./sse.ts";
5
-
6
- /** `data:image/png;base64,AAAA` -> the bare base64 the wire wants. */
7
- const DATA_URL = /^data:([^;,]+);base64,(.+)$/;
8
-
9
- /** A composer attachment data URL in the wire shape, or undefined if it is not an inline image. */
10
- export function dataUrlToImage(url: string): ChatImage | undefined {
11
- const m = DATA_URL.exec(url);
12
- return m ? { mimeType: m[1], data: m[2] } : undefined;
13
- }
14
-
15
- type PartLike = { type: string };
16
- type LastLike = {
17
- role: string;
18
- content: readonly PartLike[];
19
- attachments?: readonly { content?: readonly PartLike[] }[];
20
- };
21
-
22
- function imageParts(last: LastLike | undefined): ChatImage[] {
23
- if (last?.role !== "user") return [];
24
- const out: ChatImage[] = [];
25
- const push = (part: PartLike) => {
26
- if (part.type !== "image") return;
27
- const url = (part as { image?: string }).image;
28
- const img = typeof url === "string" ? dataUrlToImage(url) : undefined;
29
- if (img) out.push(img);
30
- };
31
- for (const part of last.content) push(part);
32
- // The edit composer lifts a user message's non-text parts out of `content`
33
- // into `attachments`, so an edited image would otherwise be dropped on re-send.
34
- for (const att of last.attachments ?? []) for (const part of att.content ?? []) push(part);
35
- return out;
36
- }
37
-
38
- /**
39
- * The converted-document parts docs.ts puts on a user message (type "file",
40
- * mimeType "text/markdown", data = the Markdown itself). Same both-places scan
41
- * as imageParts: the edit composer lifts non-text parts into `attachments`.
42
- */
43
- function docParts(last: LastLike | undefined): ChatAttachment[] {
44
- if (last?.role !== "user") return [];
45
- const out: ChatAttachment[] = [];
46
- const push = (part: PartLike) => {
47
- if (part.type !== "file") return;
48
- const p = part as { filename?: string; data?: string; mimeType?: string };
49
- if (p.mimeType !== "text/markdown" || typeof p.data !== "string" || p.data.trim() === "") return;
50
- out.push({ name: p.filename ?? "附件", text: p.data });
51
- };
52
- for (const part of last.content) push(part);
53
- for (const att of last.attachments ?? []) for (const part of att.content ?? []) push(part);
54
- return out;
55
- }
56
-
57
- export interface ChatBridge {
58
- getSessionId(): string | undefined;
59
- setSessionId(sessionId: string): void;
60
- getContext(): Record<string, unknown> | undefined;
61
- getAuthToken(): string | undefined;
62
- /** The chosen quality tier id, or undefined to run the manifest default. */
63
- getTier(): string | undefined;
64
- /** The scope this conversation belongs to, or undefined to run the product default. */
65
- getScope(): string | undefined;
66
- /** 人格:undefined = 产品默认(默认助手)。会话一旦建立就绑死,换人格会 400。 */
67
- getPersona?(): string | undefined;
68
- onRunEnd(info: { usage: TokenUsage | null; aborted: boolean }): void;
69
- /** The server paused a gated tool and waits for POST /api/decision. */
70
- onToolConfirm(info: { sessionId: string; toolCallId: string; name: string; args: Record<string, unknown> }): void;
71
- /** A confirmed tool call finished (approved or denied); dismiss its card. */
72
- onToolSettled(toolCallId: string): void;
73
- /** 工具中文名:服务端首帧下发一次,UI 只显示这句,不显示 mcp__ 声明名。 */
74
- onToolsMeta?(labels: Record<string, string>): void;
75
- /** An extension is waiting for an answer (select/confirm/input); POST /api/ui-response when decided. */
76
- onUiPrompt(prompt: UiPromptEvent): void;
77
- /** An extension sent a notification; show it, no answer expected. */
78
- onUiNotify(note: UiNotifyEvent): void;
79
- }
80
-
81
- /**
82
- * Set when an edit composer submits, consumed by the next run.
83
- *
84
- * The server keeps the transcript, so an edited message must drop the
85
- * superseded turn before the new one is sent. The run is the only place that
86
- * both knows the session id and can await the cleanup, and assistant-ui gives
87
- * the adapter no "this is an edit" flag (`sourceId` is dropped before
88
- * ChatModelRunOptions). Module-level state is fine here: one chat runtime per
89
- * page, and the flag is only ever set synchronously on the send path.
90
- */
91
- let editPending = false;
92
-
93
- /** Mark the next run as an edit. Call it before the composer sends. */
94
- export function markEdit(): void {
95
- editPending = true;
96
- }
97
-
98
- type ToolCallPart = Extract<ThreadAssistantMessagePart, { type: "tool-call" }>;
99
-
100
- /** An extension dialog forwarded by the server (event and POST /api/ui-response payload share this shape). */
101
- export type UiPromptEvent = Extract<ChatEvent, { type: "ui_prompt" }>;
102
- /** A fire-and-forget `ctx.ui.notify` from an extension. */
103
- export type UiNotifyEvent = Extract<ChatEvent, { type: "ui_notify" }>;
104
-
105
- /**
106
- * Bridges our SSE wire protocol to assistant-ui's ChatModelAdapter.
107
- *
108
- * The server owns the conversation history (resume by sessionId), so a run
109
- * sends only the newest user message — never the whole transcript.
110
- */
111
- export function createChatAdapter(bridge: ChatBridge): ChatModelAdapter {
112
- return {
113
- async *run({ messages, abortSignal }) {
114
- const last = messages.at(-1);
115
- const userText =
116
- last?.role === "user"
117
- ? last.content.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join("")
118
- : "";
119
-
120
- const req: ChatRequest = { message: userText };
121
- const sid = bridge.getSessionId();
122
- if (sid) req.sessionId = sid;
123
- const ctx = bridge.getContext();
124
- if (ctx) req.context = ctx;
125
- const tier = bridge.getTier();
126
- if (tier) req.tier = tier;
127
- const scope = bridge.getScope();
128
- if (scope) req.scope = scope;
129
- const persona = bridge.getPersona?.();
130
- if (persona) req.persona = persona;
131
- const images = imageParts(last);
132
- if (images.length > 0) req.images = images;
133
- const docs = docParts(last);
134
- if (docs.length > 0) req.attachments = docs;
135
-
136
- // Drop the superseded turn before the new one is appended; the server
137
- // rebuilds its model context from this transcript on every run, so the
138
- // old answer must be gone before /api/chat reads it. A failed cleanup is
139
- // surfaced as text rather than thrown: the user's message is already in
140
- // the transcript, and silently re-sending on top of the stale turn is
141
- // exactly the bug this feature exists to fix.
142
- if (editPending) {
143
- editPending = false;
144
- if (sid) {
145
- try {
146
- await postJson("/api/history/truncate-last-turn", { sessionId: sid }, bridge.getAuthToken());
147
- } catch (err) {
148
- yield {
149
- content: [{ type: "text", text: `⚠️ 编辑未能生效(旧回答仍在上下文里):${(err as Error).message}` }],
150
- status: { type: "incomplete", reason: "error" },
151
- };
152
- bridge.onRunEnd({ usage: null, aborted: false });
153
- return;
154
- }
155
- }
156
- }
157
-
158
- const parts: ThreadAssistantMessagePart[] = [];
159
- const appendDelta = (kind: "text" | "reasoning", delta: string) => {
160
- const tail = parts.at(-1);
161
- if (tail && tail.type === kind) (tail as { text: string }).text += delta;
162
- else parts.push({ type: kind, text: delta });
163
- };
164
-
165
- // E3: assistant-ui renders metadata.timing through the official
166
- // useMessageTiming hook but has no producer on the local-runtime path
167
- // (useStreamingTiming serves external stores; TimingTracker is not
168
- // exported from any entry). So we measure it right here: the
169
- // user-perceived wait from sending the request to the first visible
170
- // output. `ready` is a transport ack and not a token; thinking and
171
- // tool_start count, because they are the first thing on screen. The
172
- // clock starts after the edit-truncate cleanup, which is not model wait.
173
- const streamStartTime = Date.now();
174
- let firstTokenAt: number | undefined;
175
- let chunks = 0;
176
- let toolCalls = 0;
177
- const snapshot = (): MessageTiming => ({
178
- streamStartTime,
179
- totalChunks: chunks,
180
- toolCallCount: toolCalls,
181
- totalStreamTime: Date.now() - streamStartTime,
182
- ...(firstTokenAt === undefined ? {} : { firstTokenTime: firstTokenAt - streamStartTime }),
183
- });
184
-
185
- let usage: TokenUsage | null = null;
186
- let aborted = false;
187
- try {
188
- for await (const ev of streamChat(req, abortSignal, bridge.getAuthToken()) as AsyncGenerator<ChatEvent>) {
189
- switch (ev.type) {
190
- case "ready":
191
- bridge.setSessionId(ev.sessionId);
192
- continue;
193
- case "tools_meta":
194
- bridge.onToolsMeta?.(ev.labels);
195
- continue;
196
- case "text_delta":
197
- firstTokenAt ??= Date.now();
198
- appendDelta("text", ev.delta);
199
- break;
200
- case "thinking_delta":
201
- firstTokenAt ??= Date.now();
202
- appendDelta("reasoning", ev.delta);
203
- break;
204
- case "tool_start":
205
- firstTokenAt ??= Date.now();
206
- toolCalls++;
207
- parts.push({
208
- type: "tool-call",
209
- toolCallId: ev.toolCallId,
210
- toolName: ev.name,
211
- args: ev.args as ToolCallPart["args"],
212
- argsText: JSON.stringify(ev.args),
213
- });
214
- break;
215
- case "tool_confirm":
216
- bridge.onToolConfirm({ sessionId: bridge.getSessionId() ?? "", toolCallId: ev.toolCallId, name: ev.name, args: ev.args });
217
- continue;
218
- case "tool_update":
219
- case "tool_end": {
220
- if (ev.type === "tool_end") bridge.onToolSettled(ev.toolCallId);
221
- const i = parts.findIndex((p) => p.type === "tool-call" && p.toolCallId === ev.toolCallId);
222
- if (i >= 0) {
223
- const p = parts[i] as ToolCallPart;
224
- const view = ev.type === "tool_end" ? ev.result : ev.partial;
225
- parts[i] = {
226
- ...p,
227
- // details 搭 tool_end 顺风车(零协议改动)——
228
- // 卡片的排版数据从这里来,文本只喂模型/兜底展示。
229
- result: { text: view.text, details: view.details } as ToolCallPart["result"],
230
- isError: ev.type === "tool_end" ? !ev.ok : p.isError,
231
- };
232
- }
233
- break;
234
- }
235
- case "error":
236
- parts.push({ type: "text", text: `⚠️ ${ev.message}` });
237
- break;
238
- case "message_end":
239
- if (ev.usage) usage = ev.usage;
240
- continue;
241
- case "ui_prompt":
242
- // The server parked the run inside the extension's await; the run
243
- // resumes when the dialog is answered (or fails closed on timeout).
244
- bridge.onUiPrompt(ev);
245
- continue;
246
- case "ui_notify":
247
- bridge.onUiNotify(ev);
248
- continue;
249
- case "done":
250
- usage ??= ev.usage;
251
- aborted = ev.aborted;
252
- continue;
253
- }
254
- chunks++;
255
- yield { content: [...parts], metadata: { timing: snapshot() } };
256
- }
257
- } catch (err) {
258
- if ((err as Error).name !== "AbortError") {
259
- parts.push({ type: "text", text: `⚠️ 网络错误:${(err as Error).message}` });
260
- }
261
- aborted = true;
262
- }
263
-
264
- bridge.onRunEnd({ usage, aborted });
265
- yield {
266
- content: [...parts],
267
- status: aborted ? { type: "incomplete", reason: "cancelled" } : undefined,
268
- metadata: usage ? { custom: { usage }, timing: snapshot() } : { timing: snapshot() },
269
- };
270
- },
271
- };
272
- }
1
+ import type { ChatAttachment, ChatEvent, ChatImage, ChatRequest, TokenUsage } from "@njuptlzf/agent-chat-protocol";
2
+ import type { ChatModelAdapter, MessageTiming, ThreadAssistantMessagePart } from "@assistant-ui/react";
3
+ import type { ToolCallMessagePart } from "@assistant-ui/react";
4
+ import { postJson, streamChat } from "./sse.ts";
5
+
6
+ /** `data:image/png;base64,AAAA` -> the bare base64 the wire wants. */
7
+ const DATA_URL = /^data:([^;,]+);base64,(.+)$/;
8
+
9
+ /** A composer attachment data URL in the wire shape, or undefined if it is not an inline image. */
10
+ export function dataUrlToImage(url: string): ChatImage | undefined {
11
+ const m = DATA_URL.exec(url);
12
+ return m ? { mimeType: m[1], data: m[2] } : undefined;
13
+ }
14
+
15
+ type PartLike = { type: string };
16
+ type LastLike = {
17
+ role: string;
18
+ content: readonly PartLike[];
19
+ attachments?: readonly { content?: readonly PartLike[] }[];
20
+ };
21
+
22
+ function imageParts(last: LastLike | undefined): ChatImage[] {
23
+ if (last?.role !== "user") return [];
24
+ const out: ChatImage[] = [];
25
+ const push = (part: PartLike) => {
26
+ if (part.type !== "image") return;
27
+ const url = (part as { image?: string }).image;
28
+ const img = typeof url === "string" ? dataUrlToImage(url) : undefined;
29
+ if (img) out.push(img);
30
+ };
31
+ for (const part of last.content) push(part);
32
+ // The edit composer lifts a user message's non-text parts out of `content`
33
+ // into `attachments`, so an edited image would otherwise be dropped on re-send.
34
+ for (const att of last.attachments ?? []) for (const part of att.content ?? []) push(part);
35
+ return out;
36
+ }
37
+
38
+ /**
39
+ * The converted-document parts docs.ts puts on a user message (type "file",
40
+ * mimeType "text/markdown", data = the Markdown itself). Same both-places scan
41
+ * as imageParts: the edit composer lifts non-text parts into `attachments`.
42
+ */
43
+ function docParts(last: LastLike | undefined): ChatAttachment[] {
44
+ if (last?.role !== "user") return [];
45
+ const out: ChatAttachment[] = [];
46
+ const push = (part: PartLike) => {
47
+ if (part.type !== "file") return;
48
+ const p = part as { filename?: string; data?: string; mimeType?: string };
49
+ if (p.mimeType !== "text/markdown" || typeof p.data !== "string" || p.data.trim() === "") return;
50
+ out.push({ name: p.filename ?? "附件", text: p.data });
51
+ };
52
+ for (const part of last.content) push(part);
53
+ for (const att of last.attachments ?? []) for (const part of att.content ?? []) push(part);
54
+ return out;
55
+ }
56
+
57
+ export interface ChatBridge {
58
+ getSessionId(): string | undefined;
59
+ setSessionId(sessionId: string): void;
60
+ getContext(): Record<string, unknown> | undefined;
61
+ getAuthToken(): string | undefined;
62
+ /** The chosen quality tier id, or undefined to run the manifest default. */
63
+ getTier(): string | undefined;
64
+ /** The scope this conversation belongs to, or undefined to run the product default. */
65
+ getScope(): string | undefined;
66
+ /** 人格:undefined = 产品默认(默认助手)。会话一旦建立就绑死,换人格会 400。 */
67
+ getPersona?(): string | undefined;
68
+ onRunEnd(info: { usage: TokenUsage | null; aborted: boolean }): void;
69
+ /** The server paused a gated tool and waits for POST /api/decision. */
70
+ onToolConfirm(info: { sessionId: string; toolCallId: string; name: string; args: Record<string, unknown> }): void;
71
+ /** A confirmed tool call finished (approved or denied); dismiss its card. */
72
+ onToolSettled(toolCallId: string): void;
73
+ /** 工具中文名:服务端首帧下发一次,UI 只显示这句,不显示 mcp__ 声明名。 */
74
+ onToolsMeta?(labels: Record<string, string>): void;
75
+ /** An extension is waiting for an answer (select/confirm/input); POST /api/ui-response when decided. */
76
+ onUiPrompt(prompt: UiPromptEvent): void;
77
+ /** An extension sent a notification; show it, no answer expected. */
78
+ onUiNotify(note: UiNotifyEvent): void;
79
+ /**
80
+ * 多 phase 的成员事件(W4)。缺省 = 旧前端完全不消费成员视图——平台加事件、
81
+ * 产品不接也不会崩(降级契约)。传了就逐帧交给 `reduceMembers`。
82
+ */
83
+ onMember?(ev: MemberEvent): void;
84
+ }
85
+
86
+ /**
87
+ * Set when an edit composer submits, consumed by the next run.
88
+ *
89
+ * The server keeps the transcript, so an edited message must drop the
90
+ * superseded turn before the new one is sent. The run is the only place that
91
+ * both knows the session id and can await the cleanup, and assistant-ui gives
92
+ * the adapter no "this is an edit" flag (`sourceId` is dropped before
93
+ * ChatModelRunOptions). Module-level state is fine here: one chat runtime per
94
+ * page, and the flag is only ever set synchronously on the send path.
95
+ */
96
+ let editPending = false;
97
+
98
+ /** Mark the next run as an edit. Call it before the composer sends. */
99
+ export function markEdit(): void {
100
+ editPending = true;
101
+ }
102
+
103
+ type ToolCallPart = Extract<ThreadAssistantMessagePart, { type: "tool-call" }>;
104
+
105
+ /** An extension dialog forwarded by the server (event and POST /api/ui-response payload share this shape). */
106
+ export type UiPromptEvent = Extract<ChatEvent, { type: "ui_prompt" }>;
107
+ /** A fire-and-forget `ctx.ui.notify` from an extension. */
108
+ export type UiNotifyEvent = Extract<ChatEvent, { type: "ui_notify" }>;
109
+ /** 多 phase 的成员/Run 级事件,交给 ChatBridge 归集成成员卡片(W4)。 */
110
+ export type MemberEvent = Extract<ChatEvent, { type: "member_started" | "member_delta" | "member_done" | "run_done" }>;
111
+
112
+ /**
113
+ * Bridges our SSE wire protocol to assistant-ui's ChatModelAdapter.
114
+ *
115
+ * The server owns the conversation history (resume by sessionId), so a run
116
+ * sends only the newest user message — never the whole transcript.
117
+ */
118
+ export function createChatAdapter(bridge: ChatBridge): ChatModelAdapter {
119
+ return {
120
+ async *run({ messages, abortSignal }) {
121
+ const last = messages.at(-1);
122
+ const userText =
123
+ last?.role === "user"
124
+ ? last.content.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join("")
125
+ : "";
126
+
127
+ const req: ChatRequest = { message: userText };
128
+ const sid = bridge.getSessionId();
129
+ if (sid) req.sessionId = sid;
130
+ const ctx = bridge.getContext();
131
+ if (ctx) req.context = ctx;
132
+ const tier = bridge.getTier();
133
+ if (tier) req.tier = tier;
134
+ const scope = bridge.getScope();
135
+ if (scope) req.scope = scope;
136
+ const persona = bridge.getPersona?.();
137
+ if (persona) req.persona = persona;
138
+ const images = imageParts(last);
139
+ if (images.length > 0) req.images = images;
140
+ const docs = docParts(last);
141
+ if (docs.length > 0) req.attachments = docs;
142
+
143
+ // Drop the superseded turn before the new one is appended; the server
144
+ // rebuilds its model context from this transcript on every run, so the
145
+ // old answer must be gone before /api/chat reads it. A failed cleanup is
146
+ // surfaced as text rather than thrown: the user's message is already in
147
+ // the transcript, and silently re-sending on top of the stale turn is
148
+ // exactly the bug this feature exists to fix.
149
+ if (editPending) {
150
+ editPending = false;
151
+ if (sid) {
152
+ try {
153
+ await postJson("/api/history/truncate-last-turn", { sessionId: sid }, bridge.getAuthToken());
154
+ } catch (err) {
155
+ yield {
156
+ content: [{ type: "text", text: `⚠️ 编辑未能生效(旧回答仍在上下文里):${(err as Error).message}` }],
157
+ status: { type: "incomplete", reason: "error" },
158
+ };
159
+ bridge.onRunEnd({ usage: null, aborted: false });
160
+ return;
161
+ }
162
+ }
163
+ }
164
+
165
+ const parts: ThreadAssistantMessagePart[] = [];
166
+ const appendDelta = (kind: "text" | "reasoning", delta: string) => {
167
+ const tail = parts.at(-1);
168
+ if (tail && tail.type === kind) (tail as { text: string }).text += delta;
169
+ else parts.push({ type: kind, text: delta });
170
+ };
171
+
172
+ // E3: assistant-ui renders metadata.timing through the official
173
+ // useMessageTiming hook but has no producer on the local-runtime path
174
+ // (useStreamingTiming serves external stores; TimingTracker is not
175
+ // exported from any entry). So we measure it right here: the
176
+ // user-perceived wait from sending the request to the first visible
177
+ // output. `ready` is a transport ack and not a token; thinking and
178
+ // tool_start count, because they are the first thing on screen. The
179
+ // clock starts after the edit-truncate cleanup, which is not model wait.
180
+ const streamStartTime = Date.now();
181
+ let firstTokenAt: number | undefined;
182
+ let chunks = 0;
183
+ let toolCalls = 0;
184
+ const snapshot = (): MessageTiming => ({
185
+ streamStartTime,
186
+ totalChunks: chunks,
187
+ toolCallCount: toolCalls,
188
+ totalStreamTime: Date.now() - streamStartTime,
189
+ ...(firstTokenAt === undefined ? {} : { firstTokenTime: firstTokenAt - streamStartTime }),
190
+ });
191
+
192
+ let usage: TokenUsage | null = null;
193
+ let aborted = false;
194
+ try {
195
+ for await (const ev of streamChat(req, abortSignal, bridge.getAuthToken()) as AsyncGenerator<ChatEvent>) {
196
+ switch (ev.type) {
197
+ case "ready":
198
+ bridge.setSessionId(ev.sessionId);
199
+ continue;
200
+ case "tools_meta":
201
+ bridge.onToolsMeta?.(ev.labels);
202
+ continue;
203
+ case "text_delta":
204
+ firstTokenAt ??= Date.now();
205
+ appendDelta("text", ev.delta);
206
+ break;
207
+ case "thinking_delta":
208
+ firstTokenAt ??= Date.now();
209
+ appendDelta("reasoning", ev.delta);
210
+ break;
211
+ case "tool_start":
212
+ firstTokenAt ??= Date.now();
213
+ toolCalls++;
214
+ parts.push({
215
+ type: "tool-call",
216
+ toolCallId: ev.toolCallId,
217
+ toolName: ev.name,
218
+ args: ev.args as ToolCallPart["args"],
219
+ argsText: JSON.stringify(ev.args),
220
+ });
221
+ break;
222
+ case "tool_confirm":
223
+ bridge.onToolConfirm({ sessionId: bridge.getSessionId() ?? "", toolCallId: ev.toolCallId, name: ev.name, args: ev.args });
224
+ continue;
225
+ case "tool_update":
226
+ case "tool_end": {
227
+ if (ev.type === "tool_end") bridge.onToolSettled(ev.toolCallId);
228
+ const i = parts.findIndex((p) => p.type === "tool-call" && p.toolCallId === ev.toolCallId);
229
+ if (i >= 0) {
230
+ const p = parts[i] as ToolCallPart;
231
+ const view = ev.type === "tool_end" ? ev.result : ev.partial;
232
+ parts[i] = {
233
+ ...p,
234
+ // details 搭 tool_end 顺风车(零协议改动)——
235
+ // 卡片的排版数据从这里来,文本只喂模型/兜底展示。
236
+ result: { text: view.text, details: view.details } as ToolCallPart["result"],
237
+ isError: ev.type === "tool_end" ? !ev.ok : p.isError,
238
+ };
239
+ }
240
+ break;
241
+ }
242
+ case "error":
243
+ parts.push({ type: "text", text: `⚠️ ${ev.message}` });
244
+ break;
245
+ case "message_end":
246
+ if (ev.usage) usage = ev.usage;
247
+ continue;
248
+ case "ui_prompt":
249
+ // The server parked the run inside the extension's await; the run
250
+ // resumes when the dialog is answered (or fails closed on timeout).
251
+ bridge.onUiPrompt(ev);
252
+ continue;
253
+ case "ui_notify":
254
+ bridge.onUiNotify(ev);
255
+ continue;
256
+ case "member_started":
257
+ case "member_delta":
258
+ case "member_done":
259
+ case "run_done":
260
+ // 多 phase 的成员/Run 事件:交给成员视图归集,不进主气泡 parts。
261
+ // 旧 bridge 没传 onMember 时静默丢弃——这就是降级契约(不崩、不污染气泡)。
262
+ bridge.onMember?.(ev);
263
+ // 多 phase 不发 `done`(收口语义由 run_done 承担),状态栏用量在这里补上。
264
+ if (ev.type === "run_done") usage ??= ev.usage;
265
+ continue;
266
+ case "done":
267
+ usage ??= ev.usage;
268
+ aborted = ev.aborted;
269
+ continue;
270
+ default:
271
+ // 降级契约显式化:平台未来新增的事件类型,旧前端安全忽略——
272
+ // 不 throw、不往 parts 塞东西(那会污染回答气泡)。
273
+ continue;
274
+ }
275
+ chunks++;
276
+ yield { content: [...parts], metadata: { timing: snapshot() } };
277
+ }
278
+ } catch (err) {
279
+ if ((err as Error).name !== "AbortError") {
280
+ parts.push({ type: "text", text: `⚠️ 网络错误:${(err as Error).message}` });
281
+ }
282
+ aborted = true;
283
+ }
284
+
285
+ bridge.onRunEnd({ usage, aborted });
286
+ yield {
287
+ content: [...parts],
288
+ status: aborted ? { type: "incomplete", reason: "cancelled" } : undefined,
289
+ metadata: usage ? { custom: { usage }, timing: snapshot() } : { timing: snapshot() },
290
+ };
291
+ },
292
+ };
293
+ }