@assistant-ui/react 0.10.9 → 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/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/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 +5 -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/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/local/LocalThreadListRuntimeCore.tsx +4 -0
- package/src/runtimes/local/LocalThreadRuntimeCore.tsx +6 -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
@@ -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;AAAA,IAEF,SAAS;AACP,YAAM,mBAA0B;AAChC,YAAM,IAAI,MAAM,sBAAsB,gBAAgB,EAAE;AAAA,IAC1D;AAAA,EACF;AAGA,UAAQ,WAAW;AAAA,IACjB,KAAK;AACH,eAAS,YAAY,CAAC,UAAU,GAAG,SAAS,SAAS;AACrD;AAAA,IAEF,KAAK;AACH,eAAS,oBAAoB,CAAC,UAAU,GAAG,SAAS,iBAAi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WAAW;AAC/C,YAAM,IAAI,MAAM,+BAA+B;AAEjD,WAAO,KAAK,OAAO,iBAAiB;AAAA,MAClC,SAAS,YAAY;AACnB,cAAM,KAAK,uBAAuB,KAAK,QAAQ;AAC/C,cAAM,EAAE,SAAS,IAAI,MAAM,KAAK;AAChC,eAAO,MAAM,KAAK,SAAS,QAAQ,OAAO,QAAQ;AAAA,MACpD;AAAA,MACA,YAAY,CAAC,UAAU;AACrB,eAAO,oBAAoB,OAAO,KAAK,UAAU,SAAS;AAAA,MAC5D;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EAEQ,cAAc,OAAiB,MAAM,CAAC,CAAC;AAAA,EAExC,6BAAiC,MAAM;AAC5C,UAAM,KAAK,MAAM;AACjB,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"]}
|
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,8BAA8B;AAsiB7B;AA1gBV,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,QAA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AAK,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
|
}
|
@@ -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)
|
@@ -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
|
}
|
@@ -371,8 +371,13 @@ export class LocalThreadRuntimeCore
|
|
371
371
|
return message;
|
372
372
|
}
|
373
373
|
|
374
|
+
public detach() {
|
375
|
+
this.abortController?.abort({ detach: true });
|
376
|
+
this.abortController = null;
|
377
|
+
}
|
378
|
+
|
374
379
|
public cancelRun() {
|
375
|
-
this.abortController?.abort();
|
380
|
+
this.abortController?.abort({ detach: false });
|
376
381
|
this.abortController = null;
|
377
382
|
}
|
378
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();
|
@@ -1,3 +1,4 @@
|
|
1
|
+
/* eslint-disable react-hooks/rules-of-hooks */
|
1
2
|
"use client";
|
2
3
|
|
3
4
|
import {
|
@@ -138,6 +139,7 @@ export class RemoteThreadListHookInstanceManager extends BaseSubscribable {
|
|
138
139
|
private _OuterActiveThreadProvider: FC<{
|
139
140
|
threadId: string;
|
140
141
|
provider: ComponentType<PropsWithChildren>;
|
142
|
+
// eslint-disable-next-line react/display-name
|
141
143
|
}> = memo(({ threadId, provider: Provider }) => {
|
142
144
|
const assistantRuntime = useAssistantRuntime();
|
143
145
|
const threadListItemRuntime = useMemo(
|
@@ -465,7 +465,9 @@ export class RemoteThreadListThreadListRuntimeCore
|
|
465
465
|
}
|
466
466
|
|
467
467
|
private async _ensureThreadIsNotMain(threadId: string) {
|
468
|
-
|
468
|
+
if (threadId === this.newThreadId)
|
469
|
+
throw new Error("Cannot ensure new thread is not main");
|
470
|
+
|
469
471
|
if (threadId === this._mainThreadId) {
|
470
472
|
await this.switchToNewThread();
|
471
473
|
}
|
@@ -528,10 +530,22 @@ export class RemoteThreadListThreadListRuntimeCore
|
|
528
530
|
});
|
529
531
|
}
|
530
532
|
|
533
|
+
public async detach(threadIdOrRemoteId: string): Promise<void> {
|
534
|
+
const data = this.getItemById(threadIdOrRemoteId);
|
535
|
+
if (!data) throw new Error("Thread not found");
|
536
|
+
if (data.status !== "regular" && data.status !== "archived")
|
537
|
+
throw new Error("Thread is not yet initialized");
|
538
|
+
|
539
|
+
await this._ensureThreadIsNotMain(data.threadId);
|
540
|
+
this._hookManager.stopThreadRuntime(data.threadId);
|
541
|
+
}
|
542
|
+
|
531
543
|
private useBoundIds = create<string[]>(() => []);
|
532
544
|
|
533
545
|
public __internal_RenderComponent: FC = () => {
|
546
|
+
// eslint-disable-next-line react-hooks/rules-of-hooks
|
534
547
|
const id = useId();
|
548
|
+
// eslint-disable-next-line react-hooks/rules-of-hooks
|
535
549
|
useEffect(() => {
|
536
550
|
this.useBoundIds.setState((s) => [...s, id], true);
|
537
551
|
return () => {
|