@assistant-ui/react-statewire 0.0.3 → 0.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -21,6 +21,12 @@ declare namespace StatewireThread {
|
|
|
21
21
|
type Options<T> = {
|
|
22
22
|
transport: Transport<T>;
|
|
23
23
|
converter: StateConverter<T>;
|
|
24
|
+
/**
|
|
25
|
+
* "command-send" mirrors the client's ambient model context (system,
|
|
26
|
+
* tools, callSettings, config) to the server over the command channel —
|
|
27
|
+
* on connect and whenever it changes. Requires a remote transport.
|
|
28
|
+
*/
|
|
29
|
+
contextSync?: "command-send" | undefined;
|
|
24
30
|
onError?: ((error: Error) => void) | undefined;
|
|
25
31
|
capabilities?: {
|
|
26
32
|
edit?: boolean | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"StatewireThread.d.ts","names":[],"sources":["../src/StatewireThread.ts"],"mappings":";;;;;;;cA2Ja,kBAAmB,GAC9B,SAAS,gBAAgB,QAAQ,OAChC,gBAAgB;kBAGF;OACH,UAAU,KAAK,gBAAgB,UAAU;OAEzC;aACD,mBAAmB;aACnB,QAAQ;aACR;;OAGC;IACV,iBAAiB;IACjB;;OAGU,eAAe,MACzB,OAAO,GACP,oBAAoB,uBACjB;OAEO,QAAQ;IAClB,WAAW,UAAU;IACrB,WAAW,eAAe;;;;;;IAM1B;IACA,YAAY,OAAO;IACnB;MAEM;;IAGN;MAEM,cAAc"}
|
package/dist/StatewireThread.js
CHANGED
|
@@ -1,30 +1,62 @@
|
|
|
1
1
|
import { convertAppendMessageToCommand, symbolAssistantTransportExtras } from "./AssistantTransportThread.js";
|
|
2
|
-
import { useCallback, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
3
3
|
import { resource, useResource } from "@assistant-ui/tap";
|
|
4
4
|
import { ExternalThread } from "@assistant-ui/react";
|
|
5
|
-
import { forwardTransformScopes } from "@assistant-ui/store";
|
|
5
|
+
import { forwardTransformScopes, useAssistantClientRef } from "@assistant-ui/store";
|
|
6
6
|
import { useStatewire } from "statewire";
|
|
7
|
+
import { toToolsJSONSchema } from "assistant-stream";
|
|
7
8
|
//#region src/StatewireThread.ts
|
|
8
9
|
const EMPTY_CONVERTED = {
|
|
9
10
|
messages: [],
|
|
10
11
|
isRunning: false
|
|
11
12
|
};
|
|
13
|
+
const ambientContextOf = (context) => ({
|
|
14
|
+
...context.system !== void 0 && { system: context.system },
|
|
15
|
+
...context.tools !== void 0 && { tools: toToolsJSONSchema(context.tools) },
|
|
16
|
+
...context.callSettings !== void 0 && { callSettings: context.callSettings },
|
|
17
|
+
...context.config !== void 0 && { config: context.config }
|
|
18
|
+
});
|
|
12
19
|
const useStatewireThread = (options) => {
|
|
13
20
|
const latest = useRef(options);
|
|
14
21
|
latest.current = options;
|
|
15
22
|
const [pending, setPending] = useState([]);
|
|
16
23
|
const [retire] = useState(() => (command) => setPending((prev) => prev.includes(command) ? prev.filter((c) => c !== command) : prev));
|
|
17
|
-
const { state, commands } = useStatewire({
|
|
24
|
+
const { state, commands, setContext } = useStatewire({
|
|
18
25
|
transport: options.transport,
|
|
19
26
|
onCommandChange: (update) => {
|
|
20
27
|
if (update.status === "acked" || update.status === "settled") retire(update.params[0]);
|
|
21
28
|
}
|
|
22
29
|
});
|
|
30
|
+
const clientRef = useAssistantClientRef();
|
|
31
|
+
const setContextRef = useRef(setContext);
|
|
32
|
+
setContextRef.current = setContext;
|
|
33
|
+
const [syncState] = useState(() => ({ lastSent: void 0 }));
|
|
34
|
+
const { contextSync } = options;
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (contextSync === void 0) return;
|
|
37
|
+
const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
|
|
38
|
+
const send = () => {
|
|
39
|
+
const value = ambientContextOf(modelContext.getModelContext());
|
|
40
|
+
const key = JSON.stringify(value);
|
|
41
|
+
if (key === syncState.lastSent) return;
|
|
42
|
+
syncState.lastSent = key;
|
|
43
|
+
setContextRef.current(value).catch((error) => {
|
|
44
|
+
latest.current.onError?.(error);
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
send();
|
|
48
|
+
if (!modelContext.subscribe) throw new Error("statewire: contextSync requires a subscribable model context");
|
|
49
|
+
return modelContext.subscribe(send);
|
|
50
|
+
}, [
|
|
51
|
+
contextSync,
|
|
52
|
+
clientRef,
|
|
53
|
+
syncState
|
|
54
|
+
]);
|
|
23
55
|
const dispatch = useCallback((command_0) => {
|
|
24
56
|
setPending((prev_0) => [...prev_0, command_0]);
|
|
25
|
-
commands[command_0.type](command_0).catch((
|
|
57
|
+
commands[command_0.type](command_0).catch((error_0) => {
|
|
26
58
|
retire(command_0);
|
|
27
|
-
latest.current.onError?.(
|
|
59
|
+
latest.current.onError?.(error_0);
|
|
28
60
|
});
|
|
29
61
|
}, [commands, retire]);
|
|
30
62
|
const { converter } = options;
|
|
@@ -57,8 +89,8 @@ const useStatewireThread = (options) => {
|
|
|
57
89
|
onNew: handleAppend,
|
|
58
90
|
...options.capabilities?.edit && { onEdit: handleAppend },
|
|
59
91
|
onCancel: () => {
|
|
60
|
-
commands["cancel"]().catch((
|
|
61
|
-
latest.current.onError?.(
|
|
92
|
+
commands["cancel"]().catch((error_1) => {
|
|
93
|
+
latest.current.onError?.(error_1);
|
|
62
94
|
});
|
|
63
95
|
}
|
|
64
96
|
}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatewireThread.js","names":["useCallback","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","ClientOutput","AppendMessage","AttachmentAdapter","ThreadMessage","ReadonlyJSONValue","useStatewire","Statewire","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","EMPTY_CONVERTED","StatewireThread","State","messages","isRunning","useStatewireThread","options","Options","latest","current","pending","setPending","retire","command","prev","includes","filter","c","state","commands","transport","onCommandChange","update","status","params","dispatch","type","catch","error","Error","onError","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","undefined","extras","sendCommand","handleAppend","message","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","onCancel","T","Transport","StateConverter","connectionMetadata","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport { forwardTransformScopes } from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire } from \"statewire\";\nimport {\n convertAppendMessageToCommand,\n symbolAssistantTransportExtras,\n} from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst EMPTY_CONVERTED: StatewireThread.State = {\n messages: [],\n isRunning: false,\n};\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly AssistantTransportCommand[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as AssistantTransportCommand)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const { state, commands } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n }),\n [pending],\n );\n const converted = useMemo(\n () => (state === undefined ? EMPTY_CONVERTED : converter(state, metadata)),\n [converter, state, metadata],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n state,\n }),\n [dispatch, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: state === undefined,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onCancel: () => {\n void commands[\"cancel\"]!().catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: AssistantTransportCommand[];\n isSending: boolean;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n export type Options<T> = {\n transport: Transport<T>;\n converter: StateConverter<T>;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;AAwBA,MAAMwB,kBAAyC;CAC7CG,UAAU,CAAA;CACVC,WAAW;AACb;AAEA,MAAMC,sBACJC,YAC2B;CAC3B,MAAME,SAAS9B,OAAO4B,OAAO;CAC7BE,OAAOC,UAAUH;CAEjB,MAAM,CAACI,SAASC,cAAchC,SAC5B,CAAA,CACF;CACA,MAAM,CAACiC,UAAUjC,gBACRkC,YACLF,YAAYG,SACVA,KAAKC,SAASF,OAAoC,IAC9CC,KAAKE,QAAQC,MAAMA,MAAMJ,OAAO,IAChCC,IACN,CACJ;CAEA,MAAM,EAAEI,OAAOC,aAAa5B,aAAmC;EAC7D6B,WAAWd,QAAQc;EACnBC,kBAAkBC,WAAW;GAC3B,IAAIA,OAAOC,WAAW,WAAWD,OAAOC,WAAW,WACjDX,OAAOU,OAAOE,OAAO,EAAE;EAC3B;CACF,CAAC;CAED,MAAMC,WAAWjD,aACdqC,cAAuC;EACtCF,YAAYG,WAAS,CAAC,GAAGA,QAAMD,SAAO,CAAC;EACvC,SAAcA,UAAQa,KAAK,CAAEb,SAAO,CAAC,CAACc,OAAOC,UAAiB;GAC5DhB,OAAOC,SAAO;GACdL,OAAOC,QAAQqB,UAAUF,KAAK;EAChC,CAAC;CACH,GACA,CAACT,UAAUP,MAAM,CACnB;CAEA,MAAM,EAAEmB,cAAczB;CACtB,MAAM0B,WAAWvD,eAC4B;EACzCyD,iBAAiB,CAAC,GAAGxB,OAAO;EAC5ByB,WAAWzB,QAAQ0B,SAAS;CAC9B,IACA,CAAC1B,OAAO,CACV;CACA,MAAM2B,YAAY5D,cACTyC,UAAUoB,KAAAA,IAAYtC,kBAAkB+B,UAAUb,OAAOc,QAAQ,GACxE;EAACD;EAAWb;EAAOc;CAAQ,CAC7B;CAEA,MAAMO,SAAS9D,eACoB;GAC9BiB,iCAAiC;EAClC8C,aAAaf;EACbP;CACF,IACA,CAACO,UAAUP,KAAK,CAClB;CAEA,MAAMuB,gBAAgBC,YAA2B;EAC/C,MAAM7B,YAAUpB,8BAA8BiD,OAAO;EACrD,IAAI,CAAC7B,WAAS;EACdY,SAASZ,SAAO;CAClB;CAEA,OAAOhC,YACLE,eAAe;EACboB,UAAUkC,UAAUlC;EACpBC,WAAWiC,UAAUjC;EACrBuC,WAAWzB,UAAUoB,KAAAA;EACrBpB,OAAOmB,UAAUnB;EACjBqB;EACAK,mBAAmBtC,QAAQuC,UAAUC;EACrCC,OAAON;EACP,GAAInC,QAAQ0C,cAAcC,QAAQ,EAAEC,QAAQT,aAAa;EACzDU,gBAAgB;GACd,SAAc,SAAS,CAAE,CAAC,CAACxB,OAAOC,YAAiB;IACjDpB,OAAOC,QAAQqB,UAAUF,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAa3B,mBACXK,YAEA1B,SAASyB,kBAAkB,CAAC,CAACC,OAAuC;AAuCtErB,uBACEoB,oBACAtB,eAAeuD,KAAAA,CAAkB,CAAC,CAACkB,IACrC"}
|
|
1
|
+
{"version":3,"file":"StatewireThread.js","names":["useCallback","useEffect","useMemo","useRef","useState","resource","useResource","ResourceElement","ExternalThread","ExternalThreadMessage","forwardTransformScopes","useAssistantClientRef","ClientOutput","AppendMessage","AttachmentAdapter","ModelContext","ThreadMessage","toToolsJSONSchema","ReadonlyJSONValue","useStatewire","Statewire","convertAppendMessageToCommand","symbolAssistantTransportExtras","AssistantTransportExtras","AssistantTransportCommand","AnyCommands","Record","args","EMPTY_CONVERTED","StatewireThread","State","messages","isRunning","ambientContextOf","context","system","undefined","tools","callSettings","config","useStatewireThread","options","Options","latest","current","pending","setPending","retire","command","prev","includes","filter","c","state","commands","setContext","transport","onCommandChange","update","status","params","clientRef","setContextRef","syncState","lastSent","contextSync","modelContext","parent","send","value","getModelContext","key","JSON","stringify","catch","error","Error","onError","subscribe","dispatch","type","converter","metadata","ConnectionMetadata","pendingCommands","isSending","length","converted","extras","sendCommand","handleAppend","message","isLoading","attachmentAdapter","adapters","attachments","onNew","capabilities","edit","onEdit","onCancel","T","Transport","StateConverter","connectionMetadata","hook"],"sources":["../src/StatewireThread.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { resource, useResource } from \"@assistant-ui/tap\";\nimport type { ResourceElement } from \"@assistant-ui/tap\";\nimport { ExternalThread } from \"@assistant-ui/react\";\nimport type { ExternalThreadMessage } from \"@assistant-ui/react\";\nimport {\n forwardTransformScopes,\n useAssistantClientRef,\n} from \"@assistant-ui/store\";\nimport type { ClientOutput } from \"@assistant-ui/store\";\nimport type {\n AppendMessage,\n AttachmentAdapter,\n ModelContext,\n ThreadMessage,\n} from \"@assistant-ui/core\";\nimport { toToolsJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { useStatewire } from \"statewire\";\nimport type { Statewire } from \"statewire\";\nimport {\n convertAppendMessageToCommand,\n symbolAssistantTransportExtras,\n} from \"./AssistantTransportThread\";\nimport type { AssistantTransportExtras } from \"./AssistantTransportThread\";\nimport type { AssistantTransportCommand } from \"./types\";\n\ntype AnyCommands = Record<string, (...args: any[]) => unknown>;\n\nconst EMPTY_CONVERTED: StatewireThread.State = {\n messages: [],\n isRunning: false,\n};\n\nconst ambientContextOf = (context: ModelContext): Record<string, unknown> => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools !== undefined && {\n tools: toToolsJSONSchema(context.tools),\n }),\n ...(context.callSettings !== undefined && {\n callSettings: context.callSettings,\n }),\n ...(context.config !== undefined && { config: context.config }),\n});\n\nconst useStatewireThread = (\n options: StatewireThread.Options<any>,\n): ClientOutput<\"thread\"> => {\n const latest = useRef(options);\n latest.current = options;\n\n const [pending, setPending] = useState<readonly AssistantTransportCommand[]>(\n [],\n );\n const [retire] = useState(\n () => (command: unknown) =>\n setPending((prev) =>\n prev.includes(command as AssistantTransportCommand)\n ? prev.filter((c) => c !== command)\n : prev,\n ),\n );\n\n const { state, commands, setContext } = useStatewire<unknown, AnyCommands>({\n transport: options.transport,\n onCommandChange: (update) => {\n if (update.status === \"acked\" || update.status === \"settled\")\n retire(update.params[0]);\n },\n });\n\n const clientRef = useAssistantClientRef();\n const setContextRef = useRef(setContext);\n setContextRef.current = setContext;\n const [syncState] = useState(() => ({ lastSent: undefined as unknown }));\n const { contextSync } = options;\n useEffect(() => {\n if (contextSync === undefined) return;\n const modelContext = (clientRef.current ?? clientRef.parent).modelContext();\n const send = () => {\n const value = ambientContextOf(modelContext.getModelContext());\n const key = JSON.stringify(value);\n if (key === syncState.lastSent) return;\n syncState.lastSent = key;\n void setContextRef.current(value).catch((error: Error) => {\n latest.current.onError?.(error);\n });\n };\n send();\n if (!modelContext.subscribe) {\n throw new Error(\n \"statewire: contextSync requires a subscribable model context\",\n );\n }\n return modelContext.subscribe(send);\n }, [contextSync, clientRef, syncState]);\n\n const dispatch = useCallback(\n (command: AssistantTransportCommand) => {\n setPending((prev) => [...prev, command]);\n void commands[command.type]!(command).catch((error: Error) => {\n retire(command);\n latest.current.onError?.(error);\n });\n },\n [commands, retire],\n );\n\n const { converter } = options;\n const metadata = useMemo(\n (): StatewireThread.ConnectionMetadata => ({\n pendingCommands: [...pending],\n isSending: pending.length > 0,\n }),\n [pending],\n );\n const converted = useMemo(\n () => (state === undefined ? EMPTY_CONVERTED : converter(state, metadata)),\n [converter, state, metadata],\n );\n\n const extras = useMemo(\n (): AssistantTransportExtras => ({\n [symbolAssistantTransportExtras]: true,\n sendCommand: dispatch,\n state,\n }),\n [dispatch, state],\n );\n\n const handleAppend = (message: AppendMessage) => {\n const command = convertAppendMessageToCommand(message);\n if (!command) return;\n dispatch(command);\n };\n\n return useResource(\n ExternalThread({\n messages: converted.messages as readonly ExternalThreadMessage[],\n isRunning: converted.isRunning,\n isLoading: state === undefined,\n state: converted.state,\n extras,\n attachmentAdapter: options.adapters?.attachments,\n onNew: handleAppend,\n ...(options.capabilities?.edit && { onEdit: handleAppend }),\n onCancel: () => {\n void commands[\"cancel\"]!().catch((error: Error) => {\n latest.current.onError?.(error);\n });\n },\n }),\n );\n};\n\nexport const StatewireThread = <T>(\n options: StatewireThread.Options<T>,\n): ResourceElement<ClientOutput<\"thread\">> =>\n resource(useStatewireThread)(options as StatewireThread.Options<any>);\n\nexport namespace StatewireThread {\n export type Transport<T> = ResourceElement<Statewire<T | undefined, any>>;\n\n export type State = {\n readonly messages: readonly ThreadMessage[];\n readonly state?: ReadonlyJSONValue;\n readonly isRunning: boolean;\n };\n\n export type ConnectionMetadata = {\n pendingCommands: AssistantTransportCommand[];\n isSending: boolean;\n };\n\n export type StateConverter<T> = (\n state: T,\n connectionMetadata: ConnectionMetadata,\n ) => State;\n\n export type Options<T> = {\n transport: Transport<T>;\n converter: StateConverter<T>;\n /**\n * \"command-send\" mirrors the client's ambient model context (system,\n * tools, callSettings, config) to the server over the command channel —\n * on connect and whenever it changes. Requires a remote transport.\n */\n contextSync?: \"command-send\" | undefined;\n onError?: ((error: Error) => void) | undefined;\n capabilities?:\n | {\n edit?: boolean | undefined;\n }\n | undefined;\n adapters?:\n | {\n attachments?: AttachmentAdapter | undefined;\n }\n | undefined;\n };\n}\n\n// Scope transforms are keyed by the underlying hook, not the resource wrapper.\nforwardTransformScopes(\n useStatewireThread,\n ExternalThread(undefined as never).hook,\n);\n"],"mappings":";;;;;;;;AA6BA,MAAM4B,kBAAyC;CAC7CG,UAAU,CAAA;CACVC,WAAW;AACb;AAEA,MAAMC,oBAAoBC,aAAoD;CAC5E,GAAIA,QAAQC,WAAWC,KAAAA,KAAa,EAAED,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQG,UAAUD,KAAAA,KAAa,E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Ac,SAAS,CAAE,CAAC,CAAC1B,OAAOC,YAAiB;IACjDhC,OAAOC,QAAQiC,UAAUF,OAAK;GAChC,CAAC;EACH;CACF,CAAC,CACH;AACF;AAEA,MAAa9C,mBACXY,YAEApC,SAASmC,kBAAkB,CAAC,CAACC,OAAuC;AA6CtE/B,uBACE8B,oBACAhC,eAAe4B,KAAAA,CAAkB,CAAC,CAACqE,IACrC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@assistant-ui/react-statewire",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
4
4
|
"description": "assistant-ui thread binding for statewire backends",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
"@assistant-ui/store": "^0.3.0",
|
|
35
35
|
"@assistant-ui/tap": "^0.9.7",
|
|
36
36
|
"assistant-stream": "^0.3.33",
|
|
37
|
-
"statewire": "
|
|
37
|
+
"statewire": "^0.0.3"
|
|
38
38
|
},
|
|
39
39
|
"peerDependencies": {
|
|
40
40
|
"@assistant-ui/react": ">=0.14.0",
|
|
@@ -16,9 +16,14 @@ import {
|
|
|
16
16
|
useStatewireState,
|
|
17
17
|
} from "statewire/host";
|
|
18
18
|
import type { StatewireHost } from "statewire/host";
|
|
19
|
+
import { createMockTransport } from "statewire/testing";
|
|
19
20
|
import { StatewireThread } from "./StatewireThread";
|
|
20
21
|
import type { AddMessageCommand, AssistantTransportCommand } from "./types";
|
|
21
|
-
import {
|
|
22
|
+
import {
|
|
23
|
+
sendCommand,
|
|
24
|
+
threadTexts,
|
|
25
|
+
toThreadMessage,
|
|
26
|
+
} from "./__tests__/testHelpers";
|
|
22
27
|
|
|
23
28
|
type ServerState = {
|
|
24
29
|
messages: { id: string; role: "user" | "assistant"; text: string }[];
|
|
@@ -38,7 +43,13 @@ const converter: StatewireThread.StateConverter<ServerState> = (
|
|
|
38
43
|
...state.messages.map(toThreadMessage),
|
|
39
44
|
...meta.pendingCommands.flatMap((c, i) =>
|
|
40
45
|
c.type === "add-message" && c.message.role === "user"
|
|
41
|
-
? [
|
|
46
|
+
? [
|
|
47
|
+
toThreadMessage({
|
|
48
|
+
id: `optimistic-${i}`,
|
|
49
|
+
role: "user",
|
|
50
|
+
text: textOf(c),
|
|
51
|
+
}),
|
|
52
|
+
]
|
|
42
53
|
: [],
|
|
43
54
|
),
|
|
44
55
|
] as StatewireThread.State["messages"],
|
|
@@ -161,9 +172,7 @@ describe("StatewireThread", () => {
|
|
|
161
172
|
});
|
|
162
173
|
|
|
163
174
|
await waitFor(() => expect(threadTexts(aui)).toEqual(["hello"]));
|
|
164
|
-
await waitFor(() =>
|
|
165
|
-
expect(aui().thread().getState().isRunning).toBe(true),
|
|
166
|
-
);
|
|
175
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
167
176
|
|
|
168
177
|
server.cell.state!.messages.push({
|
|
169
178
|
id: "a1",
|
|
@@ -210,9 +219,7 @@ describe("StatewireThread", () => {
|
|
|
210
219
|
const { aui } = mountThread({ transport: server.transport, converter });
|
|
211
220
|
|
|
212
221
|
aui().thread().append("hello");
|
|
213
|
-
await waitFor(() =>
|
|
214
|
-
expect(aui().thread().getState().isRunning).toBe(true),
|
|
215
|
-
);
|
|
222
|
+
await waitFor(() => expect(aui().thread().getState().isRunning).toBe(true));
|
|
216
223
|
|
|
217
224
|
aui().thread().cancelRun();
|
|
218
225
|
|
|
@@ -239,14 +246,88 @@ describe("StatewireThread", () => {
|
|
|
239
246
|
},
|
|
240
247
|
});
|
|
241
248
|
|
|
242
|
-
await waitFor(() =>
|
|
243
|
-
|
|
249
|
+
await waitFor(() =>
|
|
250
|
+
expect(aui().thread().getState().isLoading).toBe(false),
|
|
251
|
+
);
|
|
252
|
+
sendCommand(aui, {
|
|
253
|
+
type: "reject-me",
|
|
254
|
+
} as unknown as AssistantTransportCommand);
|
|
244
255
|
|
|
245
256
|
await waitFor(() => expect(errors).toHaveLength(1));
|
|
246
257
|
expect(errors[0]!.message).toContain("nope");
|
|
247
258
|
await waitFor(() => expect(metas.at(-1)!.pendingCommands).toEqual([]));
|
|
248
259
|
});
|
|
249
260
|
|
|
261
|
+
describe("contextSync: command-send", () => {
|
|
262
|
+
const contextValueOf = (command: { context?: unknown }) => {
|
|
263
|
+
const ops = command.context as [
|
|
264
|
+
{ op: string; path: unknown[]; value: unknown },
|
|
265
|
+
];
|
|
266
|
+
expect(ops).toHaveLength(1);
|
|
267
|
+
expect(ops[0]).toMatchObject({ op: "replace", path: [] });
|
|
268
|
+
return ops[0].value as Record<string, unknown>;
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
it("sends the ambient model context on connect and on every change", async () => {
|
|
272
|
+
const mock = createMockTransport<ServerState>({
|
|
273
|
+
messages: [],
|
|
274
|
+
running: false,
|
|
275
|
+
});
|
|
276
|
+
const { aui } = mountThread({
|
|
277
|
+
transport: mock.transport,
|
|
278
|
+
converter,
|
|
279
|
+
contextSync: "command-send",
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
await waitFor(() => expect(mock.commands).toHaveLength(1));
|
|
283
|
+
const initial = contextValueOf(mock.commands[0]!);
|
|
284
|
+
expect(initial["system"]).toBeUndefined();
|
|
285
|
+
|
|
286
|
+
aui()
|
|
287
|
+
.modelContext()
|
|
288
|
+
.register({ getModelContext: () => ({ system: "be nice" }) });
|
|
289
|
+
|
|
290
|
+
await waitFor(() => expect(mock.commands).toHaveLength(2));
|
|
291
|
+
expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
it("skips resends while the serialized context is unchanged", async () => {
|
|
295
|
+
const mock = createMockTransport<ServerState>({
|
|
296
|
+
messages: [],
|
|
297
|
+
running: false,
|
|
298
|
+
});
|
|
299
|
+
const { aui } = mountThread({
|
|
300
|
+
transport: mock.transport,
|
|
301
|
+
converter,
|
|
302
|
+
contextSync: "command-send",
|
|
303
|
+
});
|
|
304
|
+
await waitFor(() => expect(mock.commands).toHaveLength(1));
|
|
305
|
+
|
|
306
|
+
// notifies subscribers without changing the merged context
|
|
307
|
+
aui()
|
|
308
|
+
.modelContext()
|
|
309
|
+
.register({ getModelContext: () => ({}) });
|
|
310
|
+
aui()
|
|
311
|
+
.modelContext()
|
|
312
|
+
.register({ getModelContext: () => ({ system: "be nice" }) });
|
|
313
|
+
|
|
314
|
+
await waitFor(() => expect(mock.commands).toHaveLength(2));
|
|
315
|
+
expect(contextValueOf(mock.commands[1]!)["system"]).toBe("be nice");
|
|
316
|
+
});
|
|
317
|
+
|
|
318
|
+
it("stays off the wire without the option", async () => {
|
|
319
|
+
const mock = createMockTransport<ServerState>({
|
|
320
|
+
messages: [],
|
|
321
|
+
running: false,
|
|
322
|
+
});
|
|
323
|
+
const { aui } = mountThread({ transport: mock.transport, converter });
|
|
324
|
+
await waitFor(() =>
|
|
325
|
+
expect(aui().thread().getState().isLoading).toBe(false),
|
|
326
|
+
);
|
|
327
|
+
expect(mock.commands).toEqual([]);
|
|
328
|
+
});
|
|
329
|
+
});
|
|
330
|
+
|
|
250
331
|
it("enables the edit capability from options", async () => {
|
|
251
332
|
const server = createServer();
|
|
252
333
|
const { aui } = mountThread({
|
package/src/StatewireThread.ts
CHANGED
|
@@ -1,15 +1,20 @@
|
|
|
1
|
-
import { useCallback, 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";
|
|
5
5
|
import type { ExternalThreadMessage } from "@assistant-ui/react";
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
forwardTransformScopes,
|
|
8
|
+
useAssistantClientRef,
|
|
9
|
+
} from "@assistant-ui/store";
|
|
7
10
|
import type { ClientOutput } from "@assistant-ui/store";
|
|
8
11
|
import type {
|
|
9
12
|
AppendMessage,
|
|
10
13
|
AttachmentAdapter,
|
|
14
|
+
ModelContext,
|
|
11
15
|
ThreadMessage,
|
|
12
16
|
} from "@assistant-ui/core";
|
|
17
|
+
import { toToolsJSONSchema } from "assistant-stream";
|
|
13
18
|
import type { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
14
19
|
import { useStatewire } from "statewire";
|
|
15
20
|
import type { Statewire } from "statewire";
|
|
@@ -27,6 +32,17 @@ const EMPTY_CONVERTED: StatewireThread.State = {
|
|
|
27
32
|
isRunning: false,
|
|
28
33
|
};
|
|
29
34
|
|
|
35
|
+
const ambientContextOf = (context: ModelContext): Record<string, unknown> => ({
|
|
36
|
+
...(context.system !== undefined && { system: context.system }),
|
|
37
|
+
...(context.tools !== undefined && {
|
|
38
|
+
tools: toToolsJSONSchema(context.tools),
|
|
39
|
+
}),
|
|
40
|
+
...(context.callSettings !== undefined && {
|
|
41
|
+
callSettings: context.callSettings,
|
|
42
|
+
}),
|
|
43
|
+
...(context.config !== undefined && { config: context.config }),
|
|
44
|
+
});
|
|
45
|
+
|
|
30
46
|
const useStatewireThread = (
|
|
31
47
|
options: StatewireThread.Options<any>,
|
|
32
48
|
): ClientOutput<"thread"> => {
|
|
@@ -45,7 +61,7 @@ const useStatewireThread = (
|
|
|
45
61
|
),
|
|
46
62
|
);
|
|
47
63
|
|
|
48
|
-
const { state, commands } = useStatewire<unknown, AnyCommands>({
|
|
64
|
+
const { state, commands, setContext } = useStatewire<unknown, AnyCommands>({
|
|
49
65
|
transport: options.transport,
|
|
50
66
|
onCommandChange: (update) => {
|
|
51
67
|
if (update.status === "acked" || update.status === "settled")
|
|
@@ -53,6 +69,32 @@ const useStatewireThread = (
|
|
|
53
69
|
},
|
|
54
70
|
});
|
|
55
71
|
|
|
72
|
+
const clientRef = useAssistantClientRef();
|
|
73
|
+
const setContextRef = useRef(setContext);
|
|
74
|
+
setContextRef.current = setContext;
|
|
75
|
+
const [syncState] = useState(() => ({ lastSent: undefined as unknown }));
|
|
76
|
+
const { contextSync } = options;
|
|
77
|
+
useEffect(() => {
|
|
78
|
+
if (contextSync === undefined) return;
|
|
79
|
+
const modelContext = (clientRef.current ?? clientRef.parent).modelContext();
|
|
80
|
+
const send = () => {
|
|
81
|
+
const value = ambientContextOf(modelContext.getModelContext());
|
|
82
|
+
const key = JSON.stringify(value);
|
|
83
|
+
if (key === syncState.lastSent) return;
|
|
84
|
+
syncState.lastSent = key;
|
|
85
|
+
void setContextRef.current(value).catch((error: Error) => {
|
|
86
|
+
latest.current.onError?.(error);
|
|
87
|
+
});
|
|
88
|
+
};
|
|
89
|
+
send();
|
|
90
|
+
if (!modelContext.subscribe) {
|
|
91
|
+
throw new Error(
|
|
92
|
+
"statewire: contextSync requires a subscribable model context",
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
return modelContext.subscribe(send);
|
|
96
|
+
}, [contextSync, clientRef, syncState]);
|
|
97
|
+
|
|
56
98
|
const dispatch = useCallback(
|
|
57
99
|
(command: AssistantTransportCommand) => {
|
|
58
100
|
setPending((prev) => [...prev, command]);
|
|
@@ -138,6 +180,12 @@ export namespace StatewireThread {
|
|
|
138
180
|
export type Options<T> = {
|
|
139
181
|
transport: Transport<T>;
|
|
140
182
|
converter: StateConverter<T>;
|
|
183
|
+
/**
|
|
184
|
+
* "command-send" mirrors the client's ambient model context (system,
|
|
185
|
+
* tools, callSettings, config) to the server over the command channel —
|
|
186
|
+
* on connect and whenever it changes. Requires a remote transport.
|
|
187
|
+
*/
|
|
188
|
+
contextSync?: "command-send" | undefined;
|
|
141
189
|
onError?: ((error: Error) => void) | undefined;
|
|
142
190
|
capabilities?:
|
|
143
191
|
| {
|