@assistant-ui/core 0.3.3 → 0.3.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/internal.d.ts +4 -2
- package/dist/internal.js +4 -2
- package/dist/react/primitive-hooks/useSuggestionTrigger.js +29 -25
- package/dist/react/primitive-hooks/useSuggestionTrigger.js.map +1 -1
- package/dist/react/primitives/message/MessageParts.d.ts +6 -1
- package/dist/react/primitives/message/MessageParts.d.ts.map +1 -1
- package/dist/react/primitives/message/MessageParts.js.map +1 -1
- package/dist/react/providers/ReadonlyThreadProvider.d.ts.map +1 -1
- package/dist/react/providers/ReadonlyThreadProvider.js +1 -0
- package/dist/react/providers/ReadonlyThreadProvider.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts +67 -0
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +76 -15
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +4 -0
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +22 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.d.ts +2 -0
- package/dist/react/runtimes/cloud/auiV0.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.js +6 -4
- package/dist/react/runtimes/cloud/auiV0.js.map +1 -1
- package/dist/react/types/MessagePartComponentTypes.d.ts +8 -0
- package/dist/react/types/MessagePartComponentTypes.d.ts.map +1 -1
- package/dist/runtime/api/bindings.d.ts +5 -0
- package/dist/runtime/api/bindings.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-runtime.d.ts +14 -1
- package/dist/runtime/api/thread-list-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-runtime.js +6 -1
- package/dist/runtime/api/thread-list-runtime.js.map +1 -1
- package/dist/runtime/api/thread-runtime.d.ts +7 -1
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js +11 -3
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts +3 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +54 -12
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/interfaces/thread-list-runtime-core.d.ts +10 -0
- package/dist/runtime/interfaces/thread-list-runtime-core.d.ts.map +1 -1
- package/dist/runtime/interfaces/thread-runtime-core.d.ts +14 -0
- package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-adapter.d.ts +9 -0
- package/dist/runtimes/external-store/external-store-adapter.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts +1 -0
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js +4 -0
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts +1 -0
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js +6 -0
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts +1 -0
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +1 -0
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts +1 -0
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js +1 -0
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js.map +1 -1
- package/dist/runtimes/remote-thread-list/empty-thread-core.js +1 -0
- package/dist/runtimes/remote-thread-list/empty-thread-core.js.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts +1 -0
- package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js +66 -45
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-list-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-runtime-client.js +91 -75
- package/dist/store/runtime-clients/thread-list-runtime-client.js.map +1 -1
- package/dist/store/scopes/thread-list-item.d.ts +7 -0
- package/dist/store/scopes/thread-list-item.d.ts.map +1 -1
- package/dist/store/scopes/threads.d.ts +1 -0
- package/dist/store/scopes/threads.d.ts.map +1 -1
- package/dist/types/message.d.ts +11 -0
- package/dist/types/message.d.ts.map +1 -1
- package/dist/types/message.js.map +1 -1
- package/dist/utils/data-url.d.ts +14 -1
- package/dist/utils/data-url.d.ts.map +1 -1
- package/dist/utils/data-url.js +23 -1
- package/dist/utils/data-url.js.map +1 -1
- package/dist/utils/image-media-type.d.ts +13 -0
- package/dist/utils/image-media-type.d.ts.map +1 -0
- package/dist/utils/image-media-type.js +141 -0
- package/dist/utils/image-media-type.js.map +1 -0
- package/dist/utils/wire-media.d.ts +35 -0
- package/dist/utils/wire-media.d.ts.map +1 -0
- package/dist/utils/wire-media.js +55 -0
- package/dist/utils/wire-media.js.map +1 -0
- package/package.json +4 -4
- package/src/internal.ts +12 -1
- package/src/react/primitive-hooks/useSuggestionTrigger.test.ts +148 -0
- package/src/react/primitive-hooks/useSuggestionTrigger.ts +10 -4
- package/src/react/primitives/message/MessageParts.tsx +6 -1
- package/src/react/providers/ReadonlyThreadProvider.tsx +1 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.running.test.tsx +157 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.test.tsx +160 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +135 -32
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +41 -1
- package/src/react/runtimes/cloud/auiV0.ts +8 -2
- package/src/react/types/MessagePartComponentTypes.ts +8 -0
- package/src/runtime/api/bindings.ts +5 -0
- package/src/runtime/api/thread-list-runtime.ts +22 -1
- package/src/runtime/api/thread-runtime.ts +15 -6
- package/src/runtime/base/base-composer-runtime-core.ts +72 -19
- package/src/runtime/interfaces/thread-list-runtime-core.ts +11 -0
- package/src/runtime/interfaces/thread-runtime-core.ts +15 -0
- package/src/runtimes/external-store/external-store-adapter.ts +9 -0
- package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +9 -0
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +8 -0
- package/src/runtimes/local/local-thread-runtime-core.ts +1 -0
- package/src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts +1 -0
- package/src/runtimes/remote-thread-list/empty-thread-core.ts +1 -0
- package/src/store/runtime-clients/thread-list-item-runtime-client.ts +13 -2
- package/src/store/runtime-clients/thread-list-runtime-client.ts +13 -1
- package/src/store/scopes/thread-list-item.ts +7 -0
- package/src/store/scopes/threads.ts +1 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-reloadMainThread.test.ts +257 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-switchToThread-order.test.ts +31 -0
- package/src/tests/auiV0Encode.test.ts +125 -1
- package/src/tests/base-composer-runtime-core-addAttachment.test.ts +296 -0
- package/src/tests/event-subscription-listener-errors.test.ts +1 -0
- package/src/tests/external-store-thread-list-runtime-core.test.ts +39 -1
- package/src/types/message.ts +11 -0
- package/src/utils/data-url.ts +24 -0
- package/src/utils/image-media-type.test.ts +96 -0
- package/src/utils/image-media-type.ts +118 -0
- package/src/utils/wire-media.test.ts +96 -0
- package/src/utils/wire-media.ts +70 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-composer-runtime-core.js","names":["isCreateAttachment","Attachment","CompleteAttachment","CreateAttachment","PendingAttachment","MessageRole","AppendMessage","QuoteInfo","Unsubscribe","RunConfig","BaseSubscribable","AttachmentAdapter","fileMatchesAccept","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","SendOptions","DictationAdapter","EMPTY_QUEUE_ITEMS","QueueItemState","generateId","notifyEventListeners","isAttachmentComplete","a","status","type","BaseComposerRuntimeCore","isEditing","getAttachmentAdapter","getDictationAdapter","enrichWithComposerMetadata","metadata","custom","Record","message","T","composerMetadata","attachmentAccept","accept","_attachments","attachments","setAttachments","value","_notifySubscribers","canCancel","canSend","isEmpty","text","trim","length","_text","_role","role","_runConfig","runConfig","_quote","undefined","quote","setQuote","setText","_dictation","_dictationBaseText","_currentInterimText","inputDisabled","setRole","setRunConfig","_isSending","_removedDuringSend","Set","_sendGeneration","_emptyTextAndAttachments","_onClearAttachments","adapter","pending","filter","Promise","all","map","remove","reset","clear","Object","keys","task","clearAttachments","send","options","_dictationSession","cancel","_cleanupDictation","attachmentTasks","Error","result","originalAttachments","generation","resolvedAttachments","e","allSettled","then","sentIds","id","has","finalAttachments","Omit","createdAt","Date","content","sendTask","handleSend","catch","_notifyEventSubscribers","handleCancel","queue","steerQueueItem","_queueItemId","removeQueueItem","addAttachment","fileOrAttachment","File","name","contentType","err","_safeEmitAttachmentAddError","upsertAttachment","idx","findIndex","attachment","slice","lastAttachment","promiseOrGenerator","add","file","Symbol","asyncIterator","r","reason","String","attachmentId","error","subscriberError","console","removeAttachment","index","Session","_dictationUnsubscribes","_dictationSessionIdCounter","_activeDictationSessionId","_isCleaningDictation","dictation","_isActiveSession","sessionId","session","startDictation","unsub","oldSession","stop","disableInputDuringDictation","listen","unsubSpeech","onSpeech","isFinal","needsSeparator","endsWith","transcript","separator","_","rest","push","unsubStart","onSpeechStart","unsubEnd","onSpeechEnd","statusInterval","setInterval","clearInterval","stopDictation","finally","isStaleSession","_eventSubscribers","Map","payload","event","E","subscribers","get","unstable_on","callback","wrapped","set","delete"],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"sourcesContent":["import {\n isCreateAttachment,\n type Attachment,\n type CompleteAttachment,\n type CreateAttachment,\n type PendingAttachment,\n} from \"../../types/attachment\";\nimport type { MessageRole, AppendMessage } from \"../../types/message\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\nimport {\n type AttachmentAdapter,\n fileMatchesAccept,\n} from \"../../adapters/attachment\";\nimport type {\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n SendOptions,\n} from \"../interfaces/composer-runtime-core\";\nimport type { DictationAdapter } from \"../../adapters/speech\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport { generateId } from \"../../utils/id\";\nimport { notifyEventListeners } from \"../../utils/notify-event-listeners\";\n\nconst isAttachmentComplete = (a: Attachment): a is CompleteAttachment =>\n a.status.type === \"complete\";\n\nexport abstract class BaseComposerRuntimeCore\n extends BaseSubscribable\n implements ComposerRuntimeCore\n{\n public readonly isEditing = true;\n\n protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n protected abstract getDictationAdapter(): DictationAdapter | undefined;\n\n protected enrichWithComposerMetadata<\n T extends { metadata?: { custom?: Record<string, unknown> } },\n >(message: T, composerMetadata: Record<string, unknown> | undefined): T {\n if (!composerMetadata) return message;\n return {\n ...message,\n metadata: {\n ...message.metadata,\n custom: { ...message.metadata?.custom, ...composerMetadata },\n },\n } as T;\n }\n\n public get attachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\n\n private _attachments: readonly Attachment[] = [];\n public get attachments() {\n return this._attachments;\n }\n\n protected setAttachments(value: readonly Attachment[]) {\n this._attachments = value;\n this._notifySubscribers();\n }\n\n public abstract get canCancel(): boolean;\n public abstract get canSend(): boolean;\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\n }\n\n private _text = \"\";\n\n get text() {\n return this._text;\n }\n\n private _role: MessageRole = \"user\";\n\n get role() {\n return this._role;\n }\n\n private _runConfig: RunConfig = {};\n\n get runConfig() {\n return this._runConfig;\n }\n\n private _quote: QuoteInfo | undefined = undefined;\n\n get quote() {\n return this._quote;\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n if (this._quote === quote) return;\n\n this._quote = quote;\n this._notifySubscribers();\n }\n\n public setText(value: string) {\n if (this._text === value) return;\n\n this._text = value;\n if (this._dictation) {\n this._dictationBaseText = value;\n this._currentInterimText = \"\";\n const { status, inputDisabled } = this._dictation;\n this._dictation = inputDisabled ? { status, inputDisabled } : { status };\n }\n this._notifySubscribers();\n }\n\n public setRole(role: MessageRole) {\n if (this._role === role) return;\n\n this._role = role;\n this._notifySubscribers();\n }\n\n public setRunConfig(runConfig: RunConfig) {\n if (this._runConfig === runConfig) return;\n\n this._runConfig = runConfig;\n this._notifySubscribers();\n }\n\n protected _isSending = false;\n private _removedDuringSend = new Set<string>();\n private _sendGeneration = 0;\n\n private _emptyTextAndAttachments() {\n this._attachments = [];\n this._text = \"\";\n this._notifySubscribers();\n }\n\n private async _onClearAttachments() {\n const adapter = this.getAttachmentAdapter();\n if (adapter) {\n const pending = this._attachments.filter((a) => !isAttachmentComplete(a));\n await Promise.all(pending.map((a) => adapter.remove(a)));\n }\n }\n\n public async reset() {\n // A send whose adapter never settles must not brick the composer; reset is\n // the escape hatch that releases the in-flight lock. Bumping the generation\n // invalidates that send entirely so a late-settling upload can neither\n // append the discarded draft nor touch a newer send's lock.\n this._sendGeneration++;\n this._isSending = false;\n this._removedDuringSend.clear();\n\n if (\n this._attachments.length === 0 &&\n this._text === \"\" &&\n this._role === \"user\" &&\n Object.keys(this._runConfig).length === 0 &&\n this._quote === undefined\n ) {\n return;\n }\n\n this._role = \"user\";\n this._runConfig = {};\n this._quote = undefined;\n\n const task = this._onClearAttachments();\n this._emptyTextAndAttachments();\n await task;\n }\n\n public async clearAttachments() {\n const task = this._onClearAttachments();\n this.setAttachments([]);\n\n await task;\n }\n\n public async send(options?: SendOptions) {\n if (!this.canSend || this._isSending) return;\n\n if (this._dictationSession) {\n this._dictationSession.cancel();\n this._cleanupDictation();\n }\n\n const adapter = this.getAttachmentAdapter();\n const attachmentTasks = this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n if (!adapter) throw new Error(\"Attachments are not supported\");\n const result = await adapter.send(a);\n return result as CompleteAttachment;\n });\n\n const originalAttachments = this.attachments;\n const text = this.text;\n const quote = this._quote;\n this._quote = undefined;\n this._text = \"\";\n this._isSending = true;\n const generation = ++this._sendGeneration;\n this._notifySubscribers();\n\n let resolvedAttachments: CompleteAttachment[];\n try {\n resolvedAttachments = await Promise.all(attachmentTasks);\n } catch (e) {\n if (generation === this._sendGeneration) {\n if (!this.text.trim() && this._quote === undefined) {\n this._text = text;\n this._quote = quote;\n this._notifySubscribers();\n }\n // Promise.all rejects on the first failure, but sibling uploads from\n // this batch keep running; the send rejects immediately while the\n // retry lock is held until they settle, or a retry could re-send\n // attachments that are still in flight.\n void Promise.allSettled(attachmentTasks).then(() => {\n if (generation !== this._sendGeneration) return;\n this._removedDuringSend.clear();\n this._isSending = false;\n this._notifySubscribers();\n });\n }\n throw e;\n }\n\n // A reset during the upload discarded this send's draft; the settled\n // uploads must not append it or touch the lock a newer send may own.\n if (generation !== this._sendGeneration) return;\n\n // Drop by id, not wholesale: the user may have added or removed chips while\n // the upload was in flight.\n const sentIds = new Set(originalAttachments.map((a) => a.id));\n this._attachments = this._attachments.filter((a) => !sentIds.has(a.id));\n this._isSending = false;\n this._notifySubscribers();\n\n // An attachment removed mid-upload can't be cancelled, but it can still be\n // dropped from the outgoing message instead of silently being sent anyway.\n const finalAttachments = resolvedAttachments.filter(\n (a) => !this._removedDuringSend.has(a.id),\n );\n this._removedDuringSend.clear();\n\n const message: Omit<AppendMessage, \"parentId\" | \"sourceId\"> = {\n createdAt: new Date(),\n role: this.role,\n content: text ? [{ type: \"text\", text }] : [],\n attachments: finalAttachments,\n runConfig: this.runConfig,\n metadata: { custom: { ...(quote ? { quote } : {}) } },\n };\n\n const sendTask = this.handleSend(message, options);\n if (sendTask) void sendTask.catch(() => {});\n this._notifyEventSubscribers(\"send\", {});\n }\n\n public cancel() {\n this.handleCancel();\n }\n\n public get queue(): readonly QueueItemState[] {\n return EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(_queueItemId: string): void {}\n public removeQueueItem(_queueItemId: string): void {}\n\n protected abstract handleSend(\n message: Omit<AppendMessage, \"parentId\" | \"sourceId\">,\n options?: SendOptions,\n ): void | Promise<void>;\n protected abstract handleCancel(): void;\n\n async addAttachment(fileOrAttachment: File | CreateAttachment) {\n if (isCreateAttachment(fileOrAttachment)) {\n const adapter = this.getAttachmentAdapter();\n if (\n adapter &&\n !fileMatchesAccept(\n {\n name: fileOrAttachment.name,\n type: fileOrAttachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.contentType || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\n \"not-accepted\",\n message,\n undefined,\n err,\n );\n throw err;\n }\n\n const a: CompleteAttachment = {\n id: fileOrAttachment.id ?? generateId(),\n type: fileOrAttachment.type ?? \"document\",\n name: fileOrAttachment.name,\n contentType: fileOrAttachment.contentType,\n content: fileOrAttachment.content,\n status: { type: \"complete\" },\n };\n this._attachments = [...this._attachments, a];\n this._notifySubscribers();\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n return;\n }\n\n const upsertAttachment = (a: PendingAttachment) => {\n const idx = this._attachments.findIndex(\n (attachment) => attachment.id === a.id,\n );\n if (idx !== -1)\n this._attachments = [\n ...this._attachments.slice(0, idx),\n a,\n ...this._attachments.slice(idx + 1),\n ];\n else {\n this._attachments = [...this._attachments, a];\n }\n\n this._notifySubscribers();\n };\n\n const adapter = this.getAttachmentAdapter();\n if (!adapter) {\n const message = \"Attachments are not supported\";\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"no-adapter\", message, undefined, err);\n throw err;\n }\n\n if (\n !fileMatchesAccept(\n { name: fileOrAttachment.name, type: fileOrAttachment.type },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.type || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"not-accepted\", message, undefined, err);\n throw err;\n }\n\n let lastAttachment: PendingAttachment | undefined;\n try {\n const promiseOrGenerator = adapter.add({ file: fileOrAttachment });\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n lastAttachment = r;\n upsertAttachment(r);\n }\n } else {\n lastAttachment = await promiseOrGenerator;\n upsertAttachment(lastAttachment);\n }\n } catch (e) {\n if (lastAttachment) {\n upsertAttachment({\n ...lastAttachment,\n status: {\n type: \"incomplete\",\n reason: \"error\",\n message: e instanceof Error ? e.message : String(e),\n },\n });\n }\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n e instanceof Error ? e.message : String(e),\n lastAttachment?.id,\n e instanceof Error ? e : undefined,\n );\n throw e;\n }\n\n if (\n lastAttachment?.status.type === \"incomplete\" &&\n lastAttachment.status.reason === \"error\"\n ) {\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n lastAttachment.status.message ??\n \"Attachment upload did not complete successfully.\",\n lastAttachment.id,\n );\n } else {\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n }\n }\n\n private _safeEmitAttachmentAddError(\n reason: AttachmentAddErrorReason,\n message: string,\n attachmentId?: string,\n error?: Error,\n ) {\n try {\n this._notifyEventSubscribers(\"attachmentAddError\", {\n reason,\n message,\n ...(attachmentId !== undefined && { attachmentId }),\n ...(error !== undefined && { error }),\n });\n } catch (subscriberError) {\n console.error(\n \"[assistant-ui] attachmentAddError subscriber threw:\",\n subscriberError,\n );\n }\n }\n\n async removeAttachment(attachmentId: string) {\n const index = this._attachments.findIndex((a) => a.id === attachmentId);\n if (index === -1) throw new Error(\"Attachment not found\");\n const attachment = this._attachments[index]!;\n\n // A send in flight may already be uploading this attachment; the upload\n // can't be cancelled, so mark it to be dropped from the outgoing message\n // before any await gives the upload a chance to settle first.\n if (this._isSending) this._removedDuringSend.add(attachmentId);\n\n if (!isAttachmentComplete(attachment)) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n await adapter.remove(attachment);\n }\n this._attachments = this._attachments.filter((a) => a.id !== attachmentId);\n this._notifySubscribers();\n }\n\n private _dictation: DictationState | undefined;\n private _dictationSession: DictationAdapter.Session | undefined;\n private _dictationUnsubscribes: Unsubscribe[] = [];\n private _dictationBaseText = \"\";\n private _currentInterimText = \"\";\n private _dictationSessionIdCounter = 0;\n private _activeDictationSessionId: number | undefined;\n private _isCleaningDictation = false;\n\n public get dictation(): DictationState | undefined {\n return this._dictation;\n }\n\n private _isActiveSession(\n sessionId: number,\n session: DictationAdapter.Session,\n ): boolean {\n return (\n this._activeDictationSessionId === sessionId &&\n this._dictationSession === session\n );\n }\n\n public startDictation(): void {\n const adapter = this.getDictationAdapter();\n if (!adapter) {\n throw new Error(\"Dictation adapter not configured\");\n }\n\n if (this._dictationSession) {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n const oldSession = this._dictationSession;\n oldSession.stop().catch(() => {});\n this._dictationSession = undefined;\n }\n\n const inputDisabled = adapter.disableInputDuringDictation ?? false;\n\n this._dictationBaseText = this._text;\n this._currentInterimText = \"\";\n\n const session = adapter.listen();\n this._dictationSession = session;\n const sessionId = ++this._dictationSessionIdCounter;\n this._activeDictationSessionId = sessionId;\n this._dictation = { status: session.status, inputDisabled };\n this._notifySubscribers();\n\n const unsubSpeech = session.onSpeech((result) => {\n if (!this._isActiveSession(sessionId, session)) return;\n const isFinal = result.isFinal !== false;\n\n const needsSeparator =\n this._dictationBaseText &&\n !this._dictationBaseText.endsWith(\" \") &&\n result.transcript;\n const separator = needsSeparator ? \" \" : \"\";\n\n if (isFinal) {\n this._dictationBaseText =\n this._dictationBaseText + separator + result.transcript;\n this._currentInterimText = \"\";\n this._text = this._dictationBaseText;\n\n if (this._dictation) {\n const { transcript: _, ...rest } = this._dictation;\n this._dictation = rest;\n }\n this._notifySubscribers();\n } else {\n this._currentInterimText = separator + result.transcript;\n this._text = this._dictationBaseText + this._currentInterimText;\n\n if (this._dictation) {\n this._dictation = {\n ...this._dictation,\n transcript: result.transcript,\n };\n }\n this._notifySubscribers();\n }\n });\n this._dictationUnsubscribes.push(unsubSpeech);\n\n const unsubStart = session.onSpeechStart(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n this._dictation = {\n status: { type: \"running\" },\n inputDisabled,\n ...(this._dictation?.transcript && {\n transcript: this._dictation.transcript,\n }),\n };\n this._notifySubscribers();\n });\n this._dictationUnsubscribes.push(unsubStart);\n\n const unsubEnd = session.onSpeechEnd(() => {\n this._cleanupDictation({ sessionId });\n });\n this._dictationUnsubscribes.push(unsubEnd);\n\n const statusInterval = setInterval(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n if (session.status.type === \"ended\") {\n this._cleanupDictation({ sessionId });\n }\n }, 100);\n this._dictationUnsubscribes.push(() => clearInterval(statusInterval));\n }\n\n public stopDictation(): void {\n if (!this._dictationSession) return;\n\n const session = this._dictationSession;\n const sessionId = this._activeDictationSessionId;\n session.stop().finally(() => {\n this._cleanupDictation({ sessionId });\n });\n }\n\n private _cleanupDictation(options?: { sessionId: number | undefined }): void {\n const isStaleSession =\n options?.sessionId !== undefined &&\n options.sessionId !== this._activeDictationSessionId;\n if (isStaleSession || this._isCleaningDictation) return;\n\n this._isCleaningDictation = true;\n try {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n this._dictationSession = undefined;\n this._activeDictationSessionId = undefined;\n this._dictation = undefined;\n this._dictationBaseText = \"\";\n this._currentInterimText = \"\";\n this._notifySubscribers();\n } finally {\n this._isCleaningDictation = false;\n }\n }\n\n private _eventSubscribers = new Map<\n ComposerRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n protected _notifyEventSubscribers<E extends ComposerRuntimeEventType>(\n event: E,\n payload: ComposerRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n notifyEventListeners(subscribers, payload, `Composer runtime \"${event}\"`);\n }\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;;;;AAiCA,MAAMyB,wBAAwBC,MAC5BA,EAAEC,OAAOC,SAAS;AAEpB,IAAsBC,0BAAtB,cACUnB,iBAEV;CACE,YAA4B;CAK5B,2BAEE2B,SAAYE,kBAA0D;EACtE,IAAI,CAACA,kBAAkB,OAAOF;EAC9B,OAAO;GACL,GAAGA;GACHH,UAAU;IACR,GAAGG,QAAQH;IACXC,QAAQ;KAAE,GAAGE,QAAQH,UAAUC;KAAQ,GAAGI;IAAiB;GAC7D;EACF;CACF;CAEA,IAAWC,mBAA2B;EACpC,OAAO,KAAKT,qBAAqB,CAAC,EAAEU,UAAU;CAChD;CAEA,eAA8C,CAAA;CAC9C,IAAWE,cAA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S,KAAKT,wBACvBS,MAAM;GAER,KAAKT,yBAAyB,CAAA;GAC9B,KAAKzD,oBAAoB/B,KAAAA;GACzB,KAAK0F,4BAA4B1F,KAAAA;GACjC,KAAKI,aAAaJ,KAAAA;GAClB,KAAKK,qBAAqB;GAC1B,KAAKC,sBAAsB;GAC3B,KAAKnB,mBAAmB;EAC1B,UAAU;GACR,KAAKwG,uBAAuB;EAC9B;CACF;CAEA,oCAA4B,IAAIgC,IAG9B;CAEF,wBACEE,OACAD,SACA;EACA,MAAMG,cAAc,KAAKL,kBAAkBM,IAAIH,KAAK;EACpD,IAAI,CAACE,aAAa;EAElBlK,qBAAqBkK,aAAaH,SAAS,qBAAqBC,MAAK,EAAG;CAC1E;CAEA,YACEA,OACAK,UACA;EACA,MAAMC,UAAUD;EAChB,IAAIH,cAAc,KAAKL,kBAAkBM,IAAIH,KAAK;EAClD,IAAI,CAACE,aAAa;GAChBA,8BAAc,IAAInH,IAAI;GACtB,KAAK8G,kBAAkBU,IAAIP,OAAOE,WAAW;EAC/C;EACAA,YAAYrD,IAAIyD,OAAO;EAEvB,aAAa;GACX,KAAKT,kBAAkBM,IAAIH,KAAK,CAAC,EAAEQ,OAAOF,OAAO;EACnD;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"base-composer-runtime-core.js","names":["isCreateAttachment","Attachment","CompleteAttachment","CreateAttachment","PendingAttachment","MessageRole","AppendMessage","QuoteInfo","Unsubscribe","RunConfig","BaseSubscribable","AttachmentAdapter","fileMatchesAccept","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","SendOptions","DictationAdapter","EMPTY_QUEUE_ITEMS","QueueItemState","generateId","notifyEventListeners","isAttachmentComplete","a","status","type","AttachmentAddOperation","cancelled","attachmentIds","Set","BaseComposerRuntimeCore","isEditing","getAttachmentAdapter","getDictationAdapter","enrichWithComposerMetadata","metadata","custom","Record","message","T","composerMetadata","attachmentAccept","accept","_attachments","attachments","setAttachments","value","_notifySubscribers","canCancel","canSend","isEmpty","text","trim","length","_text","_role","role","_runConfig","runConfig","_quote","undefined","quote","setQuote","setText","_dictation","_dictationBaseText","_currentInterimText","inputDisabled","setRole","setRunConfig","_isSending","_removedDuringSend","_sendGeneration","_attachmentAddOperations","_cancelAttachmentAdd","attachmentId","operation","has","delete","_cancelAllAttachmentAdds","clear","_emptyTextAndAttachments","_onClearAttachments","adapter","pending","filter","Promise","all","map","remove","reset","Object","keys","task","clearAttachments","send","options","_dictationSession","cancel","_cleanupDictation","attachmentTasks","Error","result","originalAttachments","generation","resolvedAttachments","e","allSettled","then","sentIds","id","finalAttachments","Omit","createdAt","Date","content","sendTask","handleSend","catch","_notifyEventSubscribers","handleCancel","queue","steerQueueItem","_queueItemId","removeQueueItem","addAttachment","fileOrAttachment","File","name","contentType","err","_safeEmitAttachmentAddError","operations","add","upsertAttachment","idx","findIndex","attachment","slice","lastAttachment","promiseOrGenerator","file","Symbol","asyncIterator","r","reason","String","error","subscriberError","console","removeAttachment","index","candidate","Session","_dictationUnsubscribes","_dictationSessionIdCounter","_activeDictationSessionId","_isCleaningDictation","dictation","_isActiveSession","sessionId","session","startDictation","unsub","oldSession","stop","disableInputDuringDictation","listen","unsubSpeech","onSpeech","isFinal","needsSeparator","endsWith","transcript","separator","_","rest","push","unsubStart","onSpeechStart","unsubEnd","onSpeechEnd","statusInterval","setInterval","clearInterval","stopDictation","finally","isStaleSession","_eventSubscribers","Map","payload","event","E","subscribers","get","unstable_on","callback","wrapped","set"],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"sourcesContent":["import {\n isCreateAttachment,\n type Attachment,\n type CompleteAttachment,\n type CreateAttachment,\n type PendingAttachment,\n} from \"../../types/attachment\";\nimport type { MessageRole, AppendMessage } from \"../../types/message\";\nimport type { QuoteInfo } from \"../../types/quote\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { RunConfig } from \"../../types/message\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\nimport {\n type AttachmentAdapter,\n fileMatchesAccept,\n} from \"../../adapters/attachment\";\nimport type {\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n SendOptions,\n} from \"../interfaces/composer-runtime-core\";\nimport type { DictationAdapter } from \"../../adapters/speech\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport { generateId } from \"../../utils/id\";\nimport { notifyEventListeners } from \"../../utils/notify-event-listeners\";\n\nconst isAttachmentComplete = (a: Attachment): a is CompleteAttachment =>\n a.status.type === \"complete\";\n\ntype AttachmentAddOperation = {\n cancelled: boolean;\n attachmentIds: Set<string>;\n};\n\nexport abstract class BaseComposerRuntimeCore\n extends BaseSubscribable\n implements ComposerRuntimeCore\n{\n public readonly isEditing = true;\n\n protected abstract getAttachmentAdapter(): AttachmentAdapter | undefined;\n protected abstract getDictationAdapter(): DictationAdapter | undefined;\n\n protected enrichWithComposerMetadata<\n T extends { metadata?: { custom?: Record<string, unknown> } },\n >(message: T, composerMetadata: Record<string, unknown> | undefined): T {\n if (!composerMetadata) return message;\n return {\n ...message,\n metadata: {\n ...message.metadata,\n custom: { ...message.metadata?.custom, ...composerMetadata },\n },\n } as T;\n }\n\n public get attachmentAccept(): string {\n return this.getAttachmentAdapter()?.accept ?? \"*\";\n }\n\n private _attachments: readonly Attachment[] = [];\n public get attachments() {\n return this._attachments;\n }\n\n protected setAttachments(value: readonly Attachment[]) {\n this._attachments = value;\n this._notifySubscribers();\n }\n\n public abstract get canCancel(): boolean;\n public abstract get canSend(): boolean;\n\n public get isEmpty() {\n return !this.text.trim() && !this.attachments.length;\n }\n\n private _text = \"\";\n\n get text() {\n return this._text;\n }\n\n private _role: MessageRole = \"user\";\n\n get role() {\n return this._role;\n }\n\n private _runConfig: RunConfig = {};\n\n get runConfig() {\n return this._runConfig;\n }\n\n private _quote: QuoteInfo | undefined = undefined;\n\n get quote() {\n return this._quote;\n }\n\n public setQuote(quote: QuoteInfo | undefined) {\n if (this._quote === quote) return;\n\n this._quote = quote;\n this._notifySubscribers();\n }\n\n public setText(value: string) {\n if (this._text === value) return;\n\n this._text = value;\n if (this._dictation) {\n this._dictationBaseText = value;\n this._currentInterimText = \"\";\n const { status, inputDisabled } = this._dictation;\n this._dictation = inputDisabled ? { status, inputDisabled } : { status };\n }\n this._notifySubscribers();\n }\n\n public setRole(role: MessageRole) {\n if (this._role === role) return;\n\n this._role = role;\n this._notifySubscribers();\n }\n\n public setRunConfig(runConfig: RunConfig) {\n if (this._runConfig === runConfig) return;\n\n this._runConfig = runConfig;\n this._notifySubscribers();\n }\n\n protected _isSending = false;\n private _removedDuringSend = new Set<string>();\n private _sendGeneration = 0;\n private _attachmentAddOperations = new Set<AttachmentAddOperation>();\n\n private _cancelAttachmentAdd(attachmentId: string) {\n for (const operation of [...this._attachmentAddOperations]) {\n if (!operation.attachmentIds.has(attachmentId)) continue;\n operation.cancelled = true;\n this._attachmentAddOperations.delete(operation);\n }\n }\n\n private _cancelAllAttachmentAdds() {\n for (const operation of this._attachmentAddOperations) {\n operation.cancelled = true;\n }\n this._attachmentAddOperations.clear();\n }\n\n private _emptyTextAndAttachments() {\n this._attachments = [];\n this._text = \"\";\n this._notifySubscribers();\n }\n\n private async _onClearAttachments() {\n const adapter = this.getAttachmentAdapter();\n if (adapter) {\n const pending = this._attachments.filter((a) => !isAttachmentComplete(a));\n await Promise.all(pending.map((a) => adapter.remove(a)));\n }\n }\n\n public async reset() {\n this._cancelAllAttachmentAdds();\n\n // A send whose adapter never settles must not brick the composer; reset is\n // the escape hatch that releases the in-flight lock. Bumping the generation\n // invalidates that send entirely so a late-settling upload can neither\n // append the discarded draft nor touch a newer send's lock.\n this._sendGeneration++;\n this._isSending = false;\n this._removedDuringSend.clear();\n\n if (\n this._attachments.length === 0 &&\n this._text === \"\" &&\n this._role === \"user\" &&\n Object.keys(this._runConfig).length === 0 &&\n this._quote === undefined\n ) {\n return;\n }\n\n this._role = \"user\";\n this._runConfig = {};\n this._quote = undefined;\n\n const task = this._onClearAttachments();\n this._emptyTextAndAttachments();\n await task;\n }\n\n public async clearAttachments() {\n this._cancelAllAttachmentAdds();\n const task = this._onClearAttachments();\n this.setAttachments([]);\n\n await task;\n }\n\n public async send(options?: SendOptions) {\n if (!this.canSend || this._isSending) return;\n\n if (this._dictationSession) {\n this._dictationSession.cancel();\n this._cleanupDictation();\n }\n\n const adapter = this.getAttachmentAdapter();\n const attachmentTasks = this.attachments.map(async (a) => {\n if (isAttachmentComplete(a)) return a;\n if (!adapter) throw new Error(\"Attachments are not supported\");\n const result = await adapter.send(a);\n return result as CompleteAttachment;\n });\n\n const originalAttachments = this.attachments;\n const text = this.text;\n const quote = this._quote;\n this._quote = undefined;\n this._text = \"\";\n this._isSending = true;\n const generation = ++this._sendGeneration;\n this._notifySubscribers();\n\n let resolvedAttachments: CompleteAttachment[];\n try {\n resolvedAttachments = await Promise.all(attachmentTasks);\n } catch (e) {\n if (generation === this._sendGeneration) {\n if (!this.text.trim() && this._quote === undefined) {\n this._text = text;\n this._quote = quote;\n this._notifySubscribers();\n }\n // Promise.all rejects on the first failure, but sibling uploads from\n // this batch keep running; the send rejects immediately while the\n // retry lock is held until they settle, or a retry could re-send\n // attachments that are still in flight.\n void Promise.allSettled(attachmentTasks).then(() => {\n if (generation !== this._sendGeneration) return;\n this._removedDuringSend.clear();\n this._isSending = false;\n this._notifySubscribers();\n });\n }\n throw e;\n }\n\n // A reset during the upload discarded this send's draft; the settled\n // uploads must not append it or touch the lock a newer send may own.\n if (generation !== this._sendGeneration) return;\n\n // Drop by id, not wholesale: the user may have added or removed chips while\n // the upload was in flight.\n const sentIds = new Set(originalAttachments.map((a) => a.id));\n this._attachments = this._attachments.filter((a) => !sentIds.has(a.id));\n this._isSending = false;\n this._notifySubscribers();\n\n // An attachment removed mid-upload can't be cancelled, but it can still be\n // dropped from the outgoing message instead of silently being sent anyway.\n const finalAttachments = resolvedAttachments.filter(\n (a) => !this._removedDuringSend.has(a.id),\n );\n this._removedDuringSend.clear();\n\n const message: Omit<AppendMessage, \"parentId\" | \"sourceId\"> = {\n createdAt: new Date(),\n role: this.role,\n content: text ? [{ type: \"text\", text }] : [],\n attachments: finalAttachments,\n runConfig: this.runConfig,\n metadata: { custom: { ...(quote ? { quote } : {}) } },\n };\n\n const sendTask = this.handleSend(message, options);\n if (sendTask) void sendTask.catch(() => {});\n this._notifyEventSubscribers(\"send\", {});\n }\n\n public cancel() {\n this.handleCancel();\n }\n\n public get queue(): readonly QueueItemState[] {\n return EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(_queueItemId: string): void {}\n public removeQueueItem(_queueItemId: string): void {}\n\n protected abstract handleSend(\n message: Omit<AppendMessage, \"parentId\" | \"sourceId\">,\n options?: SendOptions,\n ): void | Promise<void>;\n protected abstract handleCancel(): void;\n\n async addAttachment(fileOrAttachment: File | CreateAttachment) {\n if (isCreateAttachment(fileOrAttachment)) {\n const adapter = this.getAttachmentAdapter();\n if (\n adapter &&\n !fileMatchesAccept(\n {\n name: fileOrAttachment.name,\n type: fileOrAttachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.contentType || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\n \"not-accepted\",\n message,\n undefined,\n err,\n );\n throw err;\n }\n\n const a: CompleteAttachment = {\n id: fileOrAttachment.id ?? generateId(),\n type: fileOrAttachment.type ?? \"document\",\n name: fileOrAttachment.name,\n contentType: fileOrAttachment.contentType,\n content: fileOrAttachment.content,\n status: { type: \"complete\" },\n };\n this._attachments = [...this._attachments, a];\n this._notifySubscribers();\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n return;\n }\n\n const adapter = this.getAttachmentAdapter();\n if (!adapter) {\n const message = \"Attachments are not supported\";\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"no-adapter\", message, undefined, err);\n throw err;\n }\n\n if (\n !fileMatchesAccept(\n { name: fileOrAttachment.name, type: fileOrAttachment.type },\n adapter.accept,\n )\n ) {\n const message = `File type ${fileOrAttachment.type || \"unknown\"} is not accepted. Accepted types: ${adapter.accept}`;\n const err = new Error(message);\n this._safeEmitAttachmentAddError(\"not-accepted\", message, undefined, err);\n throw err;\n }\n\n const operation: AttachmentAddOperation = {\n cancelled: false,\n attachmentIds: new Set(),\n };\n const operations = this._attachmentAddOperations;\n operations.add(operation);\n const upsertAttachment = (a: PendingAttachment) => {\n if (operation.cancelled) return false;\n\n operation.attachmentIds.add(a.id);\n const idx = this._attachments.findIndex(\n (attachment) => attachment.id === a.id,\n );\n if (idx !== -1)\n this._attachments = [\n ...this._attachments.slice(0, idx),\n a,\n ...this._attachments.slice(idx + 1),\n ];\n else {\n this._attachments = [...this._attachments, a];\n }\n\n this._notifySubscribers();\n return true;\n };\n let lastAttachment: PendingAttachment | undefined;\n try {\n const promiseOrGenerator = adapter.add({ file: fileOrAttachment });\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n lastAttachment = r;\n if (!upsertAttachment(r)) break;\n }\n } else {\n lastAttachment = await promiseOrGenerator;\n upsertAttachment(lastAttachment);\n }\n } catch (e) {\n if (operation.cancelled) return;\n if (lastAttachment) {\n upsertAttachment({\n ...lastAttachment,\n status: {\n type: \"incomplete\",\n reason: \"error\",\n message: e instanceof Error ? e.message : String(e),\n },\n });\n }\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n e instanceof Error ? e.message : String(e),\n lastAttachment?.id,\n e instanceof Error ? e : undefined,\n );\n throw e;\n } finally {\n operations.delete(operation);\n }\n\n if (operation.cancelled) return;\n if (\n lastAttachment?.status.type === \"incomplete\" &&\n lastAttachment.status.reason === \"error\"\n ) {\n this._safeEmitAttachmentAddError(\n \"adapter-error\",\n lastAttachment.status.message ??\n \"Attachment upload did not complete successfully.\",\n lastAttachment.id,\n );\n } else {\n this._notifyEventSubscribers(\"attachmentAdd\", {});\n }\n }\n\n private _safeEmitAttachmentAddError(\n reason: AttachmentAddErrorReason,\n message: string,\n attachmentId?: string,\n error?: Error,\n ) {\n try {\n this._notifyEventSubscribers(\"attachmentAddError\", {\n reason,\n message,\n ...(attachmentId !== undefined && { attachmentId }),\n ...(error !== undefined && { error }),\n });\n } catch (subscriberError) {\n console.error(\n \"[assistant-ui] attachmentAddError subscriber threw:\",\n subscriberError,\n );\n }\n }\n\n async removeAttachment(attachmentId: string) {\n const index = this._attachments.findIndex((a) => a.id === attachmentId);\n if (index === -1) throw new Error(\"Attachment not found\");\n const attachment = this._attachments[index]!;\n\n this._cancelAttachmentAdd(attachmentId);\n\n // A send in flight may already be uploading this attachment; the upload\n // can't be cancelled, so mark it to be dropped from the outgoing message\n // before any await gives the upload a chance to settle first.\n if (this._isSending) this._removedDuringSend.add(attachmentId);\n\n if (!isAttachmentComplete(attachment)) {\n const adapter = this.getAttachmentAdapter();\n if (!adapter) throw new Error(\"Attachments are not supported\");\n try {\n await adapter.remove(attachment);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n this._attachments = this._attachments.map((candidate) =>\n candidate.id === attachmentId && !isAttachmentComplete(candidate)\n ? {\n ...candidate,\n status: { type: \"incomplete\", reason: \"error\", message },\n }\n : candidate,\n );\n this._notifySubscribers();\n throw error;\n }\n }\n this._attachments = this._attachments.filter((a) => a.id !== attachmentId);\n this._notifySubscribers();\n }\n\n private _dictation: DictationState | undefined;\n private _dictationSession: DictationAdapter.Session | undefined;\n private _dictationUnsubscribes: Unsubscribe[] = [];\n private _dictationBaseText = \"\";\n private _currentInterimText = \"\";\n private _dictationSessionIdCounter = 0;\n private _activeDictationSessionId: number | undefined;\n private _isCleaningDictation = false;\n\n public get dictation(): DictationState | undefined {\n return this._dictation;\n }\n\n private _isActiveSession(\n sessionId: number,\n session: DictationAdapter.Session,\n ): boolean {\n return (\n this._activeDictationSessionId === sessionId &&\n this._dictationSession === session\n );\n }\n\n public startDictation(): void {\n const adapter = this.getDictationAdapter();\n if (!adapter) {\n throw new Error(\"Dictation adapter not configured\");\n }\n\n if (this._dictationSession) {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n const oldSession = this._dictationSession;\n oldSession.stop().catch(() => {});\n this._dictationSession = undefined;\n }\n\n const inputDisabled = adapter.disableInputDuringDictation ?? false;\n\n this._dictationBaseText = this._text;\n this._currentInterimText = \"\";\n\n const session = adapter.listen();\n this._dictationSession = session;\n const sessionId = ++this._dictationSessionIdCounter;\n this._activeDictationSessionId = sessionId;\n this._dictation = { status: session.status, inputDisabled };\n this._notifySubscribers();\n\n const unsubSpeech = session.onSpeech((result) => {\n if (!this._isActiveSession(sessionId, session)) return;\n const isFinal = result.isFinal !== false;\n\n const needsSeparator =\n this._dictationBaseText &&\n !this._dictationBaseText.endsWith(\" \") &&\n result.transcript;\n const separator = needsSeparator ? \" \" : \"\";\n\n if (isFinal) {\n this._dictationBaseText =\n this._dictationBaseText + separator + result.transcript;\n this._currentInterimText = \"\";\n this._text = this._dictationBaseText;\n\n if (this._dictation) {\n const { transcript: _, ...rest } = this._dictation;\n this._dictation = rest;\n }\n this._notifySubscribers();\n } else {\n this._currentInterimText = separator + result.transcript;\n this._text = this._dictationBaseText + this._currentInterimText;\n\n if (this._dictation) {\n this._dictation = {\n ...this._dictation,\n transcript: result.transcript,\n };\n }\n this._notifySubscribers();\n }\n });\n this._dictationUnsubscribes.push(unsubSpeech);\n\n const unsubStart = session.onSpeechStart(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n this._dictation = {\n status: { type: \"running\" },\n inputDisabled,\n ...(this._dictation?.transcript && {\n transcript: this._dictation.transcript,\n }),\n };\n this._notifySubscribers();\n });\n this._dictationUnsubscribes.push(unsubStart);\n\n const unsubEnd = session.onSpeechEnd(() => {\n this._cleanupDictation({ sessionId });\n });\n this._dictationUnsubscribes.push(unsubEnd);\n\n const statusInterval = setInterval(() => {\n if (!this._isActiveSession(sessionId, session)) return;\n\n if (session.status.type === \"ended\") {\n this._cleanupDictation({ sessionId });\n }\n }, 100);\n this._dictationUnsubscribes.push(() => clearInterval(statusInterval));\n }\n\n public stopDictation(): void {\n if (!this._dictationSession) return;\n\n const session = this._dictationSession;\n const sessionId = this._activeDictationSessionId;\n session.stop().finally(() => {\n this._cleanupDictation({ sessionId });\n });\n }\n\n private _cleanupDictation(options?: { sessionId: number | undefined }): void {\n const isStaleSession =\n options?.sessionId !== undefined &&\n options.sessionId !== this._activeDictationSessionId;\n if (isStaleSession || this._isCleaningDictation) return;\n\n this._isCleaningDictation = true;\n try {\n for (const unsub of this._dictationUnsubscribes) {\n unsub();\n }\n this._dictationUnsubscribes = [];\n this._dictationSession = undefined;\n this._activeDictationSessionId = undefined;\n this._dictation = undefined;\n this._dictationBaseText = \"\";\n this._currentInterimText = \"\";\n this._notifySubscribers();\n } finally {\n this._isCleaningDictation = false;\n }\n }\n\n private _eventSubscribers = new Map<\n ComposerRuntimeEventType,\n Set<(payload?: unknown) => void>\n >();\n\n protected _notifyEventSubscribers<E extends ComposerRuntimeEventType>(\n event: E,\n payload: ComposerRuntimeEventPayload[E],\n ) {\n const subscribers = this._eventSubscribers.get(event);\n if (!subscribers) return;\n\n notifyEventListeners(subscribers, payload, `Composer runtime \"${event}\"`);\n }\n\n public unstable_on<E extends ComposerRuntimeEventType>(\n event: E,\n callback: ComposerRuntimeEventCallback<E>,\n ) {\n const wrapped = callback as (payload?: unknown) => void;\n let subscribers = this._eventSubscribers.get(event);\n if (!subscribers) {\n subscribers = new Set();\n this._eventSubscribers.set(event, subscribers);\n }\n subscribers.add(wrapped);\n\n return () => {\n this._eventSubscribers.get(event)?.delete(wrapped);\n };\n }\n}\n"],"mappings":";;;;;;;AAiCA,MAAMyB,wBAAwBC,MAC5BA,EAAEC,OAAOC,SAAS;AAOpB,IAAsBK,0BAAtB,cACUvB,iBAE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AE6D,UAAU,CAAC;EACtC,CAAC;CACH;CAEA,kBAA0BhE,SAAmD;EAI3E,IAFEA,SAASgE,cAAcpG,KAAAA,KACvBoC,QAAQgE,cAAc,KAAKJ,6BACP,KAAKC,sBAAsB;EAEjD,KAAKA,uBAAuB;EAC5B,IAAI;GACF,KAAK,MAAMM,SAAS,KAAKT,wBACvBS,MAAM;GAER,KAAKT,yBAAyB,CAAA;GAC9B,KAAKzD,oBAAoBrC,KAAAA;GACzB,KAAKgG,4BAA4BhG,KAAAA;GACjC,KAAKI,aAAaJ,KAAAA;GAClB,KAAKK,qBAAqB;GAC1B,KAAKC,sBAAsB;GAC3B,KAAKnB,mBAAmB;EAC1B,UAAU;GACR,KAAK8G,uBAAuB;EAC9B;CACF;CAEA,oCAA4B,IAAIgC,IAG9B;CAEF,wBACEE,OACAD,SACA;EACA,MAAMG,cAAc,KAAKL,kBAAkBM,IAAIH,KAAK;EACpD,IAAI,CAACE,aAAa;EAElB5K,qBAAqB4K,aAAaH,SAAS,qBAAqBC,MAAK,EAAG;CAC1E;CAEA,YACEA,OACAK,UACA;EACA,MAAMC,UAAUD;EAChB,IAAIH,cAAc,KAAKL,kBAAkBM,IAAIH,KAAK;EAClD,IAAI,CAACE,aAAa;GAChBA,8BAAc,IAAIpK,IAAI;GACtB,KAAK+J,kBAAkBU,IAAIP,OAAOE,WAAW;EAC/C;EACAA,YAAY5D,IAAIgE,OAAO;EAEvB,aAAa;GACX,KAAKT,kBAAkBM,IAAIH,KAAK,CAAC,EAAEjH,OAAOuH,OAAO;EACnD;CACF;AACF"}
|
|
@@ -23,6 +23,15 @@ type ThreadListRuntimeCore = {
|
|
|
23
23
|
readonly threadItems: Readonly<Record<string, ThreadListItemCoreState>>;
|
|
24
24
|
getMainThreadRuntimeCore(): ThreadRuntimeCore;
|
|
25
25
|
getThreadRuntimeCore(threadId: string): ThreadRuntimeCore;
|
|
26
|
+
/**
|
|
27
|
+
* Whether the thread currently has a run in progress, including a run on a
|
|
28
|
+
* thread that is not the main one. Implemented by thread lists that keep
|
|
29
|
+
* runtimes alive for non-main threads, and they notify their subscribers
|
|
30
|
+
* whenever the answer changes. A thread list that mounts only the main thread
|
|
31
|
+
* leaves this undefined: its other threads have no runtime and so cannot be
|
|
32
|
+
* running, and the main thread's run state is read from its runtime directly.
|
|
33
|
+
*/
|
|
34
|
+
unstable_isThreadRunning?(threadId: string): boolean;
|
|
26
35
|
getItemById(threadId: string): ThreadListItemCoreState | undefined;
|
|
27
36
|
switchToThread(threadId: string, options?: {
|
|
28
37
|
unarchive?: boolean;
|
|
@@ -30,6 +39,7 @@ type ThreadListRuntimeCore = {
|
|
|
30
39
|
switchToNewThread(): Promise<void>;
|
|
31
40
|
getLoadThreadsPromise(): Promise<void>;
|
|
32
41
|
reload?(): Promise<void>;
|
|
42
|
+
reloadMainThread?(): Promise<void>;
|
|
33
43
|
loadMore?(): Promise<void>;
|
|
34
44
|
detach(threadId: string): Promise<void>;
|
|
35
45
|
rename(threadId: string, newTitle: string): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-list-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/interfaces/thread-list-runtime-core.ts"],"mappings":";;;KAGY;KAEA;WACD;WACA;WACA;WAEA,QAAQ;WACR;WACA,gBAAgB;WAChB,SAAS;WAET,UAAU;;KAGT;WACD;WACA;WACA;EACT;EACA;EAEA;EACA;WAES,aAAa,SAAS,eAAe;EAE9C,4BAA4B;EAC5B,qBAAqB,mBAAmB;
|
|
1
|
+
{"version":3,"file":"thread-list-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/interfaces/thread-list-runtime-core.ts"],"mappings":";;;KAGY;KAEA;WACD;WACA;WACA;WAEA,QAAQ;WACR;WACA,gBAAgB;WAChB,SAAS;WAET,UAAU;;KAGT;WACD;WACA;WACA;EACT;EACA;EAEA;EACA;WAES,aAAa,SAAS,eAAe;EAE9C,4BAA4B;EAC5B,qBAAqB,mBAAmB;;;;;;;;;EAUxC,0BAA0B;EAE1B,YAAY,mBAAmB;EAE/B,eACE,kBACA;IAAY;MACX;EACH,qBAAqB;EAErB,yBAAyB;EACzB,WAAW;EACX,qBAAqB;EACrB,aAAa;EAEb,OAAO,mBAAmB;EAC1B,OAAO,kBAAkB,mBAAmB;EAC5C,cACE,kBACA,QAAQ,sCACP;EACH,QAAQ,mBAAmB;EAC3B,UAAU,mBAAmB;EAC7B,OAAO,mBAAmB;EAE1B,WACE,mBACC;IAAU;IAAkB;;EAC/B,cAAc,mBAAmB;EAEjC,UAAU,uBAAuB"}
|
|
@@ -16,6 +16,8 @@ type RuntimeCapabilities = {
|
|
|
16
16
|
readonly switchBranchDuringRun: boolean;
|
|
17
17
|
readonly edit: boolean;
|
|
18
18
|
readonly reload: boolean;
|
|
19
|
+
/** Whether the runtime can refetch this thread's remote state in place. */
|
|
20
|
+
readonly refetchThread: boolean;
|
|
19
21
|
readonly delete: boolean;
|
|
20
22
|
readonly cancel: boolean;
|
|
21
23
|
readonly unstable_copy: boolean;
|
|
@@ -171,6 +173,18 @@ type ThreadRuntimeCore = Readonly<{
|
|
|
171
173
|
exportExternalState(): any;
|
|
172
174
|
importExternalState(state: any): void;
|
|
173
175
|
reset(initialMessages?: readonly ThreadMessageLike[]): void;
|
|
176
|
+
/**
|
|
177
|
+
* Re-fetches this thread's state from its backing store, in place: no
|
|
178
|
+
* runtime-hook remount, so runtime identity and composer drafts survive.
|
|
179
|
+
* Presence signals the capability to `threads.reloadMainThread()`, which
|
|
180
|
+
* calls this and propagates its rejection. It does not touch a run in
|
|
181
|
+
* progress first, because stopping one is `cancelRun`, whose contract is
|
|
182
|
+
* that the user abandoned a send: it returns the trailing user message to
|
|
183
|
+
* the composer. An implementation is therefore responsible for whatever
|
|
184
|
+
* coordination a concurrent run needs. Runtimes without remote state leave
|
|
185
|
+
* it undefined.
|
|
186
|
+
*/
|
|
187
|
+
unstable_refetchThread?: (() => Promise<void>) | undefined;
|
|
174
188
|
/**
|
|
175
189
|
* @deprecated This API is still under active development and might change without notice.
|
|
176
190
|
* For state-derivable transitions, prefer `subscribe` + `getState`. This channel is the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/interfaces/thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;KAoBY;WACD;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;KAGC;EACV;EACA;EACA;EACA,QAAQ;EACR;EACA,WAAW;;;;;;;EAOX,wBAAwB;;KAGd;EACV;EACA;;KAGU;EACV;EACA;;EAEA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;;KAGU;WACD;WACA,QAAQ,uBAAuB;;KAG9B;WACD,QAAQ,qBAAqB;WAC7B;WACA,MAAM,qBAAqB;;KAG1B;WACD;;KAGC;;;;;;;EAOV,UAAU;;;;;;;EAOV,QAAQ;;;;;;;;;EASR,YAAY;;;;;EAKZ,oBAAoB;;KAGV,+BAA+B;KAE/B,2BAA2B,UAAU,2BAC/C,SAAS,0BAA0B;KAGzB;EACV;EACA;EACA,WAAW;;KAGD,kBAAkB;EAC5B,UACE,SAAS,wBACN,eAAe;;KAGV,oBAAoB;EAC9B,iBAAiB;IAEX;IACA,SAAS;IACT;;EAIN,cAAc;EACd,iBAAiB;EAEjB,SAAS,SAAS;EAClB,gBAAgB,6BAA6B;EAC7C,WAAW,QAAQ;EACnB,YAAY,QAAQ;EACpB;EAEA,gBAAgB,SAAS;EACzB,iBAAiB,SAAS;EAC1B,wBAAwB,SAAS;EAEjC,QAAQ;EACR;EAEA;EACA;EACA;EACA;EAEA,iBAAiB,UAAU;EAE3B,uBAAuB;EAEvB,UAAU;EACV,kBAAkB,sBAAsB;EACxC,YAAY;EAEZ,+BAA+B;EAC/B,kBAAkB;EAClB,mBAAmB;EAEnB,QAAQ;EACR,OAAO;EAEP,cAAc,SAAS;EACvB;;;;;;EAMA;EACA;;;;;;;EAOA;EACA,mBAAmB;EACnB,OAAO;EACP,sBAAsB;EAEtB;EAEA,YAAY,yBAAyB;EAErC;EACA,uBAAuB,yBAAyB;EAEhD,OAAO,YAAY;EACnB,UAAU;EAEV;EACA,oBAAoB;EAEpB,MAAM,2BAA2B;;;;;;
|
|
1
|
+
{"version":3,"file":"thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/interfaces/thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;KAoBY;WACD;WACA;WACA;WACA;;WAEA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;WACA;;KAGC;EACV;EACA;EACA;EACA,QAAQ;EACR;EACA,WAAW;;;;;;;EAOX,wBAAwB;;KAGd;EACV;EACA;;KAGU;EACV;EACA;;EAEA;EACA;;KAGU;EACV;EACA;;KAGU;EACV;;KAGU;WACD;WACA,QAAQ,uBAAuB;;KAG9B;WACD,QAAQ,qBAAqB;WAC7B;WACA,MAAM,qBAAqB;;KAG1B;WACD;;KAGC;;;;;;;EAOV,UAAU;;;;;;;EAOV,QAAQ;;;;;;;;;EASR,YAAY;;;;;EAKZ,oBAAoB;;KAGV,+BAA+B;KAE/B,2BAA2B,UAAU,2BAC/C,SAAS,0BAA0B;KAGzB;EACV;EACA;EACA,WAAW;;KAGD,kBAAkB;EAC5B,UACE,SAAS,wBACN,eAAe;;KAGV,oBAAoB;EAC9B,iBAAiB;IAEX;IACA,SAAS;IACT;;EAIN,cAAc;EACd,iBAAiB;EAEjB,SAAS,SAAS;EAClB,gBAAgB,6BAA6B;EAC7C,WAAW,QAAQ;EACnB,YAAY,QAAQ;EACpB;EAEA,gBAAgB,SAAS;EACzB,iBAAiB,SAAS;EAC1B,wBAAwB,SAAS;EAEjC,QAAQ;EACR;EAEA;EACA;EACA;EACA;EAEA,iBAAiB,UAAU;EAE3B,uBAAuB;EAEvB,UAAU;EACV,kBAAkB,sBAAsB;EACxC,YAAY;EAEZ,+BAA+B;EAC/B,kBAAkB;EAClB,mBAAmB;EAEnB,QAAQ;EACR,OAAO;EAEP,cAAc,SAAS;EACvB;;;;;;EAMA;EACA;;;;;;;EAOA;EACA,mBAAmB;EACnB,OAAO;EACP,sBAAsB;EAEtB;EAEA,YAAY,yBAAyB;EAErC;EACA,uBAAuB,yBAAyB;EAEhD,OAAO,YAAY;EACnB,UAAU;EAEV;EACA,oBAAoB;EAEpB,MAAM,2BAA2B;;;;;;;;;;;;EAajC,gCAAgC;;;;;;EAOhC,YAAY,UAAU,wBACpB,OAAO,GACP,UAAU,2BAA2B,KACpC"}
|
|
@@ -113,6 +113,15 @@ type ExternalStoreAdapterBase<T> = {
|
|
|
113
113
|
onReload?: ((parentId: string | null, config: StartRunConfig) => Promise<void>) | undefined;
|
|
114
114
|
onResume?: ((config: ResumeRunConfig) => Promise<void>) | undefined;
|
|
115
115
|
onCancel?: (() => Promise<void>) | undefined;
|
|
116
|
+
/**
|
|
117
|
+
* Re-fetches the thread's state from the backing store, in place; a
|
|
118
|
+
* rejection reaches the `threads.reloadMainThread()` caller. Unrelated to
|
|
119
|
+
* `onReload`, which re-generates an assistant message.
|
|
120
|
+
*
|
|
121
|
+
* The caller does not stop a run in progress first, so an adapter that can
|
|
122
|
+
* stream owns whatever coordination one needs.
|
|
123
|
+
*/
|
|
124
|
+
onRefetchThread?: (() => Promise<void>) | undefined;
|
|
116
125
|
onAddToolResult?: ((options: AddToolResultOptions) => Promise<void> | void) | undefined;
|
|
117
126
|
onResumeToolCall?: ((options: {
|
|
118
127
|
toolCallId: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-adapter.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-adapter.ts"],"mappings":";;;;;;;;;;;;KAqBY,wBAAwB;EAClC,QAAQ;EACR;EACA;EACA;EACA;EACA,SAAS;;KAGC;;;;EAIV;EACA;EACA,mBAAmB;EACnB,2BAA2B;;;;EAI3B,6BAA6B;;;;EAI7B,qBAAqB,qBAAqB;EAC1C,YACE,kBACA,sBACI;EACN,mBAEM,kBACA,QAAQ,wCACL;EAET,cAAc,qBAAqB;EACnC,gBAAgB,qBAAqB;EACrC,aAAa,qBAAqB;;KAGxB,8BAA8B,MACxC,SAAS,GACT,gBACG;;;;KAKO;EACV;EACA;;KAGG,qCAAqC;EACxC,gBAAgB,8BAA8B;;KAG3C,yBAAyB;;;;;;;EAO5B;;;;;;;;;EASA;;;;;;;;;EASA;EACA;EACA,oBAAoB;EACpB,oBAAoB;EACpB,uBAAuB;EACvB,QAAQ;EACR;EAEA,gBAAgB,mBAAmB;;;;;;;;;;;;;;;;;;EAkBnC,4BACM,OAAO;EAEb,aAAa,mBAAmB;EAChC;EACA,wBAAwB;EACxB,QAAQ,SAAS,kBAAkB;;EAEnC,QAAQ;EACR,WAAW,SAAS,kBAAkB;EACtC,aAAa,sBAAsB;EACnC,aACM,yBAAyB,QAAQ,mBAAmB;EAE1D,aAAa,QAAQ,oBAAoB;EACzC,kBAAkB;
|
|
1
|
+
{"version":3,"file":"external-store-adapter.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-adapter.ts"],"mappings":";;;;;;;;;;;;KAqBY,wBAAwB;EAClC,QAAQ;EACR;EACA;EACA;EACA;EACA,SAAS;;KAGC;;;;EAIV;EACA;EACA,mBAAmB;EACnB,2BAA2B;;;;EAI3B,6BAA6B;;;;EAI7B,qBAAqB,qBAAqB;EAC1C,YACE,kBACA,sBACI;EACN,mBAEM,kBACA,QAAQ,wCACL;EAET,cAAc,qBAAqB;EACnC,gBAAgB,qBAAqB;EACrC,aAAa,qBAAqB;;KAGxB,8BAA8B,MACxC,SAAS,GACT,gBACG;;;;KAKO;EACV;EACA;;KAGG,qCAAqC;EACxC,gBAAgB,8BAA8B;;KAG3C,yBAAyB;;;;;;;EAO5B;;;;;;;;;EASA;;;;;;;;;EASA;EACA;EACA,oBAAoB;EACpB,oBAAoB;EACpB,uBAAuB;EACvB,QAAQ;EACR;EAEA,gBAAgB,mBAAmB;;;;;;;;;;;;;;;;;;EAkBnC,4BACM,OAAO;EAEb,aAAa,mBAAmB;EAChC;EACA,wBAAwB;EACxB,QAAQ,SAAS,kBAAkB;;EAEnC,QAAQ;EACR,WAAW,SAAS,kBAAkB;EACtC,aAAa,sBAAsB;EACnC,aACM,yBAAyB,QAAQ,mBAAmB;EAE1D,aAAa,QAAQ,oBAAoB;EACzC,kBAAkB;;;;;;;;;EASlB,yBAAyB;EACzB,oBACM,SAAS,yBAAyB;EAExC,qBACM;IAAW;IAAoB;;EAErC,4BACM,SAAS,iCAAiC;EAEhD,iBAAiB,8BAA8B;EAC/C;IAEM,cAAc;IACd,SAAS;IACT,YAAY;IACZ,QAAQ;IACR,WAAW;;;;IAIX,aAAa;;EAGnB;IAEM;;;;;;;;;;;;;;;;;;;;;EAsBN;;;;;;;;;;EAUA,oBACM,UAAU,eAAe;;KAIrB,qBAAqB,IAAI,iBACnC,yBAAyB,MACtB,UAAU,yBAEP,qCAAqC"}
|
|
@@ -24,6 +24,7 @@ declare class ExternalStoreThreadListRuntimeCore implements ThreadListRuntimeCor
|
|
|
24
24
|
getThreadRuntimeCore(): never;
|
|
25
25
|
getItemById(threadId: string): ThreadListItemCoreState | undefined;
|
|
26
26
|
__internal_setAdapter(adapter: ExternalStoreThreadListAdapter, initialLoad?: boolean): void;
|
|
27
|
+
reloadMainThread(): Promise<void>;
|
|
27
28
|
switchToThread(threadId: string, _options?: {
|
|
28
29
|
unarchive?: boolean;
|
|
29
30
|
}): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-list-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"mappings":";;;;;KAQY,mCAAmC;cAgBlC,8CAA8C;UACjD;UACA;UACA;UACA;UAEA;MAEG;MAIA;MAIA;MAIA;MAIA,eAAW,SAAA,eAAA;EAIf,yBAAqB;UAIpB;MAEG;UAIH;EAGN,YAAA,SAAS,4CACT,eAAe;EAMV,4BAAwB;EAIxB;EAIA,YAAY,mBAAgB;EAI5B,sBACL,SAAS,gCACT;EAqFW,eACX,kBACA;IAAa;MACZ;EAUU,qBAAqB;EAUrB,OAAO,kBAAkB,mBAAmB;EAQ5C,aACX,kBACA,QAAQ,sCACP;EAUU,UAAU;EAIV,QAAQ,mBAAmB;EAQ3B,UAAU,mBAAmB;EAQ7B,OAAO,mBAAmB;EAQhC,WACL,mBACC;IAAU;IAAkB;;EAIxB;UAIC;EAED,UAAU,uBAAuB;UAKhC"}
|
|
1
|
+
{"version":3,"file":"external-store-thread-list-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"mappings":";;;;;KAQY,mCAAmC;cAgBlC,8CAA8C;UACjD;UACA;UACA;UACA;UAEA;MAEG;MAIA;MAIA;MAIA;MAIA,eAAW,SAAA,eAAA;EAIf,yBAAqB;UAIpB;MAEG;UAIH;EAGN,YAAA,SAAS,4CACT,eAAe;EAMV,4BAAwB;EAIxB;EAIA,YAAY,mBAAgB;EAI5B,sBACL,SAAS,gCACT;EAqFW,oBAAoB;EASpB,eACX,kBACA;IAAa;MACZ;EAUU,qBAAqB;EAUrB,OAAO,kBAAkB,mBAAmB;EAQ5C,aACX,kBACA,QAAQ,sCACP;EAUU,UAAU;EAIV,QAAQ,mBAAmB;EAQ3B,UAAU,mBAAmB;EAQ7B,OAAO,mBAAmB;EAQhC,WACL,mBACC;IAAU;IAAkB;;EAIxB;UAIC;EAED,UAAU,uBAAuB;UAKhC"}
|
|
@@ -92,6 +92,10 @@ var ExternalStoreThreadListRuntimeCore = class {
|
|
|
92
92
|
};
|
|
93
93
|
this._notifySubscribers();
|
|
94
94
|
}
|
|
95
|
+
async reloadMainThread() {
|
|
96
|
+
if (!this._mainThread.unstable_refetchThread) return;
|
|
97
|
+
await this._mainThread.unstable_refetchThread();
|
|
98
|
+
}
|
|
95
99
|
async switchToThread(threadId, _options) {
|
|
96
100
|
if (this._mainThreadId === threadId) return;
|
|
97
101
|
const onSwitchToThread = this.adapter.onSwitchToThread;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-list-runtime-core.js","names":["Unsubscribe","ExternalStoreThreadRuntimeCore","ThreadListItemCoreState","ThreadListRuntimeCore","ExternalStoreThreadListAdapter","ExternalStoreThreadFactory","EMPTY_ARRAY","Object","freeze","DEFAULT_THREAD_ID","DEFAULT_THREADS","DEFAULT_THREAD","id","remoteId","undefined","externalId","status","RESOLVED_PROMISE","Promise","resolve","DEFAULT_THREAD_DATA","ExternalStoreThreadListRuntimeCore","_mainThreadId","_threads","_archivedThreads","_threadData","Readonly","Record","adapter","isLoading","newThreadId","threadIds","archivedThreadIds","threadItems","getLoadThreadsPromise","_mainThread","mainThreadId","threadFactory","constructor","__internal_setAdapter","getMainThreadRuntimeCore","getThreadRuntimeCore","Error","getItemById","threadId","initialLoad","previousAdapter","newThreads","threads","newArchivedThreads","archivedThreads","previousThreadId","previousThreads","previousArchivedThreads","fromEntries","map","t","_notifySubscribers","switchToThread","_options","unarchive","onSwitchToThread","switchToNewThread","onSwitchToNewThread","rename","newTitle","onRename","updateCustom","custom","onUpdateCustom","detach","archive","onArchive","onUnarchive","delete","onDelete","initialize","generateTitle","_subscriptions","Set","subscribe","callback","add"],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { ExternalStoreThreadRuntimeCore } from \"./external-store-thread-runtime-core\";\nimport type {\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"../../runtime/interfaces/thread-list-runtime-core\";\nimport type { ExternalStoreThreadListAdapter } from \"./external-store-adapter\";\n\nexport type ExternalStoreThreadFactory = () => ExternalStoreThreadRuntimeCore;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst DEFAULT_THREAD_ID = \"DEFAULT_THREAD_ID\";\nconst DEFAULT_THREADS = Object.freeze([DEFAULT_THREAD_ID]);\nconst DEFAULT_THREAD = Object.freeze({\n id: DEFAULT_THREAD_ID,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n});\nconst RESOLVED_PROMISE = Promise.resolve();\nconst DEFAULT_THREAD_DATA = Object.freeze({\n [DEFAULT_THREAD_ID]: DEFAULT_THREAD,\n});\n\nexport class ExternalStoreThreadListRuntimeCore implements ThreadListRuntimeCore {\n private _mainThreadId: string = DEFAULT_THREAD_ID;\n private _threads: readonly string[] = DEFAULT_THREADS;\n private _archivedThreads: readonly string[] = EMPTY_ARRAY;\n private _threadData: Readonly<Record<string, ThreadListItemCoreState>> =\n DEFAULT_THREAD_DATA;\n private adapter: ExternalStoreThreadListAdapter = {};\n\n public get isLoading() {\n return this.adapter.isLoading ?? false;\n }\n\n public get newThreadId() {\n return undefined;\n }\n\n public get threadIds() {\n return this._threads;\n }\n\n public get archivedThreadIds() {\n return this._archivedThreads;\n }\n\n public get threadItems() {\n return this._threadData;\n }\n\n public getLoadThreadsPromise() {\n return RESOLVED_PROMISE;\n }\n\n private _mainThread!: ExternalStoreThreadRuntimeCore;\n\n public get mainThreadId() {\n return this._mainThreadId;\n }\n\n private threadFactory: ExternalStoreThreadFactory;\n\n constructor(\n adapter: ExternalStoreThreadListAdapter = {},\n threadFactory: ExternalStoreThreadFactory,\n ) {\n this.threadFactory = threadFactory;\n this.__internal_setAdapter(adapter, true);\n }\n\n public getMainThreadRuntimeCore() {\n return this._mainThread;\n }\n\n public getThreadRuntimeCore(): never {\n throw new Error(\"Method not implemented.\");\n }\n\n public getItemById(threadId: string) {\n return this._threadData[threadId];\n }\n\n public __internal_setAdapter(\n adapter: ExternalStoreThreadListAdapter,\n initialLoad = false,\n ) {\n const previousAdapter = this.adapter;\n this.adapter = adapter;\n\n const newThreadId = adapter.threadId ?? DEFAULT_THREAD_ID;\n const newThreads = adapter.threads ?? EMPTY_ARRAY;\n const newArchivedThreads = adapter.archivedThreads ?? EMPTY_ARRAY;\n\n const previousThreadId = previousAdapter.threadId ?? DEFAULT_THREAD_ID;\n const previousThreads = previousAdapter.threads ?? EMPTY_ARRAY;\n const previousArchivedThreads =\n previousAdapter.archivedThreads ?? EMPTY_ARRAY;\n\n if (\n !initialLoad &&\n previousThreadId === newThreadId &&\n previousThreads === newThreads &&\n previousArchivedThreads === newArchivedThreads\n ) {\n return;\n }\n\n if (\n previousThreads !== newThreads ||\n previousArchivedThreads !== newArchivedThreads ||\n previousThreadId !== newThreadId\n ) {\n this._threadData = {\n ...DEFAULT_THREAD_DATA,\n ...Object.fromEntries(\n adapter.threads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"regular\",\n },\n ]) ?? [],\n ),\n ...Object.fromEntries(\n adapter.archivedThreads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"archived\",\n },\n ]) ?? [],\n ),\n };\n }\n\n if (previousThreads !== newThreads) {\n this._threads = this.adapter.threads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n if (previousArchivedThreads !== newArchivedThreads) {\n this._archivedThreads =\n this.adapter.archivedThreads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n // `initialLoad ||`: `_mainThread!` must be assigned on construction.\n if (initialLoad || previousThreadId !== newThreadId) {\n this._mainThreadId = newThreadId;\n this._mainThread = this.threadFactory();\n }\n\n if (!this._threadData[this._mainThreadId]) {\n this._threadData = {\n ...this._threadData,\n [this._mainThreadId]: {\n id: this._mainThreadId,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n },\n };\n }\n\n this._notifySubscribers();\n }\n\n public async switchToThread(\n threadId: string,\n _options?: { unarchive?: boolean },\n ): Promise<void> {\n if (this._mainThreadId === threadId) return;\n const onSwitchToThread = this.adapter.onSwitchToThread;\n if (!onSwitchToThread)\n throw new Error(\n \"External store adapter does not support switching to thread\",\n );\n await onSwitchToThread(threadId);\n }\n\n public async switchToNewThread(): Promise<void> {\n const onSwitchToNewThread = this.adapter.onSwitchToNewThread;\n if (!onSwitchToNewThread)\n throw new Error(\n \"External store adapter does not support switching to new thread\",\n );\n\n await onSwitchToNewThread();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const onRename = this.adapter.onRename;\n if (!onRename)\n throw new Error(\"External store adapter does not support renaming\");\n\n await onRename(threadId, newTitle);\n }\n\n public async updateCustom(\n threadId: string,\n custom: Record<string, unknown> | undefined,\n ): Promise<void> {\n const onUpdateCustom = this.adapter.onUpdateCustom;\n if (!onUpdateCustom)\n throw new Error(\n \"External store adapter does not support updating custom metadata\",\n );\n\n await onUpdateCustom(threadId, custom);\n }\n\n public async detach(): Promise<void> {\n // no-op\n }\n\n public async archive(threadId: string): Promise<void> {\n const onArchive = this.adapter.onArchive;\n if (!onArchive)\n throw new Error(\"External store adapter does not support archiving\");\n\n await onArchive(threadId);\n }\n\n public async unarchive(threadId: string): Promise<void> {\n const onUnarchive = this.adapter.onUnarchive;\n if (!onUnarchive)\n throw new Error(\"External store adapter does not support unarchiving\");\n\n await onUnarchive(threadId);\n }\n\n public async delete(threadId: string): Promise<void> {\n const onDelete = this.adapter.onDelete;\n if (!onDelete)\n throw new Error(\"External store adapter does not support deleting\");\n\n await onDelete(threadId);\n }\n\n public initialize(\n threadId: string,\n ): Promise<{ remoteId: string; externalId: string | undefined }> {\n return Promise.resolve({ remoteId: threadId, externalId: undefined });\n }\n\n public generateTitle(): never {\n throw new Error(\"Method not implemented.\");\n }\n\n private _subscriptions = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n"],"mappings":";AAUA,MAAMM,cAAcC,OAAOC,OAAO,CAAA,CAAE;AACpC,MAAMC,oBAAoB;AAC1B,MAAMC,kBAAkBH,OAAOC,OAAO,CAACC,iBAAiB,CAAC;AACzD,MAAME,iBAAiBJ,OAAOC,OAAO;CACnCI,IAAIH;CACJI,UAAUC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AEA,qBAA6B;EAC3B,KAAK,MAAMA,YAAY,KAAKH,gBAAgBG,SAAS;CACvD;AACF"}
|
|
1
|
+
{"version":3,"file":"external-store-thread-list-runtime-core.js","names":["Unsubscribe","ExternalStoreThreadRuntimeCore","ThreadListItemCoreState","ThreadListRuntimeCore","ExternalStoreThreadListAdapter","ExternalStoreThreadFactory","EMPTY_ARRAY","Object","freeze","DEFAULT_THREAD_ID","DEFAULT_THREADS","DEFAULT_THREAD","id","remoteId","undefined","externalId","status","RESOLVED_PROMISE","Promise","resolve","DEFAULT_THREAD_DATA","ExternalStoreThreadListRuntimeCore","_mainThreadId","_threads","_archivedThreads","_threadData","Readonly","Record","adapter","isLoading","newThreadId","threadIds","archivedThreadIds","threadItems","getLoadThreadsPromise","_mainThread","mainThreadId","threadFactory","constructor","__internal_setAdapter","getMainThreadRuntimeCore","getThreadRuntimeCore","Error","getItemById","threadId","initialLoad","previousAdapter","newThreads","threads","newArchivedThreads","archivedThreads","previousThreadId","previousThreads","previousArchivedThreads","fromEntries","map","t","_notifySubscribers","reloadMainThread","unstable_refetchThread","switchToThread","_options","unarchive","onSwitchToThread","switchToNewThread","onSwitchToNewThread","rename","newTitle","onRename","updateCustom","custom","onUpdateCustom","detach","archive","onArchive","onUnarchive","delete","onDelete","initialize","generateTitle","_subscriptions","Set","subscribe","callback","add"],"sources":["../../../src/runtimes/external-store/external-store-thread-list-runtime-core.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { ExternalStoreThreadRuntimeCore } from \"./external-store-thread-runtime-core\";\nimport type {\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"../../runtime/interfaces/thread-list-runtime-core\";\nimport type { ExternalStoreThreadListAdapter } from \"./external-store-adapter\";\n\nexport type ExternalStoreThreadFactory = () => ExternalStoreThreadRuntimeCore;\n\nconst EMPTY_ARRAY = Object.freeze([]);\nconst DEFAULT_THREAD_ID = \"DEFAULT_THREAD_ID\";\nconst DEFAULT_THREADS = Object.freeze([DEFAULT_THREAD_ID]);\nconst DEFAULT_THREAD = Object.freeze({\n id: DEFAULT_THREAD_ID,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n});\nconst RESOLVED_PROMISE = Promise.resolve();\nconst DEFAULT_THREAD_DATA = Object.freeze({\n [DEFAULT_THREAD_ID]: DEFAULT_THREAD,\n});\n\nexport class ExternalStoreThreadListRuntimeCore implements ThreadListRuntimeCore {\n private _mainThreadId: string = DEFAULT_THREAD_ID;\n private _threads: readonly string[] = DEFAULT_THREADS;\n private _archivedThreads: readonly string[] = EMPTY_ARRAY;\n private _threadData: Readonly<Record<string, ThreadListItemCoreState>> =\n DEFAULT_THREAD_DATA;\n private adapter: ExternalStoreThreadListAdapter = {};\n\n public get isLoading() {\n return this.adapter.isLoading ?? false;\n }\n\n public get newThreadId() {\n return undefined;\n }\n\n public get threadIds() {\n return this._threads;\n }\n\n public get archivedThreadIds() {\n return this._archivedThreads;\n }\n\n public get threadItems() {\n return this._threadData;\n }\n\n public getLoadThreadsPromise() {\n return RESOLVED_PROMISE;\n }\n\n private _mainThread!: ExternalStoreThreadRuntimeCore;\n\n public get mainThreadId() {\n return this._mainThreadId;\n }\n\n private threadFactory: ExternalStoreThreadFactory;\n\n constructor(\n adapter: ExternalStoreThreadListAdapter = {},\n threadFactory: ExternalStoreThreadFactory,\n ) {\n this.threadFactory = threadFactory;\n this.__internal_setAdapter(adapter, true);\n }\n\n public getMainThreadRuntimeCore() {\n return this._mainThread;\n }\n\n public getThreadRuntimeCore(): never {\n throw new Error(\"Method not implemented.\");\n }\n\n public getItemById(threadId: string) {\n return this._threadData[threadId];\n }\n\n public __internal_setAdapter(\n adapter: ExternalStoreThreadListAdapter,\n initialLoad = false,\n ) {\n const previousAdapter = this.adapter;\n this.adapter = adapter;\n\n const newThreadId = adapter.threadId ?? DEFAULT_THREAD_ID;\n const newThreads = adapter.threads ?? EMPTY_ARRAY;\n const newArchivedThreads = adapter.archivedThreads ?? EMPTY_ARRAY;\n\n const previousThreadId = previousAdapter.threadId ?? DEFAULT_THREAD_ID;\n const previousThreads = previousAdapter.threads ?? EMPTY_ARRAY;\n const previousArchivedThreads =\n previousAdapter.archivedThreads ?? EMPTY_ARRAY;\n\n if (\n !initialLoad &&\n previousThreadId === newThreadId &&\n previousThreads === newThreads &&\n previousArchivedThreads === newArchivedThreads\n ) {\n return;\n }\n\n if (\n previousThreads !== newThreads ||\n previousArchivedThreads !== newArchivedThreads ||\n previousThreadId !== newThreadId\n ) {\n this._threadData = {\n ...DEFAULT_THREAD_DATA,\n ...Object.fromEntries(\n adapter.threads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"regular\",\n },\n ]) ?? [],\n ),\n ...Object.fromEntries(\n adapter.archivedThreads?.map((t) => [\n t.id,\n {\n ...t,\n remoteId: t.remoteId,\n externalId: t.externalId,\n status: \"archived\",\n },\n ]) ?? [],\n ),\n };\n }\n\n if (previousThreads !== newThreads) {\n this._threads = this.adapter.threads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n if (previousArchivedThreads !== newArchivedThreads) {\n this._archivedThreads =\n this.adapter.archivedThreads?.map((t) => t.id) ?? EMPTY_ARRAY;\n }\n\n // `initialLoad ||`: `_mainThread!` must be assigned on construction.\n if (initialLoad || previousThreadId !== newThreadId) {\n this._mainThreadId = newThreadId;\n this._mainThread = this.threadFactory();\n }\n\n if (!this._threadData[this._mainThreadId]) {\n this._threadData = {\n ...this._threadData,\n [this._mainThreadId]: {\n id: this._mainThreadId,\n remoteId: undefined,\n externalId: undefined,\n status: \"regular\",\n },\n };\n }\n\n this._notifySubscribers();\n }\n\n public async reloadMainThread(): Promise<void> {\n // There is no runtime hook to remount here, so the capability is the only\n // path and an adapter without it has nothing to refetch with.\n if (!this._mainThread.unstable_refetchThread) return;\n // No unsent-thread guard: every entry here is regular or archived, so the\n // \"new\" status the remote thread list has to exclude cannot occur.\n await this._mainThread.unstable_refetchThread();\n }\n\n public async switchToThread(\n threadId: string,\n _options?: { unarchive?: boolean },\n ): Promise<void> {\n if (this._mainThreadId === threadId) return;\n const onSwitchToThread = this.adapter.onSwitchToThread;\n if (!onSwitchToThread)\n throw new Error(\n \"External store adapter does not support switching to thread\",\n );\n await onSwitchToThread(threadId);\n }\n\n public async switchToNewThread(): Promise<void> {\n const onSwitchToNewThread = this.adapter.onSwitchToNewThread;\n if (!onSwitchToNewThread)\n throw new Error(\n \"External store adapter does not support switching to new thread\",\n );\n\n await onSwitchToNewThread();\n }\n\n public async rename(threadId: string, newTitle: string): Promise<void> {\n const onRename = this.adapter.onRename;\n if (!onRename)\n throw new Error(\"External store adapter does not support renaming\");\n\n await onRename(threadId, newTitle);\n }\n\n public async updateCustom(\n threadId: string,\n custom: Record<string, unknown> | undefined,\n ): Promise<void> {\n const onUpdateCustom = this.adapter.onUpdateCustom;\n if (!onUpdateCustom)\n throw new Error(\n \"External store adapter does not support updating custom metadata\",\n );\n\n await onUpdateCustom(threadId, custom);\n }\n\n public async detach(): Promise<void> {\n // no-op\n }\n\n public async archive(threadId: string): Promise<void> {\n const onArchive = this.adapter.onArchive;\n if (!onArchive)\n throw new Error(\"External store adapter does not support archiving\");\n\n await onArchive(threadId);\n }\n\n public async unarchive(threadId: string): Promise<void> {\n const onUnarchive = this.adapter.onUnarchive;\n if (!onUnarchive)\n throw new Error(\"External store adapter does not support unarchiving\");\n\n await onUnarchive(threadId);\n }\n\n public async delete(threadId: string): Promise<void> {\n const onDelete = this.adapter.onDelete;\n if (!onDelete)\n throw new Error(\"External store adapter does not support deleting\");\n\n await onDelete(threadId);\n }\n\n public initialize(\n threadId: string,\n ): Promise<{ remoteId: string; externalId: string | undefined }> {\n return Promise.resolve({ remoteId: threadId, externalId: undefined });\n }\n\n public generateTitle(): never {\n throw new Error(\"Method not implemented.\");\n }\n\n private _subscriptions = new Set<() => void>();\n\n public subscribe(callback: () => void): Unsubscribe {\n this._subscriptions.add(callback);\n return () => this._subscriptions.delete(callback);\n }\n\n private _notifySubscribers() {\n for (const callback of this._subscriptions) callback();\n }\n}\n"],"mappings":";AAUA,MAAMM,cAAcC,OAAOC,OAAO,CAAA,CAAE;AACpC,MAAMC,oBAAoB;AAC1B,MAAMC,kBAAkBH,OAAOC,OAAO,CAACC,iBAAiB,CAAC;AACzD,MAAME,iBAAiBJ,OAAOC,OAAO;CACnCI,IAAIH;CACJI,UAAUC,KAAAA;CACVC,YAAYD,KAAAA;CACZE,QAAQ;AACV,CAAC;AACD,MAAMC,mBAAmBC,QAAQC,QAAQ;AACzC,MAAMC,sBAAsBb,OAAOC,OAAO,GACvCC,oBAAoBE,eACvB,CAAC;AAED,IAAaU,qCAAb,MAAiF;CAC/E,gBAAgCZ;CAChC,WAAsCC;CACtC,mBAA8CJ;CAC9C,cACEc;CACF,UAAkD,CAAC;CAEnD,IAAWS,YAAY;EACrB,OAAO,KAAKD,QAAQC,aAAa;CACnC;CAEA,IAAWC,cAAc,CAEzB;CAEA,IAAWC,YAAY;EACrB,OAAO,KAAKR;CACd;CAEA,IAAWS,oBAAoB;EAC7B,OAAO,KAAKR;CACd;CAEA,IAAWS,cAAc;EACvB,OAAO,KAAKR;CACd;CAEA,wBAA+B;EAC7B,OAAOR;CACT;CAEA;CAEA,IAAWmB,eAAe;EACxB,OAAO,KAAKd;CACd;CAEA;CAEAgB,YACEV,UAA0C,CAAC,GAC3CS,eACA;EACA,KAAKA,gBAAgBA;EACrB,KAAKE,sBAAsBX,SAAS,IAAI;CAC1C;CAEA,2BAAkC;EAChC,OAAO,KAAKO;CACd;CAEA,uBAAqC;EACnC,MAAM,IAAIO,MAAM,yBAAyB;CAC3C;CAEA,YAAmBE,UAAkB;EACnC,OAAO,KAAKnB,YAAYmB;CAC1B;CAEA,sBACEhB,SACAiB,cAAc,OACd;EACA,MAAMC,kBAAkB,KAAKlB;EAC7B,KAAKA,UAAUA;EAEf,MAAME,cAAcF,QAAQgB,YAAYnC;EACxC,MAAMsC,aAAanB,QAAQoB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A,UACH,MAAM,IAAInC,MAAM,kDAAkD;EAEpE,MAAMmC,SAASjC,QAAQ;CACzB;CAEA,WACEA,UAC+D;EAC/D,OAAO1B,QAAQC,QAAQ;GAAEN,UAAU+B;GAAU7B,YAAYD,KAAAA;EAAU,CAAC;CACtE;CAEA,gBAA8B;EAC5B,MAAM,IAAI4B,MAAM,yBAAyB;CAC3C;CAEA,iCAAyB,IAAIuC,IAAgB;CAE7C,UAAiBE,UAAmC;EAClD,KAAKH,eAAeI,IAAID,QAAQ;EAChC,aAAa,KAAKH,eAAeJ,OAAOO,QAAQ;CAClD;CAEA,qBAA6B;EAC3B,KAAK,MAAMA,YAAY,KAAKH,gBAAgBG,SAAS;CACvD;AACF"}
|
|
@@ -32,6 +32,7 @@ declare class ExternalStoreThreadRuntimeCore extends BaseThreadRuntimeCore imple
|
|
|
32
32
|
feedback?: FeedbackAdapter | undefined;
|
|
33
33
|
threadList?: ExternalStoreThreadListAdapter | undefined;
|
|
34
34
|
} | undefined;
|
|
35
|
+
get unstable_refetchThread(): (() => Promise<void>) | undefined;
|
|
35
36
|
suggestions: readonly ThreadSuggestion[];
|
|
36
37
|
extras: unknown;
|
|
37
38
|
private _converter;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;cAkDa,qBACX,oBACA,mBAAmB;cAKR,uCACH,iCACG;UAEH;
|
|
1
|
+
{"version":3,"file":"external-store-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;cAkDa,qBACX,oBACA,mBAAmB;cAKR,uCACH,iCACG;UAEH;MAiBG,gBAAY;UAIf;EACD;EACA;MACI;MAIA;YAIQ,6BAA6B;MAI5B,sEAAK,sDAAA;MAId;kBARqC;;;;;;;MAarC,iCAAiC;EAKrC,sBAAsB;EACtB;UAEC;UAEA;;;;;UAMA;EAEQ,UAAU;EAQxB,YAAA,iBAAiB,sBACjB,OAAO;EAMF,sBAAsB,OAAO;;;;;;;UA8L5B;;;;;UAmEA;UACA;;;;;;;UAQA;EAmBQ,eAAe;;;;;;;;;UA6BvB;EAaK,OAAO,SAAS,gBAAgB;EA8BhC,cAAc,oBAAoB;EAoBxC,0BApBwC;EA0BxC,eAAe;EAIf,gBAAgB;EAIV,SAAS,QAAQ,iBAAiB;EAclC,UAAU,QAAQ,kBAAkB;EAO1C;EAOA,oBAAoB;EAmBpB;EA0CA,cAAc,SAAS;EAMvB,eAAe,SAAS;EAoBxB,sBAAsB,SAAS;EAMtB,MAAM,2BAA2B;EAMjC,OAAO,MAAM;UAQrB"}
|
|
@@ -26,6 +26,7 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
26
26
|
edit: false,
|
|
27
27
|
delete: false,
|
|
28
28
|
reload: false,
|
|
29
|
+
refetchThread: false,
|
|
29
30
|
cancel: false,
|
|
30
31
|
unstable_copy: false,
|
|
31
32
|
speech: false,
|
|
@@ -56,6 +57,10 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
56
57
|
get adapters() {
|
|
57
58
|
return this._store.adapters;
|
|
58
59
|
}
|
|
60
|
+
get unstable_refetchThread() {
|
|
61
|
+
if (!this._store.onRefetchThread) return void 0;
|
|
62
|
+
return () => this._store.onRefetchThread();
|
|
63
|
+
}
|
|
59
64
|
suggestions = [];
|
|
60
65
|
extras = void 0;
|
|
61
66
|
_converter = new ThreadMessageConverter();
|
|
@@ -89,6 +94,7 @@ var ExternalStoreThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
89
94
|
edit: this._store.onEdit !== void 0,
|
|
90
95
|
delete: this._store.onDelete !== void 0 || this._store.setMessages !== void 0,
|
|
91
96
|
reload: this._store.onReload !== void 0,
|
|
97
|
+
refetchThread: this._store.onRefetchThread !== void 0,
|
|
92
98
|
cancel: this._store.onCancel !== void 0,
|
|
93
99
|
speech: this._store.adapters?.speech !== void 0,
|
|
94
100
|
dictation: this._store.adapters?.dictation !== void 0,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","ExternalStoreBranchChange","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","EMPTY_ARRAY","Object","freeze","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","suggestions","extras","undefined","_converter","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","incoming","headId","at","message","id","repository","resetHead","getMessages","incomingIds","Set","map","parentId","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","seenIds","deduped","i","console","warn","add","push","reverse","parent","ensureInitialized","_notifyEventSubscribers","optimisticId","content","metadata","isOptimistic","type","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","result","isError","artifact","modelContent","err","error","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","clear","visit","Array","isArray","part","set","get","branchId","onBranchChange","unstable_onBranchChange","previousHeadId","canonicalHeadId","updateMessages","_notifyBranchChange","event","visibleMessageIds","append","Promise","isEdit","enqueue","steer","startRun","abort","onNew","messageIndex","findIndex","filter","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","cancelRun","head","previousMessage","composer","text","trim","setText","setTimeout","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type {\n ExternalStoreAdapter,\n ExternalStoreBranchChange,\n} from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n const incoming = store.messageRepository.messages;\n const headId =\n store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;\n\n if (oldStore && oldStore.messageRepository === store.messageRepository) {\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n } else {\n const incomingIds = new Set(incoming.map(({ message }) => message.id));\n for (const { message, parentId } of incoming) {\n this.repository.addOrUpdateMessage(parentId, message);\n }\n for (const { message } of this.repository.export().messages) {\n if (!incomingIds.has(message.id)) {\n this.repository.deleteMessage(message.id);\n }\n }\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n }\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n const seenIds = new Set<string>();\n const deduped: ThreadMessage[] = [];\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]!;\n if (seenIds.has(message.id)) {\n console.warn(\n `ExternalStoreThreadRuntimeCore: duplicate message id \"${message.id}\" in the provided messages array; keeping the last occurrence.`,\n );\n continue;\n }\n seenIds.add(message.id);\n deduped.push(message);\n }\n if (deduped.length !== messages.length) messages = deduped.reverse();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n });\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n const onBranchChange = this._store.unstable_onBranchChange;\n const previousHeadId = onBranchChange\n ? this.repository.canonicalHeadId\n : null;\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n if (onBranchChange) {\n this._notifyBranchChange(previousHeadId, onBranchChange);\n }\n }\n\n /**\n * Emit `unstable_onBranchChange` for an explicit branch switch. Reads the\n * canonical head from the repository (which skips optimistic/transient\n * messages) and de-dupes switches that leave the canonical head unchanged.\n * Comparing against the head observed just before the switch — rather than the\n * last emitted head — keeps a switch firing after an adapter resync moved the\n * head elsewhere in the meantime.\n */\n private _notifyBranchChange(\n previousHeadId: string | null,\n onBranchChange: (event: ExternalStoreBranchChange) => void,\n ): void {\n const headId = this.repository.canonicalHeadId;\n if (headId === previousHeadId) return;\n\n onBranchChange({\n headId,\n visibleMessageIds: this.repository.getMessages().map((m) => m.id),\n });\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isEdit = message.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // Buffering does not start a run, so the tool-abort below must wait until\n // the queue flushes. By then the prior run (and its tools) has settled.\n if (!isEdit && this._store.queue) {\n this._store.queue.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n this._store.queue?.clear(\"edit\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string) {\n this._store?.queue?.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n this._store.queue?.clear(\"reload\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. We only clear adapter-side\n // tool statuses when the tracker is the source of truth — otherwise\n // we'd wipe statuses the adapter is managing on its own.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._store.setToolStatuses?.({});\n }\n\n this._store.onLoadExternalState(state);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.queue?.clear(\"cancel-run\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n this._store.onCancel();\n\n // Drop an empty optimistic head (placeholder or pre-stream message); a\n // partially-streamed one is kept and re-supplied by the store on resync.\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this._notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult?.(options);\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n this._store.onRespondToToolApproval(options);\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage[]);\n }\n };\n}\n"],"mappings":";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AAC;CACxC;CAEA,OAAuB0H,MAAiC;EACtD,MAAMF,OAAOE,IAAI;EAEjB,IAAI,KAAK7J,OAAO8J,UACd,KAAK9J,OAAO8J,SAAS,KAAK7H,WAAWE,YAAY,CAAC;CAEtD;CAEA,kBAA0BzD,aAAuC;EAE/D,IADqB,KAAKsB,OAAO4C,mBAAmBtC,KAAAA,GAElD,KAAKN,OAAOoB,cAAc1C,SAASsL,QAAQnN,wBAAwB,CAAC;OAGpE,KAAKmD,OAAOoB,cAAc1C,QAA2B;CAEzD;AACF"}
|
|
1
|
+
{"version":3,"file":"external-store-thread-runtime-core.js","names":["AppendMessage","ThreadMessage","AddToolResultOptions","ResumeRunConfig","ResumeToolCallOptions","RespondToToolApprovalOptions","StartRunConfig","ThreadSuggestion","ExternalStoreAdapter","ExternalStoreBranchChange","getExternalStoreMessages","bindExternalStoreMessage","ThreadMessageConverter","getAutoStatus","isAutoStatus","fromThreadMessageLike","ThreadMessageLike","getThreadMessageText","RuntimeCapabilities","ThreadRuntimeCore","BaseThreadRuntimeCore","ModelContextProvider","ExportedMessageRepository","MessageRepository","generateId","ToolInvocationTracker","EMPTY_QUEUE_ITEMS","EMPTY_ARRAY","Object","freeze","shallowEqual","a","b","aKeys","keys","length","key","hasUpcomingMessage","isRunning","messages","role","ExternalStoreThreadRuntimeCore","_capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","capabilities","_messages","isDisabled","isSendDisabled","isLoading","_store","_getBaseMessages","state","adapters","unstable_refetchThread","Promise","onRefetchThread","undefined","suggestions","extras","_converter","_toolInvocations","beginEdit","messageId","onEdit","Error","constructor","contextProvider","store","__internal_setAdapter","oldStore","newSuggestions","newCapabilities","setMessages","onDelete","onReload","onCancel","unstable_capabilities","copy","messageRepository","_notifySubscribers","incoming","headId","at","message","id","repository","resetHead","getMessages","incomingIds","Set","map","parentId","addOrUpdateMessage","export","has","deleteMessage","convertMessage","convertMessages","cache","m","idx","isLast","autoStatus","status","messageLike","newMessage","toString","seenIds","deduped","i","console","warn","add","push","reverse","parent","ensureInitialized","_notifyEventSubscribers","optimisticId","content","metadata","isOptimistic","type","_driveToolInvocations","unstable_enableToolInvocations","reset","setToolStatuses","getModelContext","tools","onResult","command","_findMessageIdForToolCall","toolCallId","onAddToolResult","toolName","result","isError","artifact","modelContent","err","error","onStatusesChange","statuses","fromEntries","setState","_toolCallToMessageId","Map","_messagesForToolCallIndex","clear","visit","Array","isArray","part","set","get","branchId","onBranchChange","unstable_onBranchChange","previousHeadId","canonicalHeadId","updateMessages","_notifyBranchChange","event","visibleMessageIds","append","isEdit","enqueue","steer","startRun","abort","onNew","messageIndex","findIndex","filter","getQueueItems","items","steerQueueItem","queueItemId","removeQueueItem","remove","config","resumeRun","onResume","exportExternalState","onExportExternalState","importExternalState","onLoadExternalState","cancelRun","head","previousMessage","composer","text","trim","setText","setTimeout","addToolResult","options","resumeToolCall","handled","resume","payload","onResumeToolCall","respondToToolApproval","onRespondToToolApproval","initialMessages","repo","import","fromArray","data","onImport","hasConverter","flatMap"],"sources":["../../../src/runtimes/external-store/external-store-thread-runtime-core.ts"],"sourcesContent":["import type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type {\n AddToolResultOptions,\n ResumeRunConfig,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n StartRunConfig,\n ThreadSuggestion,\n} from \"../../runtime/interfaces/thread-runtime-core\";\n\nimport type {\n ExternalStoreAdapter,\n ExternalStoreBranchChange,\n} from \"./external-store-adapter\";\nimport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"../../runtime/utils/external-store-message\";\nimport { ThreadMessageConverter } from \"./thread-message-converter\";\nimport { getAutoStatus, isAutoStatus } from \"../../runtime/utils/auto-status\";\nimport {\n fromThreadMessageLike,\n type ThreadMessageLike,\n} from \"../../runtime/utils/thread-message-like\";\nimport { getThreadMessageText } from \"../../utils/text\";\nimport type {\n RuntimeCapabilities,\n ThreadRuntimeCore,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n ExportedMessageRepository,\n MessageRepository,\n} from \"../../runtime/utils/message-repository\";\nimport { generateId } from \"../../utils/id\";\nimport { ToolInvocationTracker } from \"../tool-invocations/ToolInvocationTracker\";\nimport { EMPTY_QUEUE_ITEMS } from \"../../store/scopes/queue-item\";\n\nconst EMPTY_ARRAY: readonly ThreadSuggestion[] = Object.freeze([]);\n\nconst shallowEqual = (a: object, b: object): boolean => {\n const aKeys = Object.keys(a);\n if (aKeys.length !== Object.keys(b).length) return false;\n for (const key of aKeys) {\n if ((a as any)[key] !== (b as any)[key]) return false;\n }\n return true;\n};\n\nexport const hasUpcomingMessage = (\n isRunning: boolean,\n messages: readonly ThreadMessage[],\n) => {\n return isRunning && messages[messages.length - 1]?.role !== \"assistant\";\n};\n\nexport class ExternalStoreThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n private _capabilities: RuntimeCapabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n refetchThread: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n public get capabilities() {\n return this._capabilities;\n }\n\n private _messages!: readonly ThreadMessage[];\n public isDisabled!: boolean;\n public isSendDisabled!: boolean;\n public get isLoading() {\n return this._store.isLoading ?? false;\n }\n // Unlike `isLoading`: pass `undefined` through to preserve the `getThreadState` fallback.\n public get isRunning(): boolean | undefined {\n return this._store.isRunning;\n }\n\n protected override _getBaseMessages(): readonly ThreadMessage[] {\n return this._messages;\n }\n\n public override get state() {\n return this._store.state ?? super.state;\n }\n\n public get adapters() {\n return this._store.adapters;\n }\n\n // A getter, not a method, so its presence tracks the adapter.\n public get unstable_refetchThread(): (() => Promise<void>) | undefined {\n if (!this._store.onRefetchThread) return undefined;\n return () => this._store.onRefetchThread!();\n }\n\n public suggestions: readonly ThreadSuggestion[] = [];\n public extras: unknown = undefined;\n\n private _converter = new ThreadMessageConverter();\n\n private _store!: ExternalStoreAdapter<any>;\n\n /**\n * Client-side tool-invocations pipeline. Constructed lazily on first\n * snapshot — only when `adapter.unstable_enableToolInvocations === true`.\n */\n private _toolInvocations: ToolInvocationTracker | null = null;\n\n public override beginEdit(messageId: string) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing.\");\n\n super.beginEdit(messageId);\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n store: ExternalStoreAdapter<any>,\n ) {\n super(contextProvider);\n this.__internal_setAdapter(store);\n }\n\n public __internal_setAdapter(store: ExternalStoreAdapter<any>) {\n if (this._store === store) return;\n\n const isRunning = store.isRunning ?? false;\n this.isDisabled = store.isDisabled ?? false;\n this.isSendDisabled = store.isSendDisabled ?? false;\n\n const oldStore = this._store as ExternalStoreAdapter<any> | undefined;\n this._store = store;\n if (this.extras !== store.extras) {\n this.extras = store.extras;\n }\n\n const newSuggestions = store.suggestions ?? EMPTY_ARRAY;\n if (!shallowEqual(this.suggestions, newSuggestions)) {\n this.suggestions = newSuggestions;\n }\n\n const newCapabilities: RuntimeCapabilities = {\n switchToBranch: this._store.setMessages !== undefined,\n switchBranchDuringRun: false,\n edit: this._store.onEdit !== undefined,\n delete:\n this._store.onDelete !== undefined ||\n this._store.setMessages !== undefined,\n reload: this._store.onReload !== undefined,\n refetchThread: this._store.onRefetchThread !== undefined,\n cancel: this._store.onCancel !== undefined,\n speech: this._store.adapters?.speech !== undefined,\n dictation: this._store.adapters?.dictation !== undefined,\n voice: this._store.adapters?.voice !== undefined,\n unstable_copy: this._store.unstable_capabilities?.copy !== false,\n attachments: !!this._store.adapters?.attachments,\n feedback: !!this._store.adapters?.feedback,\n queue: this._store.queue !== undefined,\n };\n if (!shallowEqual(this._capabilities, newCapabilities)) {\n this._capabilities = newCapabilities;\n }\n\n let messages: readonly ThreadMessage[];\n\n if (store.messageRepository) {\n // Handle messageRepository\n if (\n oldStore &&\n oldStore.isRunning === store.isRunning &&\n oldStore.messageRepository === store.messageRepository\n ) {\n this._notifySubscribers();\n return;\n }\n\n const incoming = store.messageRepository.messages;\n const headId =\n store.messageRepository.headId ?? incoming.at(-1)?.message.id ?? null;\n\n if (oldStore && oldStore.messageRepository === store.messageRepository) {\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n } else {\n const incomingIds = new Set(incoming.map(({ message }) => message.id));\n for (const { message, parentId } of incoming) {\n this.repository.addOrUpdateMessage(parentId, message);\n }\n for (const { message } of this.repository.export().messages) {\n if (!incomingIds.has(message.id)) {\n this.repository.deleteMessage(message.id);\n }\n }\n this.repository.resetHead(headId);\n messages = this.repository.getMessages();\n }\n } else if (store.messages) {\n // Handle messages array\n\n if (oldStore) {\n // flush the converter cache when the convertMessage prop changes\n if (oldStore.convertMessage !== store.convertMessage) {\n this._converter = new ThreadMessageConverter();\n } else if (\n oldStore.isRunning === store.isRunning &&\n oldStore.messages === store.messages\n ) {\n this._notifySubscribers();\n // no conversion update\n return;\n }\n }\n\n messages = !store.convertMessage\n ? store.messages\n : this._converter.convertMessages(store.messages, (cache, m, idx) => {\n if (!store.convertMessage) return m;\n\n const isLast = idx === (store.messages?.length ?? 0) - 1;\n const autoStatus = getAutoStatus(\n isLast,\n isRunning,\n false,\n false,\n undefined,\n );\n\n if (\n cache &&\n (cache.role !== \"assistant\" ||\n !isAutoStatus(cache.status) ||\n cache.status === autoStatus)\n )\n return cache;\n\n const messageLike = store.convertMessage(m, idx);\n const newMessage = fromThreadMessageLike(\n messageLike,\n idx.toString(),\n autoStatus,\n );\n bindExternalStoreMessage(newMessage, m);\n return newMessage;\n });\n\n const seenIds = new Set<string>();\n const deduped: ThreadMessage[] = [];\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i]!;\n if (seenIds.has(message.id)) {\n console.warn(\n `ExternalStoreThreadRuntimeCore: duplicate message id \"${message.id}\" in the provided messages array; keeping the last occurrence.`,\n );\n continue;\n }\n seenIds.add(message.id);\n deduped.push(message);\n }\n if (deduped.length !== messages.length) messages = deduped.reverse();\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i]!;\n const parent = messages[i - 1];\n this.repository.addOrUpdateMessage(parent?.id ?? null, message);\n }\n } else {\n throw new Error(\n \"ExternalStoreAdapter must provide either 'messages' or 'messageRepository'\",\n );\n }\n\n // Common logic for both paths\n if (messages.length > 0) this.ensureInitialized();\n\n if ((oldStore?.isRunning ?? false) !== (store.isRunning ?? false)) {\n if (store.isRunning) {\n this._notifyEventSubscribers(\"runStart\", {});\n } else {\n this._notifyEventSubscribers(\"runEnd\", {});\n }\n }\n\n // Append an optimistic placeholder while running but before a trailing\n // assistant message exists. resetHead evicts off-branch optimistic messages\n // (prior placeholders, mid-run id-swap siblings); export() never persists them.\n let optimisticId: string | null = null;\n if (hasUpcomingMessage(isRunning, messages)) {\n optimisticId = generateId();\n this.repository.addOrUpdateMessage(\n messages.at(-1)?.id ?? null,\n fromThreadMessageLike(\n { role: \"assistant\", content: [], metadata: { isOptimistic: true } },\n optimisticId,\n { type: \"running\" },\n ),\n );\n }\n\n this.repository.resetHead(optimisticId ?? messages.at(-1)?.id ?? null);\n\n this._messages = this.repository.getMessages();\n\n this._driveToolInvocations();\n\n this._notifySubscribers();\n }\n\n /**\n * Feed the current message snapshot into the tool-invocations tracker.\n * Opt-in via `adapter.unstable_enableToolInvocations: true`. The tracker\n * itself is fail-silent — see ToolInvocationTracker for the\n * state-transition contract.\n */\n private _driveToolInvocations(): void {\n if (!this._store.unstable_enableToolInvocations) {\n // Adapter did not opt in (default). If a tracker was previously\n // constructed (e.g. the adapter just toggled the flag off via a\n // dynamic swap), drop it so subsequent snapshots are no-ops.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._toolInvocations = null;\n this._store.setToolStatuses?.({});\n }\n return;\n }\n\n if (!this._toolInvocations) {\n this._toolInvocations = new ToolInvocationTracker(\n () => this.getModelContext().tools,\n {\n onResult: (command) => {\n try {\n const messageId = this._findMessageIdForToolCall(\n command.toolCallId,\n );\n if (messageId === undefined) {\n // The tool call no longer exists in the snapshot (e.g.\n // rolled back). Drop the result.\n return;\n }\n this._store.onAddToolResult?.({\n messageId,\n toolCallId: command.toolCallId,\n toolName: command.toolName,\n result: command.result,\n isError: command.isError,\n ...(command.artifact !== undefined && {\n artifact: command.artifact,\n }),\n ...(command.modelContent !== undefined && {\n modelContent: command.modelContent,\n }),\n });\n } catch (err) {\n console.error(\n \"[ExternalStoreThreadRuntimeCore] onAddToolResult dispatch failed\",\n err,\n );\n }\n },\n onStatusesChange: (statuses) => {\n this._store.setToolStatuses?.(Object.fromEntries(statuses));\n },\n },\n );\n }\n\n this._toolInvocations.setState({\n messages: this._messages,\n isRunning: this._store.isRunning ?? false,\n ...(this._store.isLoading !== undefined && {\n isLoading: this._store.isLoading,\n }),\n });\n }\n\n /**\n * Lookup table from `toolCallId` to the owning assistant message's `id`,\n * rebuilt lazily when `_messages` changes (see `_messagesForToolCallIndex`).\n */\n private _toolCallToMessageId = new Map<string, string>();\n private _messagesForToolCallIndex: readonly ThreadMessage[] | null = null;\n\n /**\n * Look up the assistant message that owns a tool-call part. Lazily builds\n * (and caches) a `toolCallId → messageId` map keyed off the current\n * `_messages` reference, so onResult dispatches stay O(1) instead of\n * walking the full thread on every result.\n */\n private _findMessageIdForToolCall(toolCallId: string): string | undefined {\n if (this._messagesForToolCallIndex !== this._messages) {\n this._toolCallToMessageId.clear();\n const visit = (messages: readonly ThreadMessage[]): void => {\n for (const message of messages) {\n if (!Array.isArray(message.content)) continue;\n for (const part of message.content) {\n if (!part || part.type !== \"tool-call\") continue;\n this._toolCallToMessageId.set(part.toolCallId, message.id);\n if (part.messages) visit(part.messages);\n }\n }\n };\n visit(this._messages);\n this._messagesForToolCallIndex = this._messages;\n }\n return this._toolCallToMessageId.get(toolCallId);\n }\n\n public override switchToBranch(branchId: string): void {\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support switching branches.\");\n\n // Silently ignore branch switches while running\n if (this._store.isRunning) {\n return;\n }\n\n const onBranchChange = this._store.unstable_onBranchChange;\n const previousHeadId = onBranchChange\n ? this.repository.canonicalHeadId\n : null;\n\n this.repository.switchToBranch(branchId);\n this.updateMessages(this.repository.getMessages());\n if (onBranchChange) {\n this._notifyBranchChange(previousHeadId, onBranchChange);\n }\n }\n\n /**\n * Emit `unstable_onBranchChange` for an explicit branch switch. Reads the\n * canonical head from the repository (which skips optimistic/transient\n * messages) and de-dupes switches that leave the canonical head unchanged.\n * Comparing against the head observed just before the switch — rather than the\n * last emitted head — keeps a switch firing after an adapter resync moved the\n * head elsewhere in the meantime.\n */\n private _notifyBranchChange(\n previousHeadId: string | null,\n onBranchChange: (event: ExternalStoreBranchChange) => void,\n ): void {\n const headId = this.repository.canonicalHeadId;\n if (headId === previousHeadId) return;\n\n onBranchChange({\n headId,\n visibleMessageIds: this.repository.getMessages().map((m) => m.id),\n });\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isEdit = message.parentId !== (this.messages.at(-1)?.id ?? null);\n\n // Buffering does not start a run, so the tool-abort below must wait until\n // the queue flushes. By then the prior run (and its tools) has settled.\n if (!isEdit && this._store.queue) {\n this._store.queue.enqueue(message, { steer: message.steer ?? false });\n return;\n }\n\n // Auto-abort in-flight client-side tool executions when a new run is\n // about to start. Without this, a tool that finishes after the new turn\n // begins would feed a stale result into `onAddToolResult`, racing with\n // the new turn the user just initiated. `startRun` defaults to true for\n // user messages — matches the satellites' historical opt-in cancel\n // behavior, which is now built in.\n if (message.startRun ?? message.role === \"user\") {\n await this._toolInvocations?.abort();\n }\n\n if (isEdit) {\n if (!this._store.onEdit)\n throw new Error(\"Runtime does not support editing messages.\");\n this._store.queue?.clear(\"edit\");\n await this._store.onEdit(message);\n } else {\n await this._store.onNew(message);\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n if (this._store.onDelete) {\n await this._store.onDelete(messageId);\n return;\n }\n\n if (!this._store.setMessages)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n if (this._store.isRunning) {\n await this._toolInvocations?.abort();\n }\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n this.updateMessages(messages.filter((message) => message.id !== messageId));\n }\n\n public getQueueItems() {\n // The composer reads this during base-thread construction, before the\n // constructor assigns `_store`, so guard against the unset field.\n return this._store?.queue?.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public steerQueueItem(queueItemId: string) {\n this._store?.queue?.steer(queueItemId);\n }\n\n public removeQueueItem(queueItemId: string) {\n this._store?.queue?.remove(queueItemId);\n }\n\n public async startRun(config: StartRunConfig): Promise<void> {\n if (!this._store.onReload)\n throw new Error(\"Runtime does not support reloading messages.\");\n\n this._store.queue?.clear(\"reload\");\n\n // Auto-abort in-flight client-side tool executions when a run reloads;\n // any results that land afterward would target a turn that no longer\n // exists. See `append` above for full rationale.\n await this._toolInvocations?.abort();\n\n await this._store.onReload(config.parentId, config);\n }\n\n public async resumeRun(config: ResumeRunConfig): Promise<void> {\n if (!this._store.onResume)\n throw new Error(\"Runtime does not support resuming runs.\");\n\n await this._store.onResume(config);\n }\n\n public exportExternalState(): any {\n if (!this._store.onExportExternalState)\n throw new Error(\"Runtime does not support exporting external states.\");\n\n return this._store.onExportExternalState();\n }\n\n public importExternalState(state: any): void {\n if (!this._store.onLoadExternalState)\n throw new Error(\"Runtime does not support importing external states.\");\n\n // Re-arm the tracker so the next adapter snapshot (containing the\n // imported state) is treated as historical — no streamCall/execute\n // fires for the loaded tool calls. The adapter is expected to update\n // its messages in response to onLoadExternalState; that update flows\n // back here via __internal_setAdapter. We only clear adapter-side\n // tool statuses when the tracker is the source of truth — otherwise\n // we'd wipe statuses the adapter is managing on its own.\n if (this._toolInvocations) {\n this._toolInvocations.reset();\n this._store.setToolStatuses?.({});\n }\n\n this._store.onLoadExternalState(state);\n }\n\n public cancelRun(): void {\n if (!this._store.onCancel)\n throw new Error(\"Runtime does not support cancelling runs.\");\n\n this._store.queue?.clear(\"cancel-run\");\n\n // Abort any in-flight client-side tool executions. Fire-and-forget —\n // the abort resolves once executions settle, but we don't gate the\n // cancel on it.\n void this._toolInvocations?.abort();\n\n this._store.onCancel();\n\n // Drop an empty optimistic head (placeholder or pre-stream message); a\n // partially-streamed one is kept and re-supplied by the store on resync.\n const head = this.repository.getMessages().at(-1);\n if (head && head.metadata.isOptimistic && head.content.length === 0) {\n this.repository.deleteMessage(head.id);\n }\n\n let messages = this.repository.getMessages();\n const previousMessage = messages[messages.length - 1];\n if (\n previousMessage?.role === \"user\" &&\n previousMessage.id === messages.at(-1)?.id // ensure the previous message is a leaf node\n ) {\n this.repository.deleteMessage(previousMessage.id);\n if (!this.composer.text.trim()) {\n this.composer.setText(getThreadMessageText(previousMessage));\n }\n\n messages = this.repository.getMessages();\n } else {\n this._notifySubscribers();\n }\n\n // resync messages (for reloading, to restore the previous branch)\n setTimeout(() => {\n this.updateMessages(messages);\n }, 0);\n }\n\n public addToolResult(options: AddToolResultOptions) {\n if (!this._store.onAddToolResult)\n throw new Error(\"Runtime does not support tool results.\");\n this._store.onAddToolResult?.(options);\n }\n\n public resumeToolCall(options: ResumeToolCallOptions) {\n // Tracker owns its own human-input handlers — let it resume in-process\n // tool calls without round-tripping through the adapter. Falls back to\n // the adapter's onResumeToolCall (if any) for tool calls the tracker\n // doesn't know about.\n const handled =\n this._toolInvocations?.resume(options.toolCallId, options.payload) ??\n false;\n if (handled) return;\n\n if (this._store.onResumeToolCall) {\n this._store.onResumeToolCall(options);\n return;\n }\n\n throw new Error(\n `Tool call ${options.toolCallId} is not waiting for resume.`,\n );\n }\n\n public respondToToolApproval(options: RespondToToolApprovalOptions) {\n if (!this._store.onRespondToToolApproval)\n throw new Error(\"Runtime does not support tool approvals.\");\n this._store.onRespondToToolApproval(options);\n }\n\n public override reset(initialMessages?: readonly ThreadMessageLike[]) {\n const repo = new MessageRepository();\n repo.import(ExportedMessageRepository.fromArray(initialMessages ?? []));\n this.updateMessages(repo.getMessages());\n }\n\n public override import(data: ExportedMessageRepository) {\n super.import(data);\n\n if (this._store.onImport) {\n this._store.onImport(this.repository.getMessages());\n }\n }\n\n private updateMessages = (messages: readonly ThreadMessage[]) => {\n const hasConverter = this._store.convertMessage !== undefined;\n if (hasConverter) {\n this._store.setMessages?.(messages.flatMap(getExternalStoreMessages));\n } else {\n // TODO mark this as readonly in v0.12.0\n this._store.setMessages?.(messages as ThreadMessage[]);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;AAuCA,MAAM2B,cAA2CC,OAAOC,OAAO,CAAA,CAAE;AAEjE,MAAMC,gBAAgBC,GAAWC,MAAuB;CACtD,MAAMC,QAAQL,OAAOM,KAAKH,CAAC;CAC3B,IAAIE,MAAME,WAAWP,OAAOM,KAAKF,CAAC,CAAC,CAACG,QAAQ,OAAO;CACnD,KAAK,MAAMC,OAAOH,OAChB,IAAKF,EAAUK,SAAUJ,EAAUI,MAAM,OAAO;CAElD,OAAO;AACT;AAEA,MAAaC,sBACXC,WACAC,aACG;CACH,OAAOD,aAAaC,SAASA,SAASJ,SAAS,EAAE,EAAEK,SAAS;AAC9D;AAEA,IAAaC,iCAAb,cACUrB,sBAEV;CACE,gBAA6C;EAC3CuB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,IAAWC,eAAe;EACxB,OAAO,KAAKf;CACd;CAEA;CACA;CACA;CACA,IAAWmB,YAAY;EACrB,OAAO,KAAKC,OAAOD,aAAa;CAClC;CAEA,IAAWvB,YAAiC;EAC1C,OAAO,KAAKwB,OAAOxB;CACrB;CAEA,mBAAgE;EAC9D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