@assistant-ui/react-statewire 0.19.0 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/StatewireThread.d.ts +19 -16
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +6 -3
- package/dist/StatewireThread.js.map +1 -1
- package/dist/runCommands.d.ts +9 -2
- package/dist/runCommands.d.ts.map +1 -1
- package/dist/runCommands.js +27 -1
- package/dist/runCommands.js.map +1 -1
- package/dist/runsOptimistic.d.ts.map +1 -1
- package/dist/runsOptimistic.js +15 -9
- package/dist/runsOptimistic.js.map +1 -1
- package/package.json +1 -1
- package/src/StatewireThread.runs.test.tsx +92 -10
- package/src/StatewireThread.test.tsx +102 -1
- package/src/StatewireThread.ts +53 -20
- package/src/runCommands.ts +41 -0
- package/src/runsOptimistic.test.ts +65 -3
- package/src/runsOptimistic.ts +32 -37
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runsOptimistic.js","names":["Statewire","StatewireClient","StatewireThread","LaneEntry","id","role","parts","TextPart","FilePart","metadata","Record","meta","Dispatch","trigger","messages","rollbackTo","RunEntry","runId","status","RunStatus","queue","steerQueue","dispatching","stopping","reason","nextDispatch","inputRequests","response","error","RunsDraft","Exclude","ThreadStatus","runs","startRun","draft","entry","insert","lane","insertAfter","insertBefore","Placement","index","undefined","findIndex","e","length","splice","enqueueOrSteer","command","RunEnqueueCommand","RunSteerCommand","run","message","messageId","some","sourceLane","find","l","sourceIndex","steer","type","direct","target","push","continues","Error","hasPlacement","stageRewind","dispatch","runsOptimistic","mount","Command","args","ctx","OptimisticContext","commandRunId","params","seq","method","runAnchorMessageId","RunEditCommand","RunReloadCommand","RunDequeueCommand","requestId","RunInputCommand","requests","r","every"],"sources":["../src/runsOptimistic.ts"],"sourcesContent":["import type { Statewire, StatewireClient } from \"statewire\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\ntype LaneEntry = {\n id: string;\n role: \"user\";\n parts: readonly (StatewireThread.TextPart | StatewireThread.FilePart)[];\n metadata?: Record<string, unknown>;\n meta?: unknown;\n};\n\ntype Dispatch = {\n trigger: string;\n messages: LaneEntry[];\n rollbackTo?: string | null;\n};\n\ntype RunEntry = {\n runId: string | null;\n status: StatewireThread.RunStatus;\n queue: LaneEntry[];\n steerQueue: LaneEntry[];\n dispatching?: Dispatch;\n stopping?: { reason: \"stop\" | \"message-edit\" | \"message-reload\" };\n nextDispatch?: Dispatch;\n inputRequests?: { id: string; response?: unknown }[];\n error?: unknown;\n};\n\ntype RunsDraft = {\n status: Exclude<StatewireThread.ThreadStatus, \"loading\">;\n runs?: RunEntry[];\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 = { ...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 run.stopping = {\n reason: dispatch.trigger as \"message-edit\" | \"message-reload\",\n };\n run.nextDispatch = dispatch;\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;\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq}`;\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: [{ ...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\") 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 run.stopping = { reason: \"stop\" };\n delete run.nextDispatch;\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 === undefined) 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;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C,OAAO2B,IAAI1B;GACX;EACF;EACA,KAAK,gBAAgB;GACnB,MAAM0B,MAAMjB,MAAMF,OAAO;GACzB,IAAImB,QAAQT,KAAAA,GAAWS,IAAI9B,aAAa,CAAA;GACxCY,SAASC,OAAOjB,KAAK;GACrB;EACF;EACA,KAAK,eAAe;GAClB,MAAM,EAAEoC,cAAcL,QACnB4B,OAAO;GACV,MAAMzB,MAAMjB,MAAMF,OAAO;GACzB,IAAImB,QAAQT,KAAAA,GAAW;GACvB,KAAK,MAAML,QAAQ,CAACc,IAAI/B,OAAO+B,IAAI9B,UAAU,GAAG;IAC9C,MAAMoB,QAAQJ,KAAKM,WAAWC,MAAMA,EAAExC,OAAOiD,SAAS;IACtD,IAAIZ,UAAU,IAAIJ,KAAKS,OAAOL,OAAO,CAAC;GACxC;GACA;EACF;EACA,KAAK,aAAa;GAChB,MAAM,EAAE0C,WAAWxD,aAAaqB,QAC7B4B,OAAO;GACV,MAAMS,WAAWnD,MAAMF,OAAO,EAAE,EAAEN;GAClC,IAAI2D,aAAa3C,KAAAA,GAAW;GAC5B,MAAMoB,SAASuB,SAAS7B,MAAM8B,MAAMA,EAAElF,OAAO+E,SAAS;GACtD,IAAIrB,WAAWpB,KAAAA,GAAW;GAC1BoB,OAAOnC,WAAWA;GAClB,IAAI0D,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAGrD,SAASC,OAAOjB,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","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","commandRunId","params","seq","method","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>>;\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;\n const commandRunId = (command.params[0] as { runId?: string } | undefined)\n ?.runId;\n const runId = commandRunId ?? `optimistic-${ctx.seq}`;\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 === undefined) 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":";AAgBA,MAAMgB,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,MAAME,QACJH,gBAAgBI,KAAAA,IACZJ,gBAAgB,OACd,IACAD,KAAKM,WAAWC,MAAMA,EAAEC,OAAOP,WAAW,IAAI,IAChDC,iBAAiBG,KAAAA,KAAaH,iBAAiB,OAC7CF,KAAKS,SACLT,KAAKM,WAAWC,MAAMA,EAAEC,OAAON,YAAY;CACnDF,KAAKU,OAAON,QAAQ,IAAIJ,KAAKS,SAASL,OAAO,GAAGZ,KAAK;AACvD;AAEA,MAAMmB,kBACJrB,OACAsB,SAC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D,WAAWC,aAAa7C,QAC7BoC,OAAO;GACV,MAAMW,WAAWrE,MAAMG,OAAO,EAAE,EAAEK;GAClC,IAAI6D,aAAatD,KAAAA,GAAW;GAC5B,MAAMwB,SAAS8B,SAAStC,MAAMuC,MAAMA,EAAEpD,OAAOgD,SAAS;GACtD,IAAI3B,WAAWxB,KAAAA,GAAW;GAC1BwB,OAAO4B,WAAWA;GAClB,IAAIE,SAASE,OAAOD,MAAM,cAAcA,CAAC,GAAGvE,SAASC,OAAOC,KAAK;GACjE;EACF;CAGF;AACF"}
|
package/package.json
CHANGED
|
@@ -45,7 +45,7 @@ type ServerRunEntry = {
|
|
|
45
45
|
|
|
46
46
|
type RunsServerState = {
|
|
47
47
|
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
48
|
-
status:
|
|
48
|
+
status: "ready" | StatewireThread.RunStatus;
|
|
49
49
|
runs?: ServerRunEntry[];
|
|
50
50
|
};
|
|
51
51
|
|
|
@@ -138,6 +138,13 @@ const createRemoteServer = (
|
|
|
138
138
|
parkedSnapshot?.();
|
|
139
139
|
parkedSnapshot = undefined;
|
|
140
140
|
};
|
|
141
|
+
let finSent = false;
|
|
142
|
+
let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
|
|
143
|
+
const fin = (reason: string) => {
|
|
144
|
+
finSent = true;
|
|
145
|
+
stream!.enqueue(encoder.encode(frame({ fin: { reason } })));
|
|
146
|
+
stream!.close();
|
|
147
|
+
};
|
|
141
148
|
type Frame = {
|
|
142
149
|
ctx?: { seq: number }[];
|
|
143
150
|
cmd?: { method: string; params: unknown[]; seq: number }[];
|
|
@@ -157,12 +164,14 @@ const createRemoteServer = (
|
|
|
157
164
|
const headers = new Headers(init2?.headers);
|
|
158
165
|
const clientId = headers.get("Statewire-Client-Id")!;
|
|
159
166
|
if (url.endsWith("/stream")) {
|
|
160
|
-
|
|
161
|
-
if (!known) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
167
|
+
if (!clients.has(clientId)) clients.set(clientId, { seq: 0, ctxSeq: 0 });
|
|
162
168
|
const rec = clients.get(clientId)!;
|
|
163
169
|
const attachFrame = JSON.parse(String(init2?.body)) as Frame;
|
|
164
170
|
const body = new ReadableStream<Uint8Array>({
|
|
165
171
|
start: (c) => {
|
|
172
|
+
stream = c;
|
|
173
|
+
// Reattach attempts after a fin park, so the episode status holds.
|
|
174
|
+
if (finSent) return;
|
|
166
175
|
const sendSnapshot = () => {
|
|
167
176
|
c.enqueue(
|
|
168
177
|
encoder.encode(
|
|
@@ -174,11 +183,7 @@ const createRemoteServer = (
|
|
|
174
183
|
value: { ...INITIAL_STATE, ...init },
|
|
175
184
|
},
|
|
176
185
|
],
|
|
177
|
-
syn: {
|
|
178
|
-
seq: rec.seq,
|
|
179
|
-
ctxSeq: rec.ctxSeq,
|
|
180
|
-
record: known ? "resumed" : "fresh",
|
|
181
|
-
},
|
|
186
|
+
syn: { seq: rec.seq, ctxSeq: rec.ctxSeq },
|
|
182
187
|
}),
|
|
183
188
|
),
|
|
184
189
|
);
|
|
@@ -202,6 +207,7 @@ const createRemoteServer = (
|
|
|
202
207
|
return {
|
|
203
208
|
received,
|
|
204
209
|
release,
|
|
210
|
+
fin,
|
|
205
211
|
transport: StatewireSSE<RunsServerState>({
|
|
206
212
|
url: "http://fake/api",
|
|
207
213
|
fetch: fetchImpl,
|
|
@@ -713,8 +719,9 @@ describe("StatewireThread runs mode", () => {
|
|
|
713
719
|
aui().thread().append("hello");
|
|
714
720
|
});
|
|
715
721
|
|
|
716
|
-
// The pre-attach send renders through the same optimistic + materialize
|
|
717
|
-
|
|
722
|
+
// The pre-attach send renders through the same optimistic + materialize
|
|
723
|
+
// folds; while connecting, the run presents as disconnected.
|
|
724
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
718
725
|
expect(runs().runId).toEqual(expect.any(String));
|
|
719
726
|
expect(aui().thread().getState().messages).toHaveLength(1);
|
|
720
727
|
expect(server.received).toEqual([]);
|
|
@@ -848,3 +855,78 @@ describe("StatewireThread runs mode", () => {
|
|
|
848
855
|
expect(observedStatus).toEqual(["running"]);
|
|
849
856
|
});
|
|
850
857
|
});
|
|
858
|
+
|
|
859
|
+
describe("StatewireThread connection presentation", () => {
|
|
860
|
+
it("presents a running run as evicted while reconnecting from eviction", async () => {
|
|
861
|
+
const server = createRemoteServer(
|
|
862
|
+
withRun({ status: "running", runId: "run-1" }),
|
|
863
|
+
);
|
|
864
|
+
const { aui } = mountThread({ transport: server.transport });
|
|
865
|
+
|
|
866
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
867
|
+
server.fin("evicted");
|
|
868
|
+
|
|
869
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("evicted"));
|
|
870
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
871
|
+
});
|
|
872
|
+
|
|
873
|
+
it("presents a running run as disconnected while reconnecting from a non-eviction", async () => {
|
|
874
|
+
const server = createRemoteServer(
|
|
875
|
+
withRun({ status: "running", runId: "run-1" }),
|
|
876
|
+
);
|
|
877
|
+
const { aui } = mountThread({ transport: server.transport });
|
|
878
|
+
|
|
879
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
880
|
+
server.fin("error");
|
|
881
|
+
|
|
882
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
883
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
884
|
+
});
|
|
885
|
+
|
|
886
|
+
it("presents a running run as disconnected when the session is gone", async () => {
|
|
887
|
+
const server = createRemoteServer(
|
|
888
|
+
withRun({ status: "running", runId: "run-1" }),
|
|
889
|
+
);
|
|
890
|
+
const { aui } = mountThread({ transport: server.transport });
|
|
891
|
+
|
|
892
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
893
|
+
server.fin("gone");
|
|
894
|
+
|
|
895
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("disconnected"));
|
|
896
|
+
});
|
|
897
|
+
|
|
898
|
+
it("presents a preloaded running run as disconnected while connecting", async () => {
|
|
899
|
+
const running = withRun({ status: "running", runId: "run-1" });
|
|
900
|
+
const server = createRemoteServer(running, { hold: true });
|
|
901
|
+
const { aui } = mountThread({
|
|
902
|
+
transport: server.transport,
|
|
903
|
+
initialState: { ...INITIAL_STATE, ...running },
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
expect(threadStatus(aui())).toBe("disconnected");
|
|
907
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
908
|
+
|
|
909
|
+
server.release();
|
|
910
|
+
|
|
911
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("running"));
|
|
912
|
+
expect(aui().thread().getState().isRunning).toBe(true);
|
|
913
|
+
});
|
|
914
|
+
|
|
915
|
+
it.each(["input-required", "error", "stopped"] as const)(
|
|
916
|
+
"passes %s through the disconnected overlay",
|
|
917
|
+
async (status) => {
|
|
918
|
+
const server = createRemoteServer(withRun({ status, runId: "run-1" }));
|
|
919
|
+
const statuses: string[] = [];
|
|
920
|
+
const { aui } = mountThread({
|
|
921
|
+
transport: server.transport,
|
|
922
|
+
onConnectionChange: (connection) => statuses.push(connection.status),
|
|
923
|
+
});
|
|
924
|
+
|
|
925
|
+
await waitFor(() => expect(threadStatus(aui())).toBe(status));
|
|
926
|
+
server.fin("error");
|
|
927
|
+
|
|
928
|
+
await waitFor(() => expect(statuses).toContain("reconnecting"));
|
|
929
|
+
expect(threadStatus(aui())).toBe(status);
|
|
930
|
+
},
|
|
931
|
+
);
|
|
932
|
+
});
|
|
@@ -41,7 +41,7 @@ type ServerRun = {
|
|
|
41
41
|
|
|
42
42
|
type ServerState = {
|
|
43
43
|
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
44
|
-
status:
|
|
44
|
+
status: "ready" | StatewireThread.RunStatus;
|
|
45
45
|
runs: ServerRun[];
|
|
46
46
|
};
|
|
47
47
|
|
|
@@ -1168,6 +1168,107 @@ describe("StatewireThread", () => {
|
|
|
1168
1168
|
);
|
|
1169
1169
|
});
|
|
1170
1170
|
|
|
1171
|
+
describe("branch switching", () => {
|
|
1172
|
+
const withBranch = (
|
|
1173
|
+
branch: StatewireThread.BranchMetadata,
|
|
1174
|
+
): StatewireThread.StateConverter<ServerState> => {
|
|
1175
|
+
const branchConverter: StatewireThread.StateConverter<ServerState> = (
|
|
1176
|
+
state,
|
|
1177
|
+
) => ({
|
|
1178
|
+
messages: state.messages.map((m) =>
|
|
1179
|
+
m.id === "u1"
|
|
1180
|
+
? ({
|
|
1181
|
+
...toThreadMessage(m),
|
|
1182
|
+
metadata: { custom: { branch } },
|
|
1183
|
+
} as ReturnType<typeof toThreadMessage>)
|
|
1184
|
+
: toThreadMessage(m),
|
|
1185
|
+
),
|
|
1186
|
+
});
|
|
1187
|
+
return branchConverter;
|
|
1188
|
+
};
|
|
1189
|
+
|
|
1190
|
+
const createBranchServer = (options?: { reject?: boolean }) => {
|
|
1191
|
+
const received: unknown[] = [];
|
|
1192
|
+
const transport = resource(() => {
|
|
1193
|
+
const [state] = useStatewireState<ServerState>(() => ({
|
|
1194
|
+
messages: [
|
|
1195
|
+
{ id: "u1", role: "user", text: "hi" },
|
|
1196
|
+
{ id: "a1", role: "assistant", text: "hello" },
|
|
1197
|
+
],
|
|
1198
|
+
status: "ready",
|
|
1199
|
+
runs: [],
|
|
1200
|
+
}));
|
|
1201
|
+
const commands = useStatewireCommands({
|
|
1202
|
+
"message/switch-branch": (
|
|
1203
|
+
command: StatewireThread.SwitchBranchCommand,
|
|
1204
|
+
) => {
|
|
1205
|
+
received.push(command);
|
|
1206
|
+
if (options?.reject) throw new StatewireReject("host busy");
|
|
1207
|
+
},
|
|
1208
|
+
});
|
|
1209
|
+
return { state, commands };
|
|
1210
|
+
})();
|
|
1211
|
+
return { transport, received };
|
|
1212
|
+
};
|
|
1213
|
+
|
|
1214
|
+
it("projects branch metadata into the picker and dispatches message/switch-branch", async () => {
|
|
1215
|
+
const server = createBranchServer();
|
|
1216
|
+
const { aui } = mountThread({
|
|
1217
|
+
transport: server.transport,
|
|
1218
|
+
converter: withBranch({ id: 2, siblings: [1, 2, 3] }),
|
|
1219
|
+
capabilities: { unstable_switchBranch: true },
|
|
1220
|
+
});
|
|
1221
|
+
|
|
1222
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["hi", "hello"]));
|
|
1223
|
+
const messageState = aui().thread().message({ id: "u1" }).getState();
|
|
1224
|
+
expect(messageState.branchNumber).toBe(2);
|
|
1225
|
+
expect(messageState.branchCount).toBe(3);
|
|
1226
|
+
|
|
1227
|
+
aui()
|
|
1228
|
+
.thread()
|
|
1229
|
+
.message({ id: "u1" })
|
|
1230
|
+
.switchToBranch({ position: "previous" });
|
|
1231
|
+
|
|
1232
|
+
await waitFor(() =>
|
|
1233
|
+
expect(server.received).toEqual([
|
|
1234
|
+
{ type: "message/switch-branch", branchId: 1 },
|
|
1235
|
+
]),
|
|
1236
|
+
);
|
|
1237
|
+
});
|
|
1238
|
+
|
|
1239
|
+
it("propagates a rejected message/switch-branch through onError", async () => {
|
|
1240
|
+
const server = createBranchServer({ reject: true });
|
|
1241
|
+
const errors: Error[] = [];
|
|
1242
|
+
const { aui } = mountThread({
|
|
1243
|
+
transport: server.transport,
|
|
1244
|
+
converter: withBranch({ id: 2, siblings: [1, 2, 3] }),
|
|
1245
|
+
capabilities: { unstable_switchBranch: true },
|
|
1246
|
+
onError: (error) => {
|
|
1247
|
+
errors.push(error);
|
|
1248
|
+
},
|
|
1249
|
+
});
|
|
1250
|
+
|
|
1251
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["hi", "hello"]));
|
|
1252
|
+
aui().thread().message({ id: "u1" }).switchToBranch({ position: "next" });
|
|
1253
|
+
|
|
1254
|
+
await waitFor(() => expect(errors).toHaveLength(1));
|
|
1255
|
+
expect(errors[0]!.message).toContain("host busy");
|
|
1256
|
+
});
|
|
1257
|
+
|
|
1258
|
+
it("leaves the branch surface off without the capability", async () => {
|
|
1259
|
+
const server = createBranchServer();
|
|
1260
|
+
const { aui } = mountThread({
|
|
1261
|
+
transport: server.transport,
|
|
1262
|
+
converter: withBranch({ id: 2, siblings: [1, 2, 3] }),
|
|
1263
|
+
});
|
|
1264
|
+
|
|
1265
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["hi", "hello"]));
|
|
1266
|
+
const messageState = aui().thread().message({ id: "u1" }).getState();
|
|
1267
|
+
expect(messageState.branchNumber).toBe(1);
|
|
1268
|
+
expect(messageState.branchCount).toBe(1);
|
|
1269
|
+
});
|
|
1270
|
+
});
|
|
1271
|
+
|
|
1171
1272
|
describe("connection", () => {
|
|
1172
1273
|
const trackStatuses = (seen: string[]) => {
|
|
1173
1274
|
const trackingConverter: StatewireThread.StateConverter<ServerState> = (
|
package/src/StatewireThread.ts
CHANGED
|
@@ -30,6 +30,7 @@ import type { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
|
30
30
|
import { useStatewire } from "statewire";
|
|
31
31
|
import type { Statewire, StatewireClient } from "statewire";
|
|
32
32
|
import {
|
|
33
|
+
createBranchCommandAdapter,
|
|
33
34
|
createRunQueueAdapter,
|
|
34
35
|
resolveEditCommand,
|
|
35
36
|
resolveReloadCommand,
|
|
@@ -67,6 +68,20 @@ const RESTING_RUNS: StatewireThread.Runs = {
|
|
|
67
68
|
steerQueue: [],
|
|
68
69
|
};
|
|
69
70
|
|
|
71
|
+
// Derived presentation while the connection can't vouch for progress:
|
|
72
|
+
// live-claiming "running" reads as evicted/disconnected; facts pass through.
|
|
73
|
+
const presentStatus = (
|
|
74
|
+
status: StatewireThread.ThreadStatus,
|
|
75
|
+
connection: StatewireClient.ConnectionState,
|
|
76
|
+
): StatewireThread.ThreadStatus =>
|
|
77
|
+
status !== "running" ||
|
|
78
|
+
connection.status === "live" ||
|
|
79
|
+
connection.status === "idle"
|
|
80
|
+
? status
|
|
81
|
+
: connection.status === "reconnecting" && connection.cause === "evicted"
|
|
82
|
+
? "evicted"
|
|
83
|
+
: "disconnected";
|
|
84
|
+
|
|
70
85
|
const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
|
|
71
86
|
...(context.system !== undefined && { system: context.system }),
|
|
72
87
|
...(context.tools !== undefined && {
|
|
@@ -183,7 +198,10 @@ const useStatewireThread = (
|
|
|
183
198
|
)?.runs;
|
|
184
199
|
const entry = entries?.[0];
|
|
185
200
|
return {
|
|
186
|
-
status:
|
|
201
|
+
status: presentStatus(
|
|
202
|
+
entries === undefined ? "loading" : (entry?.status ?? "ready"),
|
|
203
|
+
connection,
|
|
204
|
+
),
|
|
187
205
|
runs:
|
|
188
206
|
entry === undefined
|
|
189
207
|
? RESTING_RUNS
|
|
@@ -205,7 +223,7 @@ const useStatewireThread = (
|
|
|
205
223
|
...(entry.error !== undefined && { error: entry.error }),
|
|
206
224
|
},
|
|
207
225
|
};
|
|
208
|
-
}, [state]);
|
|
226
|
+
}, [state, connection]);
|
|
209
227
|
|
|
210
228
|
const { converter } = options;
|
|
211
229
|
const metadata = useMemo(
|
|
@@ -239,6 +257,11 @@ const useStatewireThread = (
|
|
|
239
257
|
[messages, liveRunId, runs, dispatch, dispatchSend],
|
|
240
258
|
);
|
|
241
259
|
|
|
260
|
+
const branches = useMemo(
|
|
261
|
+
() => createBranchCommandAdapter(messages, dispatch),
|
|
262
|
+
[messages, dispatch],
|
|
263
|
+
);
|
|
264
|
+
|
|
242
265
|
const inputRequests = runs.inputRequests ?? NO_INPUT_REQUESTS;
|
|
243
266
|
|
|
244
267
|
const extras = useMemo(
|
|
@@ -307,6 +330,7 @@ const useStatewireThread = (
|
|
|
307
330
|
}),
|
|
308
331
|
}),
|
|
309
332
|
...(options.capabilities?.reload && { onReload: handleReload }),
|
|
333
|
+
...(options.capabilities?.unstable_switchBranch && { branches }),
|
|
310
334
|
onAddToolResult: (toolOptions: AddToolResultOptions) =>
|
|
311
335
|
dispatch(resolveToolResultInput(inputRequests, toolOptions, liveRunId)),
|
|
312
336
|
onRespondToToolApproval: (approval: RespondToToolApprovalOptions) =>
|
|
@@ -455,8 +479,8 @@ export namespace StatewireThread {
|
|
|
455
479
|
readonly insertBefore?: string | null;
|
|
456
480
|
};
|
|
457
481
|
|
|
458
|
-
|
|
459
|
-
readonly type:
|
|
482
|
+
type RunSendCommand<TType extends "run/enqueue" | "run/steer"> = {
|
|
483
|
+
readonly type: TType;
|
|
460
484
|
/** The run this command targets — the live run's id, or a fresh client-minted uuid on run-creating sends. */
|
|
461
485
|
readonly runId: string;
|
|
462
486
|
} & (
|
|
@@ -469,19 +493,9 @@ export namespace StatewireThread {
|
|
|
469
493
|
) &
|
|
470
494
|
Placement;
|
|
471
495
|
|
|
472
|
-
export type
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
readonly runId: string;
|
|
476
|
-
} & (
|
|
477
|
-
| {
|
|
478
|
-
readonly message: UserMessage;
|
|
479
|
-
/** 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. */
|
|
480
|
-
readonly runAnchorMessageId?: string | null;
|
|
481
|
-
}
|
|
482
|
-
| { readonly messageId: string }
|
|
483
|
-
) &
|
|
484
|
-
Placement;
|
|
496
|
+
export type RunEnqueueCommand = RunSendCommand<"run/enqueue">;
|
|
497
|
+
|
|
498
|
+
export type RunSteerCommand = RunSendCommand<"run/steer">;
|
|
485
499
|
|
|
486
500
|
export type RunDequeueCommand = {
|
|
487
501
|
readonly type: "run/dequeue";
|
|
@@ -544,6 +558,17 @@ export namespace StatewireThread {
|
|
|
544
558
|
readonly meta?: ReadonlyJSONValue;
|
|
545
559
|
};
|
|
546
560
|
|
|
561
|
+
/** Per-message branch metadata read from `metadata.custom.branch`: the message's own branch id and the fan-out's branch ids in creation order (own id included). */
|
|
562
|
+
export type BranchMetadata = {
|
|
563
|
+
readonly id: number;
|
|
564
|
+
readonly siblings: readonly number[];
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
export type SwitchBranchCommand = {
|
|
568
|
+
readonly type: "message/switch-branch";
|
|
569
|
+
readonly branchId: number;
|
|
570
|
+
};
|
|
571
|
+
|
|
547
572
|
export type RunReloadCommand = {
|
|
548
573
|
readonly type: "run/reload";
|
|
549
574
|
/** The live run's id when redirecting it, or a fresh client-minted uuid when idle. */
|
|
@@ -573,8 +598,13 @@ export namespace StatewireThread {
|
|
|
573
598
|
/** Run subsystem status replicated by the host. */
|
|
574
599
|
export type RunStatus = "running" | "stopped" | "error" | "input-required";
|
|
575
600
|
|
|
576
|
-
/** The thread's status
|
|
577
|
-
export type ThreadStatus =
|
|
601
|
+
/** The thread's status: `"loading"` while the runs mount is absent, `"ready"` while resting, otherwise the run's status; `"evicted"` and `"disconnected"` are client-derived from the connection, never replicated. */
|
|
602
|
+
export type ThreadStatus =
|
|
603
|
+
| "loading"
|
|
604
|
+
| "ready"
|
|
605
|
+
| "evicted"
|
|
606
|
+
| "disconnected"
|
|
607
|
+
| RunStatus;
|
|
578
608
|
|
|
579
609
|
/** A queue-lane entry as replicated: the user message plus host-stamped `meta`. */
|
|
580
610
|
export type RunsQueueEntry = UserMessage & {
|
|
@@ -650,7 +680,7 @@ export namespace StatewireThread {
|
|
|
650
680
|
/** The runs mount as replicated: the run entries plus the top-level status projection. */
|
|
651
681
|
export type RunsState = {
|
|
652
682
|
/** Projection of `runs[0]?.status ?? "ready"`. */
|
|
653
|
-
readonly status:
|
|
683
|
+
readonly status: "ready" | RunStatus;
|
|
654
684
|
/** At most one entry; empty while resting. */
|
|
655
685
|
readonly runs: readonly RunState[];
|
|
656
686
|
};
|
|
@@ -750,6 +780,8 @@ export namespace StatewireThread {
|
|
|
750
780
|
continue?: boolean | undefined;
|
|
751
781
|
/** The host supports `run/reload` (regenerating an assistant message). */
|
|
752
782
|
reload?: boolean | undefined;
|
|
783
|
+
/** The host supports `message/switch-branch` (thread-global branch switching driven by `metadata.custom.branch`). */
|
|
784
|
+
unstable_switchBranch?: boolean | undefined;
|
|
753
785
|
}
|
|
754
786
|
| undefined;
|
|
755
787
|
/**
|
|
@@ -784,6 +816,7 @@ declare module "@assistant-ui/core" {
|
|
|
784
816
|
runContinue: StatewireThread.RunContinueCommand;
|
|
785
817
|
runReload: StatewireThread.RunReloadCommand;
|
|
786
818
|
runInput: StatewireThread.RunInputCommand;
|
|
819
|
+
messageSwitchBranch: StatewireThread.SwitchBranchCommand;
|
|
787
820
|
}
|
|
788
821
|
}
|
|
789
822
|
}
|
package/src/runCommands.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
AppendMessage,
|
|
3
|
+
ExternalThreadBranchAdapter,
|
|
3
4
|
ExternalThreadQueueAdapter,
|
|
4
5
|
QueuePlacement,
|
|
5
6
|
} from "@assistant-ui/core";
|
|
@@ -191,6 +192,46 @@ export const createRunQueueAdapter = (
|
|
|
191
192
|
};
|
|
192
193
|
};
|
|
193
194
|
|
|
195
|
+
const branchOf = (
|
|
196
|
+
message: { metadata: { custom: Record<string, unknown> } } | undefined,
|
|
197
|
+
): StatewireThread.BranchMetadata | undefined => {
|
|
198
|
+
const branch = message?.metadata.custom["branch"];
|
|
199
|
+
if (branch === undefined) return undefined;
|
|
200
|
+
const { id, siblings } = branch as StatewireThread.BranchMetadata;
|
|
201
|
+
if (
|
|
202
|
+
!Number.isInteger(id) ||
|
|
203
|
+
!Array.isArray(siblings) ||
|
|
204
|
+
!siblings.every(Number.isInteger) ||
|
|
205
|
+
!siblings.includes(id)
|
|
206
|
+
)
|
|
207
|
+
throw new Error("statewire: malformed branch metadata");
|
|
208
|
+
return { id, siblings };
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */
|
|
212
|
+
export const createBranchCommandAdapter = (
|
|
213
|
+
messages: readonly {
|
|
214
|
+
id: string;
|
|
215
|
+
metadata: { custom: Record<string, unknown> };
|
|
216
|
+
}[],
|
|
217
|
+
dispatch: (command: StatewireThread.SwitchBranchCommand) => void,
|
|
218
|
+
): ExternalThreadBranchAdapter => ({
|
|
219
|
+
getBranches: (messageId) => {
|
|
220
|
+
const branch = branchOf(messages.find((m) => m.id === messageId));
|
|
221
|
+
if (branch === undefined) return [];
|
|
222
|
+
// the own slot carries the message id so the picker can locate its position
|
|
223
|
+
return branch.siblings.map((sibling) =>
|
|
224
|
+
sibling === branch.id ? messageId : String(sibling),
|
|
225
|
+
);
|
|
226
|
+
},
|
|
227
|
+
switchToBranch: (branchId) => {
|
|
228
|
+
const target = Number(branchId);
|
|
229
|
+
if (!Number.isInteger(target))
|
|
230
|
+
throw new Error(`statewire: unknown branch "${branchId}"`);
|
|
231
|
+
dispatch({ type: "message/switch-branch", branchId: target });
|
|
232
|
+
},
|
|
233
|
+
});
|
|
234
|
+
|
|
194
235
|
export const resolveReloadCommand = (
|
|
195
236
|
messages: readonly { id: string; role: string }[],
|
|
196
237
|
parentId: string | null,
|
|
@@ -270,7 +270,7 @@ describe("runsOptimistic", () => {
|
|
|
270
270
|
});
|
|
271
271
|
});
|
|
272
272
|
|
|
273
|
-
it("run/stop
|
|
273
|
+
it("run/stop leaves a staged rewind and its window in place", () => {
|
|
274
274
|
const draft = mount({ status: "running", runId: "run-1" });
|
|
275
275
|
apply(draft, "run/edit", {
|
|
276
276
|
type: "run/edit",
|
|
@@ -280,11 +280,73 @@ describe("runsOptimistic", () => {
|
|
|
280
280
|
runAnchorMessageId: "p0",
|
|
281
281
|
});
|
|
282
282
|
apply(draft, "run/stop", { runId: "run-1" });
|
|
283
|
-
expect(run(draft).stopping).toEqual({ reason: "
|
|
284
|
-
expect(run(draft).nextDispatch).
|
|
283
|
+
expect(run(draft).stopping).toEqual({ reason: "message-edit" });
|
|
284
|
+
expect(run(draft).nextDispatch).toEqual({
|
|
285
|
+
trigger: "message-edit",
|
|
286
|
+
messages: [message("m1b")],
|
|
287
|
+
rollbackTo: "p0",
|
|
288
|
+
});
|
|
285
289
|
expect(run(draft).status).toBe("running");
|
|
286
290
|
});
|
|
287
291
|
|
|
292
|
+
it("a second run/edit appends to the staged rewind, keeping its anchor", () => {
|
|
293
|
+
const draft = mount({ status: "running", runId: "run-1" });
|
|
294
|
+
apply(draft, "run/edit", {
|
|
295
|
+
type: "run/edit",
|
|
296
|
+
runId: "run-1",
|
|
297
|
+
message: message("m1b"),
|
|
298
|
+
sourceId: "m1",
|
|
299
|
+
runAnchorMessageId: "p0",
|
|
300
|
+
});
|
|
301
|
+
apply(draft, "run/edit", {
|
|
302
|
+
type: "run/edit",
|
|
303
|
+
runId: "run-1",
|
|
304
|
+
message: message("m2b"),
|
|
305
|
+
sourceId: "m2",
|
|
306
|
+
runAnchorMessageId: "a1",
|
|
307
|
+
});
|
|
308
|
+
expect(run(draft).nextDispatch).toEqual({
|
|
309
|
+
trigger: "message-edit",
|
|
310
|
+
messages: [message("m1b"), message("m2b")],
|
|
311
|
+
rollbackTo: "p0",
|
|
312
|
+
});
|
|
313
|
+
expect(run(draft).stopping).toEqual({ reason: "message-edit" });
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it("run/edit replaces a staged reload; run/reload leaves a staged rewind", () => {
|
|
317
|
+
const draft = mount({ status: "running", runId: "run-1" });
|
|
318
|
+
apply(draft, "run/reload", {
|
|
319
|
+
type: "run/reload",
|
|
320
|
+
runId: "run-1",
|
|
321
|
+
sourceId: "a1",
|
|
322
|
+
runAnchorMessageId: "m1",
|
|
323
|
+
});
|
|
324
|
+
apply(draft, "run/edit", {
|
|
325
|
+
type: "run/edit",
|
|
326
|
+
runId: "run-1",
|
|
327
|
+
message: message("m1b"),
|
|
328
|
+
sourceId: "m1",
|
|
329
|
+
runAnchorMessageId: "p0",
|
|
330
|
+
});
|
|
331
|
+
expect(run(draft).nextDispatch).toEqual({
|
|
332
|
+
trigger: "message-edit",
|
|
333
|
+
messages: [message("m1b")],
|
|
334
|
+
rollbackTo: "p0",
|
|
335
|
+
});
|
|
336
|
+
apply(draft, "run/reload", {
|
|
337
|
+
type: "run/reload",
|
|
338
|
+
runId: "run-1",
|
|
339
|
+
sourceId: "a1",
|
|
340
|
+
runAnchorMessageId: "m1",
|
|
341
|
+
});
|
|
342
|
+
expect(run(draft).nextDispatch).toEqual({
|
|
343
|
+
trigger: "message-edit",
|
|
344
|
+
messages: [message("m1b")],
|
|
345
|
+
rollbackTo: "p0",
|
|
346
|
+
});
|
|
347
|
+
expect(run(draft).stopping).toEqual({ reason: "message-edit" });
|
|
348
|
+
});
|
|
349
|
+
|
|
288
350
|
it("run/reload predicts the rewind dispatch record", () => {
|
|
289
351
|
const draft = mount({
|
|
290
352
|
status: "stopped",
|