@assistant-ui/react-statewire 0.32.0 → 0.33.0

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.
@@ -40,7 +40,6 @@ import {
40
40
  createBranchCommandAdapter,
41
41
  createRunQueueAdapter,
42
42
  resolveEditCommand,
43
- retryCommand,
44
43
  resolveReloadCommand,
45
44
  sendFields,
46
45
  toWireMessage,
@@ -74,34 +73,13 @@ export const asStatewireExtras = (extras: unknown): StatewireThread.Extras => {
74
73
 
75
74
  const NO_INPUT_REQUESTS: readonly StatewireThread.InputRequestState[] = [];
76
75
 
76
+ const NO_HELD: readonly StatewireThread.RunsHeldEntry[] = [];
77
+
77
78
  const RESTING_RUNS: StatewireThread.Runs = {
78
79
  runId: null,
79
80
  queue: [],
80
81
  steerQueue: [],
81
- failed: [],
82
- };
83
-
84
- /** The failed run sends the thread can project: enqueue/steer/edit invocations carrying a message. */
85
- const failedRunCommand = (
86
- entry: StatewireClient.FailedCommand,
87
- ):
88
- | ((
89
- | StatewireThread.RunEnqueueCommand
90
- | StatewireThread.RunSteerCommand
91
- | StatewireThread.RunEditCommand
92
- ) & { message: StatewireThread.UserMessage })
93
- | undefined => {
94
- if (
95
- entry.command !== "run/enqueue" &&
96
- entry.command !== "run/steer" &&
97
- entry.command !== "run/edit"
98
- )
99
- return undefined;
100
- const command = entry.params[0] as
101
- | { message?: StatewireThread.UserMessage }
102
- | undefined;
103
- if (command?.message === undefined) return undefined;
104
- return command as ReturnType<typeof failedRunCommand>;
82
+ held: NO_HELD,
105
83
  };
106
84
 
107
85
  // Derived presentation while the connection can't vouch for progress:
@@ -136,7 +114,6 @@ const useStatewireThread = (
136
114
  ): ClientOutput<"thread"> => {
137
115
  const latest = useRef(options);
138
116
  latest.current = options;
139
- const retrying = useRef(new Set<string>());
140
117
 
141
118
  const [pending, setPending] = useState<readonly StatewireThread.Command[]>(
142
119
  [],
@@ -158,8 +135,7 @@ const useStatewireThread = (
158
135
  invoke,
159
136
  setContext,
160
137
  isBusy,
161
- failed,
162
- discardFailed,
138
+ outbox,
163
139
  } = useStatewire<unknown, AnyCommands>({
164
140
  transport: options.transport,
165
141
  onError: (error) => latest.current.onError?.(error),
@@ -174,34 +150,13 @@ const useStatewireThread = (
174
150
  onCommandChange: (update, ctx) => {
175
151
  if (update.status === "applied" || update.status === "settled")
176
152
  retire(update.params[0]);
177
- latest.current.onCommandChange?.(update, ctx);
153
+ return latest.current.onCommandChange?.(update, ctx);
178
154
  },
179
155
  onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
180
156
  onConnectionChange: (connection) =>
181
157
  latest.current.onConnectionChange?.(connection),
182
- failureCovered: (state, entry) => {
183
- const command = failedRunCommand(entry);
184
- if (command === undefined) return false;
185
- const messages = (state as { messages?: readonly { id: string }[] })
186
- .messages;
187
- return messages?.some((m) => m.id === command.message.id) ?? false;
188
- },
189
158
  });
190
159
 
191
- const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());
192
- // Effects can replay before the updated failed lane reaches the binding.
193
- useEffect(() => {
194
- for (const entry of failed) {
195
- if (
196
- failedRunCommand(entry) === undefined &&
197
- !discarded.current.has(entry)
198
- ) {
199
- discarded.current.add(entry);
200
- discardFailed(entry);
201
- }
202
- }
203
- }, [failed, discardFailed]);
204
-
205
160
  const clientRef = useAssistantClientRef();
206
161
  const contextRef = useRef(setContext);
207
162
  contextRef.current = setContext;
@@ -323,21 +278,16 @@ const useStatewireThread = (
323
278
  state as { runs?: readonly StatewireThread.RunState[] } | undefined
324
279
  )?.runs;
325
280
  const entry = entries?.[0];
326
- const failedEntries = failed.flatMap(
327
- (failure): StatewireThread.RunsFailedEntry[] => {
328
- const command = failedRunCommand(failure);
329
- return command === undefined
330
- ? []
331
- : [{ ...command.message, sendFailure: failure.failure }];
332
- },
333
- );
281
+ const held =
282
+ (state as { runsHeld?: readonly StatewireThread.RunsHeldEntry[] })
283
+ ?.runsHeld ?? NO_HELD;
334
284
  return {
335
285
  status: presentStatus(
336
286
  entries === undefined ? "loading" : (entry?.status ?? "ready"),
337
287
  connection,
338
288
  ),
339
289
  runs:
340
- entry === undefined && failedEntries.length === 0
290
+ entry === undefined && held.length === 0
341
291
  ? RESTING_RUNS
342
292
  : {
343
293
  ...(entry === undefined
@@ -364,10 +314,10 @@ const useStatewireThread = (
364
314
  }),
365
315
  ...(entry.error !== undefined && { error: entry.error }),
366
316
  }),
367
- failed: failedEntries,
317
+ held,
368
318
  },
369
319
  };
370
- }, [state, connection, failed]);
320
+ }, [state, connection]);
371
321
 
