@njuptlzf/agent-chat-web 0.2.0 → 0.3.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 +23 -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/assets/_commonjs-dynamic-modules-TDtrdbi3.js +1 -0
  7. package/dist/assets/exceljs.min-jlEt4kSc.js +29 -0
  8. package/dist/assets/index-B7uSE8SM.css +1 -0
  9. package/dist/assets/index-D57mU5H5.js +50 -0
  10. package/dist/assets/index-Dviy7gnB.js +44 -0
  11. package/dist/assets/pdf-CfhDiWmk.js +55 -0
  12. package/dist/assets/pdf.worker.min-CdXBBzB4.js +1 -0
  13. package/dist/assets/pdf.worker.min-CjEcRF4W.mjs +28 -0
  14. package/dist/index.html +13 -0
  15. package/dist/mount.d.ts +7 -1
  16. package/dist/mount.js +2 -2
  17. package/dist/styles.css +1492 -1478
  18. package/dist/suggestions.d.ts +41 -0
  19. package/dist/suggestions.js +98 -0
  20. package/dist/ui/FollowUpSuggestions.d.ts +9 -0
  21. package/dist/ui/FollowUpSuggestions.js +13 -0
  22. package/dist/ui/Icon.d.ts +8 -0
  23. package/dist/ui/Icon.js +26 -0
  24. package/dist/ui/icons.d.ts +19 -0
  25. package/dist/ui/icons.js +25 -0
  26. package/dist/ui/slots.d.ts +23 -0
  27. package/dist/ui/slots.js +13 -0
  28. package/package.json +71 -72
  29. package/src/App.tsx +13 -13
  30. package/src/agent-chat/AgentChat.tsx +729 -692
  31. package/src/agent-chat/AgentChatApp.tsx +211 -206
  32. package/src/agent-chat/PersonasPage.tsx +705 -678
  33. package/src/agent-chat/adapter.ts +272 -272
  34. package/src/agent-chat/app-def-check.ts +215 -215
  35. package/src/agent-chat/app.tsx +327 -327
  36. package/src/agent-chat/auth.ts +83 -83
  37. package/src/agent-chat/dock.ts +161 -161
  38. package/src/agent-chat/docs.ts +179 -179
  39. package/src/agent-chat/index.ts +17 -17
  40. package/src/agent-chat/mount.tsx +8 -1
  41. package/src/agent-chat/qual.ts +55 -55
  42. package/src/agent-chat/sse.ts +104 -104
  43. package/src/agent-chat/suggestions.ts +127 -0
  44. package/src/agent-chat/theme.ts +23 -23
  45. package/src/agent-chat/ui/CodeCopyHeader.tsx +29 -29
  46. package/src/agent-chat/ui/ConfirmCard.tsx +32 -32
  47. package/src/agent-chat/ui/FollowUpSuggestions.tsx +28 -0
  48. package/src/agent-chat/ui/Icon.tsx +53 -0
  49. package/src/agent-chat/ui/Lightbox.tsx +32 -32
  50. package/src/agent-chat/ui/QueueBar.tsx +70 -70
  51. package/src/agent-chat/ui/Splitter.tsx +81 -81
  52. package/src/agent-chat/ui/ThemeToggle.tsx +25 -25
  53. package/src/agent-chat/ui/TierPicker.tsx +112 -112
  54. package/src/agent-chat/ui/UIPromptCard.tsx +68 -68
  55. package/src/agent-chat/ui/icons.ts +31 -0
  56. package/src/agent-chat/ui/slots.tsx +35 -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 +1492 -1478
@@ -1,272 +1,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
-
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
+
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
+ }