@assistant-ui/react-statewire 0.1.0 → 0.1.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/types.d.ts CHANGED
@@ -37,7 +37,26 @@ type AddToolResultCommand = {
37
37
  readonly artifact?: ReadonlyJSONValue;
38
38
  readonly modelContent?: readonly ToolModelContentPart[];
39
39
  };
40
- type AssistantTransportCommand = AddMessageCommand | AddToolResultCommand | UserCommands;
40
+ type EnqueueMessageCommand = {
41
+ readonly type: "enqueue-message";
42
+ readonly message: UserMessage | AssistantMessage;
43
+ readonly parentId: string | null;
44
+ readonly sourceId: string | null;
45
+ readonly steer: boolean;
46
+ };
47
+ type SteerQueueItemCommand = {
48
+ readonly type: "steer-queue-item";
49
+ readonly queueItemId: string;
50
+ };
51
+ type RemoveQueueItemCommand = {
52
+ readonly type: "remove-queue-item";
53
+ readonly queueItemId: string;
54
+ };
55
+ type ClearQueueCommand = {
56
+ readonly type: "clear-queue";
57
+ readonly reason: "edit" | "reload" | "cancel-run";
58
+ };
59
+ type AssistantTransportCommand = AddMessageCommand | AddToolResultCommand | EnqueueMessageCommand | SteerQueueItemCommand | RemoveQueueItemCommand | ClearQueueCommand | UserCommands;
41
60
  type AssistantTransportState = {
42
61
  readonly messages: readonly ThreadMessage[];
43
62
  readonly state?: ReadonlyJSONValue;
@@ -89,11 +108,16 @@ type AssistantTransportOptions<T> = {
89
108
  }) => void) | undefined;
90
109
  capabilities?: {
91
110
  edit?: boolean | undefined;
111
+ /**
112
+ * Buffer messages sent during a run in an in-memory queue and dispatch
113
+ * them once the run settles. Steering interrupts the active run.
114
+ */
115
+ queue?: boolean | undefined;
92
116
  } | undefined;
93
117
  adapters?: {
94
118
  attachments?: AttachmentAdapter | undefined;
95
119
  } | undefined;
96
120
  };
97
121
  //#endregion
98
- export { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, HeadersValue, ImagePart, SendCommandsRequestBody, TextPart, UserCommands, UserExternalState, UserMessage, UserMessagePart };
122
+ export { AddMessageCommand, AddToolResultCommand, AssistantMessage, AssistantTransportCommand, AssistantTransportConnectionMetadata, AssistantTransportOptions, AssistantTransportProtocol, AssistantTransportState, AssistantTransportStateConverter, ClearQueueCommand, EnqueueMessageCommand, HeadersValue, ImagePart, RemoveQueueItemCommand, SendCommandsRequestBody, SteerQueueItemCommand, TextPart, UserCommands, UserExternalState, UserMessage, UserMessagePart };
99
123
  //# sourceMappingURL=types.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,kBAAkB,WAAW;KAE7B;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,SAAS,cAAc;WACvB;WACA;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB,4BACR,oBACA,uBACA;KAEQ;WACD,mBAAmB;WACnB,QAAQ;WACR;;KAGC;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;EAGN;IAEM,cAAc"}
