@assistant-ui/react-statewire 0.34.0 → 0.35.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.
@@ -21,12 +21,21 @@ const insert = (lane, entry, { insertAfter, insertBefore }) => {
21
21
  const index = insertAfter !== void 0 ? insertAfter === null ? 0 : lane.findIndex((e) => e.id === insertAfter) + 1 : insertBefore === void 0 || insertBefore === null ? lane.length : lane.findIndex((e) => e.id === insertBefore);
22
22
  lane.splice(index < 0 ? lane.length : index, 0, entry);
23
23
  };
24
- const enqueueOrSteer = (draft, command, runId) => {
24
+ const BEHAVIORS = [
25
+ "auto",
26
+ "steer",
27
+ "preempt",
28
+ "queue"
29
+ ];
30
+ const send = (draft, command, runId) => {
25
31
  const run = draft.runs?.[0];
26
32
  const status = run?.status ?? "ready";
33
+ const behavior = command.behavior ?? "auto";
34
+ if (!BEHAVIORS.includes(behavior)) throw new Error(`statewire: unknown run/send behavior "${behavior}"`);
27
35
  const id = "message" in command ? command.message.id : command.messageId;
28
36
  if (run?.dispatching?.messages.some((e) => e.id === id)) return;
29
37
  const sourceLane = run === void 0 ? void 0 : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));
38
+ if (behavior === "auto" && "message" in command && sourceLane !== void 0) return;
30
39
  let entry;
31
40
  let sourceIndex = -1;
