@assistant-ui/react-statewire 0.4.4 → 0.6.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/src/hooks.ts CHANGED
@@ -4,6 +4,7 @@ import { useAui, useAuiState } from "@assistant-ui/store";
4
4
  import { asAssistantTransportExtras } from "./AssistantTransportThread";
5
5
  import type { Assistant } from "@assistant-ui/react";
6
6
  import type { AssistantTransportThread } from "./AssistantTransportThread";
7
+ import type { StatewireThread } from "./StatewireThread";
7
8
 
8
9
  type UserExternalState = keyof Assistant.ExternalState extends never
9
10
  ? Record<string, unknown>
@@ -18,6 +19,17 @@ export const useAssistantTransportSendCommand = () => {
18
19
  };
19
20
  };
20
21
 
22
+ /** The typed runs read; requires StatewireThread with the `runs` option. */
23
+ export const useStatewireRuns = (): StatewireThread.Runs =>
24
+ useAuiState((s) => {
25
+ const { runs } = asAssistantTransportExtras(s.thread.extras);
26
+ if (runs === undefined)
27
+ throw new Error(
28
+ "statewire: useStatewireRuns requires StatewireThread with the runs option enabled",
29
+ );
30
+ return runs;
31
+ });
32
+
21
33
  export function useAssistantTransportState(): UserExternalState;
22
34
  export function useAssistantTransportState<T>(
23
35
  selector: (state: UserExternalState) => T,
package/src/index.ts CHANGED
@@ -3,4 +3,5 @@ export { StatewireThread } from "./StatewireThread";
3
3
  export {
4
4
  useAssistantTransportSendCommand,
5
5
  useAssistantTransportState,
6
+ useStatewireRuns,
6
7
  } from "./hooks";
@@ -25,47 +25,32 @@ const INITIAL_STATE: TestState = { messages: [] };
25
25
 
26
26
  const converter: AssistantTransportThread.StateConverter<TestState> = (
27
27
  state,
28
- meta,
29
28
  ) => ({
30
- messages: [
31
- ...state.messages.map(
32
- (m) =>
33
- ({
34
- id: m.id,
35
- role: m.role,
36
- createdAt: new Date(0),
37
- content: [{ type: "text", text: m.text }],
38
- attachments: [],
39
- metadata: { custom: {} },
40
- ...(m.role === "assistant" && {
41
- status: { type: "complete", reason: "stop" },
42
- }),
43
- }) as unknown as ExternalThreadMessage,
44
- ),
45
- ...meta.pendingCommands.flatMap((c, i) =>
46
- // The legacy runtime still surfaces add-message pending commands.
47
- (c.type === "run/steer" || (c.type as string) === "add-message") &&
48
- "message" in c &&
49
- c.message.role === "user"
50
- ? [
51
- {
52
- id: `optimistic-${i}`,
53
- role: "user",
54
- createdAt: new Date(0),
55
- content: [
56
- {
57
- type: "text",
58
- text:
59
- c.message.parts.find((p) => p.type === "text")?.text ?? "",
60
- },
61
- ],
62
- attachments: [],
63
- metadata: { custom: {} },
64
- } as unknown as ExternalThreadMessage,
65
- ]
66
- : [],
67
- ),
68
- ],
29
+ messages: state.messages.map(
30
+ (m) =>
31
+ ({
32
+ id: m.id,
33
+ role: m.role,
34
+ createdAt: new Date(0),
35
+ content: [{ type: "text", text: m.text }],
36
+ attachments: [],
37
+ metadata: { custom: {} },
38
+ ...(m.role === "assistant" && {
39
+ status: { type: "complete", reason: "stop" },
40
+ }),
41
+ }) as unknown as ExternalThreadMessage,
42
+ ),
43
+ isRunning: false,
44
+ });
45
+
46
+ // The legacy runtime still feeds connection metadata into its converter.
47
+ type LegacyMeta = {
48
+ pendingCommands: { type: string; message?: { role: string } }[];
49
+ isSending: boolean;
50
+ };
51
+
52
+ const legacyConverter = (state: TestState, meta: LegacyMeta) => ({
53
+ ...converter(state),
69
54
  isRunning: meta.isSending,
70
55
  });
71
56
 
@@ -184,7 +169,7 @@ const observeLegacy = async (): Promise<{
184
169
  api: "https://example.com/api",
185
170
  protocol: "assistant-transport",
186
171
  headers: {},
187
- converter: converter as never,
172
+ converter: legacyConverter as never,
188
173
  });
