@assistant-ui/react-statewire 0.27.1 → 0.28.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/StatewireThread.d.ts +2 -0
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +42 -8
- package/dist/StatewireThread.js.map +1 -1
- package/dist/localStorage.d.ts +4 -0
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +37 -28
- package/dist/localStorage.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.failed.test.tsx +28 -2
- package/src/StatewireThread.retract.test.tsx +175 -0
- package/src/StatewireThread.runs.test.tsx +39 -29
- package/src/StatewireThread.test.tsx +4 -6
- package/src/StatewireThread.ts +55 -8
- package/src/localStorage.test.ts +69 -13
- package/src/localStorage.ts +62 -96
|
@@ -80,6 +80,7 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
80
80
|
if (url.endsWith("/stream")) {
|
|
81
81
|
if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
82
82
|
const rec = clients.get(clientId)!;
|
|
83
|
+
rec.ctxSeq = 0;
|
|
83
84
|
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
84
85
|
const body = new ReadableStream<Uint8Array>({
|
|
85
86
|
start: (c) => {
|
|
@@ -97,7 +98,7 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
97
98
|
],
|
|
98
99
|
syn: {
|
|
99
100
|
seq: rec.seq,
|
|
100
|
-
ctxSeq:
|
|
101
|
+
ctxSeq: 0,
|
|
101
102
|
version: "2026-09-07",
|
|
102
103
|
protocols: [{ name: "default", version: "2026-09-07" }],
|
|
103
104
|
},
|
|
@@ -195,7 +196,7 @@ describe("StatewireThread failed lane", () => {
|
|
|
195
196
|
expect(runs().runId).toBeNull();
|
|
196
197
|
});
|
|
197
198
|
|
|
198
|
-
it("retry
|
|
199
|
+
it("repeated retry actions dispatch once and remove the entry", async () => {
|
|
199
200
|
const { server, aui, runs } = await mountFailed({
|
|
200
201
|
type: "run/enqueue",
|
|
201
202
|
runId: "run-1",
|
|
@@ -205,6 +206,7 @@ describe("StatewireThread failed lane", () => {
|
|
|
205
206
|
server.accept();
|
|
206
207
|
act(() => {
|
|
207
208
|
extras(aui).retryFailed("m1");
|
|
209
|
+
extras(aui).retryFailed("m1");
|
|
208
210
|
});
|
|
209
211
|
await waitFor(() => expect(runs().failed).toHaveLength(0));
|
|
210
212
|
const sends = server.received.filter((r) => r.method === "run/enqueue");
|
|
@@ -216,6 +218,30 @@ describe("StatewireThread failed lane", () => {
|
|
|
216
218
|
expect((sends[1]!.params[0] as { runId: string }).runId).not.toBe("run-1");
|
|
217
219
|
});
|
|
218
220
|
|
|
221
|
+
it("allows another retry after the previous retry is rejected", async () => {
|
|
222
|
+
const { server, aui, runs } = await mountFailed({
|
|
223
|
+
type: "run/enqueue",
|
|
224
|
+
runId: "run-1",
|
|
225
|
+
message: wireMessage("m1", "hello"),
|
|
226
|
+
runAnchorMessageId: null,
|
|
227
|
+
});
|
|
228
|
+
act(() => {
|
|
229
|
+
extras(aui).retryFailed("m1");
|
|
230
|
+
});
|
|
231
|
+
await waitFor(() => {
|
|
232
|
+
expect(server.received).toHaveLength(2);
|
|
233
|
+
expect(runs().failed).toHaveLength(1);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
server.accept();
|
|
237
|
+
act(() => {
|
|
238
|
+
extras(aui).retryFailed("m1");
|
|
239
|
+
extras(aui).retryFailed("m1");
|
|
240
|
+
});
|
|
241
|
+
await waitFor(() => expect(runs().failed).toHaveLength(0));
|
|
242
|
+
expect(server.received).toHaveLength(3);
|
|
243
|
+
});
|
|
244
|
+
|
|
219
245
|
it("a failed steer whose run is gone retries as a plain enqueue", async () => {
|
|
220
246
|
const { server, aui, runs } = await mountFailed({
|
|
221
247
|
type: "run/steer",
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
|
|
3
|
+
// Contract tests for the stopping client's pop: the run/stop verdict carries
|
|
4
|
+
// the run's retracted items, and the client that stopped dequeues them into
|
|
5
|
+
// an empty composer. A non-empty composer and rejected dequeues leave them
|
|
6
|
+
// queued.
|
|
7
|
+
|
|
8
|
+
import { act, render, waitFor } from "@testing-library/react";
|
|
9
|
+
import type { FC } from "react";
|
|
10
|
+
import { describe, expect, it } from "vitest";
|
|
11
|
+
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
12
|
+
import { resource } from "@assistant-ui/tap";
|
|
13
|
+
import {
|
|
14
|
+
StatewireReject,
|
|
15
|
+
useStatewireCommands,
|
|
16
|
+
useStatewireState,
|
|
17
|
+
} from "statewire/host";
|
|
18
|
+
import { asStatewireExtras, StatewireThread } from "./StatewireThread";
|
|
19
|
+
import { toThreadMessage } from "./__tests__/testHelpers";
|
|
20
|
+
|
|
21
|
+
type QueueItem = {
|
|
22
|
+
id: string;
|
|
23
|
+
role: "user";
|
|
24
|
+
parts: { type: "text"; text: string }[];
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
type ServerState = {
|
|
28
|
+
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
29
|
+
status: "ready" | StatewireThread.RunStatus;
|
|
30
|
+
runs: {
|
|
31
|
+
runId: string | null;
|
|
32
|
+
status: StatewireThread.RunStatus;
|
|
33
|
+
queue: QueueItem[];
|
|
34
|
+
steerQueue: QueueItem[];
|
|
35
|
+
}[];
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const item = (id: string, text: string): QueueItem => ({
|
|
39
|
+
id,
|
|
40
|
+
role: "user",
|
|
41
|
+
parts: [{ type: "text", text }],
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const converter: StatewireThread.StateConverter<ServerState> = (state) => ({
|
|
45
|
+
messages: state.messages.map(toThreadMessage),
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
// A host whose run/stop retracts the given items into the lanes and answers
|
|
49
|
+
// with them; run/dequeue removes an item unless `rejectDequeue` names it.
|
|
50
|
+
const createServer = (opts: {
|
|
51
|
+
retract: { queue?: QueueItem[]; steer?: QueueItem[] };
|
|
52
|
+
rejectDequeue?: string;
|
|
53
|
+
}) => {
|
|
54
|
+
const received: { method: string; params: unknown }[] = [];
|
|
55
|
+
const transport = resource(() => {
|
|
56
|
+
const [state] = useStatewireState<ServerState>(() => ({
|
|
57
|
+
messages: [{ id: "m1", role: "user", text: "hello" }],
|
|
58
|
+
status: "running",
|
|
59
|
+
runs: [{ runId: "run-1", status: "running", queue: [], steerQueue: [] }],
|
|
60
|
+
}));
|
|
61
|
+
const commands = useStatewireCommands({
|
|
62
|
+
"run/stop": (params: unknown) => {
|
|
63
|
+
received.push({ method: "run/stop", params });
|
|
64
|
+
const entry = state.runs[0]!;
|
|
65
|
+
entry.queue = opts.retract.queue ?? [];
|
|
66
|
+
entry.steerQueue = opts.retract.steer ?? [];
|
|
67
|
+
entry.status = "stopped";
|
|
68
|
+
state.status = "stopped";
|
|
69
|
+
state.messages = [];
|
|
70
|
+
return [...entry.queue, ...entry.steerQueue];
|
|
71
|
+
},
|
|
72
|
+
"run/dequeue": (params: { messageId: string }) => {
|
|
73
|
+
received.push({ method: "run/dequeue", params });
|
|
74
|
+
if (params.messageId === opts.rejectDequeue)
|
|
75
|
+
throw new StatewireReject("not yours", {
|
|
76
|
+
payload: { reason: "not-owner" },
|
|
77
|
+
});
|
|
78
|
+
const entry = state.runs[0]!;
|
|
79
|
+
entry.queue = entry.queue.filter((q) => q.id !== params.messageId);
|
|
80
|
+
entry.steerQueue = entry.steerQueue.filter(
|
|
81
|
+
(q) => q.id !== params.messageId,
|
|
82
|
+
);
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
return { state, commands };
|
|
86
|
+
})();
|
|
87
|
+
return { transport, received };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const mountThread = (
|
|
91
|
+
transport: ReturnType<typeof createServer>["transport"],
|
|
92
|
+
) => {
|
|
93
|
+
const captured: { aui?: ReturnType<typeof useAui> } = {};
|
|
94
|
+
const Capture: FC = () => {
|
|
95
|
+
captured.aui = useAui();
|
|
96
|
+
return null;
|
|
97
|
+
};
|
|
98
|
+
const App: FC = () => {
|
|
99
|
+
const aui = useAui({
|
|
100
|
+
thread: StatewireThread<ServerState>({
|
|
101
|
+
initialState: { messages: [], status: "ready", runs: [] },
|
|
102
|
+
converter,
|
|
103
|
+
transport,
|
|
104
|
+
}),
|
|
105
|
+
});
|
|
106
|
+
return (
|
|
107
|
+
<AuiProvider value={aui}>
|
|
108
|
+
<Capture />
|
|
109
|
+
</AuiProvider>
|
|
110
|
+
);
|
|
111
|
+
};
|
|
112
|
+
render(<App />);
|
|
113
|
+
return () => captured.aui!;
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const composerText = (aui: () => ReturnType<typeof useAui>) =>
|
|
117
|
+
aui().thread().composer().getState().text;
|
|
118
|
+
|
|
119
|
+
const dequeued = (received: { method: string; params: unknown }[]) =>
|
|
120
|
+
received
|
|
121
|
+
.filter((r) => r.method === "run/dequeue")
|
|
122
|
+
.map((r) => (r.params as { messageId: string }).messageId);
|
|
123
|
+
|
|
124
|
+
describe("StatewireThread retraction pop", () => {
|
|
125
|
+
it("dequeues the retracted items into the empty composer in thread order", async () => {
|
|
126
|
+
const server = createServer({
|
|
127
|
+
retract: {
|
|
128
|
+
queue: [item("m1", "hello")],
|
|
129
|
+
steer: [item("s1", "and this")],
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
const aui = mountThread(server.transport);
|
|
133
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
134
|
+
act(() => {
|
|
135
|
+
aui().thread().cancelRun();
|
|
136
|
+
});
|
|
137
|
+
await waitFor(() => expect(composerText(aui)).toBe("hello\n\nand this"));
|
|
138
|
+
expect(dequeued(server.received)).toEqual(["m1", "s1"]);
|
|
139
|
+
await waitFor(() => {
|
|
140
|
+
const runs = asStatewireExtras(aui().thread().getState().extras).runs;
|
|
141
|
+
expect([...runs.queue, ...runs.steerQueue]).toHaveLength(0);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
it("leaves the items queued while the composer holds text", async () => {
|
|
146
|
+
const server = createServer({ retract: { queue: [item("m1", "hello")] } });
|
|
147
|
+
const aui = mountThread(server.transport);
|
|
148
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
149
|
+
act(() => {
|
|
150
|
+
aui().thread().composer().setText("draft");
|
|
151
|
+
aui().thread().cancelRun();
|
|
152
|
+
});
|
|
153
|
+
await waitFor(() =>
|
|
154
|
+
expect(aui().thread().getState().isRunning).toBe(false),
|
|
155
|
+
);
|
|
156
|
+
await waitFor(() =>
|
|
157
|
+
expect(server.received.map((r) => r.method)).toEqual(["run/stop"]),
|
|
158
|
+
);
|
|
159
|
+
expect(composerText(aui)).toBe("draft");
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it("keeps an item whose dequeue rejects and pops the rest", async () => {
|
|
163
|
+
const server = createServer({
|
|
164
|
+
retract: { queue: [item("m1", "mine")], steer: [item("s1", "theirs")] },
|
|
165
|
+
rejectDequeue: "s1",
|
|
166
|
+
});
|
|
167
|
+
const aui = mountThread(server.transport);
|
|
168
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
169
|
+
act(() => {
|
|
170
|
+
aui().thread().cancelRun();
|
|
171
|
+
});
|
|
172
|
+
await waitFor(() => expect(composerText(aui)).toBe("mine"));
|
|
173
|
+
expect(dequeued(server.received)).toEqual(["m1", "s1"]);
|
|
174
|
+
});
|
|
175
|
+
});
|
|
@@ -125,8 +125,9 @@ const createServer = (init?: Partial<RunsServerState>) => {
|
|
|
125
125
|
// snapshot until `release()` to expose the pre-attach window.
|
|
126
126
|
const createRemoteServer = (
|
|
127
127
|
init?: Partial<RunsServerState>,
|
|
128
|
-
opts?: { hold?: boolean },
|
|
128
|
+
opts?: { hold?: boolean; protocol?: string },
|
|
129
129
|
) => {
|
|
130
|
+
const protocol = opts?.protocol ?? "default";
|
|
130
131
|
const received: { method: string; params: unknown[] }[] = [];
|
|
131
132
|
const clients = new Map<string, { seq: number; ctxSeq: number }>();
|
|
132
133
|
const encoder = new TextEncoder();
|
|
@@ -171,6 +172,7 @@ const createRemoteServer = (
|
|
|
171
172
|
if (url.endsWith("/stream")) {
|
|
172
173
|
if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
173
174
|
const rec = clients.get(clientId)!;
|
|
175
|
+
rec.ctxSeq = 0;
|
|
174
176
|
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
175
177
|
const body = new ReadableStream<Uint8Array>({
|
|
176
178
|
start: (c) => {
|
|
@@ -184,16 +186,16 @@ const createRemoteServer = (
|
|
|
184
186
|
ops: [
|
|
185
187
|
{
|
|
186
188
|
op: "mount",
|
|
187
|
-
protocol
|
|
189
|
+
protocol,
|
|
188
190
|
main: true,
|
|
189
191
|
value: { ...INITIAL_STATE, ...init },
|
|
190
192
|
},
|
|
191
193
|
],
|
|
192
194
|
syn: {
|
|
193
195
|
seq: rec.seq,
|
|
194
|
-
ctxSeq:
|
|
196
|
+
ctxSeq: 0,
|
|
195
197
|
version: "2026-09-07",
|
|
196
|
-
protocols: [{ name:
|
|
198
|
+
protocols: [{ name: protocol, version: "2026-09-07" }],
|
|
197
199
|
},
|
|
198
200
|
}),
|
|
199
201
|
),
|
|
@@ -222,6 +224,7 @@ const createRemoteServer = (
|
|
|
222
224
|
transport: StatewireHttp<RunsServerState>({
|
|
223
225
|
url: "http://fake/api",
|
|
224
226
|
fetch: fetchImpl,
|
|
227
|
+
protocol,
|
|
225
228
|
}),
|
|
226
229
|
};
|
|
227
230
|
};
|
|
@@ -718,34 +721,41 @@ describe("StatewireThread runs mode", () => {
|
|
|
718
721
|
expect(aui().thread().getState().isRunning).toBe(true);
|
|
719
722
|
});
|
|
720
723
|
|
|
721
|
-
it(
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
724
|
+
it.each([undefined, "athena"])(
|
|
725
|
+
"preloads initialState: interactive before attach, sends fold in (protocol: %s)",
|
|
726
|
+
async (protocol) => {
|
|
727
|
+
const server = createRemoteServer(
|
|
728
|
+
{},
|
|
729
|
+
{ hold: true, ...(protocol !== undefined && { protocol }) },
|
|
730
|
+
);
|
|
731
|
+
const { aui, runs } = mountThread({
|
|
732
|
+
transport: server.transport,
|
|
733
|
+
materialize: rollbackMaterialize,
|
|
734
|
+
protocol,
|
|
735
|
+
});
|
|
727
736
|
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
737
|
+
expect(threadStatus(aui())).toBe("ready");
|
|
738
|
+
act(() => {
|
|
739
|
+
aui().thread().append("hello");
|
|
740
|
+
});
|
|
732
741
|
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
742
|
+
// The pre-attach send renders through the same optimistic + materialize
|
|
743
|
+
// folds; while connecting, the run presents as disconnected.
|
|
744
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
745
|
+
expect(runs().runId).toEqual(expect.any(String));
|
|
746
|
+
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
747
|
+
expect(server.received).toEqual([]);
|
|
739
748
|
|
|
740
|
-
|
|
749
|
+
server.release();
|
|
741
750
|
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
751
|
+
// Attach posts the queued command; the still-unapplied overlay survives the snapshot.
|
|
752
|
+
await waitFor(() =>
|
|
753
|
+
expect(server.received.map((c) => c.method)).toEqual(["run/enqueue"]),
|
|
754
|
+
);
|
|
755
|
+
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
756
|
+
expect(threadStatus(aui())).toBe("running");
|
|
757
|
+
},
|
|
758
|
+
);
|
|
749
759
|
|
|
750
760
|
it("preloads again after a transport swap on a persistent thread", async () => {
|
|
751
761
|
const serverA = createRemoteServer({
|
|
@@ -936,7 +946,7 @@ describe("StatewireThread connection presentation", () => {
|
|
|
936
946
|
await waitFor(() => expect(threadStatus(aui())).toBe(status));
|
|
937
947
|
server.fin("error");
|
|
938
948
|
|
|
939
|
-
await waitFor(() => expect(statuses).toContain("
|
|
949
|
+
await waitFor(() => expect(statuses).toContain("retrying"));
|
|
940
950
|
expect(threadStatus(aui())).toBe(status);
|
|
941
951
|
},
|
|
942
952
|
);
|
|
@@ -595,11 +595,9 @@ describe("StatewireThread", () => {
|
|
|
595
595
|
|
|
596
596
|
await waitFor(() => expect(statuses).toEqual(["connected"]));
|
|
597
597
|
await mock.finish("gone");
|
|
598
|
-
await waitFor(() =>
|
|
599
|
-
expect(statuses).toEqual(["connected", "disconnected"]),
|
|
600
|
-
);
|
|
598
|
+
await waitFor(() => expect(statuses).toEqual(["connected", "stopped"]));
|
|
601
599
|
await new Promise((r) => setTimeout(r, 20));
|
|
602
|
-
expect(statuses).toEqual(["connected", "
|
|
600
|
+
expect(statuses).toEqual(["connected", "stopped"]);
|
|
603
601
|
});
|
|
604
602
|
|
|
605
603
|
it("stays quiet on unrelated re-renders and callback identity changes", async () => {
|
|
@@ -1327,7 +1325,7 @@ describe("StatewireThread", () => {
|
|
|
1327
1325
|
expect(seen).toEqual(["connecting", "connected"]);
|
|
1328
1326
|
|
|
1329
1327
|
await mock.finish("gone", "taken over");
|
|
1330
|
-
await waitFor(() => expect(seen.at(-1)).toBe("
|
|
1328
|
+
await waitFor(() => expect(seen.at(-1)).toBe("stopped"));
|
|
1331
1329
|
});
|
|
1332
1330
|
|
|
1333
1331
|
it("reports connected without re-converting on a local transport", async () => {
|
|
@@ -1351,7 +1349,7 @@ describe("StatewireThread", () => {
|
|
|
1351
1349
|
|
|
1352
1350
|
await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
|
|
1353
1351
|
await mock.finish("gone");
|
|
1354
|
-
await waitFor(() => expect(seen.at(-1)).toBe("
|
|
1352
|
+
await waitFor(() => expect(seen.at(-1)).toBe("stopped"));
|
|
1355
1353
|
|
|
1356
1354
|
asStatewireExtras(aui().thread().getState().extras).reconnect();
|
|
1357
1355
|
|
package/src/StatewireThread.ts
CHANGED
|
@@ -101,9 +101,9 @@ const presentStatus = (
|
|
|
101
101
|
): StatewireThread.ThreadStatus =>
|
|
102
102
|
status !== "running" ||
|
|
103
103
|
connection.status === "connected" ||
|
|
104
|
-
(connection.status === "
|
|
104
|
+
(connection.status === "standby" && connection.reason === "idle")
|
|
105
105
|
? status
|
|
106
|
-
: connection.status === "
|
|
106
|
+
: connection.status === "retrying" &&
|
|
107
107
|
connection.cause === "reconnect" &&
|
|
108
108
|
connection.code === "evicted"
|
|
109
109
|
? "evicted"
|
|
@@ -125,6 +125,7 @@ const useStatewireThread = (
|
|
|
125
125
|
): ClientOutput<"thread"> => {
|
|
126
126
|
const latest = useRef(options);
|
|
127
127
|
latest.current = options;
|
|
128
|
+
const retrying = useRef(new Set<string>());
|
|
128
129
|
|
|
129
130
|
const [pending, setPending] = useState<readonly StatewireThread.Command[]>(
|
|
130
131
|
[],
|
|
@@ -151,6 +152,7 @@ const useStatewireThread = (
|
|
|
151
152
|
onError: (error) => latest.current.onError?.(error),
|
|
152
153
|
storage: options.storage,
|
|
153
154
|
initialState: options.initialState,
|
|
155
|
+
...(options.protocol !== undefined && { protocol: options.protocol }),
|
|
154
156
|
optimistic: (draft, command, ctx) => {
|
|
155
157
|
runsOptimistic(draft, command, ctx);
|
|
156
158
|
latest.current.optimistic?.(draft, command, ctx);
|
|
@@ -243,6 +245,36 @@ const useStatewireThread = (
|
|
|
243
245
|
[dispatch],
|
|
244
246
|
);
|
|
245
247
|
|
|
248
|
+
// The stop verdict carries the run's retracted items; the stopping client
|
|
249
|
+
// dequeues them into an empty composer. Other clients see them queued.
|
|
250
|
+
const popRetracted = async (
|
|
251
|
+
retracted: unknown,
|
|
252
|
+
runId: string | null,
|
|
253
|
+
): Promise<void> => {
|
|
254
|
+
if (!Array.isArray(retracted) || retracted.length === 0 || runId === null)
|
|
255
|
+
return;
|
|
256
|
+
const composerApi = threadRef.current!.composer();
|
|
257
|
+
if (composerApi.getState().text !== "") return;
|
|
258
|
+
const texts: string[] = [];
|
|
259
|
+
for (const item of retracted as StatewireThread.RunsQueueEntry[]) {
|
|
260
|
+
try {
|
|
261
|
+
await dispatch({ type: "run/dequeue", runId, messageId: item.id });
|
|
262
|
+
} catch {
|
|
263
|
+
continue; // rejected dequeue: the item stays queued
|
|
264
|
+
}
|
|
265
|
+
texts.push(
|
|
266
|
+
item.parts
|
|
267
|
+
.flatMap((part) => (part.type === "text" ? [part.text] : []))
|
|
268
|
+
.join("\n\n"),
|
|
269
|
+
);
|
|
270
|
+
}
|
|
271
|
+
if (texts.length === 0) return;
|
|
272
|
+
const setText = composerApi.setText as (
|
|
273
|
+
next: string | ((prev: string) => string),
|
|
274
|
+
) => void;
|
|
275
|
+
setText((prev) => [prev, ...texts].filter(Boolean).join("\n\n"));
|
|
276
|
+
};
|
|
277
|
+
|
|
246
278
|
const { status, runs } = useMemo((): {
|
|
247
279
|
status: StatewireThread.ThreadStatus;
|
|
248
280
|
runs: StatewireThread.Runs;
|
|
@@ -352,14 +384,24 @@ const useStatewireThread = (
|
|
|
352
384
|
inputRequests,
|
|
353
385
|
runs,
|
|
354
386
|
retryFailed: (messageId) => {
|
|
387
|
+
if (retrying.current.has(messageId)) return;
|
|
355
388
|
const entry = takeFailed(messageId);
|
|
356
389
|
const command = retryCommand(
|
|
357
390
|
messages,
|
|
358
391
|
liveRunId,
|
|
359
392
|
failedRunCommand(entry)!,
|
|
360
393
|
);
|
|
361
|
-
|
|
362
|
-
|
|
394
|
+
retrying.current.add(messageId);
|
|
395
|
+
const release = () => {
|
|
396
|
+
retrying.current.delete(messageId);
|
|
397
|
+
};
|
|
398
|
+
try {
|
|
399
|
+
discardFailed(entry);
|
|
400
|
+
void dispatch(command).then(release, release);
|
|
401
|
+
} catch (error) {
|
|
402
|
+
release();
|
|
403
|
+
throw error;
|
|
404
|
+
}
|
|
363
405
|
},
|
|
364
406
|
discardFailed: (messageId) => discardFailed(takeFailed(messageId)),
|
|
365
407
|
popFailed: (messageId) => {
|
|
@@ -442,13 +484,16 @@ const useStatewireThread = (
|
|
|
442
484
|
Array.isArray(payload))
|
|
443
485
|
)
|
|
444
486
|
throw new Error("statewire: stopPayload must return a plain object");
|
|
487
|
+
const runId = runs.runId;
|
|
445
488
|
void commands["run/stop"]!({
|
|
446
489
|
...payload,
|
|
447
|
-
runId
|
|
490
|
+
runId,
|
|
448
491
|
...(runs.epoch !== undefined && { epoch: runs.epoch }),
|
|
449
|
-
})
|
|
450
|
-
|
|
451
|
-
|
|
492
|
+
})
|
|
493
|
+
.then((retracted) => popRetracted(retracted, runId))
|
|
494
|
+
.catch((error: Error) => {
|
|
495
|
+
latest.current.onError?.(error);
|
|
496
|
+
});
|
|
452
497
|
},
|
|
453
498
|
}),
|
|
454
499
|
);
|
|
@@ -846,6 +891,8 @@ export namespace StatewireThread {
|
|
|
846
891
|
transport: Transport<T>;
|
|
847
892
|
/** The pre-attach state, replaced by the attach snapshot. `runs: []` projects ready (interactive from the first render); an absent runs mount projects loading until attach. */
|
|
848
893
|
initialState: T;
|
|
894
|
+
/** Application protocol for optimistic commands; must match the transport's protocol. */
|
|
895
|
+
protocol?: string | undefined;
|
|
849
896
|
converter: StateConverter<T>;
|
|
850
897
|
/** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
|
|
851
898
|
optimistic?:
|
package/src/localStorage.test.ts
CHANGED
|
@@ -141,7 +141,14 @@ describe("LocalStorageSession", () => {
|
|
|
141
141
|
Object.defineProperty(navigator, "locks", {
|
|
142
142
|
configurable: true,
|
|
143
143
|
value: {
|
|
144
|
-
request: (
|
|
144
|
+
request: (
|
|
145
|
+
name: string,
|
|
146
|
+
options: (() => Promise<unknown>) | object,
|
|
147
|
+
callback?: () => Promise<unknown>,
|
|
148
|
+
) => {
|
|
149
|
+
const cb = typeof options === "function" ? options : callback!;
|
|
150
|
+
if (name.startsWith("aui:statewire-session-active:"))
|
|
151
|
+
return Promise.resolve().then(() => cb());
|
|
145
152
|
requested.push(name);
|
|
146
153
|
const run = chain.then(() => cb());
|
|
147
154
|
chain = run.then(
|
|
@@ -168,7 +175,6 @@ describe("LocalStorageSession", () => {
|
|
|
168
175
|
const record = {
|
|
169
176
|
clientId: "c-1",
|
|
170
177
|
nextSeq: 3,
|
|
171
|
-
ctxNextSeq: 1,
|
|
172
178
|
commands: [
|
|
173
179
|
{
|
|
174
180
|
seq: 2,
|
|
@@ -180,40 +186,38 @@ describe("LocalStorageSession", () => {
|
|
|
180
186
|
],
|
|
181
187
|
};
|
|
182
188
|
root.getValue().save(record);
|
|
183
|
-
expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual(
|
|
184
|
-
record,
|
|
185
|
-
|
|
189
|
+
expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
|
|
190
|
+
...record,
|
|
191
|
+
statewireStorageVersion: 2,
|
|
192
|
+
savedAt: expect.any(Number),
|
|
193
|
+
});
|
|
186
194
|
expect(root.getValue().load()).toEqual(record);
|
|
187
195
|
root.unmount();
|
|
188
196
|
});
|
|
189
197
|
|
|
190
|
-
it("
|
|
198
|
+
it("rejects malformed session records without deleting them", () => {
|
|
191
199
|
const root = mountSession({ threadId: "t1" });
|
|
192
200
|
for (const raw of [
|
|
193
201
|
"{",
|
|
194
202
|
JSON.stringify({
|
|
195
203
|
clientId: "c-1",
|
|
196
204
|
nextSeq: 1,
|
|
197
|
-
ctxNextSeq: 1,
|
|
198
205
|
commands: "invalid",
|
|
199
206
|
}),
|
|
200
207
|
JSON.stringify({
|
|
201
208
|
clientId: "c-1",
|
|
202
209
|
nextSeq: 2,
|
|
203
|
-
ctxNextSeq: 1,
|
|
204
210
|
commands: [{ seq: 1, method: "run", params: null, meta: {} }],
|
|
205
211
|
}),
|
|
206
212
|
JSON.stringify({
|
|
207
213
|
clientId: "c-1",
|
|
208
214
|
nextSeq: 1,
|
|
209
|
-
ctxNextSeq: 1,
|
|
210
215
|
commands: [],
|
|
211
216
|
verdicts: [{ seq: 1, type: "future" }],
|
|
212
217
|
}),
|
|
213
218
|
JSON.stringify({
|
|
214
219
|
clientId: "c-1",
|
|
215
220
|
nextSeq: 1,
|
|
216
|
-
ctxNextSeq: 1,
|
|
217
221
|
commands: [],
|
|
218
222
|
failed: [
|
|
219
223
|
{
|
|
@@ -227,8 +231,8 @@ describe("LocalStorageSession", () => {
|
|
|
227
231
|
}),
|
|
228
232
|
]) {
|
|
229
233
|
localStorage.setItem(`${SESSION_PREFIX}t1`, raw);
|
|
230
|
-
expect(root.getValue().load()).
|
|
231
|
-
expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).
|
|
234
|
+
expect(() => root.getValue().load()).toThrow();
|
|
235
|
+
expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).toBe(raw);
|
|
232
236
|
}
|
|
233
237
|
root.unmount();
|
|
234
238
|
});
|
|
@@ -238,7 +242,6 @@ describe("LocalStorageSession", () => {
|
|
|
238
242
|
root.getValue().save({
|
|
239
243
|
clientId: "c-1",
|
|
240
244
|
nextSeq: 1,
|
|
241
|
-
ctxNextSeq: 1,
|
|
242
245
|
commands: [],
|
|
243
246
|
});
|
|
244
247
|
expect(localStorage.getItem(`${SESSION_PREFIX}user-42:t1`)).not.toBeNull();
|
|
@@ -289,6 +292,59 @@ describe("LocalStorageSession", () => {
|
|
|
289
292
|
root.unmount();
|
|
290
293
|
});
|
|
291
294
|
|
|
295
|
+
it("skips other tabs' active sessions and busy record locks during retention", async () => {
|
|
296
|
+
const prefix = "aui:statewire-session-active:";
|
|
297
|
+
const keys = ["other-active", "other-writing", "unused"];
|
|
298
|
+
for (const key of keys)
|
|
299
|
+
localStorage.setItem(
|
|
300
|
+
`${SESSION_PREFIX}${key}`,
|
|
301
|
+
JSON.stringify({
|
|
302
|
+
clientId: key,
|
|
303
|
+
nextSeq: 1,
|
|
304
|
+
commands: [],
|
|
305
|
+
savedAt: 1,
|
|
306
|
+
}),
|
|
307
|
+
);
|
|
308
|
+
const calls: { name: string; options: LockOptions | undefined }[] = [];
|
|
309
|
+
const request = (
|
|
310
|
+
name: string,
|
|
311
|
+
options: LockOptions | LockGrantedCallback<unknown>,
|
|
312
|
+
callback?: LockGrantedCallback<unknown>,
|
|
313
|
+
) => {
|
|
314
|
+
const args = typeof options === "function" ? undefined : options;
|
|
315
|
+
const fn = typeof options === "function" ? options : callback!;
|
|
316
|
+
calls.push({ name, options: args });
|
|
317
|
+
const unavailable =
|
|
318
|
+
name === `${prefix}${SESSION_PREFIX}other-active` ||
|
|
319
|
+
name === `${SESSION_LOCK_PREFIX}other-writing`;
|
|
320
|
+
return Promise.resolve().then(() =>
|
|
321
|
+
fn(unavailable ? null : ({} as Lock)),
|
|
322
|
+
);
|
|
323
|
+
};
|
|
324
|
+
Object.defineProperty(navigator, "locks", {
|
|
325
|
+
configurable: true,
|
|
326
|
+
value: { request },
|
|
327
|
+
});
|
|
328
|
+
const root = mountSession({
|
|
329
|
+
threadId: "current",
|
|
330
|
+
retention: { maxAgeMs: 1 },
|
|
331
|
+
});
|
|
332
|
+
await vi.waitFor(() =>
|
|
333
|
+
expect(localStorage.getItem(`${SESSION_PREFIX}unused`)).toBeNull(),
|
|
334
|
+
);
|
|
335
|
+
expect(
|
|
336
|
+
localStorage.getItem(`${SESSION_PREFIX}other-active`),
|
|
337
|
+
).not.toBeNull();
|
|
338
|
+
expect(
|
|
339
|
+
localStorage.getItem(`${SESSION_PREFIX}other-writing`),
|
|
340
|
+
).not.toBeNull();
|
|
341
|
+
expect(
|
|
342
|
+
calls.find(({ name }) => name === `${SESSION_LOCK_PREFIX}other-writing`)
|
|
343
|
+
?.options,
|
|
344
|
+
).toEqual({ ifAvailable: true });
|
|
345
|
+
root.unmount();
|
|
346
|
+
});
|
|
347
|
+
|
|
292
348
|
it("throws without localStorage", () => {
|
|
293
349
|
vi.stubGlobal("localStorage", undefined);
|
|
294
350
|
expect(() => mountSession({ threadId: "t1" })).toThrow(
|