@assistant-ui/react-statewire 0.28.0 → 0.29.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/dist/StatewireThread.d.ts +6 -0
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +55 -12
- package/dist/StatewireThread.js.map +1 -1
- package/dist/localStorage.d.ts +1 -1
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +2 -2
- package/dist/localStorage.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.failed.test.tsx +36 -13
- package/src/StatewireThread.retract.test.tsx +175 -0
- package/src/StatewireThread.runs.test.tsx +41 -36
- package/src/StatewireThread.test.tsx +20 -5
- package/src/StatewireThread.ts +99 -45
- package/src/localStorage.test.ts +14 -22
- package/src/localStorage.ts +3 -3
package/src/StatewireThread.ts
CHANGED
|
@@ -27,7 +27,7 @@ import type {
|
|
|
27
27
|
} from "@assistant-ui/core";
|
|
28
28
|
import { toToolsJSONSchema } from "assistant-stream";
|
|
29
29
|
import type { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
30
|
-
import { useStatewire } from "statewire";
|
|
30
|
+
import { DEFAULT_PROTOCOL, useStatewire } from "statewire";
|
|
31
31
|
import type { Statewire, StatewireClient } from "statewire";
|
|
32
32
|
import {
|
|
33
33
|
createBranchCommandAdapter,
|
|
@@ -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
|
[],
|
|
@@ -138,40 +139,34 @@ const useStatewireThread = (
|
|
|
138
139
|
),
|
|
139
140
|
);
|
|
140
141
|
|
|
141
|
-
const {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
if (command === undefined) return false;
|
|
170
|
-
const messages = (state as { messages?: readonly { id: string }[] })
|
|
171
|
-
.messages;
|
|
172
|
-
return messages?.some((m) => m.id === command.message.id) ?? false;
|
|
173
|
-
},
|
|
174
|
-
});
|
|
142
|
+
const { state, commands, connection, invoke, isBusy, failed, discardFailed } =
|
|
143
|
+
useStatewire<unknown, AnyCommands>({
|
|
144
|
+
transport: options.transport,
|
|
145
|
+
onError: (error) => latest.current.onError?.(error),
|
|
146
|
+
storage: options.storage,
|
|
147
|
+
initialState: options.initialState,
|
|
148
|
+
...(options.protocol !== undefined && { protocol: options.protocol }),
|
|
149
|
+
optimistic: (draft, command, ctx) => {
|
|
150
|
+
runsOptimistic(draft, command, ctx);
|
|
151
|
+
latest.current.optimistic?.(draft, command, ctx);
|
|
152
|
+
},
|
|
153
|
+
materialize: (draft: {}) => latest.current.materialize?.(draft),
|
|
154
|
+
onCommandChange: (update, ctx) => {
|
|
155
|
+
if (update.status === "applied" || update.status === "settled")
|
|
156
|
+
retire(update.params[0]);
|
|
157
|
+
latest.current.onCommandChange?.(update, ctx);
|
|
158
|
+
},
|
|
159
|
+
onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
|
|
160
|
+
onConnectionChange: (connection) =>
|
|
161
|
+
latest.current.onConnectionChange?.(connection),
|
|
162
|
+
failureCovered: (state, entry) => {
|
|
163
|
+
const command = failedRunCommand(entry);
|
|
164
|
+
if (command === undefined) return false;
|
|
165
|
+
const messages = (state as { messages?: readonly { id: string }[] })
|
|
166
|
+
.messages;
|
|
167
|
+
return messages?.some((m) => m.id === command.message.id) ?? false;
|
|
168
|
+
},
|
|
169
|
+
});
|
|
175
170
|
|
|
176
171
|
const discarded = useRef(new WeakSet<StatewireClient.FailedCommand>());
|
|
177
172
|
// Effects can replay before the updated failed lane reaches the binding.
|
|
@@ -188,19 +183,26 @@ const useStatewireThread = (
|
|
|
188
183
|
}, [failed, discardFailed]);
|
|
189
184
|
|
|
190
185
|
const clientRef = useAssistantClientRef();
|
|
191
|
-
const
|
|
192
|
-
|
|
186
|
+
const invokeRef = useRef(invoke);
|
|
187
|
+
invokeRef.current = invoke;
|
|
193
188
|
const [syncState] = useState(() => ({ lastSent: undefined as unknown }));
|
|
194
189
|
const { contextSync } = options;
|
|
190
|
+
const contextProtocol = `${options.protocol ?? DEFAULT_PROTOCOL}/context`;
|
|
191
|
+
// The context document dies with its attach: resend on every connect.
|
|
192
|
+
const connected = connection.status === "connected";
|
|
195
193
|
useEffect(() => {
|
|
196
194
|
if (contextSync === undefined) return;
|
|
195
|
+
if (!connected) {
|
|
196
|
+
syncState.lastSent = undefined;
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
197
199
|
const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
|
|
198
200
|
const send = () => {
|
|
199
201
|
const value = ambientContextOf(modelContext.getModelContext());
|
|
200
202
|
const key = JSON.stringify(value);
|
|
201
203
|
if (key === syncState.lastSent) return;
|
|
202
204
|
syncState.lastSent = key;
|
|
203
|
-
|
|
205
|
+
void invokeRef.current(contextProtocol, "set", [value]);
|
|
204
206
|
};
|
|
205
207
|
send();
|
|
206
208
|
if (!modelContext.subscribe) {
|
|
@@ -209,7 +211,7 @@ const useStatewireThread = (
|
|
|
209
211
|
);
|
|
210
212
|
}
|
|
211
213
|
return modelContext.subscribe(send);
|
|
212
|
-
}, [contextSync, clientRef, syncState]);
|
|
214
|
+
}, [contextSync, connected, contextProtocol, clientRef, syncState]);
|
|
213
215
|
|
|
214
216
|
const dispatch = useCallback(
|
|
215
217
|
(command: StatewireThread.Command) => {
|
|
@@ -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;
|
|
@@ -273,6 +305,9 @@ const useStatewireThread = (
|
|
|
273
305
|
: {
|
|
274
306
|
runId: entry.runId,
|
|
275
307
|
...(entry.epoch !== undefined && { epoch: entry.epoch }),
|
|
308
|
+
...(entry.stopReason !== undefined && {
|
|
309
|
+
stopReason: entry.stopReason,
|
|
310
|
+
}),
|
|
276
311
|
queue: entry.queue,
|
|
277
312
|
steerQueue: entry.steerQueue,
|
|
278
313
|
...(entry.dispatching !== undefined && {
|
|
@@ -352,14 +387,24 @@ const useStatewireThread = (
|
|
|
352
387
|
inputRequests,
|
|
353
388
|
runs,
|
|
354
389
|
retryFailed: (messageId) => {
|
|
390
|
+
if (retrying.current.has(messageId)) return;
|
|
355
391
|
const entry = takeFailed(messageId);
|
|
356
392
|
const command = retryCommand(
|
|
357
393
|
messages,
|
|
358
394
|
liveRunId,
|
|
359
395
|
failedRunCommand(entry)!,
|
|
360
396
|
);
|
|
361
|
-
|
|
362
|
-
|
|
397
|
+
retrying.current.add(messageId);
|
|
398
|
+
const release = () => {
|
|
399
|
+
retrying.current.delete(messageId);
|
|
400
|
+
};
|
|
401
|
+
try {
|
|
402
|
+
discardFailed(entry);
|
|
403
|
+
void dispatch(command).then(release, release);
|
|
404
|
+
} catch (error) {
|
|
405
|
+
release();
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
363
408
|
},
|
|
364
409
|
discardFailed: (messageId) => discardFailed(takeFailed(messageId)),
|
|
365
410
|
popFailed: (messageId) => {
|
|
@@ -442,13 +487,16 @@ const useStatewireThread = (
|
|
|
442
487
|
Array.isArray(payload))
|
|
443
488
|
)
|
|
444
489
|
throw new Error("statewire: stopPayload must return a plain object");
|
|
490
|
+
const runId = runs.runId;
|
|
445
491
|
void commands["run/stop"]!({
|
|
446
492
|
...payload,
|
|
447
|
-
runId
|
|
493
|
+
runId,
|
|
448
494
|
...(runs.epoch !== undefined && { epoch: runs.epoch }),
|
|
449
|
-
})
|
|
450
|
-
|
|
451
|
-
|
|
495
|
+
})
|
|
496
|
+
.then((retracted) => popRetracted(retracted, runId))
|
|
497
|
+
.catch((error: Error) => {
|
|
498
|
+
latest.current.onError?.(error);
|
|
499
|
+
});
|
|
452
500
|
},
|
|
453
501
|
}),
|
|
454
502
|
);
|
|
@@ -762,6 +810,8 @@ export namespace StatewireThread {
|
|
|
762
810
|
readonly runId: string | null;
|
|
763
811
|
/** Counts the entry's dispatches; a `run/stop` carrying a stale epoch rejects. */
|
|
764
812
|
readonly epoch?: number;
|
|
813
|
+
/** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
|
|
814
|
+
readonly stopReason?: string | null;
|
|
765
815
|
readonly status: RunStatus;
|
|
766
816
|
readonly queue: readonly RunsQueueEntry[];
|
|
767
817
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
@@ -798,6 +848,8 @@ export namespace StatewireThread {
|
|
|
798
848
|
readonly runId: string | null;
|
|
799
849
|
/** Counts the entry's dispatches; rides `run/stop` so a replayed stop cannot end a later leg. */
|
|
800
850
|
readonly epoch?: number;
|
|
851
|
+
/** The reason carried by `run/stop`; persists through error/stop, cleared at the next dispatch. */
|
|
852
|
+
readonly stopReason?: string | null;
|
|
801
853
|
readonly queue: readonly RunsQueueEntry[];
|
|
802
854
|
readonly steerQueue: readonly RunsQueueEntry[];
|
|
803
855
|
/** The dispatch record — the unapplied batch handed to the run, cleared at applied. */
|
|
@@ -846,6 +898,8 @@ export namespace StatewireThread {
|
|
|
846
898
|
transport: Transport<T>;
|
|
847
899
|
/** 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
900
|
initialState: T;
|
|
901
|
+
/** Application protocol for optimistic commands; must match the transport's protocol. */
|
|
902
|
+
protocol?: string | undefined;
|
|
849
903
|
converter: StateConverter<T>;
|
|
850
904
|
/** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
|
|
851
905
|
optimistic?:
|
package/src/localStorage.test.ts
CHANGED
|
@@ -174,22 +174,24 @@ describe("LocalStorageSession", () => {
|
|
|
174
174
|
|
|
175
175
|
const record = {
|
|
176
176
|
clientId: "c-1",
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
177
|
+
lanes: {
|
|
178
|
+
default: {
|
|
179
|
+
nextSeq: 3,
|
|
180
|
+
commands: [
|
|
181
|
+
{
|
|
182
|
+
seq: 2,
|
|
183
|
+
method: "run/steer",
|
|
184
|
+
params: [{ text: "hi" }],
|
|
185
|
+
meta: { requestId: "r-2" },
|
|
186
|
+
},
|
|
187
|
+
],
|
|
186
188
|
},
|
|
187
|
-
|
|
189
|
+
},
|
|
188
190
|
};
|
|
189
191
|
root.getValue().save(record);
|
|
190
192
|
expect(JSON.parse(localStorage.getItem(`${SESSION_PREFIX}t1`)!)).toEqual({
|
|
191
193
|
...record,
|
|
192
|
-
statewireStorageVersion:
|
|
194
|
+
statewireStorageVersion: 3,
|
|
193
195
|
savedAt: expect.any(Number),
|
|
194
196
|
});
|
|
195
197
|
expect(root.getValue().load()).toEqual(record);
|
|
@@ -203,26 +205,22 @@ describe("LocalStorageSession", () => {
|
|
|
203
205
|
JSON.stringify({
|
|
204
206
|
clientId: "c-1",
|
|
205
207
|
nextSeq: 1,
|
|
206
|
-
ctxNextSeq: 1,
|
|
207
208
|
commands: "invalid",
|
|
208
209
|
}),
|
|
209
210
|
JSON.stringify({
|
|
210
211
|
clientId: "c-1",
|
|
211
212
|
nextSeq: 2,
|
|
212
|
-
ctxNextSeq: 1,
|
|
213
213
|
commands: [{ seq: 1, method: "run", params: null, meta: {} }],
|
|
214
214
|
}),
|
|
215
215
|
JSON.stringify({
|
|
216
216
|
clientId: "c-1",
|
|
217
217
|
nextSeq: 1,
|
|
218
|
-
ctxNextSeq: 1,
|
|
219
218
|
commands: [],
|
|
220
219
|
verdicts: [{ seq: 1, type: "future" }],
|
|
221
220
|
}),
|
|
222
221
|
JSON.stringify({
|
|
223
222
|
clientId: "c-1",
|
|
224
223
|
nextSeq: 1,
|
|
225
|
-
ctxNextSeq: 1,
|
|
226
224
|
commands: [],
|
|
227
225
|
failed: [
|
|
228
226
|
{
|
|
@@ -244,12 +242,7 @@ describe("LocalStorageSession", () => {
|
|
|
244
242
|
|
|
245
243
|
it("derives the storage key through the key callback", () => {
|
|
246
244
|
const root = mountSession({ threadId: "t1", key: (id) => `user-42:${id}` });
|
|
247
|
-
root.getValue().save({
|
|
248
|
-
clientId: "c-1",
|
|
249
|
-
nextSeq: 1,
|
|
250
|
-
ctxNextSeq: 1,
|
|
251
|
-
commands: [],
|
|
252
|
-
});
|
|
245
|
+
root.getValue().save({ clientId: "c-1", lanes: {} });
|
|
253
246
|
expect(localStorage.getItem(`${SESSION_PREFIX}user-42:t1`)).not.toBeNull();
|
|
254
247
|
expect(localStorage.getItem(`${SESSION_PREFIX}t1`)).toBeNull();
|
|
255
248
|
root.unmount();
|
|
@@ -307,7 +300,6 @@ describe("LocalStorageSession", () => {
|
|
|
307
300
|
JSON.stringify({
|
|
308
301
|
clientId: key,
|
|
309
302
|
nextSeq: 1,
|
|
310
|
-
ctxNextSeq: 1,
|
|
311
303
|
commands: [],
|
|
312
304
|
savedAt: 1,
|
|
313
305
|
}),
|
package/src/localStorage.ts
CHANGED
|
@@ -188,7 +188,7 @@ const useLocalStorageSession = ({
|
|
|
188
188
|
threadId,
|
|
189
189
|
migrate,
|
|
190
190
|
key = (id) => id,
|
|
191
|
-
|
|
191
|
+
protocol,
|
|
192
192
|
retention,
|
|
193
193
|
onError,
|
|
194
194
|
}: LocalStorageSession.Options): StatewireClient.SessionStorage => {
|
|
@@ -222,7 +222,7 @@ const useLocalStorageSession = ({
|
|
|
222
222
|
key: key(threadId),
|
|
223
223
|
namespace: SESSION_PREFIX,
|
|
224
224
|
...(migrate === undefined ? {} : { migrate }),
|
|
225
|
-
...(
|
|
225
|
+
...(protocol === undefined ? {} : { protocol }),
|
|
226
226
|
...(retention === undefined ? {} : { retention }),
|
|
227
227
|
...(onError === undefined ? {} : { onError }),
|
|
228
228
|
}),
|
|
@@ -248,7 +248,7 @@ export const LocalStorageSession = resource(useLocalStorageSession);
|
|
|
248
248
|
|
|
249
249
|
export namespace LocalStorageSession {
|
|
250
250
|
export type Options = {
|
|
251
|
-
|
|
251
|
+
protocol?: KeyValueSessionStorage.Options["protocol"];
|
|
252
252
|
retention?: KeyValueSessionStorage.Options["retention"];
|
|
253
253
|
onError?: KeyValueSessionStorage.Options["onError"];
|
|
254
254
|
/** Upgrade incompatible queued commands, or return null to discard the saved session. */
|