@assistant-ui/react-statewire 0.1.1 → 0.2.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.
@@ -20,31 +20,35 @@ import { createMockTransport } from "statewire/testing";
20
20
  import { StatewireThread } from "./StatewireThread";
21
21
  import { asAssistantTransportExtras } from "./AssistantTransportThread";
22
22
  import { useAssistantTransportState } from "./hooks";
23
- import type {
24
- AddMessageCommand,
25
- AssistantTransportCommand,
26
- ClearQueueCommand,
27
- EnqueueMessageCommand,
28
- RemoveQueueItemCommand,
29
- SteerQueueItemCommand,
30
- } from "./types";
23
+ import type { MessageAddCommand, AssistantTransportCommand } from "./types";
31
24
  import {
32
25
  sendCommand,
33
26
  threadTexts,
34
27
  toThreadMessage,
35
28
  } from "./__tests__/testHelpers";
36
29
 
30
+ type QueueEntry = {
31
+ id: string;
32
+ parts: StatewireThread.UserMessage["parts"];
33
+ };
34
+
37
35
  type ServerState = {
38
36
  messages: { id: string; role: "user" | "assistant"; text: string }[];
39
37
  running: boolean;
40
- queue: { id: string; prompt: string }[];
38
+ queue: QueueEntry[];
39
+ steerQueue: QueueEntry[];
41
40
  };
42
41
 
43
- const textOf = (command: Pick<AddMessageCommand, "message">) =>
42
+ const textOf = (command: Pick<MessageAddCommand, "message">) =>
44
43
  command.message.parts
45
44
  .flatMap((p) => (p.type === "text" ? [p.text] : []))
46
45
  .join("");
47
46
 