372
322
  const { converter } = options;
373
323
  const mounted = useSyncExternalStore(
@@ -419,16 +369,8 @@ const useStatewireThread = (
419
369
  [messages, dispatch],
420
370
  );
421
371
 
422
- const extras = useMemo((): StatewireThread.Extras => {
423
- const takeFailed = (messageId: string): StatewireClient.FailedCommand => {
424
- const entry = failed.find(
425
- (f) => failedRunCommand(f)?.message.id === messageId,
426
- );
427
- if (entry === undefined)
428
- throw new Error(`statewire: unknown failed entry "${messageId}"`);
429
- return entry;
430
- };
431
- return {
372
+ const extras = useMemo(
373
+ (): StatewireThread.Extras => ({
432
374
  [symbolStatewireExtras]: true,
433
375
  sendCommand: dispatch,
434
376
  reconnect: connection.reconnect,
@@ -440,54 +382,22 @@ const useStatewireThread = (
440
382
  isBusy,
441
383
  inputRequests,
442
384
  runs,
443
- retryFailed: (messageId) => {
444
- if (retrying.current.has(messageId)) return;
445
- const entry = takeFailed(messageId);
446
- const command = retryCommand(
447
- messages,
448
- liveRunId,
449
- failedRunCommand(entry)!,
450
- );
451
- const held = heldByContext(command);
452
- if (held !== undefined) throw held;
453
- retrying.current.add(messageId);
454
- const release = () => {
455
- retrying.current.delete(messageId);
456
- };
457
- try {
458
- discardFailed(entry);
459
- void dispatch(command).then(release, release);
460
- } catch (error) {
461
- release();
462
- throw error;
463
- }
464
- },
465
- discardFailed: (messageId) => discardFailed(takeFailed(messageId)),
466
- popFailed: (messageId) => {
467
- const entry = takeFailed(messageId);
468
- discardFailed(entry);
469
- return failedRunCommand(entry)!
470
- .message.parts.flatMap((p) => (p.type === "text" ? [p.text] : []))
471
- .join("\n\n");
472
- },
473
- };
474
- }, [
475
- dispatch,
476
- heldByContext,
477
- connection,
478
- documents,
479
- invoke,
480
- state,
481
- converted.state,
482
- status,
483
- isBusy,
484
- inputRequests,
485
- runs,
486
- failed,
487
- discardFailed,
488
- messages,
489
- liveRunId,
490
- ]);
385
+ outbox,
386
+ }),
387
+ [
388
+ dispatch,
389
+ connection,
390
+ documents,
391
+ invoke,
392
+ state,
393
+ converted.state,
394
+ status,
395
+ isBusy,
396
+ inputRequests,
397
+ runs,
398
+ outbox,
399
+ ],
400
+ );
491
401
 
492
402
  const handleAppend = (message: AppendMessage) => {
493
403
  dispatchSend(
@@ -678,12 +588,8 @@ export namespace StatewireThread {
678
588
  isBusy: boolean;
679
589
  inputRequests: readonly InputRequestState[];
680
590
  runs: Runs;
681
- /** Re-dispatches the failed entry against the current thread and removes it; keyed by the entry's message id. */
682
- retryFailed: (messageId: string) => void;
683
- /** Removes the failed entry; keyed by the entry's message id. */
684
- discardFailed: (messageId: string) => void;
685
- /** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */
686
- popFailed: (messageId: string) => string;
591
+ /** The session's outbox: release, edit or remove held sends. */
592
+ outbox: StatewireClient.Outbox;
687
593
  };
688
594
 
689
595
  export type TextPart = {
@@ -845,9 +751,9 @@ export namespace StatewireThread {
845
751
  readonly meta?: ReadonlyJSONValue;
846
752
  };
847
753
 
848
- /** A failed run send projected out of the retained lane: the entry shape plus its send failure. */
849
- export type RunsFailedEntry = RunsQueueEntry & {
850
- readonly sendFailure: StatewireClient.SendFailure;
754
+ /** A held run send folded from the outbox: the message plus the entry's localMeta. */
755
+ export type RunsHeldEntry = RunsQueueEntry & {
756
+ readonly localMeta: unknown;
851
757
  };
852
758
 
853
759
  /** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
@@ -944,8 +850,8 @@ export namespace StatewireThread {
944
850
  readonly inputRequests?: readonly InputRequestState[];
945
851
  /** Set only by an unhandled throw; cleared by the next user-initiated run. */
946
852
  readonly error?: RunsError;
947
- /** Run sends retained after a non-accepted settle; retry, discard, or pop via the thread extras. */
948
- readonly failed: readonly RunsFailedEntry[];
853
+ /** Held run sends (enqueue, steer, edit) in queue order; release or remove them through `extras.outbox`. */
854
+ readonly held: readonly RunsHeldEntry[];
949
855
  };
950
856
 
951
857
  export type ConnectionMetadata = {
@@ -1009,14 +915,14 @@ export namespace StatewireThread {
1009
915
  contextSync?: "command-send" | undefined;
1010
916
  /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
1011
917
  stopPayload?: (() => StopPayload) | undefined;
1012
- /** Observes each command's lifecycle (queued, posted, applied, settled); runs after the built-in pending-command retirement. */
918
+ /** Observes each command's lifecycle after the built-in pending-command retirement; a durable `settled` update is acked once the returned promise resolves. */
1013
919
  onCommandChange?:
1014
920
  | ((
1015
921
  update: Statewire.CommandUpdate<
1016
922
  Record<string, (...args: any[]) => unknown>
1017
923
  >,
1018
924
  ctx: { state: NonNullable<T> },
1019
- ) => void)
925
+ ) => unknown)
1020
926
  | undefined;
1021
927
  /** Observes the transport state: fires with the attach snapshot, then once per change. */
1022
928
  onStateChange?:
@@ -235,7 +235,7 @@ describe("LocalStorageSession", () => {
235
235
  root.getValue().save(record);
236
236
  expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
237
237
  ...record,
238
- statewireStorageVersion: 4,
238
+ statewireStorageVersion: 5,
239
239
  savedAt: expect.any(Number),
240
240
  });
241
241
  expect(root.getValue().load()).toEqual(record);
@@ -182,6 +182,8 @@ const SESSION_ACTIVE_PREFIX = "aui:statewire-session-active:";
182
182
 
183
183
  const TAB_LOCK_PREFIX = "statewire-tab:";
184
184
 
185
+ const NOTIFY_LOCK_PREFIX = "statewire-notify:";
186
+
185
187
  const sessionBackend: KeyValueSessionStorage.Backend = {
186
188
  getItem: (key) => localStorage.getItem(key),
187
189
  setItem: (key, value) => localStorage.setItem(key, value),
@@ -203,6 +205,13 @@ const sessionBackend: KeyValueSessionStorage.Backend = {
203
205
  (lock) => (lock === null ? undefined : action()),
204
206
  ),
205
207
  ),
208
+ subscribe: (listener) => {
209
+ const onStorage = (event: StorageEvent) => {
210
+ if (event.key !== null) listener(event.key);
211
+ };
212
+ window.addEventListener("storage", onStorage);
213
+ return () => window.removeEventListener("storage", onStorage);
214
+ },
206
215
  };
207
216
 
208
217
  const useLocalStorageSession = ({
@@ -211,7 +220,9 @@ const useLocalStorageSession = ({
211
220
  principal,
212
221
  protocol,
213
222
  retention,
223
+ limits,
214
224
  onError,
225
+ onEvict,
215
226
  }: LocalStorageSession.Options): StatewireClient.SessionStorage => {
216
227
  if (typeof localStorage === "undefined")
217
228
  throw new Error("statewire: LocalStorageSession requires localStorage");
@@ -261,13 +272,17 @@ const useLocalStorageSession = ({
261
272
  ...(migrate === undefined ? {} : { migrate }),
262
273
  ...(protocol === undefined ? {} : { protocol }),
263
274
  ...(retention === undefined ? {} : { retention }),
275
+ ...(limits === undefined ? {} : { limits }),
264
276
  ...(onError === undefined ? {} : { onError }),
277
+ ...(onEvict === undefined ? {} : { onEvict }),
265
278
  }),
266
279
  );
267
280
  return useMemo(
268
281
  (): StatewireClient.SessionStorage => ({
269
282
  ...storage,
270
283
  lock: (fn) => navigator.locks.request(lockName, async () => fn()),
284
+ notifyLock: (fn) =>
285
+ navigator.locks.request(NOTIFY_LOCK_PREFIX + storageKey, fn),
271
286
  owner: {
272
287
  id: tabId,
273
288
  whenGone: (id, signal) =>
@@ -285,6 +300,13 @@ const useLocalStorageSession = ({
285
300
  );
286
301
  };
287
302
 
303
+ /** The localStorage backend `LocalStorageSession` writes through; pass it to `readOutboxes` / `subscribeOutboxes`. */
304
+ export const localStorageSessionBackend = sessionBackend;
305
+
306
+ /** The namespace `LocalStorageSession` stores a principal's sessions under. */
307
+ export const localStorageSessionNamespace = (principal: string) =>
308
+ scopePrefix(SESSION_PREFIX, principal);
309
+
288
310
  /** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
289
311
  export const LocalStorageSession = resource(useLocalStorageSession);
290
312
 
@@ -292,7 +314,9 @@ export namespace LocalStorageSession {
292
314
  export type Options = {
293
315
  protocol?: KeyValueSessionStorage.Options["protocol"];
294
316
  retention?: KeyValueSessionStorage.Options["retention"];
317
+ limits?: KeyValueSessionStorage.Options["limits"];
295
318
  onError?: KeyValueSessionStorage.Options["onError"];
319
+ onEvict?: KeyValueSessionStorage.Options["onEvict"];
296
320
  /** Upgrade incompatible queued commands, or return null to discard the saved session. */
297
321
  migrate?: StatewireClient.SessionStorage["migrate"];
298
322
  /** The thread whose session this storage holds. */
@@ -128,38 +128,6 @@ export const sendFields = (
128
128
  runAnchorMessageId: viewedLeafId(messages),
129
129
  };
130
130
 
131
- /** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */
132
- export const retryCommand = (
133
- messages: readonly { id: string; status?: { type: string } }[],
134
- runId: string | null,
135
- command:
136
- | (StatewireThread.RunEnqueueCommand & {
137
- message: StatewireThread.UserMessage;
138
- })
139
- | (StatewireThread.RunSteerCommand & {
140
- message: StatewireThread.UserMessage;
141
- })
142
- | StatewireThread.RunEditCommand,
143
- ): StatewireThread.RunCommand => {
144
- if (command.type === "run/edit") {
145
- const index = messages.findIndex((m) => m.id === command.sourceId);
146
- if (index === -1)
147
- throw new Error(
148
- `statewire: run/edit source "${command.sourceId}" is unknown`,
149
- );
150
- return {
151
- ...command,
152
- runId: runId ?? crypto.randomUUID(),
153
- runAnchorMessageId: messages[index - 1]?.id ?? null,
154
- };
155
- }
156
- if (runId !== null && command.runId === runId) return command;
157
- return {
158
- type: "run/enqueue",
159
- ...sendFields(messages, runId, command.message),
160
- };
161
- };
162
-
163
131
  export const createRunQueueAdapter = (
164
132
  live: () => { messages: readonly { id: string }[]; runId: string | null },
165
133
  queueItems: readonly StatewireThread.RunQueueItem[],
@@ -6,7 +6,7 @@ import { runsOptimistic } from "./runsOptimistic";
6
6
 
7
7
  type Draft = Record<string, any>;
8
8
 
9
- const ctx = { ts: 0, seq: 7, held: null };
9
+ const ctx = { ts: 0, seq: 7, state: "sending" as const, localMeta: undefined };
10
10
 
11
11
  const mount = (entry?: Draft): Draft =>
12
12
  entry === undefined
@@ -13,6 +13,7 @@ type LaneEntry = Mutable<StatewireThread.RunsQueueEntry>;
13
13
  type Dispatch = Mutable<StatewireThread.RunsDispatch>;
14
14
  type RunEntry = Mutable<StatewireThread.RunState>;
15
15
  type RunsDraft = Partial<Mutable<StatewireThread.RunsState>>;
16
+ type HeldEntry = LaneEntry & { localMeta: unknown };
16
17
 
17
18
  const laneEntry = (message: StatewireThread.UserMessage): LaneEntry => ({
18
19
  ...message,
@@ -144,7 +145,24 @@ export const runsOptimistic = (
144
145
  command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,
145
146
  ctx: StatewireClient.OptimisticContext,
146
147
  ): void => {
147
- const draft = mount as RunsDraft;
148
+ const draft = mount as RunsDraft & { runsHeld?: HeldEntry[] };
149
+ // A held send waits in the outbox: it shows as held, never as a run.
150
+ if (ctx.state === "held") {
151
+ const params = command.params[0] as
152
+ | { message?: StatewireThread.UserMessage }
153
+ | undefined;
154
+ if (
155
+ (command.method === "run/enqueue" ||
156
+ command.method === "run/steer" ||
157
+ command.method === "run/edit") &&
158
+ params?.message !== undefined
159
+ )
160
+ (draft.runsHeld ??= []).push({
161
+ ...laneEntry(params.message),
162
+ localMeta: ctx.localMeta,
163
+ });
164
+ return;
165
+ }
148
166
  const commandRunId = (command.params[0] as { runId?: string } | undefined)
149
167
  ?.runId;
150
168
  const runId = commandRunId ?? `optimistic-${ctx.seq ?? `q${ctx.ts}`}`;