@assistant-ui/react-statewire 0.31.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.
- package/README.md +4 -4
- package/dist/StatewireThread.d.ts +337 -343
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +73 -135
- package/dist/StatewireThread.js.map +1 -1
- package/dist/hooks.d.ts +7 -9
- package/dist/hooks.d.ts.map +1 -1
- package/dist/hooks.js +1 -2
- package/dist/hooks.js.map +1 -1
- package/dist/index.d.ts +4 -4
- package/dist/index.d.ts.map +1 -0
- package/dist/inputRequests.d.ts +9 -12
- package/dist/inputRequests.d.ts.map +1 -1
- package/dist/inputRequests.js +1 -2
- package/dist/localStorage.d.ts +33 -30
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +61 -62
- package/dist/localStorage.js.map +1 -1
- package/dist/runCommands.d.ts +26 -40
- package/dist/runCommands.d.ts.map +1 -1
- package/dist/runCommands.js +2 -20
- package/dist/runCommands.js.map +1 -1
- package/dist/runsMaterialize.d.ts +2 -5
- package/dist/runsMaterialize.d.ts.map +1 -1
- package/dist/runsMaterialize.js +1 -2
- package/dist/runsOptimistic.d.ts +2 -5
- package/dist/runsOptimistic.d.ts.map +1 -1
- package/dist/runsOptimistic.js +10 -3
- package/dist/runsOptimistic.js.map +1 -1
- package/package.json +16 -14
- package/src/{StatewireThread.failed.test.tsx → StatewireThread.held.test.tsx} +60 -137
- package/src/StatewireThread.runs.test.tsx +1 -1
- package/src/StatewireThread.ts +44 -137
- package/src/localStorage.test.ts +7 -2
- package/src/localStorage.ts +46 -2
- package/src/runCommands.ts +0 -32
- package/src/runsOptimistic.test.ts +1 -1
- package/src/runsOptimistic.ts +20 -2
package/src/StatewireThread.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
|
327
|
-
(
|
|
328
|
-
|
|
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 &&
|
|
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
|
-
|
|
317
|
+
held,
|
|
368
318
|
},
|
|
369
319
|
};
|
|
370
|
-
}, [state, connection
|
|
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(
|
|
423
|
-
|
|
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
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
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(
|
|
@@ -520,9 +430,9 @@ const useStatewireThread = (
|
|
|
520
430
|
resolveToolResultInput(inputRequests, toolOptions, runId),
|
|
521
431
|
);
|
|
522
432
|
},
|
|
523
|
-
onRespondToToolApproval: (approval: RespondToToolApprovalOptions) => {
|
|
433
|
+
onRespondToToolApproval: async (approval: RespondToToolApprovalOptions) => {
|
|
524
434
|
const { inputRequests, runId, dispatch } = live.current;
|
|
525
|
-
|
|
435
|
+
await dispatch(resolveToolApprovalInput(inputRequests, approval, runId));
|
|
526
436
|
},
|
|
527
437
|
}));
|
|
528
438
|
|
|
@@ -539,11 +449,12 @@ const useStatewireThread = (
|
|
|
539
449
|
queue,
|
|
540
450
|
...(options.capabilities?.edit && { onEdit: messageHandlers.onEdit }),
|
|
541
451
|
...(options.capabilities?.continue && {
|
|
542
|
-
onResume: () =>
|
|
543
|
-
dispatch({
|
|
452
|
+
onResume: async () => {
|
|
453
|
+
await dispatch({
|
|
544
454
|
type: "run/continue",
|
|
545
455
|
...(liveRunId !== null && { runId: liveRunId }),
|
|
546
|
-
})
|
|
456
|
+
});
|
|
457
|
+
},
|
|
547
458
|
}),
|
|
548
459
|
...(options.capabilities?.reload && { onReload: handleReload }),
|
|
549
460
|
...(options.capabilities?.unstable_switchBranch && { branches }),
|
|
@@ -677,12 +588,8 @@ export namespace StatewireThread {
|
|
|
677
588
|
isBusy: boolean;
|
|
678
589
|
inputRequests: readonly InputRequestState[];
|
|
679
590
|
runs: Runs;
|
|
680
|
-
/**
|
|
681
|
-
|
|
682
|
-
/** Removes the failed entry; keyed by the entry's message id. */
|
|
683
|
-
discardFailed: (messageId: string) => void;
|
|
684
|
-
/** Removes the failed entry and returns its text for the composer; keyed by the entry's message id. */
|
|
685
|
-
popFailed: (messageId: string) => string;
|
|
591
|
+
/** The session's outbox: release, edit or remove held sends. */
|
|
592
|
+
outbox: StatewireClient.Outbox;
|
|
686
593
|
};
|
|
687
594
|
|
|
688
595
|
export type TextPart = {
|
|
@@ -844,9 +751,9 @@ export namespace StatewireThread {
|
|
|
844
751
|
readonly meta?: ReadonlyJSONValue;
|
|
845
752
|
};
|
|
846
753
|
|
|
847
|
-
/** A
|
|
848
|
-
export type
|
|
849
|
-
readonly
|
|
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;
|
|
850
757
|
};
|
|
851
758
|
|
|
852
759
|
/** An input outcome riding a dispatch record: the request with its response (null = abandoned) and `run/input` meta. */
|
|
@@ -943,8 +850,8 @@ export namespace StatewireThread {
|
|
|
943
850
|
readonly inputRequests?: readonly InputRequestState[];
|
|
944
851
|
/** Set only by an unhandled throw; cleared by the next user-initiated run. */
|
|
945
852
|
readonly error?: RunsError;
|
|
946
|
-
/**
|
|
947
|
-
readonly
|
|
853
|
+
/** Held run sends (enqueue, steer, edit) in queue order; release or remove them through `extras.outbox`. */
|
|
854
|
+
readonly held: readonly RunsHeldEntry[];
|
|
948
855
|
};
|
|
949
856
|
|
|
950
857
|
export type ConnectionMetadata = {
|
|
@@ -1008,14 +915,14 @@ export namespace StatewireThread {
|
|
|
1008
915
|
contextSync?: "command-send" | undefined;
|
|
1009
916
|
/** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
|
|
1010
917
|
stopPayload?: (() => StopPayload) | undefined;
|
|
1011
|
-
/** Observes each command's lifecycle
|
|
918
|
+
/** Observes each command's lifecycle after the built-in pending-command retirement; a durable `settled` update is acked once the returned promise resolves. */
|
|
1012
919
|
onCommandChange?:
|
|
1013
920
|
| ((
|
|
1014
921
|
update: Statewire.CommandUpdate<
|
|
1015
922
|
Record<string, (...args: any[]) => unknown>
|
|
1016
923
|
>,
|
|
1017
924
|
ctx: { state: NonNullable<T> },
|
|
1018
|
-
) =>
|
|
925
|
+
) => unknown)
|
|
1019
926
|
| undefined;
|
|
1020
927
|
/** Observes the transport state: fires with the attach snapshot, then once per change. */
|
|
1021
928
|
onStateChange?:
|
package/src/localStorage.test.ts
CHANGED
|
@@ -186,7 +186,10 @@ describe("LocalStorageSession", () => {
|
|
|
186
186
|
callback?: () => Promise<unknown>,
|
|
187
187
|
) => {
|
|
188
188
|
const cb = typeof options === "function" ? options : callback!;
|
|
189
|
-
if (
|
|
189
|
+
if (
|
|
190
|
+
name.startsWith("aui:statewire-session-active:") ||
|
|
191
|
+
name.startsWith("statewire-tab:")
|
|
192
|
+
)
|
|
190
193
|
return Promise.resolve().then(() => cb());
|
|
191
194
|
requested.push(name);
|
|
192
195
|
const run = chain.then(() => cb());
|
|
@@ -218,6 +221,8 @@ describe("LocalStorageSession", () => {
|
|
|
218
221
|
nextSeq: 3,
|
|
219
222
|
commands: [
|
|
220
223
|
{
|
|
224
|
+
id: "cmd-2",
|
|
225
|
+
ts: 1,
|
|
221
226
|
seq: 2,
|
|
222
227
|
method: "run/steer",
|
|
223
228
|
params: [{ text: "hi" }],
|
|
@@ -230,7 +235,7 @@ describe("LocalStorageSession", () => {
|
|
|
230
235
|
root.getValue().save(record);
|
|
231
236
|
expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
|
|
232
237
|
...record,
|
|
233
|
-
statewireStorageVersion:
|
|
238
|
+
statewireStorageVersion: 5,
|
|
234
239
|
savedAt: expect.any(Number),
|
|
235
240
|
});
|
|
236
241
|
expect(root.getValue().load()).toEqual(record);
|
package/src/localStorage.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useEffect, useMemo, useRef } from "react";
|
|
1
|
+
import { useEffect, useMemo, useRef, useState } from "react";
|
|
2
2
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
3
3
|
import { KeyValueSessionStorage } from "statewire/storage";
|
|
4
4
|
import type { StatewireClient } from "statewire";
|
|
@@ -180,6 +180,10 @@ const SESSION_LOCK_PREFIX = "aui:statewire-session-lock:";
|
|
|
180
180
|
|
|
181
181
|
const SESSION_ACTIVE_PREFIX = "aui:statewire-session-active:";
|
|
182
182
|
|
|
183
|
+
const TAB_LOCK_PREFIX = "statewire-tab:";
|
|
184
|
+
|
|
185
|
+
const NOTIFY_LOCK_PREFIX = "statewire-notify:";
|
|
186
|
+
|
|
183
187
|
const sessionBackend: KeyValueSessionStorage.Backend = {
|
|
184
188
|
getItem: (key) => localStorage.getItem(key),
|
|
185
189
|
setItem: (key, value) => localStorage.setItem(key, value),
|
|
@@ -201,6 +205,13 @@ const sessionBackend: KeyValueSessionStorage.Backend = {
|
|
|
201
205
|
(lock) => (lock === null ? undefined : action()),
|
|
202
206
|
),
|
|
203
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
|
+
},
|
|
204
215
|
};
|
|
205
216
|
|
|
206
217
|
const useLocalStorageSession = ({
|
|
@@ -209,7 +220,9 @@ const useLocalStorageSession = ({
|
|
|
209
220
|
principal,
|
|
210
221
|
protocol,
|
|
211
222
|
retention,
|
|
223
|
+
limits,
|
|
212
224
|
onError,
|
|
225
|
+
onEvict,
|
|
213
226
|
}: LocalStorageSession.Options): StatewireClient.SessionStorage => {
|
|
214
227
|
if (typeof localStorage === "undefined")
|
|
215
228
|
throw new Error("statewire: LocalStorageSession requires localStorage");
|
|
@@ -222,6 +235,19 @@ const useLocalStorageSession = ({
|
|
|
222
235
|
usePrincipal(principal);
|
|
223
236
|
const storageKey = SESSION_PREFIX + scopeKey;
|
|
224
237
|
const lockName = SESSION_LOCK_PREFIX + scopeKey;
|
|
238
|
+
const [tabId] = useState(() => crypto.randomUUID());
|
|
239
|
+
const latestOnError = useRef(onError);
|
|
240
|
+
latestOnError.current = onError;
|
|
241
|
+
useEffect(() => {
|
|
242
|
+
let release: (() => void) | undefined;
|
|
243
|
+
const held = new Promise<void>((resolve) => {
|
|
244
|
+
release = resolve;
|
|
245
|
+
});
|
|
246
|
+
void navigator.locks
|
|
247
|
+
.request(TAB_LOCK_PREFIX + tabId, () => held)
|
|
248
|
+
.catch((error: unknown) => latestOnError.current?.(error));
|
|
249
|
+
return () => release?.();
|
|
250
|
+
}, [tabId]);
|
|
225
251
|
useEffect(() => {
|
|
226
252
|
let release: (() => void) | undefined;
|
|
227
253
|
let disposed = false;
|
|
@@ -246,13 +272,22 @@ const useLocalStorageSession = ({
|
|
|
246
272
|
...(migrate === undefined ? {} : { migrate }),
|
|
247
273
|
...(protocol === undefined ? {} : { protocol }),
|
|
248
274
|
...(retention === undefined ? {} : { retention }),
|
|
275
|
+
...(limits === undefined ? {} : { limits }),
|
|
249
276
|
...(onError === undefined ? {} : { onError }),
|
|
277
|
+
...(onEvict === undefined ? {} : { onEvict }),
|
|
250
278
|
}),
|
|
251
279
|
);
|
|
252
280
|
return useMemo(
|
|
253
281
|
(): StatewireClient.SessionStorage => ({
|
|
254
282
|
...storage,
|
|
255
283
|
lock: (fn) => navigator.locks.request(lockName, async () => fn()),
|
|
284
|
+
notifyLock: (fn) =>
|
|
285
|
+
navigator.locks.request(NOTIFY_LOCK_PREFIX + storageKey, fn),
|
|
286
|
+
owner: {
|
|
287
|
+
id: tabId,
|
|
288
|
+
whenGone: (id, signal) =>
|
|
289
|
+
navigator.locks.request(TAB_LOCK_PREFIX + id, { signal }, () => {}),
|
|
290
|
+
},
|
|
256
291
|
subscribe: (listener) => {
|
|
257
292
|
const onStorage = (event: StorageEvent) => {
|
|
258
293
|
if (event.key === storageKey) listener();
|
|
@@ -261,10 +296,17 @@ const useLocalStorageSession = ({
|
|
|
261
296
|
return () => window.removeEventListener("storage", onStorage);
|
|
262
297
|
},
|
|
263
298
|
}),
|
|
264
|
-
[storage, storageKey, lockName],
|
|
299
|
+
[storage, storageKey, lockName, tabId],
|
|
265
300
|
);
|
|
266
301
|
};
|
|
267
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
|
+
|
|
268
310
|
/** Session storage on localStorage, keyed per principal and thread; sharers serialize through a per-key Web Lock. */
|
|
269
311
|
export const LocalStorageSession = resource(useLocalStorageSession);
|
|
270
312
|
|
|
@@ -272,7 +314,9 @@ export namespace LocalStorageSession {
|
|
|
272
314
|
export type Options = {
|
|
273
315
|
protocol?: KeyValueSessionStorage.Options["protocol"];
|
|
274
316
|
retention?: KeyValueSessionStorage.Options["retention"];
|
|
317
|
+
limits?: KeyValueSessionStorage.Options["limits"];
|
|
275
318
|
onError?: KeyValueSessionStorage.Options["onError"];
|
|
319
|
+
onEvict?: KeyValueSessionStorage.Options["onEvict"];
|
|
276
320
|
/** Upgrade incompatible queued commands, or return null to discard the saved session. */
|
|
277
321
|
migrate?: StatewireClient.SessionStorage["migrate"];
|
|
278
322
|
/** The thread whose session this storage holds. */
|
package/src/runCommands.ts
CHANGED
|
@@ -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 };
|
|
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
|
package/src/runsOptimistic.ts
CHANGED
|
@@ -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,10 +145,27 @@ 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
|
-
const runId = commandRunId ?? `optimistic-${ctx.seq}`;
|
|
168
|
+
const runId = commandRunId ?? `optimistic-${ctx.seq ?? `q${ctx.ts}`}`;
|
|
151
169
|
switch (command.method) {
|
|
152
170
|
case "run/enqueue":
|
|
153
171
|
case "run/steer": {
|