1
+ {"version":3,"file":"types.d.ts","names":[],"sources":["../src/types.ts"],"mappings":";;;;;KAWY,eAAe,UAAU,eAAe,UAAU;KAClD,0BAA0B,UAAU,8BAC5C,0BACA,UAAU,oBAAoB,UAAU;KAEhC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,kBAAkB,WAAW;KAE7B;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,gBAAgB;;KAGf;WACD;WACA,SAAS,cAAc;WACvB;WACA;;KAGC;WACD;WACA;WACA;WACA,QAAQ;WACR;WACA,WAAW;WACX,wBAAwB;;KAGvB;WACD;WACA,SAAS,cAAc;WACvB;WACA;WACA;;KAGC;WACD;WACA;;KAGC;WACD;WACA;;KAGC;WACD;WACA;;KAGC,4BACR,oBACA,uBACA,wBACA,wBACA,yBACA,oBACA;KAEQ;WACD,mBAAmB;WACnB,QAAQ;WACR;;KAGC;EACV,iBAAiB;EACjB;EACA,cAAc,eAAe;;KAGnB,iCAAiC,MAC3C,OAAO,GACP,oBAAoB,yCACjB;KAEO,eAAe,yBAAyB;KAExC;KAEA;EACV,UAAU;EACV;EACA;EACA,OAAO;EACP,cAAc;EACd,QAAQ;EACR;EACA;GACC;;KAGS,0BAA0B;EACpC,cAAc;EACd,WAAW,iCAAiC;EAC5C;EACA;EACA,WAAW;EACX,SAAS,sBAAsB,QAAQ;EACvC,uBAAuB;;EAEvB,+BAEM,MAAM,4BACH,0BAA0B,QAAQ;EAE3C,eAAe,UAAU;EACzB;EACA,YAEM,OAAO,OACP;IACE,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;eAE7B;;;;;EAMhB,aACM;IACA,UAAU;IACV,cAAc,UAAU,OAAO,MAAM;IACrC,QAAQ;;EAGd;IAEM;;;;;IAKA;;EAGN;IAEM,cAAc"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -34,7 +34,7 @@
34
34
  "@assistant-ui/store": "^0.3.0",
35
35
  "@assistant-ui/tap": "^0.9.7",
36
36
  "assistant-stream": "^0.3.33",
37
- "statewire": "^0.0.3"
37
+ "statewire": "^0.0.4"
38
38
  },