32
41
  if (sourceLane !== void 0) {
@@ -40,7 +49,7 @@ const enqueueOrSteer = (draft, command, runId) => {
40
49
  if (!("message" in command)) return;
41
50
  entry = laneEntry(command.message);
42
51
  }
43
- const steer = command.type === "run/steer";
52
+ const steer = behavior === "auto" ? status === "running" || status === "input-required" || run?.stopping != null : behavior !== "queue";
44
53
  if (steer ? status === "ready" || status === "input-required" : sourceLane === void 0 && (status === "ready" || (status === "stopped" || status === "error") && run !== void 0 && run.queue.length === 0 && run.steerQueue.length === 0)) {
45
54
  const trigger = status === "error" ? "error-continue" : status === "stopped" ? "stop-continue" : "message-send";
46
55
  const target = startRun(draft, runId);
@@ -64,6 +73,7 @@ const enqueueOrSteer = (draft, command, runId) => {
64
73
  if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);
65
74
  else insert(lane, entry, command);
66
75
  if (continues) startRun(draft, runId);
76
+ if (behavior === "preempt" && status === "running" && run.nextDispatch === void 0) run.stopping = { reason: "stop" };
67
77
  };
68
78
  const stageRewind = (run, dispatch) => {
69
79
  const staged = run.nextDispatch;
@@ -76,7 +86,7 @@ const runsOptimistic = (mount, command, ctx) => {
76
86
  const draft = mount;
77
87
  if (ctx.state === "held") {
78
88
  const params = command.params[0];
79
- if ((command.method === "run/enqueue" || command.method === "run/steer" || command.method === "run/edit") && params?.message !== void 0) (draft.runsHeld ??= []).push({
89
+ if ((command.method === "run/send" || command.method === "run/edit") && params?.message !== void 0) (draft.runsHeld ??= []).push({
80
90
  ...laneEntry(params.message),
81
91
  localMeta: ctx.localMeta
82
92
  });
@@ -84,9 +94,8 @@ const runsOptimistic = (mount, command, ctx) => {
84
94
  }
85
95
  const runId = command.params[0]?.runId ?? `optimistic-${ctx.seq ?? `q${ctx.ts}`}`;
86
96
  switch (command.method) {
87
- case "run/enqueue":
88
- case "run/steer":
89
- enqueueOrSteer(draft, command.params[0], runId);
97
+ case "run/send":
98
+ send(draft, command.params[0], runId);
90
99
  break;
91
100
  case "run/edit": {
92
101
  const { message, runAnchorMessageId } = command.params[0];
@@ -1 +1 @@
1
- {"version":3,"file":"runsOptimistic.js","names":["ReadonlyJSONValue","Statewire","StatewireClient","StatewireThread","Mutable","T","K","LaneEntry","RunsQueueEntry","Dispatch","RunsDispatch","RunEntry","RunState","RunsDraft","Partial","RunsState","HeldEntry","localMeta","laneEntry","message","UserMessage","parts","startRun","draft","runId","entry","runs","status","queue","steerQueue","error","inputRequests","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","id","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","messageId","dispatching","messages","some","sourceLane","find","l","sourceIndex","metadata","steer","type","direct","trigger","target","push","continues","Error","hasPlacement","stageRewind","dispatch","staged","nextDispatch","stopping","reason","runsOptimistic","mount","Command","Record","args","ctx","OptimisticContext","runsHeld","state","params","method","commandRunId","seq","ts","runAnchorMessageId","RunEditCommand","rollbackTo","RunReloadCommand","RunDequeueCommand","requestId","response","RunInputCommand","requests","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\n// Opaque payloads (meta, response, rollbackTo) stay readonly: only reassigned, never mutated.\ntype Mutable<T> = ReadonlyJSONValue extends T\n ? T\n : T extends object\n ? { -readonly [K in keyof T]: Mutable<T[K]> }\n : T;\n\ntype LaneEntry = Mutable<StatewireThread.RunsQueueEntry>;\ntype Dispatch = Mutable<StatewireThread.RunsDispatch>;\ntype RunEntry = Mutable<StatewireThread.RunState>;\ntype RunsDraft = Partial<Mutable<StatewireThread.RunsState>>;\ntype HeldEntry = LaneEntry & { localMeta: unknown };\n\nconst laneEntry = (message: StatewireThread.UserMessage): LaneEntry => ({\n ...message,\n parts: [...message.parts],\n});\n\nconst startRun = (draft: RunsDraft, runId: string): RunEntry => {\n const entry = ((draft.runs ??= [])[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n });\n entry.status = \"running\";\n // A live run keeps its identity; a mint folds the client-generated id.\n if (entry.runId === null) entry.runId = runId;\n delete entry.error;\n delete entry.inputRequests;\n draft.status = \"running\";\n return entry;\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst enqueueOrSteer = (\n draft: RunsDraft,\n command: StatewireThread.RunEnqueueCommand | StatewireThread.RunSteerCommand,\n runId: string,\n): void => {\n const run = draft.runs?.[0];\n // The entry status is the truth; hosts replicating the top-level projection agree.\n const status = run?.status ?? \"ready\";\n const id = \"message\" in command ? command.message.id : command.messageId;\n // In dispatch limbo the canonical state already tells the story: no fold.\n if (run?.dispatching?.messages.some((e) => e.id === id)) return;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = [...command.message.parts];\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = laneEntry(command.message);\n }\n\n const steer = command.type === \"run/steer\";\n const direct = steer\n ? status === \"ready\" || status === \"input-required\"\n : sourceLane === undefined &&\n (status === \"ready\" ||\n ((status === \"stopped\" || status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (direct) {\n const trigger =\n status === \"error\"\n ? \"error-continue\"\n : status === \"stopped\"\n ? \"stop-continue\"\n : \"message-send\";\n const target = startRun(draft, runId);\n if (steer) {\n // The whole steer lane rides the dispatch, in lane order.\n if (sourceLane === target.steerQueue)\n target.steerQueue.splice(sourceIndex, 0, entry);\n else target.steerQueue.push(entry);\n target.dispatching = {\n trigger,\n messages: target.steerQueue.splice(0),\n };\n } else target.dispatching = { trigger, messages: [entry] };\n return;\n }\n const continues = steer && status !== \"running\";\n\n if (run === undefined)\n throw new Error(\"statewire: non-direct fold without a run entry\");\n const lane = steer ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n if (continues) startRun(draft, runId);\n};\n\nconst stageRewind = (run: RunEntry, dispatch: Dispatch): void => {\n const staged = run.nextDispatch;\n if (\n staged?.trigger === \"message-edit\" &&\n dispatch.trigger === \"message-edit\"\n ) {\n staged.messages.push(...dispatch.messages);\n } else {\n run.nextDispatch = dispatch;\n }\n run.stopping = {\n reason: run.nextDispatch!.trigger as \"message-edit\" | \"message-reload\",\n };\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft & { runsHeld?: HeldEntry[] };\n // A held send waits in the outbox: it shows as held, never as a run.\n if (ctx.state === \"held\") {\n const params = command.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (\n (command.method === \"run/enqueue\" ||\n command.method === \"run/steer\" ||\n command.method === \"run/edit\") &&\n params?.message !== undefined\n )\n (draft.runsHeld ??= []).push({\n ...laneEntry(params.message),\n localMeta: ctx.localMeta,\n });\n return;\n }\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq ?? `q${ctx.ts}`}`;\n switch (command.method) {\n case \"run/enqueue\":\n case \"run/steer\": {\n enqueueOrSteer(\n draft,\n command.params[0] as\n | StatewireThread.RunEnqueueCommand\n | StatewireThread.RunSteerCommand,\n runId,\n );\n break;\n }\n case \"run/edit\": {\n const { message, runAnchorMessageId } = command\n .params[0] as StatewireThread.RunEditCommand;\n const dispatch: Dispatch = {\n trigger: \"message-edit\",\n messages: [laneEntry(message)],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/reload\": {\n const { runAnchorMessageId } = command\n .params[0] as StatewireThread.RunReloadCommand;\n const dispatch: Dispatch = {\n trigger: \"message-reload\",\n messages: [],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") {\n if (run.nextDispatch === undefined) stageRewind(run, dispatch);\n } else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/stop\": {\n const run = draft.runs?.[0];\n if (run?.status !== \"running\") break;\n if (run.nextDispatch === undefined) run.stopping = { reason: \"stop\" };\n break;\n }\n case \"run/continue\": {\n const run = draft.runs?.[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs?.[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs?.[0]?.inputRequests;\n if (requests == null) break;\n const target = requests.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests.every((r) => \"response\" in r)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AAiBA,MAAMkB,aAAaC,aAAqD;CACtE,GAAGA;CACHE,OAAO,CAAC,GAAGF,QAAQE,KAAK;AAC1B;AAEA,MAAMC,YAAYC,OAAkBC,UAA4B;CAC9D,MAAMC,QAAS,CAACF,MAAMG,SAAS,CAAA,EAAA,CAAI,OAAO;EACxCF,OAAO;EACPG,QAAQ;EACRC,OAAO,CAAA;EACPC,YAAY,CAAA;CACd;CACAJ,MAAME,SAAS;CAEf,IAAIF,MAAMD,UAAU,MAAMC,MAAMD,QAAQA;CACxC,OAAOC,MAAMK;CACb,OAAOL,MAAMM;CACbR,MAAMI,SAAS;CACf,OAAOF;AACT;AAEA,MAAMO,UACJC,MACAR,OACA,EAAES,aAAaC,mBACN;CACT,M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AO;GACzB,IAAIsB,KAAKrB,WAAW,WAAW;GAC/B,IAAIqB,IAAIsB,iBAAiBhC,KAAAA,GAAWU,IAAIuB,WAAW,EAAEC,QAAQ,OAAO;GACpE;EACF;EACA,KAAK,gBAAgB;GACnB,MAAMxB,MAAMzB,MAAMG,OAAO;GACzB,IAAIsB,QAAQV,KAAAA,GAAWU,IAAInB,aAAa,CAAA;GACxCP,SAASC,OAAOC,KAAK;GACrB;EACF;EACA,KAAK,eAAe;GAClB,MAAM,EAAEyB,cAAcJ,QACnBqC,OAAO;GACV,MAAMlC,MAAMzB,MAAMG,OAAO;GACzB,IAAIsB,QAAQV,KAAAA,GAAW;GACvB,KAAK,MAAML,QAAQ,CAACe,IAAIpB,OAAOoB,IAAInB,UAAU,GAAG;IAC9C,MAAMQ,QAAQJ,KAAKM,WAAWC,MAAMA,EAAEC,OAAOQ,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKU,OAAON,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAEuD,WAAWC,aAAahD,QAC7BqC,OAAO;GACV,MAAMa,WAAWxE,MAAMG,OAAO,EAAE,EAAEK;GAClC,IAAIgE,YAAY,MAAM;GACtB,MAAMjC,SAASiC,SAASzC,MAAM0C,MAAMA,EAAEvD,OAAOmD,SAAS;GACtD,IAAI9B,WAAWxB,KAAAA,GAAW;GAC1BwB,OAAO+B,WAAWA;GAClB,IAAIE,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAG1E,SAASC,OAAOC,KAAK;GACjE;EACF;CAGF;AACF"}
1
+ {"version":3,"file":"runsOptimistic.js","names":["ReadonlyJSONValue","Statewire","StatewireClient","StatewireThread","Mutable","T","K","LaneEntry","RunsQueueEntry","Dispatch","RunsDispatch","RunEntry","RunState","RunsDraft","Partial","RunsState","HeldEntry","localMeta","laneEntry","message","UserMessage","parts","startRun","draft","runId","entry","runs","status","queue","steerQueue","error","inputRequests","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","id","length","splice","BEHAVIORS","send","command","RunSendCommand","run","behavior","includes","Error","messageId","dispatching","messages","some","sourceLane","find","l","sourceIndex","metadata","steer","stopping","direct","trigger","target","push","continues","hasPlacement","nextDispatch","reason","stageRewind","dispatch","staged","runsOptimistic","mount","Command","Record","args","ctx","OptimisticContext","runsHeld","state","params","method","commandRunId","seq","ts","runAnchorMessageId","RunEditCommand","rollbackTo","RunReloadCommand","RunDequeueCommand","requestId","response","RunInputCommand","requests","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\n// Opaque payloads (meta, response, rollbackTo) stay readonly: only reassigned, never mutated.\ntype Mutable<T> = ReadonlyJSONValue extends T\n ? T\n : T extends object\n ? { -readonly [K in keyof T]: Mutable<T[K]> }\n : T;\n\ntype LaneEntry = Mutable<StatewireThread.RunsQueueEntry>;\ntype Dispatch = Mutable<StatewireThread.RunsDispatch>;\ntype RunEntry = Mutable<StatewireThread.RunState>;\ntype RunsDraft = Partial<Mutable<StatewireThread.RunsState>>;\ntype HeldEntry = LaneEntry & { localMeta: unknown };\n\nconst laneEntry = (message: StatewireThread.UserMessage): LaneEntry => ({\n ...message,\n parts: [...message.parts],\n});\n\nconst startRun = (draft: RunsDraft, runId: string): RunEntry => {\n const entry = ((draft.runs ??= [])[0] ??= {\n runId: null,\n status: \"running\",\n queue: [],\n steerQueue: [],\n });\n entry.status = \"running\";\n // A live run keeps its identity; a mint folds the client-generated id.\n if (entry.runId === null) entry.runId = runId;\n delete entry.error;\n delete entry.inputRequests;\n draft.status = \"running\";\n return entry;\n};\n\nconst insert = (\n lane: LaneEntry[],\n entry: LaneEntry,\n { insertAfter, insertBefore }: StatewireThread.Placement,\n): void => {\n const index =\n insertAfter !== undefined\n ? insertAfter === null\n ? 0\n : lane.findIndex((e) => e.id === insertAfter) + 1\n : insertBefore === undefined || insertBefore === null\n ? lane.length\n : lane.findIndex((e) => e.id === insertBefore);\n lane.splice(index < 0 ? lane.length : index, 0, entry);\n};\n\nconst BEHAVIORS = [\"auto\", \"steer\", \"preempt\", \"queue\"];\n\nconst send = (\n draft: RunsDraft,\n command: StatewireThread.RunSendCommand,\n runId: string,\n): void => {\n const run = draft.runs?.[0];\n // The entry status is the truth; hosts replicating the top-level projection agree.\n const status = run?.status ?? \"ready\";\n const behavior = command.behavior ?? \"auto\";\n if (!BEHAVIORS.includes(behavior))\n throw new Error(`statewire: unknown run/send behavior \"${behavior}\"`);\n const id = \"message\" in command ? command.message.id : command.messageId;\n // In dispatch limbo the canonical state already tells the story: no fold.\n if (run?.dispatching?.messages.some((e) => e.id === id)) return;\n const sourceLane =\n run === undefined\n ? undefined\n : [run.queue, run.steerQueue].find((l) => l.some((e) => e.id === id));\n // A laned \"auto\" send is host-placed: its lane is the host's decision.\n if (behavior === \"auto\" && \"message\" in command && sourceLane !== undefined)\n return;\n\n let entry: LaneEntry;\n let sourceIndex = -1;\n if (sourceLane !== undefined) {\n sourceIndex = sourceLane.findIndex((e) => e.id === id);\n entry = sourceLane.splice(sourceIndex, 1)[0]!;\n if (\"message\" in command) {\n entry.parts = [...command.message.parts];\n if (command.message.metadata !== undefined)\n entry.metadata = command.message.metadata;\n }\n } else {\n if (!(\"message\" in command)) return;\n entry = laneEntry(command.message);\n }\n\n const steer =\n behavior === \"auto\"\n ? status === \"running\" ||\n status === \"input-required\" ||\n run?.stopping != null\n : behavior !== \"queue\";\n const direct = steer\n ? status === \"ready\" || status === \"input-required\"\n : sourceLane === undefined &&\n (status === \"ready\" ||\n ((status === \"stopped\" || status === \"error\") &&\n run !== undefined &&\n run.queue.length === 0 &&\n run.steerQueue.length === 0));\n if (direct) {\n const trigger =\n status === \"error\"\n ? \"error-continue\"\n : status === \"stopped\"\n ? \"stop-continue\"\n : \"message-send\";\n const target = startRun(draft, runId);\n if (steer) {\n // The whole steer lane rides the dispatch, in lane order.\n if (sourceLane === target.steerQueue)\n target.steerQueue.splice(sourceIndex, 0, entry);\n else target.steerQueue.push(entry);\n target.dispatching = {\n trigger,\n messages: target.steerQueue.splice(0),\n };\n } else target.dispatching = { trigger, messages: [entry] };\n return;\n }\n const continues = steer && status !== \"running\";\n\n if (run === undefined)\n throw new Error(\"statewire: non-direct fold without a run entry\");\n const lane = steer ? run.steerQueue : run.queue;\n const hasPlacement =\n command.insertAfter !== undefined || command.insertBefore !== undefined;\n if (sourceLane === lane && !hasPlacement) lane.splice(sourceIndex, 0, entry);\n else insert(lane, entry, command);\n if (continues) startRun(draft, runId);\n if (\n behavior === \"preempt\" &&\n status === \"running\" &&\n run.nextDispatch === undefined\n )\n run.stopping = { reason: \"stop\" };\n};\n\nconst stageRewind = (run: RunEntry, dispatch: Dispatch): void => {\n const staged = run.nextDispatch;\n if (\n staged?.trigger === \"message-edit\" &&\n dispatch.trigger === \"message-edit\"\n ) {\n staged.messages.push(...dispatch.messages);\n } else {\n run.nextDispatch = dispatch;\n }\n run.stopping = {\n reason: run.nextDispatch!.trigger as \"message-edit\" | \"message-reload\",\n };\n};\n\n/** The run dialect's optimistic reducer: folds an unsettled `run/*` command into the mount draft. */\nexport const runsOptimistic = (\n mount: unknown,\n command: Statewire.Command<Record<string, (...args: any[]) => unknown>>,\n ctx: StatewireClient.OptimisticContext,\n): void => {\n const draft = mount as RunsDraft & { runsHeld?: HeldEntry[] };\n // A held send waits in the outbox: it shows as held, never as a run.\n if (ctx.state === \"held\") {\n const params = command.params[0] as\n | { message?: StatewireThread.UserMessage }\n | undefined;\n if (\n (command.method === \"run/send\" || command.method === \"run/edit\") &&\n params?.message !== undefined\n )\n (draft.runsHeld ??= []).push({\n ...laneEntry(params.message),\n localMeta: ctx.localMeta,\n });\n return;\n }\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq ?? `q${ctx.ts}`}`;\n switch (command.method) {\n case \"run/send\": {\n send(draft, command.params[0] as StatewireThread.RunSendCommand, runId);\n break;\n }\n case \"run/edit\": {\n const { message, runAnchorMessageId } = command\n .params[0] as StatewireThread.RunEditCommand;\n const dispatch: Dispatch = {\n trigger: \"message-edit\",\n messages: [laneEntry(message)],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") stageRewind(run, dispatch);\n else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/reload\": {\n const { runAnchorMessageId } = command\n .params[0] as StatewireThread.RunReloadCommand;\n const dispatch: Dispatch = {\n trigger: \"message-reload\",\n messages: [],\n rollbackTo: runAnchorMessageId,\n };\n const run = draft.runs?.[0];\n if (run?.status === \"running\") {\n if (run.nextDispatch === undefined) stageRewind(run, dispatch);\n } else startRun(draft, runId).dispatching = dispatch;\n break;\n }\n case \"run/stop\": {\n const run = draft.runs?.[0];\n if (run?.status !== \"running\") break;\n if (run.nextDispatch === undefined) run.stopping = { reason: \"stop\" };\n break;\n }\n case \"run/continue\": {\n const run = draft.runs?.[0];\n if (run !== undefined) run.steerQueue = [];\n startRun(draft, runId);\n break;\n }\n case \"run/dequeue\": {\n const { messageId } = command\n .params[0] as StatewireThread.RunDequeueCommand;\n const run = draft.runs?.[0];\n if (run === undefined) break;\n for (const lane of [run.queue, run.steerQueue]) {\n const index = lane.findIndex((e) => e.id === messageId);\n if (index !== -1) lane.splice(index, 1);\n }\n break;\n }\n case \"run/input\": {\n const { requestId, response } = command\n .params[0] as StatewireThread.RunInputCommand;\n const requests = draft.runs?.[0]?.inputRequests;\n if (requests == null) break;\n const target = requests.find((r) => r.id === requestId);\n if (target === undefined) break;\n target.response = response;\n if (requests.every((r) => \"response\" in r)) startRun(draft, runId);\n break;\n }\n default:\n break;\n }\n};\n"],"mappings":";AAiBA,MAAMkB,aAAaC,aAAqD;CACtE,GAAGA;CACHE,OAAO,CAAC,GAAGF,QAAQE,KAAK;AAC1B;AAEA,MAAMC,YAAYC,OAA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MA,EAAEC,OAAOW,SAAS;IACtD,IAAIf,UAAU,IAAIJ,KAAKU,OAAON,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAEwD,WAAWC,aAAahD,QAC7BqC,OAAO;GACV,MAAMa,WAAWzE,MAAMG,OAAO,EAAE,EAAEK;GAClC,IAAIiE,YAAY,MAAM;GACtB,MAAM/B,SAAS+B,SAASvC,MAAMwC,MAAMA,EAAExD,OAAOoD,SAAS;GACtD,IAAI5B,WAAW3B,KAAAA,GAAW;GAC1B2B,OAAO6B,WAAWA;GAClB,IAAIE,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAG3E,SAASC,OAAOC,KAAK;GACjE;EACF;CAGF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assistant-ui/react-statewire",
3
- "version": "0.34.0",
3
+ "version": "0.35.0",
4
4
  "description": "assistant-ui thread binding for statewire backends",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -39,7 +39,7 @@
39
39
  "@assistant-ui/store": "^0.3.22",
40
40
  "@assistant-ui/tap": "^0.9.24",
41
41
  "assistant-stream": "^0.3.53",
42
- "statewire": "^0.25.0"
42
+ "statewire": "^0.26.0"
43
43
  },
44
44
  "peerDependencies": {
45
45
  "@assistant-ui/core": ">=0.3.12",
@@ -42,8 +42,7 @@ const createServer = ({ rejectSends = false } = {}) => {
42
42
  if (rejectSends) throw new StatewireReject("unknown command");
43
43
  };
44
44
  const commands = useStatewireCommands({
45
- "run/enqueue": submit,
46
- "run/steer": submit,
45
+ "run/send": submit,
47
46
  });
48
47
  return { state, commands };
49
48
  })();
@@ -162,8 +162,9 @@ const mountThread = (
162
162
  };
163
163
 
164
164
  const enqueue = (id: string, text: string): StatewireThread.RunCommand => ({
165
- type: "run/enqueue",
165
+ type: "run/send",
166
166
  runId: "run-1",
167
+ behavior: "queue",
167
168
  message: wireMessage(id, text),
168
169
  runAnchorMessageId: null,
169
170
  });
@@ -205,8 +206,8 @@ describe("StatewireThread held sends", () => {
205
206
  await act(() => extras(aui).outbox.release(entry!.id));
206
207
  await waitFor(() => expect(mounted.runs().held).toHaveLength(0));
207
208
  expect(server.received.map((r) => r.method)).toEqual([
208
- "run/enqueue",
209
- "run/enqueue",
209
+ "run/send",
210
+ "run/send",
210
211
  ]);
211
212
  });
212
213
 
@@ -216,13 +217,13 @@ describe("StatewireThread held sends", () => {
216
217
  await waitFor(() => expect(extras(mounted.aui).status).toBe("ready"));
217
218
  act(() => {
218
219
  void extras(mounted.aui)
219
- .invoke("default", "run/enqueue", [enqueue("m2", "later")])
220
+ .invoke("default", "run/send", [enqueue("m2", "later")])
220
221
  .catch(() => {});
221
222
  });
222
223
  await waitFor(() => expect(server.received).toHaveLength(1));
223
224
  const id = extras(mounted.aui).outbox.insert({
224
225
  protocol: "default",
225
- command: { method: "run/enqueue", params: [enqueue("m3", "wait")] },
226
+ command: { method: "run/send", params: [enqueue("m3", "wait")] },
226
227
  held: true,
227
228
  });
228
229
  await waitFor(() => expect(mounted.runs().held).toHaveLength(1));
@@ -93,7 +93,10 @@ const converter: StatewireThread.StateConverter<RunsServerState> = (state) => ({
93
93
  messages: state.messages.map(toThreadMessage),
94
94
  });
95
95
 
96
- const createServer = (init?: Partial<RunsServerState>) => {
96
+ const createServer = (
97
+ init?: Partial<RunsServerState>,
98
+ send?: (state: RunsServerState, command: unknown) => Promise<void>,
99
+ ) => {
97
100
  const received: unknown[] = [];
98
101
  const cell: { state?: RunsServerState } = {};
99
102
  const transport = resource(() => {
@@ -106,8 +109,10 @@ const createServer = (init?: Partial<RunsServerState>) => {
106
109
  received.push(command);
107
110
  };
108
111
  const commands = useStatewireCommands({
109
- "run/enqueue": record,
110
- "run/steer": record,
112
+ "run/send": (command: unknown) => {
113
+ record(command);
114
+ return send?.(state, command);
115
+ },
111
116
  "run/dequeue": record,
112
117
  "run/edit": record,
113
118
  "run/reload": record,
@@ -300,6 +305,66 @@ describe("StatewireThread runs mode", () => {
300
305
  );
301
306
  });
302
307
 
308
+ it("moves a downgraded auto send to the queue lane without duplicating or flickering back", async () => {
309
+ const gate = { decide: () => {}, settle: () => {} };
310
+ const server = createServer(
311
+ withRun({ status: "running", runId: "run-1" }),
312
+ async (state, command) => {
313
+ const { message } = command as { message: ServerRunEntry["queue"][0] };
314
+ await new Promise<void>((resolve) => (gate.decide = resolve));
315
+ state.runs![0]!.queue.push(message);
316
+ await new Promise<void>((resolve) => (gate.settle = resolve));
317
+ },
318
+ );
319
+ const observed: {
320
+ queue: string[];
321
+ steerQueue: string[];
322
+ sending: boolean;
323
+ }[] = [];
324
+ const { aui, runs } = mountThread({
325
+ transport: server.transport,
326
+ converter: (state, meta) => {
327
+ observed.push({
328
+ queue: meta.runs.queue.map((e) => e.id),
329
+ steerQueue: meta.runs.steerQueue.map((e) => e.id),
330
+ sending: meta.isSending,
331
+ });
332
+ return converter(state, meta);
333
+ },
334
+ });
335
+ await waitFor(() => expect(threadStatus(aui())).toBe("running"));
336
+
337
+ act(() => {
338
+ aui().thread().composer().setText("later");
339
+ });
340
+ act(() => {
341
+ aui().thread().composer().send();
342
+ });
343
+ await waitFor(() => expect(runs().steerQueue).toHaveLength(1));
344
+ expect(server.received).toMatchObject([
345
+ { type: "run/send", runId: "run-1", behavior: "auto" },
346
+ ]);
347
+ const id = runs().steerQueue[0]!.id;
348
+
349
+ act(() => gate.decide());
350
+ await waitFor(() => expect(runs().queue.map((e) => e.id)).toEqual([id]));
351
+ expect(runs().steerQueue).toEqual([]);
352
+
353
+ act(() => gate.settle());
354
+ await waitFor(() => expect(observed.at(-1)!.sending).toBe(false));
355
+ expect(runs().queue.map((e) => e.id)).toEqual([id]);
356
+ expect(runs().steerQueue).toEqual([]);
357
+
358
+ const firstQueued = observed.findIndex((o) => o.queue.includes(id));
359
+ expect(firstQueued).toBeGreaterThan(-1);
360
+ expect(
361
+ observed.filter((o) => o.queue.includes(id) && o.steerQueue.includes(id)),
362
+ ).toEqual([]);
363
+ expect(
364
+ observed.slice(firstQueued).filter((o) => o.steerQueue.includes(id)),
365
+ ).toEqual([]);
366
+ });
367
+
303
368
  it("delivers the runs read to the converter as meta.runs", async () => {
304
369
  const server = createServer(withRun({ status: "stopped", runId: "run-5" }));
305
370
  const observed: StatewireThread.Runs[] = [];
@@ -624,7 +689,8 @@ describe("StatewireThread runs mode", () => {
624
689
  await waitFor(() => expect(threadStatus(aui())).toBe("running"));
625
690
  act(() => {
626
691
  sendCommand(aui, {
627
- type: "run/steer",
692
+ type: "run/send",
693
+ behavior: "steer",
628
694
  runId: "run-1",
629
695
  message: {
630
696
  id: "s1",
@@ -639,7 +705,7 @@ describe("StatewireThread runs mode", () => {
639
705
  { type: "text", text: "hello" },
640
706
  ]);
641
707
  expect(runs().runId).toBe("run-1");
642
- expect(server.received.map((c) => c.method)).toEqual(["run/steer"]);
708
+ expect(server.received.map((c) => c.method)).toEqual(["run/send"]);
643
709
  });
644
710
 
645
711
  it("targets the live run for a mid-run send, no anchor", async () => {
@@ -749,7 +815,7 @@ describe("StatewireThread runs mode", () => {
749
815
 
750
816
  // Attach posts the queued command; the still-unapplied overlay survives the snapshot.
751
817
  await waitFor(() =>
752
- expect(server.received.map((c) => c.method)).toEqual(["run/enqueue"]),
818
+ expect(server.received.map((c) => c.method)).toEqual(["run/send"]),
753
819
  );
754
820
  expect(aui().thread().getState().messages).toHaveLength(1);
755
821
  expect(threadStatus(aui())).toBe("running");
@@ -844,10 +910,10 @@ describe("StatewireThread runs mode", () => {
844
910
  const { aui } = mountThread({
845
911
  transport: server.transport,
846
912
  optimistic: (draft, command) => {
847
- if (command.method !== "run/enqueue") return;
913
+ if (command.method !== "run/send") return;
848
914
  observedStatus.push(draft.status);
849
915
  const message = (
850
- command.params[0] as StatewireThread.RunEnqueueCommand & {
916
+ command.params[0] as StatewireThread.RunSendCommand & {
851
917
  message: StatewireThread.UserMessage;
852
918
  }
853
919
  ).message;
@@ -128,13 +128,9 @@ const createServer = (init?: Partial<ServerState>) => {
128
128
  state.runs.push(runEntry({ status: "running", runId }));
129
129
  else run.status = "running";
130
130
  };
131
- const submitSend = (
132
- lane: "queue" | "steerQueue",
133
- command:
134
- | StatewireThread.RunEnqueueCommand
135
- | StatewireThread.RunSteerCommand,
136
- ) => {
131
+ const submitSend = (command: StatewireThread.RunSendCommand) => {
137
132
  received.push(command);
133
+ const lane = command.behavior === "queue" ? "queue" : "steerQueue";
138
134
  if (cell.rejectSends) throw new StatewireReject("unknown command");
139
135
  if (cell.hold) {
140
136
  return new Promise<void>((resolve, reject) => {
@@ -167,10 +163,7 @@ const createServer = (init?: Partial<ServerState>) => {
167
163
  };
168
164
 
169
165
  const commands = useStatewireCommands({
170
- "run/enqueue": (command: StatewireThread.RunEnqueueCommand) =>
171
- submitSend("queue", command),
172
- "run/steer": (command: StatewireThread.RunSteerCommand) =>
173
- submitSend("steerQueue", command),
166
+ "run/send": submitSend,
174
167
  "run/dequeue": (command: StatewireThread.RunDequeueCommand) => {
175
168
  received.push(command);
176
169
  if (!takeEntry(command.messageId))
@@ -298,7 +291,8 @@ describe("StatewireThread", () => {
298
291
  await waitFor(() =>
299
292
  expect(server.received).toMatchObject([
300
293
  {
301
- type: "run/enqueue",
294
+ type: "run/send",
295
+ behavior: "auto",
302
296
  runId: expect.any(String),
303
297
  message: {
304
298
  id: expect.any(String),
@@ -314,7 +308,8 @@ describe("StatewireThread", () => {
314
308
  aui().thread().append("queued follow-up");
315
309
  await waitFor(() =>
316
310
  expect(server.received.at(-1)).toMatchObject({
317
- type: "run/enqueue",
311
+ type: "run/send",
312
+ behavior: "queue",
318
313
  message: {
319
314
  role: "user",
320
315
  parts: [{ type: "text", text: "queued follow-up" }],
@@ -360,9 +355,7 @@ describe("StatewireThread", () => {
360
355
  aui().thread().append("hello");
361
356
 
362
357
  await waitFor(() => expect(metas.at(-1)!.isSending).toBe(true));
363
- expect(metas.at(-1)!.pendingCommands).toMatchObject([
364
- { type: "run/enqueue" },
365
- ]);
358
+ expect(metas.at(-1)!.pendingCommands).toMatchObject([{ type: "run/send" }]);
366
359
 
367
360
  server.cell.resolvers!.resolve();
368
361
 
@@ -376,8 +369,7 @@ describe("StatewireThread", () => {
376
369
 
377
370
  aui().thread().append("hello");
378
371
  await waitFor(() => expect(isRunning(aui)).toBe(true));
379
- const runId = (server.received[0] as StatewireThread.RunEnqueueCommand)
380
- .runId;
372
+ const runId = (server.received[0] as StatewireThread.RunSendCommand).runId;
381
373
 
382
374
  aui().thread().cancelRun();
383
375
 
@@ -478,8 +470,8 @@ describe("StatewireThread", () => {
478
470
  ]),
479
471
  );
480
472
  expect(updates.at(-1)).toMatchObject({
481
- method: "run/enqueue",
482
- params: [{ type: "run/enqueue" }],
473
+ method: "run/send",
474
+ params: [{ type: "run/send", behavior: "auto" }],
483
475
  });
484
476
  expect(states.at(-1)!.messages.map((m) => m.text)).toEqual(["hello"]);
485
477
  await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
@@ -749,8 +741,13 @@ describe("StatewireThread", () => {
749
741
  await waitFor(() =>
750
742
  expect(mock.commands).toMatchObject([
751
743
  {
752
- method: "run/enqueue",
753
- params: [{ message: { parts: [{ type: "text", text: "hello" }] } }],
744
+ method: "run/send",
745
+ params: [
746
+ {
747
+ behavior: "auto",
748
+ message: { parts: [{ type: "text", text: "hello" }] },
749
+ },
750
+ ],
754
751
  },
755
752
  ]),
756
753
  );
@@ -767,7 +764,7 @@ describe("StatewireThread", () => {
767
764
  });
768
765
 
769
766
  describe("run/* queue", () => {
770
- it("steers by default when the composer sends mid-run", async () => {
767
+ it("sends auto by default when the composer sends mid-run", async () => {
771
768
  const server = createServer();
772
769
  const { aui } = mountThread({ transport: server.transport, converter });
773
770
 
@@ -779,7 +776,8 @@ describe("StatewireThread", () => {
779
776
 
780
777
  await waitFor(() =>
781
778
  expect(server.received.at(-1)).toMatchObject({
782
- type: "run/steer",
779
+ type: "run/send",
780
+ behavior: "auto",
783
781
  message: {
784
782
  id: expect.any(String),
785
783
  role: "user",
@@ -817,7 +815,7 @@ describe("StatewireThread", () => {
817
815
  );
818
816
  });
819
817
 
820
- it("sends item controls as run/* commands with placement", async () => {
818
+ it("sends item controls as run/send with the target lane's behavior and placement", async () => {
821
819
  const server = createServer({
822
820
  status: "running",
823
821
  runs: [
@@ -838,7 +836,8 @@ describe("StatewireThread", () => {
838
836
  aui().thread().composer().queueItem({ id: "q1" }).steer();
839
837
  await waitFor(() =>
840
838
  expect(server.received).toContainEqual({
841
- type: "run/steer",
839
+ type: "run/send",
840
+ behavior: "steer",
842
841
  runId: "run-1",
843
842
  messageId: "q1",
844
843
  insertAfter: null,
@@ -858,7 +857,8 @@ describe("StatewireThread", () => {
858
857
  .move({ insertBefore: null });
859
858
  await waitFor(() =>
860
859
  expect(server.received).toContainEqual({
861
- type: "run/steer",
860
+ type: "run/send",
861
+ behavior: "steer",
862
862
  runId: "run-1",
863
863
  messageId: "s1",
864
864
  insertBefore: null,
@@ -872,7 +872,8 @@ describe("StatewireThread", () => {
872
872
  .move({ lane: "queue", insertAfter: "q2" });
873
873
  await waitFor(() =>
874
874
  expect(server.received).toContainEqual({
875
- type: "run/enqueue",
875
+ type: "run/send",
876
+ behavior: "queue",
876
877
  runId: "run-1",
877
878
  messageId: "q1",
878
879
  insertAfter: "q2",
@@ -1083,8 +1084,8 @@ describe("StatewireThread", () => {
1083
1084
 
1084
1085
  await waitFor(() =>
1085
1086
  expect(sent()).toEqual([
1086
- { method: "run/steer", runId: "run-2" },
1087
- { method: "run/steer", runId: "run-2" },
1087
+ { method: "run/send", runId: "run-2" },
1088
+ { method: "run/send", runId: "run-2" },
1088
1089
  { method: "run/edit", runId: "run-2" },
1089
1090
  ]),
1090
1091
  );
@@ -1273,8 +1274,7 @@ describe("StatewireThread", () => {
1273
1274
 
1274
1275
  aui().thread().append("hello");
1275
1276
  await waitFor(() => expect(isRunning(aui)).toBe(true));
1276
- const runId = (server.received[0] as StatewireThread.RunEnqueueCommand)
1277
- .runId;
1277
+ const runId = (server.received[0] as StatewireThread.RunSendCommand).runId;
1278
1278
 
1279
1279
  aui().thread().cancelRun();
1280
1280
 
@@ -194,9 +194,7 @@ const useStatewireThread = (
194
194
  () =>
195
195
  (command: StatewireThread.Command): Error | undefined =>
196
196
  contextFailure.current !== undefined &&
197
- (command.type === "run/enqueue" ||
198
- command.type === "run/steer" ||
199
- command.type === "run/edit")
197
+ (command.type === "run/send" || command.type === "run/edit")
200
198
  ? new Error("statewire: the model context was rejected", {
201
199
  cause: contextFailure.current,
202
200
  })
@@ -349,7 +347,13 @@ const useStatewireThread = (
349
347
  // ExternalThread rebuilds every message's state when `queue` or a message
350
348
  // handler changes identity, so these read the latest pass instead of closing over it.
351
349
  const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
352
- const pass = { messages, runId: liveRunId, inputRequests, dispatch };
350
+ const pass = {
351
+ messages,
352
+ runId: liveRunId,
353
+ running: status === "running",
354
+ inputRequests,
355
+ dispatch,
356
+ };
353
357
  const live = useRef(pass);
354
358
  live.current = pass;
355
359
  const queue = useMemo(
@@ -404,7 +408,8 @@ const useStatewireThread = (
404
408
  message.sourceId != null
405
409
  ? resolveEditCommand(messages, message, liveRunId)
406
410
  : {
407
- type: "run/steer",
411
+ type: "run/send",
412
+ behavior: "auto",
408
413
  ...sendFields(
409
414
  messages,
410
415
  liveRunId,
@@ -617,24 +622,28 @@ export namespace StatewireThread {
617
622
  readonly insertBefore?: string | null;
618
623
  };
619
624
 
620
- type RunSendCommand<TType extends "run/enqueue" | "run/steer"> = {
621
- readonly type: TType;
625
+ /** How a send lands while a run is live: `"auto"` lets the host decide, `"steer"` folds it into the live run, `"preempt"` stops the run and handles it next, `"queue"` runs it after the run. */
626
+ export type RunSendBehavior = "auto" | "steer" | "preempt" | "queue";
627
+
628
+ export type RunSendCommand = {
629
+ readonly type: "run/send";
622
630
  /** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
623
631
  readonly runId: string;
632
+ /** Defaults to `"auto"`. */
633
+ readonly behavior?: RunSendBehavior;
624
634
  } & (
625
635
  | {
626
636
  readonly message: UserMessage;
627
637
  /** Run anchor: the message the new content grows after, null asserting an empty thread. Present on run-creating sends; absent when targeting the live run. */
628
638
  readonly runAnchorMessageId?: string | null;
629
639
  }
630
- | { readonly messageId: string }
640
+ | {
641
+ /** A queued message to move into the behavior's lane. */
642
+ readonly messageId: string;
643
+ }
631
644
  ) &
632
645
  Placement;
633
646
 
634
- export type RunEnqueueCommand = RunSendCommand<"run/enqueue">;
635
-
636
- export type RunSteerCommand = RunSendCommand<"run/steer">;
637
-
638
647
  export type RunDequeueCommand = {
639
648
  readonly type: "run/dequeue";
640
649
  readonly runId: string;
@@ -717,8 +726,7 @@ export namespace StatewireThread {
717
726
  };
718
727
 
719
728
  export type RunCommand =
720
- | RunEnqueueCommand
721
- | RunSteerCommand
729
+ | RunSendCommand
722
730
  | RunDequeueCommand
723
731
  | RunEditCommand
724
732
  | RunContinueCommand
@@ -850,7 +858,7 @@ export namespace StatewireThread {
850
858
  readonly inputRequests?: readonly InputRequestState[];
851
859
  /** Set only by an unhandled throw; cleared by the next user-initiated run. */
852
860
  readonly error?: RunsError;
853
- /** Held run sends (enqueue, steer, edit) in queue order; release or remove them through `extras.outbox`. */
861
+ /** Held run sends (send, edit) in queue order; release or remove them through `extras.outbox`. */
854
862
  readonly held: readonly RunsHeldEntry[];
855
863
  };
856
864
 
@@ -969,8 +977,7 @@ export namespace StatewireThread {
969
977
  declare module "@assistant-ui/core" {
970
978
  namespace Assistant {
971
979
  interface Commands {
972
- runEnqueue: StatewireThread.RunEnqueueCommand;
973
- runSteer: StatewireThread.RunSteerCommand;
980
+ runSend: StatewireThread.RunSendCommand;
974
981
  runDequeue: StatewireThread.RunDequeueCommand;
975
982
  runEdit: StatewireThread.RunEditCommand;
976
983
  runContinue: StatewireThread.RunContinueCommand;
@@ -224,7 +224,7 @@ describe("LocalStorageSession", () => {
224
224
  id: "cmd-2",
225
225
  ts: 1,
226
226
  seq: 2,
227
- method: "run/steer",
227
+ method: "run/send",
228
228
  params: [{ text: "hi" }],
229
229
  meta: { requestId: "r-2" },
230
230
  },