189
174
  return (
190
175
  <AssistantRuntimeProvider runtime={captured.runtime}>
@@ -287,10 +272,9 @@ type ToolState = TestState & {
287
272
 
288
273
  const toolConverter: AssistantTransportThread.StateConverter<ToolState> = (
289
274
  state,
290
- meta,
291
275
  ) => {
292
276
  const base = {
293
- ...converter(state, meta),
277
+ ...converter(state),
294
278
  inputRequests: state.inputRequests ?? [],
295
279
  };
296
280
  if (!state.toolCall) return base;
@@ -316,10 +300,14 @@ const toolConverter: AssistantTransportThread.StateConverter<ToolState> = (
316
300
  status: { type: "requires-action", reason: "tool-call" },
317
301
  } as unknown as ExternalThreadMessage,
318
302
  ],
319
- isRunning: meta.isSending,
320
303
  };
321
304
  };
322
305
 
306
+ const legacyToolConverter = (state: ToolState, meta: LegacyMeta) => ({
307
+ ...toolConverter(state),
308
+ isRunning: meta.isSending,
309
+ });
310
+
323
311
  const TOOL_TRANSCRIPT: string[][] = [
324
312
  [
325
313
  sseEvent({
@@ -472,9 +460,10 @@ const observeLegacyToolRun = async (): Promise<ToolObserved> => {
472
460
  runtime?: ReturnType<typeof useAssistantTransportRuntime>;
473
461
  } = {};
474
462
  const App: FC = () => {
475
- captured.runtime = useAssistantTransportRuntime<ToolState>(
476
- toolOptions(events) as never,
477
- );
463
+ captured.runtime = useAssistantTransportRuntime<ToolState>({
464
+ ...toolOptions(events),
465
+ converter: legacyToolConverter,
466
+ } as never);
478
467
  return (
479
468
  <AssistantRuntimeProvider runtime={captured.runtime}>
480
469
  {null}
@@ -80,6 +80,18 @@ export const viewedLeafId = (
80
80
  messages: readonly { id: string }[],
81
81
  ): string | null => messages.at(-1)?.id ?? null;
82
82
 
83
+ export const resolveEditCommand = (
84
+ message: AppendMessage,
85
+ ): AssistantTransportThread.RunEditCommand => {
86
+ if (message.sourceId == null)
87
+ throw new Error("statewire: run/edit requires a sourceId");
88
+ return {
89
+ type: "run/edit",
90
+ message: toWireMessage(message, crypto.randomUUID()),
91
+ sourceId: message.sourceId,
92
+ };
93
+ };
94
+
83
95
  export const createRunQueueAdapter = (
84
96
  messages: readonly { id: string }[],
85
97
  queueItems: readonly AssistantTransportThread.RunQueueItem[],
@@ -92,21 +104,25 @@ export const createRunQueueAdapter = (
92
104
  if (queueItems.some((item) => item.id === queueItemId)) return "queue";
93
105
  throw new Error(`statewire: unknown queue item "${queueItemId}"`);
94
106
  };
107
+ // edit-composer sends carry a sourceId; they bypass the lanes into run/edit
108
+ const sendCommand = (
109
+ lane: "queue" | "steer",
110
+ message: AppendMessage,
111
+ ): AssistantTransportThread.RunCommand => {
112
+ if (message.sourceId != null) return resolveEditCommand(message);
113
+ const fields = {
114
+ message: toWireMessage(message, crypto.randomUUID()),
115
+ anchorMessageId: viewedLeafId(messages),
116
+ };
117
+ return lane === "steer"
118
+ ? { type: "run/steer", ...fields }
119
+ : { type: "run/enqueue", ...fields };
120
+ };
95
121
  return {
96
122
  items: queueItems.map(toQueueItemState),
97
123
  steerItems: (steerQueueItems ?? []).map(toQueueItemState),
98
- enqueue: (message) =>
99
- dispatch({
100
- type: "run/enqueue",
101
- message: toWireMessage(message, crypto.randomUUID()),
102
- anchorMessageId: viewedLeafId(messages),
103
- }),
104
- steer: (message) =>
105
- dispatch({
106
- type: "run/steer",
107
- message: toWireMessage(message, crypto.randomUUID()),
108
- anchorMessageId: viewedLeafId(messages),
109
- }),
124
+ enqueue: (message) => dispatch(sendCommand("queue", message)),
125
+ steer: (message) => dispatch(sendCommand("steer", message)),
110
126
  move: (queueItemId, placement) => {
111
127
  const lane = placement.lane ?? laneOf(queueItemId);
112
128
  const fields = {
@@ -0,0 +1,225 @@
1
+ // Contract tests for the run-dialect optimistic reducer: unsettled run/*
2
+ // commands fold into the runs mount draft.
3
+
4
+ import { describe, expect, it } from "vitest";
5
+ import { runsOptimistic } from "./runsOptimistic";
6
+
7
+ type Draft = Record<string, any>;
8
+
9
+ const ctx = { ts: 0, seq: 7 };
10
+
11
+ const mount = (entry?: Draft): Draft =>
12
+ entry === undefined
13
+ ? { status: "ready", runs: [] }
14
+ : {
15
+ status: entry.status,
16
+ runs: [
17
+ {
18
+ runId: null,
19
+ queue: [],
20
+ steerQueue: [],
21
+ error: null,
22
+ runLeafMessageId: null,
23
+ ...entry,
24
+ },
25
+ ],
26
+ };
27
+
28
+ const run = (draft: Draft): Draft => draft.runs[0];
29
+
30
+ const message = (id: string) => ({
31
+ id,
32
+ role: "user" as const,
33
+ parts: [{ type: "text" as const, text: id }],
34
+ });
35
+
36
+ const apply = (draft: Draft, method: string, param?: unknown) =>
37
+ runsOptimistic(
38
+ draft,
39
+ { method, params: param === undefined ? [] : [param] } as never,
40
+ ctx,
41
+ );
42
+
43
+ describe("runsOptimistic", () => {
44
+ it("parks a steer add in the lane while running", () => {
45
+ const draft = mount({ status: "running", runId: "run-1" });
46
+ apply(draft, "run/steer", {
47
+ type: "run/steer",
48
+ message: message("s1"),
49
+ anchorMessageId: null,
50
+ });
51
+ expect(run(draft).steerQueue.map((e: Draft) => e.id)).toEqual(["s1"]);
52
+ expect(draft.status).toBe("running");
53
+ expect(run(draft).status).toBe("running");
54
+ expect(run(draft).runId).toBe("run-1");
55
+ });
56
+
57
+ it("dispatches a steer while no run is active: the whole lane enters the thread", () => {
58
+ const draft = mount({
59
+ status: "stopped",
60
+ steerQueue: [message("s1")],
61
+ error: { message: "boom" },
62
+ });
63
+ apply(draft, "run/steer", {
64
+ type: "run/steer",
65
+ message: message("s2"),
66
+ anchorMessageId: null,
67
+ });
68
+ expect(draft.status).toBe("running");
69
+ expect(run(draft).status).toBe("running");
70
+ expect(run(draft).runId).toBe("optimistic-7");
71
+ expect(run(draft).steerQueue).toEqual([]);
72
+ expect(run(draft).error).toBeNull();
73
+ });
74
+
75
+ it("dispatches an enqueue add only in ready or in error/stop with empty lanes", () => {
76
+ const ready = mount();
77
+ apply(ready, "run/enqueue", {
78
+ type: "run/enqueue",
79
+ message: message("a"),
80
+ anchorMessageId: null,
81
+ });
82
+ expect(ready.status).toBe("running");
83
+ expect(run(ready).runId).toBe("optimistic-7");
84
+ expect(run(ready).queue).toEqual([]);
85
+
86
+ const stopped = mount({ status: "stopped", queue: [message("q1")] });
87
+ apply(stopped, "run/enqueue", {
88
+ type: "run/enqueue",
89
+ message: message("a"),
90
+ anchorMessageId: null,
91
+ });
92
+ expect(stopped.status).toBe("stopped");
93
+ expect(run(stopped).queue.map((e: Draft) => e.id)).toEqual(["q1", "a"]);
94
+ });
95
+
96
+ it("parks an enqueue add at its placement while running", () => {
97
+ const draft = mount({
98
+ status: "running",
99
+ runId: "r",
100
+ queue: [message("a"), message("b")],
101
+ });
102
+ apply(draft, "run/enqueue", {
103
+ type: "run/enqueue",
104
+ message: message("x"),
105
+ anchorMessageId: null,
106
+ insertAfter: "a",
107
+ });
108
+ expect(run(draft).queue.map((e: Draft) => e.id)).toEqual(["a", "x", "b"]);
109
+ });
110
+
111
+ it("applies moves, edits of queued items, and dequeue", () => {
112
+ const draft = mount({
113
+ status: "running",
114
+ runId: "r",
115
+ queue: [{ ...message("q1"), meta: { m: 1 } }, message("q2")],
116
+ });
117
+ apply(draft, "run/steer", { type: "run/steer", messageId: "q1" });
118
+ expect(run(draft).queue.map((e: Draft) => e.id)).toEqual(["q2"]);
119
+ expect(run(draft).steerQueue.map((e: Draft) => e.id)).toEqual(["q1"]);
120
+ expect(run(draft).steerQueue[0].meta).toEqual({ m: 1 });
121
+
122
+ apply(draft, "run/enqueue", {
123
+ type: "run/enqueue",
124
+ message: { ...message("q2"), parts: [{ type: "text", text: "new" }] },
125
+ });
126
+ expect(run(draft).queue.map((e: Draft) => e.id)).toEqual(["q2"]);
127
+ expect(run(draft).queue[0].parts).toEqual([{ type: "text", text: "new" }]);
128
+
129
+ apply(draft, "run/dequeue", { type: "run/dequeue", messageId: "q1" });
130
+ expect(run(draft).steerQueue).toEqual([]);
131
+ });
132
+
133
+ it("run/edit, run/reload, and run/continue start the run optimistically", () => {
134
+ const draft = mount({
135
+ status: "input-required",
136
+ runId: "run-1",
137
+ inputRequests: [{ type: "custom", id: "r1", response: null }],
138
+ });
139
+ apply(draft, "run/edit", {
140
+ type: "run/edit",
141
+ message: message("m2b"),
142
+ sourceId: "m2",
143
+ });
144
+ expect(draft.status).toBe("running");
145
+ expect(run(draft).runId).toBe("optimistic-7");
146
+ expect(run(draft).inputRequests).toBeUndefined();
147
+
148
+ const stopped = mount({ status: "stopped", steerQueue: [message("s1")] });
149
+ apply(stopped, "run/continue", { type: "run/continue" });
150
+ expect(stopped.status).toBe("running");
151
+ expect(run(stopped).steerQueue).toEqual([]);
152
+ });
153
+
154
+ it("dispatches from a bare ready mount by creating the run entry", () => {
155
+ const draft = mount();
156
+ apply(draft, "run/steer", {
157
+ type: "run/steer",
158
+ message: message("s1"),
159
+ anchorMessageId: null,
160
+ });
161
+ expect(draft.status).toBe("running");
162
+ expect(draft.runs).toHaveLength(1);
163
+ expect(run(draft)).toEqual({
164
+ runId: "optimistic-7",
165
+ status: "running",
166
+ queue: [],
167
+ steerQueue: [],
168
+ error: null,
169
+ runLeafMessageId: null,
170
+ });
171
+ });
172
+
173
+ it("echoes run/input answers and dispatches once the set completes", () => {
174
+ const draft = mount({
175
+ status: "input-required",
176
+ runId: "run-1",
177
+ inputRequests: [
178
+ { type: "custom", id: "r1", response: null },
179
+ { type: "custom", id: "r2", response: null },
180
+ ],
181
+ });
182
+ apply(draft, "run/input", {
183
+ type: "run/input",
184
+ requestId: "r1",
185
+ response: { ok: true },
186
+ });
187
+ expect(draft.status).toBe("input-required");
188
+ expect(run(draft).inputRequests[0].response).toEqual({ ok: true });
189
+
190
+ apply(draft, "run/input", {
191
+ type: "run/input",
192
+ requestId: "r2",
193
+ response: { ok: true },
194
+ });
195
+ expect(draft.status).toBe("running");
196
+ expect(run(draft).inputRequests).toBeUndefined();
197
+ });
198
+
199
+ it("dispatches a steer over a partially answered set: the answered subset rides, requests clear", () => {
200
+ const draft = mount({
201
+ status: "input-required",
202
+ runId: "run-1",
203
+ inputRequests: [
204
+ { type: "custom", id: "r1", response: { ok: true } },
205
+ { type: "custom", id: "r2", response: null },
206
+ ],
207
+ });
208
+ apply(draft, "run/steer", {
209
+ type: "run/steer",
210
+ message: message("s1"),
211
+ anchorMessageId: null,
212
+ });
213
+ expect(draft.status).toBe("running");
214
+ expect(run(draft).runId).toBe("optimistic-7");
215
+ expect(run(draft).inputRequests).toBeUndefined();
216
+ expect(run(draft).steerQueue).toEqual([]);
217
+ });
218
+
219
+ it("leaves the draft untouched for run/stop and unknown moves", () => {
220
+ const draft = mount({ status: "running", runId: "run-1" });
221
+ apply(draft, "run/stop", { runId: "run-1" });
222
+ apply(draft, "run/enqueue", { type: "run/enqueue", messageId: "ghost" });
223
+ expect(draft).toEqual(mount({ status: "running", runId: "run-1" }));
224
+ });
225
+ });
@@ -0,0 +1,164 @@
1
+ import type { Statewire, StatewireClient } from "statewire";
2
+ import type { StatewireThread } from "./StatewireThread";
3
+
4
+ type LaneEntry = {
5
+ id: string;
6
+ role: "user";
7
+ parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];
8
+ metadata?: Record<string, unknown>;
9
+ meta?: unknown;
10
+ };
11
+
12
+ type RunEntry = {
13
+ runId: string | null;
14
+ status: StatewireThread.RunStatus;
15
+ queue: LaneEntry[];
16
+ steerQueue: LaneEntry[];
17
+ inputRequests?: { id: string; response: unknown }[];
18
+ error: unknown;
19
+ runLeafMessageId: string | null;
20
+ };
21
+
22
+ type RunsDraft = {
23
+ status: StatewireThread.RunStatus;
24
+ runs: RunEntry[];
25
+ };
26
+
27
+ const startRun = (draft: RunsDraft, runId: string): void => {
28
+ const entry = (draft.runs[0] ??= {
29
+ runId: null,
30
+ status: "running",
31
+ queue: [],
32
+ steerQueue: [],
33
+ error: null,
34
+ runLeafMessageId: null,
35
+ });
36
+ entry.status = "running";
37
+ entry.runId = runId;
38
+ entry.error = null;
39
+ delete entry.inputRequests;
40
+ draft.status = "running";
41
+ };
42
+
43
+ const insert = (
44
+ lane: LaneEntry[],
45
+ entry: LaneEntry,
46
+ { insertAfter, insertBefore }: StatewireThread.Placement,
47
+ ): void => {
48
+ const index =
49
+ insertAfter !== undefined
50
+ ? insertAfter === null
51
+ ? 0
52
+ : lane.findIndex((e) => e.id === insertAfter) + 1
53
+ : insertBefore === undefined || insertBefore === null
54
+ ? lane.length
55
+ : lane.findIndex((e) => e.id === insertBefore);
56
+ lane.splice(index < 0 ? lane.length : index, 0, entry);
57
+ };
58
+
59
+ const enqueueOrSteer = (
60
+ draft: RunsDraft,
61
+ command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,
62
+ runId: string,
63
+ ): void => {
64
+ const run = draft.runs[0];
65
+ const id = "message" in command ? command.message.id : command.messageId;
66
+ const sourceLane =
67
+ run === undefined
68
+ ? undefined
69
+ : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));
70
+
71
+ let entry: LaneEntry;
72
+ let sourceIndex = -1;
73
+ if (sourceLane !== undefined) {
74
+ sourceIndex = sourceLane.findIndex((e) => e.id === id);
75
+ entry = sourceLane.splice(sourceIndex, 1)[0]!;
76
+ if ("message" in command) {
77
+ entry.parts = command.message.parts;
78
+ if (command.message.metadata !== undefined)
79
+ entry.metadata = command.message.metadata;
80
+ }
81
+ } else {
82
+ if (!("message" in command)) return;
83
+ entry = { ...command.message };
84
+ }
85
+
86
+ const dispatching =
87
+ command.type === "run/steer"
88
+ ? draft.status !== "running"
89
+ : sourceLane === undefined &&
90
+ (draft.status === "ready" ||
91
+ ((draft.status === "stopped" || draft.status === "error") &&
92
+ run !== undefined &&
93
+ run.queue.length === 0 &&
94
+ run.steerQueue.length === 0));
95
+ if (dispatching) {
96
+ if (command.type === "run/steer" && run !== undefined) run.steerQueue = [];
97
+ startRun(draft, runId);
98
+ return;
99
+ }
100
+
101
+ if (run === undefined) return;
102
+ const lane = command.type === "run/steer" ? run.steerQueue : run.queue;
103
+ const hasPlacement =
104
+ command.insertAfter !== undefined || command.insertBefore !== undefined;
105
+ if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);
106
+ else insert(lane, entry, command);
107
+ };
108
+
109
+ /** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */
110
+ export const runsOptimistic = (
111
+ mount: unknown,
112
+ command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,
113
+ ctx: StatewireClient.OptimisticContext,
114
+ ): void => {
115
+ const draft = mount as RunsDraft;
116
+ const runId = `optimistic-${ctx.seq}`;
117
+ switch (command.method) {
118
+ case "run/enqueue":
119
+ case "run/steer": {
120
+ enqueueOrSteer(
121
+ draft,
122
+ command.params[0] as
123
+ | StatewireThread.RunEnqueueCommand
124
+ | StatewireThread.RunSteerCommand,
125
+ runId,
126
+ );
127
+ break;
128
+ }
129
+ case "run/edit":
130
+ case "run/reload": {
131
+ startRun(draft, runId);
132
+ break;
133
+ }
134
+ case "run/continue": {
135
+ const run = draft.runs[0];
136
+ if (run !== undefined) run.steerQueue = [];
137
+ startRun(draft, runId);
138
+ break;
139
+ }
140
+ case "run/dequeue": {
141
+ const { messageId } = command
142
+ .params[0] as StatewireThread.RunDequeueCommand;
143
+ const run = draft.runs[0];
144
+ if (run === undefined) break;
145
+ for (const lane of [run.queue, run.steerQueue]) {
146
+ const index = lane.findIndex((e) => e.id === messageId);
147
+ if (index !== -1) lane.splice(index, 1);
148
+ }
149
+ break;
150
+ }
151
+ case "run/input": {
152
+ const { requestId, response } = command
153
+ .params[0] as StatewireThread.RunInputCommand;
154
+ const requests = draft.runs[0]?.inputRequests;
155
+ const target = requests?.find((r) => r.id === requestId);
156
+ if (target === undefined) break;
157
+ target.response = response;
158
+ if (requests!.every((r) => r.response !== null)) startRun(draft, runId);
159
+ break;
160
+ }
161
+ default:
162
+ break;
163
+ }
164
+ };