@assistant-ui/react-statewire 0.28.1 → 0.29.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/StatewireThread.d.ts +17 -2
- package/dist/StatewireThread.d.ts.map +1 -1
- package/dist/StatewireThread.js +41 -10
- package/dist/StatewireThread.js.map +1 -1
- package/dist/localStorage.d.ts +1 -1
- package/dist/localStorage.d.ts.map +1 -1
- package/dist/localStorage.js +2 -2
- package/dist/localStorage.js.map +1 -1
- package/dist/runCommands.d.ts.map +1 -1
- package/dist/runCommands.js +2 -1
- package/dist/runCommands.js.map +1 -1
- package/package.json +2 -2
- package/src/StatewireThread.drafts.test.tsx +12 -16
- package/src/StatewireThread.failed.test.tsx +13 -16
- package/src/StatewireThread.retract.test.tsx +3 -3
- package/src/StatewireThread.runs.test.tsx +11 -16
- package/src/StatewireThread.test.tsx +109 -16
- package/src/StatewireThread.ts +78 -12
- package/src/localStorage.test.ts +14 -15
- package/src/localStorage.ts +3 -3
- package/src/runCommands.test.ts +31 -0
- package/src/runCommands.ts +8 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAQa,gBACX,SAAS,eACT,eACC,gBAAgB;
|
|
1
|
+
{"version":3,"file":"runCommands.d.ts","names":[],"sources":["../src/runCommands.ts"],"mappings":";;;cAQa,gBACX,SAAS,eACT,eACC,gBAAgB;cAgFN,qBACX;EAAqB;KACrB,SAAS,eACT,yBACC,gBAAgB;;cAkBN,aACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,SAAS,gBAAgB;EAEzB;EACA,SAAS,gBAAgB;EACzB;;;cAWW,eACX;EAAqB;EAAY;IAAW;;KAC5C,sBACA,UACK,gBAAgB;EACf,SAAS,gBAAgB;MAE1B,gBAAgB;EACf,SAAS,gBAAgB;KAE3B,gBAAgB,mBACnB,gBAAgB;cAoBN,wBACX;EAAqB;KACrB,sBACA,qBAAqB,gBAAgB,gBACrC,0BAA0B,gBAAgB,gBAC1C,WAAW,SAAS,gBAAgB,qBACpC,eACE,SAAS,gBAAgB,YACzB,SAAS,2BAEV;;cA8EU,6BACX;EACE;EACA;IAAY,QAAQ;;KAEtB,WAAW,SAAS,gBAAgB,iCACnC;cAiBU,uBACX;EAAqB;EAAY;KACjC,yBACA,yBACC,gBAAgB"}
|
package/dist/runCommands.js
CHANGED
|
@@ -25,7 +25,8 @@ const toWireMessage = (message, id) => {
|
|
|
25
25
|
return {
|
|
26
26
|
id,
|
|
27
27
|
role: "user",
|
|
28
|
-
parts
|
|
28
|
+
parts,
|
|
29
|
+
...message.metadata?.custom !== void 0 && { metadata: JSON.parse(JSON.stringify(message.metadata.custom)) }
|
|
29
30
|
};
|
|
30
31
|
};
|
|
31
32
|
const toQueueItemState = (item) => ({
|
package/dist/runCommands.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","retryCommand","command","RunEnqueueCommand","RunSteerCommand","RunCommand","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","metadata","custom","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return { id, role: \"user\", parts };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\n/** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */\nexport const retryCommand = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n command:\n | (StatewireThread.RunEnqueueCommand & {\n message: StatewireThread.UserMessage;\n })\n | (StatewireThread.RunSteerCommand & {\n message: StatewireThread.UserMessage;\n })\n | StatewireThread.RunEditCommand,\n): StatewireThread.RunCommand => {\n if (command.type === \"run/edit\") {\n const index = messages.findIndex((m) => m.id === command.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${command.sourceId}\" is unknown`,\n );\n return {\n ...command,\n runId: runId ?? crypto.randomUUID(),\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n }\n if (runId !== null && command.runId === runId) return command;\n return {\n type: \"run/enqueue\",\n ...sendFields(messages, runId, command.message),\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.rand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AAW7D,KAAAA,GAAW,OAAO,CAAA;EAEjC,OAAO6D,OAAOC,SAASpD,KAAK+D,YAC1BA,YAAYZ,OAAOnF,KAAK0E,YAAYsB,OAAOD,OAAO,CACpD;CACF;CACAE,iBAAiBC,aAAa;EAC5B,MAAMC,SAASd,OAAOa,QAAQ;EAC9B,IAAI,CAACb,OAAOC,UAAUa,MAAM,GAC1B,MAAM,IAAIhG,MAAM,8BAA8B+F,SAAQ,EAAG;EAC3DtC,SAAS;GAAE/C,MAAM;GAAyBqF,UAAUC;EAAO,CAAC;CAC9D;AACF;AAEA,MAAaC,wBACX9D,UACA+D,UACA3D,UACqC;CACrC,MAAMG,QACJwD,aAAa,OACT,IACA/D,SAASQ,WAAW/C,YAAYA,QAAQC,OAAOqG,QAAQ,IAAI;CACjE,IAAIA,aAAa,QAAQxD,UAAU,GACjC,MAAM,IAAI1C,MAAM,iCAAiCkG,SAAQ,aAAc;CACzE,MAAMF,SAAS7D,SAASO;CACxB,IAAIsD,WAAW7E,KAAAA,KAAa6E,OAAOjG,SAAS,aAC1C,MAAM,IAAIC,MACR,mEACF;CACF,OAAO;EACLU,MAAM;EACN6B,OAAOA,SAASM,OAAOC,WAAW;EAClCL,UAAUuD,OAAOnG;EACjBkD,oBAAoBmD;CACtB;AACF"}
|
|
1
|
+
{"version":3,"file":"runCommands.js","names":["AppendMessage","ExternalThreadBranchAdapter","ExternalThreadQueueAdapter","QueuePlacement","StatewireThread","toWireMessage","message","id","UserMessage","role","Error","files","FilePart","texts","source","content","attachments","flatMap","a","part","type","push","text","mediaType","url","image","mimeType","data","filename","undefined","parts","TextPart","length","const","join","metadata","custom","JSON","parse","stringify","toQueueItemState","item","RunQueueItem","prompt","map","placementFields","placement","insertAfter","insertBefore","viewedLeafId","messages","status","i","resolveEditCommand","runId","RunEditCommand","sourceId","index","findIndex","m","crypto","randomUUID","runAnchorMessageId","sendFields","retryCommand","command","RunEnqueueCommand","RunSteerCommand","RunCommand","createRunQueueAdapter","queueItems","steerQueueItems","dispatch","dispatchSend","liveRunId","laneOf","queueItemId","some","sendCommand","lane","fields","items","steerItems","enqueue","steer","move","messageId","edit","wireMessage","remove","branchOf","Record","BranchMetadata","branch","siblings","Number","isInteger","Array","isArray","every","includes","createBranchCommandAdapter","SwitchBranchCommand","getBranches","find","sibling","String","switchToBranch","branchId","target","resolveReloadCommand","parentId","RunReloadCommand"],"sources":["../src/runCommands.ts"],"sourcesContent":["import type {\n AppendMessage,\n ExternalThreadBranchAdapter,\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"@assistant-ui/core\";\nimport type { StatewireThread } from \"./StatewireThread\";\n\nexport const toWireMessage = (\n message: AppendMessage,\n id: string,\n): StatewireThread.UserMessage => {\n if (message.role !== \"user\")\n throw new Error(\"statewire: only user messages are supported\");\n const files: StatewireThread.FilePart[] = [];\n const texts: string[] = [];\n const source = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const part of source) {\n if (part.type === \"text\") {\n texts.push(part.text);\n } else if (part.type === \"image\") {\n files.push({ type: \"file\", mediaType: \"image/*\", url: part.image });\n } else if (part.type === \"file\") {\n files.push({\n type: \"file\",\n mediaType: part.mimeType,\n url: part.data,\n ...(part.filename !== undefined && { filename: part.filename }),\n });\n } else {\n throw new Error(`statewire: unsupported message part \"${part.type}\"`);\n }\n }\n // default-safe against host capabilities: files first, one merged text part\n const parts: (StatewireThread.TextPart | StatewireThread.FilePart)[] = [\n ...files,\n ...(texts.length > 0\n ? [{ type: \"text\" as const, text: texts.join(\"\\n\\n\") }]\n : []),\n ];\n if (parts.length === 0)\n throw new Error(\"statewire: cannot send an empty message\");\n return {\n id,\n role: \"user\",\n parts,\n ...(message.metadata?.custom !== undefined && {\n metadata: JSON.parse(JSON.stringify(message.metadata.custom)),\n }),\n };\n};\n\nconst toQueueItemState = (item: StatewireThread.RunQueueItem) => ({\n id: item.id,\n prompt: item.parts\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\\n\\n\"),\n parts: item.parts.map((part) =>\n part.type === \"text\"\n ? part\n : {\n type: \"file\" as const,\n data: part.url,\n mimeType: part.mediaType,\n ...(part.filename !== undefined && { filename: part.filename }),\n },\n ),\n});\n\nconst placementFields = (placement: QueuePlacement) => ({\n ...(placement.insertAfter !== undefined && {\n insertAfter: placement.insertAfter,\n }),\n ...(placement.insertBefore !== undefined && {\n insertBefore: placement.insertBefore,\n }),\n});\n\nconst viewedLeafId = (\n messages: readonly { id: string; status?: { type: string } }[],\n): string | null => {\n // An in-flight assistant message is not host-committed history: anchor below it.\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.status?.type !== \"running\") return messages[i]!.id;\n }\n return null;\n};\n\nexport const resolveEditCommand = (\n messages: readonly { id: string }[],\n message: AppendMessage,\n runId: string | null,\n): StatewireThread.RunEditCommand => {\n if (message.sourceId == null)\n throw new Error(\"statewire: run/edit requires a sourceId\");\n const index = messages.findIndex((m) => m.id === message.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${message.sourceId}\" is unknown`,\n );\n return {\n type: \"run/edit\",\n runId: runId ?? crypto.randomUUID(),\n message: toWireMessage(message, crypto.randomUUID()),\n sourceId: message.sourceId,\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n};\n\n/** The send fields for a run-creating or run-targeting enqueue/steer: target the live run, or mint a fresh one anchored at the viewed leaf. */\nexport const sendFields = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n message: StatewireThread.UserMessage,\n): {\n runId: string;\n message: StatewireThread.UserMessage;\n runAnchorMessageId?: string | null;\n} =>\n runId !== null\n ? { runId, message }\n : {\n runId: crypto.randomUUID(),\n message,\n runAnchorMessageId: viewedLeafId(messages),\n };\n\n/** Rebuilds a failed send against the current thread: edits re-anchor at the source's current parent, sends whose target run is gone fall back to a fresh enqueue. */\nexport const retryCommand = (\n messages: readonly { id: string; status?: { type: string } }[],\n runId: string | null,\n command:\n | (StatewireThread.RunEnqueueCommand & {\n message: StatewireThread.UserMessage;\n })\n | (StatewireThread.RunSteerCommand & {\n message: StatewireThread.UserMessage;\n })\n | StatewireThread.RunEditCommand,\n): StatewireThread.RunCommand => {\n if (command.type === \"run/edit\") {\n const index = messages.findIndex((m) => m.id === command.sourceId);\n if (index === -1)\n throw new Error(\n `statewire: run/edit source \"${command.sourceId}\" is unknown`,\n );\n return {\n ...command,\n runId: runId ?? crypto.randomUUID(),\n runAnchorMessageId: messages[index - 1]?.id ?? null,\n };\n }\n if (runId !== null && command.runId === runId) return command;\n return {\n type: \"run/enqueue\",\n ...sendFields(messages, runId, command.message),\n };\n};\n\nexport const createRunQueueAdapter = (\n messages: readonly { id: string }[],\n runId: string | null,\n queueItems: readonly StatewireThread.RunQueueItem[],\n steerQueueItems: readonly StatewireThread.RunQueueItem[],\n dispatch: (command: StatewireThread.RunCommand) => void,\n dispatchSend: (\n command: StatewireThread.RunCommand,\n message: AppendMessage,\n ) => void,\n): ExternalThreadQueueAdapter => {\n const liveRunId = (): string => {\n if (runId === null) throw new Error(\"statewire: no live run to target\");\n return runId;\n };\n const laneOf = (queueItemId: string): \"queue\" | \"steer\" => {\n if (steerQueueItems.some((item) => item.id === queueItemId)) return \"steer\";\n if (queueItems.some((item) => item.id === queueItemId)) return \"queue\";\n throw new Error(`statewire: unknown queue item \"${queueItemId}\"`);\n };\n // edit-composer sends carry a sourceId; they bypass the lanes into run/edit\n const sendCommand = (\n lane: \"queue\" | \"steer\",\n message: AppendMessage,\n ): StatewireThread.RunCommand => {\n if (message.sourceId != null)\n return resolveEditCommand(messages, message, runId);\n const fields = sendFields(\n messages,\n runId,\n toWireMessage(message, crypto.randomUUID()),\n );\n return lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields };\n };\n return {\n items: queueItems.map(toQueueItemState),\n steerItems: steerQueueItems.map(toQueueItemState),\n enqueue: (message) => dispatchSend(sendCommand(\"queue\", message), message),\n steer: (message) => dispatchSend(sendCommand(\"steer\", message), message),\n move: (queueItemId, placement) => {\n const lane = placement.lane ?? laneOf(queueItemId);\n const fields = {\n runId: liveRunId(),\n messageId: queueItemId,\n ...placementFields(placement),\n };\n dispatch(\n lane === \"steer\"\n ? { type: \"run/steer\", ...fields }\n : { type: \"run/enqueue\", ...fields },\n );\n },\n edit: (queueItemId, message) => {\n const wireMessage = toWireMessage(message, queueItemId);\n dispatch(\n laneOf(queueItemId) === \"steer\"\n ? { type: \"run/steer\", runId: liveRunId(), message: wireMessage }\n : { type: \"run/enqueue\", runId: liveRunId(), message: wireMessage },\n );\n },\n remove: (queueItemId) =>\n dispatch({\n type: \"run/dequeue\",\n runId: liveRunId(),\n messageId: queueItemId,\n }),\n };\n};\n\nconst branchOf = (\n message: { metadata: { custom: Record<string, unknown> } } | undefined,\n): StatewireThread.BranchMetadata | undefined => {\n const branch = message?.metadata.custom[\"branch\"];\n if (branch === undefined) return undefined;\n const { id, siblings } = branch as StatewireThread.BranchMetadata;\n if (\n !Number.isInteger(id) ||\n !Array.isArray(siblings) ||\n !siblings.every(Number.isInteger) ||\n !siblings.includes(id)\n )\n throw new Error(\"statewire: malformed branch metadata\");\n return { id, siblings };\n};\n\n/** Branch surface over the host's thread-global branch: siblings come from `metadata.custom.branch`, switching sends `message/switch-branch`. */\nexport const createBranchCommandAdapter = (\n messages: readonly {\n id: string;\n metadata: { custom: Record<string, unknown> };\n }[],\n dispatch: (command: StatewireThread.SwitchBranchCommand) => void,\n): ExternalThreadBranchAdapter => ({\n getBranches: (messageId) => {\n const branch = branchOf(messages.find((m) => m.id === messageId));\n if (branch === undefined) return [];\n // the own slot carries the message id so the picker can locate its position\n return branch.siblings.map((sibling) =>\n sibling === branch.id ? messageId : String(sibling),\n );\n },\n switchToBranch: (branchId) => {\n const target = Number(branchId);\n if (!Number.isInteger(target))\n throw new Error(`statewire: unknown branch \"${branchId}\"`);\n dispatch({ type: \"message/switch-branch\", branchId: target });\n },\n});\n\nexport const resolveReloadCommand = (\n messages: readonly { id: string; role: string }[],\n parentId: string | null,\n runId: string | null,\n): StatewireThread.RunReloadCommand => {\n const index =\n parentId === null\n ? 0\n : messages.findIndex((message) => message.id === parentId) + 1;\n if (parentId !== null && index === 0)\n throw new Error(`statewire: run/reload parent \"${parentId}\" is unknown`);\n const target = messages[index];\n if (target === undefined || target.role !== \"assistant\")\n throw new Error(\n \"statewire: run/reload requires an assistant message to regenerate\",\n );\n return {\n type: \"run/reload\",\n runId: runId ?? crypto.randomUUID(),\n sourceId: target.id,\n runAnchorMessageId: parentId,\n };\n};\n"],"mappings":";AAQA,MAAaK,iBACXC,SACAC,OACgC;CAChC,IAAID,QAAQG,SAAS,QACnB,MAAM,IAAIC,MAAM,6CAA6C;CAC/D,MAAMC,QAAoC,CAAA;CAC1C,MAAME,QAAkB,CAAA;CACxB,MAAMC,SAAS,CACb,GAAGR,QAAQS,SACX,GAAIT,QAAQU,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,QAAQL,QACjB,IAAIK,KAAKC,SAAS,QAChBP,MAAMQ,KAAKF,KAAKG,IAAI;MACf,IAAIH,KAAKC,SAAS,SACvBT,MAAMU,KAAK;EAAED,MAAM;EAAQG,WAAW;EAAWC,KAAKL,KAAKM;CAAM,CAAC;MAC7D,IAAIN,KAAKC,SAAS,QACvBT,MAAMU,KAAK;EACTD,MAAM;EACNG,WAAWJ,KAAKO;EAChBF,KAAKL,KAAKQ;EACV,GAAIR,KAAKS,aAAaC,KAAAA,KAAa,EAAED,UAAUT,KAAKS,SAAS;CAC/D,CAAC;MAED,MAAM,IAAIlB,MAAM,wCAAwCS,KAAKC,KAAI,EAAG;CAIxE,MAAMU,QAAiE,CACrE,GAAGnB,OACH,GAAIE,MAAMmB,SAAS,IACf,CAAC;EAAEZ,MAAM;EAAiBE,MAAMT,MAAMqB,KAAK,MAAM;CAAE,CAAC,IACpD,CAAA,CAAG;CAET,IAAIJ,MAAME,WAAW,GACnB,MAA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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.29.1",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -38,7 +38,7 @@
|
|
|
38
38
|
"@assistant-ui/store": "^0.3.0",
|
|
39
39
|
"@assistant-ui/tap": "^0.9.7",
|
|
40
40
|
"assistant-stream": "^0.3.37",
|
|
41
|
-
"statewire": "^0.
|
|
41
|
+
"statewire": "^0.19.1"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
44
44
|
"@assistant-ui/core": ">=0.3.12",
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// @vitest-environment jsdom
|
|
2
2
|
|
|
3
3
|
// Contract tests for the composer draft storage seam: restore on mount,
|
|
4
|
-
//
|
|
4
|
+
// write-through in the commit that applies a change, clear when consumed.
|
|
5
5
|
|
|
6
6
|
import { act, render, waitFor } from "@testing-library/react";
|
|
7
7
|
import type { FC } from "react";
|
|
8
8
|
import { useState } from "react";
|
|
9
9
|
import { describe, expect, it } from "vitest";
|
|
10
|
-
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
10
|
+
import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
|
|
11
11
|
import { flushTapSync, resource } from "@assistant-ui/tap";
|
|
12
12
|
import {
|
|
13
13
|
StatewireReject,
|
|
@@ -84,7 +84,7 @@ const mountThread = (
|
|
|
84
84
|
const [storage, setStorage] =
|
|
85
85
|
useState<StatewireThread.Options<ServerState>["storage"]>();
|
|
86
86
|
knobs.setStorage = (element) => setStorage({ composer: element });
|
|
87
|
-
const
|
|
87
|
+
const config = AuiConfig({
|
|
88
88
|
thread: StatewireThread({
|
|
89
89
|
initialState: { messages: [], status: "ready", runs: [] },
|
|
90
90
|
converter,
|
|
@@ -93,7 +93,7 @@ const mountThread = (
|
|
|
93
93
|
}),
|
|
94
94
|
});
|
|
95
95
|
return (
|
|
96
|
-
<AuiProvider
|
|
96
|
+
<AuiProvider config={config}>
|
|
97
97
|
<Capture />
|
|
98
98
|
</AuiProvider>
|
|
99
99
|
);
|
|
@@ -136,13 +136,11 @@ describe("StatewireThread composer draft storage", () => {
|
|
|
136
136
|
});
|
|
137
137
|
await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
|
|
138
138
|
|
|
139
|
-
act(() =>
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
expect(store.cell.draft).toEqual({ text: "hello", attachments: [] });
|
|
145
|
-
});
|
|
139
|
+
act(() => flushTapSync(() => composerOf(aui).setText("hel")));
|
|
140
|
+
// the write landed in the commit that applied the text — no await, no timers
|
|
141
|
+
expect(store.cell.draft).toEqual({ text: "hel", attachments: [] });
|
|
142
|
+
act(() => flushTapSync(() => composerOf(aui).setText("hello")));
|
|
143
|
+
expect(store.cell.draft).toEqual({ text: "hello", attachments: [] });
|
|
146
144
|
expect(store.cell.log).toEqual(["write:hel", "write:hello"]);
|
|
147
145
|
});
|
|
148
146
|
|
|
@@ -155,11 +153,9 @@ describe("StatewireThread composer draft storage", () => {
|
|
|
155
153
|
});
|
|
156
154
|
await waitFor(() => expect(composerOf(aui).getState().type).toBe("thread"));
|
|
157
155
|
|
|
158
|
-
act(() =>
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
expect(store.cell.draft).toBeUndefined();
|
|
162
|
-
});
|
|
156
|
+
act(() => flushTapSync(() => composerOf(aui).setText("hello")));
|
|
157
|
+
act(() => flushTapSync(() => composerOf(aui).send()));
|
|
158
|
+
expect(store.cell.draft).toBeUndefined();
|
|
163
159
|
expect(store.cell.log).toEqual(["write:hello", "clear"]);
|
|
164
160
|
await waitFor(() => expect(server.received).toHaveLength(1));
|
|
165
161
|
});
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import { act, render, waitFor } from "@testing-library/react";
|
|
8
8
|
import type { FC } from "react";
|
|
9
9
|
import { describe, expect, it } from "vitest";
|
|
10
|
-
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
10
|
+
import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
|
|
11
11
|
import { StatewireHttp } from "statewire";
|
|
12
12
|
import { asStatewireExtras, StatewireThread } from "./StatewireThread";
|
|
13
13
|
import { useStatewireRuns } from "./hooks";
|
|
@@ -42,7 +42,7 @@ const extras = (aui: () => ReturnType<typeof useAui>) =>
|
|
|
42
42
|
// canonical state, for the covered contract.
|
|
43
43
|
const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
44
44
|
const received: { method: string; params: unknown[]; seq: number }[] = [];
|
|
45
|
-
const clients = new Map<string, { seq: number
|
|
45
|
+
const clients = new Map<string, { seq: number }>();
|
|
46
46
|
const encoder = new TextEncoder();
|
|
47
47
|
const frame = (chunk: unknown) => `data: ${JSON.stringify(chunk)}\n\n`;
|
|
48
48
|
let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
|
|
@@ -53,14 +53,10 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
53
53
|
const push = (chunk: unknown) =>
|
|
54
54
|
stream!.enqueue(encoder.encode(frame(chunk)));
|
|
55
55
|
type Frame = {
|
|
56
|
-
ctx?: { seq: number }[];
|
|
57
56
|
cmd?: { method: string; params: unknown[]; seq: number }[];
|
|
58
57
|
};
|
|
59
58
|
const admit = (clientId: string, body: Frame) => {
|
|
60
59
|
const rec = clients.get(clientId)!;
|
|
61
|
-
for (const statement of body.ctx ?? []) {
|
|
62
|
-
rec.ctxSeq = Math.max(rec.ctxSeq, statement.seq);
|
|
63
|
-
}
|
|
64
60
|
for (const statement of body.cmd ?? []) {
|
|
65
61
|
rec.seq = Math.max(rec.seq, statement.seq);
|
|
66
62
|
received.push({
|
|
@@ -68,8 +64,10 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
68
64
|
params: statement.params,
|
|
69
65
|
seq: statement.seq,
|
|
70
66
|
});
|
|
71
|
-
push({ cmd: [{ seq: statement.seq, dur: true }] });
|
|
72
|
-
push({
|
|
67
|
+
push({ cmd: [{ protocol: "default", seq: statement.seq, dur: true }] });
|
|
68
|
+
push({
|
|
69
|
+
cmd: [{ protocol: "default", seq: statement.seq, ...verdict() }],
|
|
70
|
+
});
|
|
73
71
|
}
|
|
74
72
|
};
|
|
75
73
|
const fetchImpl = (async (input: RequestInfo | URL, init2?: RequestInit) => {
|
|
@@ -78,9 +76,8 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
78
76
|
const clientId =
|
|
79
77
|
headers.get("Statewire-Client-Id") ?? [...clients.keys()].at(-1)!;
|
|
80
78
|
if (url.endsWith("/stream")) {
|
|
81
|
-
if (!clients.has(clientId)) clients.set(clientId, { seq: 0
|
|
79
|
+
if (!clients.has(clientId)) clients.set(clientId, { seq: 0 });
|
|
82
80
|
const rec = clients.get(clientId)!;
|
|
83
|
-
rec.ctxSeq = 0;
|
|
84
81
|
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
85
82
|
const body = new ReadableStream<Uint8Array>({
|
|
86
83
|
start: (c) => {
|
|
@@ -97,10 +94,10 @@ const createSettlingServer = (init?: Partial<ServerState>) => {
|
|
|
97
94
|
},
|
|
98
95
|
],
|
|
99
96
|
syn: {
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
97
|
+
version: "2026-09-13",
|
|
98
|
+
protocols: [
|
|
99
|
+
{ name: "default", version: "2026-09-13", seq: rec.seq },
|
|
100
|
+
],
|
|
104
101
|
},
|
|
105
102
|
}),
|
|
106
103
|
),
|
|
@@ -148,7 +145,7 @@ const mountThread = (
|
|
|
148
145
|
return null;
|
|
149
146
|
};
|
|
150
147
|
const App: FC = () => {
|
|
151
|
-
const
|
|
148
|
+
const config = AuiConfig({
|
|
152
149
|
thread: StatewireThread<ServerState>({
|
|
153
150
|
initialState: INITIAL_STATE,
|
|
154
151
|
converter,
|
|
@@ -156,7 +153,7 @@ const mountThread = (
|
|
|
156
153
|
}),
|
|
157
154
|
});
|
|
158
155
|
return (
|
|
159
|
-
<AuiProvider
|
|
156
|
+
<AuiProvider config={config}>
|
|
160
157
|
<Capture />
|
|
161
158
|
</AuiProvider>
|
|
162
159
|
);
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { act, render, waitFor } from "@testing-library/react";
|
|
9
9
|
import type { FC } from "react";
|
|
10
10
|
import { describe, expect, it } from "vitest";
|
|
11
|
-
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
11
|
+
import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
|
|
12
12
|
import { resource } from "@assistant-ui/tap";
|
|
13
13
|
import {
|
|
14
14
|
StatewireReject,
|
|
@@ -96,7 +96,7 @@ const mountThread = (
|
|
|
96
96
|
return null;
|
|
97
97
|
};
|
|
98
98
|
const App: FC = () => {
|
|
99
|
-
const
|
|
99
|
+
const config = AuiConfig({
|
|
100
100
|
thread: StatewireThread<ServerState>({
|
|
101
101
|
initialState: { messages: [], status: "ready", runs: [] },
|
|
102
102
|
converter,
|
|
@@ -104,7 +104,7 @@ const mountThread = (
|
|
|
104
104
|
}),
|
|
105
105
|
});
|
|
106
106
|
return (
|
|
107
|
-
<AuiProvider
|
|
107
|
+
<AuiProvider config={config}>
|
|
108
108
|
<Capture />
|
|
109
109
|
</AuiProvider>
|
|
110
110
|
);
|
|
@@ -9,7 +9,7 @@ import { useState } from "react";
|
|
|
9
9
|
import type { FC } from "react";
|
|
10
10
|
import type { ExternalThreadMessage } from "@assistant-ui/core/store";
|
|
11
11
|
import { describe, expect, it } from "vitest";
|
|
12
|
-
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
12
|
+
import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
|
|
13
13
|
import { resource, withKey } from "@assistant-ui/tap";
|
|
14
14
|
import { StatewireHttp } from "statewire";
|
|
15
15
|
import { useStatewireCommands, useStatewireState } from "statewire/host";
|
|
@@ -129,7 +129,7 @@ const createRemoteServer = (
|
|
|
129
129
|
) => {
|
|
130
130
|
const protocol = opts?.protocol ?? "default";
|
|
131
131
|
const received: { method: string; params: unknown[] }[] = [];
|
|
132
|
-
const clients = new Map<string, { seq: number
|
|
132
|
+
const clients = new Map<string, { seq: number }>();
|
|
133
133
|
const encoder = new TextEncoder();
|
|
134
134
|
const frame = (chunk: unknown) => `data: ${JSON.stringify(chunk)}\n\n`;
|
|
135
135
|
let released = !(opts?.hold ?? false);
|
|
@@ -151,14 +151,10 @@ const createRemoteServer = (
|
|
|
151
151
|
stream!.close();
|
|
152
152
|
};
|
|
153
153
|
type Frame = {
|
|
154
|
-
ctx?: { seq: number }[];
|
|
155
154
|
cmd?: { method: string; params: unknown[]; seq: number }[];
|
|
156
155
|
};
|
|
157
156
|
const admit = (clientId: string, body: Frame) => {
|
|
158
157
|
const rec = clients.get(clientId)!;
|
|
159
|
-
for (const statement of body.ctx ?? []) {
|
|
160
|
-
rec.ctxSeq = Math.max(rec.ctxSeq, statement.seq);
|
|
161
|
-
}
|
|
162
158
|
for (const statement of body.cmd ?? []) {
|
|
163
159
|
rec.seq = Math.max(rec.seq, statement.seq);
|
|
164
160
|
received.push({ method: statement.method, params: statement.params });
|
|
@@ -170,9 +166,8 @@ const createRemoteServer = (
|
|
|
170
166
|
const clientId =
|
|
171
167
|
headers.get("Statewire-Client-Id") ?? [...clients.keys()].at(-1)!;
|
|
172
168
|
if (url.endsWith("/stream")) {
|
|
173
|
-
if (!clients.has(clientId)) clients.set(clientId, { seq: 0
|
|
169
|
+
if (!clients.has(clientId)) clients.set(clientId, { seq: 0 });
|
|
174
170
|
const rec = clients.get(clientId)!;
|
|
175
|
-
rec.ctxSeq = 0;
|
|
176
171
|
const attachFrame = JSON.parse(String(init2?.body ?? "{}")) as Frame;
|
|
177
172
|
const body = new ReadableStream<Uint8Array>({
|
|
178
173
|
start: (c) => {
|
|
@@ -192,10 +187,10 @@ const createRemoteServer = (
|
|
|
192
187
|
},
|
|
193
188
|
],
|
|
194
189
|
syn: {
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
190
|
+
version: "2026-09-13",
|
|
191
|
+
protocols: [
|
|
192
|
+
{ name: protocol, version: "2026-09-13", seq: rec.seq },
|
|
193
|
+
],
|
|
199
194
|
},
|
|
200
195
|
}),
|
|
201
196
|
),
|
|
@@ -251,7 +246,7 @@ const mountThread = (
|
|
|
251
246
|
return null;
|
|
252
247
|
};
|
|
253
248
|
const App: FC = () => {
|
|
254
|
-
const
|
|
249
|
+
const config = AuiConfig({
|
|
255
250
|
thread: StatewireThread<RunsServerState>({
|
|
256
251
|
initialState: INITIAL_STATE,
|
|
257
252
|
converter,
|
|
@@ -259,7 +254,7 @@ const mountThread = (
|
|
|
259
254
|
}),
|
|
260
255
|
});
|
|
261
256
|
return (
|
|
262
|
-
<AuiProvider
|
|
257
|
+
<AuiProvider config={config}>
|
|
263
258
|
<Capture />
|
|
264
259
|
</AuiProvider>
|
|
265
260
|
);
|
|
@@ -779,7 +774,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
779
774
|
withKey("a", serverA.transport),
|
|
780
775
|
);
|
|
781
776
|
cell.swap = () => setTransport(() => withKey("b", serverB.transport));
|
|
782
|
-
const
|
|
777
|
+
const config = AuiConfig({
|
|
783
778
|
thread: StatewireThread<RunsServerState>({
|
|
784
779
|
initialState: preload,
|
|
785
780
|
converter,
|
|
@@ -787,7 +782,7 @@ describe("StatewireThread runs mode", () => {
|
|
|
787
782
|
}),
|
|
788
783
|
});
|
|
789
784
|
return (
|
|
790
|
-
<AuiProvider
|
|
785
|
+
<AuiProvider config={config}>
|
|
791
786
|
<Capture />
|
|
792
787
|
</AuiProvider>
|
|
793
788
|
);
|
|
@@ -7,7 +7,7 @@ import { act, render, waitFor } from "@testing-library/react";
|
|
|
7
7
|
import type { FC, ReactNode } from "react";
|
|
8
8
|
import { useState } from "react";
|
|
9
9
|
import { describe, expect, it } from "vitest";
|
|
10
|
-
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
10
|
+
import { AuiConfig, AuiProvider, useAui } from "@assistant-ui/store";
|
|
11
11
|
import { resource } from "@assistant-ui/tap";
|
|
12
12
|
import {
|
|
13
13
|
StatewireReject,
|
|
@@ -225,11 +225,11 @@ const mountThread = (
|
|
|
225
225
|
return null;
|
|
226
226
|
};
|
|
227
227
|
const App: FC = () => {
|
|
228
|
-
const
|
|
228
|
+
const config = AuiConfig({
|
|
229
229
|
thread: StatewireThread({ initialState: INITIAL_STATE, ...options }),
|
|
230
230
|
});
|
|
231
231
|
return (
|
|
232
|
-
<AuiProvider
|
|
232
|
+
<AuiProvider config={config}>
|
|
233
233
|
<Capture />
|
|
234
234
|
{children}
|
|
235
235
|
</AuiProvider>
|
|
@@ -436,7 +436,9 @@ describe("StatewireThread", () => {
|
|
|
436
436
|
await waitFor(() => expect(mock.commands).toHaveLength(1));
|
|
437
437
|
await act(async () => {
|
|
438
438
|
await mock.sendEnvelope({
|
|
439
|
-
cmd: [
|
|
439
|
+
cmd: [
|
|
440
|
+
{ protocol: "default", seq: 1, type: "rejected", message: "retry" },
|
|
441
|
+
],
|
|
440
442
|
});
|
|
441
443
|
});
|
|
442
444
|
await waitFor(() => expect(errors).toHaveLength(1));
|
|
@@ -584,7 +586,7 @@ describe("StatewireThread", () => {
|
|
|
584
586
|
expect(seen).toHaveLength(2);
|
|
585
587
|
});
|
|
586
588
|
|
|
587
|
-
it("fires onConnectionChange with the status
|
|
589
|
+
it("fires onConnectionChange with the initial status, then once per transition", async () => {
|
|
588
590
|
const statuses: string[] = [];
|
|
589
591
|
const mock = createMockTransport<ServerState>(INITIAL_STATE);
|
|
590
592
|
mountThread({
|
|
@@ -593,11 +595,15 @@ describe("StatewireThread", () => {
|
|
|
593
595
|
onConnectionChange: (connection) => statuses.push(connection.status),
|
|
594
596
|
});
|
|
595
597
|
|
|
596
|
-
await waitFor(() =>
|
|
598
|
+
await waitFor(() =>
|
|
599
|
+
expect(statuses).toEqual(["connecting", "connected"]),
|
|
600
|
+
);
|
|
597
601
|
await mock.finish("gone");
|
|
598
|
-
await waitFor(() =>
|
|
602
|
+
await waitFor(() =>
|
|
603
|
+
expect(statuses).toEqual(["connecting", "connected", "stopped"]),
|
|
604
|
+
);
|
|
599
605
|
await new Promise((r) => setTimeout(r, 20));
|
|
600
|
-
expect(statuses).toEqual(["connected", "stopped"]);
|
|
606
|
+
expect(statuses).toEqual(["connecting", "connected", "stopped"]);
|
|
601
607
|
});
|
|
602
608
|
|
|
603
609
|
it("stays quiet on unrelated re-renders and callback identity changes", async () => {
|
|
@@ -608,7 +614,7 @@ describe("StatewireThread", () => {
|
|
|
608
614
|
const App: FC = () => {
|
|
609
615
|
const [, setTick] = useState(0);
|
|
610
616
|
knobs.rerender = () => setTick((t) => t + 1);
|
|
611
|
-
const
|
|
617
|
+
const config = AuiConfig({
|
|
612
618
|
thread: StatewireThread({
|
|
613
619
|
initialState: INITIAL_STATE,
|
|
614
620
|
transport: server.transport,
|
|
@@ -618,7 +624,7 @@ describe("StatewireThread", () => {
|
|
|
618
624
|
statuses.push(connection.status),
|
|
619
625
|
}),
|
|
620
626
|
});
|
|
621
|
-
return <AuiProvider
|
|
627
|
+
return <AuiProvider config={config}>{null}</AuiProvider>;
|
|
622
628
|
};
|
|
623
629
|
render(<App />);
|
|
624
630
|
|
|
@@ -635,11 +641,22 @@ describe("StatewireThread", () => {
|
|
|
635
641
|
});
|
|
636
642
|
|
|
637
643
|
describe("contextSync: command-send", () => {
|
|
638
|
-
const contextValueOf = (command: {
|
|
639
|
-
|
|
644
|
+
const contextValueOf = (command: {
|
|
645
|
+
protocol: string;
|
|
646
|
+
method: string;
|
|
647
|
+
params: unknown[];
|
|
648
|
+
}) => {
|
|
649
|
+
expect([command.protocol, command.method]).toEqual([
|
|
650
|
+
"default/context",
|
|
651
|
+
"set",
|
|
652
|
+
]);
|
|
653
|
+
return command.params[0] as Record<string, unknown>;
|
|
654
|
+
};
|
|
640
655
|
|
|
641
656
|
it("sends the ambient model context on connect and on every change", async () => {
|
|
642
|
-
const mock = createMockTransport<ServerState>(INITIAL_STATE
|
|
657
|
+
const mock = createMockTransport<ServerState>(INITIAL_STATE, "default", {
|
|
658
|
+
ephemeral: ["context"],
|
|
659
|
+
});
|
|
643
660
|
const { aui } = mountThread({
|
|
644
661
|
transport: mock.transport,
|
|
645
662
|
converter,
|
|
@@ -659,7 +676,9 @@ describe("StatewireThread", () => {
|
|
|
659
676
|
});
|
|
660
677
|
|
|
661
678
|
it("skips resends while the serialized context is unchanged", async () => {
|
|
662
|
-
const mock = createMockTransport<ServerState>(INITIAL_STATE
|
|
679
|
+
const mock = createMockTransport<ServerState>(INITIAL_STATE, "default", {
|
|
680
|
+
ephemeral: ["context"],
|
|
681
|
+
});
|
|
663
682
|
const { aui } = mountThread({
|
|
664
683
|
transport: mock.transport,
|
|
665
684
|
converter,
|
|
@@ -679,6 +698,35 @@ describe("StatewireThread", () => {
|
|
|
679
698
|
expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
|
|
680
699
|
});
|
|
681
700
|
|
|
701
|
+
it("keeps a set the hello did not negotiate off the wire and re-sends it once the lane is negotiated", async () => {
|
|
702
|
+
const lanes: string[] = [];
|
|
703
|
+
const mock = createMockTransport<ServerState>(INITIAL_STATE, "default", {
|
|
704
|
+
ephemeral: lanes,
|
|
705
|
+
});
|
|
706
|
+
const { aui } = mountThread({
|
|
707
|
+
transport: mock.transport,
|
|
708
|
+
converter,
|
|
709
|
+
contextSync: "command-send",
|
|
710
|
+
});
|
|
711
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
|
|
712
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
713
|
+
expect(mock.commands).toEqual([]);
|
|
714
|
+
|
|
715
|
+
lanes.push("context");
|
|
716
|
+
act(() =>
|
|
717
|
+
asStatewireExtras(aui().thread().getState().extras).reconnect(),
|
|
718
|
+
);
|
|
719
|
+
await waitFor(() => expect(mock.attached).toBe(true));
|
|
720
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
721
|
+
// notifies subscribers without changing the merged context
|
|
722
|
+
aui()
|
|
723
|
+
.modelContext()
|
|
724
|
+
.register({ getModelContext: () => ({}) });
|
|
725
|
+
|
|
726
|
+
await waitFor(() => expect(mock.commands).toHaveLength(1));
|
|
727
|
+
expect(contextValueOf(mock.commands[0]!)).toEqual({});
|
|
728
|
+
});
|
|
729
|
+
|
|
682
730
|
it("stays off the wire without the option", async () => {
|
|
683
731
|
const mock = createMockTransport<ServerState>(INITIAL_STATE);
|
|
684
732
|
const { aui } = mountThread({ transport: mock.transport, converter });
|
|
@@ -883,6 +931,7 @@ describe("StatewireThread", () => {
|
|
|
883
931
|
id: expect.any(String),
|
|
884
932
|
role: "user",
|
|
885
933
|
parts: [{ type: "text", text: "better question" }],
|
|
934
|
+
metadata: {},
|
|
886
935
|
},
|
|
887
936
|
}),
|
|
888
937
|
);
|
|
@@ -922,6 +971,7 @@ describe("StatewireThread", () => {
|
|
|
922
971
|
id: expect.any(String),
|
|
923
972
|
role: "user",
|
|
924
973
|
parts: [{ type: "text", text: "better question" }],
|
|
974
|
+
metadata: {},
|
|
925
975
|
},
|
|
926
976
|
},
|
|
927
977
|
]),
|
|
@@ -1313,6 +1363,45 @@ describe("StatewireThread", () => {
|
|
|
1313
1363
|
return trackingConverter;
|
|
1314
1364
|
};
|
|
1315
1365
|
|
|
1366
|
+
it("hands the converter and extras the documents, mounted map, invoke and connection", async () => {
|
|
1367
|
+
const passes: StatewireThread.ConnectionMetadata[] = [];
|
|
1368
|
+
const mock = createMockTransport<ServerState>(INITIAL_STATE);
|
|
1369
|
+
const { aui } = mountThread({
|
|
1370
|
+
transport: mock.transport,
|
|
1371
|
+
converter: (state, meta) => {
|
|
1372
|
+
passes.push(meta);
|
|
1373
|
+
return { ...converter(state, meta), state: { pass: passes.length } };
|
|
1374
|
+
},
|
|
1375
|
+
});
|
|
1376
|
+
await waitFor(() => expect(threadStatus(aui())).toBe("ready"));
|
|
1377
|
+
await mock.setState({
|
|
1378
|
+
...INITIAL_STATE,
|
|
1379
|
+
messages: [{ id: "m1", role: "user", text: "hi" }],
|
|
1380
|
+
});
|
|
1381
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["hi"]));
|
|
1382
|
+
|
|
1383
|
+
const first = passes[0]!;
|
|
1384
|
+
const last = passes.at(-1)!;
|
|
1385
|
+
expect(passes.length).toBeGreaterThan(1);
|
|
1386
|
+
expect(last.documents).toBe(first.documents);
|
|
1387
|
+
expect(last.invoke).toBe(first.invoke);
|
|
1388
|
+
expect(last.mounted.get(0)?.value).toMatchObject({
|
|
1389
|
+
messages: [{ id: "m1" }],
|
|
1390
|
+
});
|
|
1391
|
+
|
|
1392
|
+
const extras = asStatewireExtras(aui().thread().getState().extras);
|
|
1393
|
+
expect(extras.connection.status).toBe("connected");
|
|
1394
|
+
expect(extras.documents).toBe(first.documents);
|
|
1395
|
+
expect(extras.invoke).toBe(first.invoke);
|
|
1396
|
+
expect(extras.state).toEqual({ pass: passes.length });
|
|
1397
|
+
void extras.invoke("default", "ping", [1]);
|
|
1398
|
+
await waitFor(() =>
|
|
1399
|
+
expect(mock.commands).toEqual([
|
|
1400
|
+
{ protocol: "default", method: "ping", params: [1] },
|
|
1401
|
+
]),
|
|
1402
|
+
);
|
|
1403
|
+
});
|
|
1404
|
+
|
|
1316
1405
|
it("projects connection transitions into the converter", async () => {
|
|
1317
1406
|
const seen: string[] = [];
|
|
1318
1407
|
const mock = createMockTransport<ServerState>(INITIAL_STATE);
|
|
@@ -1351,9 +1440,13 @@ describe("StatewireThread", () => {
|
|
|
1351
1440
|
await mock.finish("gone");
|
|
1352
1441
|
await waitFor(() => expect(seen.at(-1)).toBe("stopped"));
|
|
1353
1442
|
|
|
1354
|
-
|
|
1443
|
+
act(() =>
|
|
1444
|
+
asStatewireExtras(aui().thread().getState().extras).reconnect(),
|
|
1445
|
+
);
|
|
1355
1446
|
|
|
1356
|
-
|
|
1447
|
+
// A fresh episode: first dial at attempt 0, then the dead server fails it.
|
|
1448
|
+
expect(seen.at(-1)).toBe("connecting");
|
|
1449
|
+
await waitFor(() => expect(seen.at(-1)).toBe("retrying"));
|
|
1357
1450
|
});
|
|
1358
1451
|
});
|
|
1359
1452
|
});
|