@assistant-ui/react 0.10.8 → 0.10.10
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/api/ComposerRuntime.d.ts +46 -0
- package/dist/api/ComposerRuntime.d.ts.map +1 -1
- package/dist/api/ComposerRuntime.js.map +1 -1
- package/dist/api/ThreadListItemRuntime.d.ts +5 -0
- package/dist/api/ThreadListItemRuntime.d.ts.map +1 -1
- package/dist/api/ThreadListItemRuntime.js +5 -0
- package/dist/api/ThreadListItemRuntime.js.map +1 -1
- package/dist/cloud/auiV0.d.ts +1 -0
- package/dist/cloud/auiV0.d.ts.map +1 -1
- package/dist/cloud/auiV0.js.map +1 -1
- package/dist/primitives/composer/ComposerInput.d.ts +2 -0
- package/dist/primitives/composer/ComposerInput.d.ts.map +1 -1
- package/dist/primitives/composer/ComposerInput.js +19 -1
- package/dist/primitives/composer/ComposerInput.js.map +1 -1
- package/dist/primitives/error/ErrorMessage.d.ts +10 -0
- package/dist/primitives/error/ErrorMessage.d.ts.map +1 -0
- package/dist/primitives/error/ErrorMessage.js +19 -0
- package/dist/primitives/error/ErrorMessage.js.map +1 -0
- package/dist/primitives/error/ErrorRoot.d.ts +10 -0
- package/dist/primitives/error/ErrorRoot.d.ts.map +1 -0
- package/dist/primitives/error/ErrorRoot.js +14 -0
- package/dist/primitives/error/ErrorRoot.js.map +1 -0
- package/dist/primitives/error/index.d.ts +3 -0
- package/dist/primitives/error/index.d.ts.map +1 -0
- package/dist/primitives/error/index.js +8 -0
- package/dist/primitives/error/index.js.map +1 -0
- package/dist/primitives/index.d.ts +1 -0
- package/dist/primitives/index.d.ts.map +1 -1
- package/dist/primitives/index.js +2 -0
- package/dist/primitives/index.js.map +1 -1
- package/dist/primitives/message/MessageContent.d.ts.map +1 -1
- package/dist/primitives/message/MessageContent.js +10 -3
- package/dist/primitives/message/MessageContent.js.map +1 -1
- package/dist/primitives/message/MessageError.d.ts +3 -0
- package/dist/primitives/message/MessageError.d.ts.map +1 -0
- package/dist/primitives/message/MessageError.js +16 -0
- package/dist/primitives/message/MessageError.js.map +1 -0
- package/dist/primitives/message/index.d.ts +1 -0
- package/dist/primitives/message/index.d.ts.map +1 -1
- package/dist/primitives/message/index.js +2 -0
- package/dist/primitives/message/index.js.map +1 -1
- package/dist/runtimes/core/ThreadListRuntimeCore.d.ts +1 -0
- package/dist/runtimes/core/ThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/external-store/ExternalStoreThreadListRuntimeCore.d.ts +1 -0
- package/dist/runtimes/external-store/ExternalStoreThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/external-store/ExternalStoreThreadListRuntimeCore.js +2 -0
- package/dist/runtimes/external-store/ExternalStoreThreadListRuntimeCore.js.map +1 -1
- package/dist/runtimes/external-store/external-message-converter.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-message-converter.js +3 -0
- package/dist/runtimes/external-store/external-message-converter.js.map +1 -1
- package/dist/runtimes/local/ChatModelAdapter.d.ts +1 -0
- package/dist/runtimes/local/ChatModelAdapter.d.ts.map +1 -1
- package/dist/runtimes/local/LocalThreadListRuntimeCore.d.ts +1 -0
- package/dist/runtimes/local/LocalThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/local/LocalThreadListRuntimeCore.js +3 -0
- package/dist/runtimes/local/LocalThreadListRuntimeCore.js.map +1 -1
- package/dist/runtimes/local/LocalThreadRuntimeCore.d.ts +1 -0
- package/dist/runtimes/local/LocalThreadRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/local/LocalThreadRuntimeCore.js +6 -1
- package/dist/runtimes/local/LocalThreadRuntimeCore.js.map +1 -1
- package/dist/runtimes/local/useLocalRuntime.d.ts.map +1 -1
- package/dist/runtimes/local/useLocalRuntime.js +5 -0
- package/dist/runtimes/local/useLocalRuntime.js.map +1 -1
- package/dist/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.d.ts +1 -0
- package/dist/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.js +10 -0
- package/dist/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/package.json +1 -1
- package/src/api/ComposerRuntime.ts +54 -0
- package/src/api/ThreadListItemRuntime.ts +12 -0
- package/src/cloud/auiV0.ts +2 -4
- package/src/primitives/composer/ComposerInput.tsx +22 -0
- package/src/primitives/error/ErrorMessage.tsx +31 -0
- package/src/primitives/error/ErrorRoot.tsx +18 -0
- package/src/primitives/error/index.ts +2 -0
- package/src/primitives/index.ts +1 -0
- package/src/primitives/message/MessageContent.tsx +16 -4
- package/src/primitives/message/MessageError.tsx +13 -0
- package/src/primitives/message/index.ts +1 -0
- package/src/runtimes/core/ThreadListRuntimeCore.tsx +1 -0
- package/src/runtimes/external-store/ExternalStoreThreadListRuntimeCore.tsx +4 -0
- package/src/runtimes/external-store/external-message-converter.tsx +4 -0
- package/src/runtimes/local/ChatModelAdapter.tsx +1 -0
- package/src/runtimes/local/LocalThreadListRuntimeCore.tsx +4 -0
- package/src/runtimes/local/LocalThreadRuntimeCore.tsx +9 -1
- package/src/runtimes/local/useLocalRuntime.tsx +6 -0
- package/src/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.tsx +2 -0
- package/src/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx +15 -1
- package/src/tests/MessageRepository.test.ts +1 -0
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n FC,\n useCallback,\n useRef,\n useEffect,\n memo,\n useMemo,\n PropsWithChildren,\n ComponentType,\n} from \"react\";\nimport { UseBoundStore, StoreApi, create } from \"zustand\";\nimport { useAssistantRuntime } from \"../../context\";\nimport { ThreadListItemRuntimeProvider } from \"../../context/providers/ThreadListItemRuntimeProvider\";\nimport {\n useThreadListItem,\n useThreadListItemRuntime,\n} from \"../../context/react/ThreadListItemContext\";\nimport { ThreadRuntimeCore, ThreadRuntimeImpl } from \"../../internal\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { AssistantRuntime } from \"../../api\";\n\ntype RemoteThreadListHook = () => AssistantRuntime;\n\ntype RemoteThreadListHookInstance = {\n runtime?: ThreadRuntimeCore;\n};\nexport class RemoteThreadListHookInstanceManager extends BaseSubscribable {\n private useRuntimeHook: UseBoundStore<\n StoreApi<{ useRuntime: RemoteThreadListHook }>\n >;\n private instances = new Map<string, RemoteThreadListHookInstance>();\n private useAliveThreadsKeysChanged = create(() => ({}));\n\n constructor(runtimeHook: RemoteThreadListHook) {\n super();\n this.useRuntimeHook = create(() => ({ useRuntime: runtimeHook }));\n }\n\n public startThreadRuntime(threadId: string) {\n if (!this.instances.has(threadId)) {\n this.instances.set(threadId, {});\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n return new Promise<ThreadRuntimeCore>((resolve, reject) => {\n const callback = () => {\n const instance = this.instances.get(threadId);\n if (!instance) {\n dispose();\n reject(new Error(\"Thread was deleted before runtime was started\"));\n } else if (!instance.runtime) {\n return; // misc update\n } else {\n dispose();\n resolve(instance.runtime);\n }\n };\n const dispose = this.subscribe(callback);\n callback();\n });\n }\n\n public getThreadRuntimeCore(threadId: string) {\n const instance = this.instances.get(threadId);\n if (!instance)\n throw new Error(\n \"getThreadRuntimeCore not found. This is a bug in assistant-ui.\",\n );\n return instance.runtime;\n }\n\n public stopThreadRuntime(threadId: string) {\n this.instances.delete(threadId);\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n public setRuntimeHook(newRuntimeHook: RemoteThreadListHook) {\n const prevRuntimeHook = this.useRuntimeHook.getState().useRuntime;\n if (prevRuntimeHook !== newRuntimeHook) {\n this.useRuntimeHook.setState({ useRuntime: newRuntimeHook }, true);\n }\n }\n\n private _InnerActiveThreadProvider: FC = () => {\n const { id } = useThreadListItem();\n\n const { useRuntime } = this.useRuntimeHook();\n const runtime = useRuntime();\n\n const threadBinding = (runtime.thread as ThreadRuntimeImpl)\n .__internal_threadBinding;\n\n const updateRuntime = useCallback(() => {\n const aliveThread = this.instances.get(id);\n if (!aliveThread)\n throw new Error(\"Thread not found. This is a bug in assistant-ui.\");\n\n aliveThread.runtime = threadBinding.getState();\n\n if (isMounted) {\n this._notifySubscribers();\n }\n }, [id, threadBinding]);\n\n const isMounted = useRef(false);\n if (!isMounted.current) {\n updateRuntime();\n }\n\n useEffect(() => {\n isMounted.current = true;\n updateRuntime();\n return threadBinding.outerSubscribe(updateRuntime);\n }, [threadBinding, updateRuntime]);\n\n // auto initialize thread\n const threadListItemRuntime = useThreadListItemRuntime();\n useEffect(() => {\n return runtime.threads.main.unstable_on(\"initialize\", () => {\n if (threadListItemRuntime.getState().status === \"new\") {\n threadListItemRuntime.initialize();\n\n // auto generate a title after first run\n const dispose = runtime.thread.unstable_on(\"run-end\", () => {\n dispose();\n\n threadListItemRuntime.generateTitle();\n });\n }\n });\n }, [runtime, threadListItemRuntime]);\n\n return null;\n };\n\n private _OuterActiveThreadProvider: FC<{\n threadId: string;\n provider: ComponentType<PropsWithChildren>;\n }> = memo(({ threadId, provider: Provider }) => {\n const assistantRuntime = useAssistantRuntime();\n const threadListItemRuntime = useMemo(\n () => assistantRuntime.threads.getItemById(threadId),\n [assistantRuntime, threadId],\n );\n\n return (\n <ThreadListItemRuntimeProvider runtime={threadListItemRuntime}>\n <Provider>\n <this._InnerActiveThreadProvider />\n </Provider>\n </ThreadListItemRuntimeProvider>\n );\n });\n\n public __internal_RenderThreadRuntimes: FC<{\n provider: ComponentType<PropsWithChildren>;\n }> = ({ provider }) => {\n this.useAliveThreadsKeysChanged(); // trigger re-render on alive threads change\n\n return Array.from(this.instances.keys()).map((threadId) => (\n <this._OuterActiveThreadProvider\n key={threadId}\n threadId={threadId}\n provider={provider}\n />\n ));\n };\n}\n"],"mappings":";;;
|
1
|
+
{"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListHookInstanceManager.tsx"],"sourcesContent":["/* eslint-disable react-hooks/rules-of-hooks */\n\"use client\";\n\nimport {\n FC,\n useCallback,\n useRef,\n useEffect,\n memo,\n useMemo,\n PropsWithChildren,\n ComponentType,\n} from \"react\";\nimport { UseBoundStore, StoreApi, create } from \"zustand\";\nimport { useAssistantRuntime } from \"../../context\";\nimport { ThreadListItemRuntimeProvider } from \"../../context/providers/ThreadListItemRuntimeProvider\";\nimport {\n useThreadListItem,\n useThreadListItemRuntime,\n} from \"../../context/react/ThreadListItemContext\";\nimport { ThreadRuntimeCore, ThreadRuntimeImpl } from \"../../internal\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { AssistantRuntime } from \"../../api\";\n\ntype RemoteThreadListHook = () => AssistantRuntime;\n\ntype RemoteThreadListHookInstance = {\n runtime?: ThreadRuntimeCore;\n};\nexport class RemoteThreadListHookInstanceManager extends BaseSubscribable {\n private useRuntimeHook: UseBoundStore<\n StoreApi<{ useRuntime: RemoteThreadListHook }>\n >;\n private instances = new Map<string, RemoteThreadListHookInstance>();\n private useAliveThreadsKeysChanged = create(() => ({}));\n\n constructor(runtimeHook: RemoteThreadListHook) {\n super();\n this.useRuntimeHook = create(() => ({ useRuntime: runtimeHook }));\n }\n\n public startThreadRuntime(threadId: string) {\n if (!this.instances.has(threadId)) {\n this.instances.set(threadId, {});\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n return new Promise<ThreadRuntimeCore>((resolve, reject) => {\n const callback = () => {\n const instance = this.instances.get(threadId);\n if (!instance) {\n dispose();\n reject(new Error(\"Thread was deleted before runtime was started\"));\n } else if (!instance.runtime) {\n return; // misc update\n } else {\n dispose();\n resolve(instance.runtime);\n }\n };\n const dispose = this.subscribe(callback);\n callback();\n });\n }\n\n public getThreadRuntimeCore(threadId: string) {\n const instance = this.instances.get(threadId);\n if (!instance)\n throw new Error(\n \"getThreadRuntimeCore not found. This is a bug in assistant-ui.\",\n );\n return instance.runtime;\n }\n\n public stopThreadRuntime(threadId: string) {\n this.instances.delete(threadId);\n this.useAliveThreadsKeysChanged.setState({}, true);\n }\n\n public setRuntimeHook(newRuntimeHook: RemoteThreadListHook) {\n const prevRuntimeHook = this.useRuntimeHook.getState().useRuntime;\n if (prevRuntimeHook !== newRuntimeHook) {\n this.useRuntimeHook.setState({ useRuntime: newRuntimeHook }, true);\n }\n }\n\n private _InnerActiveThreadProvider: FC = () => {\n const { id } = useThreadListItem();\n\n const { useRuntime } = this.useRuntimeHook();\n const runtime = useRuntime();\n\n const threadBinding = (runtime.thread as ThreadRuntimeImpl)\n .__internal_threadBinding;\n\n const updateRuntime = useCallback(() => {\n const aliveThread = this.instances.get(id);\n if (!aliveThread)\n throw new Error(\"Thread not found. This is a bug in assistant-ui.\");\n\n aliveThread.runtime = threadBinding.getState();\n\n if (isMounted) {\n this._notifySubscribers();\n }\n }, [id, threadBinding]);\n\n const isMounted = useRef(false);\n if (!isMounted.current) {\n updateRuntime();\n }\n\n useEffect(() => {\n isMounted.current = true;\n updateRuntime();\n return threadBinding.outerSubscribe(updateRuntime);\n }, [threadBinding, updateRuntime]);\n\n // auto initialize thread\n const threadListItemRuntime = useThreadListItemRuntime();\n useEffect(() => {\n return runtime.threads.main.unstable_on(\"initialize\", () => {\n if (threadListItemRuntime.getState().status === \"new\") {\n threadListItemRuntime.initialize();\n\n // auto generate a title after first run\n const dispose = runtime.thread.unstable_on(\"run-end\", () => {\n dispose();\n\n threadListItemRuntime.generateTitle();\n });\n }\n });\n }, [runtime, threadListItemRuntime]);\n\n return null;\n };\n\n private _OuterActiveThreadProvider: FC<{\n threadId: string;\n provider: ComponentType<PropsWithChildren>;\n // eslint-disable-next-line react/display-name\n }> = memo(({ threadId, provider: Provider }) => {\n const assistantRuntime = useAssistantRuntime();\n const threadListItemRuntime = useMemo(\n () => assistantRuntime.threads.getItemById(threadId),\n [assistantRuntime, threadId],\n );\n\n return (\n <ThreadListItemRuntimeProvider runtime={threadListItemRuntime}>\n <Provider>\n <this._InnerActiveThreadProvider />\n </Provider>\n </ThreadListItemRuntimeProvider>\n );\n });\n\n public __internal_RenderThreadRuntimes: FC<{\n provider: ComponentType<PropsWithChildren>;\n }> = ({ provider }) => {\n this.useAliveThreadsKeysChanged(); // trigger re-render on alive threads change\n\n return Array.from(this.instances.keys()).map((threadId) => (\n <this._OuterActiveThreadProvider\n key={threadId}\n threadId={threadId}\n provider={provider}\n />\n ));\n };\n}\n"],"mappings":";;;AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAGK;AACP,SAAkC,cAAc;AAChD,SAAS,2BAA2B;AACpC,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,wBAAwB;AAmIvB;AA3HH,IAAM,sCAAN,cAAkD,iBAAiB;AAAA,EAChE;AAAA,EAGA,YAAY,oBAAI,IAA0C;AAAA,EAC1D,6BAA6B,OAAO,OAAO,CAAC,EAAE;AAAA,EAEtD,YAAY,aAAmC;AAC7C,UAAM;AACN,SAAK,iBAAiB,OAAO,OAAO,EAAE,YAAY,YAAY,EAAE;AAAA,EAClE;AAAA,EAEO,mBAAmB,UAAkB;AAC1C,QAAI,CAAC,KAAK,UAAU,IAAI,QAAQ,GAAG;AACjC,WAAK,UAAU,IAAI,UAAU,CAAC,CAAC;AAC/B,WAAK,2BAA2B,SAAS,CAAC,GAAG,IAAI;AAAA,IACnD;AAEA,WAAO,IAAI,QAA2B,CAAC,SAAS,WAAW;AACzD,YAAM,WAAW,MAAM;AACrB,cAAM,WAAW,KAAK,UAAU,IAAI,QAAQ;AAC5C,YAAI,CAAC,UAAU;AACb,kBAAQ;AACR,iBAAO,IAAI,MAAM,+CAA+C,CAAC;AA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AAa;AAAA,IACnD,GAAG,CAAC,eAAe,aAAa,CAAC;AAGjC,UAAM,wBAAwB,yBAAyB;AACvD,cAAU,MAAM;AACd,aAAO,QAAQ,QAAQ,KAAK,YAAY,cAAc,MAAM;AAC1D,YAAI,sBAAsB,SAAS,EAAE,WAAW,OAAO;AACrD,gCAAsB,WAAW;AAGjC,gBAAM,UAAU,QAAQ,OAAO,YAAY,WAAW,MAAM;AAC1D,oBAAQ;AAER,kCAAsB,cAAc;AAAA,UACtC,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,IACH,GAAG,CAAC,SAAS,qBAAqB,CAAC;AAEnC,WAAO;AAAA,EACT;AAAA,EAEQ,6BAIH,KAAK,CAAC,EAAE,UAAU,UAAU,SAAS,MAAM;AAC9C,UAAM,mBAAmB,oBAAoB;AAC7C,UAAM,wBAAwB;AAAA,MAC5B,MAAM,iBAAiB,QAAQ,YAAY,QAAQ;AAAA,MACnD,CAAC,kBAAkB,QAAQ;AAAA,IAC7B;AAEA,WACE,oBAAC,iCAA8B,SAAS,uBACtC,8BAAC,YACC,8BAAC,KAAK,4BAAL,EAAgC,GACnC,GACF;AAAA,EAEJ,CAAC;AAAA,EAEM,kCAEF,CAAC,EAAE,SAAS,MAAM;AACrB,SAAK,2BAA2B;AAEhC,WAAO,MAAM,KAAK,KAAK,UAAU,KAAK,CAAC,EAAE,IAAI,CAAC,aAC5C;AAAA,MAAC,KAAK;AAAA,MAAL;AAAA,QAEC;AAAA,QACA;AAAA;AAAA,MAFK;AAAA,IAGP,CACD;AAAA,EACH;AACF;","names":[]}
|
@@ -114,6 +114,7 @@ export declare class RemoteThreadListThreadListRuntimeCore extends BaseSubscriba
|
|
114
114
|
archive(threadIdOrRemoteId: string): Promise<void>;
|
115
115
|
unarchive(threadIdOrRemoteId: string): Promise<void>;
|
116
116
|
delete(threadIdOrRemoteId: string): Promise<void>;
|
117
|
+
detach(threadIdOrRemoteId: string): Promise<void>;
|
117
118
|
private useBoundIds;
|
118
119
|
__internal_RenderComponent: FC;
|
119
120
|
}
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"file":"RemoteThreadListThreadListRuntimeCore.d.ts","sourceRoot":"","sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEtE,OAAO,EACL,8BAA8B,EAC9B,uBAAuB,EACxB,MAAM,SAAS,CAAC;AAEjB,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAGtD,OAAO,EAAE,EAAE,EAA8B,MAAM,OAAO,CAAC;AAGvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAG3D,KAAK,gBAAgB,GACjB;IACE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC;IACvB,QAAQ,CAAC,KAAK,EAAE,SAAS,CAAC;CAC3B,GACD;IACE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;IACjE,QAAQ,CAAC,QAAQ,CAAC,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,UAAU,CAAC,EAAE,SAAS,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,SAAS,GAAG,UAAU,CAAC;IACxC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC,GACD;IACE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,cAAc,EAAE,OAAO,CAAC,8BAA8B,CAAC,CAAC;IACjE,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,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AI,CAAC;IAqB9C,MAAM,CAAC,kBAAkB,EAAE,MAAM;IAkBjC,MAAM,CAAC,kBAAkB,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAU9D,OAAO,CAAC,WAAW,CAA8B;IAE1C,0BAA0B,EAAE,EAAE,CA4BnC;CACH"}
|
@@ -347,6 +347,8 @@ var RemoteThreadListThreadListRuntimeCore = class extends BaseSubscribable {
|
|
347
347
|
});
|
348
348
|
}
|
349
349
|
async _ensureThreadIsNotMain(threadId) {
|
350
|
+
if (threadId === this.newThreadId)
|
351
|
+
throw new Error("Cannot ensure new thread is not main");
|
350
352
|
if (threadId === this._mainThreadId) {
|
351
353
|
await this.switchToNewThread();
|
352
354
|
}
|
@@ -402,6 +404,14 @@ var RemoteThreadListThreadListRuntimeCore = class extends BaseSubscribable {
|
|
402
404
|
}
|
403
405
|
});
|
404
406
|
}
|
407
|
+
async detach(threadIdOrRemoteId) {
|
408
|
+
const data = this.getItemById(threadIdOrRemoteId);
|
409
|
+
if (!data) throw new Error("Thread not found");
|
410
|
+
if (data.status !== "regular" && data.status !== "archived")
|
411
|
+
throw new Error("Thread is not yet initialized");
|
412
|
+
await this._ensureThreadIsNotMain(data.threadId);
|
413
|
+
this._hookManager.stopThreadRuntime(data.threadId);
|
414
|
+
}
|
405
415
|
useBoundIds = create(() => []);
|
406
416
|
__internal_RenderComponent = () => {
|
407
417
|
const id = useId();
|
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx"],"sourcesContent":["\"use client\";\n\nimport { ThreadListRuntimeCore } from \"../core/ThreadListRuntimeCore\";\nimport { generateId } from \"../../internal\";\nimport {\n RemoteThreadInitializeResponse,\n RemoteThreadListOptions,\n} from \"./types\";\nimport { RemoteThreadListHookInstanceManager } from \"./RemoteThreadListHookInstanceManager\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { EMPTY_THREAD_CORE } from \"./EMPTY_THREAD_CORE\";\nimport { OptimisticState } from \"./OptimisticState\";\nimport { FC, Fragment, useEffect, useId } from \"react\";\nimport { create } from \"zustand\";\nimport { AssistantMessageStream } from \"assistant-stream\";\nimport { ModelContextProvider } from \"../../model-context\";\nimport { RuntimeAdapterProvider } from \"../adapters/RuntimeAdapterProvider\";\n\ntype RemoteThreadData =\n | {\n readonly threadId: string;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"new\";\n readonly title: undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: string;\n readonly externalId: string | undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n };\n\ntype THREAD_MAPPING_ID = string & { __brand: \"THREAD_MAPPING_ID\" };\nfunction createThreadMappingId(id: string): THREAD_MAPPING_ID {\n return id as THREAD_MAPPING_ID;\n}\n\ntype RemoteThreadState = {\n readonly isLoading: boolean;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly threadIdMap: Readonly<Record<string, THREAD_MAPPING_ID>>;\n readonly threadData: Readonly<Record<THREAD_MAPPING_ID, RemoteThreadData>>;\n};\n\nconst getThreadData = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n) => {\n const idx = state.threadIdMap[threadIdOrRemoteId];\n if (idx === undefined) return undefined;\n return state.threadData[idx];\n};\n\nconst updateStatusReducer = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n newStatus: \"regular\" | \"archived\" | \"deleted\",\n) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n const { threadId, remoteId, status: lastStatus } = data;\n if (lastStatus === newStatus) return state;\n\n const newState = { ...state };\n\n // lastStatus\n switch (lastStatus) {\n case \"new\":\n newState.newThreadId = undefined;\n break;\n case \"regular\":\n newState.threadIds = newState.threadIds.filter((t) => t !== threadId);\n break;\n case \"archived\":\n newState.archivedThreadIds = newState.archivedThreadIds.filter(\n (t) => t !== threadId,\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = lastStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n // newStatus\n switch (newStatus) {\n case \"regular\":\n newState.threadIds = [threadId, ...newState.threadIds];\n break;\n\n case \"archived\":\n newState.archivedThreadIds = [threadId, ...newState.archivedThreadIds];\n break;\n\n case \"deleted\":\n newState.threadData = Object.fromEntries(\n Object.entries(newState.threadData).filter(([key]) => key !== threadId),\n );\n newState.threadIdMap = Object.fromEntries(\n Object.entries(newState.threadIdMap).filter(\n ([key]) => key !== threadId && key !== remoteId,\n ),\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = newStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n if (newStatus !== \"deleted\") {\n newState.threadData = {\n ...newState.threadData,\n [threadId]: {\n ...data,\n status: newStatus,\n },\n };\n }\n\n return newState;\n};\n\nexport class RemoteThreadListThreadListRuntimeCore\n extends BaseSubscribable\n implements ThreadListRuntimeCore\n{\n private _options!: RemoteThreadListOptions;\n private readonly _hookManager: RemoteThreadListHookInstanceManager;\n\n private _loadThreadsPromise: Promise<void> | undefined;\n\n private _mainThreadId!: string;\n private readonly _state = new OptimisticState<RemoteThreadState>({\n isLoading: false,\n newThreadId: undefined,\n threadIds: [],\n archivedThreadIds: [],\n threadIdMap: {},\n threadData: {},\n });\n\n public getLoadThreadsPromise() {\n // TODO this needs to be cached in case this promise is loaded during suspense\n if (!this._loadThreadsPromise) {\n this._loadThreadsPromise = this._state\n .optimisticUpdate({\n execute: () => this._options.adapter.list(),\n loading: (state) => {\n return {\n ...state,\n isLoading: true,\n };\n },\n then: (state, l) => {\n const newThreadIds = [];\n const newArchivedThreadIds = [];\n const newThreadIdMap = {} as Record<string, THREAD_MAPPING_ID>;\n const newThreadData = {} as Record<\n THREAD_MAPPING_ID,\n RemoteThreadData\n >;\n\n for (const thread of l.threads) {\n switch (thread.status) {\n case \"regular\":\n newThreadIds.push(thread.remoteId);\n break;\n case \"archived\":\n newArchivedThreadIds.push(thread.remoteId);\n break;\n default: {\n const _exhaustiveCheck: never = thread.status;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n const mappingId = createThreadMappingId(thread.remoteId);\n newThreadIdMap[thread.remoteId] = mappingId;\n newThreadData[mappingId] = {\n threadId: thread.remoteId,\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n status: thread.status,\n title: thread.title,\n initializeTask: Promise.resolve({\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n }),\n };\n }\n\n return {\n ...state,\n threadIds: newThreadIds,\n archivedThreadIds: newArchivedThreadIds,\n threadIdMap: {\n ...state.threadIdMap,\n ...newThreadIdMap,\n },\n threadData: {\n ...state.threadData,\n ...newThreadData,\n },\n };\n },\n })\n .then(() => {});\n }\n\n return this._loadThreadsPromise;\n }\n\n constructor(\n options: RemoteThreadListOptions,\n private readonly contextProvider: ModelContextProvider,\n ) {\n super();\n\n this._state.subscribe(() => this._notifySubscribers());\n this._hookManager = new RemoteThreadListHookInstanceManager(\n options.runtimeHook,\n );\n this.useProvider = create(() => ({\n Provider: options.adapter.unstable_Provider ?? Fragment,\n }));\n this.__internal_setOptions(options);\n\n this.switchToNewThread();\n }\n\n private useProvider;\n\n public __internal_setOptions(options: RemoteThreadListOptions) {\n if (this._options === options) return;\n\n this._options = options;\n\n const Provider = options.adapter.unstable_Provider ?? Fragment;\n if (Provider !== this.useProvider.getState().Provider) {\n this.useProvider.setState({ Provider }, true);\n }\n\n this._hookManager.setRuntimeHook(options.runtimeHook);\n }\n\n public __internal_load() {\n this.getLoadThreadsPromise(); // begin loading on initial bind\n }\n\n public get threadIds() {\n return this._state.value.threadIds;\n }\n\n public get archivedThreadIds() {\n return this._state.value.archivedThreadIds;\n }\n\n public get newThreadId() {\n return this._state.value.newThreadId;\n }\n\n public get mainThreadId(): string {\n return this._mainThreadId;\n }\n\n public getMainThreadRuntimeCore() {\n const result = this._hookManager.getThreadRuntimeCore(this._mainThreadId);\n if (!result) return EMPTY_THREAD_CORE;\n return result;\n }\n\n public getThreadRuntimeCore(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n const result = this._hookManager.getThreadRuntimeCore(data.threadId);\n if (!result) throw new Error(\"Thread not found\");\n return result;\n }\n\n public getItemById(threadIdOrRemoteId: string) {\n return getThreadData(this._state.value, threadIdOrRemoteId);\n }\n\n public async switchToThread(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n if (this._mainThreadId === data.threadId) return;\n\n const task = this._hookManager.startThreadRuntime(data.threadId);\n if (this.mainThreadId !== undefined) {\n await task;\n } else {\n task.then(() => this._notifySubscribers());\n }\n\n if (data.status === \"archived\") await this.unarchive(data.threadId);\n this._mainThreadId = data.threadId;\n\n this._notifySubscribers();\n }\n\n public async switchToNewThread(): Promise<void> {\n // an initialization transaction is in progress, wait for it to settle\n while (\n this._state.baseValue.newThreadId !== undefined &&\n this._state.value.newThreadId === undefined\n ) {\n await this._state.waitForUpdate();\n }\n\n const state = this._state.value;\n let threadId: string | undefined = this._state.value.newThreadId;\n if (threadId === undefined) {\n do {\n threadId = `__LOCALID_${generateId()}`;\n } while (state.threadIdMap[threadId]);\n\n const mappingId = createThreadMappingId(threadId);\n this._state.update({\n ...state,\n newThreadId: threadId,\n threadIdMap: {\n ...state.threadIdMap,\n [threadId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [threadId]: {\n status: \"new\",\n threadId,\n },\n },\n });\n }\n\n return this.switchToThread(threadId);\n }\n\n public initialize = async (threadId: string) => {\n if (this._state.value.newThreadId !== threadId) {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Unexpected new state\");\n return data.initializeTask;\n }\n\n return this._state.optimisticUpdate({\n execute: () => {\n return this._options.adapter.initialize(threadId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, threadId, \"regular\");\n },\n loading: (state, task) => {\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...state.threadData[mappingId],\n initializeTask: task,\n },\n },\n };\n },\n then: (state, { remoteId, externalId }) => {\n const data = getThreadData(state, threadId);\n if (!data) return state;\n\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadIdMap: {\n ...state.threadIdMap,\n [remoteId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...data,\n initializeTask: Promise.resolve({ remoteId, externalId }),\n remoteId,\n externalId,\n },\n },\n };\n },\n });\n };\n\n public generateTitle = async (threadId: string) => {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n const { remoteId } = await data.initializeTask;\n const messages = this.getThreadRuntimeCore(threadId).messages;\n const stream = await this._options.adapter.generateTitle(\n remoteId,\n messages,\n );\n const messageStream = AssistantMessageStream.fromAssistantStream(stream);\n for await (const result of messageStream) {\n const newTitle = result.parts.filter((c) => c.type === \"text\")[0]?.text;\n const state = this._state.baseValue;\n this._state.update({\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n });\n }\n };\n\n public rename(threadIdOrRemoteId: string, newTitle: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.rename(remoteId, newTitle);\n },\n optimistic: (state) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n };\n },\n });\n }\n\n private async _ensureThreadIsNotMain(threadId: string) {\n // if thread is main thread, switch to another thread\n if (threadId === this._mainThreadId) {\n await this.switchToNewThread();\n }\n }\n\n public async archive(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\")\n throw new Error(\"Thread is not yet initialized or already archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.archive(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"archived\");\n },\n });\n }\n\n public unarchive(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"archived\") throw new Error(\"Thread is not archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n try {\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.unarchive(remoteId);\n } catch (error) {\n await this._ensureThreadIsNotMain(data.threadId);\n throw error;\n }\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"regular\");\n },\n });\n }\n\n public async delete(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\" && data.status !== \"archived\")\n throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.delete(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"deleted\");\n },\n });\n }\n\n private useBoundIds = create<string[]>(() => []);\n\n public __internal_RenderComponent: FC = () => {\n const id = useId();\n useEffect(() => {\n this.useBoundIds.setState((s) => [...s, id], true);\n return () => {\n this.useBoundIds.setState((s) => s.filter((i) => i !== id), true);\n };\n }, [id]);\n\n const boundIds = this.useBoundIds();\n const { Provider } = this.useProvider();\n\n const adapters = {\n modelContext: this.contextProvider,\n };\n\n return (\n (boundIds.length === 0 || boundIds[0] === id) && (\n // only render if the component is the first one mounted\n <RuntimeAdapterProvider adapters={adapters}>\n <this._hookManager.__internal_RenderThreadRuntimes\n provider={Provider}\n />\n </RuntimeAdapterProvider>\n )\n );\n };\n}\n"],"mappings":";;;AAGA,SAAS,kBAAkB;AAK3B,SAAS,2CAA2C;AACpD,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAa,UAAU,WAAW,aAAa;AAC/C,SAAS,cAAc;AACvB,SAAS,8BAA8B;AAEvC,SAAS,8BAA8B;AAwhB7B;AA5fV,SAAS,sBAAsB,IAA+B;AAC5D,SAAO;AACT;AAWA,IAAM,gBAAgB,CACpB,OACA,uBACG;AACH,QAAM,MAAM,MAAM,YAAY,kBAAkB;AAChD,MAAI,QAAQ,OAAW,QAAO;AAC9B,SAAO,MAAM,WAAW,GAAG;AAC7B;AAEA,IAAM,sBAAsB,CAC1B,OACA,oBACA,cACG;AACH,QAAM,OAAO,cAAc,OAAO,kBAAkB;AACpD,MAAI,CAAC,KAAM,QAAO;AAElB,QAAM,EAAE,UAAU,UAAU,QAAQ,WAAW,IAAI;AACnD,MAAI,eAAe,UAAW,QAAO;AAErC,QAAM,WAAW,EAAE,GAAG,MAAM;AAG5B,UAAQ,YAAY;AAAA,IAClB,KAAK;AACH,eAAS,cAAc;AACvB;AAAA,IACF,KAAK;AACH,eAAS,YAAY,SAAS,UAAU,OAAO,CAAC,MAAM,MAAM,QAAQ;AACpE;AAAA,IACF,KAAK;AACH,eAAS,oBAAoB,SAAS,kBAAkB;AAAA,QACtD,CAAC,MAAM,MAAM;AAAA,MACf;AACA;AA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,GACF;AAAA,EAGN;AACF;","names":["data"]}
|
1
|
+
{"version":3,"sources":["../../../src/runtimes/remote-thread-list/RemoteThreadListThreadListRuntimeCore.tsx"],"sourcesContent":["\"use client\";\n\nimport { ThreadListRuntimeCore } from \"../core/ThreadListRuntimeCore\";\nimport { generateId } from \"../../internal\";\nimport {\n RemoteThreadInitializeResponse,\n RemoteThreadListOptions,\n} from \"./types\";\nimport { RemoteThreadListHookInstanceManager } from \"./RemoteThreadListHookInstanceManager\";\nimport { BaseSubscribable } from \"./BaseSubscribable\";\nimport { EMPTY_THREAD_CORE } from \"./EMPTY_THREAD_CORE\";\nimport { OptimisticState } from \"./OptimisticState\";\nimport { FC, Fragment, useEffect, useId } from \"react\";\nimport { create } from \"zustand\";\nimport { AssistantMessageStream } from \"assistant-stream\";\nimport { ModelContextProvider } from \"../../model-context\";\nimport { RuntimeAdapterProvider } from \"../adapters/RuntimeAdapterProvider\";\n\ntype RemoteThreadData =\n | {\n readonly threadId: string;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"new\";\n readonly title: undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId?: undefined;\n readonly externalId?: undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n }\n | {\n readonly threadId: string;\n readonly initializeTask: Promise<RemoteThreadInitializeResponse>;\n readonly remoteId: string;\n readonly externalId: string | undefined;\n readonly status: \"regular\" | \"archived\";\n readonly title?: string | undefined;\n };\n\ntype THREAD_MAPPING_ID = string & { __brand: \"THREAD_MAPPING_ID\" };\nfunction createThreadMappingId(id: string): THREAD_MAPPING_ID {\n return id as THREAD_MAPPING_ID;\n}\n\ntype RemoteThreadState = {\n readonly isLoading: boolean;\n readonly newThreadId: string | undefined;\n readonly threadIds: readonly string[];\n readonly archivedThreadIds: readonly string[];\n readonly threadIdMap: Readonly<Record<string, THREAD_MAPPING_ID>>;\n readonly threadData: Readonly<Record<THREAD_MAPPING_ID, RemoteThreadData>>;\n};\n\nconst getThreadData = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n) => {\n const idx = state.threadIdMap[threadIdOrRemoteId];\n if (idx === undefined) return undefined;\n return state.threadData[idx];\n};\n\nconst updateStatusReducer = (\n state: RemoteThreadState,\n threadIdOrRemoteId: string,\n newStatus: \"regular\" | \"archived\" | \"deleted\",\n) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n const { threadId, remoteId, status: lastStatus } = data;\n if (lastStatus === newStatus) return state;\n\n const newState = { ...state };\n\n // lastStatus\n switch (lastStatus) {\n case \"new\":\n newState.newThreadId = undefined;\n break;\n case \"regular\":\n newState.threadIds = newState.threadIds.filter((t) => t !== threadId);\n break;\n case \"archived\":\n newState.archivedThreadIds = newState.archivedThreadIds.filter(\n (t) => t !== threadId,\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = lastStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n // newStatus\n switch (newStatus) {\n case \"regular\":\n newState.threadIds = [threadId, ...newState.threadIds];\n break;\n\n case \"archived\":\n newState.archivedThreadIds = [threadId, ...newState.archivedThreadIds];\n break;\n\n case \"deleted\":\n newState.threadData = Object.fromEntries(\n Object.entries(newState.threadData).filter(([key]) => key !== threadId),\n );\n newState.threadIdMap = Object.fromEntries(\n Object.entries(newState.threadIdMap).filter(\n ([key]) => key !== threadId && key !== remoteId,\n ),\n );\n break;\n\n default: {\n const _exhaustiveCheck: never = newStatus;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n if (newStatus !== \"deleted\") {\n newState.threadData = {\n ...newState.threadData,\n [threadId]: {\n ...data,\n status: newStatus,\n },\n };\n }\n\n return newState;\n};\n\nexport class RemoteThreadListThreadListRuntimeCore\n extends BaseSubscribable\n implements ThreadListRuntimeCore\n{\n private _options!: RemoteThreadListOptions;\n private readonly _hookManager: RemoteThreadListHookInstanceManager;\n\n private _loadThreadsPromise: Promise<void> | undefined;\n\n private _mainThreadId!: string;\n private readonly _state = new OptimisticState<RemoteThreadState>({\n isLoading: false,\n newThreadId: undefined,\n threadIds: [],\n archivedThreadIds: [],\n threadIdMap: {},\n threadData: {},\n });\n\n public getLoadThreadsPromise() {\n // TODO this needs to be cached in case this promise is loaded during suspense\n if (!this._loadThreadsPromise) {\n this._loadThreadsPromise = this._state\n .optimisticUpdate({\n execute: () => this._options.adapter.list(),\n loading: (state) => {\n return {\n ...state,\n isLoading: true,\n };\n },\n then: (state, l) => {\n const newThreadIds = [];\n const newArchivedThreadIds = [];\n const newThreadIdMap = {} as Record<string, THREAD_MAPPING_ID>;\n const newThreadData = {} as Record<\n THREAD_MAPPING_ID,\n RemoteThreadData\n >;\n\n for (const thread of l.threads) {\n switch (thread.status) {\n case \"regular\":\n newThreadIds.push(thread.remoteId);\n break;\n case \"archived\":\n newArchivedThreadIds.push(thread.remoteId);\n break;\n default: {\n const _exhaustiveCheck: never = thread.status;\n throw new Error(`Unsupported state: ${_exhaustiveCheck}`);\n }\n }\n\n const mappingId = createThreadMappingId(thread.remoteId);\n newThreadIdMap[thread.remoteId] = mappingId;\n newThreadData[mappingId] = {\n threadId: thread.remoteId,\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n status: thread.status,\n title: thread.title,\n initializeTask: Promise.resolve({\n remoteId: thread.remoteId,\n externalId: thread.externalId,\n }),\n };\n }\n\n return {\n ...state,\n threadIds: newThreadIds,\n archivedThreadIds: newArchivedThreadIds,\n threadIdMap: {\n ...state.threadIdMap,\n ...newThreadIdMap,\n },\n threadData: {\n ...state.threadData,\n ...newThreadData,\n },\n };\n },\n })\n .then(() => {});\n }\n\n return this._loadThreadsPromise;\n }\n\n constructor(\n options: RemoteThreadListOptions,\n private readonly contextProvider: ModelContextProvider,\n ) {\n super();\n\n this._state.subscribe(() => this._notifySubscribers());\n this._hookManager = new RemoteThreadListHookInstanceManager(\n options.runtimeHook,\n );\n this.useProvider = create(() => ({\n Provider: options.adapter.unstable_Provider ?? Fragment,\n }));\n this.__internal_setOptions(options);\n\n this.switchToNewThread();\n }\n\n private useProvider;\n\n public __internal_setOptions(options: RemoteThreadListOptions) {\n if (this._options === options) return;\n\n this._options = options;\n\n const Provider = options.adapter.unstable_Provider ?? Fragment;\n if (Provider !== this.useProvider.getState().Provider) {\n this.useProvider.setState({ Provider }, true);\n }\n\n this._hookManager.setRuntimeHook(options.runtimeHook);\n }\n\n public __internal_load() {\n this.getLoadThreadsPromise(); // begin loading on initial bind\n }\n\n public get threadIds() {\n return this._state.value.threadIds;\n }\n\n public get archivedThreadIds() {\n return this._state.value.archivedThreadIds;\n }\n\n public get newThreadId() {\n return this._state.value.newThreadId;\n }\n\n public get mainThreadId(): string {\n return this._mainThreadId;\n }\n\n public getMainThreadRuntimeCore() {\n const result = this._hookManager.getThreadRuntimeCore(this._mainThreadId);\n if (!result) return EMPTY_THREAD_CORE;\n return result;\n }\n\n public getThreadRuntimeCore(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n const result = this._hookManager.getThreadRuntimeCore(data.threadId);\n if (!result) throw new Error(\"Thread not found\");\n return result;\n }\n\n public getItemById(threadIdOrRemoteId: string) {\n return getThreadData(this._state.value, threadIdOrRemoteId);\n }\n\n public async switchToThread(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n\n if (this._mainThreadId === data.threadId) return;\n\n const task = this._hookManager.startThreadRuntime(data.threadId);\n if (this.mainThreadId !== undefined) {\n await task;\n } else {\n task.then(() => this._notifySubscribers());\n }\n\n if (data.status === \"archived\") await this.unarchive(data.threadId);\n this._mainThreadId = data.threadId;\n\n this._notifySubscribers();\n }\n\n public async switchToNewThread(): Promise<void> {\n // an initialization transaction is in progress, wait for it to settle\n while (\n this._state.baseValue.newThreadId !== undefined &&\n this._state.value.newThreadId === undefined\n ) {\n await this._state.waitForUpdate();\n }\n\n const state = this._state.value;\n let threadId: string | undefined = this._state.value.newThreadId;\n if (threadId === undefined) {\n do {\n threadId = `__LOCALID_${generateId()}`;\n } while (state.threadIdMap[threadId]);\n\n const mappingId = createThreadMappingId(threadId);\n this._state.update({\n ...state,\n newThreadId: threadId,\n threadIdMap: {\n ...state.threadIdMap,\n [threadId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [threadId]: {\n status: \"new\",\n threadId,\n },\n },\n });\n }\n\n return this.switchToThread(threadId);\n }\n\n public initialize = async (threadId: string) => {\n if (this._state.value.newThreadId !== threadId) {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Unexpected new state\");\n return data.initializeTask;\n }\n\n return this._state.optimisticUpdate({\n execute: () => {\n return this._options.adapter.initialize(threadId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, threadId, \"regular\");\n },\n loading: (state, task) => {\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...state.threadData[mappingId],\n initializeTask: task,\n },\n },\n };\n },\n then: (state, { remoteId, externalId }) => {\n const data = getThreadData(state, threadId);\n if (!data) return state;\n\n const mappingId = createThreadMappingId(threadId);\n return {\n ...state,\n threadIdMap: {\n ...state.threadIdMap,\n [remoteId]: mappingId,\n },\n threadData: {\n ...state.threadData,\n [mappingId]: {\n ...data,\n initializeTask: Promise.resolve({ remoteId, externalId }),\n remoteId,\n externalId,\n },\n },\n };\n },\n });\n };\n\n public generateTitle = async (threadId: string) => {\n const data = this.getItemById(threadId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n const { remoteId } = await data.initializeTask;\n const messages = this.getThreadRuntimeCore(threadId).messages;\n const stream = await this._options.adapter.generateTitle(\n remoteId,\n messages,\n );\n const messageStream = AssistantMessageStream.fromAssistantStream(stream);\n for await (const result of messageStream) {\n const newTitle = result.parts.filter((c) => c.type === \"text\")[0]?.text;\n const state = this._state.baseValue;\n this._state.update({\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n });\n }\n };\n\n public rename(threadIdOrRemoteId: string, newTitle: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status === \"new\") throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.rename(remoteId, newTitle);\n },\n optimistic: (state) => {\n const data = getThreadData(state, threadIdOrRemoteId);\n if (!data) return state;\n\n return {\n ...state,\n threadData: {\n ...state.threadData,\n [data.threadId]: {\n ...data,\n title: newTitle,\n },\n },\n };\n },\n });\n }\n\n private async _ensureThreadIsNotMain(threadId: string) {\n if (threadId === this.newThreadId)\n throw new Error(\"Cannot ensure new thread is not main\");\n\n if (threadId === this._mainThreadId) {\n await this.switchToNewThread();\n }\n }\n\n public async archive(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\")\n throw new Error(\"Thread is not yet initialized or already archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return this._options.adapter.archive(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"archived\");\n },\n });\n }\n\n public unarchive(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"archived\") throw new Error(\"Thread is not archived\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n try {\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.unarchive(remoteId);\n } catch (error) {\n await this._ensureThreadIsNotMain(data.threadId);\n throw error;\n }\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"regular\");\n },\n });\n }\n\n public async delete(threadIdOrRemoteId: string) {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\" && data.status !== \"archived\")\n throw new Error(\"Thread is not yet initialized\");\n\n return this._state.optimisticUpdate({\n execute: async () => {\n await this._ensureThreadIsNotMain(data.threadId);\n const { remoteId } = await data.initializeTask;\n return await this._options.adapter.delete(remoteId);\n },\n optimistic: (state) => {\n return updateStatusReducer(state, data.threadId, \"deleted\");\n },\n });\n }\n\n public async detach(threadIdOrRemoteId: string): Promise<void> {\n const data = this.getItemById(threadIdOrRemoteId);\n if (!data) throw new Error(\"Thread not found\");\n if (data.status !== \"regular\" && data.status !== \"archived\")\n throw new Error(\"Thread is not yet initialized\");\n\n await this._ensureThreadIsNotMain(data.threadId);\n this._hookManager.stopThreadRuntime(data.threadId);\n }\n\n private useBoundIds = create<string[]>(() => []);\n\n public __internal_RenderComponent: FC = () => {\n // eslint-disable-next-line react-hooks/rules-of-hooks\n const id = useId();\n // eslint-disable-next-line react-hooks/rules-of-hooks\n useEffect(() => {\n this.useBoundIds.setState((s) => [...s, id], true);\n return () => {\n this.useBoundIds.setState((s) => s.filter((i) => i !== id), true);\n };\n }, [id]);\n\n const boundIds = this.useBoundIds();\n const { Provider } = this.useProvider();\n\n const adapters = {\n modelContext: this.contextProvider,\n };\n\n return (\n (boundIds.length === 0 || boundIds[0] === id) && (\n // only render if the component is the first one mounted\n <RuntimeAdapterProvider adapters={adapters}>\n <this._hookManager.__internal_RenderThreadRuntimes\n provider={Provider}\n />\n </RuntimeAdapterProvider>\n )\n );\n };\n}\n"],"mappings":";;;AAGA,SAAS,kBAAkB;AAK3B,SAAS,2CAA2C;AACpD,SAAS,wBAAwB;AACjC,SAAS,yBAAyB;AAClC,SAAS,uBAAuB;AAChC,SAAa,UAAU,WAAW,aAAa;AAC/C,SAAS,cAAc;AACvB,SAAS,8BAA8B;AAEvC,SAAS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AAAA,MACpD;AAAA,MACA,YAAY,CAAC,UAAU;AACrB,eAAO,oBAAoB,OAAO,KAAK,UAAU,SAAS;AAAA,MAC5D;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEA,MAAa,OAAO,oBAA2C;AAC7D,UAAM,OAAO,KAAK,YAAY,kBAAkB;AAChD,QAAI,CAAC,KAAM,OAAM,IAAI,MAAM,kBAAkB;AAC7C,QAAI,KAAK,WAAW,aAAa,KAAK,WAAW;AAC/C,YAAM,IAAI,MAAM,+BAA+B;AAEjD,UAAM,KAAK,uBAAuB,KAAK,QAAQ;AAC/C,SAAK,aAAa,kBAAkB,KAAK,QAAQ;AAAA,EACnD;AAAA,EAEQ,cAAc,OAAiB,MAAM,CAAC,CAAC;AAAA,EAExC,6BAAiC,MAAM;AAE5C,UAAM,KAAK,MAAM;AAEjB,cAAU,MAAM;AACd,WAAK,YAAY,SAAS,CAAC,MAAM,CAAC,GAAG,GAAG,EAAE,GAAG,IAAI;AACjD,aAAO,MAAM;AACX,aAAK,YAAY,SAAS,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,MAAM,EAAE,GAAG,IAAI;AAAA,MAClE;AAAA,IACF,GAAG,CAAC,EAAE,CAAC;AAEP,UAAM,WAAW,KAAK,YAAY;AAClC,UAAM,EAAE,SAAS,IAAI,KAAK,YAAY;AAEtC,UAAM,WAAW;AAAA,MACf,cAAc,KAAK;AAAA,IACrB;AAEA,YACG,SAAS,WAAW,KAAK,SAAS,CAAC,MAAM;AAAA,IAExC,oBAAC,0BAAuB,UACtB;AAAA,MAAC,KAAK,aAAa;AAAA,MAAlB;AAAA,QACC,UAAU;AAAA;AAAA,IACZ,GACF;AAAA,EAGN;AACF;","names":["data"]}
|
package/package.json
CHANGED
@@ -100,21 +100,75 @@ const getEditComposerState = (
|
|
100
100
|
export type ComposerRuntime = {
|
101
101
|
readonly path: ComposerRuntimePath;
|
102
102
|
readonly type: "edit" | "thread";
|
103
|
+
|
104
|
+
/**
|
105
|
+
* Get the current state of the composer. Includes any data that has been added to the composer.
|
106
|
+
*/
|
103
107
|
getState(): ComposerState;
|
104
108
|
|
105
109
|
getAttachmentAccept(): string;
|
110
|
+
|
111
|
+
/**
|
112
|
+
* Given a standard js File object, add it to the composer. A composer can have multiple attachments.
|
113
|
+
* @param file The file to add to the composer.
|
114
|
+
*/
|
106
115
|
addAttachment(file: File): Promise<void>;
|
107
116
|
|
117
|
+
/**
|
118
|
+
* Set the text of the composer.
|
119
|
+
* @param text The text to set in the composer.
|
120
|
+
*/
|
108
121
|
setText(text: string): void;
|
122
|
+
|
123
|
+
/**
|
124
|
+
* Set the role of the composer. For instance, if you'd like a specific message to have the 'assistant' role, you can do so here.
|
125
|
+
* @param role The role to set in the composer.
|
126
|
+
*/
|
109
127
|
setRole(role: MessageRole): void;
|
128
|
+
|
129
|
+
/**
|
130
|
+
* Set the run config of the composer. This is used to send custom configuration data to the model.
|
131
|
+
* Within your backend, you can access this data using the `runConfig` object.
|
132
|
+
* Example:
|
133
|
+
* ```ts
|
134
|
+
* composerRuntime.setRunConfig({
|
135
|
+
* custom: { customField: "customValue" }
|
136
|
+
* });
|
137
|
+
* ```
|
138
|
+
* @param runConfig The run config to set in the composer.
|
139
|
+
*/
|
110
140
|
setRunConfig(runConfig: RunConfig): void;
|
111
141
|
|
142
|
+
/**
|
143
|
+
* Reset the composer. This will clear the entire state of the composer, including all text and attachments.
|
144
|
+
*/
|
112
145
|
reset(): Promise<void>;
|
146
|
+
|
147
|
+
/**
|
148
|
+
* Clear all attachments from the composer.
|
149
|
+
*/
|
113
150
|
clearAttachments(): Promise<void>;
|
114
151
|
|
152
|
+
/**
|
153
|
+
* Send a message. This will send whatever text or attachments are in the composer.
|
154
|
+
*/
|
115
155
|
send(): void;
|
156
|
+
|
157
|
+
/**
|
158
|
+
* Cancel the current run. In edit mode, this will exit edit mode.
|
159
|
+
*/
|
116
160
|
cancel(): void;
|
161
|
+
|
162
|
+
/**
|
163
|
+
* Listens for changes to the composer state.
|
164
|
+
* @param callback The callback to call when the composer state changes.
|
165
|
+
*/
|
117
166
|
subscribe(callback: () => void): Unsubscribe;
|
167
|
+
|
168
|
+
/**
|
169
|
+
* Get an attachment by index.
|
170
|
+
* @param idx The index of the attachment to get.
|
171
|
+
*/
|
118
172
|
getAttachmentByIndex(idx: number): AttachmentRuntime;
|
119
173
|
};
|
120
174
|
|
@@ -34,6 +34,11 @@ export type ThreadListItemRuntime = {
|
|
34
34
|
unarchive(): Promise<void>;
|
35
35
|
delete(): Promise<void>;
|
36
36
|
|
37
|
+
/**
|
38
|
+
* Detaches the ThreadListItem instance, unmounting the ThreadRuntime hook.
|
39
|
+
*/
|
40
|
+
detach(): void;
|
41
|
+
|
37
42
|
subscribe(callback: () => void): Unsubscribe;
|
38
43
|
|
39
44
|
unstable_on(
|
@@ -68,6 +73,7 @@ export class ThreadListItemRuntimeImpl implements ThreadListItemRuntime {
|
|
68
73
|
this.subscribe = this.subscribe.bind(this);
|
69
74
|
this.unstable_on = this.unstable_on.bind(this);
|
70
75
|
this.getState = this.getState.bind(this);
|
76
|
+
this.detach = this.detach.bind(this);
|
71
77
|
}
|
72
78
|
|
73
79
|
public getState(): ThreadListItemState {
|
@@ -132,4 +138,10 @@ export class ThreadListItemRuntimeImpl implements ThreadListItemRuntime {
|
|
132
138
|
public subscribe(callback: () => void): Unsubscribe {
|
133
139
|
return this._core.subscribe(callback);
|
134
140
|
}
|
141
|
+
|
142
|
+
public detach(): void {
|
143
|
+
const state = this._core.getState();
|
144
|
+
|
145
|
+
this._threadListBinding.detach(state.id);
|
146
|
+
}
|
135
147
|
}
|
package/src/cloud/auiV0.ts
CHANGED
@@ -3,10 +3,7 @@ import { MessageStatus } from "../types/AssistantTypes";
|
|
3
3
|
import { fromThreadMessageLike } from "../runtimes/external-store/ThreadMessageLike";
|
4
4
|
import { CloudMessage } from "./AssistantCloudThreadMessages";
|
5
5
|
import { isJSONValue } from "../utils/json/is-json";
|
6
|
-
import {
|
7
|
-
ReadonlyJSONObject,
|
8
|
-
ReadonlyJSONValue,
|
9
|
-
} from "assistant-stream/utils";
|
6
|
+
import { ReadonlyJSONObject, ReadonlyJSONValue } from "assistant-stream/utils";
|
10
7
|
import { ExportedMessageRepositoryItem } from "../runtimes/utils/MessageRepository";
|
11
8
|
|
12
9
|
type AuiV0MessageContentPart =
|
@@ -47,6 +44,7 @@ type AuiV0Message = {
|
|
47
44
|
readonly status?: MessageStatus;
|
48
45
|
readonly content: readonly AuiV0MessageContentPart[];
|
49
46
|
readonly metadata: {
|
47
|
+
readonly unstable_state?: ReadonlyJSONValue;
|
50
48
|
readonly unstable_annotations: readonly ReadonlyJSONValue[];
|
51
49
|
readonly unstable_data: readonly ReadonlyJSONValue[];
|
52
50
|
readonly steps: readonly {
|
@@ -4,6 +4,7 @@ import { composeEventHandlers } from "@radix-ui/primitive";
|
|
4
4
|
import { useComposedRefs } from "@radix-ui/react-compose-refs";
|
5
5
|
import { Slot } from "@radix-ui/react-slot";
|
6
6
|
import {
|
7
|
+
ClipboardEvent,
|
7
8
|
type KeyboardEvent,
|
8
9
|
forwardRef,
|
9
10
|
useCallback,
|
@@ -31,6 +32,7 @@ export namespace ComposerPrimitiveInput {
|
|
31
32
|
unstable_focusOnRunStart?: boolean | undefined;
|
32
33
|
unstable_focusOnScrollToBottom?: boolean | undefined;
|
33
34
|
unstable_focusOnThreadSwitched?: boolean | undefined;
|
35
|
+
addAttachmentOnPaste?: boolean | undefined;
|
34
36
|
};
|
35
37
|
}
|
36
38
|
|
@@ -45,11 +47,13 @@ export const ComposerPrimitiveInput = forwardRef<
|
|
45
47
|
disabled: disabledProp,
|
46
48
|
onChange,
|
47
49
|
onKeyDown,
|
50
|
+
onPaste,
|
48
51
|
submitOnEnter = true,
|
49
52
|
cancelOnEscape = true,
|
50
53
|
unstable_focusOnRunStart = true,
|
51
54
|
unstable_focusOnScrollToBottom = true,
|
52
55
|
unstable_focusOnThreadSwitched = true,
|
56
|
+
addAttachmentOnPaste = true,
|
53
57
|
...rest
|
54
58
|
},
|
55
59
|
forwardedRef,
|
@@ -95,6 +99,23 @@ export const ComposerPrimitiveInput = forwardRef<
|
|
95
99
|
}
|
96
100
|
};
|
97
101
|
|
102
|
+
const handlePaste = async (e: ClipboardEvent<HTMLTextAreaElement>) => {
|
103
|
+
if (!addAttachmentOnPaste) return;
|
104
|
+
const threadCapabilities = threadRuntime.getState().capabilities;
|
105
|
+
const files = Array.from(e.clipboardData?.files || []);
|
106
|
+
|
107
|
+
if (threadCapabilities.attachments && files.length > 0) {
|
108
|
+
try {
|
109
|
+
e.preventDefault();
|
110
|
+
await Promise.all(
|
111
|
+
files.map((file) => composerRuntime.addAttachment(file)),
|
112
|
+
);
|
113
|
+
} catch (error) {
|
114
|
+
console.error("Error adding attachment:", error);
|
115
|
+
}
|
116
|
+
}
|
117
|
+
};
|
118
|
+
|
98
119
|
const autoFocusEnabled = autoFocus && !isDisabled;
|
99
120
|
const focus = useCallback(() => {
|
100
121
|
const textarea = textareaRef.current;
|
@@ -143,6 +164,7 @@ export const ComposerPrimitiveInput = forwardRef<
|
|
143
164
|
return composerRuntime.setText(e.target.value);
|
144
165
|
})}
|
145
166
|
onKeyDown={composeEventHandlers(onKeyDown, handleKeyPress)}
|
167
|
+
onPaste={composeEventHandlers(onPaste, handlePaste)}
|
146
168
|
/>
|
147
169
|
);
|
148
170
|
},
|
@@ -0,0 +1,31 @@
|
|
1
|
+
"use client";
|
2
|
+
|
3
|
+
import { Primitive } from "@radix-ui/react-primitive";
|
4
|
+
import { type ComponentRef, forwardRef, ComponentPropsWithoutRef } from "react";
|
5
|
+
import { useMessage } from "../../context/react/MessageContext";
|
6
|
+
|
7
|
+
export namespace ErrorPrimitiveMessage {
|
8
|
+
export type Element = ComponentRef<typeof Primitive.span>;
|
9
|
+
export type Props = ComponentPropsWithoutRef<typeof Primitive.span>;
|
10
|
+
}
|
11
|
+
|
12
|
+
export const ErrorPrimitiveMessage = forwardRef<
|
13
|
+
ErrorPrimitiveMessage.Element,
|
14
|
+
ErrorPrimitiveMessage.Props
|
15
|
+
>(({ children, ...props }, forwardRef) => {
|
16
|
+
const error = useMessage((m) => {
|
17
|
+
return m.status?.type === "incomplete" && m.status.reason === "error"
|
18
|
+
? m.status.error
|
19
|
+
: undefined;
|
20
|
+
});
|
21
|
+
|
22
|
+
if (error === undefined) return null;
|
23
|
+
|
24
|
+
return (
|
25
|
+
<Primitive.span {...props} ref={forwardRef}>
|
26
|
+
{children ?? String(error)}
|
27
|
+
</Primitive.span>
|
28
|
+
);
|
29
|
+
});
|
30
|
+
|
31
|
+
ErrorPrimitiveMessage.displayName = "ErrorPrimitive.Message";
|
@@ -0,0 +1,18 @@
|
|
1
|
+
"use client";
|
2
|
+
|
3
|
+
import { Primitive } from "@radix-ui/react-primitive";
|
4
|
+
import { type ComponentRef, forwardRef, ComponentPropsWithoutRef } from "react";
|
5
|
+
|
6
|
+
export namespace ErrorPrimitiveRoot {
|
7
|
+
export type Element = ComponentRef<typeof Primitive.div>;
|
8
|
+
export type Props = ComponentPropsWithoutRef<typeof Primitive.div>;
|
9
|
+
}
|
10
|
+
|
11
|
+
export const ErrorPrimitiveRoot = forwardRef<
|
12
|
+
ErrorPrimitiveRoot.Element,
|
13
|
+
ErrorPrimitiveRoot.Props
|
14
|
+
>((props, forwardRef) => {
|
15
|
+
return <Primitive.div role="alert" {...props} ref={forwardRef} />;
|
16
|
+
});
|
17
|
+
|
18
|
+
ErrorPrimitiveRoot.displayName = "ErrorPrimitive.Root";
|
package/src/primitives/index.ts
CHANGED
@@ -4,6 +4,7 @@ export * as AttachmentPrimitive from "./attachment";
|
|
4
4
|
export * as BranchPickerPrimitive from "./branchPicker";
|
5
5
|
export * as ComposerPrimitive from "./composer";
|
6
6
|
export * as ContentPartPrimitive from "./contentPart";
|
7
|
+
export * as ErrorPrimitive from "./error";
|
7
8
|
export * as MessagePrimitive from "./message";
|
8
9
|
export * as ThreadPrimitive from "./thread";
|
9
10
|
export * as ThreadListPrimitive from "./threadList";
|
@@ -218,12 +218,24 @@ export const MessagePrimitiveContent: FC<MessagePrimitiveContent.Props> = ({
|
|
218
218
|
const contentLength = useMessage((s) => s.content.length);
|
219
219
|
|
220
220
|
if (contentLength === 0) {
|
221
|
-
return
|
221
|
+
return (
|
222
|
+
<>
|
223
|
+
<EmptyContent components={components} />
|
224
|
+
</>
|
225
|
+
);
|
222
226
|
}
|
223
227
|
|
224
|
-
return
|
225
|
-
|
226
|
-
|
228
|
+
return (
|
229
|
+
<>
|
230
|
+
{Array.from({ length: contentLength }, (_, index) => (
|
231
|
+
<MessageContentPart
|
232
|
+
key={index}
|
233
|
+
partIndex={index}
|
234
|
+
components={components}
|
235
|
+
/>
|
236
|
+
))}
|
237
|
+
</>
|
238
|
+
);
|
227
239
|
};
|
228
240
|
|
229
241
|
MessagePrimitiveContent.displayName = "MessagePrimitive.Content";
|
@@ -0,0 +1,13 @@
|
|
1
|
+
"use client";
|
2
|
+
|
3
|
+
import { FC, PropsWithChildren } from "react";
|
4
|
+
import { useMessage } from "../../context/react/MessageContext";
|
5
|
+
|
6
|
+
export const MessagePrimitiveError: FC<PropsWithChildren> = ({ children }) => {
|
7
|
+
const hasError = useMessage(
|
8
|
+
(m) => m.status?.type === "incomplete" && m.status.reason === "error",
|
9
|
+
);
|
10
|
+
return hasError ? <>{children}</> : null;
|
11
|
+
};
|
12
|
+
|
13
|
+
MessagePrimitiveError.displayName = "MessagePrimitive.Error";
|
@@ -2,3 +2,4 @@ export { MessagePrimitiveRoot as Root } from "./MessageRoot";
|
|
2
2
|
export { MessagePrimitiveIf as If } from "./MessageIf";
|
3
3
|
export { MessagePrimitiveContent as Content } from "./MessageContent";
|
4
4
|
export { MessagePrimitiveAttachments as Attachments } from "./MessageAttachments";
|
5
|
+
export { MessagePrimitiveError as Error } from "./MessageError";
|
@@ -30,6 +30,7 @@ export type ThreadListRuntimeCore = {
|
|
30
30
|
getLoadThreadsPromise(): Promise<void>;
|
31
31
|
// getLoadArchivedThreadsPromise(): Promise<void>;
|
32
32
|
|
33
|
+
detach(threadId: string): Promise<void>;
|
33
34
|
rename(threadId: string, newTitle: string): Promise<void>;
|
34
35
|
archive(threadId: string): Promise<void>;
|
35
36
|
unarchive(threadId: string): Promise<void>;
|
@@ -139,6 +139,10 @@ export class ExternalStoreThreadListRuntimeCore
|
|
139
139
|
onRename(threadId, newTitle);
|
140
140
|
}
|
141
141
|
|
142
|
+
public async detach(): Promise<void> {
|
143
|
+
// no-op
|
144
|
+
}
|
145
|
+
|
142
146
|
public async archive(threadId: string): Promise<void> {
|
143
147
|
const onArchive = this.adapter.onArchive;
|
144
148
|
if (!onArchive)
|
@@ -113,6 +113,10 @@ const joinExternalMessages = (
|
|
113
113
|
|
114
114
|
if (output.metadata) {
|
115
115
|
assistantMessage.metadata ??= {};
|
116
|
+
if (output.metadata.unstable_state) {
|
117
|
+
assistantMessage.metadata.unstable_state =
|
118
|
+
output.metadata.unstable_state;
|
119
|
+
}
|
116
120
|
if (output.metadata.unstable_annotations) {
|
117
121
|
assistantMessage.metadata.unstable_annotations = [
|
118
122
|
...(assistantMessage.metadata.unstable_annotations ?? []),
|
@@ -22,6 +22,7 @@ export type ChatModelRunResult = {
|
|
22
22
|
readonly content?: readonly ThreadAssistantContentPart[] | undefined;
|
23
23
|
readonly status?: MessageStatus | undefined;
|
24
24
|
readonly metadata?: {
|
25
|
+
readonly unstable_state?: ReadonlyJSONValue;
|
25
26
|
readonly unstable_annotations?: readonly ReadonlyJSONValue[] | undefined;
|
26
27
|
readonly unstable_data?: readonly ReadonlyJSONValue[] | undefined;
|
27
28
|
readonly steps?: readonly ThreadStep[] | undefined;
|
@@ -74,6 +74,10 @@ export class LocalThreadListRuntimeCore
|
|
74
74
|
throw new Error("Method not implemented.");
|
75
75
|
}
|
76
76
|
|
77
|
+
public detach(): Promise<void> {
|
78
|
+
throw new Error("Method not implemented.");
|
79
|
+
}
|
80
|
+
|
77
81
|
public unarchive(): Promise<void> {
|
78
82
|
throw new Error("Method not implemented.");
|
79
83
|
}
|
@@ -252,6 +252,9 @@ export class LocalThreadRuntimeCore
|
|
252
252
|
? {
|
253
253
|
metadata: {
|
254
254
|
...message.metadata,
|
255
|
+
...(m.metadata.unstable_state
|
256
|
+
? { unstable_state: m.metadata.unstable_state }
|
257
|
+
: undefined),
|
255
258
|
...(annotations
|
256
259
|
? { unstable_annotations: annotations }
|
257
260
|
: undefined),
|
@@ -368,8 +371,13 @@ export class LocalThreadRuntimeCore
|
|
368
371
|
return message;
|
369
372
|
}
|
370
373
|
|
374
|
+
public detach() {
|
375
|
+
this.abortController?.abort({ detach: true });
|
376
|
+
this.abortController = null;
|
377
|
+
}
|
378
|
+
|
371
379
|
public cancelRun() {
|
372
|
-
this.abortController?.abort();
|
380
|
+
this.abortController?.abort({ detach: false });
|
373
381
|
this.abortController = null;
|
374
382
|
}
|
375
383
|
|
@@ -28,6 +28,12 @@ const useLocalThreadRuntime = (
|
|
28
28
|
|
29
29
|
const [runtime] = useState(() => new LocalRuntimeCore(opt, initialMessages));
|
30
30
|
|
31
|
+
useEffect(() => {
|
32
|
+
return () => {
|
33
|
+
runtime.threads.getMainThreadRuntimeCore().detach();
|
34
|
+
};
|
35
|
+
}, [runtime]);
|
36
|
+
|
31
37
|
useEffect(() => {
|
32
38
|
runtime.threads.getMainThreadRuntimeCore().__internal_setOptions(opt);
|
33
39
|
runtime.threads.getMainThreadRuntimeCore().__internal_load();
|