@assistant-ui/react-statewire 0.4.3 → 0.5.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.
Files changed (49) hide show
  1. package/dist/AssistantTransportThread.d.ts +193 -4
  2. package/dist/AssistantTransportThread.d.ts.map +1 -1
  3. package/dist/AssistantTransportThread.js +12 -16
  4. package/dist/AssistantTransportThread.js.map +1 -1
  5. package/dist/StatewireThread.d.ts +92 -11
  6. package/dist/StatewireThread.d.ts.map +1 -1
  7. package/dist/StatewireThread.js +74 -45
  8. package/dist/StatewireThread.js.map +1 -1
  9. package/dist/hooks.d.ts +8 -3
  10. package/dist/hooks.d.ts.map +1 -1
  11. package/dist/hooks.js +10 -1
  12. package/dist/hooks.js.map +1 -1
  13. package/dist/host.d.ts +5 -5
  14. package/dist/host.d.ts.map +1 -1
  15. package/dist/host.js.map +1 -1
  16. package/dist/index.d.ts +3 -38
  17. package/dist/index.js +2 -2
  18. package/dist/inputRequests.d.ts +4 -4
  19. package/dist/inputRequests.d.ts.map +1 -1
  20. package/dist/inputRequests.js.map +1 -1
  21. package/dist/runCommands.d.ts +8 -7
  22. package/dist/runCommands.d.ts.map +1 -1
  23. package/dist/runCommands.js +25 -11
  24. package/dist/runCommands.js.map +1 -1
  25. package/dist/runsOptimistic.d.ts +7 -0
  26. package/dist/runsOptimistic.d.ts.map +1 -0
  27. package/dist/runsOptimistic.js +92 -0
  28. package/dist/runsOptimistic.js.map +1 -0
  29. package/package.json +3 -3
  30. package/src/AssistantTransportThread.ts +267 -24
  31. package/src/StatewireThread.runs.test.tsx +405 -0
  32. package/src/StatewireThread.test.tsx +180 -3
  33. package/src/StatewireThread.ts +223 -80
  34. package/src/__tests__/testHelpers.tsx +11 -17
  35. package/src/athena.e2e.test.tsx +15 -19
  36. package/src/hooks.ts +19 -2
  37. package/src/host.ts +11 -13
  38. package/src/index.ts +2 -36
  39. package/src/inputRequests.ts +8 -6
  40. package/src/legacy-diff.test.tsx +4 -7
  41. package/src/runCommands.ts +42 -28
  42. package/src/runsOptimistic.test.ts +225 -0
  43. package/src/runsOptimistic.ts +164 -0
  44. package/src/transport.test.tsx +12 -16
  45. package/dist/index.d.ts.map +0 -1
  46. package/dist/types.d.ts +0 -189
  47. package/dist/types.d.ts.map +0 -1
  48. package/dist/types.js +0 -0
  49. package/src/types.ts +0 -255
@@ -13,8 +13,10 @@ import type {
13
13
  AppendMessage,
14
14
  AttachmentAdapter,
15
15
  ExternalThreadQueueAdapter,
16
+ FeedbackAdapter,
16
17
  ModelContext,
17
18
  RespondToToolApprovalOptions,
19
+ SpeechSynthesisAdapter,
18
20
  ThreadMessage,
19
21
  } from "@assistant-ui/core";
20
22
  import { toToolsJSONSchema } from "assistant-stream";
@@ -22,9 +24,13 @@ import type { ReadonlyJSONValue } from "assistant-stream/utils";
22
24
  import { useStatewire } from "statewire";
23
25
  import type { Statewire, StatewireClient } from "statewire";
24
26
  import { symbolAssistantTransportExtras } from "./AssistantTransportThread";