39
39
  "peerDependencies": {
40
40
  "@assistant-ui/react": ">=0.14.0",
@@ -1,4 +1,11 @@
1
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
1
+ import {
2
+ useCallback,
3
+ useEffect,
4
+ useMemo,
5
+ useRef,
6
+ useState,
7
+ useSyncExternalStore,
8
+ } from "react";
2
9
  import { resource, useResource } from "@assistant-ui/tap";
3
10
  import type { ResourceElement } from "@assistant-ui/tap";
4
11
  import { ExternalThread } from "@assistant-ui/react";
@@ -8,9 +15,12 @@ import {
8
15
  useAssistantClientRef,
9
16
  } from "@assistant-ui/store";
10
17
  import type { ClientOutput } from "@assistant-ui/store";
18
+ import { createMessageQueue } from "@assistant-ui/core";
11
19
  import type {
12
20
  AddToolResultOptions,
13
21
  AppendMessage,
22
+ MessageQueueController,
23
+ MessageQueueDriver,
14
24
  ResumeToolCallOptions,
15
25
  ThreadMessage,
16
26
  ToolExecutionStatus,
@@ -35,6 +45,8 @@ import type {
35
45
  } from "./types";
36
46
 
37
47
  const EMPTY_TOOL_STATUSES: Record<string, ToolExecutionStatus> = {};
48
+ const EMPTY_QUEUE_ITEMS: MessageQueueController["adapter"]["items"] = [];
49
+ const subscribeNoop = () => () => {};
38
50
 
39
51
  export const symbolAssistantTransportExtras = Symbol(
40
52
  "assistant-transport-extras",
@@ -43,6 +55,7 @@ export const symbolAssistantTransportExtras = Symbol(
43
55
  export type AssistantTransportExtras = {
44
56
  [symbolAssistantTransportExtras]: true;
45
57
  sendCommand: (command: AssistantTransportCommand) => void;
58
+ reconnect: () => void;
46
59
  state: unknown;
47
60
  };
48
61
 
@@ -127,7 +140,7 @@ const useAssistantTransportThread = (
127
140
  const [queueCell] = useState(
128
141
  (): HostQueueCell => ({ current: { queued: [], inTransit: [] } }),
129
142
  );
130
- const { state, commands } = useStatewire<
143
+ const { state, commands, connection } = useStatewire<
131
144
  AssistantTransportHostState,
132
145
  AssistantTransportHostCommands
133
146
  >({
@@ -202,9 +215,10 @@ const useAssistantTransportThread = (
202
215
  (): AssistantTransportExtras => ({
203
216
  [symbolAssistantTransportExtras]: true,
204
217
  sendCommand: dispatch,
218
+ reconnect: connection.reconnect,
205
219
  state: agentState,
206
220
  }),
207
- [dispatch, agentState],
221
+ [dispatch, connection.reconnect, agentState],
208
222
  );
209
223
 
210
224
  const handleAppend = (message: AppendMessage) => {
@@ -224,6 +238,60 @@ const useAssistantTransportThread = (
224
238
  }
225
239
  };
226
240
 
241
+ const handleCancel = () => {
242
+ void toolInvocations.abort();
243
+ void commands.cancel().catch(() => {});
244
+ };
245
+
246
+ const driverRef = useRef<{
247
+ run: MessageQueueDriver["run"];
248
+ cancel: () => void;
249
+ }>(undefined as never);
250
+ driverRef.current = {
251
+ // the queued message was stamped with the head at enqueue time; restamp so
252
+ // it appends to the thread the finished run left behind
253
+ run: (message) =>
254
+ handleAppend({
255
+ ...message,
256
+ parentId: convertedRef.current.messages.at(-1)?.id ?? null,
257
+ }),
258
+ cancel: handleCancel,
259
+ };
260
+
261
+ const enableQueue = options.capabilities?.queue === true;
262
+ const queueRef = useRef<MessageQueueController | null>(null);
263
+ if (enableQueue && !queueRef.current) {
264
+ queueRef.current = createMessageQueue({
265
+ run: (message, opts) => driverRef.current.run(message, opts),
266
+ cancel: () => driverRef.current.cancel(),
267
+ });
268
+ } else if (!enableQueue && queueRef.current) {
269
+ queueRef.current.adapter.clear("cancel-run");
270
+ queueRef.current = null;
271
+ }
272
+ const messageQueue = queueRef.current;
273
+
274
+ // fresh view per snapshot: the controller mutates adapter.items in place,
275
+ // which a stable prop identity would hide from the thread resource
276
+ const queueItems = useSyncExternalStore(
277
+ messageQueue?.subscribe ?? subscribeNoop,
278
+ () => messageQueue?.adapter.items ?? EMPTY_QUEUE_ITEMS,
279
+ () => EMPTY_QUEUE_ITEMS,
280
+ );
281
+
282
+ // settled edge: the queue only advances once the host run loop has fully
283
+ // released (isSending), the converted state agrees, and no client tool from
284
+ // the finished run is still executing
285
+ const busy =
286
+ isSending || converted.isRunning || Object.keys(toolStatuses).length > 0;
287
+ const wasBusyRef = useRef(false);
288
+ useEffect(() => {
289
+ if (wasBusyRef.current === busy) return;
290
+ wasBusyRef.current = busy;
291
+ if (busy) messageQueue?.notifyBusy();
292
+ else messageQueue?.notifyIdle();
293
+ });
294
+
227
295
  return useResource(
228
296
  ExternalThread({
229
297
  messages: converted.messages as readonly ExternalThreadMessage[],
@@ -233,16 +301,16 @@ const useAssistantTransportThread = (
233
301
  extras,
234
302
  attachmentAdapter: options.adapters?.attachments,
235
303
  onNew: handleAppend,
304
+ ...(messageQueue && {
305
+ queue: { ...messageQueue.adapter, items: queueItems },
306
+ }),
236
307
  ...(options.capabilities?.edit && { onEdit: handleAppend }),
237
308
  onReload: (parentId: string | null) => {
238
309
  void toolInvocations.abort().then(() => {
239
310
  void commands.reload(parentId).catch(() => {});
240
311
  });
241
312
  },
242
- onCancel: () => {
243
- void toolInvocations.abort();
244
- void commands.cancel().catch(() => {});
245
- },
313
+ onCancel: handleCancel,
246
314
  onResume: () => {
247
315
  if (!options.resumeApi)
248
316
  throw new Error("Must pass resumeApi to options to resume runs");
@@ -18,8 +18,16 @@ import {
18
18
  import type { StatewireHost } from "statewire/host";
19
19
  import { createMockTransport } from "statewire/testing";
20
20
  import { StatewireThread } from "./StatewireThread";
21
+ import { asAssistantTransportExtras } from "./AssistantTransportThread";
21
22
  import { useAssistantTransportState } from "./hooks";
22
- import type { AddMessageCommand, AssistantTransportCommand } from "./types";
23
+ import type {
24
+ AddMessageCommand,
25
+ AssistantTransportCommand,
26
+ ClearQueueCommand,
27
+ EnqueueMessageCommand,
28
+ RemoveQueueItemCommand,
29
+ SteerQueueItemCommand,
30
+ } from "./types";
23
31
  import {
24
32
  sendCommand,
25
33
  threadTexts,
@@ -29,9 +37,10 @@ import {
29
37
  type ServerState = {
30
38
  messages: { id: string; role: "user" | "assistant"; text: string }[];
31
39
  running: boolean;
40
+ queue: { id: string; prompt: string }[];
32
41
  };
33
42
 
34
- const textOf = (command: AddMessageCommand) =>
43
+ const textOf = (command: Pick<AddMessageCommand, "message">) =>
35
44
  command.message.parts
36
45
  .flatMap((p) => (p.type === "text" ? [p.text] : []))
37
46
  .join("");
@@ -57,7 +66,10 @@ const converter: StatewireThread.StateConverter<ServerState> = (
57
66
  isRunning: state.running,
58
67
  });
59
68
 
60
- const createServer = (init?: { messages?: ServerState["messages"] }) => {
69
+ const createServer = (init?: {
70
+ messages?: ServerState["messages"];
71
+ queue?: ServerState["queue"];
72
+ }) => {
61
73
  const received: unknown[] = [];
62
74
  const cell: {
63
75
  state?: ServerState;
@@ -68,6 +80,7 @@ const createServer = (init?: { messages?: ServerState["messages"] }) => {
68
80
  const [state] = useStatewireState<ServerState>(() => ({
69
81
  messages: init?.messages ?? [],
70
82
  running: false,
83
+ queue: init?.queue ?? [],
71
84
  }));
72
85
  cell.state = state;
73
86
  const commands = useStatewireCommands({
@@ -86,10 +99,35 @@ const createServer = (init?: { messages?: ServerState["messages"] }) => {
86
99
  state.running = true;
87
100
  return undefined;
88
101
  },
89
- cancel: () => {
90
- received.push({ type: "cancel" });
102
+ cancel: (payload?: unknown) => {
103
+ received.push(
104
+ payload === undefined
105
+ ? { type: "cancel" }
106
+ : { type: "cancel", payload },
107
+ );
91
108
  state.running = false;
92
109
  },
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
+ },
93
131
  "reject-me": () => {
94
132
  throw new StatewireReject("nope");
95
133
  },
@@ -99,7 +137,7 @@ const createServer = (init?: { messages?: ServerState["messages"] }) => {
99
137
  return { transport, received, cell };
100
138
  };
101
139
 
102
- const INITIAL_STATE: ServerState = { messages: [], running: false };
140
+ const INITIAL_STATE: ServerState = { messages: [], running: false, queue: [] };
103
141
 
104
142
  const mountThread = (
105
143
  options: Omit<StatewireThread.Options<ServerState>, "initialState"> &
@@ -151,6 +189,7 @@ describe("StatewireThread", () => {
151
189
  const [state] = useStatewireState<ServerState>(() => ({
152
190
  messages: [{ id: "m1", role: "assistant", text: "welcome" }],
153
191
  running: false,
192
+ queue: [],
154
193
  }));
155
194
  const commands = useStatewireCommands({});
156
195
  return { state: attached ? state : undefined, commands };
@@ -159,6 +198,7 @@ describe("StatewireThread", () => {
159
198
  const initialState: ServerState = {
160
199
  messages: [{ id: "i1", role: "assistant", text: "local" }],
161
200
  running: false,
201
+ queue: [],
162
202
  };
163
203
  const observed: unknown[] = [];
164
204
  const Probe: FC = () => {
@@ -296,6 +336,7 @@ describe("StatewireThread", () => {
296
336
  const mock = createMockTransport<ServerState>({
297
337
  messages: [],
298
338
  running: false,
339
+ queue: [],
299
340
  });
300
341
  const { aui } = mountThread({
301
342
  transport: mock.transport,
@@ -319,6 +360,7 @@ describe("StatewireThread", () => {
319
360
  const mock = createMockTransport<ServerState>({
320
361
  messages: [],
321
362
  running: false,
363
+ queue: [],
322
364
  });
323
365
  const { aui } = mountThread({
324
366
  transport: mock.transport,
@@ -343,6 +385,7 @@ describe("StatewireThread", () => {
343
385
  const mock = createMockTransport<ServerState>({
344
386
  messages: [],
345
387
  running: false,
388
+ queue: [],
346
389
  });
347
390
  const { aui } = mountThread({ transport: mock.transport, converter });
348
391
  await waitFor(() =>
@@ -352,6 +395,137 @@ describe("StatewireThread", () => {
352
395
  });
353
396
  });
354
397
 
398
+ describe("message queue", () => {
399
+ const queueConverter: StatewireThread.StateConverter<ServerState> = (
400
+ state,
401
+ meta,
402
+ ) => ({
403
+ ...converter(state, meta),
404
+ queue: state.queue,
405
+ });
406
+
407
+ it("routes composer sends through enqueue-message while a run is active and mirrors the server queue", async () => {
408
+ const server = createServer();
409
+ const { aui } = mountThread({
410
+ transport: server.transport,
411
+ converter: queueConverter,
412
+ });
413
+
414
+ await waitFor(() =>
415
+ expect(aui().thread().getState().capabilities.queue).toBe(true),
416
+ );
417
+
418
+ aui().thread().append("hello");
419
+ await waitFor(() =>
420
+ expect(server.received).toMatchObject([{ type: "add-message" }]),
421
+ );
422
+ await waitFor(() =>
423
+ expect(aui().thread().getState().isRunning).toBe(true),
424
+ );
425
+
426
+ aui().thread().append("queued follow-up");
427
+ await waitFor(() =>
428
+ expect(server.received.at(-1)).toMatchObject({
429
+ type: "enqueue-message",
430
+ steer: false,
431
+ message: {
432
+ role: "user",
433
+ parts: [{ type: "text", text: "queued follow-up" }],
434
+ },
435
+ }),
436
+ );
437
+ await waitFor(() =>
438
+ expect(aui().thread().composer().getState().queue).toMatchObject([
439
+ { id: "q0", prompt: "queued follow-up" },
440
+ ]),
441
+ );
442
+ });
443
+
444
+ it("sends item controls as queue commands", async () => {
445
+ const server = createServer({
446
+ queue: [{ id: "q1", prompt: "queued" }],
447
+ });
448
+ const { aui } = mountThread({
449
+ transport: server.transport,
450
+ converter: queueConverter,
451
+ });
452
+
453
+ await waitFor(() =>
454
+ expect(aui().thread().composer().getState().queue).toHaveLength(1),
455
+ );
456
+
457
+ aui().thread().composer().queueItem({ index: 0 }).steer();
458
+ await waitFor(() =>
459
+ expect(server.received).toContainEqual({
460
+ type: "steer-queue-item",
461
+ queueItemId: "q1",
462
+ }),
463
+ );
464
+
465
+ aui().thread().composer().queueItem({ index: 0 }).remove();
466
+ await waitFor(() =>
467
+ expect(server.received).toContainEqual({
468
+ type: "remove-queue-item",
469
+ queueItemId: "q1",
470
+ }),
471
+ );
472
+ await waitFor(() =>
473
+ expect(aui().thread().composer().getState().queue).toHaveLength(0),
474
+ );
475
+ });
476
+
477
+ it("sends clear-queue on cancel", async () => {
478
+ const server = createServer({
479
+ queue: [{ id: "q1", prompt: "queued" }],
480
+ });
481
+ const { aui } = mountThread({
482
+ transport: server.transport,
483
+ converter: queueConverter,
484
+ });
485
+
486
+ aui().thread().append("hello");
487
+ await waitFor(() =>
488
+ expect(aui().thread().getState().isRunning).toBe(true),
489
+ );
490
+
491
+ aui().thread().cancelRun();
492
+
493
+ await waitFor(() =>
494
+ expect(server.received).toContainEqual({
495
+ type: "clear-queue",
496
+ reason: "cancel-run",
497
+ }),
498
+ );
499
+ await waitFor(() =>
500
+ expect(server.received).toContainEqual({ type: "cancel" }),
501
+ );
502
+ await waitFor(() =>
503
+ expect(aui().thread().composer().getState().queue).toHaveLength(0),
504
+ );
505
+ });
506
+ });
507
+
508
+ it("sends the cancelPayload with the cancel command", async () => {
509
+ const server = createServer();
510
+ const { aui } = mountThread({
511
+ transport: server.transport,
512
+ converter,
513
+ cancelPayload: () => ({ reason: "user-stop", surface: "test" }),
514
+ });
515
+
516
+ aui().thread().append("hello");
517
+ await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
518
+
519
+ aui().thread().cancelRun();
520
+
521
+ await waitFor(() =>
522
+ expect(server.received).toContainEqual({
523
+ type: "cancel",
524
+ payload: { reason: "user-stop", surface: "test" },
525
+ }),
526
+ );
527
+ });
528
+
355
529
  it("enables the edit capability from options", async () => {
356
530
  const server = createServer();
357
531
  const { aui } = mountThread({
@@ -364,4 +538,73 @@ describe("StatewireThread", () => {
364
538
  expect(aui().thread().getState().capabilities.edit).toBe(true),
365
539
  );
366
540
  });
541
+
542
+ describe("connection", () => {
543
+ const trackStatuses = (seen: string[]) => {
544
+ const trackingConverter: StatewireThread.StateConverter<ServerState> = (
545
+ state,
546
+ meta,
547
+ ) => {
548
+ if (seen.at(-1) !== meta.connection.status)
549
+ seen.push(meta.connection.status);
550
+ return converter(state, meta);
551
+ };
552
+ return trackingConverter;
553
+ };
554
+
555
+ it("projects connection transitions into the converter", async () => {
556
+ const seen: string[] = [];
557
+ const mock = createMockTransport<ServerState>({
558
+ messages: [],
559
+ running: false,
560
+ queue: [],
561
+ });
562
+ const { aui } = mountThread({
563
+ transport: mock.transport,
564
+ converter: trackStatuses(seen),
565
+ });
566
+
567
+ await waitFor(() =>
568
+ expect(aui().thread().getState().isLoading).toBe(false),
569
+ );
570
+ expect(seen).toEqual(["connecting", "live"]);
571
+
572
+ await mock.finish("superseded", "taken over");
573
+ await waitFor(() => expect(seen.at(-1)).toBe("gone"));
574
+ });
575
+
576
+ it("reports live without re-converting on a local transport", async () => {
577
+ const seen: string[] = [];
578
+ const server = createServer();
579
+ mountThread({
580
+ transport: server.transport,
581
+ converter: trackStatuses(seen),
582
+ });
583
+
584
+ await waitFor(() => expect(seen).toEqual(["live"]));
585
+ });
586
+
587
+ it("exposes reconnect through extras", async () => {
588
+ const seen: string[] = [];
589
+ const mock = createMockTransport<ServerState>({
590
+ messages: [],
591
+ running: false,
592
+ queue: [],
593
+ });
594
+ const { aui } = mountThread({
595
+ transport: mock.transport,
596
+ converter: trackStatuses(seen),
597
+ });
598
+
599
+ await waitFor(() =>
600
+ expect(aui().thread().getState().isLoading).toBe(false),
601
+ );
602
+ await mock.finish("superseded");
603
+ await waitFor(() => expect(seen.at(-1)).toBe("gone"));
604
+
605
+ asAssistantTransportExtras(aui().thread().getState().extras).reconnect();
606
+
607
+ await waitFor(() => expect(seen.at(-1)).toBe("reconnecting"));
608
+ });
609
+ });
367
610
  });