@nexface/chat 0.1.21-alpha.0 → 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/react.js CHANGED
@@ -7,7 +7,8 @@ import { PageConfirmationProvider, } from "./page-confirmation.js";
7
7
  import { createChatClient, getClientController, ClientError, } from "./client.js";
8
8
  import { attachmentContent } from "./attachments.js";
9
9
  import { projectMessages } from "./protocol-messages.js";
10
- import { chatStorageKey, readChatStorage, writeChatStorage } from "./storage.js";
10
+ import { encodeSession } from "./storage.js";
11
+ import { SessionHistory, sessionLockedError } from "./session-history.js";
11
12
  import { getToolPresentationController, } from "./shared/tool-presentation.js";
12
13
  export function isChatError(error) {
13
14
  const value = error;
@@ -16,6 +17,34 @@ export function isChatError(error) {
16
17
  typeof value.code === "string" &&
17
18
  typeof value.message === "string");
18
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
+ }
19
48
  const sendGuards = new WeakMap();
20
49
  const appendOnlySessions = new WeakMap();
21
50
  const chatsWithoutRecovery = new WeakSet();
@@ -99,6 +128,7 @@ export function NexfaceProvider(props) {
99
128
  id: saved?.id ?? controller.id,
100
129
  client,
101
130
  ...(saved?.title ? { title: saved.title } : {}),
131
+ persisted: Boolean(saved),
102
132
  unsubscribe: client.subscribe(changed),
103
133
  };
104
134
  }, [props.agent, props.run, toolRuntime, changed]);
@@ -109,7 +139,14 @@ export function NexfaceProvider(props) {
109
139
  activeId: first.id,
110
140
  loaded: false,
111
141
  switching: false,
112
- version: { value: null },
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(),
113
150
  };
114
151
  }
115
152
  const store = storeRef.current;
@@ -121,6 +158,7 @@ export function NexfaceProvider(props) {
121
158
  return session;
122
159
  };
123
160
  const busy = () => store.switching ||
161
+ store.admitting ||
124
162
  store.sessions.some((session) => getClientController(session.client).busy && session.client.getStatus() !== "waiting");
125
163
  const assertIdle = (code = "CHAT_RUN_ACTIVE") => {
126
164
  if (busy())
@@ -134,112 +172,381 @@ export function NexfaceProvider(props) {
134
172
  if (active().client.getStatus() === "waiting")
135
173
  active().client.cancel();
136
174
  };
137
- useEffect(() => {
138
- if (store.loaded)
139
- return;
140
- store.loaded = true;
141
- const saved = readChatStorage(chatStorageKey, store.version);
142
- if (!saved)
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))
143
187
  return;
144
- const restored = saved.sessions.map(createSessionValue);
145
- const latest = restored.at(-1);
146
- if (latest.client.getMessages().length === 0) {
147
- store.sessions.forEach(release);
148
- store.sessions = restored;
149
- store.activeId = latest.id;
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();
150
213
  }
151
- else {
152
- store.sessions = [...restored, ...store.sessions];
214
+ catch (cause) {
215
+ storageFailure(cause);
153
216
  }
154
- changed();
155
- }, []);
156
- const persist = () => {
157
- if (store.storageConflict)
158
- return;
159
- const stored = {
160
- activeSessionId: store.activeId,
161
- sessions: store.sessions.map((session) => ({
162
- id: session.id,
163
- ...(session.title ? { title: session.title } : {}),
164
- ...(getClientController(session.client).appendOnly ? { appendOnly: true } : {}),
165
- messages: [...projectMessages(session.client.getMessages())],
166
- })),
167
- };
168
- if (writeChatStorage(chatStorageKey, stored, store.version) === "conflict") {
169
- store.storageConflict = true;
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;
233
+ changed();
170
234
  }
171
235
  };
