@nexface/chat 0.1.1-alpha.1 → 0.1.1-alpha.10

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 (103) hide show
  1. package/dist/THIRD_PARTY_LICENSES.txt +44 -0
  2. package/dist/assistant-attachments.d.ts +31 -0
  3. package/dist/assistant-attachments.js +158 -0
  4. package/dist/assistant-attachments.js.map +1 -0
  5. package/dist/assistant-components.d.ts +19 -0
  6. package/dist/assistant-components.js +39 -0
  7. package/dist/assistant-components.js.map +1 -0
  8. package/dist/assistant-runtime.d.ts +24 -0
  9. package/dist/assistant-runtime.js +104 -0
  10. package/dist/assistant-runtime.js.map +1 -0
  11. package/dist/attachments.d.ts +3 -1
  12. package/dist/attachments.js +13 -0
  13. package/dist/attachments.js.map +1 -1
  14. package/dist/client.d.ts +89 -0
  15. package/dist/client.js +620 -0
  16. package/dist/client.js.map +1 -0
  17. package/dist/config.d.ts +1 -1
  18. package/dist/config.js.map +1 -1
  19. package/dist/default-chat.d.ts +2 -1
  20. package/dist/default-chat.js +85 -115
  21. package/dist/default-chat.js.map +1 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/messages.d.ts +27 -0
  24. package/dist/messages.js +121 -0
  25. package/dist/messages.js.map +1 -0
  26. package/dist/page-confirmation.d.ts +2 -1
  27. package/dist/page-confirmation.js.map +1 -1
  28. package/dist/protocol-messages.d.ts +9 -0
  29. package/dist/protocol-messages.js +249 -0
  30. package/dist/protocol-messages.js.map +1 -0
  31. package/dist/protocol-response.d.ts +32 -0
  32. package/dist/protocol-response.js +62 -0
  33. package/dist/protocol-response.js.map +1 -0
  34. package/dist/react.d.ts +29 -41
  35. package/dist/react.js +225 -662
  36. package/dist/react.js.map +1 -1
  37. package/dist/storage.d.ts +19 -0
  38. package/dist/storage.js +111 -0
  39. package/dist/storage.js.map +1 -0
  40. package/dist/styles.css +2337 -95
  41. package/dist/tool-result.d.ts +1 -0
  42. package/dist/tool-result.js +12 -0
  43. package/dist/tool-result.js.map +1 -0
  44. package/dist/types.d.ts +40 -1
  45. package/dist/types.js.map +1 -1
  46. package/dist/ui/attachment.aui.d.ts +7 -0
  47. package/dist/ui/attachment.aui.js +93 -0
  48. package/dist/ui/attachment.aui.js.map +1 -0
  49. package/dist/ui/avatar.d.ts +11 -0
  50. package/dist/ui/avatar.js +24 -0
  51. package/dist/ui/avatar.js.map +1 -0
  52. package/dist/ui/button.d.ts +13 -0
  53. package/dist/ui/button.js +38 -0
  54. package/dist/ui/button.js.map +1 -0
  55. package/dist/ui/dialog.d.ts +17 -0
  56. package/dist/ui/dialog.js +43 -0
  57. package/dist/ui/dialog.js.map +1 -0
  58. package/dist/ui/dropdown-menu.d.ts +25 -0
  59. package/dist/ui/dropdown-menu.js +60 -0
  60. package/dist/ui/dropdown-menu.js.map +1 -0
  61. package/dist/ui/input.d.ts +3 -0
  62. package/dist/ui/input.js +9 -0
  63. package/dist/ui/input.js.map +1 -0
  64. package/dist/ui/markdown-text.d.ts +7 -0
  65. package/dist/ui/markdown-text.js +73 -0
  66. package/dist/ui/markdown-text.js.map +1 -0
  67. package/dist/ui/skeleton.d.ts +2 -0
  68. package/dist/ui/skeleton.js +8 -0
  69. package/dist/ui/skeleton.js.map +1 -0
  70. package/dist/ui/surface.d.ts +4 -0
  71. package/dist/ui/surface.js +53 -0
  72. package/dist/ui/surface.js.map +1 -0
  73. package/dist/ui/thread-list.aui.d.ts +9 -0
  74. package/dist/ui/thread-list.aui.js +19 -0
  75. package/dist/ui/thread-list.aui.js.map +1 -0
  76. package/dist/ui/thread.aui.d.ts +29 -0
  77. package/dist/ui/thread.aui.js +25 -0
  78. package/dist/ui/thread.aui.js.map +1 -0
  79. package/dist/ui/tooltip-icon-button.d.ts +7 -0
  80. package/dist/ui/tooltip-icon-button.js +12 -0
  81. package/dist/ui/tooltip-icon-button.js.map +1 -0
  82. package/dist/ui/tooltip.d.ts +7 -0
  83. package/dist/ui/tooltip.js +23 -0
  84. package/dist/ui/tooltip.js.map +1 -0
  85. package/dist/ui/use-attachment-src.d.ts +1 -0
  86. package/dist/ui/use-attachment-src.js +28 -0
  87. package/dist/ui/use-attachment-src.js.map +1 -0
  88. package/dist/ui/use-copy-to-clipboard.d.ts +7 -0
  89. package/dist/ui/use-copy-to-clipboard.js +16 -0
  90. package/dist/ui/use-copy-to-clipboard.js.map +1 -0
  91. package/dist/ui/utils.d.ts +2 -0
  92. package/dist/ui/utils.js +8 -0
  93. package/dist/ui/utils.js.map +1 -0
  94. package/package.json +25 -12
  95. package/dist/operation-surface.d.ts +0 -7
  96. package/dist/operation-surface.js +0 -79
  97. package/dist/operation-surface.js.map +0 -1
  98. package/dist/operation-types.d.ts +0 -17
  99. package/dist/operation-types.js +0 -2
  100. package/dist/operation-types.js.map +0 -1
  101. package/dist/operation-view.d.ts +0 -13
  102. package/dist/operation-view.js +0 -367
  103. package/dist/operation-view.js.map +0 -1
