@nexface/chat 0.1.20 → 0.1.21-alpha.1
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/assistant-components.d.ts +2 -1
- package/dist/assistant-components.js +22 -10
- package/dist/assistant-runtime.js +15 -4
- package/dist/client.d.ts +3 -1
- package/dist/client.js +136 -42
- package/dist/config.d.ts +1 -1
- package/dist/default-chat.d.ts +1 -1
- package/dist/default-chat.js +26411 -26047
- package/dist/fonts/Inter-OFL.txt +93 -0
- package/dist/fonts/inter-medium.ttf +0 -0
- package/dist/protocol-messages.js +15 -16
- package/dist/protocol-response.js +10 -3
- package/dist/react.d.ts +13 -1
- package/dist/react.js +609 -99
- package/dist/session-coordinator.d.ts +23 -0
- package/dist/session-coordinator.js +139 -0
- package/dist/session-history.d.ts +29 -0
- package/dist/session-history.js +282 -0
- package/dist/shared/errors.d.ts +1 -1
- package/dist/shared/errors.js +2 -0
- package/dist/shared/tool-presentation.d.ts +17 -0
- package/dist/shared/tool-presentation.js +5 -0
- package/dist/shared/tool-proxy.d.ts +6 -0
- package/dist/shared/tool-proxy.js +25 -0
- package/dist/storage.d.ts +4 -6
- package/dist/storage.js +52 -43
- package/dist/styles.css +1491 -676
- package/dist/tool-confirmation-card.d.ts +5 -0
- package/dist/tool-confirmation-card.js +33 -0
- package/dist/tool-confirmation.d.ts +23 -0
- package/dist/tool-confirmation.js +25 -0
- package/dist/tool-presentation.d.ts +6 -0
- package/dist/tool-presentation.js +132 -0
- package/dist/tool-result.d.ts +5 -0
- package/dist/tool-result.js +31 -0
- package/dist/types.d.ts +3 -1
- package/dist/ui/home-demo/greeting.d.ts +3 -1
- package/dist/ui/home-demo/greeting.js +2 -2
- package/dist/ui/home-demo/suggestions.d.ts +2 -4
- package/dist/ui/home-demo/suggestions.js +5 -4
- package/dist/ui/home-demo/trace.js +2 -3
- package/dist/ui/thread-list.aui.d.ts +2 -1
- package/dist/ui/thread-list.aui.js +2 -2
- package/package.json +3 -3
package/dist/react.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { confirmationControllers, confirmationRequest, } from "./tool-confirmation.js";
|
|
2
3
|
import { reportError } from "./errors.js";
|
|
3
4
|
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useReducer, useCallback, } from "react";
|
|
4
5
|
import { ToolsProvider } from "@nexface/tools";
|
|
@@ -6,7 +7,9 @@ import { PageConfirmationProvider, } from "./page-confirmation.js";
|
|
|
6
7
|
import { createChatClient, getClientController, ClientError, } from "./client.js";
|
|
7
8
|
import { attachmentContent } from "./attachments.js";
|
|
8
9
|
import { projectMessages } from "./protocol-messages.js";
|
|
9
|
-
import {
|
|
10
|
+
import { encodeSession } from "./storage.js";
|
|
11
|
+
import { SessionHistory, sessionLockedError } from "./session-history.js";
|
|
12
|
+
import { getToolPresentationController, } from "./shared/tool-presentation.js";
|
|
10
13
|
export function isChatError(error) {
|
|
11
14
|
const value = error;
|
|
12
15
|
return (!!value &&
|
|
@@ -14,12 +17,62 @@ export function isChatError(error) {
|
|
|
14
17
|
typeof value.code === "string" &&
|
|
15
18
|
typeof value.message === "string");
|
|
16
19
|
}
|
|
20
|
+
function persistenceSnapshot(session) {
|
|
21
|
+
return encodeSession({
|
|
22
|
+
id: session.id,
|
|
23
|
+
...(session.title ? { title: session.title } : {}),
|
|
24
|
+
...(getClientController(session.client).appendOnly ? { appendOnly: true } : {}),
|
|
25
|
+
messages: [...projectMessages(session.client.getMessages())],
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
const historyStates = new WeakMap();
|
|
29
|
+
export function isChatHistoryReady(chat) {
|
|
30
|
+
return historyStates.get(chat)?.loading === false;
|
|
31
|
+
}
|
|
32
|
+
export function isSessionOccupied(chat, id) {
|
|
33
|
+
return historyStates.get(chat)?.occupied.has(id) ?? false;
|
|
34
|
+
}
|
|
35
|
+
export function isSessionOperationPending(chat) {
|
|
36
|
+
return historyStates.get(chat)?.pending ?? false;
|
|
37
|
+
}
|
|
38
|
+
export function watchHistorySidebar(chat) {
|
|
39
|
+
return historyStates.get(chat)?.history.coordinator.watch();
|
|
40
|
+
}
|
|
41
|
+
export function historyNotice(chat) {
|
|
42
|
+
return historyStates.get(chat)?.notice;
|
|
43
|
+
}
|
|
44
|
+
const commandResults = new WeakMap();
|
|
45
|
+
export function sessionCommandResult(chat) {
|
|
46
|
+
return commandResults.get(chat.sendMessage);
|
|
47
|
+
}
|
|
17
48
|
const sendGuards = new WeakMap();
|
|
49
|
+
const appendOnlySessions = new WeakMap();
|
|
50
|
+
const chatsWithoutRecovery = new WeakSet();
|
|
51
|
+
export function isChatRecoveryUnavailable(chat) {
|
|
52
|
+
return chatsWithoutRecovery.has(chat);
|
|
53
|
+
}
|
|
54
|
+
export function canEditChatSession(chat, sessionId) {
|
|
55
|
+
return !appendOnlySessions.get(chat)?.has(sessionId);
|
|
56
|
+
}
|
|
18
57
|
// Read the live Store at draft submission, including updates before React commits.
|
|
19
58
|
export function assertChatSendable(chat, sessionId) {
|
|
20
59
|
sendGuards.get(chat.sendMessage)?.(sessionId);
|
|
21
60
|
}
|
|
22
61
|
const ChatContext = createContext(null);
|
|
62
|
+
const ToolPresentationContext = createContext(null);
|
|
63
|
+
function ToolPresentationProvider({ controller, report, children, }) {
|
|
64
|
+
const [, changed] = useReducer((revision) => revision + 1, 0);
|
|
65
|
+
useLayoutEffect(() => {
|
|
66
|
+
const unsubscribe = controller?.subscribe(changed);
|
|
67
|
+
// Child bindings may have registered before this provider's layout effect.
|
|
68
|
+
changed();
|
|
69
|
+
return unsubscribe;
|
|
70
|
+
}, [controller]);
|
|
71
|
+
return (_jsx(ToolPresentationContext.Provider, { value: { controller, report }, children: children }));
|
|
72
|
+
}
|
|
73
|
+
export function useToolPresentations() {
|
|
74
|
+
return useContext(ToolPresentationContext);
|
|
75
|
+
}
|
|
23
76
|
const createId = () => globalThis.crypto.randomUUID();
|
|
24
77
|
const textOf = (message) => message.parts
|
|
25
78
|
.filter((part) => part.type === "text")
|
|
@@ -66,11 +119,16 @@ export function NexfaceProvider(props) {
|
|
|
66
119
|
controller.id = saved.id;
|
|
67
120
|
controller.setPageResolver((name) => pageTools.current.has(name));
|
|
68
121
|
if (saved)
|
|
69
|
-
controller.restore(saved.messages);
|
|
122
|
+
controller.restore(saved.messages, saved.appendOnly);
|
|
70
123
|
return {
|
|
124
|
+
confirmations: {
|
|
125
|
+
restored: new Set(saved?.messages.flatMap((message) => message.parts.flatMap((part) => (part.type === "tool" ? [part.toolCallId] : []))) ?? []),
|
|
126
|
+
decisions: new Map(),
|
|
127
|
+
},
|
|
71
128
|
id: saved?.id ?? controller.id,
|
|
72
129
|
client,
|
|
73
130
|
...(saved?.title ? { title: saved.title } : {}),
|
|
131
|
+
persisted: Boolean(saved),
|
|
74
132
|
unsubscribe: client.subscribe(changed),
|
|
75
133
|
};
|
|
76
134
|
}, [props.agent, props.run, toolRuntime, changed]);
|
|
@@ -81,7 +139,14 @@ export function NexfaceProvider(props) {
|
|
|
81
139
|
activeId: first.id,
|
|
82
140
|
loaded: false,
|
|
83
141
|
switching: false,
|
|
84
|
-
|
|
142
|
+
history: new SessionHistory(),
|
|
143
|
+
tail: Promise.resolve(),
|
|
144
|
+
pending: 0,
|
|
145
|
+
admitting: false,
|
|
146
|
+
admissionCancelled: false,
|
|
147
|
+
suspended: false,
|
|
148
|
+
intendedId: first.id,
|
|
149
|
+
occupied: new Set(),
|
|
85
150
|
};
|
|
86
151
|
}
|
|
87
152
|
const store = storeRef.current;
|
|
@@ -93,6 +158,7 @@ export function NexfaceProvider(props) {
|
|
|
93
158
|
return session;
|
|
94
159
|
};
|
|
95
160
|
const busy = () => store.switching ||
|
|
161
|
+
store.admitting ||
|
|
96
162
|
store.sessions.some((session) => getClientController(session.client).busy && session.client.getStatus() !== "waiting");
|
|
97
163
|
const assertIdle = (code = "CHAT_RUN_ACTIVE") => {
|
|
98
164
|
if (busy())
|
|
@@ -106,113 +172,381 @@ export function NexfaceProvider(props) {
|
|
|
106
172
|
if (active().client.getStatus() === "waiting")
|
|
107
173
|
active().client.cancel();
|
|
108
174
|
};
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
if (
|
|
175
|
+
const storageFailure = (cause) => {
|
|
176
|
+
const original = asError(cause);
|
|
177
|
+
const error = original.code.startsWith("CHAT_") || original.code === "UNKNOWN_SESSION"
|
|
178
|
+
? original
|
|
179
|
+
: new ClientError("CHAT_STORAGE_UNAVAILABLE", `Chat history could not be updated. ${original.message}`);
|
|
180
|
+
if (store.error?.code !== error.code || store.error.message !== error.message) {
|
|
181
|
+
store.error = error;
|
|
182
|
+
changed();
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
const refreshHistory = (initial = false) => {
|
|
186
|
+
if (!store.loaded || !mounted.current || (store.pending && !initial))
|
|
115
187
|
return;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
store.sessions
|
|
120
|
-
|
|
121
|
-
|
|
188
|
+
try {
|
|
189
|
+
const saved = store.history.list();
|
|
190
|
+
const ids = new Set(saved.map((item) => item.id));
|
|
191
|
+
const previous = store.sessions;
|
|
192
|
+
const records = saved.map((item) => {
|
|
193
|
+
const existing = previous.find((session) => session.id === item.id);
|
|
194
|
+
if (existing) {
|
|
195
|
+
if (existing.id !== store.activeId &&
|
|
196
|
+
!store.history.coordinator.owns(existing.id) &&
|
|
197
|
+
!store.history.unchangedSinceSaved(existing.id) &&
|
|
198
|
+
JSON.stringify(persistenceSnapshot(existing)) !== JSON.stringify(encodeSession(item))) {
|
|
199
|
+
release(existing);
|
|
200
|
+
return createSessionValue(item);
|
|
201
|
+
}
|
|
202
|
+
existing.persisted = true;
|
|
203
|
+
return existing;
|
|
204
|
+
}
|
|
205
|
+
return createSessionValue(item);
|
|
206
|
+
});
|
|
207
|
+
const local = previous.filter((item) => !ids.has(item.id) && (!item.persisted || item.id === store.activeId));
|
|
208
|
+
for (const item of previous)
|
|
209
|
+
if (!ids.has(item.id) && !records.includes(item) && !local.includes(item))
|
|
210
|
+
release(item);
|
|
211
|
+
store.sessions = [...records, ...local];
|
|
212
|
+
changed();
|
|
122
213
|
}
|
|
123
|
-
|
|
124
|
-
|
|
214
|
+
catch (cause) {
|
|
215
|
+
storageFailure(cause);
|
|
125
216
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
217
|
+
};
|
|
218
|
+
const ready = () => (store.ready ??= (async () => {
|
|
219
|
+
await store.history.initialize();
|
|
220
|
+
await store.history.open(store.activeId, true);
|
|
221
|
+
store.loaded = true;
|
|
222
|
+
refreshHistory(true);
|
|
223
|
+
})());
|
|
224
|
+
const saveSession = async (session) => {
|
|
225
|
+
if (!store.history.coordinator.owns(session.id))
|
|
226
|
+
throw sessionLockedError();
|
|
227
|
+
const snapshot = persistenceSnapshot(session);
|
|
228
|
+
await store.history.save(snapshot);
|
|
229
|
+
if (snapshot.messages.length || snapshot.title)
|
|
230
|
+
session.persisted = true;
|
|
231
|
+
if (store.error?.code.startsWith("CHAT_STORAGE")) {
|
|
232
|
+
delete store.error;
|
|
142
233
|
changed();
|
|
143
234
|
}
|
|
144
235
|
};
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
236
|
+
const persist = async () => {
|
|
237
|
+
await ready();
|
|
238
|
+
const session = active();
|
|
239
|
+
await saveSession(session);
|
|
240
|
+
};
|
|
241
|
+
const enqueue = (operation) => {
|
|
242
|
+
store.pending++;
|
|
243
|
+
const result = store.tail.then(async () => {
|
|
244
|
+
await ready();
|
|
245
|
+
if (!mounted.current)
|
|
246
|
+
throw new ClientError("CHAT_SESSION_SWITCH_BLOCKED", "The chat was unmounted before the operation started.");
|
|
247
|
+
await operation();
|
|
248
|
+
});
|
|
249
|
+
commandResults.set(sendMessage, result);
|
|
250
|
+
store.tail = result.catch(storageFailure).finally(() => {
|
|
251
|
+
store.pending--;
|
|
252
|
+
if (!store.pending) {
|
|
253
|
+
store.intendedId = store.activeId;
|
|
254
|
+
refreshHistory();
|
|
255
|
+
}
|
|
256
|
+
changed();
|
|
257
|
+
});
|
|
258
|
+
changed();
|
|
259
|
+
return result;
|
|
260
|
+
};
|
|
149
261
|
useEffect(() => {
|
|
150
262
|
mounted.current = true;
|
|
151
|
-
|
|
152
|
-
|
|
263
|
+
let disposed = false;
|
|
264
|
+
let reconciling = false;
|
|
265
|
+
let lifecycle = 0;
|
|
266
|
+
const reconcile = () => {
|
|
267
|
+
if (disposed || reconciling)
|
|
268
|
+
return;
|
|
269
|
+
reconciling = true;
|
|
270
|
+
queueMicrotask(() => {
|
|
271
|
+
reconciling = false;
|
|
272
|
+
if (!disposed) {
|
|
273
|
+
refreshHistory();
|
|
274
|
+
void store.history.coordinator
|
|
275
|
+
.occupied()
|
|
276
|
+
.then((occupied) => {
|
|
277
|
+
if (disposed)
|
|
278
|
+
return;
|
|
279
|
+
const changedLocks = [...occupied].sort().join("\0") !== [...store.occupied].sort().join("\0");
|
|
280
|
+
store.occupied = occupied;
|
|
281
|
+
if (changedLocks)
|
|
282
|
+
changed();
|
|
283
|
+
})
|
|
284
|
+
.catch(storageFailure);
|
|
285
|
+
}
|
|
286
|
+
});
|
|
287
|
+
};
|
|
288
|
+
store.history.coordinator.connect(reconcile);
|
|
289
|
+
store.history.onEvict = (count) => {
|
|
290
|
+
store.notice = `Removed ${count} older conversation${count === 1 ? "" : "s"} to free storage space.`;
|
|
291
|
+
changed();
|
|
292
|
+
};
|
|
293
|
+
void ready().then(reconcile).catch(storageFailure);
|
|
294
|
+
const flush = () => {
|
|
295
|
+
void store.tail.then(persist).catch(storageFailure);
|
|
296
|
+
};
|
|
297
|
+
const onHide = (event) => {
|
|
298
|
+
if (!event.persisted) {
|
|
299
|
+
flush();
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
const ticket = ++lifecycle;
|
|
303
|
+
store.suspended = true;
|
|
304
|
+
store.admissionCancelled = true;
|
|
305
|
+
active().client.cancel();
|
|
306
|
+
changed();
|
|
307
|
+
void store.tail
|
|
308
|
+
.then(persist)
|
|
309
|
+
.catch(storageFailure)
|
|
310
|
+
.finally(() => {
|
|
311
|
+
if (ticket === lifecycle)
|
|
312
|
+
store.history.coordinator.release(store.activeId);
|
|
313
|
+
});
|
|
314
|
+
};
|
|
315
|
+
const onShow = (event) => {
|
|
316
|
+
reconcile();
|
|
317
|
+
if (!event.persisted && !store.suspended)
|
|
318
|
+
return;
|
|
319
|
+
lifecycle++;
|
|
320
|
+
store.suspended = false;
|
|
321
|
+
void enqueue(async () => {
|
|
322
|
+
if (store.history.coordinator.owns(store.activeId))
|
|
323
|
+
return;
|
|
324
|
+
const previous = active();
|
|
325
|
+
try {
|
|
326
|
+
const saved = await store.history.open(previous.id, !previous.persisted);
|
|
327
|
+
if (saved && !store.history.canReuse(previous.id)) {
|
|
328
|
+
const replacement = createSessionValue(saved);
|
|
329
|
+
store.history.adoptRestored(persistenceSnapshot(replacement));
|
|
330
|
+
release(previous);
|
|
331
|
+
store.sessions = store.sessions.map((item) => (item === previous ? replacement : item));
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
catch (cause) {
|
|
335
|
+
if (asError(cause).code !== "CHAT_SESSION_LOCKED" &&
|
|
336
|
+
asError(cause).code !== "UNKNOWN_SESSION")
|
|
337
|
+
throw cause;
|
|
338
|
+
const fresh = createSessionValue();
|
|
339
|
+
await store.history.open(fresh.id, true);
|
|
340
|
+
store.sessions.push(fresh);
|
|
341
|
+
store.activeId = fresh.id;
|
|
342
|
+
store.notice = "The previous conversation is unavailable. A new conversation was opened.";
|
|
343
|
+
}
|
|
344
|
+
}).catch(() => undefined);
|
|
345
|
+
};
|
|
346
|
+
window.addEventListener("storage", reconcile);
|
|
347
|
+
window.addEventListener("focus", reconcile);
|
|
348
|
+
window.addEventListener("pageshow", onShow);
|
|
349
|
+
window.addEventListener("pagehide", onHide);
|
|
350
|
+
// Reconcile missed release notifications after a tab crashes; no lock stealing.
|
|
351
|
+
const timer = window.setInterval(() => {
|
|
352
|
+
if (store.history.coordinator.visible && document.visibilityState !== "hidden")
|
|
353
|
+
reconcile();
|
|
354
|
+
}, 3000);
|
|
153
355
|
return () => {
|
|
356
|
+
disposed = true;
|
|
154
357
|
mounted.current = false;
|
|
155
|
-
window.
|
|
156
|
-
|
|
358
|
+
window.clearInterval(timer);
|
|
359
|
+
window.removeEventListener("storage", reconcile);
|
|
360
|
+
window.removeEventListener("focus", reconcile);
|
|
361
|
+
window.removeEventListener("pageshow", onShow);
|
|
362
|
+
window.removeEventListener("pagehide", onHide);
|
|
157
363
|
queueMicrotask(() => {
|
|
158
|
-
if (
|
|
364
|
+
if (mounted.current)
|
|
365
|
+
return;
|
|
366
|
+
const close = () => {
|
|
159
367
|
store.sessions.forEach(release);
|
|
368
|
+
store.history.coordinator.close();
|
|
369
|
+
};
|
|
370
|
+
try {
|
|
371
|
+
if (!store.pending &&
|
|
372
|
+
!getClientController(active().client).busy &&
|
|
373
|
+
store.history.isSaved(persistenceSnapshot(active()))) {
|
|
374
|
+
close();
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
catch {
|
|
379
|
+
/* Fall through to the best-effort final save. */
|
|
380
|
+
}
|
|
381
|
+
store.sessions.forEach((session) => session.client.cancel());
|
|
382
|
+
void store.tail
|
|
383
|
+
.then(persist)
|
|
384
|
+
.catch(() => undefined)
|
|
385
|
+
.finally(() => {
|
|
386
|
+
if (mounted.current)
|
|
387
|
+
return;
|
|
388
|
+
close();
|
|
389
|
+
});
|
|
160
390
|
});
|
|
161
391
|
};
|
|
162
392
|
}, []);
|
|
393
|
+
useEffect(() => {
|
|
394
|
+
if (!store.loaded || store.pending || store.admitting)
|
|
395
|
+
return;
|
|
396
|
+
const timer = setTimeout(() => {
|
|
397
|
+
void store.tail.then(persist).catch(storageFailure);
|
|
398
|
+
}, busy() ? 250 : 0);
|
|
399
|
+
return () => clearTimeout(timer);
|
|
400
|
+
});
|
|
401
|
+
const activate = async (target) => {
|
|
402
|
+
if (target.id === store.activeId)
|
|
403
|
+
return;
|
|
404
|
+
const previous = active();
|
|
405
|
+
const saved = await store.history.open(target.id, !target.persisted);
|
|
406
|
+
try {
|
|
407
|
+
await saveSession(previous);
|
|
408
|
+
if (!mounted.current)
|
|
409
|
+
throw new ClientError("CHAT_SESSION_SWITCH_BLOCKED", "The chat was unmounted before the conversation opened.");
|
|
410
|
+
const wasWaiting = previous.client.getStatus() === "waiting";
|
|
411
|
+
cancelWaiting();
|
|
412
|
+
if (wasWaiting && getClientController(previous.client).busy)
|
|
413
|
+
await new Promise((resolve) => {
|
|
414
|
+
const done = () => {
|
|
415
|
+
if (!getClientController(previous.client).busy) {
|
|
416
|
+
unsubscribe();
|
|
417
|
+
resolve();
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
const unsubscribe = previous.client.subscribe(done);
|
|
421
|
+
done();
|
|
422
|
+
});
|
|
423
|
+
// Cancellation can add a final outcome; persist it before releasing ownership.
|
|
424
|
+
await saveSession(previous);
|
|
425
|
+
if (saved && !store.history.canReuse(target.id)) {
|
|
426
|
+
const replacement = createSessionValue(saved);
|
|
427
|
+
store.history.adoptRestored(persistenceSnapshot(replacement));
|
|
428
|
+
release(target);
|
|
429
|
+
store.sessions = store.sessions.map((item) => (item === target ? replacement : item));
|
|
430
|
+
}
|
|
431
|
+
store.activeId = target.id;
|
|
432
|
+
delete store.error;
|
|
433
|
+
store.history.coordinator.release(previous.id);
|
|
434
|
+
}
|
|
435
|
+
catch (cause) {
|
|
436
|
+
store.history.coordinator.release(target.id);
|
|
437
|
+
throw cause;
|
|
438
|
+
}
|
|
439
|
+
};
|
|
163
440
|
const createSession = useCallback(() => {
|
|
164
441
|
assertIdle("CHAT_SESSION_CREATE_BLOCKED");
|
|
165
|
-
cancelWaiting();
|
|
166
442
|
const latest = store.sessions.at(-1);
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
return
|
|
443
|
+
const target = latest.client.getMessages().length === 0 && !latest.persisted ? latest : createSessionValue();
|
|
444
|
+
store.intendedId = target.id;
|
|
445
|
+
if (target.id === store.activeId) {
|
|
446
|
+
commandResults.delete(sendMessage);
|
|
447
|
+
return target.id;
|
|
172
448
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
449
|
+
void enqueue(async () => {
|
|
450
|
+
const created = !store.sessions.includes(target);
|
|
451
|
+
if (created)
|
|
452
|
+
store.sessions.push(target);
|
|
453
|
+
try {
|
|
454
|
+
await activate(target);
|
|
455
|
+
}
|
|
456
|
+
catch (cause) {
|
|
457
|
+
if (created && store.activeId !== target.id && !target.persisted) {
|
|
458
|
+
store.sessions = store.sessions.filter((item) => item !== target);
|
|
459
|
+
release(target);
|
|
460
|
+
}
|
|
461
|
+
throw cause;
|
|
462
|
+
}
|
|
463
|
+
}).catch(() => undefined);
|
|
464
|
+
return target.id;
|
|
179
465
|
}, [createSessionValue]);
|
|
180
466
|
const switchSession = (id) => {
|
|
181
467
|
assertIdle("CHAT_SESSION_SWITCH_BLOCKED");
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
changed();
|
|
468
|
+
if (store.loaded && !store.pending)
|
|
469
|
+
find(id);
|
|
470
|
+
store.intendedId = id;
|
|
471
|
+
void enqueue(async () => {
|
|
472
|
+
await activate(find(id));
|
|
473
|
+
}).catch(() => undefined);
|
|
189
474
|
};
|
|
190
475
|
const deleteSession = (id) => {
|
|
191
476
|
assertIdle();
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
store.
|
|
197
|
-
|
|
198
|
-
store.
|
|
199
|
-
|
|
477
|
+
if (store.loaded && !store.pending)
|
|
478
|
+
find(id);
|
|
479
|
+
void enqueue(async () => {
|
|
480
|
+
const session = find(id);
|
|
481
|
+
await store.history.remove([id]);
|
|
482
|
+
release(session);
|
|
483
|
+
store.sessions = store.sessions.filter((item) => item !== session);
|
|
484
|
+
store.history.coordinator.release(id);
|
|
485
|
+
if (store.activeId === id) {
|
|
486
|
+
const first = createSessionValue();
|
|
487
|
+
await store.history.open(first.id, true);
|
|
488
|
+
store.sessions.push(first);
|
|
489
|
+
store.activeId = first.id;
|
|
490
|
+
store.intendedId = first.id;
|
|
491
|
+
}
|
|
492
|
+
delete store.error;
|
|
493
|
+
}).catch(() => undefined);
|
|
200
494
|
};
|
|
201
495
|
const clearSession = (id = store.activeId) => {
|
|
202
496
|
assertIdle();
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
497
|
+
if (store.loaded && !store.pending)
|
|
498
|
+
find(id);
|
|
499
|
+
void enqueue(async () => {
|
|
500
|
+
const previous = find(id);
|
|
501
|
+
await store.history.remove([id]);
|
|
502
|
+
const session = createSessionValue();
|
|
503
|
+
if (previous.title)
|
|
504
|
+
session.title = previous.title;
|
|
505
|
+
await store.history.open(session.id, true);
|
|
506
|
+
try {
|
|
507
|
+
if (session.title)
|
|
508
|
+
await saveSession(session);
|
|
509
|
+
}
|
|
510
|
+
finally {
|
|
511
|
+
if (store.activeId !== id)
|
|
512
|
+
store.history.coordinator.release(session.id);
|
|
513
|
+
}
|
|
514
|
+
release(previous);
|
|
515
|
+
store.history.coordinator.release(id);
|
|
516
|
+
store.sessions = store.sessions.map((item) => (item === previous ? session : item));
|
|
517
|
+
if (store.activeId === id) {
|
|
518
|
+
store.activeId = session.id;
|
|
519
|
+
store.intendedId = session.id;
|
|
520
|
+
}
|
|
521
|
+
delete store.error;
|
|
522
|
+
}).catch(() => undefined);
|
|
212
523
|
};
|
|
213
524
|
const sendMessage = useCallback(async (text, attachments = [], revisionOf) => {
|
|
525
|
+
if (store.suspended)
|
|
526
|
+
throw new ClientError("CHAT_RUN_ACTIVE", "Wait for the page to resume before sending.");
|
|
214
527
|
if (store.switching)
|
|
215
528
|
throw new ClientError("CHAT_RUN_ACTIVE", "The model is switching.");
|
|
529
|
+
const targetId = store.intendedId;
|
|
530
|
+
const admission = store.tail;
|
|
531
|
+
if (store.admitting)
|
|
532
|
+
throw new ClientError("CHAT_RUN_ACTIVE", "A task is already starting.");
|
|
533
|
+
store.admitting = true;
|
|
534
|
+
store.admissionCancelled = false;
|
|
535
|
+
changed();
|
|
536
|
+
try {
|
|
537
|
+
await ready();
|
|
538
|
+
await admission;
|
|
539
|
+
if (store.admissionCancelled)
|
|
540
|
+
throw new DOMException("Agent task cancelled.", "AbortError");
|
|
541
|
+
if (!mounted.current || store.activeId !== targetId)
|
|
542
|
+
throw new ClientError("CHAT_RUN_ACTIVE", "The session has changed. Return to the original session and send again.");
|
|
543
|
+
if (!store.history.coordinator.owns(targetId))
|
|
544
|
+
throw sessionLockedError();
|
|
545
|
+
}
|
|
546
|
+
finally {
|
|
547
|
+
store.admitting = false;
|
|
548
|
+
changed();
|
|
549
|
+
}
|
|
216
550
|
let session = active();
|
|
217
551
|
const content = text.trim();
|
|
218
552
|
if (!content && !attachments.length)
|
|
@@ -243,7 +577,15 @@ export function NexfaceProvider(props) {
|
|
|
243
577
|
if (session.client.getMessages().length > messageCount)
|
|
244
578
|
delete store.completion;
|
|
245
579
|
const result = await pending;
|
|
246
|
-
store.
|
|
580
|
+
if (store.sessions.includes(session) && store.history.coordinator.owns(session.id)) {
|
|
581
|
+
try {
|
|
582
|
+
await saveSession(session);
|
|
583
|
+
}
|
|
584
|
+
catch (cause) {
|
|
585
|
+
storageFailure(cause);
|
|
586
|
+
}
|
|
587
|
+
store.completion = { id: createId(), sessionId: session.id, result };
|
|
588
|
+
}
|
|
247
589
|
changed();
|
|
248
590
|
return result;
|
|
249
591
|
}
|
|
@@ -254,6 +596,14 @@ export function NexfaceProvider(props) {
|
|
|
254
596
|
store.sessions = store.sessions.map((item) => (item === session ? previous : item));
|
|
255
597
|
previous = undefined;
|
|
256
598
|
}
|
|
599
|
+
if (store.sessions.includes(session) && store.history.coordinator.owns(session.id)) {
|
|
600
|
+
try {
|
|
601
|
+
await saveSession(session);
|
|
602
|
+
}
|
|
603
|
+
catch (cause) {
|
|
604
|
+
storageFailure(cause);
|
|
605
|
+
}
|
|
606
|
+
}
|
|
257
607
|
changed();
|
|
258
608
|
throw error;
|
|
259
609
|
}
|
|
@@ -265,10 +615,97 @@ export function NexfaceProvider(props) {
|
|
|
265
615
|
sendGuards.set(sendMessage, (sessionId) => {
|
|
266
616
|
if (store.activeId !== sessionId)
|
|
267
617
|
throw new ClientError("CHAT_RUN_ACTIVE", "The session has changed. Return to the original session and send again.");
|
|
268
|
-
if (busy()
|
|
618
|
+
if (busy() ||
|
|
619
|
+
store.pending ||
|
|
620
|
+
store.suspended ||
|
|
621
|
+
(store.loaded && !store.history.coordinator.owns(sessionId)))
|
|
269
622
|
throw new ClientError("CHAT_RUN_ACTIVE", "A task is already running. Try sending again later.");
|
|
270
623
|
getClientController(active().client).assertRecoveryAvailable();
|
|
271
624
|
});
|
|
625
|
+
const confirmationState = (sessionId, request) => {
|
|
626
|
+
const session = store.sessions.find((item) => item.id === sessionId);
|
|
627
|
+
if (!session)
|
|
628
|
+
return "expired";
|
|
629
|
+
const decided = session.confirmations.decisions.get(request.toolCallId);
|
|
630
|
+
if (decided)
|
|
631
|
+
return decided;
|
|
632
|
+
if (session.confirmations.restored.has(request.toolCallId))
|
|
633
|
+
return "expired";
|
|
634
|
+
const messages = projectMessages(session.client.getMessages());
|
|
635
|
+
const lastUser = messages.reduce((last, message, index) => (message.role === "user" ? index : last), -1);
|
|
636
|
+
const owner = messages.findIndex((message) => message.parts.some((part) => {
|
|
637
|
+
const actual = confirmationRequest(part);
|
|
638
|
+
return (actual?.toolCallId === request.toolCallId &&
|
|
639
|
+
actual.requestId === request.requestId &&
|
|
640
|
+
actual.toolName === request.toolName);
|
|
641
|
+
}));
|
|
642
|
+
for (const message of messages)
|
|
643
|
+
for (const part of message.parts) {
|
|
644
|
+
if (part.type !== "tool" || part.name !== request.toolName)
|
|
645
|
+
continue;
|
|
646
|
+
try {
|
|
647
|
+
const decision = JSON.parse(part.arguments)?.confirmation;
|
|
648
|
+
if (decision?.requestId === request.requestId && typeof decision.approved === "boolean")
|
|
649
|
+
return decision.approved ? "approved" : "rejected";
|
|
650
|
+
}
|
|
651
|
+
catch {
|
|
652
|
+
/* Streaming arguments may be incomplete. */
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
return owner > lastUser && store.activeId === sessionId ? "pending" : "expired";
|
|
656
|
+
};
|
|
657
|
+
confirmationControllers.set(sendMessage, {
|
|
658
|
+
state: confirmationState,
|
|
659
|
+
async respond(sessionId, request, approved) {
|
|
660
|
+
if (!store.loaded)
|
|
661
|
+
await ready();
|
|
662
|
+
sendGuards.get(sendMessage)?.(sessionId);
|
|
663
|
+
if (confirmationState(sessionId, request) !== "pending")
|
|
664
|
+
throw new ClientError("INVALID_INPUT", "This confirmation is no longer available.");
|
|
665
|
+
const session = active();
|
|
666
|
+
const controller = getClientController(session.client);
|
|
667
|
+
const messageId = createId();
|
|
668
|
+
session.confirmations.decisions.set(request.toolCallId, "sending");
|
|
669
|
+
changed();
|
|
670
|
+
try {
|
|
671
|
+
const decision = approved ? "确认" : "拒绝";
|
|
672
|
+
const pending = controller.send(JSON.stringify({
|
|
673
|
+
userDecision: {
|
|
674
|
+
toolName: request.toolName,
|
|
675
|
+
toolCallId: request.toolCallId,
|
|
676
|
+
requestId: request.requestId,
|
|
677
|
+
approved,
|
|
678
|
+
},
|
|
679
|
+
message: `${decision}:${request.message}`,
|
|
680
|
+
}), {
|
|
681
|
+
id: messageId,
|
|
682
|
+
role: "user",
|
|
683
|
+
parts: [{ type: "text", text: `${decision}此操作` }],
|
|
684
|
+
});
|
|
685
|
+
if (controller.getMessages().some((message) => message.id === messageId)) {
|
|
686
|
+
session.confirmations.decisions.set(request.toolCallId, approved ? "approved" : "rejected");
|
|
687
|
+
delete store.completion;
|
|
688
|
+
changed();
|
|
689
|
+
}
|
|
690
|
+
const result = await pending;
|
|
691
|
+
try {
|
|
692
|
+
await saveSession(session);
|
|
693
|
+
}
|
|
694
|
+
catch (cause) {
|
|
695
|
+
storageFailure(cause);
|
|
696
|
+
}
|
|
697
|
+
store.completion = { id: createId(), sessionId, result };
|
|
698
|
+
}
|
|
699
|
+
finally {
|
|
700
|
+
// An admitted reply remains answered even if the following model run fails.
|
|
701
|
+
if (controller.getMessages().some((message) => message.id === messageId))
|
|
702
|
+
session.confirmations.decisions.set(request.toolCallId, approved ? "approved" : "rejected");
|
|
703
|
+
else
|
|
704
|
+
session.confirmations.decisions.delete(request.toolCallId);
|
|
705
|
+
changed();
|
|
706
|
+
}
|
|
707
|
+
},
|
|
708
|
+
});
|
|
272
709
|
const session = active();
|
|
273
710
|
const client = session.client;
|
|
274
711
|
const controller = getClientController(client);
|
|
@@ -292,12 +729,15 @@ export function NexfaceProvider(props) {
|
|
|
292
729
|
messages: projectMessages(client.getMessages()),
|
|
293
730
|
status: store.switching
|
|
294
731
|
? "switching-model"
|
|
295
|
-
:
|
|
296
|
-
?
|
|
297
|
-
|
|
732
|
+
: store.admitting
|
|
733
|
+
? store.admissionCancelled
|
|
734
|
+
? "cancelling"
|
|
735
|
+
: "running"
|
|
736
|
+
: controller.cancelling
|
|
737
|
+
? "cancelling"
|
|
738
|
+
: client.getStatus(),
|
|
298
739
|
model: controller.agent?.model ?? { provider: "server", model: "server" },
|
|
299
740
|
...(approval ? { interrupt: approval } : {}),
|
|
300
|
-
...(store.warning ? { storageWarning: store.warning } : {}),
|
|
301
741
|
...(error || store.error ? { error: error ? asError(error) : store.error } : {}),
|
|
302
742
|
...(store.completion?.sessionId === session.id
|
|
303
743
|
? { completed: { id: store.completion.id, result: store.completion.result } }
|
|
@@ -315,27 +755,72 @@ export function NexfaceProvider(props) {
|
|
|
315
755
|
clearSession,
|
|
316
756
|
clearAllSessions() {
|
|
317
757
|
assertIdle();
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
758
|
+
void enqueue(async () => {
|
|
759
|
+
await store.history.remove(store.sessions.map((item) => item.id), true);
|
|
760
|
+
store.sessions.forEach((item) => {
|
|
761
|
+
release(item);
|
|
762
|
+
store.history.coordinator.release(item.id);
|
|
763
|
+
});
|
|
764
|
+
const first = createSessionValue();
|
|
765
|
+
await store.history.open(first.id, true);
|
|
766
|
+
store.sessions = [first];
|
|
767
|
+
store.activeId = first.id;
|
|
768
|
+
store.intendedId = first.id;
|
|
769
|
+
delete store.error;
|
|
770
|
+
}).catch(() => undefined);
|
|
323
771
|
},
|
|
324
772
|
renameSession(id, title) {
|
|
325
773
|
if (!title.trim())
|
|
326
774
|
throw new ClientError("INVALID_INPUT", "Session title is required.");
|
|
327
|
-
|
|
328
|
-
|
|
775
|
+
assertIdle();
|
|
776
|
+
if (store.loaded && !store.pending)
|
|
777
|
+
find(id);
|
|
778
|
+
void enqueue(async () => {
|
|
779
|
+
const session = find(id);
|
|
780
|
+
const temporary = !store.history.coordinator.owns(id);
|
|
781
|
+
try {
|
|
782
|
+
if (temporary) {
|
|
783
|
+
const saved = await store.history.open(id, !session.persisted);
|
|
784
|
+
if (saved) {
|
|
785
|
+
release(session);
|
|
786
|
+
const replacement = createSessionValue(saved);
|
|
787
|
+
store.sessions = store.sessions.map((item) => item === session ? replacement : item);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
const current = find(id);
|
|
791
|
+
const previous = current.title;
|
|
792
|
+
current.title = title.trim().slice(0, 80);
|
|
793
|
+
try {
|
|
794
|
+
await saveSession(current);
|
|
795
|
+
}
|
|
796
|
+
catch (cause) {
|
|
797
|
+
if (previous === undefined)
|
|
798
|
+
delete current.title;
|
|
799
|
+
else
|
|
800
|
+
current.title = previous;
|
|
801
|
+
throw cause;
|
|
802
|
+
}
|
|
803
|
+
delete store.error;
|
|
804
|
+
}
|
|
805
|
+
finally {
|
|
806
|
+
if (temporary)
|
|
807
|
+
store.history.coordinator.release(id);
|
|
808
|
+
}
|
|
809
|
+
}).catch(() => undefined);
|
|
329
810
|
},
|
|
330
811
|
cancel() {
|
|
812
|
+
if (store.admitting) {
|
|
813
|
+
store.admissionCancelled = true;
|
|
814
|
+
changed();
|
|
815
|
+
}
|
|
331
816
|
active().client.cancel();
|
|
332
817
|
},
|
|
333
818
|
confirmInterrupt() {
|
|
334
|
-
if (approval?.mode === "chat")
|
|
819
|
+
if (approval?.mode === "chat" && !store.pending && store.history.coordinator.owns(session.id))
|
|
335
820
|
void client.respondToApproval(approval.id, { approved: true }).catch(() => undefined);
|
|
336
821
|
},
|
|
337
822
|
rejectInterrupt() {
|
|
338
|
-
if (approval?.mode === "chat")
|
|
823
|
+
if (approval?.mode === "chat" && !store.pending && store.history.coordinator.owns(session.id))
|
|
339
824
|
void client.respondToApproval(approval.id, { approved: false }).catch(() => undefined);
|
|
340
825
|
},
|
|
341
826
|
async switchModel(model) {
|
|
@@ -356,12 +841,37 @@ export function NexfaceProvider(props) {
|
|
|
356
841
|
}
|
|
357
842
|
},
|
|
358
843
|
};
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
844
|
+
historyStates.set(value, {
|
|
845
|
+
history: store.history,
|
|
846
|
+
loading: !store.loaded,
|
|
847
|
+
pending: store.pending > 0 || store.admitting || store.suspended,
|
|
848
|
+
occupied: store.occupied,
|
|
849
|
+
notice: (store.error?.code.startsWith("CHAT_STORAGE") ||
|
|
850
|
+
store.error?.code === "CHAT_HISTORY_CONFLICT" ||
|
|
851
|
+
store.error?.code === "CHAT_SESSION_LOCKED"
|
|
852
|
+
? store.error.message
|
|
853
|
+
: undefined) ?? store.notice,
|
|
854
|
+
});
|
|
855
|
+
if (controller.recoveryUnavailable)
|
|
856
|
+
chatsWithoutRecovery.add(value);
|
|
857
|
+
appendOnlySessions.set(value, new Set(store.sessions
|
|
858
|
+
.filter(({ client }) => getClientController(client).appendOnly)
|
|
859
|
+
.map(({ id }) => id)));
|
|
860
|
+
return (_jsx(ChatContext.Provider, { value: value, children: _jsx(ToolPresentationProvider, { controller: getToolPresentationController(toolRuntime), report: (cause, sessionId, toolCallId) => reportError({
|
|
861
|
+
cause,
|
|
862
|
+
sessionId,
|
|
863
|
+
toolCallId,
|
|
864
|
+
code: "CHAT_TOOL_RENDER_FAILED",
|
|
865
|
+
}, onError.current), children: _jsx(ToolsProvider, { toolRuntime: toolRuntime, webMcp: webMcp, children: _jsx(PageConfirmationProvider, { interrupt: approval, onConfirm: () => {
|
|
866
|
+
if (store.pending || !store.history.coordinator.owns(store.activeId))
|
|
867
|
+
return;
|
|
868
|
+
return getClientController(active().client).confirmPage();
|
|
869
|
+
}, onBindingRemoved: () => getClientController(active().client).invalidate("Page confirmation entry was removed."), onBindingRegistration: (name, registered) => {
|
|
870
|
+
if (registered)
|
|
871
|
+
pageTools.current.add(name);
|
|
872
|
+
else
|
|
873
|
+
pageTools.current.delete(name);
|
|
874
|
+
}, children: children }) }) }) }));
|
|
365
875
|
}
|
|
366
876
|
export function useChat() {
|
|
367
877
|
const chat = useContext(ChatContext);
|