172
- useEffect(() => {
173
- const timer = setTimeout(persist, busy() ? 250 : 0);
174
- return () => clearTimeout(timer);
175
- });
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
+ };
176
261
  useEffect(() => {
177
262
  mounted.current = true;
178
- const flush = () => persist();
179
- window.addEventListener("pagehide", flush);
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);
180
355
  return () => {
356
+ disposed = true;
181
357
  mounted.current = false;
182
- window.removeEventListener("pagehide", flush);
183
- flush();
358
+ window.clearInterval(timer);
359
+ window.removeEventListener("storage", reconcile);
360
+ window.removeEventListener("focus", reconcile);
361
+ window.removeEventListener("pageshow", onShow);
362
+ window.removeEventListener("pagehide", onHide);
184
363
  queueMicrotask(() => {
185
- if (!mounted.current)
364
+ if (mounted.current)
365
+ return;
366
+ const close = () => {
186
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
+ });
187
390
  });
188
391
  };
189
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
+ };
190
440
  const createSession = useCallback(() => {
191
441
  assertIdle("CHAT_SESSION_CREATE_BLOCKED");
192
- cancelWaiting();
193
442
  const latest = store.sessions.at(-1);
194
- if (latest.client.getMessages().length === 0) {
195
- store.activeId = latest.id;
196
- delete store.error;
197
- changed();
198
- return latest.id;
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;
199
448
  }
200
- const session = createSessionValue();
201
- store.sessions.push(session);
202
- store.activeId = session.id;
203
- delete store.error;
204
- changed();
205
- return session.id;
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;
206
465
  }, [createSessionValue]);
207
466
  const switchSession = (id) => {
208
467
  assertIdle("CHAT_SESSION_SWITCH_BLOCKED");
209
- find(id);
210
- if (store.activeId === id)
211
- return;
212
- cancelWaiting();
213
- store.activeId = id;
214
- delete store.error;
215
- 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);
216
474
  };
217
475
  const deleteSession = (id) => {
218
476
  assertIdle();
219
- const session = find(id);
220
- release(session);
221
- store.sessions = store.sessions.filter((item) => item !== session);
222
- if (!store.sessions.length)
223
- store.sessions.push(createSessionValue());
224
- if (store.activeId === id)
225
- store.activeId = store.sessions[0].id;
226
- changed();
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);
227
494
  };
228
495
  const clearSession = (id = store.activeId) => {
229
496
  assertIdle();
230
- const previous = find(id);
231
- const session = createSessionValue();
232
- if (previous.title)
233
- session.title = previous.title;
234
- release(previous);
235
- store.sessions = store.sessions.map((item) => (item === previous ? session : item));
236
- if (store.activeId === id)
237
- store.activeId = session.id;
238
- changed();
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);
239
523
  };
240
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.");
241
527
  if (store.switching)
242
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
+ }
243
550
  let session = active();
244
551
  const content = text.trim();
245
552
  if (!content && !attachments.length)
@@ -270,7 +577,15 @@ export function NexfaceProvider(props) {
270
577
  if (session.client.getMessages().length > messageCount)
271
578
  delete store.completion;
272
579
  const result = await pending;
273
- store.completion = { id: createId(), sessionId: session.id, result };
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
+ }
274
589
  changed();
275
590
  return result;
276
591
  }
@@ -281,6 +596,14 @@ export function NexfaceProvider(props) {
281
596
  store.sessions = store.sessions.map((item) => (item === session ? previous : item));
282
597
  previous = undefined;
283
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
+ }
284
607
  changed();
285
608
  throw error;
286
609
  }
