@nexface/chat 0.1.1-alpha.5 → 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/client-entry.d.ts +2 -0
- package/dist/client-entry.js +2 -0
- package/dist/client-entry.js.map +1 -0
- package/dist/client.d.ts +89 -0
- package/dist/client.js +490 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +1 -1
- package/dist/default-chat.js +3 -2
- package/dist/default-chat.js.map +1 -1
- package/dist/messages.d.ts +27 -0
- package/dist/messages.js +121 -0
- package/dist/messages.js.map +1 -0
- package/dist/page-confirmation.d.ts +2 -4
- package/dist/protocol-messages.d.ts +8 -0
- package/dist/protocol-messages.js +236 -0
- package/dist/protocol-messages.js.map +1 -0
- package/dist/react.d.ts +22 -39
- package/dist/react.js +172 -716
- package/dist/react.js.map +1 -1
- package/dist/storage.js +2 -2
- package/dist/storage.js.map +1 -1
- package/dist/types.d.ts +3 -1
- package/package.json +13 -7
package/dist/react.js
CHANGED
|
@@ -1,755 +1,211 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
-
import {
|
|
3
|
-
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useReducer, } from "react";
|
|
4
|
-
import { createAgent, } from "@nexface/agent";
|
|
2
|
+
import { createContext, useContext, useEffect, useRef, useReducer, useCallback } from "react";
|
|
5
3
|
import { ToolsProvider } from "@nexface/tools";
|
|
6
4
|
import { PageConfirmationProvider } from "./page-confirmation.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
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
|
-
|
|
11
|
-
function getAgentChatController(agent) {
|
|
12
|
-
return agent[agentChatControllerSymbol];
|
|
13
|
-
}
|
|
8
|
+
export { applyEvent } from "./messages.js";
|
|
14
9
|
export function isChatError(error) {
|
|
15
|
-
|
|
16
|
-
|
|
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
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
if (
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
}
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
|
|
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 } };
|
|
323
48
|
}
|
|
324
|
-
const
|
|
325
|
-
const
|
|
326
|
-
if (!
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
const
|
|
330
|
-
|
|
331
|
-
const
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
status: "idle",
|
|
335
|
-
error: undefined,
|
|
336
|
-
});
|
|
337
|
-
const stateRef = useRef(state);
|
|
338
|
-
stateRef.current = state;
|
|
339
|
-
const pendingInterruptsRef = useRef(new Map());
|
|
340
|
-
const activeRunRef = useRef(undefined);
|
|
341
|
-
const modelSwitchRef = useRef(undefined);
|
|
342
|
-
const mountedRef = useRef(false);
|
|
343
|
-
const storageLoadedRef = useRef(false);
|
|
344
|
-
const storageVersionRef = useRef({ value: null });
|
|
345
|
-
const storageConflictRef = useRef(false);
|
|
346
|
-
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(); };
|
|
347
59
|
useEffect(() => {
|
|
348
|
-
if (
|
|
60
|
+
if (store.loaded)
|
|
349
61
|
return;
|
|
350
|
-
|
|
351
|
-
const saved = readChatStorage(chatStorageKey,
|
|
62
|
+
store.loaded = true;
|
|
63
|
+
const saved = readChatStorage(chatStorageKey, store.version);
|
|
352
64
|
if (!saved)
|
|
353
65
|
return;
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
stateRef.current = { ...stateRef.current, sessions, activeSessionId: saved.activeSessionId };
|
|
362
|
-
dispatch({ type: "restore", sessions, activeSessionId: saved.activeSessionId });
|
|
363
|
-
}, [createSessionAgent]);
|
|
364
|
-
const persistChat = useCallback(() => {
|
|
365
|
-
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)
|
|
366
73
|
return;
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
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();
|
|
370
78
|
}
|
|
371
|
-
}
|
|
79
|
+
};
|
|
372
80
|
useEffect(() => {
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
storageTimerRef.current = undefined;
|
|
377
|
-
persistChat();
|
|
378
|
-
}, state.status === "idle" ? 0 : 250);
|
|
379
|
-
}, [state, persistChat]);
|
|
81
|
+
const timer = setTimeout(persist, busy() ? 250 : 0);
|
|
82
|
+
return () => clearTimeout(timer);
|
|
83
|
+
});
|
|
380
84
|
useEffect(() => {
|
|
381
|
-
|
|
85
|
+
mounted.current = true;
|
|
86
|
+
const flush = () => persist();
|
|
382
87
|
window.addEventListener("pagehide", flush);
|
|
383
88
|
return () => {
|
|
384
|
-
|
|
385
|
-
storageTimerRef.current = undefined;
|
|
89
|
+
mounted.current = false;
|
|
386
90
|
window.removeEventListener("pagehide", flush);
|
|
387
91
|
flush();
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
useEffect(() => {
|
|
391
|
-
mountedRef.current = true;
|
|
392
|
-
return () => {
|
|
393
|
-
mountedRef.current = false;
|
|
394
|
-
queueMicrotask(() => {
|
|
395
|
-
if (mountedRef.current)
|
|
396
|
-
return;
|
|
397
|
-
activeRunRef.current?.run.cancel();
|
|
398
|
-
for (const [sessionId, interrupt] of pendingInterruptsRef.current) {
|
|
399
|
-
const agent = sessionAgentsByIdRef.current?.get(sessionId);
|
|
400
|
-
if (agent)
|
|
401
|
-
getAgentChatController(agent).settle(interrupt.id, { type: "cancel" });
|
|
402
|
-
}
|
|
403
|
-
pendingInterruptsRef.current.clear();
|
|
404
|
-
});
|
|
92
|
+
queueMicrotask(() => { if (!mounted.current)
|
|
93
|
+
store.sessions.forEach(release); });
|
|
405
94
|
};
|
|
406
95
|
}, []);
|
|
407
|
-
useEffect(() => {
|
|
408
|
-
const runtime = getInternalToolRuntime(toolRuntime);
|
|
409
|
-
return runtime.subscribeActivity(() => {
|
|
410
|
-
if (activeRunRef.current && runtime.getActivitySnapshot().operation?.status === "cancelling") {
|
|
411
|
-
dispatch({ type: "status", status: "cancelling" });
|
|
412
|
-
}
|
|
413
|
-
});
|
|
414
|
-
}, [toolRuntime]);
|
|
415
|
-
useEffect(() => toolRuntime.on("toolchange", (event) => {
|
|
416
|
-
if (event.change !== "unregistered")
|
|
417
|
-
return;
|
|
418
|
-
let changed = false;
|
|
419
|
-
for (const [sessionId, interrupt] of pendingInterruptsRef.current) {
|
|
420
|
-
if (interrupt.toolName !== event.toolName)
|
|
421
|
-
continue;
|
|
422
|
-
pendingInterruptsRef.current.delete(sessionId);
|
|
423
|
-
changed = true;
|
|
424
|
-
}
|
|
425
|
-
if (!changed)
|
|
426
|
-
return;
|
|
427
|
-
dispatch({
|
|
428
|
-
type: "invalidate-tool-interrupts",
|
|
429
|
-
toolName: event.toolName,
|
|
430
|
-
});
|
|
431
|
-
}), [toolRuntime]);
|
|
432
|
-
const consumeRun = useCallback(async (sessionId, run) => {
|
|
433
|
-
activeRunRef.current = { sessionId, run };
|
|
434
|
-
dispatch({ type: "status", status: "running" });
|
|
435
|
-
const consumeEvents = async () => {
|
|
436
|
-
for await (const event of run) {
|
|
437
|
-
dispatch({ type: "apply-event", sessionId, event });
|
|
438
|
-
}
|
|
439
|
-
};
|
|
440
|
-
const [resultOutcome, eventOutcome] = await Promise.allSettled([
|
|
441
|
-
run.result,
|
|
442
|
-
consumeEvents(),
|
|
443
|
-
]);
|
|
444
|
-
if (activeRunRef.current?.run === run)
|
|
445
|
-
activeRunRef.current = undefined;
|
|
446
|
-
const failure = resultOutcome.status === "rejected"
|
|
447
|
-
? resultOutcome.reason
|
|
448
|
-
: eventOutcome.status === "rejected"
|
|
449
|
-
? eventOutcome.reason
|
|
450
|
-
: undefined;
|
|
451
|
-
const runError = failure === undefined ? undefined : errorFromRun(failure);
|
|
452
|
-
const terminalError = runError;
|
|
453
|
-
if (resultOutcome.status === "fulfilled"
|
|
454
|
-
&& resultOutcome.value.status === "interrupted") {
|
|
455
|
-
pendingInterruptsRef.current.set(sessionId, resultOutcome.value.interrupt);
|
|
456
|
-
dispatch({
|
|
457
|
-
type: "interrupt",
|
|
458
|
-
sessionId,
|
|
459
|
-
interrupt: resultOutcome.value.interrupt,
|
|
460
|
-
});
|
|
461
|
-
}
|
|
462
|
-
if (resultOutcome.status === "fulfilled"
|
|
463
|
-
&& resultOutcome.value.status === "completed") {
|
|
464
|
-
pendingInterruptsRef.current.delete(sessionId);
|
|
465
|
-
dispatch({ type: "interrupt", sessionId, interrupt: undefined });
|
|
466
|
-
dispatch({ type: "completed", sessionId, result: resultOutcome.value });
|
|
467
|
-
}
|
|
468
|
-
if (terminalError) {
|
|
469
|
-
dispatch({
|
|
470
|
-
type: "append-terminal",
|
|
471
|
-
sessionId,
|
|
472
|
-
text: runError?.code === "AbortError"
|
|
473
|
-
? "任务已取消。"
|
|
474
|
-
: terminalError.message,
|
|
475
|
-
});
|
|
476
|
-
}
|
|
477
|
-
dispatch({
|
|
478
|
-
type: "status",
|
|
479
|
-
status: "idle",
|
|
480
|
-
...(terminalError ? { error: terminalError } : {}),
|
|
481
|
-
});
|
|
482
|
-
if (resultOutcome.status === "rejected")
|
|
483
|
-
throw resultOutcome.reason;
|
|
484
|
-
if (eventOutcome.status === "rejected")
|
|
485
|
-
throw eventOutcome.reason;
|
|
486
|
-
return resultOutcome.value;
|
|
487
|
-
}, []);
|
|
488
|
-
const settlePendingInterrupt = useCallback((sessionId, settlement) => {
|
|
489
|
-
const session = stateRef.current.sessions.find(({ id }) => id === sessionId);
|
|
490
|
-
const interrupt = pendingInterruptsRef.current.get(sessionId);
|
|
491
|
-
if (!session || !interrupt)
|
|
492
|
-
return;
|
|
493
|
-
if (!getAgentChatController(session.agent).settle(interrupt.id, settlement))
|
|
494
|
-
return;
|
|
495
|
-
pendingInterruptsRef.current.delete(sessionId);
|
|
496
|
-
const cancelled = settlement.type === "cancel";
|
|
497
|
-
dispatch({
|
|
498
|
-
type: "settle-interrupt",
|
|
499
|
-
sessionId,
|
|
500
|
-
interrupt,
|
|
501
|
-
code: cancelled ? "TOOL_CANCELLED" : "TOOL_CONFIRMATION_INVALIDATED",
|
|
502
|
-
message: cancelled
|
|
503
|
-
? "The pending Tool confirmation was cancelled."
|
|
504
|
-
: settlement.message,
|
|
505
|
-
reason: cancelled ? "interrupt_cancelled" : settlement.reason,
|
|
506
|
-
});
|
|
507
|
-
}, []);
|
|
508
|
-
const cancelPendingInterrupt = useCallback((sessionId) => {
|
|
509
|
-
settlePendingInterrupt(sessionId, { type: "cancel" });
|
|
510
|
-
}, [settlePendingInterrupt]);
|
|
511
|
-
const invalidatePendingInterrupt = useCallback((sessionId, reason, message = "The active confirmation context changed.") => {
|
|
512
|
-
settlePendingInterrupt(sessionId, { type: "invalidate", message, reason });
|
|
513
|
-
}, [settlePendingInterrupt]);
|
|
514
|
-
const sendMessage = useCallback(async (text, attachments = [], revisionOf) => {
|
|
515
|
-
if (activeRunRef.current || modelSwitchRef.current) {
|
|
516
|
-
throw new ChatError("CHAT_RUN_ACTIVE", "A chat run is already active.");
|
|
517
|
-
}
|
|
518
|
-
const content = text.trim();
|
|
519
|
-
if (!content && !attachments.length)
|
|
520
|
-
throw new ChatError("INVALID_INPUT", "Chat message is required.");
|
|
521
|
-
const sessionId = activeSessionIdRef.current;
|
|
522
|
-
const agent = sessionAgentsByIdRef.current.get(sessionId);
|
|
523
|
-
if (!agent)
|
|
524
|
-
throw new ChatError("UNKNOWN_SESSION", "The active chat session does not exist.");
|
|
525
|
-
const parts = [
|
|
526
|
-
...(content ? [{ type: "text", text: revisionOf ? "修订上一条用户请求(保留已执行操作):" + content : content }] : []),
|
|
527
|
-
...attachments.map((attachment) => attachment.content),
|
|
528
|
-
];
|
|
529
|
-
const run = agent.run({ message: { content: attachments.length ? parts : parts[0]?.type === "text" ? parts[0].text : content } });
|
|
530
|
-
const pending = pendingInterruptsRef.current.get(sessionId);
|
|
531
|
-
if (pending) {
|
|
532
|
-
pendingInterruptsRef.current.delete(sessionId);
|
|
533
|
-
dispatch({
|
|
534
|
-
type: "settle-interrupt",
|
|
535
|
-
sessionId,
|
|
536
|
-
interrupt: pending,
|
|
537
|
-
code: "TOOL_CONFIRMATION_INVALIDATED",
|
|
538
|
-
message: "A new user message started.",
|
|
539
|
-
reason: "new_message",
|
|
540
|
-
});
|
|
541
|
-
}
|
|
542
|
-
dispatch({
|
|
543
|
-
type: "append-message",
|
|
544
|
-
sessionId,
|
|
545
|
-
message: {
|
|
546
|
-
id: createId(),
|
|
547
|
-
role: "user",
|
|
548
|
-
parts: [{ type: "text", text: content }],
|
|
549
|
-
attachments,
|
|
550
|
-
...(revisionOf ? { revisionOf } : {}),
|
|
551
|
-
},
|
|
552
|
-
});
|
|
553
|
-
return consumeRun(sessionId, run);
|
|
554
|
-
}, [consumeRun]);
|
|
555
|
-
const cancel = useCallback(() => {
|
|
556
|
-
const active = activeRunRef.current;
|
|
557
|
-
if (!active) {
|
|
558
|
-
cancelPendingInterrupt(activeSessionIdRef.current);
|
|
559
|
-
return;
|
|
560
|
-
}
|
|
561
|
-
dispatch({ type: "status", status: "cancelling" });
|
|
562
|
-
active.run.cancel();
|
|
563
|
-
}, [cancelPendingInterrupt]);
|
|
564
96
|
const createSession = useCallback(() => {
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
const switchSession = useCallback((sessionId) => {
|
|
579
|
-
if (activeRunRef.current || modelSwitchRef.current) {
|
|
580
|
-
throw new ChatError("CHAT_SESSION_SWITCH_BLOCKED", "A session cannot be switched while a chat run is active.");
|
|
581
|
-
}
|
|
582
|
-
if (!sessionAgentsByIdRef.current.has(sessionId)) {
|
|
583
|
-
throw new ChatError("UNKNOWN_SESSION", `Unknown chat session: ${sessionId}.`);
|
|
584
|
-
}
|
|
585
|
-
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)
|
|
586
110
|
return;
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
const assertIdle = () => {
|
|
592
|
-
if (activeRunRef.current || modelSwitchRef.current)
|
|
593
|
-
throw new ChatError("CHAT_RUN_ACTIVE", "请等待当前运行结束。");
|
|
594
|
-
};
|
|
595
|
-
const renameSession = (id, title) => {
|
|
596
|
-
if (!sessionAgentsByIdRef.current.has(id))
|
|
597
|
-
throw new ChatError("UNKNOWN_SESSION", "会话不存在。");
|
|
598
|
-
if (!title.trim())
|
|
599
|
-
throw new ChatError("INVALID_INPUT", "会话名称不能为空。");
|
|
600
|
-
dispatch({ type: "rename-session", sessionId: id, title: title.trim().slice(0, 80) });
|
|
111
|
+
cancelWaiting();
|
|
112
|
+
store.activeId = id;
|
|
113
|
+
delete store.error;
|
|
114
|
+
changed();
|
|
601
115
|
};
|
|
602
116
|
const deleteSession = (id) => {
|
|
603
117
|
assertIdle();
|
|
604
|
-
const
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
if (
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
if (activeSessionIdRef.current === id)
|
|
613
|
-
activeSessionIdRef.current = agents.keys().next().value;
|
|
614
|
-
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();
|
|
615
126
|
};
|
|
616
|
-
const clearSession = (id =
|
|
127
|
+
const clearSession = (id = store.activeId) => {
|
|
617
128
|
assertIdle();
|
|
618
|
-
const
|
|
619
|
-
const
|
|
620
|
-
if (
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
activeSessionIdRef.current = agent.id;
|
|
628
|
-
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();
|
|
629
138
|
};
|
|
630
|
-
const
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
throw new ChatError("CHAT_MODEL_SWITCH_BLOCKED", "The model cannot be switched while the chat is busy.");
|
|
639
|
-
}
|
|
640
|
-
const sessionId = activeSessionIdRef.current;
|
|
641
|
-
const sessionAgent = sessionAgentsByIdRef.current.get(sessionId);
|
|
642
|
-
if (!sessionAgent) {
|
|
643
|
-
throw new ChatError("UNKNOWN_SESSION", "The active chat session does not exist.");
|
|
644
|
-
}
|
|
645
|
-
dispatch({ type: "status", status: "switching-model" });
|
|
646
|
-
const switching = sessionAgent.switchModel(model);
|
|
647
|
-
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)];
|
|
648
147
|
try {
|
|
649
|
-
await
|
|
650
|
-
|
|
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;
|
|
651
152
|
}
|
|
652
153
|
catch (error) {
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
throw chatError;
|
|
656
|
-
}
|
|
657
|
-
finally {
|
|
658
|
-
if (modelSwitchRef.current === switching)
|
|
659
|
-
modelSwitchRef.current = undefined;
|
|
154
|
+
changed();
|
|
155
|
+
throw error;
|
|
660
156
|
}
|
|
661
157
|
}, []);
|
|
662
|
-
const
|
|
663
|
-
const
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
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);
|
|
681
194
|
}
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
toolSettled,
|
|
697
|
-
};
|
|
698
|
-
}
|
|
699
|
-
catch (error) {
|
|
700
|
-
const chatError = errorFromRun(error);
|
|
701
|
-
dispatch({ type: "status", status: "idle", error: chatError });
|
|
702
|
-
return undefined;
|
|
703
|
-
}
|
|
704
|
-
}, [consumeRun]);
|
|
705
|
-
const confirmInterrupt = useCallback(() => {
|
|
706
|
-
void resumeInterrupt(activeSession, true, "chat")?.completion.catch(() => undefined);
|
|
707
|
-
}, [activeSession, resumeInterrupt]);
|
|
708
|
-
const rejectInterrupt = useCallback(() => {
|
|
709
|
-
if (activeSession.interrupt?.mode !== "chat")
|
|
710
|
-
return;
|
|
711
|
-
void resumeInterrupt(activeSession, false, "chat")?.completion.catch(() => undefined);
|
|
712
|
-
}, [activeSession, resumeInterrupt]);
|
|
713
|
-
const consumeCompletion = useCallback((id) => {
|
|
714
|
-
if (consumedCompletionIdRef.current === id)
|
|
715
|
-
return false;
|
|
716
|
-
consumedCompletionIdRef.current = id;
|
|
717
|
-
return true;
|
|
718
|
-
}, []);
|
|
719
|
-
const value = useMemo(() => ({
|
|
720
|
-
sessions: state.sessions.map((session, index) => ({
|
|
721
|
-
id: session.id,
|
|
722
|
-
title: sessionTitle(session, index),
|
|
723
|
-
messageCount: session.messages.length,
|
|
724
|
-
})),
|
|
725
|
-
activeSessionId: state.activeSessionId,
|
|
726
|
-
messages: activeSession.messages,
|
|
727
|
-
status: state.status,
|
|
728
|
-
...(state.storageWarning ? { storageWarning: state.storageWarning } : {}),
|
|
729
|
-
model: activeSession.agent.model,
|
|
730
|
-
...(activeSession.interrupt === undefined
|
|
731
|
-
? {}
|
|
732
|
-
: { interrupt: activeSession.interrupt }),
|
|
733
|
-
...(state.completed?.sessionId === activeSession.id
|
|
734
|
-
? { completed: { id: state.completed.id, result: state.completed.result } }
|
|
735
|
-
: {}),
|
|
736
|
-
...(state.error === undefined ? {} : { error: state.error }),
|
|
737
|
-
consumeCompletion,
|
|
738
|
-
sendMessage,
|
|
739
|
-
cancel,
|
|
740
|
-
confirmInterrupt,
|
|
741
|
-
rejectInterrupt,
|
|
742
|
-
createSession,
|
|
743
|
-
switchSession,
|
|
744
|
-
switchModel,
|
|
745
|
-
renameSession, deleteSession, clearSession, clearAllSessions,
|
|
746
|
-
}), [activeSession, cancel, confirmInterrupt, consumeCompletion, createSession, rejectInterrupt, sendMessage, state, switchModel, switchSession]);
|
|
747
|
-
return (_jsx(ChatContext.Provider, { value: value, 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) => {
|
|
748
|
-
if (registered)
|
|
749
|
-
pageConfirmationToolsRef.current.add(toolName);
|
|
750
|
-
else
|
|
751
|
-
pageConfirmationToolsRef.current.delete(toolName);
|
|
752
|
-
}, 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 }) }) });
|
|
753
209
|
}
|
|
754
210
|
export function useChat() {
|
|
755
211
|
const chat = useContext(ChatContext);
|