25
- import type { AssistantTransportExtras } from "./AssistantTransportThread";
27
+ import type {
28
+ AssistantTransportExtras,
29
+ AssistantTransportThread,
30
+ } from "./AssistantTransportThread";
26
31
  import {
27
32
  createRunQueueAdapter,
33
+ resolveEditCommand,
28
34
  resolveReloadCommand,
29
35
  toWireMessage,
30
36
  viewedLeafId,
@@ -33,10 +39,23 @@ import {
33
39
  resolveToolApprovalInput,
34
40
  resolveToolResultInput,
35
41
  } from "./inputRequests";
36
- import type { AssistantTransportCommand } from "./types";
42
+ import { runsOptimistic } from "./runsOptimistic";
37
43
 
38
44
  type AnyCommands = Record<string, (...args: any[]) => unknown>;
39
45
 
46
+ type AnyOptions =
47
+ | StatewireThread.Options<any>
48
+ | StatewireThread.RunsOptions<any>;
49
+
50
+ const READY_RUNS: StatewireThread.Runs = {
51
+ status: "ready",
52
+ runId: null,
53
+ queue: [],
54
+ steerQueue: [],
55
+ error: null,
56
+ runLeafMessageId: null,
57
+ };
58
+
40
59
  const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
41
60
  ...(context.system !== undefined && { system: context.system }),
42
61
  ...(context.tools !== undefined && {
@@ -48,44 +67,7 @@ const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
48
67
  ...(context.config !== undefined && { config: context.config }),
49
68
  });
50
69
 
51
- const withSessionLostFallback = (
52
- transport: StatewireThread.Transport<any>,
53
- latest: { current: StatewireThread.Options<any> },
54
- ): StatewireThread.Transport<any> => {
55
- const [transportOptions, ...rest] = transport.args as [
56
- Record<string, unknown>,
57
- ...unknown[],
58
- ];
59
- if (
60
- rest.length > 0 ||
61
- typeof transportOptions !== "object" ||
62
- transportOptions === null
63
- ) {
64
- throw new Error(
65
- "statewire: onCommandSessionLost requires a transport element that takes a single options object",
66
- );
67
- }
68
- const transportLevel = transportOptions.onCommandSessionLost as
69
- | ((command: StatewireClient.SessionLostCommand) => "replay" | void)
70
- | undefined;
71
- return {
72
- ...transport,
73
- args: [
74
- {
75
- ...transportOptions,
76
- onCommandSessionLost: (
77
- command: StatewireClient.SessionLostCommand,
78
- ): "replay" | void =>
79
- transportLevel?.(command) ??
80
- latest.current.onCommandSessionLost?.(command),
81
- },
82
- ],
83
- };
84
- };
85
-
86
- const useStatewireThread = (
87
- options: StatewireThread.Options<any>,
88
- ): ClientOutput<"thread"> => {
70
+ const useStatewireThread = (options: AnyOptions): ClientOutput<"thread"> => {
89
71
  const latest = useRef(options);
90
72
  latest.current = options;
91
73
 
@@ -101,21 +83,41 @@ const useStatewireThread = (
101
83
  ),
102
84
  );
103
85
 
86
+ const runsOption = options.runs;
87
+ const [runsSeam] = useState(() => runsOption !== undefined);
88
+ if (runsSeam !== (runsOption !== undefined))
89
+ throw new Error(
90
+ "statewire: the runs option must be stable — it was " +
91
+ (runsSeam ? "set" : "unset") +
92
+ " on first render and changed since",
93
+ );
94
+
104
95
  const {
105
96
  state: transportState,
106
97
  commands,
107
98
  connection,
108
99
  setContext,
109
100
  } = useStatewire<unknown, AnyCommands>({
110
- transport:
111
- options.onCommandSessionLost === undefined
112
- ? options.transport
113
- : withSessionLostFallback(options.transport, latest),
101
+ transport: options.transport,
102
+ ...(runsSeam && {
103
+ optimistic: (draft, command, ctx) => {
104
+ const runsOpt = latest.current.runs!;
105
+ runsOptimistic(runsOpt === true ? draft : runsOpt(draft), command, ctx);
106
+ (latest.current as StatewireThread.RunsOptions<unknown>).optimistic?.(
107
+ draft,
108
+ command,
109
+ ctx,
110
+ );
111
+ },
112
+ }),
114
113
  onCommandChange: (update, ctx) => {
115
114
  if (update.status === "acked" || update.status === "settled")
116
115
  retire(update.params[0]);
117
116
  latest.current.onCommandChange?.(update, ctx);
118
117
  },
118
+ onStateChange: (state, ctx) => latest.current.onStateChange?.(state, ctx),
119
+ onConnectionChange: (connection) =>
120
+ latest.current.onConnectionChange?.(connection),
119
121
  });
120
122
  const attached = transportState !== undefined;
121
123
  const state = attached ? transportState : options.initialState;
@@ -157,21 +159,50 @@ const useStatewireThread = (
157
159
  [commands, retire],
158
160
  );
159
161
 
162
+ const runs = useMemo((): StatewireThread.Runs | undefined => {
163
+ if (runsOption === undefined) return undefined;
164
+ const mount = (runsOption === true ? state : runsOption(state)) as
165
+ | StatewireThread.RunsState
166
+ | undefined;
167
+ const entry = mount?.runs?.[0];
168
+ return entry === undefined
169
+ ? READY_RUNS
170
+ : {
171
+ status: entry.status,
172
+ runId: entry.runId,
173
+ queue: entry.queue,
174
+ steerQueue: entry.steerQueue,
175
+ ...(entry.inputRequests !== undefined && {
176
+ inputRequests: entry.inputRequests,
177
+ }),
178
+ error: entry.error,
179
+ runLeafMessageId: entry.runLeafMessageId,
180
+ };
181
+ }, [runsOption, state]);
182
+
160
183
  const { converter } = options;
161
184
  const metadata = useMemo(
162
185
  (): StatewireThread.ConnectionMetadata => ({
163
186
  pendingCommands: [...pending],
164
187
  isSending: pending.length > 0,
165
188
  connection,
189
+ ...(runs !== undefined && { runs }),
166
190
  }),
167
- [pending, connection],
191
+ [pending, connection, runs],
168
192
  );
169
193
  const converted = useMemo(
170
- () => converter(state, metadata),
194
+ () =>
195
+ converter(
196
+ state,
197
+ metadata as StatewireThread.ConnectionMetadata & {
198
+ runs: StatewireThread.Runs;
199
+ },
200
+ ) as StatewireThread.State,
171
201
  [converter, state, metadata],
172
202
  );
173
- const queueItems = converted.queue;
174
- const steerQueueItems = converted.steerQueue;
203
+ const queueItems = runs !== undefined ? runs.queue : converted.queue;
204
+ const steerQueueItems =
205
+ runs !== undefined ? runs.steerQueue : converted.steerQueue;
175
206
  if (steerQueueItems !== undefined && queueItems === undefined)
176
207
  throw new Error(
177
208
  "statewire: the converter's steerQueue projection requires the queue projection",
@@ -199,7 +230,8 @@ const useStatewireThread = (
199
230
  [converted.messages, queueItems, steerQueueItems, dispatch],
200
231
  );
201
232
 
202
- const inputRequests = converted.inputRequests;
233
+ const inputRequests =
234
+ runs !== undefined ? (runs.inputRequests ?? []) : converted.inputRequests;
203
235
  const [inputSeam] = useState(() => ({
204
236
  present: inputRequests !== undefined,
205
237
  }));
@@ -217,16 +249,21 @@ const useStatewireThread = (
217
249
  reconnect: connection.reconnect,
218
250
  state,
219
251
  ...(inputRequests !== undefined && { inputRequests }),
252
+ ...(runs !== undefined && { runs }),
220
253
  }),
221
- [dispatch, connection.reconnect, state, inputRequests],
254
+ [dispatch, connection.reconnect, state, inputRequests, runs],
222
255
  );
223
256
 
224
257
  const handleAppend = (message: AppendMessage) => {
225
- dispatch({
226
- type: "run/steer",
227
- message: toWireMessage(message, crypto.randomUUID()),
228
- anchorMessageId: viewedLeafId(converted.messages),
229
- });
258
+ dispatch(
259
+ message.sourceId != null
260
+ ? resolveEditCommand(message)
261
+ : {
262
+ type: "run/steer",
263
+ message: toWireMessage(message, crypto.randomUUID()),
264
+ anchorMessageId: viewedLeafId(converted.messages),
265
+ },
266
+ );
230
267
  };
231
268
 
232
269
  const handleReload = (parentId: string | null) => {
@@ -234,23 +271,20 @@ const useStatewireThread = (
234
271
  };
235
272
 
236
273
  const handleEdit = (message: AppendMessage) => {
237
- if (message.sourceId == null)
238
- throw new Error("statewire: run/edit requires a sourceId");
239
- dispatch({
240
- type: "run/edit",
241
- message: toWireMessage(message, crypto.randomUUID()),
242
- sourceId: message.sourceId,
243
- });
274
+ dispatch(resolveEditCommand(message));
244
275
  };
245
276
 
246
277
  return useResource(
247
278
  ExternalThread({
248
279
  messages: converted.messages as readonly ExternalThreadMessage[],
249
- isRunning: converted.isRunning,
280
+ isRunning:
281
+ runs !== undefined ? runs.status === "running" : converted.isRunning,
250
282
  isLoading: !attached,
251
283
  state: converted.state,
252
284
  extras,
253
285
  attachmentAdapter: options.adapters?.attachments,
286
+ speechAdapter: options.adapters?.speech,
287
+ feedbackAdapter: options.adapters?.feedback,
254
288
  onNew: handleAppend,
255
289
  ...(queue && { queue }),
256
290
  ...(options.capabilities?.edit && { onEdit: handleEdit }),
@@ -273,9 +307,14 @@ const useStatewireThread = (
273
307
  Array.isArray(payload))
274
308
  )
275
309
  throw new Error("statewire: stopPayload must return a plain object");
276
- void commands["run/stop"]!(
277
- ...(payload === undefined ? [] : [payload]),
278
- ).catch((error: Error) => {
310
+ const runId = runs !== undefined ? runs.runId : converted.runId;
311
+ const args =
312
+ runId === undefined
313
+ ? payload === undefined
314
+ ? []
315
+ : [payload]
316
+ : [{ ...payload, runId }];
317
+ void commands["run/stop"]!(...args).catch((error: Error) => {
279
318
  latest.current.onError?.(error);
280
319
  });
281
320
  },
@@ -283,10 +322,15 @@ const useStatewireThread = (
283
322
  );
284
323
  };
285
324
 
286
- export const StatewireThread = <T>(
287
- options: StatewireThread.Options<T>,
288
- ): ResourceElement<ClientOutput<"thread">> =>
289
- resource(useStatewireThread)(options as StatewireThread.Options<any>);
325
+ export const StatewireThread: {
326
+ <T>(
327
+ options: StatewireThread.RunsOptions<T>,
328
+ ): ResourceElement<ClientOutput<"thread">>;
329
+ <T>(
330
+ options: StatewireThread.Options<T>,
331
+ ): ResourceElement<ClientOutput<"thread">>;
332
+ } = (options: AnyOptions): ResourceElement<ClientOutput<"thread">> =>
333
+ resource(useStatewireThread)(options);
290
334
 
291
335
  export namespace StatewireThread {
292
336
  export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;
@@ -419,7 +463,7 @@ export namespace StatewireThread {
419
463
  | RunReloadCommand
420
464
  | RunInputCommand;
421
465
 
422
- export type Command = AssistantTransportCommand | RunCommand;
466
+ export type Command = AssistantTransportThread.Command | RunCommand;
423
467
 
424
468
  /** A queued message projected out of the host state, wire shape. */
425
469
  export type QueueItem = {
@@ -431,6 +475,8 @@ export namespace StatewireThread {
431
475
  readonly messages: readonly ThreadMessage[];
432
476
  readonly state?: ReadonlyJSONValue;
433
477
  readonly isRunning: boolean;
478
+ /** The live run's id projected out of the host state; stamped onto `run/stop`. */
479
+ readonly runId?: string | null;
434
480
  /**
435
481
  * The host's regular queue lane projected out of the state. Returning it
436
482
  * (even empty) turns on the queue capability: sends become `run/enqueue`
@@ -449,11 +495,67 @@ export namespace StatewireThread {
449
495
  readonly inputRequests?: readonly InputRequestState[];
450
496
  };
451
497
 
498
+ /** Run subsystem status replicated by the host. */
499
+ export type RunStatus =
500
+ | "ready"
501
+ | "running"
502
+ | "stopped"
503
+ | "error"
504
+ | "input-required";
505
+
506
+ /** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
507
+ export type RunsQueueEntry = UserMessage & {
508
+ /** Host-stamped opaque per-entry metadata. */
509
+ readonly meta?: ReadonlyJSONValue;
510
+ };
511
+
512
+ /** The replicated run error — set on an unhandled failure, cleared by the next user-initiated run. */
513
+ export type RunsError = {
514
+ readonly message: string;
515
+ readonly [key: string]: ReadonlyJSONValue | undefined;
516
+ };
517
+
518
+ /** A replicated run entry — one element of the mount's `runs` array. */
519
+ export type RunState = {
520
+ /** The run's identity — minted at dispatch, persists through input-required, null in error/stop. */
521
+ readonly runId: string | null;
522
+ readonly status: Exclude<RunStatus, "ready">;
523
+ readonly queue: readonly RunsQueueEntry[];
524
+ readonly steerQueue: readonly RunsQueueEntry[];
525
+ /** The parked pending set; present only in input-required. */
526
+ readonly inputRequests?: readonly InputRequestState[];
527
+ readonly error: RunsError | null;
528
+ readonly runLeafMessageId: string | null;
529
+ };
530
+
531
+ /** The runs mount as replicated: the run entries plus the top-level status projection. */
532
+ export type RunsState = {
533
+ /** Projection of `runs[0]?.status ?? "ready"`. */
534
+ readonly status: RunStatus;
535
+ /** At most one entry; empty while resting. */
536
+ readonly runs: readonly RunState[];
537
+ };
538
+
539
+ /** The run subsystem's typed read — `runs[0]` of the selected mount with unsettled commands folded in, ready defaults while resting. */
540
+ export type Runs = {
541
+ readonly status: RunStatus;
542
+ /** The live run's id — non-null in running and input-required; stamped onto `run/stop`. */
543
+ readonly runId: string | null;
544
+ readonly queue: readonly RunsQueueEntry[];
545
+ readonly steerQueue: readonly RunsQueueEntry[];
546
+ /** The parked pending set; present only in input-required. */
547
+ readonly inputRequests?: readonly InputRequestState[];
548
+ readonly error: RunsError | null;
549
+ readonly runLeafMessageId: string | null;
550
+ };
551
+
452
552
  export type ConnectionMetadata = {
453
553
  pendingCommands: Command[];
454
554
  isSending: boolean;
455
555
  /** Statewire connection status; local transports are always `live`. */
456
556
  connection: StatewireClient.ConnectionState;
557
+ /** The typed runs read; present iff the `runs` option is set. */
558
+ runs?: Runs;
457
559
  };
458
560
 
459
561
  export type StateConverter<T> = (
@@ -461,6 +563,17 @@ export namespace StatewireThread {
461
563
  connectionMetadata: ConnectionMetadata,
462
564
  ) => State;
463
565
 
566
+ /** Converter output in runs mode: app-owned keys only — the lib projects the run mounts itself. */
567
+ export type RunsConverterState = {
568
+ readonly messages: readonly ThreadMessage[];
569
+ readonly state?: ReadonlyJSONValue;
570
+ };
571
+
572
+ export type RunsStateConverter<T> = (
573
+ state: T,
574
+ connectionMetadata: ConnectionMetadata & { runs: Runs },
575
+ ) => RunsConverterState;
576
+
464
577
  /**
465
578
  * Payload of the built-in `run/stop` command. `reason` is the one well-known
466
579
  * field; apps extend it with their own JSON-serializable fields.
@@ -474,6 +587,7 @@ export namespace StatewireThread {
474
587
  transport: Transport<T>;
475
588
  initialState: T;
476
589
  converter: StateConverter<T>;
590
+ runs?: undefined;
477
591
  /**
478
592
  * "command-send" mirrors the client's ambient model context (system,
479
593
  * tools, callSettings, config) to the server over the command channel —
@@ -482,15 +596,6 @@ export namespace StatewireThread {
482
596
  contextSync?: "command-send" | undefined;
483
597
  /** Supplies the `run/stop` command's payload; omitted, stop sends no payload. */
484
598
  stopPayload?: (() => StopPayload) | undefined;
485
- /**
486
- * Offered each pending command when a remote transport's session is
487
- * evicted; return "replay" to re-enqueue it under the rotated client id.
488
- * A callback set on the transport options is consulted first; this one
489
- * runs for commands it declined.
490
- */
491
- onCommandSessionLost?:
492
- | ((command: StatewireClient.SessionLostCommand) => "replay" | void)
493
- | undefined;
494
599
  /** Observes each command's lifecycle (queued, posted, acked, settled); runs after the built-in pending-command retirement. */
495
600
  onCommandChange?:
496
601
  | ((
@@ -500,6 +605,14 @@ export namespace StatewireThread {
500
605
  ctx: { state: NonNullable<T> },
501
606
  ) => void)
502
607
  | undefined;
608
+ /** Observes the transport state: fires with the attach snapshot, then once per change. */
609
+ onStateChange?:
610
+ | ((state: NonNullable<T>, ctx: { changes: Statewire.Changes }) => void)
611
+ | undefined;
612
+ /** Observes connection status transitions, starting with the initial status. */
613
+ onConnectionChange?:
614
+ | ((connection: StatewireClient.Connection) => void)
615
+ | undefined;
503
616
  onError?: ((error: Error) => void) | undefined;
504
617
  capabilities?:
505
618
  | {
@@ -513,9 +626,39 @@ export namespace StatewireThread {
513
626
  adapters?:
514
627
  | {
515
628
  attachments?: AttachmentAdapter | undefined;
629
+ speech?: SpeechSynthesisAdapter | undefined;
630
+ feedback?: FeedbackAdapter | undefined;
516
631
  }
517
632
  | undefined;
518
633
  };
634
+
635
+ /** Options with the runs read enabled: the lib types the run mounts and the converter returns app-owned keys only. */
636
+ export type RunsOptions<T> = Omit<Options<T>, "converter" | "runs"> & {
637
+ /** `true` reads the run mounts off the state root; a selector picks a nested mount. */
638
+ runs: true | ((state: T) => unknown);
639
+ converter: RunsStateConverter<T>;
640
+ /** Folds app-owned keys for an unsettled command into the draft; runs after the lib's run-dialect reducer. */
641
+ optimistic?:
642
+ | StatewireClient.Optimistic<
643
+ T,
644
+ Record<string, (...args: any[]) => unknown>
645
+ >
646
+ | undefined;
647
+ };
648
+ }
649
+
650
+ declare module "@assistant-ui/react" {
651
+ namespace Assistant {
652
+ interface Commands {
653
+ runEnqueue: StatewireThread.RunEnqueueCommand;
654
+ runSteer: StatewireThread.RunSteerCommand;
655
+ runDequeue: StatewireThread.RunDequeueCommand;
656
+ runEdit: StatewireThread.RunEditCommand;
657
+ runContinue: StatewireThread.RunContinueCommand;
658
+ runReload: StatewireThread.RunReloadCommand;
659
+ runInput: StatewireThread.RunInputCommand;
660
+ }
661
+ }
519
662
  }
520
663
 
521
664
  // Scope transforms are keyed by the underlying hook, not the resource wrapper.
@@ -7,13 +7,6 @@ import {
7
7
  asAssistantTransportExtras,
8
8
  AssistantTransportThread,
9
9
  } from "../AssistantTransportThread";
10
- import type {
11
- AssistantTransportCommand,
12
- AssistantTransportConnectionMetadata,
13
- AssistantTransportOptions,
14
- AssistantTransportStateConverter,
15
- InputRequestState,
16
- } from "../types";
17
10
 
18
11
  export type TestState = {
19
12
  messages: { id: string; role: "user" | "assistant"; text: string }[];
@@ -39,10 +32,9 @@ export const toThreadMessage = (m: {
39
32
  }),
40
33
  }) as unknown as ExternalThreadMessage;
41
34
 
42
- export const defaultConverter: AssistantTransportStateConverter<TestState> = (
43
- state,
44
- meta,
45
- ) => ({
35
+ export const defaultConverter: AssistantTransportThread.StateConverter<
36
+ TestState
37
+ > = (state, meta) => ({
46
38
  messages: [
47
39
  ...state.messages.map(toThreadMessage),
48
40
  ...meta.pendingCommands.flatMap((c, i) =>
@@ -139,7 +131,7 @@ export const abortableStream = (init: RequestInit) => {
139
131
  };
140
132
 
141
133
  export const mountThread = (
142
- options?: Partial<AssistantTransportOptions<TestState>>,
134
+ options?: Partial<AssistantTransportThread.Options<TestState>>,
143
135
  mountOpts?: {
144
136
  wrap?: (node: ReactElement) => ReactElement;
145
137
  children?: ReactNode;
@@ -175,7 +167,7 @@ export const mountThread = (
175
167
 
176
168
  export const sendCommand = (
177
169
  aui: () => ReturnType<typeof useAui>,
178
- command: AssistantTransportCommand,
170
+ command: AssistantTransportThread.Command,
179
171
  ) =>
180
172
  asAssistantTransportExtras(aui().thread().getState().extras).sendCommand(
181
173
  command,
@@ -190,11 +182,11 @@ export const threadTexts = (aui: () => ReturnType<typeof useAui>) =>
190
182
  );
191
183
 
192
184
  export const toolCallConverter = (
193
- metas: AssistantTransportConnectionMetadata[],
194
- ): AssistantTransportStateConverter<TestState> => {
185
+ metas: AssistantTransportThread.ConnectionMetadata[],
186
+ ): AssistantTransportThread.StateConverter<TestState> => {
195
187
  type ToolCallState = TestState & {
196
188
  toolCall?: { id: string; name: string; argsText: string };
197
- inputRequests?: InputRequestState[];
189
+ inputRequests?: AssistantTransportThread.InputRequestState[];
198
190
  };
199
191
  return (state, meta) => {
200
192
  metas.push(meta);
@@ -257,4 +249,6 @@ export const emitToolCall = (server: StreamResponse) => {
257
249
  };
258
250
 
259
251
  export const allCommands = (requests: RecordedRequest[]) =>
260
- requests.flatMap((r) => r.body.commands as AssistantTransportCommand[]);
252
+ requests.flatMap(
253
+ (r) => r.body.commands as AssistantTransportThread.Command[],
254
+ );
@@ -12,15 +12,7 @@ import { AuiProvider, useAui } from "@assistant-ui/store";
12
12
  import type { ExternalThreadMessage } from "@assistant-ui/react";
13
13
  import { AssistantTransportThread } from "./AssistantTransportThread";
14
14
  import { useAssistantTransportSendCommand } from "./hooks";
15
- import type {
16
- InputRequestState,
17
- RunEditCommand,
18
- RunSteerCommand,
19
- RunUserMessage,
20
- AssistantTransportCommand,
21
- AssistantTransportOptions,
22
- AssistantTransportStateConverter,
23
- } from "./types";
15
+
24
16
  import {
25
17
  createStreamResponse,
26
18
  installFetch,
@@ -40,7 +32,7 @@ type LangGraphMessage =
40
32
  type LangGraphState = {
41
33
  messages: LangGraphMessage[];
42
34
  todos: string[];
43
- inputRequests?: InputRequestState[];
35
+ inputRequests?: AssistantTransportThread.InputRequestState[];
44
36
  };
45
37
 
46
38
  const INITIAL_STATE: LangGraphState = { messages: [], todos: [] };
@@ -48,12 +40,15 @@ const INITIAL_STATE: LangGraphState = { messages: [], todos: [] };
48
40
  // Athena's optimistic dedup: each user-message command gets a stable
49
41
  // trackingId; the server echoes it on the human message, which retires the
50
42
  // optimistic copy without a flicker frame or a phantom duplicate.
51
- type UserMessageCommand = (RunSteerCommand | RunEditCommand) & {
52
- message: RunUserMessage;
43
+ type UserMessageCommand = (
44
+ | AssistantTransportThread.RunSteerCommand
45
+ | AssistantTransportThread.RunEditCommand
46
+ ) & {
47
+ message: AssistantTransportThread.RunUserMessage;
53
48
  };
54
49
 
55
50
  const isUserMessageCommand = (
56
- c: AssistantTransportCommand,
51
+ c: AssistantTransportThread.Command,
57
52
  ): c is UserMessageCommand =>
58
53
  (c.type === "run/steer" || c.type === "run/edit") && "message" in c;
59
54
 
@@ -69,7 +64,7 @@ const createConverter = () => {
69
64
  return id;
70
65
  };
71
66
 
72
- const converter: AssistantTransportStateConverter<LangGraphState> = (
67
+ const converter: AssistantTransportThread.StateConverter<LangGraphState> = (
73
68
  state,
74
69
  meta,
75
70
  ) => {
@@ -152,14 +147,14 @@ const createConverter = () => {
152
147
 
153
148
  const mountDeepAgent = () => {
154
149
  const { converter, trackingIdOf } = createConverter();
155
- const cancelled: AssistantTransportCommand[][] = [];
156
- const errored: AssistantTransportCommand[][] = [];
150
+ const cancelled: AssistantTransportThread.Command[][] = [];
151
+ const errored: AssistantTransportThread.Command[][] = [];
157
152
  const responses: (string | null)[] = [];
158
153
  let finishCount = 0;
159
154
 
160
155
  const captured: {
161
156
  aui?: ReturnType<typeof useAui>;
162
- sendCommand?: (command: AssistantTransportCommand) => void;
157
+ sendCommand?: (command: AssistantTransportThread.Command) => void;
163
158
  } = {};
164
159
  const Capture: FC = () => {
165
160
  captured.aui = useAui();
@@ -167,7 +162,7 @@ const mountDeepAgent = () => {
167
162
  return null;
168
163
  };
169
164
 
170
- const options: AssistantTransportOptions<LangGraphState> = {
165
+ const options: AssistantTransportThread.Options<LangGraphState> = {
171
166
  initialState: INITIAL_STATE,
172
167
  api: "https://sync.example.com/api/chat",
173
168
  resumeApi: "https://sync.example.com/api/resume",
@@ -243,7 +238,8 @@ const mountDeepAgent = () => {
243
238
  const utils = render(<App />);
244
239
  return {
245
240
  aui: () => captured.aui!,
246
- sendCommand: (c: AssistantTransportCommand) => captured.sendCommand!(c),
241
+ sendCommand: (c: AssistantTransportThread.Command) =>
242
+ captured.sendCommand!(c),
247
243
  cancelled,
248
244
  errored,
249
245
  responses,
package/src/hooks.ts CHANGED
@@ -2,17 +2,34 @@
2
2
 
3
3
  import { useAui, useAuiState } from "@assistant-ui/store";
4
4
  import { asAssistantTransportExtras } from "./AssistantTransportThread";
5
- import type { AssistantTransportCommand, UserExternalState } from "./types";
5
+ import type { Assistant } from "@assistant-ui/react";
6
+ import type { AssistantTransportThread } from "./AssistantTransportThread";
7
+ import type { StatewireThread } from "./StatewireThread";
8
+
9
+ type UserExternalState = keyof Assistant.ExternalState extends never
10
+ ? Record<string, unknown>
11
+ : Assistant.ExternalState[keyof Assistant.ExternalState];
6
12
 
7
13
  export const useAssistantTransportSendCommand = () => {
8
14
  const aui = useAui();
9
15
 
10
- return (command: AssistantTransportCommand) => {
16
+ return (command: AssistantTransportThread.Command) => {
11
17
  const extras = aui.thread().getState().extras;
12
18
  asAssistantTransportExtras(extras).sendCommand(command);
13
19
  };
14
20
  };
15
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
+
16
33
  export function useAssistantTransportState(): UserExternalState;
17
34
  export function useAssistantTransportState<T>(
18
35
  selector: (state: UserExternalState) => T,