@assistant-ui/react-statewire 0.0.1 → 0.0.3
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/AssistantTransportThread.d.ts +4 -2
- package/dist/AssistantTransportThread.d.ts.map +1 -1
- package/dist/AssistantTransportThread.js +11 -10
- package/dist/AssistantTransportThread.js.map +1 -1
- package/dist/StatewireThread.d.ts +35 -0
- package/dist/StatewireThread.d.ts.map +1 -0
- package/dist/StatewireThread.js +71 -0
- package/dist/StatewireThread.js.map +1 -0
- package/dist/host.d.ts +2 -3
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +120 -123
- package/dist/host.js.map +1 -1
- package/dist/index.d.ts +22 -2
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2 -2
- package/dist/replayBoundaryStream.d.ts.map +1 -1
- package/dist/replayBoundaryStream.js +4 -2
- package/dist/replayBoundaryStream.js.map +1 -1
- package/dist/stateOps.d.ts +2 -2
- package/dist/stateOps.d.ts.map +1 -1
- package/dist/stateOps.js +24 -16
- package/dist/stateOps.js.map +1 -1
- package/package.json +15 -16
- package/src/AssistantTransportThread.ts +18 -17
- package/src/StatewireThread.test.tsx +262 -0
- package/src/StatewireThread.ts +159 -0
- package/src/host.ts +112 -98
- package/src/index.ts +23 -19
- package/src/replayBoundaryStream.ts +8 -2
- package/src/stateOps.test.ts +53 -13
- package/src/stateOps.ts +23 -19
- package/src/transport.test.tsx +146 -6
- package/LICENSE +0 -21
package/dist/stateOps.js
CHANGED
|
@@ -4,23 +4,22 @@ const UNSAFE_SEGMENTS = /* @__PURE__ */ new Set([
|
|
|
4
4
|
"constructor",
|
|
5
5
|
"prototype"
|
|
6
6
|
]);
|
|
7
|
-
const assertSafeSegment = (segment) => {
|
|
8
|
-
if (UNSAFE_SEGMENTS.has(segment)) throw new Error(`Unsafe gorp path segment: ${segment}`);
|
|
9
|
-
};
|
|
10
7
|
const assertStringTarget = (current, op) => {
|
|
11
8
|
if (typeof current !== "string") throw new Error(`Expected string at path [${op.path.join(", ")}]`);
|
|
12
9
|
};
|
|
13
10
|
const vivified = (segments, from, op) => {
|
|
14
11
|
if (op.type === "append-text") assertStringTarget(void 0, op);
|
|
15
12
|
let value = op.value;
|
|
16
|
-
for (let i = segments.length - 1; i >= from; i--) {
|
|
17
|
-
assertSafeSegment(segments[i]);
|
|
18
|
-
value = { [segments[i]]: value };
|
|
19
|
-
}
|
|
13
|
+
for (let i = segments.length - 1; i >= from; i--) value = { [segments[i]]: value };
|
|
20
14
|
return value;
|
|
21
15
|
};
|
|
22
16
|
const translateStateOp = (root, op) => {
|
|
23
17
|
const segments = op.path;
|
|
18
|
+
const unsafe = segments.find((segment) => UNSAFE_SEGMENTS.has(segment));
|
|
19
|
+
if (unsafe !== void 0) {
|
|
20
|
+
console.warn(`statewire: stripped op with unsafe path segment "${unsafe}"`);
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
24
23
|
const path = [];
|
|
25
24
|
let node = root;
|
|
26
25
|
for (let i = 0; i < segments.length; i++) {
|
|
@@ -31,7 +30,6 @@ const translateStateOp = (root, op) => {
|
|
|
31
30
|
};
|
|
32
31
|
if (typeof node !== "object") throw new Error(`Invalid path: [${segments.slice(i).join(", ")}]`);
|
|
33
32
|
const key = segments[i];
|
|
34
|
-
assertSafeSegment(key);
|
|
35
33
|
const last = i === segments.length - 1;
|
|
36
34
|
if (Array.isArray(node)) {
|
|
37
35
|
const idx = Number(key);
|
|
@@ -40,10 +38,15 @@ const translateStateOp = (root, op) => {
|
|
|
40
38
|
const insert = idx === node.length;
|
|
41
39
|
if (last) {
|
|
42
40
|
if (op.type === "append-text") {
|
|
43
|
-
|
|
41
|
+
const current = insert ? void 0 : node[idx];
|
|
42
|
+
assertStringTarget(current, op);
|
|
44
43
|
return {
|
|
45
|
-
op: "
|
|
46
|
-
path: [
|
|
44
|
+
op: "add",
|
|
45
|
+
path: [
|
|
46
|
+
...path,
|
|
47
|
+
idx,
|
|
48
|
+
current.length
|
|
49
|
+
],
|
|
47
50
|
value: op.value
|
|
48
51
|
};
|
|
49
52
|
}
|
|
@@ -65,10 +68,15 @@ const translateStateOp = (root, op) => {
|
|
|
65
68
|
const obj = node;
|
|
66
69
|
if (last) {
|
|
67
70
|
if (op.type === "append-text") {
|
|
68
|
-
|
|
71
|
+
const current = Object.hasOwn(obj, key) ? obj[key] : void 0;
|
|
72
|
+
assertStringTarget(current, op);
|
|
69
73
|
return {
|
|
70
|
-
op: "
|
|
71
|
-
path: [
|
|
74
|
+
op: "add",
|
|
75
|
+
path: [
|
|
76
|
+
...path,
|
|
77
|
+
key,
|
|
78
|
+
current.length
|
|
79
|
+
],
|
|
72
80
|
value: op.value
|
|
73
81
|
};
|
|
74
82
|
}
|
|
@@ -89,8 +97,8 @@ const translateStateOp = (root, op) => {
|
|
|
89
97
|
if (op.type === "append-text") {
|
|
90
98
|
assertStringTarget(node, op);
|
|
91
99
|
return {
|
|
92
|
-
op: "
|
|
93
|
-
path: [],
|
|
100
|
+
op: "add",
|
|
101
|
+
path: [node.length],
|
|
94
102
|
value: op.value
|
|
95
103
|
};
|
|
96
104
|
}
|
package/dist/stateOps.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stateOps.js","names":["AssistantTransportStateOperation","Statewire","TranslatedOp","Extract","Op","op","UNSAFE_SEGMENTS","Set","
|
|
1
|
+
{"version":3,"file":"stateOps.js","names":["AssistantTransportStateOperation","Statewire","TranslatedOp","Extract","Op","op","UNSAFE_SEGMENTS","Set","assertStringTarget","current","Error","path","join","vivified","segments","from","type","undefined","value","i","length","translateStateOp","root","unsafe","find","segment","has","console","warn","node","slice","key","last","Array","isArray","idx","Number","isNaN","insert","Object","hasOwn","push","obj","Record"],"sources":["../src/stateOps.ts"],"sourcesContent":["import type { AssistantTransportStateOperation } from \"assistant-stream\";\nimport type { Statewire } from \"statewire\";\n\nexport type TranslatedOp = Extract<Statewire.Op, { op: \"replace\" | \"add\" }>;\n\nconst UNSAFE_SEGMENTS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nconst assertStringTarget = (\n current: unknown,\n op: AssistantTransportStateOperation,\n) => {\n if (typeof current !== \"string\") {\n throw new Error(`Expected string at path [${op.path.join(\", \")}]`);\n }\n};\n\n// Missing intermediates auto-vivify as nested objects, exactly like gorp's updatePath.\nconst vivified = (\n segments: readonly string[],\n from: number,\n op: AssistantTransportStateOperation,\n): unknown => {\n if (op.type === \"append-text\") assertStringTarget(undefined, op);\n let value: unknown = op.value;\n for (let i = segments.length - 1; i >= from; i--) {\n value = { [segments[i]!]: value };\n }\n return value;\n};\n\n// Expresses a gorp `update-state` op as a statewire op against the current\n// state, replicating GorpStreamAccumulator's path semantics — including its\n// errors. Ops with unsafe path segments are stripped with a warning.\nexport const translateStateOp = (\n root: unknown,\n op: AssistantTransportStateOperation,\n): TranslatedOp | undefined => {\n const segments = op.path;\n const unsafe = segments.find((segment) => UNSAFE_SEGMENTS.has(segment));\n if (unsafe !== undefined) {\n console.warn(`statewire: stripped op with unsafe path segment \"${unsafe}\"`);\n return undefined;\n }\n const path: (string | number)[] = [];\n let node: unknown = root;\n\n for (let i = 0; i < segments.length; i++) {\n if (node === null || node === undefined) {\n return { op: \"replace\", path, value: vivified(segments, i, op) };\n }\n if (typeof node !== \"object\") {\n throw new Error(`Invalid path: [${segments.slice(i).join(\", \")}]`);\n }\n const key = segments[i]!;\n const last = i === segments.length - 1;\n\n if (Array.isArray(node)) {\n // gorp parity: Number(\"\"), and thus an empty-string key, is index 0\n const idx = Number(key);\n if (Number.isNaN(idx)) {\n throw new Error(\n `Expected array index at [${segments.slice(i).join(\", \")}]`,\n );\n }\n if (idx > node.length || idx < 0) {\n throw new Error(`Insert array index out of bounds`);\n }\n const insert = idx === node.length;\n if (last) {\n if (op.type === \"append-text\") {\n const current = insert ? undefined : node[idx];\n assertStringTarget(current, op);\n return {\n op: \"add\",\n path: [...path, idx, (current as string).length],\n value: op.value,\n };\n }\n return {\n op: insert ? \"add\" : \"replace\",\n path: [...path, idx],\n value: op.value,\n };\n }\n if (insert || !Object.hasOwn(node, idx)) {\n return {\n op: insert ? \"add\" : \"replace\",\n path: [...path, idx],\n value: vivified(segments, i + 1, op),\n };\n }\n path.push(idx);\n node = node[idx];\n continue;\n }\n\n const obj = node as Record<string, unknown>;\n if (last) {\n if (op.type === \"append-text\") {\n const current = Object.hasOwn(obj, key) ? obj[key] : undefined;\n assertStringTarget(current, op);\n return {\n op: \"add\",\n path: [...path, key, (current as string).length],\n value: op.value,\n };\n }\n return { op: \"replace\", path: [...path, key], value: op.value };\n }\n if (!Object.hasOwn(obj, key)) {\n return {\n op: \"replace\",\n path: [...path, key],\n value: vivified(segments, i + 1, op),\n };\n }\n path.push(key);\n node = obj[key];\n }\n\n if (op.type === \"append-text\") {\n assertStringTarget(node, op);\n return { op: \"add\", path: [(node as string).length], value: op.value };\n }\n return { op: \"replace\", path: [], value: op.value };\n};\n"],"mappings":"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"}
|
package/package.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.3",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
8
|
"url": "git+https://github.com/assistant-ui/harness-sdk.git",
|
|
9
|
-
"directory": "packages/react
|
|
9
|
+
"directory": "packages/statewire/react"
|
|
10
10
|
},
|
|
11
11
|
"publishConfig": {
|
|
12
12
|
"access": "public"
|
|
@@ -22,22 +22,26 @@
|
|
|
22
22
|
"types": "./dist/index.d.ts",
|
|
23
23
|
"files": [
|
|
24
24
|
"dist",
|
|
25
|
-
"src"
|
|
26
|
-
"README.md"
|
|
25
|
+
"src"
|
|
27
26
|
],
|
|
27
|
+
"scripts": {
|
|
28
|
+
"build": "aui-build",
|
|
29
|
+
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p typetests/tsconfig.json --noEmit",
|
|
30
|
+
"test": "vitest run"
|
|
31
|
+
},
|
|
28
32
|
"dependencies": {
|
|
29
|
-
"@assistant-ui/core": "^0.
|
|
30
|
-
"@assistant-ui/store": "^0.
|
|
31
|
-
"@assistant-ui/tap": "^0.9.
|
|
32
|
-
"assistant-stream": "^0.3.
|
|
33
|
-
"statewire": "
|
|
33
|
+
"@assistant-ui/core": "^0.3.0",
|
|
34
|
+
"@assistant-ui/store": "^0.3.0",
|
|
35
|
+
"@assistant-ui/tap": "^0.9.7",
|
|
36
|
+
"assistant-stream": "^0.3.33",
|
|
37
|
+
"statewire": "workspace:*"
|
|
34
38
|
},
|
|
35
39
|
"peerDependencies": {
|
|
36
40
|
"@assistant-ui/react": ">=0.14.0",
|
|
37
41
|
"react": "^18 || ^19"
|
|
38
42
|
},
|
|
39
43
|
"devDependencies": {
|
|
40
|
-
"@assistant-ui/react": "^0.
|
|
44
|
+
"@assistant-ui/react": "^0.15.0",
|
|
41
45
|
"@assistant-ui/x-buildutils": "^0.0.20",
|
|
42
46
|
"@testing-library/react": "^16.3.2",
|
|
43
47
|
"@types/react": "^19.2.17",
|
|
@@ -45,10 +49,5 @@
|
|
|
45
49
|
"react": "^19.2.8",
|
|
46
50
|
"react-dom": "^19.2.8",
|
|
47
51
|
"vitest": "^4.1.10"
|
|
48
|
-
},
|
|
49
|
-
"scripts": {
|
|
50
|
-
"build": "aui-build",
|
|
51
|
-
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p typetests/tsconfig.json --noEmit",
|
|
52
|
-
"test": "vitest run"
|
|
53
52
|
}
|
|
54
|
-
}
|
|
53
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useEffect, useMemo, useRef, useState } from "react";
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
2
2
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
3
3
|
import type { ResourceElement } from "@assistant-ui/tap";
|
|
4
4
|
import { ExternalThread } from "@assistant-ui/react";
|
|
@@ -55,13 +55,13 @@ export const asAssistantTransportExtras = (
|
|
|
55
55
|
!(symbolAssistantTransportExtras in extras)
|
|
56
56
|
)
|
|
57
57
|
throw new Error(
|
|
58
|
-
"This method can only be called when you are using AssistantTransportThread",
|
|
58
|
+
"This method can only be called when you are using AssistantTransportThread or StatewireThread",
|
|
59
59
|
);
|
|
60
60
|
|
|
61
61
|
return extras as AssistantTransportExtras;
|
|
62
62
|
};
|
|
63
63
|
|
|
64
|
-
const convertAppendMessageToCommand = (
|
|
64
|
+
export const convertAppendMessageToCommand = (
|
|
65
65
|
message: AppendMessage,
|
|
66
66
|
): AddMessageCommand | null => {
|
|
67
67
|
if (message.role !== "user")
|
|
@@ -136,22 +136,25 @@ const useAssistantTransportThread = (
|
|
|
136
136
|
const { agent: agentState, isSending, isReplaying } = state;
|
|
137
137
|
const queue = queueCell.current;
|
|
138
138
|
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
139
|
+
const dispatch = useCallback(
|
|
140
|
+
(command: AssistantTransportCommand, opts?: SendOptions) => {
|
|
141
|
+
void commands.send(command, opts).catch(() => {});
|
|
142
|
+
},
|
|
143
|
+
[commands],
|
|
144
|
+
);
|
|
143
145
|
|
|
144
146
|
const [toolStatuses, setToolStatuses] =
|
|
145
147
|
useState<Record<string, ToolExecutionStatus>>(EMPTY_TOOL_STATUSES);
|
|
146
148
|
|
|
149
|
+
const { converter } = options;
|
|
147
150
|
const converted = useMemo(
|
|
148
151
|
() =>
|
|
149
|
-
|
|
152
|
+
converter(agentState, {
|
|
150
153
|
pendingCommands: [...queue.inTransit, ...queue.queued],
|
|
151
154
|
isSending,
|
|
152
155
|
toolStatuses,
|
|
153
156
|
}),
|
|
154
|
-
[
|
|
157
|
+
[converter, agentState, queue, isSending, toolStatuses],
|
|
155
158
|
);
|
|
156
159
|
const convertedRef = useRef(converted);
|
|
157
160
|
convertedRef.current = converted;
|
|
@@ -201,7 +204,7 @@ const useAssistantTransportThread = (
|
|
|
201
204
|
sendCommand: dispatch,
|
|
202
205
|
state: agentState,
|
|
203
206
|
}),
|
|
204
|
-
[
|
|
207
|
+
[dispatch, agentState],
|
|
205
208
|
);
|
|
206
209
|
|
|
207
210
|
const handleAppend = (message: AppendMessage) => {
|
|
@@ -231,13 +234,11 @@ const useAssistantTransportThread = (
|
|
|
231
234
|
attachmentAdapter: options.adapters?.attachments,
|
|
232
235
|
onNew: handleAppend,
|
|
233
236
|
...(options.capabilities?.edit && { onEdit: handleAppend }),
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
void
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
},
|
|
240
|
-
}),
|
|
237
|
+
onReload: (parentId: string | null) => {
|
|
238
|
+
void toolInvocations.abort().then(() => {
|
|
239
|
+
void commands.reload(parentId).catch(() => {});
|
|
240
|
+
});
|
|
241
|
+
},
|
|
241
242
|
onCancel: () => {
|
|
242
243
|
void toolInvocations.abort();
|
|
243
244
|
void commands.cancel().catch(() => {});
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
// @vitest-environment jsdom
|
|
2
|
+
|
|
3
|
+
// Contract tests for StatewireThread at its public seam: an in-process
|
|
4
|
+
// statewire host stands in for the server.
|
|
5
|
+
|
|
6
|
+
import { render, waitFor } from "@testing-library/react";
|
|
7
|
+
import type { FC } from "react";
|
|
8
|
+
import { useState } from "react";
|
|
9
|
+
import { describe, expect, it } from "vitest";
|
|
10
|
+
import { AuiProvider, useAui } from "@assistant-ui/store";
|
|
11
|
+
import { resource } from "@assistant-ui/tap";
|
|
12
|
+
import {
|
|
13
|
+
CommandExecution,
|
|
14
|
+
StatewireReject,
|
|
15
|
+
useStatewireCommands,
|
|
16
|
+
useStatewireState,
|
|
17
|
+
} from "statewire/host";
|
|
18
|
+
import type { StatewireHost } from "statewire/host";
|
|
19
|
+
import { StatewireThread } from "./StatewireThread";
|
|
20
|
+
import type { AddMessageCommand, AssistantTransportCommand } from "./types";
|
|
21
|
+
import { sendCommand, threadTexts, toThreadMessage } from "./__tests__/testHelpers";
|
|
22
|
+
|
|
23
|
+
type ServerState = {
|
|
24
|
+
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
25
|
+
running: boolean;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const textOf = (command: AddMessageCommand) =>
|
|
29
|
+
command.message.parts
|
|
30
|
+
.flatMap((p) => (p.type === "text" ? [p.text] : []))
|
|
31
|
+
.join("");
|
|
32
|
+
|
|
33
|
+
const converter: StatewireThread.StateConverter<ServerState> = (
|
|
34
|
+
state,
|
|
35
|
+
meta,
|
|
36
|
+
) => ({
|
|
37
|
+
messages: [
|
|
38
|
+
...state.messages.map(toThreadMessage),
|
|
39
|
+
...meta.pendingCommands.flatMap((c, i) =>
|
|
40
|
+
c.type === "add-message" && c.message.role === "user"
|
|
41
|
+
? [toThreadMessage({ id: `optimistic-${i}`, role: "user", text: textOf(c) })]
|
|
42
|
+
: [],
|
|
43
|
+
),
|
|
44
|
+
] as StatewireThread.State["messages"],
|
|
45
|
+
isRunning: state.running,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const createServer = (init?: { messages?: ServerState["messages"] }) => {
|
|
49
|
+
const received: unknown[] = [];
|
|
50
|
+
const cell: {
|
|
51
|
+
state?: ServerState;
|
|
52
|
+
hold?: boolean;
|
|
53
|
+
resolvers?: StatewireHost.ExecutionResolvers;
|
|
54
|
+
} = {};
|
|
55
|
+
const transport = resource(() => {
|
|
56
|
+
const [state] = useStatewireState<ServerState>(() => ({
|
|
57
|
+
messages: init?.messages ?? [],
|
|
58
|
+
running: false,
|
|
59
|
+
}));
|
|
60
|
+
cell.state = state;
|
|
61
|
+
const commands = useStatewireCommands({
|
|
62
|
+
"add-message": (command: AddMessageCommand) => {
|
|
63
|
+
received.push(command);
|
|
64
|
+
if (cell.hold) {
|
|
65
|
+
const [execution, resolvers] = CommandExecution.withResolvers();
|
|
66
|
+
cell.resolvers = resolvers;
|
|
67
|
+
return execution;
|
|
68
|
+
}
|
|
69
|
+
state.messages.push({
|
|
70
|
+
id: `u${state.messages.length}`,
|
|
71
|
+
role: "user",
|
|
72
|
+
text: textOf(command),
|
|
73
|
+
});
|
|
74
|
+
state.running = true;
|
|
75
|
+
return undefined;
|
|
76
|
+
},
|
|
77
|
+
cancel: () => {
|
|
78
|
+
received.push({ type: "cancel" });
|
|
79
|
+
state.running = false;
|
|
80
|
+
},
|
|
81
|
+
"reject-me": () => {
|
|
82
|
+
throw new StatewireReject("nope");
|
|
83
|
+
},
|
|
84
|
+
});
|
|
85
|
+
return { state, commands };
|
|
86
|
+
})();
|
|
87
|
+
return { transport, received, cell };
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const mountThread = (options: StatewireThread.Options<ServerState>) => {
|
|
91
|
+
const captured: { aui?: ReturnType<typeof useAui> } = {};
|
|
92
|
+
const Capture: FC = () => {
|
|
93
|
+
captured.aui = useAui();
|
|
94
|
+
return null;
|
|
95
|
+
};
|
|
96
|
+
const App: FC = () => {
|
|
97
|
+
const aui = useAui({ thread: StatewireThread(options) });
|
|
98
|
+
return (
|
|
99
|
+
<AuiProvider value={aui}>
|
|
100
|
+
<Capture />
|
|
101
|
+
</AuiProvider>
|
|
102
|
+
);
|
|
103
|
+
};
|
|
104
|
+
render(<App />);
|
|
105
|
+
return { aui: () => captured.aui! };
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
describe("StatewireThread", () => {
|
|
109
|
+
it("populates messages from the attach snapshot", async () => {
|
|
110
|
+
const server = createServer({
|
|
111
|
+
messages: [
|
|
112
|
+
{ id: "m1", role: "user", text: "hi" },
|
|
113
|
+
{ id: "m2", role: "assistant", text: "hello there" },
|
|
114
|
+
],
|
|
115
|
+
});
|
|
116
|
+
const { aui } = mountThread({ transport: server.transport, converter });
|
|
117
|
+
|
|
118
|
+
await waitFor(() =>
|
|
119
|
+
expect(threadTexts(aui)).toEqual(["hi", "hello there"]),
|
|
120
|
+
);
|
|
121
|
+
expect(aui().thread().getState().isLoading).toBe(false);
|
|
122
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it("stays loading until the transport delivers a state", async () => {
|
|
126
|
+
const cell: { attach?: () => void } = {};
|
|
127
|
+
const transport = resource(() => {
|
|
128
|
+
const [attached, setAttached] = useState(false);
|
|
129
|
+
cell.attach = () => setAttached(true);
|
|
130
|
+
const [state] = useStatewireState<ServerState>(() => ({
|
|
131
|
+
messages: [{ id: "m1", role: "assistant", text: "welcome" }],
|
|
132
|
+
running: false,
|
|
133
|
+
}));
|
|
134
|
+
const commands = useStatewireCommands({});
|
|
135
|
+
return { state: attached ? state : undefined, commands };
|
|
136
|
+
})();
|
|
137
|
+
|
|
138
|
+
const { aui } = mountThread({ transport, converter });
|
|
139
|
+
|
|
140
|
+
await waitFor(() => expect(aui().thread().getState().isLoading).toBe(true));
|
|
141
|
+
expect(threadTexts(aui)).toEqual([]);
|
|
142
|
+
|
|
143
|
+
cell.attach!();
|
|
144
|
+
|
|
145
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["welcome"]));
|
|
146
|
+
expect(aui().thread().getState().isLoading).toBe(false);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it("round-trips an appended message through the add-message command", async () => {
|
|
150
|
+
const server = createServer();
|
|
151
|
+
const { aui } = mountThread({ transport: server.transport, converter });
|
|
152
|
+
|
|
153
|
+
aui().thread().append("hello");
|
|
154
|
+
|
|
155
|
+
await waitFor(() => expect(server.received).toHaveLength(1));
|
|
156
|
+
expect(server.received[0]).toMatchObject({
|
|
157
|
+
type: "add-message",
|
|
158
|
+
message: { role: "user", parts: [{ type: "text", text: "hello" }] },
|
|
159
|
+
parentId: null,
|
|
160
|
+
sourceId: null,
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
|
|
164
|
+
await waitFor(() =>
|
|
165
|
+
expect(aui().thread().getState().isRunning).toBe(true),
|
|
166
|
+
);
|
|
167
|
+
|
|
168
|
+
server.cell.state!.messages.push({
|
|
169
|
+
id: "a1",
|
|
170
|
+
role: "assistant",
|
|
171
|
+
text: "hi there",
|
|
172
|
+
});
|
|
173
|
+
server.cell.state!.running = false;
|
|
174
|
+
|
|
175
|
+
await waitFor(() =>
|
|
176
|
+
expect(threadTexts(aui)).toEqual(["hello", "hi there"]),
|
|
177
|
+
);
|
|
178
|
+
expect(aui().thread().getState().isRunning).toBe(false);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
it("passes pendingCommands and isSending to the converter while a command is open", async () => {
|
|
182
|
+
const server = createServer();
|
|
183
|
+
server.cell.hold = true;
|
|
184
|
+
|
|
185
|
+
const metas: StatewireThread.ConnectionMetadata[] = [];
|
|
186
|
+
const { aui } = mountThread({
|
|
187
|
+
transport: server.transport,
|
|
188
|
+
converter: (state, meta) => {
|
|
189
|
+
metas.push(meta);
|
|
190
|
+
return converter(state, meta);
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
aui().thread().append("hello");
|
|
195
|
+
|
|
196
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
|
|
197
|
+
const meta = metas.at(-1)!;
|
|
198
|
+
expect(meta.isSending).toBe(true);
|
|
199
|
+
expect(meta.pendingCommands).toMatchObject([{ type: "add-message" }]);
|
|
200
|
+
|
|
201
|
+
server.cell.resolvers!.resolve();
|
|
202
|
+
|
|
203
|
+
await waitFor(() => expect(threadTexts(aui)).toEqual([]));
|
|
204
|
+
expect(metas.at(-1)!.isSending).toBe(false);
|
|
205
|
+
expect(metas.at(-1)!.pendingCommands).toEqual([]);
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it("dispatches the cancel command from cancelRun", async () => {
|
|
209
|
+
const server = createServer();
|
|
210
|
+
const { aui } = mountThread({ transport: server.transport, converter });
|
|
211
|
+
|
|
212
|
+
aui().thread().append("hello");
|
|
213
|
+
await waitFor(() =>
|
|
214
|
+
expect(aui().thread().getState().isRunning).toBe(true),
|
|
215
|
+
);
|
|
216
|
+
|
|
217
|
+
aui().thread().cancelRun();
|
|
218
|
+
|
|
219
|
+
await waitFor(() =>
|
|
220
|
+
expect(server.received).toContainEqual({ type: "cancel" }),
|
|
221
|
+
);
|
|
222
|
+
await waitFor(() =>
|
|
223
|
+
expect(aui().thread().getState().isRunning).toBe(false),
|
|
224
|
+
);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
it("surfaces command failures through onError and retires the pending command", async () => {
|
|
228
|
+
const server = createServer();
|
|
229
|
+
const errors: Error[] = [];
|
|
230
|
+
const metas: StatewireThread.ConnectionMetadata[] = [];
|
|
231
|
+
const { aui } = mountThread({
|
|
232
|
+
transport: server.transport,
|
|
233
|
+
converter: (state, meta) => {
|
|
234
|
+
metas.push(meta);
|
|
235
|
+
return converter(state, meta);
|
|
236
|
+
},
|
|
237
|
+
onError: (error) => {
|
|
238
|
+
errors.push(error);
|
|
239
|
+
},
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
await waitFor(() => expect(aui().thread().getState().isLoading).toBe(false));
|
|
243
|
+
sendCommand(aui, { type: "reject-me" } as unknown as AssistantTransportCommand);
|
|
244
|
+
|
|
245
|
+
await waitFor(() => expect(errors).toHaveLength(1));
|
|
246
|
+
expect(errors[0]!.message).toContain("nope");
|
|
247
|
+
await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
it("enables the edit capability from options", async () => {
|
|
251
|
+
const server = createServer();
|
|
252
|
+
const { aui } = mountThread({
|
|
253
|
+
transport: server.transport,
|
|
254
|
+
converter,
|
|
255
|
+
capabilities: { edit: true },
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
await waitFor(() =>
|
|
259
|
+
expect(aui().thread().getState().capabilities.edit).toBe(true),
|
|
260
|
+
);
|
|
261
|
+
});
|
|
262
|
+
});
|