@nexface/chat 0.1.1-alpha.4 → 0.1.1-alpha.6

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