47
+ const textEntry = (id: string, text: string): QueueEntry => ({
48
+ id,
49
+ parts: [{ type: "text", text }],
50
+ });
51
+
48
52
  const converter: StatewireThread.StateConverter<ServerState> = (
49
53
  state,
50
54
  meta,
@@ -52,7 +56,7 @@ const converter: StatewireThread.StateConverter<ServerState> = (
52
56
  messages: [
53
57
  ...state.messages.map(toThreadMessage),
54
58
  ...meta.pendingCommands.flatMap((c, i) =>
55
- c.type === "add-message" && c.message.role === "user"
59
+ c.type === "message/add" && c.message.role === "user"
56
60
  ? [
57
61
  toThreadMessage({
58
62
  id: `optimistic-${i}`,
@@ -69,6 +73,7 @@ const converter: StatewireThread.StateConverter<ServerState> = (
69
73
  const createServer = (init?: {
70
74
  messages?: ServerState["messages"];
71
75
  queue?: ServerState["queue"];
76
+ steerQueue?: ServerState["steerQueue"];
72
77
  }) => {
73
78
  const received: unknown[] = [];
74
79
  const cell: {
@@ -81,10 +86,96 @@ const createServer = (init?: {
81
86
  messages: init?.messages ?? [],
82
87
  running: false,
83
88
  queue: init?.queue ?? [],
89
+ steerQueue: init?.steerQueue ?? [],
84
90
  }));
85
91
  cell.state = state;
92
+
93
+ const takeEntry = (id: string): QueueEntry | undefined => {
94
+ for (const lane of [state.steerQueue, state.queue]) {
95
+ const index = lane.findIndex((entry) => entry.id === id);
96
+ if (index !== -1) {
97
+ // snapshot before splicing: element proxies are path-based
98
+ const removed = JSON.parse(JSON.stringify(lane[index])) as QueueEntry;
99
+ lane.splice(index, 1);
100
+ return removed;
101
+ }
102
+ }
103
+ return undefined;
104
+ };
105
+ const place = (
106
+ lane: QueueEntry[],
107
+ entry: QueueEntry,
108
+ placement: StatewireThread.Placement,
109
+ ) => {
110
+ if (placement.insertAfter === null) lane.unshift(entry);
111
+ else if (placement.insertAfter != null)
112
+ lane.splice(
113
+ lane.findIndex((e) => e.id === placement.insertAfter) + 1,
114
+ 0,
115
+ entry,
116
+ );
117
+ else if (placement.insertBefore == null) lane.push(entry);
118
+ else
119
+ lane.splice(
120
+ lane.findIndex((e) => e.id === placement.insertBefore),
121
+ 0,
122
+ entry,
123
+ );
124
+ };
125
+ const submitSend = (
126
+ lane: "queue" | "steerQueue",
127
+ command:
128
+ | StatewireThread.RunEnqueueCommand
129
+ | StatewireThread.RunSteerCommand,
130
+ ) => {
131
+ received.push(command);
132
+ if ("messageId" in command) {
133
+ const entry = takeEntry(command.messageId);
134
+ if (!entry) throw new StatewireReject("unknown-id");
135
+ place(state[lane], entry, command);
136
+ return;
137
+ }
138
+ const entry: QueueEntry = {
139
+ id: command.message.id,
140
+ parts: [...command.message.parts],
141
+ };
142
+ const replaced = takeEntry(entry.id);
143
+ if (replaced) {
144
+ place(state[lane], entry, command);
145
+ return;
146
+ }
147
+ if (!state.running) {
148
+ state.messages.push({
149
+ id: entry.id,
150
+ role: "user",
151
+ text: command.message.parts
152
+ .flatMap((p) => (p.type === "text" ? [p.text] : []))
153
+ .join(""),
154
+ });
155
+ state.running = true;
156
+ return;
157
+ }
158
+ state[lane].push(entry);
159
+ };
160
+
86
161
  const commands = useStatewireCommands({
87
- "add-message": (command: AddMessageCommand) => {
162
+ "run/enqueue": (command: StatewireThread.RunEnqueueCommand) =>
163
+ submitSend("queue", command),
164
+ "run/steer": (command: StatewireThread.RunSteerCommand) =>
165
+ submitSend("steerQueue", command),
166
+ "run/dequeue": (command: StatewireThread.RunDequeueCommand) => {
167
+ received.push(command);
168
+ if (!takeEntry(command.messageId))
169
+ throw new StatewireReject("unknown-id");
170
+ },
171
+ "run/edit": (command: StatewireThread.RunEditCommand) => {
172
+ received.push(command);
173
+ },
174
+ "run/continue": (command: StatewireThread.RunContinueCommand) => {
175
+ received.push(command);
176
+ state.running = true;
177
+ },
178
+ "message/add": (command: MessageAddCommand) => {
88
179
  received.push(command);
89
180
  if (cell.hold) {
90
181
  const [execution, resolvers] = CommandExecution.withResolvers();
@@ -99,35 +190,14 @@ const createServer = (init?: {
99
190
  state.running = true;
100
191
  return undefined;
101
192
  },
102
- cancel: (payload?: unknown) => {
193
+ "run/cancel": (payload?: unknown) => {
103
194
  received.push(
104
195
  payload === undefined
105
- ? { type: "cancel" }
106
- : { type: "cancel", payload },
196
+ ? { type: "run/cancel" }
197
+ : { type: "run/cancel", payload },
107
198
  );
108
199
  state.running = false;
109
200
  },
110
- "enqueue-message": (command: EnqueueMessageCommand) => {
111
- received.push(command);
112
- state.queue.push({
113
- id: `q${state.queue.length}`,
114
- prompt: textOf(command),
115
- });
116
- },
117
- "steer-queue-item": (command: SteerQueueItemCommand) => {
118
- received.push(command);
119
- },
120
- "remove-queue-item": (command: RemoveQueueItemCommand) => {
121
- received.push(command);
122
- const index = state.queue.findIndex(
123
- (item) => item.id === command.queueItemId,
124
- );
125
- if (index !== -1) state.queue.splice(index, 1);
126
- },
127
- "clear-queue": (command: ClearQueueCommand) => {
128
- received.push(command);
129
- state.queue.splice(0);
130
- },
131
201
  "reject-me": () => {
132
202
  throw new StatewireReject("nope");
133
203
  },
@@ -137,7 +207,12 @@ const createServer = (init?: {
137
207
  return { transport, received, cell };
138
208
  };
139
209
 
140
- const INITIAL_STATE: ServerState = { messages: [], running: false, queue: [] };
210
+ const INITIAL_STATE: ServerState = {
211
+ messages: [],
212
+ running: false,
213
+ queue: [],
214
+ steerQueue: [],
215
+ };
141
216
 
142
217
  const mountThread = (
143
218
  options: Omit<StatewireThread.Options<ServerState>, "initialState"> &
@@ -190,6 +265,7 @@ describe("StatewireThread", () => {
190
265
  messages: [{ id: "m1", role: "assistant", text: "welcome" }],
191
266
  running: false,
192
267
  queue: [],
268
+ steerQueue: [],
193
269
  }));
194
270
  const commands = useStatewireCommands({});
195
271
  return { state: attached ? state : undefined, commands };
@@ -199,6 +275,7 @@ describe("StatewireThread", () => {
199
275
  messages: [{ id: "i1", role: "assistant", text: "local" }],
200
276
  running: false,
201
277
  queue: [],
278
+ steerQueue: [],
202
279
  };
203
280
  const observed: unknown[] = [];
204
281
  const Probe: FC = () => {
@@ -221,7 +298,7 @@ describe("StatewireThread", () => {
221
298
  expect((observed.at(-1) as ServerState).messages[0]!.text).toBe("welcome");
222
299
  });
223
300
 
224
- it("round-trips an appended message through the add-message command", async () => {
301
+ it("round-trips an appended message through the message/add command", async () => {
225
302
  const server = createServer();
226
303
  const { aui } = mountThread({ transport: server.transport, converter });
227
304
 
@@ -229,7 +306,7 @@ describe("StatewireThread", () => {
229
306
 
230
307
  await waitFor(() => expect(server.received).toHaveLength(1));
231
308
  expect(server.received[0]).toMatchObject({
232
- type: "add-message",
309
+ type: "message/add",
233
310
  message: { role: "user", parts: [{ type: "text", text: "hello" }] },
234
311
  parentId: null,
235
312
  sourceId: null,
@@ -269,7 +346,7 @@ describe("StatewireThread", () => {
269
346
  await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
270
347
  const meta = metas.at(-1)!;
271
348
  expect(meta.isSending).toBe(true);
272
- expect(meta.pendingCommands).toMatchObject([{ type: "add-message" }]);
349
+ expect(meta.pendingCommands).toMatchObject([{ type: "message/add" }]);
273
350
 
274
351
  server.cell.resolvers!.resolve();
275
352
 
@@ -278,7 +355,7 @@ describe("StatewireThread", () => {
278
355
  expect(metas.at(-1)!.pendingCommands).toEqual([]);
279
356
  });
280
357
 
281
- it("dispatches the cancel command from cancelRun", async () => {
358
+ it("dispatches the run/cancel command from cancelRun", async () => {
282
359
  const server = createServer();
283
360
  const { aui } = mountThread({ transport: server.transport, converter });
284
361
 
@@ -288,7 +365,7 @@ describe("StatewireThread", () => {
288
365
  aui().thread().cancelRun();
289
366
 
290
367
  await waitFor(() =>
291
- expect(server.received).toContainEqual({ type: "cancel" }),
368
+ expect(server.received).toContainEqual({ type: "run/cancel" }),
292
369
  );
293
370
  await waitFor(() =>
294
371
  expect(aui().thread().getState().isRunning).toBe(false),
@@ -337,6 +414,7 @@ describe("StatewireThread", () => {
337
414
  messages: [],
338
415
  running: false,
339
416
  queue: [],
417
+ steerQueue: [],
340
418
  });
341
419
  const { aui } = mountThread({
342
420
  transport: mock.transport,
@@ -361,6 +439,7 @@ describe("StatewireThread", () => {
361
439
  messages: [],
362
440
  running: false,
363
441
  queue: [],
442
+ steerQueue: [],
364
443
  });
365
444
  const { aui } = mountThread({
366
445
  transport: mock.transport,
@@ -386,6 +465,7 @@ describe("StatewireThread", () => {
386
465
  messages: [],
387
466
  running: false,
388
467
  queue: [],
468
+ steerQueue: [],
389
469
  });
390
470
  const { aui } = mountThread({ transport: mock.transport, converter });
391
471
  await waitFor(() =>
@@ -395,16 +475,17 @@ describe("StatewireThread", () => {
395
475
  });
396
476
  });
397
477
 
398
- describe("message queue", () => {
478
+ describe("run/* queue", () => {
399
479
  const queueConverter: StatewireThread.StateConverter<ServerState> = (
400
480
  state,
401
481
  meta,
402
482
  ) => ({
403
483
  ...converter(state, meta),
404
484
  queue: state.queue,
485
+ steerQueue: state.steerQueue,
405
486
  });
406
487
 
407
- it("routes composer sends through enqueue-message while a run is active and mirrors the server queue", async () => {
488
+ it("sends run/enqueue: idle append starts a run, mid-run append becomes a queue item", async () => {
408
489
  const server = createServer();
409
490
  const { aui } = mountThread({
410
491
  transport: server.transport,
@@ -417,8 +498,18 @@ describe("StatewireThread", () => {
417
498
 
418
499
  aui().thread().append("hello");
419
500
  await waitFor(() =>
420
- expect(server.received).toMatchObject([{ type: "add-message" }]),
501
+ expect(server.received).toMatchObject([
502
+ {
503
+ type: "run/enqueue",
504
+ message: {
505
+ id: expect.any(String),
506
+ role: "user",
507
+ parts: [{ type: "text", text: "hello" }],
508
+ },
509
+ },
510
+ ]),
421
511
  );
512
+ await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
422
513
  await waitFor(() =>
423
514
  expect(aui().thread().getState().isRunning).toBe(true),
424
515
  );
@@ -426,8 +517,7 @@ describe("StatewireThread", () => {
426
517
  aui().thread().append("queued follow-up");
427
518
  await waitFor(() =>
428
519
  expect(server.received.at(-1)).toMatchObject({
429
- type: "enqueue-message",
430
- steer: false,
520
+ type: "run/enqueue",
431
521
  message: {
432
522
  role: "user",
433
523
  parts: [{ type: "text", text: "queued follow-up" }],
@@ -436,14 +526,50 @@ describe("StatewireThread", () => {
436
526
  );
437
527
  await waitFor(() =>
438
528
  expect(aui().thread().composer().getState().queue).toMatchObject([
439
- { id: "q0", prompt: "queued follow-up" },
529
+ {
530
+ prompt: "queued follow-up",
531
+ parts: [{ type: "text", text: "queued follow-up" }],
532
+ },
533
+ ]),
534
+ );
535
+ });
536
+
537
+ it("steers by default when the composer sends mid-run", async () => {
538
+ const server = createServer();
539
+ const { aui } = mountThread({
540
+ transport: server.transport,
541
+ converter: queueConverter,
542
+ });
543
+
544
+ aui().thread().append("hello");
545
+ await waitFor(() =>
546
+ expect(aui().thread().getState().isRunning).toBe(true),
547
+ );
548
+
549
+ aui().thread().composer().setText("steer me");
550
+ aui().thread().composer().send();
551
+
552
+ await waitFor(() =>
553
+ expect(server.received.at(-1)).toMatchObject({
554
+ type: "run/steer",
555
+ message: {
556
+ id: expect.any(String),
557
+ role: "user",
558
+ parts: [{ type: "text", text: "steer me" }],
559
+ },
560
+ }),
561
+ );
562
+ await waitFor(() =>
563
+ expect(aui().thread().composer().getState().queue).toMatchObject([
564
+ { prompt: "steer me" },
440
565
  ]),
441
566
  );
442
567
  });
443
568
 
444
- it("sends item controls as queue commands", async () => {
569
+ it("projects the steer lane ahead of the regular lane", async () => {
445
570
  const server = createServer({
446
- queue: [{ id: "q1", prompt: "queued" }],
571
+ queue: [textEntry("q1", "first"), textEntry("q2", "second")],
572
+ steerQueue: [textEntry("s1", "urgent")],
447
573
  });
448
574
  const { aui } = mountThread({
449
575
  transport: server.transport,
@@ -451,32 +577,88 @@ describe("StatewireThread", () => {
451
577
  });
452
578
 
453
579
  await waitFor(() =>
454
- expect(aui().thread().composer().getState().queue).toHaveLength(1),
580
+ expect(aui().thread().composer().getState().queue).toMatchObject([
581
+ { id: "s1", prompt: "urgent" },
582
+ { id: "q1", prompt: "first" },
583
+ { id: "q2", prompt: "second" },
584
+ ]),
585
+ );
586
+ });
587
+
588
+ it("sends item controls as run/* commands with placement", async () => {
589
+ const server = createServer({
590
+ queue: [textEntry("q1", "first"), textEntry("q2", "second")],
591
+ steerQueue: [textEntry("s1", "urgent")],
592
+ });
593
+ const { aui } = mountThread({
594
+ transport: server.transport,
595
+ converter: queueConverter,
596
+ });
597
+
598
+ await waitFor(() =>
599
+ expect(aui().thread().composer().getState().queue).toHaveLength(3),
600
+ );
601
+
602
+ aui().thread().composer().queueItem({ id: "q1" }).steer();
603
+ await waitFor(() =>
604
+ expect(server.received).toContainEqual({
605
+ type: "run/steer",
606
+ messageId: "q1",
607
+ insertAfter: null,
608
+ }),
609
+ );
610
+ await waitFor(() =>
611
+ expect(server.cell.state!.steerQueue.map((e) => e.id)).toEqual([
612
+ "q1",
613
+ "s1",
614
+ ]),
615
+ );
616
+
617
+ // no lane: repositions within the item's current lane
618
+ aui()
619
+ .thread()
620
+ .composer()
621
+ .queueItem({ id: "s1" })
622
+ .move({ insertBefore: null });
623
+ await waitFor(() =>
624
+ expect(server.received).toContainEqual({
625
+ type: "run/steer",
626
+ messageId: "s1",
627
+ insertBefore: null,
628
+ }),
455
629
  );
456
630
 
457
- aui().thread().composer().queueItem({ index: 0 }).steer();
631
+ aui()
632
+ .thread()
633
+ .composer()
634
+ .queueItem({ id: "q1" })
635
+ .move({ lane: "queue", insertAfter: "q2" });
458
636
  await waitFor(() =>
459
637
  expect(server.received).toContainEqual({
460
- type: "steer-queue-item",
461
- queueItemId: "q1",
638
+ type: "run/enqueue",
639
+ messageId: "q1",
640
+ insertAfter: "q2",
462
641
  }),
463
642
  );
643
+ await waitFor(() =>
644
+ expect(server.cell.state!.queue.map((e) => e.id)).toEqual(["q2", "q1"]),
645
+ );
464
646
 
465
- aui().thread().composer().queueItem({ index: 0 }).remove();
647
+ aui().thread().composer().queueItem({ id: "q1" }).remove();
466
648
  await waitFor(() =>
467
649
  expect(server.received).toContainEqual({
468
- type: "remove-queue-item",
469
- queueItemId: "q1",
650
+ type: "run/dequeue",
651
+ messageId: "q1",
470
652
  }),
471
653
  );
472
654
  await waitFor(() =>
473
- expect(aui().thread().composer().getState().queue).toHaveLength(0),
655
+ expect(aui().thread().composer().getState().queue).toHaveLength(2),
474
656
  );
475
657
  });
476
658
 
477
- it("sends clear-queue on cancel", async () => {
659
+ it("leaves the host queue alone on cancel", async () => {
478
660
  const server = createServer({
479
- queue: [{ id: "q1", prompt: "queued" }],
661
+ queue: [textEntry("q1", "queued")],
480
662
  });
481
663
  const { aui } = mountThread({
482
664
  transport: server.transport,
@@ -490,17 +672,88 @@ describe("StatewireThread", () => {
490
672
 
491
673
  aui().thread().cancelRun();
492
674
 
675
+ await waitFor(() =>
676
+ expect(server.received).toContainEqual({ type: "run/cancel" }),
677
+ );
678
+ expect(server.cell.state!.queue.map((e) => e.id)).toEqual(["q1"]);
679
+ await waitFor(() =>
680
+ expect(aui().thread().composer().getState().queue).toHaveLength(1),
681
+ );
682
+ });
683
+
684
+ it("sends run/edit for message edits", async () => {
685
+ const server = createServer({
686
+ messages: [
687
+ { id: "h1", role: "user", text: "bad question" },
688
+ { id: "a1", role: "assistant", text: "bad answer" },
689
+ ],
690
+ });
691
+ const { aui } = mountThread({
692
+ transport: server.transport,
693
+ converter: queueConverter,
694
+ capabilities: { edit: true },
695
+ });
696
+
697
+ await waitFor(() =>
698
+ expect(threadTexts(aui)).toEqual(["bad question", "bad answer"]),
699
+ );
700
+
701
+ const composer = aui().thread().message({ id: "h1" }).composer();
702
+ composer.beginEdit();
703
+ await waitFor(() => expect(composer.getState().isEditing).toBe(true));
704
+ composer.setText("better question");
705
+ composer.send();
706
+
493
707
  await waitFor(() =>
494
708
  expect(server.received).toContainEqual({
495
- type: "clear-queue",
496
- reason: "cancel-run",
709
+ type: "run/edit",
710
+ sourceId: "h1",
711
+ message: {
712
+ id: expect.any(String),
713
+ role: "user",
714
+ parts: [{ type: "text", text: "better question" }],
715
+ },
497
716
  }),
498
717
  );
718
+ const command = server.received.at(-1) as StatewireThread.RunEditCommand;
719
+ expect(command.message.id).not.toBe("h1");
720
+ });
721
+
722
+ it("dispatches run/continue from resumeRun under the continue capability", async () => {
723
+ const server = createServer();
724
+ const { aui } = mountThread({
725
+ transport: server.transport,
726
+ converter: queueConverter,
727
+ capabilities: { continue: true },
728
+ });
729
+
730
+ await waitFor(() =>
731
+ expect(aui().thread().getState().isLoading).toBe(false),
732
+ );
733
+
734
+ aui().thread().resumeRun({ parentId: null });
735
+
499
736
  await waitFor(() =>
500
- expect(server.received).toContainEqual({ type: "cancel" }),
737
+ expect(server.received).toContainEqual({ type: "run/continue" }),
501
738
  );
502
739
  await waitFor(() =>
503
- expect(aui().thread().composer().getState().queue).toHaveLength(0),
740
+ expect(aui().thread().getState().isRunning).toBe(true),
741
+ );
742
+ });
743
+
744
+ it("rejects resumeRun without the continue capability", async () => {
745
+ const server = createServer();
746
+ const { aui } = mountThread({
747
+ transport: server.transport,
748
+ converter: queueConverter,
749
+ });
750
+
751
+ await waitFor(() =>
752
+ expect(aui().thread().getState().isLoading).toBe(false),
753
+ );
754
+
755
+ expect(() => aui().thread().resumeRun({ parentId: null })).toThrow(
756
+ /does not support resuming/,
504
757
  );
505
758
  });
506
759
  });
@@ -520,7 +773,7 @@ describe("StatewireThread", () => {
520
773
 
521
774
  await waitFor(() =>
522
775
  expect(server.received).toContainEqual({
523
- type: "cancel",
776
+ type: "run/cancel",
524
777
  payload: { reason: "user-stop", surface: "test" },
525
778
  }),
526
779
  );
@@ -558,6 +811,7 @@ describe("StatewireThread", () => {
558
811
  messages: [],
559
812
  running: false,
560
813
  queue: [],
814
+ steerQueue: [],
561
815
  });
562
816
  const { aui } = mountThread({
563
817
  transport: mock.transport,
@@ -590,6 +844,7 @@ describe("StatewireThread", () => {
590
844
  messages: [],
591
845
  running: false,
592
846
  queue: [],
847
+ steerQueue: [],
593
848
  });
594
849
  const { aui } = mountThread({
595
850
  transport: mock.transport,