package/dist/react.js CHANGED
@@ -1,699 +1,262 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useReducer, } from "react";
3
- import { createAgent, } from "@nexface/agent";
2
+ import { createContext, useContext, useEffect, useRef, useReducer, useCallback } from "react";
4
3
  import { ToolsProvider } from "@nexface/tools";
5
- import { OperationHostContext } from "@nexface/tools/internal/react";
6
4
  import { PageConfirmationProvider } from "./page-confirmation.js";
7
- import { resolveModelConfig } from "./config.js";
8
- import { EventType } from "@ag-ui/core";
9
- const agentChatControllerSymbol = Symbol.for("@nexface/agent/chat-controller");
10
- function getAgentChatController(agent) {
11
- return agent[agentChatControllerSymbol];
12
- }
5
+ import { createChatClient, getClientController, ClientError } from "./client.js";
6
+ import { attachmentContent } from "./attachments.js";
7
+ import { projectMessages } from "./protocol-messages.js";
8
+ import { chatStorageKey, readChatStorage, writeChatStorage, conversationFromMessages } from "./storage.js";
9
+ export { applyEvent } from "./messages.js";
13
10
  export function isChatError(error) {
14
- if (!error || typeof error !== "object")
15
- return false;
16
- const candidate = error;
17
- return candidate.type === "chat_error"
18
- && typeof candidate.code === "string"
19
- && typeof candidate.message === "string";
20
- }
21
- class ChatErrorImplementation extends Error {
22
- code;
23
- type = "chat_error";
24
- constructor(code, message) {
25
- super(message);
26
- this.code = code;
27
- this.name = "ChatError";
28
- }
29
- }
30
- const ChatError = ChatErrorImplementation;
31
- function createId() {
32
- return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random()}`;
33
- }
34
- const maxChatToolDetailLength = 4_000;
35
- function compactToolDetail(value) {
36
- if (value.length <= maxChatToolDetailLength)
37
- return value;
38
- return JSON.stringify({
39
- contentOmitted: true,
40
- preview: value.slice(0, maxChatToolDetailLength),
41
- });
42
- }
43
- function messageText(message) {
44
- return message.parts
45
- .filter((part) => part.type === "text")
46
- .map((part) => part.text)
47
- .join("");
48
- }
49
- function sessionTitle(session, index) {
50
- if (session.title)
51
- return session.title;
52
- const firstUserMessage = session.messages.find((message) => message.role === "user");
53
- const text = firstUserMessage ? messageText(firstUserMessage).trim() : "";
54
- if (!text)
55
- return `会话 ${index + 1}`;
56
- return text.length > 24 ? `${text.slice(0, 24)}…` : text;
57
- }
58
- function settledToolState(parts) {
59
- const toolParts = parts.filter((part) => part.type === "tool");
60
- if (toolParts.some((part) => part.result === undefined))
61
- return "running";
62
- return toolParts.some((part) => part.isError) ? "error" : "success";
11
+ const value = error;
12
+ return !!value && value.type === "chat_error" && typeof value.code === "string" && typeof value.message === "string";
63
13
  }
64
- function toolErrorResult(code, message, details) {
65
- return JSON.stringify({ error: { code, message, details } });
66
- }
67
- function settleInterruptMessages(messages, interrupt, code, message, reason) {
68
- let pendingSeen = false;
69
- return messages.map((chatMessage) => {
70
- let changed = false;
71
- const parts = chatMessage.parts.map((part) => {
72
- if (part.type !== "tool" || part.result !== undefined)
73
- return part;
74
- if (part.toolCallId === interrupt.toolCallId) {
75
- pendingSeen = true;
76
- changed = true;
77
- return {
78
- ...part,
79
- result: toolErrorResult(code, message, {
80
- reason,
81
- toolExecuted: false,
82
- }),
83
- isError: true,
84
- errorMessage: message,
85
- };
86
- }
87
- if (!pendingSeen)
88
- return part;
89
- changed = true;
90
- const skippedMessage = "Skipped because an earlier tool call required confirmation.";
91
- return {
92
- ...part,
93
- result: toolErrorResult("TOOL_SKIPPED", skippedMessage, {
94
- failedToolCallId: interrupt.toolCallId,
95
- }),
96
- isError: true,
97
- errorMessage: skippedMessage,
98
- };
99
- });
100
- return changed ? { ...chatMessage, parts, state: "error" } : chatMessage;
101
- });
102
- }
103
- function updateSession(state, sessionId, update) {
104
- return {
105
- ...state,
106
- sessions: state.sessions.map((session) => session.id === sessionId ? update(session) : session),
107
- };
108
- }
109
- export function applyEvent(messages, event) {
110
- if (event.type === EventType.TEXT_MESSAGE_START) {
111
- if (messages.some((message) => message.id === event.messageId))
112
- return messages;
113
- return [...messages, { id: event.messageId, role: "assistant", parts: [], state: "running" }];
114
- }
115
- if (event.type === EventType.TEXT_MESSAGE_CONTENT || event.type === EventType.TEXT_MESSAGE_END) {
116
- return messages.map((message) => {
117
- if (message.id !== event.messageId)
118
- return message;
119
- if (event.type === EventType.TEXT_MESSAGE_END)
120
- return { ...message, state: "success" };
121
- const parts = [...message.parts];
122
- const index = parts.findIndex((part) => part.type === "text");
123
- const current = parts[index];
124
- if (current?.type === "text")
125
- parts[index] = { type: "text", text: current.text + event.delta };
126
- else
127
- parts.push({ type: "text", text: event.delta });
128
- return { ...message, parts };
129
- });
130
- }
131
- if (event.type === EventType.TOOL_CALL_START) {
132
- const id = event.parentMessageId ?? event.toolCallId;
133
- const base = messages.some((message) => message.id === id) ? messages
134
- : [...messages, { id, role: "assistant", parts: [] }];
135
- return base.map((message) => message.id !== id ? message : {
136
- ...message, state: "running", parts: [...message.parts, {
137
- type: "tool", toolCallId: event.toolCallId, name: event.toolCallName, arguments: "",
138
- }],
139
- });
140
- }
141
- if (event.type === EventType.TOOL_CALL_ARGS || event.type === EventType.TOOL_CALL_RESULT) {
142
- return messages.map((message) => {
143
- if (!message.parts.some((part) => part.type === "tool" && part.toolCallId === event.toolCallId))
144
- return message;
145
- const parts = message.parts.map((part) => {
146
- if (part.type !== "tool" || part.toolCallId !== event.toolCallId)
147
- return part;
148
- if (event.type === EventType.TOOL_CALL_ARGS)
149
- return { ...part, arguments: part.arguments + event.delta };
150
- let isError = false;
151
- let errorMessage;
152
- try {
153
- const error = JSON.parse(event.content).error;
154
- isError = Boolean(error);
155
- if (typeof error?.message === "string")
156
- errorMessage = error.message;
157
- }
158
- catch { /* Plain Tool results are valid. */ }
159
- return { ...part, result: compactToolDetail(event.content), isError,
160
- ...(errorMessage === undefined ? {} : { errorMessage }),
161
- };
162
- });
163
- return { ...message, parts, state: settledToolState(parts) };
164
- });
165
- }
166
- return messages;
167
- }
168
- function reducer(state, action) {
169
- switch (action.type) {
170
- case "replace-session":
171
- return { ...state,
172
- sessions: state.sessions.map((session) => session.id === action.sessionId ? { ...action.session, ...(session.title ? { title: session.title } : {}) } : session),
173
- activeSessionId: state.activeSessionId === action.sessionId ? action.session.id : state.activeSessionId,
174
- error: undefined,
175
- };
176
- case "rename-session":
177
- return updateSession(state, action.sessionId, (session) => ({ ...session, title: action.title }));
178
- case "remove-session":
179
- return { ...state, sessions: state.sessions.filter((session) => session.id !== action.sessionId), activeSessionId: action.activeSessionId, error: undefined };
180
- case "create-session":
181
- return {
182
- ...state,
183
- sessions: [...state.sessions, action.session],
184
- activeSessionId: action.session.id,
185
- error: undefined,
186
- };
187
- case "switch-session":
188
- return { ...state, activeSessionId: action.sessionId, error: undefined };
189
- case "append-message":
190
- return updateSession(state, action.sessionId, (session) => ({
191
- ...session,
192
- messages: [...session.messages, action.message],
193
- }));
194
- case "apply-event":
195
- return updateSession(state, action.sessionId, (session) => ({
196
- ...session,
197
- messages: applyEvent(session.messages, action.event),
198
- }));
199
- case "append-result":
200
- return updateSession(state, action.sessionId, (session) => ({
201
- ...session,
202
- messages: [
203
- ...session.messages,
204
- {
205
- id: createId(),
206
- role: "assistant",
207
- parts: [{ type: "text", text: action.text }],
208
- state: "success",
209
- },
210
- ],
211
- }));
212
- case "append-terminal":
213
- return updateSession(state, action.sessionId, (session) => ({
214
- ...session,
215
- messages: [
216
- ...session.messages.map((message) => message.state === "running"
217
- ? { ...message, state: "error" }
218
- : message),
219
- {
220
- id: createId(),
221
- role: "assistant",
222
- parts: [{ type: "text", text: action.text }],
223
- state: "error",
224
- },
225
- ],
226
- }));
227
- case "interrupt":
228
- return updateSession(state, action.sessionId, (session) => {
229
- const { interrupt: _interrupt, ...rest } = session;
230
- return action.interrupt === undefined
231
- ? rest
232
- : { ...rest, interrupt: action.interrupt };
233
- });
234
- case "settle-interrupt":
235
- return updateSession(state, action.sessionId, (session) => {
236
- const { interrupt: _interrupt, ...rest } = session;
237
- return {
238
- ...rest,
239
- messages: settleInterruptMessages(session.messages, action.interrupt, action.code, action.message, action.reason),
240
- };
241
- });
242
- case "invalidate-tool-interrupts":
243
- return {
244
- ...state,
245
- sessions: state.sessions.map((session) => {
246
- if (session.interrupt?.toolName !== action.toolName)
247
- return session;
248
- const { interrupt: _interrupt, ...rest } = session;
249
- return {
250
- ...rest,
251
- messages: [
252
- ...settleInterruptMessages(session.messages, session.interrupt, "TOOL_CONFIRMATION_INVALIDATED", "The Tool Binding changed.", "binding_changed"),
253
- {
254
- id: createId(),
255
- role: "assistant",
256
- parts: [{
257
- type: "text",
258
- text: "页面能力已发生变化,本次任务已中断。你可以发送新消息继续。",
259
- }],
260
- state: "error",
261
- },
262
- ],
263
- };
264
- }),
265
- };
266
- case "completed":
267
- return {
268
- ...state,
269
- completed: { id: createId(), sessionId: action.sessionId, result: action.result },
270
- };
271
- case "status":
272
- return {
273
- ...state,
274
- status: action.status,
275
- ...(action.error === undefined ? { error: undefined } : { error: action.error }),
276
- };
277
- }
278
- }
279
- function errorFromRun(error) {
280
- const errorRecord = typeof error === "object" && error !== null
281
- ? error
282
- : undefined;
283
- const name = typeof errorRecord?.name === "string"
284
- ? errorRecord.name
285
- : "CHAT_RUN_ERROR";
286
- const message = typeof errorRecord?.message === "string"
287
- ? errorRecord.message
288
- : String(error);
289
- const candidateCode = errorRecord?.code;
290
- const code = typeof candidateCode === "string" && candidateCode
291
- ? candidateCode
292
- : name;
293
- return new ChatError(code, message);
14
+ const sendGuards = new WeakMap();
15
+ // Read the live Store at draft submission, including updates before React commits.
16
+ export function assertChatSendable(chat, sessionId) {
17
+ sendGuards.get(chat.sendMessage)?.(sessionId);
294
18
  }
295
19
  const ChatContext = createContext(null);
296
- export function NexfaceProvider({ agent: agentConfig, toolRuntime, children, webMcp = true }) {
297
- const operationSurface = useRef(null);
298
- const pageConfirmationToolsRef = useRef(new Set());
299
- const runtimeRef = useRef(toolRuntime);
300
- if (runtimeRef.current !== toolRuntime) {
301
- throw new ChatError("CHAT_RUNTIME_CHANGED", "NexfaceProvider requires a stable ToolRuntime. Remount the Provider to reset it.");
302
- }
303
- if (!agentConfig || typeof agentConfig !== "object"
304
- || "toolRuntime" in agentConfig || "toolBridge" in agentConfig || "run" in agentConfig) {
305
- throw new ChatError("INVALID_INPUT", "agent must be a NexfaceAgentConfig, without a Runtime, Bridge, or Agent instance.");
20
+ const createId = () => globalThis.crypto.randomUUID();
21
+ const textOf = (message) => message.parts.filter((part) => part.type === "text").map((part) => part.text).join("");
22
+ const asError = (error) => {
23
+ if (isChatError(error))
24
+ return error;
25
+ const value = error;
26
+ return new ClientError(typeof value?.code === "string" ? value.code : typeof value?.name === "string" ? value.name : "CHAT_RUN_ERROR", typeof value?.message === "string" ? value.message : String(error));
27
+ };
28
+ export function NexfaceProvider(props) {
29
+ const { toolRuntime, children, webMcp = true } = props;
30
+ const runtime = useRef(toolRuntime);
31
+ if (runtime.current !== toolRuntime)
32
+ throw new ClientError("CHAT_RUNTIME_CHANGED", "NexfaceProvider requires a stable ToolRuntime. Remount it to change Runtime.");
33
+ if (Boolean(props.agent) === Boolean(props.run) || (props.agent && ("toolRuntime" in props.agent || "toolBridge" in props.agent || "run" in props.agent)))
34
+ throw new ClientError("INVALID_INPUT", "Provide exactly one agent configuration or run function.");
35
+ const pageTools = useRef(new Set());
36
+ const [, render] = useReducer((n) => n + 1, 0);
37
+ const mounted = useRef(false);
38
+ const storeRef = useRef(undefined);
39
+ const changed = useCallback(() => render(), []);
40
+ const createSessionValue = useCallback((saved) => {
41
+ const current = props;
42
+ const client = createChatClient(current.run ? { toolRuntime, run: current.run } : { toolRuntime, agent: current.agent });
43
+ const controller = getClientController(client);
44
+ if (saved)
45
+ controller.id = saved.id;
46
+ controller.setPageResolver((name) => pageTools.current.has(name));
47
+ if (saved)
48
+ controller.restore(saved.messages, conversationFromMessages(saved.messages));
49
+ return { id: saved?.id ?? controller.id, client, ...(saved?.title ? { title: saved.title } : {}), unsubscribe: client.subscribe(changed) };
50
+ }, [props.agent, props.run, toolRuntime, changed]);
51
+ if (!storeRef.current) {
52
+ const first = createSessionValue();
53
+ storeRef.current = { sessions: [first], activeId: first.id, loaded: false, switching: false, version: { value: null } };
306
54
  }
307
- const createSessionAgent = useCallback(() => {
308
- const agent = createAgent({
309
- ...agentConfig,
310
- model: resolveModelConfig(agentConfig.model),
311
- toolRuntime,
312
- });
313
- getAgentChatController(agent).setPageConfirmationResolver((toolName) => pageConfirmationToolsRef.current.has(toolName));
314
- return agent;
315
- }, [agentConfig, toolRuntime]);
316
- const initialAgentRef = useRef(undefined);
317
- if (!initialAgentRef.current) {
318
- initialAgentRef.current = createSessionAgent();
319
- }
320
- const initialAgent = initialAgentRef.current;
321
- const sessionAgentsByIdRef = useRef(undefined);
322
- if (!sessionAgentsByIdRef.current) {
323
- sessionAgentsByIdRef.current = new Map([[initialAgent.id, initialAgent]]);
324
- }
325
- const consumedCompletionIdRef = useRef(undefined);
326
- const activeSessionIdRef = useRef(initialAgent.id);
327
- const [state, dispatch] = useReducer(reducer, {
328
- sessions: [{ id: initialAgent.id, agent: initialAgent, messages: [] }],
329
- activeSessionId: initialAgent.id,
330
- status: "idle",
331
- error: undefined,
332
- });
333
- const stateRef = useRef(state);
334
- stateRef.current = state;
335
- const pendingInterruptsRef = useRef(new Map());
336
- const activeRunRef = useRef(undefined);
337
- const modelSwitchRef = useRef(undefined);
338
- const mountedRef = useRef(false);
55
+ const store = storeRef.current;
56
+ const active = () => store.sessions.find((session) => session.id === store.activeId);
57
+ const find = (id) => { const session = store.sessions.find((item) => item.id === id); if (!session)
58
+ throw new ClientError("UNKNOWN_SESSION", "Unknown chat session."); return session; };
59
+ const busy = () => store.switching || store.sessions.some((session) => getClientController(session.client).busy && session.client.getStatus() !== "waiting");
60
+ const assertIdle = (code = "CHAT_RUN_ACTIVE") => { if (busy())
61
+ throw new ClientError(code, "Wait for the active task to finish."); };
62
+ const release = (session) => { session.unsubscribe(); session.client.dispose(); };
63
+ const cancelWaiting = () => { if (active().client.getStatus() === "waiting")
64
+ active().client.cancel(); };
339
65
  useEffect(() => {
340
- mountedRef.current = true;
341
- return () => {
342
- mountedRef.current = false;
343
- queueMicrotask(() => {
344
- if (mountedRef.current)
345
- return;
346
- activeRunRef.current?.run.cancel();
347
- });
348
- };
349
- }, []);
350
- useEffect(() => toolRuntime.on("toolchange", (event) => {
351
- if (event.change !== "unregistered")
66
+ if (store.loaded)
352
67
  return;
353
- let changed = false;
354
- for (const [sessionId, interrupt] of pendingInterruptsRef.current) {
355
- if (interrupt.toolName !== event.toolName)
356
- continue;
357
- pendingInterruptsRef.current.delete(sessionId);
358
- changed = true;
359
- }
360
- if (!changed)
68
+ store.loaded = true;
69
+ const saved = readChatStorage(chatStorageKey, store.version);
70
+ if (!saved)
361
71
  return;
362
- dispatch({
363
- type: "invalidate-tool-interrupts",
364
- toolName: event.toolName,
365
- });
366
- }), [toolRuntime]);
367
- const consumeRun = useCallback(async (sessionId, run) => {
368
- activeRunRef.current = { sessionId, run };
369
- dispatch({ type: "status", status: "running" });
370
- const consumeEvents = async () => {
371
- for await (const event of run) {
372
- dispatch({ type: "apply-event", sessionId, event });
373
- }
374
- };
375
- const [resultOutcome, eventOutcome] = await Promise.allSettled([
376
- run.result,
377
- consumeEvents(),
378
- ]);
379
- if (activeRunRef.current?.run === run)
380
- activeRunRef.current = undefined;
381
- const failure = resultOutcome.status === "rejected"
382
- ? resultOutcome.reason
383
- : eventOutcome.status === "rejected"
384
- ? eventOutcome.reason
385
- : undefined;
386
- const runError = failure === undefined ? undefined : errorFromRun(failure);
387
- const terminalError = runError;
388
- if (resultOutcome.status === "fulfilled"
389
- && resultOutcome.value.status === "interrupted") {
390
- pendingInterruptsRef.current.set(sessionId, resultOutcome.value.interrupt);
391
- dispatch({
392
- type: "interrupt",
393
- sessionId,
394
- interrupt: resultOutcome.value.interrupt,
395
- });
396
- }
397
- if (resultOutcome.status === "fulfilled"
398
- && resultOutcome.value.status === "completed") {
399
- pendingInterruptsRef.current.delete(sessionId);
400
- dispatch({ type: "interrupt", sessionId, interrupt: undefined });
401
- dispatch({ type: "completed", sessionId, result: resultOutcome.value });
72
+ const restored = saved.sessions.map(createSessionValue);
73
+ const latest = restored.at(-1);
74
+ if (latest.client.getMessages().length === 0) {
75
+ store.sessions.forEach(release);
76
+ store.sessions = restored;
77
+ store.activeId = latest.id;
402
78
  }
403
- if (terminalError) {
404
- dispatch({
405
- type: "append-terminal",
406
- sessionId,
407
- text: runError?.code === "AbortError"
408
- ? "任务已取消。"
409
- : terminalError.message,
410
- });
79
+ else {
80
+ store.sessions = [...restored, ...store.sessions];
411
81
  }
412
- dispatch({
413
- type: "status",
414
- status: "idle",
415
- ...(terminalError ? { error: terminalError } : {}),
416
- });
417
- if (resultOutcome.status === "rejected")
418
- throw resultOutcome.reason;
419
- if (eventOutcome.status === "rejected")
420
- throw eventOutcome.reason;
421
- return resultOutcome.value;
422
- }, []);
423
- const settlePendingInterrupt = useCallback((sessionId, settlement) => {
424
- const session = stateRef.current.sessions.find(({ id }) => id === sessionId);
425
- const interrupt = pendingInterruptsRef.current.get(sessionId);
426
- if (!session || !interrupt)
427
- return;
428
- if (!getAgentChatController(session.agent).settle(interrupt.id, settlement))
429
- return;
430
- pendingInterruptsRef.current.delete(sessionId);
431
- const cancelled = settlement.type === "cancel";
432
- dispatch({
433
- type: "settle-interrupt",
434
- sessionId,
435
- interrupt,
436
- code: cancelled ? "TOOL_CANCELLED" : "TOOL_CONFIRMATION_INVALIDATED",
437
- message: cancelled
438
- ? "The pending Tool confirmation was cancelled."
439
- : settlement.message,
440
- reason: cancelled ? "interrupt_cancelled" : settlement.reason,
441
- });
82
+ changed();
442
83
  }, []);
443
- const cancelPendingInterrupt = useCallback((sessionId) => {
444
- settlePendingInterrupt(sessionId, { type: "cancel" });
445
- }, [settlePendingInterrupt]);
446
- const invalidatePendingInterrupt = useCallback((sessionId, reason, message = "The active confirmation context changed.") => {
447
- settlePendingInterrupt(sessionId, { type: "invalidate", message, reason });
448
- }, [settlePendingInterrupt]);
449
- const sendMessage = useCallback(async (text, attachments = [], revisionOf) => {
450
- if (activeRunRef.current || modelSwitchRef.current) {
451
- throw new ChatError("CHAT_RUN_ACTIVE", "A chat run is already active.");
452
- }
453
- const content = text.trim();
454
- if (!content && !attachments.length)
455
- throw new ChatError("INVALID_INPUT", "Chat message is required.");
456
- const sessionId = activeSessionIdRef.current;
457
- const agent = sessionAgentsByIdRef.current.get(sessionId);
458
- if (!agent)
459
- throw new ChatError("UNKNOWN_SESSION", "The active chat session does not exist.");
460
- const pending = pendingInterruptsRef.current.get(sessionId);
461
- if (pending) {
462
- pendingInterruptsRef.current.delete(sessionId);
463
- dispatch({
464
- type: "settle-interrupt",
465
- sessionId,
466
- interrupt: pending,
467
- code: "TOOL_CONFIRMATION_INVALIDATED",
468
- message: "A new user message started.",
469
- reason: "new_message",
470
- });
471
- }
472
- dispatch({
473
- type: "append-message",
474
- sessionId,
475
- message: {
476
- id: createId(),
477
- role: "user",
478
- parts: [{ type: "text", text: content }],
479
- attachments,
480
- ...(revisionOf ? { revisionOf } : {}),
481
- },
482
- });
483
- const parts = [
484
- ...(content ? [{ type: "text", text: revisionOf ? "修订上一条用户请求(保留已执行操作):" + content : content }] : []),
485
- ...attachments.map((attachment) => attachment.content),
486
- ];
487
- return consumeRun(sessionId, agent.run({ message: { content: attachments.length ? parts : parts[0]?.type === "text" ? parts[0].text : content } }));
488
- }, [consumeRun]);
489
- const cancel = useCallback(() => {
490
- const active = activeRunRef.current;
491
- if (!active) {
492
- cancelPendingInterrupt(activeSessionIdRef.current);
84
+ const persist = () => {
85
+ if (store.warning)
493
86
  return;
87
+ const stored = { activeSessionId: store.activeId, sessions: store.sessions.map((session) => ({ id: session.id, ...(session.title ? { title: session.title } : {}), messages: [...projectMessages(session.client.getMessages())] })) };
88
+ if (writeChatStorage(chatStorageKey, stored, store.version) === "conflict") {
89
+ store.warning = "其他标签页已更新历史会话,本页已暂停保存。请先复制本页需要保留的新消息,再刷新以加载最新历史。";
90
+ changed();
494
91
  }
495
- dispatch({ type: "status", status: "cancelling" });
496
- active.run.cancel();
497
- }, [cancelPendingInterrupt]);
92
+ };
93
+ useEffect(() => {
94
+ const timer = setTimeout(persist, busy() ? 250 : 0);
95
+ return () => clearTimeout(timer);
96
+ });
97
+ useEffect(() => {
98
+ mounted.current = true;
99
+ const flush = () => persist();
100
+ window.addEventListener("pagehide", flush);
101
+ return () => {
102
+ mounted.current = false;
103
+ window.removeEventListener("pagehide", flush);
104
+ flush();
105
+ queueMicrotask(() => { if (!mounted.current)
106
+ store.sessions.forEach(release); });
107
+ };
108
+ }, []);
498
109
  const createSession = useCallback(() => {
499
- if (activeRunRef.current || modelSwitchRef.current) {
500
- throw new ChatError("CHAT_SESSION_CREATE_BLOCKED", "A session cannot be created while a chat run is active.");
501
- }
502
- const sessionAgent = createSessionAgent();
503
- invalidatePendingInterrupt(activeSessionIdRef.current, "session_changed");
504
- sessionAgentsByIdRef.current.set(sessionAgent.id, sessionAgent);
505
- activeSessionIdRef.current = sessionAgent.id;
506
- dispatch({
507
- type: "create-session",
508
- session: { id: sessionAgent.id, agent: sessionAgent, messages: [] },
509
- });
510
- return sessionAgent.id;
511
- }, [createSessionAgent, invalidatePendingInterrupt]);
512
- const switchSession = useCallback((sessionId) => {
513
- if (activeRunRef.current || modelSwitchRef.current) {
514
- throw new ChatError("CHAT_SESSION_SWITCH_BLOCKED", "A session cannot be switched while a chat run is active.");
110
+ assertIdle("CHAT_SESSION_CREATE_BLOCKED");
111
+ cancelWaiting();
112
+ const latest = store.sessions.at(-1);
113
+ if (latest.client.getMessages().length === 0) {
114
+ store.activeId = latest.id;
115
+ delete store.error;
116
+ changed();
117
+ return latest.id;
515
118
  }
516
- if (!sessionAgentsByIdRef.current.has(sessionId)) {
517
- throw new ChatError("UNKNOWN_SESSION", `Unknown chat session: ${sessionId}.`);
518
- }
519
- if (sessionId === activeSessionIdRef.current)
119
+ const session = createSessionValue();
120
+ store.sessions.push(session);
121
+ store.activeId = session.id;
122
+ delete store.error;
123
+ changed();
124
+ return session.id;
125
+ }, [createSessionValue]);
126
+ const switchSession = (id) => {
127
+ assertIdle("CHAT_SESSION_SWITCH_BLOCKED");
128
+ find(id);
129
+ if (store.activeId === id)
520
130
  return;
521
- invalidatePendingInterrupt(activeSessionIdRef.current, "session_changed");
522
- activeSessionIdRef.current = sessionId;
523
- dispatch({ type: "switch-session", sessionId });
524
- }, [invalidatePendingInterrupt]);
525
- const assertIdle = () => {
526
- if (activeRunRef.current || modelSwitchRef.current)
527
- throw new ChatError("CHAT_RUN_ACTIVE", "请等待当前运行结束。");
528
- };
529
- const renameSession = (id, title) => {
530
- if (!sessionAgentsByIdRef.current.has(id))
531
- throw new ChatError("UNKNOWN_SESSION", "会话不存在。");
532
- if (!title.trim())
533
- throw new ChatError("INVALID_INPUT", "会话名称不能为空。");
534
- dispatch({ type: "rename-session", sessionId: id, title: title.trim().slice(0, 80) });
131
+ cancelWaiting();
132
+ store.activeId = id;
133
+ delete store.error;
134
+ changed();
535
135
  };
536
136
  const deleteSession = (id) => {
537
137
  assertIdle();
538
- const agents = sessionAgentsByIdRef.current;
539
- const agent = agents.get(id);
540
- if (!agent)
541
- throw new ChatError("UNKNOWN_SESSION", "会话不存在。");
542
- invalidatePendingInterrupt(id, "session_deleted");
543
- if (agents.size === 1)
544
- createSession();
545
- agents.delete(id);
546
- if (activeSessionIdRef.current === id)
547
- activeSessionIdRef.current = agents.keys().next().value;
548
- dispatch({ type: "remove-session", sessionId: id, activeSessionId: activeSessionIdRef.current });
549
- };
550
- const clearSession = (id = activeSessionIdRef.current) => {
551
- assertIdle();
552
- const agents = sessionAgentsByIdRef.current;
553
- const previous = agents.get(id);
554
- if (!previous)
555
- throw new ChatError("UNKNOWN_SESSION", "会话不存在。");
556
- const agent = createSessionAgent();
557
- invalidatePendingInterrupt(id, "session_cleared");
558
- agents.delete(id);
559
- agents.set(agent.id, agent);
560
- if (activeSessionIdRef.current === id)
561
- activeSessionIdRef.current = agent.id;
562
- dispatch({ type: "replace-session", sessionId: id, session: { id: agent.id, agent, messages: [] } });
138
+ const session = find(id);
139
+ release(session);
140
+ store.sessions = store.sessions.filter((item) => item !== session);
141
+ if (!store.sessions.length)
142
+ store.sessions.push(createSessionValue());
143
+ if (store.activeId === id)
144
+ store.activeId = store.sessions[0].id;
145
+ changed();
563
146
  };
564
- const clearAllSessions = () => {
147
+ const clearSession = (id = store.activeId) => {
565
148
  assertIdle();
566
- const ids = [...sessionAgentsByIdRef.current.keys()];
567
- createSession();
568
- ids.forEach(deleteSession);
149
+ const previous = find(id);
150
+ const session = createSessionValue();
151
+ if (previous.title)
152
+ session.title = previous.title;
153
+ release(previous);
154
+ store.sessions = store.sessions.map((item) => item === previous ? session : item);
155
+ if (store.activeId === id)
156
+ store.activeId = session.id;
157
+ changed();
569
158
  };
570
- const switchModel = useCallback(async (model) => {
571
- if (activeRunRef.current || modelSwitchRef.current) {
572
- throw new ChatError("CHAT_MODEL_SWITCH_BLOCKED", "The model cannot be switched while the chat is busy.");
573
- }
574
- const sessionId = activeSessionIdRef.current;
575
- const sessionAgent = sessionAgentsByIdRef.current.get(sessionId);
576
- if (!sessionAgent) {
577
- throw new ChatError("UNKNOWN_SESSION", "The active chat session does not exist.");
159
+ const sendMessage = useCallback(async (text, attachments = [], revisionOf) => {
160
+ if (store.switching)
161
+ throw new ClientError("CHAT_RUN_ACTIVE", "The model is switching.");
162
+ let session = active();
163
+ const content = text.trim();
164
+ if (!content && !attachments.length)
165
+ throw new ClientError("INVALID_INPUT", "Chat message is required.");
166
+ let previous;
167
+ let retainedCount = 0;
168
+ if (revisionOf) {
169
+ assertIdle();
170
+ const controller = getClientController(session.client);
171
+ if (controller.busy)
172
+ throw new ClientError("CHAT_RUN_ACTIVE", "Wait for the active task to finish.");
173
+ const client = controller.recreateBefore(revisionOf);
174
+ const replacement = { ...session, client, unsubscribe: client.subscribe(changed) };
175
+ previous = session;
176
+ retainedCount = client.getMessages().length;
177
+ store.sessions = store.sessions.map((item) => item === session ? replacement : item);
178
+ session = replacement;
179
+ delete store.completion;
578
180
  }
579
- dispatch({ type: "status", status: "switching-model" });
580
- const switching = sessionAgent.switchModel(model);
581
- modelSwitchRef.current = switching;
181
+ const parts = [...(content ? [{ type: "text", text: content }] : []), ...attachments.flatMap(attachmentContent)];
582
182
  try {
583
- await switching;
584
- dispatch({ type: "status", status: "idle" });
183
+ const result = await getClientController(session.client).send(attachments.length ? parts : parts[0]?.type === "text" ? parts[0].text : content, { id: createId(), role: "user", parts: [{ type: "text", text: content }], attachments });
184
+ store.completion = { id: createId(), sessionId: session.id, result };
185
+ changed();
186
+ return result;
585
187
  }
586
188
  catch (error) {
587
- const chatError = errorFromRun(error);
588
- dispatch({ type: "status", status: "idle", error: chatError });
589
- throw chatError;
189
+ // Keep the original conversation if validation or Runtime acquisition rejected the edit.
190
+ if (previous && session.client.getMessages().length === retainedCount) {
191
+ release(session);
192
+ store.sessions = store.sessions.map((item) => item === session ? previous : item);
193
+ previous = undefined;
194
+ }
195
+ changed();
196
+ throw error;
590
197
  }
591
198
  finally {
592
- if (modelSwitchRef.current === switching)
593
- modelSwitchRef.current = undefined;
199
+ if (previous)
200
+ release(previous);
594
201
  }
595
202
  }, []);
596
- const activeSession = state.sessions.find(({ id }) => id === state.activeSessionId);
597
- const resumeInterrupt = useCallback((session, approved, source) => {
598
- const pending = session.interrupt;
599
- if (!pending)
600
- return undefined;
601
- if (pending.mode !== source || (source === "page" && !approved)) {
602
- return undefined;
603
- }
604
- if (pendingInterruptsRef.current.get(session.id)?.id !== pending.id) {
605
- return undefined;
606
- }
607
- pendingInterruptsRef.current.delete(session.id);
608
- dispatch({ type: "interrupt", sessionId: session.id, interrupt: undefined });
609
- try {
610
- const response = {
611
- interruptId: pending.id,
612
- status: "resolved",
613
- payload: { approved },
614
- };
615
- if (source === "page") {
616
- getAgentChatController(session.agent).authorizePageResponse(response);
203
+ sendGuards.set(sendMessage, (sessionId) => {
204
+ if (store.activeId !== sessionId)
205
+ throw new ClientError("CHAT_RUN_ACTIVE", "会话已切换,请返回原会话重新发送。");
206
+ if (busy())
207
+ throw new ClientError("CHAT_RUN_ACTIVE", "已有任务正在运行,请稍后重新发送。");
208
+ });
209
+ const session = active();
210
+ const client = session.client;
211
+ const controller = getClientController(client);
212
+ const approval = client.getApproval();
213
+ const error = client.getError();
214
+ const value = {
215
+ sessions: store.sessions.map((item, index) => {
216
+ const messages = projectMessages(item.client.getMessages());
217
+ const first = messages.find((message) => message.role === "user");
218
+ const title = first ? textOf(first).trim() : "";
219
+ return { id: item.id, title: item.title || (title ? title.length > 24 ? title.slice(0, 24) + "…" : title : `会话 ${index + 1}`), messageCount: messages.length };
220
+ }).reverse(),
221
+ activeSessionId: session.id, messages: projectMessages(client.getMessages()),
222
+ status: store.switching ? "switching-model" : controller.cancelling ? "cancelling" : client.getStatus(),
223
+ model: controller.agent?.model ?? { provider: "server", model: "server" },
224
+ ...(approval ? { interrupt: approval } : {}), ...(store.warning ? { storageWarning: store.warning } : {}),
225
+ ...(error || store.error ? { error: error ? asError(error) : store.error } : {}),
226
+ ...(store.completion?.sessionId === session.id ? { completed: { id: store.completion.id, result: store.completion.result } } : {}),
227
+ consumeCompletion(id) { if (store.consumed === id)
228
+ return false; store.consumed = id; return true; },
229
+ sendMessage, createSession, switchSession, deleteSession, clearSession,
230
+ clearAllSessions() { assertIdle(); store.sessions.forEach(release); const first = createSessionValue(); store.sessions = [first]; store.activeId = first.id; changed(); },
231
+ renameSession(id, title) { if (!title.trim())
232
+ throw new ClientError("INVALID_INPUT", "Session title is required."); find(id).title = title.trim().slice(0, 80); changed(); },
233
+ cancel() { active().client.cancel(); },
234
+ confirmInterrupt() { if (approval?.mode === "chat")
235
+ void client.respondToApproval(approval.id, { approved: true }).catch(() => undefined); },
236
+ rejectInterrupt() { if (approval?.mode === "chat")
237
+ void client.respondToApproval(approval.id, { approved: false }).catch(() => undefined); },
238
+ async switchModel(model) {
239
+ if (busy() || active().client.getApproval())
240
+ throw new ClientError("CHAT_MODEL_SWITCH_BLOCKED", "The chat is busy.");
241
+ store.switching = true;
242
+ changed();
243
+ try {
244
+ await getClientController(active().client).switchModel(model);
617
245
  }
618
- const run = session.agent.run({
619
- resume: [response],
620
- });
621
- const toolSettled = (async () => {
622
- for await (const event of run) {
623
- if (event.type === EventType.TOOL_CALL_RESULT
624
- && event.toolCallId === pending.toolCallId)
625
- return;
626
- }
627
- })();
628
- return {
629
- completion: consumeRun(session.id, run),
630
- toolSettled,
631
- };
632
- }
633
- catch (error) {
634
- const chatError = errorFromRun(error);
635
- dispatch({ type: "append-terminal", sessionId: session.id, text: chatError.message });
636
- dispatch({ type: "status", status: "idle", error: chatError });
637
- return undefined;
638
- }
639
- }, [consumeRun]);
640
- const confirmInterrupt = useCallback(() => {
641
- void resumeInterrupt(activeSession, true, "chat")?.completion.catch(() => undefined);
642
- }, [activeSession, resumeInterrupt]);
643
- const rejectInterrupt = useCallback(() => {
644
- if (activeSession.interrupt?.mode !== "chat")
645
- return;
646
- void resumeInterrupt(activeSession, false, "chat")?.completion.catch(() => undefined);
647
- }, [activeSession, resumeInterrupt]);
648
- const consumeCompletion = useCallback((id) => {
649
- if (consumedCompletionIdRef.current === id)
650
- return false;
651
- consumedCompletionIdRef.current = id;
652
- return true;
653
- }, []);
654
- const value = useMemo(() => ({
655
- sessions: state.sessions.map((session, index) => ({
656
- id: session.id,
657
- title: sessionTitle(session, index),
658
- messageCount: session.messages.length,
659
- })),
660
- activeSessionId: state.activeSessionId,
661
- messages: activeSession.messages,
662
- status: state.status,
663
- model: activeSession.agent.model,
664
- ...(activeSession.interrupt === undefined
665
- ? {}
666
- : { interrupt: activeSession.interrupt }),
667
- ...(state.completed?.sessionId === activeSession.id
668
- ? { completed: { id: state.completed.id, result: state.completed.result } }
669
- : {}),
670
- ...(state.error === undefined ? {} : { error: state.error }),
671
- consumeCompletion,
672
- sendMessage,
673
- cancel,
674
- confirmInterrupt,
675
- rejectInterrupt,
676
- createSession,
677
- switchSession,
678
- switchModel,
679
- renameSession, deleteSession, clearSession, clearAllSessions,
680
- }), [activeSession, cancel, confirmInterrupt, consumeCompletion, createSession, rejectInterrupt, sendMessage, state, switchModel, switchSession]);
681
- return (_jsx(ChatContext.Provider, { value: value, children: _jsx(OperationHostContext.Provider, { value: {
682
- toolRuntime, operationSurface,
683
- sessionId: activeSession.id,
684
- turnId: `${activeSession.id}:${[...activeSession.messages].reverse().find((message) => message.role === "user")?.id ?? ""}`,
685
- taskLabel: [...activeSession.messages].reverse().find((message) => message.role === "user")?.parts
686
- .filter((part) => part.type === "text").map((part) => part.text).join(" ") ?? "",
687
- running: state.status === "running" || state.status === "cancelling",
688
- waiting: Boolean(activeSession.interrupt),
689
- failed: Boolean(state.error && state.error.code !== "AbortError"),
690
- cancel,
691
- }, children: _jsx(ToolsProvider, { toolRuntime: toolRuntime, webMcp: webMcp, children: _jsx(PageConfirmationProvider, { interrupt: activeSession.interrupt, onConfirm: () => resumeInterrupt(activeSession, true, "page")?.toolSettled, onBindingRemoved: () => invalidatePendingInterrupt(activeSession.id, "page_confirmation_hook_removed", "Page confirmation entry was removed."), onBindingRegistration: (toolName, registered) => {
692
- if (registered)
693
- pageConfirmationToolsRef.current.add(toolName);
694
- else
695
- pageConfirmationToolsRef.current.delete(toolName);
696
- }, children: children }) }) }) }));
246
+ catch (error) {
247
+ store.error = asError(error);
248
+ throw error;
249
+ }
250
+ finally {
251
+ store.switching = false;
252
+ changed();
253
+ }
254
+ },
255
+ };
256
+ return _jsx(ChatContext.Provider, { value: value, children: _jsx(ToolsProvider, { toolRuntime: toolRuntime, webMcp: webMcp, children: _jsx(PageConfirmationProvider, { interrupt: approval, onConfirm: () => getClientController(active().client).confirmPage(), onBindingRemoved: () => getClientController(active().client).invalidate("Page confirmation entry was removed."), onBindingRegistration: (name, registered) => { if (registered)
257
+ pageTools.current.add(name);
258
+ else
259
+ pageTools.current.delete(name); }, children: children }) }) });
697
260
  }
698
261
  export function useChat() {
699
262
  const chat = useContext(ChatContext);