@@ -292,7 +615,10 @@ export function NexfaceProvider(props) {
292
615
  sendGuards.set(sendMessage, (sessionId) => {
293
616
  if (store.activeId !== sessionId)
294
617
  throw new ClientError("CHAT_RUN_ACTIVE", "The session has changed. Return to the original session and send again.");
295
- if (busy())
618
+ if (busy() ||
619
+ store.pending ||
620
+ store.suspended ||
621
+ (store.loaded && !store.history.coordinator.owns(sessionId)))
296
622
  throw new ClientError("CHAT_RUN_ACTIVE", "A task is already running. Try sending again later.");
297
623
  getClientController(active().client).assertRecoveryAvailable();
298
624
  });
@@ -331,6 +657,8 @@ export function NexfaceProvider(props) {
331
657
  confirmationControllers.set(sendMessage, {
332
658
  state: confirmationState,
333
659
  async respond(sessionId, request, approved) {
660
+ if (!store.loaded)
661
+ await ready();
334
662
  sendGuards.get(sendMessage)?.(sessionId);
335
663
  if (confirmationState(sessionId, request) !== "pending")
336
664
  throw new ClientError("INVALID_INPUT", "This confirmation is no longer available.");
@@ -360,6 +688,12 @@ export function NexfaceProvider(props) {
360
688
  changed();
361
689
  }
362
690
  const result = await pending;
691
+ try {
692
+ await saveSession(session);
693
+ }
694
+ catch (cause) {
695
+ storageFailure(cause);
696
+ }
363
697
  store.completion = { id: createId(), sessionId, result };
364
698
  }
365
699
  finally {
@@ -395,9 +729,13 @@ export function NexfaceProvider(props) {
395
729
  messages: projectMessages(client.getMessages()),
396
730
  status: store.switching
397
731
  ? "switching-model"
398
- : controller.cancelling
399
- ? "cancelling"
400
- : client.getStatus(),
732
+ : store.admitting
733
+ ? store.admissionCancelled
734
+ ? "cancelling"
735
+ : "running"
736
+ : controller.cancelling
737
+ ? "cancelling"
738
+ : client.getStatus(),
401
739
  model: controller.agent?.model ?? { provider: "server", model: "server" },
402
740
  ...(approval ? { interrupt: approval } : {}),
403
741
  ...(error || store.error ? { error: error ? asError(error) : store.error } : {}),
@@ -417,27 +755,72 @@ export function NexfaceProvider(props) {
417
755
  clearSession,
418
756
  clearAllSessions() {
419
757
  assertIdle();
420
- store.sessions.forEach(release);
421
- const first = createSessionValue();
422
- store.sessions = [first];
423
- store.activeId = first.id;
424
- changed();
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);
425
771
  },
426
772
  renameSession(id, title) {
427
773
  if (!title.trim())
428
774
  throw new ClientError("INVALID_INPUT", "Session title is required.");
429
- find(id).title = title.trim().slice(0, 80);
430
- changed();
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);
431
810
  },
432
811
  cancel() {
812
+ if (store.admitting) {
813
+ store.admissionCancelled = true;
814
+ changed();
815
+ }
433
816
  active().client.cancel();
434
817
  },
435
818
  confirmInterrupt() {
436
- if (approval?.mode === "chat")
819
+ if (approval?.mode === "chat" && !store.pending && store.history.coordinator.owns(session.id))
437
820
  void client.respondToApproval(approval.id, { approved: true }).catch(() => undefined);
438
821
  },
439
822
  rejectInterrupt() {
440
- if (approval?.mode === "chat")
823
+ if (approval?.mode === "chat" && !store.pending && store.history.coordinator.owns(session.id))
441
824
  void client.respondToApproval(approval.id, { approved: false }).catch(() => undefined);
442
825
  },
443
826
  async switchModel(model) {
@@ -458,6 +841,17 @@ export function NexfaceProvider(props) {
458
841
  }
459
842
  },
460
843
  };
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
+ });
461
855
  if (controller.recoveryUnavailable)
462
856
  chatsWithoutRecovery.add(value);
463
857
  appendOnlySessions.set(value, new Set(store.sessions
@@ -468,7 +862,11 @@ export function NexfaceProvider(props) {
468
862
  sessionId,
469
863
  toolCallId,
470
864
  code: "CHAT_TOOL_RENDER_FAILED",
471
- }, onError.current), 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) => {
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) => {
472
870
  if (registered)
473
871
  pageTools.current.add(name);
474
872
  else