@assistant-ui/core 0.3.18 → 0.3.19
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/adapters/speech.d.ts.map +1 -1
- package/dist/adapters/speech.js +13 -3
- package/dist/adapters/speech.js.map +1 -1
- package/dist/adapters/thread-history.d.ts +4 -0
- package/dist/adapters/thread-history.d.ts.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/model-context/frame/host.d.ts.map +1 -1
- package/dist/model-context/frame/host.js +26 -11
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/interactable-composer-metadata.js +11 -9
- package/dist/model-context/interactable-composer-metadata.js.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.d.ts.map +1 -1
- package/dist/react/adapters/LocalStorageThreadListAdapter.js +45 -7
- package/dist/react/adapters/LocalStorageThreadListAdapter.js.map +1 -1
- package/dist/react/client/DataRenderers.d.ts.map +1 -1
- package/dist/react/client/DataRenderers.js +20 -15
- package/dist/react/client/DataRenderers.js.map +1 -1
- package/dist/react/client/Interactables.d.ts.map +1 -1
- package/dist/react/client/Interactables.js +11 -5
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
- package/dist/react/client/RemoteThreadList.js +3 -2
- package/dist/react/client/RemoteThreadList.js.map +1 -1
- package/dist/react/client/interactable-model-context.d.ts.map +1 -1
- package/dist/react/client/interactable-model-context.js +3 -2
- package/dist/react/client/interactable-model-context.js.map +1 -1
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +2 -2
- package/dist/react/interactables-legacy/useAssistantInteractable.d.ts.map +1 -1
- package/dist/react/interactables-legacy/useAssistantInteractable.js +3 -0
- package/dist/react/interactables-legacy/useAssistantInteractable.js.map +1 -1
- package/dist/react/model-context/useInteractable.d.ts.map +1 -1
- package/dist/react/model-context/useInteractable.js +4 -1
- package/dist/react/model-context/useInteractable.js.map +1 -1
- package/dist/react/model-context/useInteractableVersions.js +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.d.ts +11 -2
- package/dist/react/primitives/message/MessageGroupedParts.d.ts.map +1 -1
- package/dist/react/primitives/message/MessageGroupedParts.js +3 -2
- package/dist/react/primitives/message/MessageGroupedParts.js.map +1 -1
- package/dist/react/primitives/part/PartMessages.d.ts +1 -0
- package/dist/react/primitives/part/PartMessages.d.ts.map +1 -1
- package/dist/react/primitives/part/PartMessages.js +1 -0
- package/dist/react/primitives/part/PartMessages.js.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.d.ts.map +1 -1
- package/dist/react/primitives/thread/ThreadMessages.js +6 -5
- package/dist/react/primitives/thread/ThreadMessages.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +2 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts +2 -24
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +135 -374
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts +1 -0
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js +22 -2
- package/dist/react/runtimes/cloud/CloudFileAttachmentAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.d.ts +40 -15
- package/dist/react/runtimes/cloud/auiV0.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/auiV0.js +62 -15
- package/dist/react/runtimes/cloud/auiV0.js.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts +2 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js +4 -0
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/sdkIdentity.d.ts +6 -0
- package/dist/react/runtimes/cloud/sdkIdentity.d.ts.map +1 -0
- package/dist/react/runtimes/cloud/sdkIdentity.js +9 -0
- package/dist/react/runtimes/cloud/sdkIdentity.js.map +1 -0
- package/dist/react/runtimes/external-message-converter.d.ts +12 -2
- package/dist/react/runtimes/external-message-converter.d.ts.map +1 -1
- package/dist/react/runtimes/external-message-converter.js +26 -61
- package/dist/react/runtimes/external-message-converter.js.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
- package/dist/react/utils/groupParts.d.ts +6 -1
- package/dist/react/utils/groupParts.d.ts.map +1 -1
- package/dist/react/utils/groupParts.js +6 -0
- package/dist/react/utils/groupParts.js.map +1 -1
- package/dist/react/utils/useJSONEqual.d.ts +3 -1
- package/dist/react/utils/useJSONEqual.d.ts.map +1 -1
- package/dist/react/utils/useJSONEqual.js +6 -1
- package/dist/react/utils/useJSONEqual.js.map +1 -1
- package/dist/react/utils/useJSONSchemaDependency.d.ts +7 -0
- package/dist/react/utils/useJSONSchemaDependency.d.ts.map +1 -0
- package/dist/react/utils/useJSONSchemaDependency.js +20 -0
- package/dist/react/utils/useJSONSchemaDependency.js.map +1 -0
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js +2 -5
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts +1 -0
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +46 -10
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.d.ts +2 -0
- package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js +155 -64
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/interfaces/thread-runtime-core.d.ts +6 -0
- package/dist/runtime/interfaces/thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/queue/message-queue.d.ts +5 -0
- package/dist/runtime/queue/message-queue.d.ts.map +1 -1
- package/dist/runtime/queue/message-queue.js +61 -6
- package/dist/runtime/queue/message-queue.js.map +1 -1
- package/dist/runtime/utils/auto-status.d.ts +6 -2
- package/dist/runtime/utils/auto-status.d.ts.map +1 -1
- package/dist/runtime/utils/auto-status.js +12 -4
- package/dist/runtime/utils/auto-status.js.map +1 -1
- package/dist/runtime/utils/external-message-conversion.d.ts +16 -4
- package/dist/runtime/utils/external-message-conversion.d.ts.map +1 -1
- package/dist/runtime/utils/external-message-conversion.js +48 -12
- package/dist/runtime/utils/external-message-conversion.js.map +1 -1
- package/dist/runtime/utils/message-repository.js +3 -3
- package/dist/runtime/utils/message-repository.js.map +1 -1
- package/dist/runtime/utils/thread-message-like.d.ts +2 -1
- package/dist/runtime/utils/thread-message-like.d.ts.map +1 -1
- package/dist/runtime/utils/thread-message-like.js +4 -2
- package/dist/runtime/utils/thread-message-like.js.map +1 -1
- 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 +8 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/internal.d.ts +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +4 -1
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.d.ts.map +1 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js +2 -1
- package/dist/runtimes/tool-invocations/ToolInvocationTracker.js.map +1 -1
- package/dist/store/clients/external-thread.d.ts.map +1 -1
- package/dist/store/clients/external-thread.js +241 -200
- package/dist/store/clients/external-thread.js.map +1 -1
- package/dist/store/clients/thread-tasks.d.ts +13 -0
- package/dist/store/clients/thread-tasks.d.ts.map +1 -0
- package/dist/store/clients/thread-tasks.js +69 -0
- package/dist/store/clients/thread-tasks.js.map +1 -0
- package/dist/store/index.d.ts +3 -2
- package/dist/store/index.js +3 -3
- package/dist/store/primitive-predicates.d.ts.map +1 -1
- package/dist/store/primitive-predicates.js +4 -4
- package/dist/store/primitive-predicates.js.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.js +176 -128
- package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
- package/dist/store/scope-registration.d.ts +2 -0
- package/dist/store/scope-registration.d.ts.map +1 -1
- package/dist/store/scopes/task.d.ts +36 -0
- package/dist/store/scopes/task.d.ts.map +1 -0
- package/dist/store/scopes/task.js +0 -0
- package/dist/store/scopes/thread.d.ts +20 -0
- package/dist/store/scopes/thread.d.ts.map +1 -1
- package/dist/subscribable/subscribable.d.ts +2 -1
- package/dist/subscribable/subscribable.d.ts.map +1 -1
- package/dist/subscribable/subscribable.js +23 -15
- package/dist/subscribable/subscribable.js.map +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/message.d.ts +8 -1
- package/dist/types/message.d.ts.map +1 -1
- package/dist/types/message.js.map +1 -1
- package/dist/utils/abortable-iterable.d.ts.map +1 -1
- package/dist/utils/abortable-iterable.js +30 -14
- package/dist/utils/abortable-iterable.js.map +1 -1
- package/dist/utils/getGroupStatus.d.ts +18 -2
- package/dist/utils/getGroupStatus.d.ts.map +1 -1
- package/dist/utils/getGroupStatus.js +32 -7
- package/dist/utils/getGroupStatus.js.map +1 -1
- package/dist/utils/wire-media.d.ts.map +1 -1
- package/dist/utils/wire-media.js +2 -2
- package/dist/utils/wire-media.js.map +1 -1
- package/package.json +6 -6
- package/src/adapters/speech.test.ts +236 -0
- package/src/adapters/speech.ts +17 -10
- package/src/adapters/thread-history.ts +3 -0
- package/src/index.ts +1 -0
- package/src/model-context/frame/host.test.ts +113 -1
- package/src/model-context/frame/host.ts +39 -12
- package/src/model-context/interactable-composer-metadata.test.ts +30 -0
- package/src/model-context/interactable-composer-metadata.ts +10 -10
- package/src/react/adapters/LocalStorageThreadListAdapter.test.ts +244 -0
- package/src/react/adapters/LocalStorageThreadListAdapter.tsx +104 -7
- package/src/react/client/DataRenderers.test.tsx +45 -0
- package/src/react/client/DataRenderers.ts +13 -9
- package/src/react/client/Interactables.test.ts +44 -1
- package/src/react/client/Interactables.ts +7 -1
- package/src/react/client/RemoteThreadList.test.ts +41 -1
- package/src/react/client/RemoteThreadList.ts +15 -2
- package/src/react/client/interactable-model-context.test.ts +44 -0
- package/src/react/client/interactable-model-context.ts +3 -2
- package/src/react/index.ts +5 -1
- package/src/react/interactables-legacy/useAssistantInteractable.test.tsx +132 -0
- package/src/react/interactables-legacy/useAssistantInteractable.ts +10 -1
- package/src/react/model-context/useInteractable.test.tsx +177 -0
- package/src/react/model-context/useInteractable.ts +3 -0
- package/src/react/primitive-hooks/useActionBarCopy.test.ts +0 -1
- package/src/react/primitive-hooks/useSuggestionTrigger.test.ts +0 -1
- package/src/react/primitives/message/MessageGroupedParts.test.tsx +96 -0
- package/src/react/primitives/message/MessageGroupedParts.tsx +15 -4
- package/src/react/primitives/part/PartMessages.test.tsx +104 -1
- package/src/react/primitives/part/PartMessages.tsx +1 -0
- package/src/react/primitives/thread/ThreadMessages.test.tsx +142 -0
- package/src/react/primitives/thread/ThreadMessages.tsx +8 -5
- package/src/react/providers/ReadonlyThreadProvider.test.tsx +56 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +7 -1
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.ts +20 -14
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +221 -1
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +166 -512
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.test.ts +77 -0
- package/src/react/runtimes/cloud/CloudFileAttachmentAdapter.ts +27 -1
- package/src/react/runtimes/cloud/auiV0.ts +160 -25
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.test.ts +21 -0
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.ts +7 -1
- package/src/react/runtimes/cloud/sdkIdentity.ts +9 -0
- package/src/react/runtimes/cloud/useCloudThreadListAdapter.test.tsx +18 -4
- package/src/react/runtimes/external-message-converter.test.ts +136 -1
- package/src/react/runtimes/external-message-converter.ts +39 -93
- package/src/react/runtimes/useRemoteThreadListRuntime.ts +1 -1
- package/src/react/utils/groupParts.ts +12 -1
- package/src/react/utils/useJSONEqual.ts +9 -0
- package/src/react/utils/useJSONSchemaDependency.ts +22 -0
- package/src/runtime/api/thread-runtime.test.ts +58 -0
- package/src/runtime/api/thread-runtime.ts +2 -4
- package/src/runtime/base/base-composer-runtime-core.ts +69 -16
- package/src/runtime/base/base-thread-runtime-core.test.ts +1008 -1
- package/src/runtime/base/base-thread-runtime-core.ts +222 -83
- package/src/runtime/interfaces/thread-runtime-core.ts +6 -0
- package/src/runtime/queue/message-queue.ts +68 -6
- package/src/runtime/utils/auto-status.test.ts +112 -1
- package/src/runtime/utils/auto-status.ts +31 -5
- package/src/runtime/utils/external-message-conversion.test.ts +134 -0
- package/src/runtime/utils/external-message-conversion.ts +122 -31
- package/src/runtime/utils/message-repository.test.ts +49 -0
- package/src/runtime/utils/message-repository.ts +3 -3
- package/src/runtime/utils/thread-message-like.test.ts +52 -0
- package/src/runtime/utils/thread-message-like.ts +4 -0
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +31 -1
- package/src/runtimes/local/local-thread-runtime-core.test.ts +21 -0
- package/src/runtimes/local/local-thread-runtime-core.ts +11 -1
- package/src/runtimes/tool-invocations/EDGE_CASES.md +2 -6
- package/src/runtimes/tool-invocations/ToolInvocationTracker.test.ts +133 -0
- package/src/runtimes/tool-invocations/ToolInvocationTracker.ts +10 -6
- package/src/store/clients/external-thread.ts +19 -1
- package/src/store/clients/thread-tasks.test.ts +274 -0
- package/src/store/clients/thread-tasks.ts +138 -0
- package/src/store/index.ts +8 -0
- package/src/store/primitive-predicates.test.ts +48 -5
- package/src/store/primitive-predicates.ts +7 -2
- package/src/store/runtime-clients/thread-runtime-client.ts +31 -1
- package/src/store/scope-registration.ts +2 -0
- package/src/store/scopes/task.ts +34 -0
- package/src/store/scopes/thread.ts +16 -0
- package/src/store/thread-tasks.test.tsx +209 -0
- package/src/subscribable/subscribable.test.ts +156 -1
- package/src/subscribable/subscribable.ts +25 -15
- package/src/tests/MessageRepository.test.ts +1 -5
- package/src/tests/auiV0Encode.test.ts +300 -0
- package/src/tests/base-composer-runtime-core-send.test.ts +51 -0
- package/src/tests/base-composer-runtime-core.test.ts +314 -2
- package/src/tests/external-store-thread-runtime-core-adapter.test.ts +151 -0
- package/src/tests/external-thread-attachments.test.tsx +69 -0
- package/src/tests/external-thread-parity.test.tsx +34 -0
- package/src/tests/groupParts.test.ts +71 -0
- package/src/tests/message-queue.test.ts +253 -0
- package/src/tests/remote-thread-list-reactive-threadId.test.ts +51 -0
- package/src/tests/useRemoteThreadListRuntime-controlled.test.tsx +43 -0
- package/src/types/index.ts +1 -0
- package/src/types/message.ts +8 -0
- package/src/utils/abortable-iterable.test.ts +115 -0
- package/src/utils/abortable-iterable.ts +34 -23
- package/src/utils/getGroupStatus.test.ts +70 -4
- package/src/utils/getGroupStatus.ts +35 -12
- package/src/utils/wire-media.test.ts +10 -0
- package/src/utils/wire-media.ts +6 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRemoteThreadListRuntime.js","names":["useState","useEffect","useInsertionEffect","useMemo","useRef","useCallback","useEffectEvent","BaseAssistantRuntimeCore","AssistantRuntimeImpl","RemoteThreadListOptions","AssistantRuntimeCore","AssistantRuntime","RemoteThreadListThreadListRuntimeCore","WritableSubscribable","useSubscribable","useAui","RemoteThreadListRuntimeCore","threads","constructor","options","_contextProvider","RenderComponent","__internal_RenderComponent","useRemoteThreadListRuntimeImpl","$","_c","t0","runtime","t1","queueMicrotask","__internal_dispose","t2","t3","__internal_setOptions","__internal_load","t4","t5","window","document","reloadAfterError","loadError","undefined","reload","reloadAfterVisible","visibilityState","addEventListener","removeEventListener","t6","t7","useRemoteThreadListRuntime","runtimeHookStore","runtimeHook","setState","initialThreadIdRef","initialThreadId","stableRuntimeHook","useCommittedRuntimeHook","subscribe","getState","getServerSnapshot","onThreadIdChange","threadId","stableOptions","adapter","allowNesting","current","aui","isNested","threadListItem","source","Error"],"sources":["../../../src/react/runtimes/useRemoteThreadListRuntime.ts"],"sourcesContent":["import {\n useState,\n useEffect,\n useInsertionEffect,\n useMemo,\n useRef,\n useCallback,\n useEffectEvent,\n} from \"react\";\nimport { BaseAssistantRuntimeCore } from \"../../runtime/base/base-assistant-runtime-core\";\nimport { AssistantRuntimeImpl } from \"../../runtime/api/assistant-runtime\";\nimport type { RemoteThreadListOptions } from \"../../runtimes/remote-thread-list/types\";\nimport type { AssistantRuntimeCore } from \"../../runtime/interfaces/assistant-runtime-core\";\nimport type { AssistantRuntime } from \"../../runtime/api/assistant-runtime\";\nimport { RemoteThreadListThreadListRuntimeCore } from \"./RemoteThreadListThreadListRuntimeCore\";\nimport { WritableSubscribable } from \"../../subscribable/subscribable\";\nimport { useSubscribable } from \"../../store/runtime-clients/useSubscribable\";\nimport { useAui } from \"@assistant-ui/store\";\n\nclass RemoteThreadListRuntimeCore\n extends BaseAssistantRuntimeCore\n implements AssistantRuntimeCore\n{\n public readonly threads;\n\n constructor(options: RemoteThreadListOptions) {\n super();\n this.threads = new RemoteThreadListThreadListRuntimeCore(\n options,\n this._contextProvider,\n );\n }\n\n public get RenderComponent() {\n return this.threads.__internal_RenderComponent;\n }\n}\n\nconst useRemoteThreadListRuntimeImpl = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const [runtime] = useState(() => new RemoteThreadListRuntimeCore(options));\n\n // Insertion-effect cleanup runs only when React deletes the fiber, so a\n // hidden <Activity> or a re-suspended boundary keeps the threads alive; the\n // disposal is deferred to a microtask because it notifies subscribers and\n // React forbids scheduling updates from an insertion effect.\n useInsertionEffect(\n () => () => queueMicrotask(() => runtime.threads.__internal_dispose()),\n [runtime],\n );\n\n useEffect(() => {\n runtime.threads.__internal_setOptions(options);\n runtime.threads.__internal_load();\n }, [runtime, options]);\n\n useEffect(() => {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return;\n }\n\n const reloadAfterError = () => {\n if (runtime.threads.loadError !== undefined) {\n void runtime.threads.reload();\n }\n };\n const reloadAfterVisible = () => {\n if (document.visibilityState === \"visible\") reloadAfterError();\n };\n\n window.addEventListener(\"online\", reloadAfterError);\n document.addEventListener(\"visibilitychange\", reloadAfterVisible);\n return () => {\n window.removeEventListener(\"online\", reloadAfterError);\n document.removeEventListener(\"visibilitychange\", reloadAfterVisible);\n };\n }, [runtime]);\n\n return useMemo(() => new AssistantRuntimeImpl(runtime), [runtime]);\n};\n\nexport const useRemoteThreadListRuntime = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const [runtimeHookStore] = useState(\n () => new WritableSubscribable(options.runtimeHook),\n );\n useEffect(() => {\n runtimeHookStore.setState(options.runtimeHook);\n }, [runtimeHookStore, options.runtimeHook]);\n\n const initialThreadIdRef = useRef(options.initialThreadId);\n\n // Thread resources subscribe to the store rather than reading a ref, so a\n // hook published at commit reaches exactly the resources that use it and an\n // abandoned render publishes nothing. The store pins its server snapshot to\n // the constructor value for hydration, which tap reads on any never-mounted\n // fiber, so the live state serves as the server snapshot here.\n const stableRuntimeHook = useCallback(\n function useCommittedRuntimeHook() {\n return useSubscribable({\n subscribe: runtimeHookStore.subscribe,\n getState: runtimeHookStore.getState,\n getServerSnapshot: runtimeHookStore.getState,\n })();\n },\n [runtimeHookStore],\n );\n\n const onThreadIdChange = useEffectEvent((threadId: string | undefined) => {\n options.onThreadIdChange?.(threadId);\n });\n\n const stableOptions = useMemo<RemoteThreadListOptions>(\n () => ({\n adapter: options.adapter,\n allowNesting: options.allowNesting,\n threadId: options.threadId,\n initialThreadId: initialThreadIdRef.current,\n runtimeHook: stableRuntimeHook,\n onThreadIdChange,\n }),\n [\n options.adapter,\n options.allowNesting,\n options.threadId,\n stableRuntimeHook,\n ],\n );\n\n const aui = useAui();\n const isNested = aui.threadListItem.source !== null;\n\n if (isNested) {\n if (!stableOptions.allowNesting) {\n throw new Error(\n \"useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. \" +\n \"Set allowNesting: true to allow nesting (the inner runtime will become a no-op).\",\n );\n }\n\n // If allowNesting is true and already inside a thread list context,\n // just call the runtimeHook directly (no-op behavior)\n return options.runtimeHook();\n }\n\n const runtime = useRemoteThreadListRuntimeImpl(stableOptions);\n\n return runtime;\n};\n"],"mappings":";;;;;;;;;AAmBA,IAAMgB,8BAAN,cACUT,yBAEV;CACE;CAEAW,YAAYC,SAAkC;EAC5C,MAAM;EACN,KAAKF,UAAU,IAAIL,sCACjBO,SACA,KAAKC,gBACP;CACF;CAEA,IAAWC,kBAAkB;EAC3B,OAAO,KAAKJ,QAAQK;CACtB;AACF;AAEA,MAAMC,kCAAiCJ,YAAA;CAAA,MAAAK,IAAAC,EAAA,EAAA;CAAA,IAAAC;CAAA,IAAAF,EAAA,OAAAL,SAAA;EAGVO,WAAM,IAAIV,4BAA4BG,OAAO;EAACK,EAAA,KAAAL;EAAAK,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAzE,MAAA,CAAAG,WAAkB3B,SAAS0B,EAA8C;CAAE,IAAAE;CAAA,IAAAJ,EAAA,OAAAG,QAAAV,SAAA;EAOzEW,iBAAYC,qBAAqBF,QA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B,EAAA,MAAAG,QAAAV;EAAAO,EAAA,MAAAY;CAAA,OAAAA,KAAAZ,EAAA;CAAA,IAAAuB;CAAA,IAAAvB,EAAA,QAAAG,SAAA;EAAEoB,KAAA,CAACpB,OAAO;EAACH,EAAA,MAAAG;EAAAH,EAAA,MAAAuB;CAAA,OAAAA,KAAAvB,EAAA;CApBZvB,UAAUmC,IAoBPW,EAAS;CAAC,IAAAC;CAAA,IAAAxB,EAAA,QAAAG,SAAA;EAEQqB,KAAA,IAAIxC,qBAAqBmB,OAAO;EAACH,EAAA,MAAAG;EAAAH,EAAA,MAAAwB;CAAA,OAAAA,KAAAxB,EAAA;CAAA,OAAjCwB;AAAiC;AAGxD,MAAaC,8BACX9B,YACqB;CACrB,MAAM,CAAC+B,oBAAoBlD,eACnB,IAAIa,qBAAqBM,QAAQgC,WAAW,CACpD;CACAlD,gBAAgB;EACdiD,iBAAiBE,SAASjC,QAAQgC,WAAW;CAC/C,GAAG,CAACD,kBAAkB/B,QAAQgC,WAAW,CAAC;CAE1C,MAAME,qBAAqBjD,OAAOe,QAAQmC,eAAe;CAOzD,MAAMC,oBAAoBlD,YACxB,SAASmD,0BAA0B;EACjC,OAAO1C,gBAAgB;GACrB2C,WAAWP,iBAAiBO;GAC5BC,UAAUR,iBAAiBQ;GAC3BC,mBAAmBT,iBAAiBQ;EACtC,CAAC,CAAC,CAAC;CACL,GACA,CAACR,gBAAgB,CACnB;CAEA,MAAMU,mBAAmBtD,gBAAgBuD,aAAiC;
|
|
1
|
+
{"version":3,"file":"useRemoteThreadListRuntime.js","names":["useState","useEffect","useInsertionEffect","useMemo","useRef","useCallback","useEffectEvent","BaseAssistantRuntimeCore","AssistantRuntimeImpl","RemoteThreadListOptions","AssistantRuntimeCore","AssistantRuntime","RemoteThreadListThreadListRuntimeCore","WritableSubscribable","useSubscribable","useAui","RemoteThreadListRuntimeCore","threads","constructor","options","_contextProvider","RenderComponent","__internal_RenderComponent","useRemoteThreadListRuntimeImpl","$","_c","t0","runtime","t1","queueMicrotask","__internal_dispose","t2","t3","__internal_setOptions","__internal_load","t4","t5","window","document","reloadAfterError","loadError","undefined","reload","reloadAfterVisible","visibilityState","addEventListener","removeEventListener","t6","t7","useRemoteThreadListRuntime","runtimeHookStore","runtimeHook","setState","initialThreadIdRef","initialThreadId","stableRuntimeHook","useCommittedRuntimeHook","subscribe","getState","getServerSnapshot","onThreadIdChange","threadId","stableOptions","adapter","allowNesting","current","aui","isNested","threadListItem","source","Error"],"sources":["../../../src/react/runtimes/useRemoteThreadListRuntime.ts"],"sourcesContent":["import {\n useState,\n useEffect,\n useInsertionEffect,\n useMemo,\n useRef,\n useCallback,\n useEffectEvent,\n} from \"react\";\nimport { BaseAssistantRuntimeCore } from \"../../runtime/base/base-assistant-runtime-core\";\nimport { AssistantRuntimeImpl } from \"../../runtime/api/assistant-runtime\";\nimport type { RemoteThreadListOptions } from \"../../runtimes/remote-thread-list/types\";\nimport type { AssistantRuntimeCore } from \"../../runtime/interfaces/assistant-runtime-core\";\nimport type { AssistantRuntime } from \"../../runtime/api/assistant-runtime\";\nimport { RemoteThreadListThreadListRuntimeCore } from \"./RemoteThreadListThreadListRuntimeCore\";\nimport { WritableSubscribable } from \"../../subscribable/subscribable\";\nimport { useSubscribable } from \"../../store/runtime-clients/useSubscribable\";\nimport { useAui } from \"@assistant-ui/store\";\n\nclass RemoteThreadListRuntimeCore\n extends BaseAssistantRuntimeCore\n implements AssistantRuntimeCore\n{\n public readonly threads;\n\n constructor(options: RemoteThreadListOptions) {\n super();\n this.threads = new RemoteThreadListThreadListRuntimeCore(\n options,\n this._contextProvider,\n );\n }\n\n public get RenderComponent() {\n return this.threads.__internal_RenderComponent;\n }\n}\n\nconst useRemoteThreadListRuntimeImpl = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const [runtime] = useState(() => new RemoteThreadListRuntimeCore(options));\n\n // Insertion-effect cleanup runs only when React deletes the fiber, so a\n // hidden <Activity> or a re-suspended boundary keeps the threads alive; the\n // disposal is deferred to a microtask because it notifies subscribers and\n // React forbids scheduling updates from an insertion effect.\n useInsertionEffect(\n () => () => queueMicrotask(() => runtime.threads.__internal_dispose()),\n [runtime],\n );\n\n useEffect(() => {\n runtime.threads.__internal_setOptions(options);\n runtime.threads.__internal_load();\n }, [runtime, options]);\n\n useEffect(() => {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") {\n return;\n }\n\n const reloadAfterError = () => {\n if (runtime.threads.loadError !== undefined) {\n void runtime.threads.reload();\n }\n };\n const reloadAfterVisible = () => {\n if (document.visibilityState === \"visible\") reloadAfterError();\n };\n\n window.addEventListener(\"online\", reloadAfterError);\n document.addEventListener(\"visibilitychange\", reloadAfterVisible);\n return () => {\n window.removeEventListener(\"online\", reloadAfterError);\n document.removeEventListener(\"visibilitychange\", reloadAfterVisible);\n };\n }, [runtime]);\n\n return useMemo(() => new AssistantRuntimeImpl(runtime), [runtime]);\n};\n\nexport const useRemoteThreadListRuntime = (\n options: RemoteThreadListOptions,\n): AssistantRuntime => {\n const [runtimeHookStore] = useState(\n () => new WritableSubscribable(options.runtimeHook),\n );\n useEffect(() => {\n runtimeHookStore.setState(options.runtimeHook);\n }, [runtimeHookStore, options.runtimeHook]);\n\n const initialThreadIdRef = useRef(options.initialThreadId);\n\n // Thread resources subscribe to the store rather than reading a ref, so a\n // hook published at commit reaches exactly the resources that use it and an\n // abandoned render publishes nothing. The store pins its server snapshot to\n // the constructor value for hydration, which tap reads on any never-mounted\n // fiber, so the live state serves as the server snapshot here.\n const stableRuntimeHook = useCallback(\n function useCommittedRuntimeHook() {\n return useSubscribable({\n subscribe: runtimeHookStore.subscribe,\n getState: runtimeHookStore.getState,\n getServerSnapshot: runtimeHookStore.getState,\n })();\n },\n [runtimeHookStore],\n );\n\n const onThreadIdChange = useEffectEvent((threadId: string | undefined) => {\n return options.onThreadIdChange?.(threadId);\n });\n\n const stableOptions = useMemo<RemoteThreadListOptions>(\n () => ({\n adapter: options.adapter,\n allowNesting: options.allowNesting,\n threadId: options.threadId,\n initialThreadId: initialThreadIdRef.current,\n runtimeHook: stableRuntimeHook,\n onThreadIdChange,\n }),\n [\n options.adapter,\n options.allowNesting,\n options.threadId,\n stableRuntimeHook,\n ],\n );\n\n const aui = useAui();\n const isNested = aui.threadListItem.source !== null;\n\n if (isNested) {\n if (!stableOptions.allowNesting) {\n throw new Error(\n \"useRemoteThreadListRuntime cannot be nested inside another RemoteThreadListRuntime. \" +\n \"Set allowNesting: true to allow nesting (the inner runtime will become a no-op).\",\n );\n }\n\n // If allowNesting is true and already inside a thread list context,\n // just call the runtimeHook directly (no-op behavior)\n return options.runtimeHook();\n }\n\n const runtime = useRemoteThreadListRuntimeImpl(stableOptions);\n\n return runtime;\n};\n"],"mappings":";;;;;;;;;AAmBA,IAAMgB,8BAAN,cACUT,yBAEV;CACE;CAEAW,YAAYC,SAAkC;EAC5C,MAAM;EACN,KAAKF,UAAU,IAAIL,sCACjBO,SACA,KAAKC,gBACP;CACF;CAEA,IAAWC,kBAAkB;EAC3B,OAAO,KAAKJ,QAAQK;CACtB;AACF;AAEA,MAAMC,kCAAiCJ,YAAA;CAAA,MAAAK,IAAAC,EAAA,EAAA;CAAA,IAAAC;CAAA,IAAAF,EAAA,OAAAL,SAAA;EAGVO,WAAM,IAAIV,4BAA4BG,OAAO;EAACK,EAAA,KAAAL;EAAAK,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAzE,MAAA,CAAAG,WAAkB3B,SAAS0B,EAA8C;CAAE,IAAAE;CAAA,IAAAJ,EAAA,OAAAG,QAAAV,SAAA;EAOzEW,iBAAYC,qBAAqBF,QAAOV,QAAQa,mBAAoB,CAAC;EAACN,EAAA,KAAAG,QAAAV;EAAAO,EAAA,KAAAI;CAAA,OAAAA,KAAAJ,EAAA;CAAA,IAAAO;CAAA,IAAAP,EAAA,OAAAG,SAAA;EACtEI,KAAA,CAACJ,OAAO;EAACH,EAAA,KAAAG;EAAAH,EAAA,KAAAO;CAAA,OAAAA,K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41
41
|
* `display: "standalone"`). Resolving the registry-driven cases reads the
|
|
42
42
|
* {@link GroupByContext} passed to the `groupBy` function. Takes precedence
|
|
43
43
|
* over the `"tool-call"` entry.
|
|
44
|
+
*
|
|
45
|
+
* A `"tool-call:<name>"` entry matches tool calls by tool name and takes precedence over the plain `"tool-call"` entry, while `"standalone-tool-call"` still wins first.
|
|
44
46
|
*/
|
|
45
|
-
type GroupPartType = PartState["type"] | "standalone-tool-call"
|
|
47
|
+
type GroupPartType = PartState["type"] | "standalone-tool-call" | `tool-call:${string}`;
|
|
46
48
|
/**
|
|
47
49
|
* Build a `groupBy` from a `part.type → group-key path` lookup.
|
|
48
50
|
* Parts whose type isn't in the map are left ungrouped. The returned
|
|
@@ -56,11 +58,14 @@ type GroupPartType = PartState["type"] | "standalone-tool-call";
|
|
|
56
58
|
* {@link GroupByContext} that `<MessagePrimitive.GroupedParts>` passes to the
|
|
57
59
|
* `groupBy` function — the helper needs nothing threaded into it.
|
|
58
60
|
*
|
|
61
|
+
* A `"tool-call:<name>"` entry matches tool calls by tool name and takes precedence over the plain `"tool-call"` entry, while `"standalone-tool-call"` still wins first.
|
|
62
|
+
*
|
|
59
63
|
* @example
|
|
60
64
|
* ```tsx
|
|
61
65
|
* <MessagePrimitive.GroupedParts
|
|
62
66
|
* groupBy={groupPartByType({
|
|
63
67
|
* reasoning: ["group-thought", "group-reasoning"],
|
|
68
|
+
* "tool-call:task": ["group-subagents"],
|
|
64
69
|
* "tool-call": ["group-thought", "group-tool"],
|
|
65
70
|
* "standalone-tool-call": [],
|
|
66
71
|
* })}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupParts.d.ts","names":[],"sources":["../../../src/react/utils/groupParts.ts"],"mappings":";;;;;;;;;KAUY;;WAED,UAAU;;;;;;;;;;;;;;;;;;;;cAsBR
|
|
1
|
+
{"version":3,"file":"groupParts.d.ts","names":[],"sources":["../../../src/react/utils/groupParts.ts"],"mappings":";;;;;;;;;KAUY;;WAED,UAAU;;;;;;;;;;;;;;;;;;;;cAsBR;;;;;;;;;;;;;;;KAkBR,gBACD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAiCS,kBAAmB,gCAC9B,KAAK,QAAQ,SAAS,OAAO,wBAAwB,gBAClD,MAAM,WAAW,UAAU,4BAA4B;KA8BhD,YAAY,iBAAiB;UAExB;WACN;;WAEA;;WAEA;;;;;WAKA;;WAEA;WACA,mBAAmB;;UAGb;WACN;;WAEA;;WAEA;;;;;WAKA;;;;;;;;;cAiCE,iBACX,uCACA,uDACU"}
|
|
@@ -32,11 +32,14 @@ const GROUPBY_MEMO_KEY = Symbol.for("@assistant-ui/groupBy.memoKey");
|
|
|
32
32
|
* {@link GroupByContext} that `<MessagePrimitive.GroupedParts>` passes to the
|
|
33
33
|
* `groupBy` function — the helper needs nothing threaded into it.
|
|
34
34
|
*
|
|
35
|
+
* A `"tool-call:<name>"` entry matches tool calls by tool name and takes precedence over the plain `"tool-call"` entry, while `"standalone-tool-call"` still wins first.
|
|
36
|
+
*
|
|
35
37
|
* @example
|
|
36
38
|
* ```tsx
|
|
37
39
|
* <MessagePrimitive.GroupedParts
|
|
38
40
|
* groupBy={groupPartByType({
|
|
39
41
|
* reasoning: ["group-thought", "group-reasoning"],
|
|
42
|
+
* "tool-call:task": ["group-subagents"],
|
|
40
43
|
* "tool-call": ["group-thought", "group-tool"],
|
|
41
44
|
* "standalone-tool-call": [],
|
|
42
45
|
* })}
|
|
@@ -50,6 +53,9 @@ const groupPartByType = (map) => {
|
|
|
50
53
|
const fn = ((part, context) => {
|
|
51
54
|
if (part.type === "tool-call") {
|
|
52
55
|
if ((isMcpAppUri(part.mcp?.app?.resourceUri) || (context?.toolUIs?.[part.toolName]?.[0]?.standalone ?? false)) && lookup["standalone-tool-call"] !== void 0) return lookup["standalone-tool-call"];
|
|
56
|
+
const toolCallPath = lookup[`tool-call:${part.toolName}`];
|
|
57
|
+
if (toolCallPath !== void 0) return toolCallPath;
|
|
58
|
+
return lookup["tool-call"] ?? [];
|
|
53
59
|
}
|
|
54
60
|
return lookup[part.type] ?? [];
|
|
55
61
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"groupParts.js","names":["isMcpAppUri","PartState","ToolsState","GroupByContext","toolUIs","GROUPBY_MEMO_KEY","Symbol","for","GroupPartType","groupPartByType","map","Partial","Readonly","Record","TKey","part","context","lookup","fn","type","isMcpApp","mcp","app","resourceUri","isStandalone","toolName","standalone","undefined","sortedKeys","Object","keys","sort","sortedEntries","k","JSON","stringify","GroupNode","GroupNodeGroup","GroupNodePart","key","nodeKey","idKey","indices","children","index","BuildFrame","nextChildIdx","claimed","Set","makeChildNodeKey","parent","idx","String","claimIdKey","frame","id","has","add","buildGroupTree","paths","partIds","root","stack","closeTop","closing","pop","length","push","i","path","common","top","s"],"sources":["../../../src/react/utils/groupParts.ts"],"sourcesContent":["import { isMcpAppUri } from \"../../types/message\";\nimport type { PartState } from \"../../store/scopes/part\";\nimport type { ToolsState } from \"../types/scopes/tools\";\n\n/**\n * Registry context passed to a `groupBy` function as its second argument by\n * `<MessagePrimitive.GroupedParts>`. Carries the live tool-UI registry so a\n * `groupBy` can resolve registry-driven grouping (e.g. standalone tool calls)\n * without the part itself having to carry that information.\n */\nexport type GroupByContext = {\n /** Tool UIs registered in the tool-UI registry, keyed by tool name. */\n readonly toolUIs?: ToolsState[\"toolUIs\"];\n};\n\n/**\n * Hierarchical adjacent-coalescing grouping for message parts.\n *\n * Given a group path per part (from `groupBy`), builds a tree of group\n * nodes wrapping individual parts. Adjacent parts sharing a path prefix\n * coalesce into the same group; ungrouped parts are direct children of\n * the root.\n *\n * Each node gets a structural `nodeKey` built from sibling indices\n * (`\"0.1.0\"`), stable under append-only streaming.\n */\n\n/**\n * Symbol attached to memoizable `groupBy` functions (e.g. those returned\n * by {@link groupPartByType}). Carries a string fingerprint of the config\n * so `MessagePrimitive.GroupedParts` can memo the tree on\n * `[parts, memoKey]` across renders — even when the helper call site\n * reconstructs the function each render.\n */\nexport const GROUPBY_MEMO_KEY: unique symbol = Symbol.for(\n \"@assistant-ui/groupBy.memoKey\",\n);\n\n/**\n * Synthetic part-type keys recognized by {@link groupPartByType}, in\n * addition to real {@link PartState} types:\n *\n * - `\"standalone-tool-call\"` — a tool-call whose UI should be presented on its\n * own, outside the chain-of-thought grouping. Matches MCP-app tool calls plus\n * any tool-call whose registered UI opts into standalone display (human\n * tools, the built-in generative-UI tool, and tools that set\n * `display: \"standalone\"`). Resolving the registry-driven cases reads the\n * {@link GroupByContext} passed to the `groupBy` function. Takes precedence\n * over the `\"tool-call\"` entry.\n */\ntype GroupPartType = PartState[\"type\"] | \"standalone-tool-call\";\n\n/**\n * Build a `groupBy` from a `part.type → group-key path` lookup.\n * Parts whose type isn't in the map are left ungrouped. The returned\n * function carries a stable {@link GROUPBY_MEMO_KEY} fingerprint so\n * `<MessagePrimitive.GroupedParts>` can memoize its tree across renders.\n *\n * The synthetic `\"standalone-tool-call\"` key matches tool calls that should\n * render outside the chain-of-thought grouping. MCP-app calls are detected from\n * the part alone; the registry-driven cases (human tools, the generative-UI\n * tool, `display: \"standalone\"` opt-ins) are resolved from the\n * {@link GroupByContext} that `<MessagePrimitive.GroupedParts>` passes to the\n * `groupBy` function — the helper needs nothing threaded into it.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * \"standalone-tool-call\": [],\n * })}\n * >\n * {({ part, children }) => { ... }}\n * </MessagePrimitive.GroupedParts>\n * ```\n */\nexport const groupPartByType = <TKey extends `group-${string}`>(\n map: Partial<Readonly<Record<GroupPartType, readonly TKey[]>>>,\n): ((part: PartState, context?: GroupByContext) => readonly TKey[]) => {\n const lookup = map as Readonly<Record<string, readonly TKey[] | undefined>>;\n const fn = ((part, context) => {\n if (part.type === \"tool-call\") {\n const isMcpApp = isMcpAppUri(part.mcp?.app?.resourceUri);\n // Read the first registration's flag — the same one `resolveToolRender`\n // renders — so grouping and rendering never disagree for a tool name.\n const isStandalone =\n isMcpApp ||\n (context?.toolUIs?.[part.toolName]?.[0]?.standalone ?? false);\n if (isStandalone && lookup[\"standalone-tool-call\"] !== undefined) {\n return lookup[\"standalone-tool-call\"]!;\n }\n }\n return lookup[part.type] ?? [];\n }) as ((part: PartState, context?: GroupByContext) => readonly TKey[]) & {\n [GROUPBY_MEMO_KEY]?: string;\n };\n // Sort keys so the fingerprint is insensitive to map insertion order —\n // two maps with the same key/value pairs but different declaration order\n // would otherwise hash differently and invalidate the memo unnecessarily.\n const sortedKeys = Object.keys(map).sort();\n const sortedEntries = sortedKeys.map((k) => [k, map[k as keyof typeof map]]);\n fn[GROUPBY_MEMO_KEY] = `groupPartByType:${JSON.stringify(sortedEntries)}`;\n return fn;\n};\n\nexport type GroupNode = GroupNodeGroup | GroupNodePart;\n\nexport interface GroupNodeGroup {\n readonly type: \"group\";\n /** Current-level group key (last segment of the path). */\n readonly key: string;\n /** Structural React key: sibling-index path, e.g. `\"0.1.0\"`. */\n readonly nodeKey: string;\n /**\n * Identity key (`\"id:<partId>\"`) from the group's first part; undefined\n * when absent or already claimed by an earlier sibling.\n */\n readonly idKey: string | undefined;\n /** Indices of parts in this subtree, in order. */\n readonly indices: readonly number[];\n readonly children: readonly GroupNode[];\n}\n\nexport interface GroupNodePart {\n readonly type: \"part\";\n /** Index of the part in the message. */\n readonly index: number;\n /** Structural React key: sibling-index path within parent. */\n readonly nodeKey: string;\n /**\n * Identity key (`\"id:<partId>\"`); undefined when absent or already\n * claimed by an earlier sibling.\n */\n readonly idKey: string | undefined;\n}\n\ninterface BuildFrame {\n key: string;\n nodeKey: string;\n indices: number[];\n children: GroupNode[];\n nextChildIdx: number;\n claimed: Set<string>;\n}\n\nconst makeChildNodeKey = (parent: BuildFrame): string => {\n const idx = parent.nextChildIdx++;\n return parent.nodeKey === \"\" ? String(idx) : `${parent.nodeKey}.${idx}`;\n};\n\nconst claimIdKey = (\n frame: BuildFrame,\n id: string | undefined,\n): string | undefined => {\n if (id === undefined || frame.claimed.has(id)) return undefined;\n frame.claimed.add(id);\n return `id:${id}`;\n};\n\n/**\n * Build the group tree from an array of normalized group paths.\n * `paths[i]` is the path for part `i`. The output tree contains one\n * `part` node per part and one `group` node per coalesced run.\n * `partIds[i]` optionally carries a stable identity for part `i` (e.g. a\n * tool call id), from which nodes derive an `idKey`.\n */\nexport const buildGroupTree = (\n paths: readonly (readonly string[])[],\n partIds?: readonly (string | undefined)[],\n): readonly GroupNode[] => {\n const root: BuildFrame = {\n key: \"\",\n nodeKey: \"\",\n indices: [],\n children: [],\n nextChildIdx: 0,\n claimed: new Set(),\n };\n const stack: BuildFrame[] = [root];\n\n const closeTop = (): void => {\n const closing = stack.pop()!;\n const parent = stack[stack.length - 1]!;\n parent.children.push({\n type: \"group\",\n key: closing.key,\n nodeKey: closing.nodeKey,\n idKey: claimIdKey(parent, partIds?.[closing.indices[0]!]),\n indices: closing.indices,\n children: closing.children,\n });\n };\n\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i]!;\n\n // Find the longest prefix shared between currently-open groups\n // (excluding root) and this part's path.\n let common = 0;\n while (\n common < stack.length - 1 &&\n common < path.length &&\n stack[common + 1]!.key === path[common]\n ) {\n common++;\n }\n\n // Close groups not on this path.\n while (stack.length - 1 > common) {\n closeTop();\n }\n\n // Open new groups down to the part's depth.\n while (stack.length - 1 < path.length) {\n const parent = stack[stack.length - 1]!;\n stack.push({\n key: path[stack.length - 1]!,\n nodeKey: makeChildNodeKey(parent),\n indices: [],\n children: [],\n nextChildIdx: 0,\n claimed: new Set(),\n });\n }\n\n // Push this part as a leaf in the deepest open group (or root).\n const top = stack[stack.length - 1]!;\n top.children.push({\n type: \"part\",\n index: i,\n nodeKey: makeChildNodeKey(top),\n idKey: claimIdKey(top, partIds?.[i]),\n });\n\n // Record the part index in every open ancestor group.\n for (let s = 1; s < stack.length; s++) {\n stack[s]!.indices.push(i);\n }\n }\n\n // Close any still-open groups.\n while (stack.length > 1) {\n closeTop();\n }\n\n return root.children;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkCA,MAAaK,mBAAkCC,OAAOC,IACpD,+BACF;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAaE,mBACXC,QACqE;CACrE,MAAMO,SAASP;CACf,MAAMQ,OAAOH,MAAMC,YAAY;EAC7B,IAAID,KAAKI,SAAS,aACCnB;QAAAA,YAAYe,KAAKM,KAAKC,KAAKC,WAI1CH,MACCJ,SAASZ,UAAUW,KAAKU,SAAS,GAAG,EAAE,EAAEC,cAAc,WACrCT,OAAO,4BAA4BU,KAAAA,GACrD,OAAOV,OAAO;EAAA;EAGlB,OAAOA,OAAOF,KAAKI,SAAS,CAAA;CAC9B;CAOA,MAAMa,gBADaH,OAAOC,KAAKpB,GAAG,CAAC,CAACqB,KACdH,CAAU,CAAClB,KAAKuB,MAAM,CAACA,GAAGvB,IAAIuB,EAAsB,CAAC;CAC3Ef,GAAGb,oBAAoB,mBAAmB6B,KAAKC,UAAUH,aAAa;CACtE,OAAOd;AACT;AA0CA,MAAM+B,oBAAoBC,WAA+B;CACvD,MAAMC,MAAMD,OAAOJ;CACnB,OAAOI,OAAOV,YAAY,KAAKY,OAAOD,GAAG,IAAI,GAAGD,OAAOV,QAAO,GAAIW;AACpE;AAEA,MAAME,cACJC,OACAC,OACuB;CACvB,IAAIA,OAAO5B,KAAAA,KAAa2B,MAAMP,QAAQS,IAAID,EAAE,GAAG,OAAO5B,KAAAA;CACtD2B,MAAMP,QAAQU,IAAIF,EAAE;CACpB,OAAO,MAAMA;AACf;;;;;;;;AASA,MAAaG,kBACXC,OACAC,YACyB;CACzB,MAAMC,OAAmB;EACvBtB,KAAK;EACLC,SAAS;EACTE,SAAS,CAAA;EACTC,UAAU,CAAA;EACVG,cAAc;EACdC,yBAAS,IAAIC,IAAI;CACnB;CACA,MAAMc,QAAsB,CAACD,I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3,"file":"groupParts.js","names":["isMcpAppUri","PartState","ToolsState","GroupByContext","toolUIs","GROUPBY_MEMO_KEY","Symbol","for","GroupPartType","groupPartByType","map","Partial","Readonly","Record","TKey","part","context","lookup","fn","type","isMcpApp","mcp","app","resourceUri","isStandalone","toolName","standalone","undefined","toolCallPath","sortedKeys","Object","keys","sort","sortedEntries","k","JSON","stringify","GroupNode","GroupNodeGroup","GroupNodePart","key","nodeKey","idKey","indices","children","index","BuildFrame","nextChildIdx","claimed","Set","makeChildNodeKey","parent","idx","String","claimIdKey","frame","id","has","add","buildGroupTree","paths","partIds","root","stack","closeTop","closing","pop","length","push","i","path","common","top","s"],"sources":["../../../src/react/utils/groupParts.ts"],"sourcesContent":["import { isMcpAppUri } from \"../../types/message\";\nimport type { PartState } from \"../../store/scopes/part\";\nimport type { ToolsState } from \"../types/scopes/tools\";\n\n/**\n * Registry context passed to a `groupBy` function as its second argument by\n * `<MessagePrimitive.GroupedParts>`. Carries the live tool-UI registry so a\n * `groupBy` can resolve registry-driven grouping (e.g. standalone tool calls)\n * without the part itself having to carry that information.\n */\nexport type GroupByContext = {\n /** Tool UIs registered in the tool-UI registry, keyed by tool name. */\n readonly toolUIs?: ToolsState[\"toolUIs\"];\n};\n\n/**\n * Hierarchical adjacent-coalescing grouping for message parts.\n *\n * Given a group path per part (from `groupBy`), builds a tree of group\n * nodes wrapping individual parts. Adjacent parts sharing a path prefix\n * coalesce into the same group; ungrouped parts are direct children of\n * the root.\n *\n * Each node gets a structural `nodeKey` built from sibling indices\n * (`\"0.1.0\"`), stable under append-only streaming.\n */\n\n/**\n * Symbol attached to memoizable `groupBy` functions (e.g. those returned\n * by {@link groupPartByType}). Carries a string fingerprint of the config\n * so `MessagePrimitive.GroupedParts` can memo the tree on\n * `[parts, memoKey]` across renders — even when the helper call site\n * reconstructs the function each render.\n */\nexport const GROUPBY_MEMO_KEY: unique symbol = Symbol.for(\n \"@assistant-ui/groupBy.memoKey\",\n);\n\n/**\n * Synthetic part-type keys recognized by {@link groupPartByType}, in\n * addition to real {@link PartState} types:\n *\n * - `\"standalone-tool-call\"` — a tool-call whose UI should be presented on its\n * own, outside the chain-of-thought grouping. Matches MCP-app tool calls plus\n * any tool-call whose registered UI opts into standalone display (human\n * tools, the built-in generative-UI tool, and tools that set\n * `display: \"standalone\"`). Resolving the registry-driven cases reads the\n * {@link GroupByContext} passed to the `groupBy` function. Takes precedence\n * over the `\"tool-call\"` entry.\n *\n * A `\"tool-call:<name>\"` entry matches tool calls by tool name and takes precedence over the plain `\"tool-call\"` entry, while `\"standalone-tool-call\"` still wins first.\n */\ntype GroupPartType =\n | PartState[\"type\"]\n | \"standalone-tool-call\"\n | `tool-call:${string}`;\n\n/**\n * Build a `groupBy` from a `part.type → group-key path` lookup.\n * Parts whose type isn't in the map are left ungrouped. The returned\n * function carries a stable {@link GROUPBY_MEMO_KEY} fingerprint so\n * `<MessagePrimitive.GroupedParts>` can memoize its tree across renders.\n *\n * The synthetic `\"standalone-tool-call\"` key matches tool calls that should\n * render outside the chain-of-thought grouping. MCP-app calls are detected from\n * the part alone; the registry-driven cases (human tools, the generative-UI\n * tool, `display: \"standalone\"` opt-ins) are resolved from the\n * {@link GroupByContext} that `<MessagePrimitive.GroupedParts>` passes to the\n * `groupBy` function — the helper needs nothing threaded into it.\n *\n * A `\"tool-call:<name>\"` entry matches tool calls by tool name and takes precedence over the plain `\"tool-call\"` entry, while `\"standalone-tool-call\"` still wins first.\n *\n * @example\n * ```tsx\n * <MessagePrimitive.GroupedParts\n * groupBy={groupPartByType({\n * reasoning: [\"group-thought\", \"group-reasoning\"],\n * \"tool-call:task\": [\"group-subagents\"],\n * \"tool-call\": [\"group-thought\", \"group-tool\"],\n * \"standalone-tool-call\": [],\n * })}\n * >\n * {({ part, children }) => { ... }}\n * </MessagePrimitive.GroupedParts>\n * ```\n */\nexport const groupPartByType = <TKey extends `group-${string}`>(\n map: Partial<Readonly<Record<GroupPartType, readonly TKey[]>>>,\n): ((part: PartState, context?: GroupByContext) => readonly TKey[]) => {\n const lookup = map as Readonly<Record<string, readonly TKey[] | undefined>>;\n const fn = ((part, context) => {\n if (part.type === \"tool-call\") {\n const isMcpApp = isMcpAppUri(part.mcp?.app?.resourceUri);\n // Read the first registration's flag — the same one `resolveToolRender`\n // renders — so grouping and rendering never disagree for a tool name.\n const isStandalone =\n isMcpApp ||\n (context?.toolUIs?.[part.toolName]?.[0]?.standalone ?? false);\n if (isStandalone && lookup[\"standalone-tool-call\"] !== undefined) {\n return lookup[\"standalone-tool-call\"]!;\n }\n const toolCallPath = lookup[`tool-call:${part.toolName}`];\n if (toolCallPath !== undefined) return toolCallPath;\n return lookup[\"tool-call\"] ?? [];\n }\n return lookup[part.type] ?? [];\n }) as ((part: PartState, context?: GroupByContext) => readonly TKey[]) & {\n [GROUPBY_MEMO_KEY]?: string;\n };\n // Sort keys so the fingerprint is insensitive to map insertion order —\n // two maps with the same key/value pairs but different declaration order\n // would otherwise hash differently and invalidate the memo unnecessarily.\n const sortedKeys = Object.keys(map).sort();\n const sortedEntries = sortedKeys.map((k) => [k, map[k as keyof typeof map]]);\n fn[GROUPBY_MEMO_KEY] = `groupPartByType:${JSON.stringify(sortedEntries)}`;\n return fn;\n};\n\nexport type GroupNode = GroupNodeGroup | GroupNodePart;\n\nexport interface GroupNodeGroup {\n readonly type: \"group\";\n /** Current-level group key (last segment of the path). */\n readonly key: string;\n /** Structural React key: sibling-index path, e.g. `\"0.1.0\"`. */\n readonly nodeKey: string;\n /**\n * Identity key (`\"id:<partId>\"`) from the group's first part; undefined\n * when absent or already claimed by an earlier sibling.\n */\n readonly idKey: string | undefined;\n /** Indices of parts in this subtree, in order. */\n readonly indices: readonly number[];\n readonly children: readonly GroupNode[];\n}\n\nexport interface GroupNodePart {\n readonly type: \"part\";\n /** Index of the part in the message. */\n readonly index: number;\n /** Structural React key: sibling-index path within parent. */\n readonly nodeKey: string;\n /**\n * Identity key (`\"id:<partId>\"`); undefined when absent or already\n * claimed by an earlier sibling.\n */\n readonly idKey: string | undefined;\n}\n\ninterface BuildFrame {\n key: string;\n nodeKey: string;\n indices: number[];\n children: GroupNode[];\n nextChildIdx: number;\n claimed: Set<string>;\n}\n\nconst makeChildNodeKey = (parent: BuildFrame): string => {\n const idx = parent.nextChildIdx++;\n return parent.nodeKey === \"\" ? String(idx) : `${parent.nodeKey}.${idx}`;\n};\n\nconst claimIdKey = (\n frame: BuildFrame,\n id: string | undefined,\n): string | undefined => {\n if (id === undefined || frame.claimed.has(id)) return undefined;\n frame.claimed.add(id);\n return `id:${id}`;\n};\n\n/**\n * Build the group tree from an array of normalized group paths.\n * `paths[i]` is the path for part `i`. The output tree contains one\n * `part` node per part and one `group` node per coalesced run.\n * `partIds[i]` optionally carries a stable identity for part `i` (e.g. a\n * tool call id), from which nodes derive an `idKey`.\n */\nexport const buildGroupTree = (\n paths: readonly (readonly string[])[],\n partIds?: readonly (string | undefined)[],\n): readonly GroupNode[] => {\n const root: BuildFrame = {\n key: \"\",\n nodeKey: \"\",\n indices: [],\n children: [],\n nextChildIdx: 0,\n claimed: new Set(),\n };\n const stack: BuildFrame[] = [root];\n\n const closeTop = (): void => {\n const closing = stack.pop()!;\n const parent = stack[stack.length - 1]!;\n parent.children.push({\n type: \"group\",\n key: closing.key,\n nodeKey: closing.nodeKey,\n idKey: claimIdKey(parent, partIds?.[closing.indices[0]!]),\n indices: closing.indices,\n children: closing.children,\n });\n };\n\n for (let i = 0; i < paths.length; i++) {\n const path = paths[i]!;\n\n // Find the longest prefix shared between currently-open groups\n // (excluding root) and this part's path.\n let common = 0;\n while (\n common < stack.length - 1 &&\n common < path.length &&\n stack[common + 1]!.key === path[common]\n ) {\n common++;\n }\n\n // Close groups not on this path.\n while (stack.length - 1 > common) {\n closeTop();\n }\n\n // Open new groups down to the part's depth.\n while (stack.length - 1 < path.length) {\n const parent = stack[stack.length - 1]!;\n stack.push({\n key: path[stack.length - 1]!,\n nodeKey: makeChildNodeKey(parent),\n indices: [],\n children: [],\n nextChildIdx: 0,\n claimed: new Set(),\n });\n }\n\n // Push this part as a leaf in the deepest open group (or root).\n const top = stack[stack.length - 1]!;\n top.children.push({\n type: \"part\",\n index: i,\n nodeKey: makeChildNodeKey(top),\n idKey: claimIdKey(top, partIds?.[i]),\n });\n\n // Record the part index in every open ancestor group.\n for (let s = 1; s < stack.length; s++) {\n stack[s]!.indices.push(i);\n }\n }\n\n // Close any still-open groups.\n while (stack.length > 1) {\n closeTop();\n }\n\n return root.children;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAkCA,MAAaK,mBAAkCC,OAAOC,IACpD,+BACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAaE,mBACXC,QACqE;CACrE,MAAMO,SAASP;CACf,MAAMQ,OAAOH,MAAMC,YAAY;EAC7B,IAAID,KAAKI,SAAS,aAAa;GAO7B,KANiBnB,YAAYe,KAAKM,KAAKC,KAAKC,WAI1CH,MACCJ,SAASZ,UAAUW,KAAKU,SAAS,GAAG,EAAE,EAAEC,cAAc,WACrCT,OAAO,4BAA4BU,KAAAA,GACrD,OAAOV,OAAO;GAEhB,MAAMW,eAAeX,OAAO,aAAaF,KAAKU;GAC9C,IAAIG,iBAAiBD,KAAAA,GAAW,OAAOC;GACvC,OAAOX,OAAO,gBAAgB,CAAA;EAChC;EACA,OAAOA,OAAOF,KAAKI,SAAS,CAAA;CAC9B;CAOA,MAAMc,gBADaH,OAAOC,KAAKrB,GAAG,CAAC,CAACsB,KACdH,CAAU,CAACnB,KAAKwB,MAAM,CAACA,GAAGxB,IAAIwB,EAAsB,CAAC;CAC3EhB,GAAGb,oBAAoB,mBAAmB8B,KAAKC,UAAUH,aAAa;CACtE,OAAOf;AACT;AA0CA,MAAMgC,oBAAoBC,WAA+B;CACvD,MAAMC,MAAMD,OAAOJ;CACnB,OAAOI,OAAOV,YAAY,KAAKY,OAAOD,GAAG,IAAI,GAAGD,OAAOV,QAAO,GAAIW;AACpE;AAEA,MAAME,cACJC,OACAC,OAC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EACjCK,IAAI5B,SAASwB,KAAK;GAChBjD,MAAM;GACN0B,OAAOwB;GACP5B,SAASS,iBAAiBsB,GAAG;GAC7B9B,OAAOY,WAAWkB,KAAKX,UAAUQ,EAAE;EACrC,CAAC;EAGD,KAAK,IAAII,IAAI,GAAGA,IAAIV,MAAMI,QAAQM,KAChCV,MAAMU,EAAE,CAAE9B,QAAQyB,KAAKC,CAAC;CAE5B;CAGA,OAAON,MAAMI,SAAS,GACpBH,SAAS;CAGX,OAAOF,KAAKlB;AACd"}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
1
2
|
//#region src/react/utils/useJSONEqual.d.ts
|
|
3
|
+
declare function useJSONEqualValue<T extends ReadonlyJSONValue>(value: T): T;
|
|
2
4
|
/**
|
|
3
5
|
* Like `useShallow`, but with JSON deep-equality. Use when a selector derives an
|
|
4
6
|
* equal-but-fresh value on every store update — e.g. folding over
|
|
@@ -7,5 +9,5 @@
|
|
|
7
9
|
*/
|
|
8
10
|
declare function useJSONEqual<S, U>(selector: (state: S) => U): (state: S) => U;
|
|
9
11
|
//#endregion
|
|
10
|
-
export { useJSONEqual };
|
|
12
|
+
export { useJSONEqual, useJSONEqualValue };
|
|
11
13
|
//# sourceMappingURL=useJSONEqual.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useJSONEqual.d.ts","names":[],"sources":["../../../src/react/utils/useJSONEqual.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"useJSONEqual.d.ts","names":[],"sources":["../../../src/react/utils/useJSONEqual.ts"],"mappings":";;iBAIgB,kBAAkB,UAAU,mBAAmB,OAAO,IAAI;;;;;;;iBAc1D,aAAa,GAAG,GAAG,WAAW,OAAO,MAAM,KAAK,OAAO,MAAM"}
|
|
@@ -2,6 +2,11 @@ import { isJSONValueEqual } from "../../utils/json/is-json-equal.js";
|
|
|
2
2
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
3
3
|
import { useRef } from "@assistant-ui/tap/react-shim";
|
|
4
4
|
//#region src/react/utils/useJSONEqual.ts
|
|
5
|
+
function useJSONEqualValue(value) {
|
|
6
|
+
const prev = useRef(value);
|
|
7
|
+
if (prev.current !== value && !isJSONValueEqual(prev.current, value)) prev.current = value;
|
|
8
|
+
return prev.current;
|
|
9
|
+
}
|
|
5
10
|
/**
|
|
6
11
|
* Like `useShallow`, but with JSON deep-equality. Use when a selector derives an
|
|
7
12
|
* equal-but-fresh value on every store update — e.g. folding over
|
|
@@ -25,6 +30,6 @@ function useJSONEqual(selector) {
|
|
|
25
30
|
return t0;
|
|
26
31
|
}
|
|
27
32
|
//#endregion
|
|
28
|
-
export { useJSONEqual };
|
|
33
|
+
export { useJSONEqual, useJSONEqualValue };
|
|
29
34
|
|
|
30
35
|
//# sourceMappingURL=useJSONEqual.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useJSONEqual.js","names":["useRef","isJSONValueEqual","useJSONEqual","selector","$","_c","
|
|
1
|
+
{"version":3,"file":"useJSONEqual.js","names":["useRef","ReadonlyJSONValue","isJSONValueEqual","useJSONEqualValue","value","T","prev","current","useJSONEqual","selector","$","_c","undefined","t0","state","next"],"sources":["../../../src/react/utils/useJSONEqual.ts"],"sourcesContent":["import { useRef } from \"react\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { isJSONValueEqual } from \"../../utils/json/is-json-equal\";\n\nexport function useJSONEqualValue<T extends ReadonlyJSONValue>(value: T): T {\n const prev = useRef(value);\n if (prev.current !== value && !isJSONValueEqual(prev.current, value)) {\n prev.current = value;\n }\n return prev.current;\n}\n\n/**\n * Like `useShallow`, but with JSON deep-equality. Use when a selector derives an\n * equal-but-fresh value on every store update — e.g. folding over\n * `thread.messages`, whose identity changes on every streaming token — where a\n * shallow compare would re-render regardless.\n */\nexport function useJSONEqual<S, U>(selector: (state: S) => U): (state: S) => U {\n const prev = useRef<U | undefined>(undefined);\n return (state) => {\n const next = selector(state);\n if (prev.current !== undefined && isJSONValueEqual(prev.current, next)) {\n return prev.current;\n }\n prev.current = next;\n return next;\n };\n}\n"],"mappings":";;;;AAIA,SAAgBG,kBAA+CC,OAAa;CAC1E,MAAME,OAAON,OAAOI,KAAK;CACzB,IAAIE,KAAKC,YAAYH,SAAS,CAACF,iBAAiBI,KAAKC,SAASH,KAAK,GACjEE,KAAKC,UAAUH;CAEjB,OAAOE,KAAKC;AACd;;;;;;;AAQA,SAAOC,aAAAC,UAAA;CAAA,MAAAC,IAAAC,EAAA,CAAA;CACL,MAAAL,OAAaN,OAAsBY,KAAAA,CAAS;CAAE,IAAAC;CAAA,IAAAH,EAAA,OAAAD,UAAA;EACvCI,MAAAC,UAAA;GACL,MAAAC,OAAaN,SAASK,KAAK;GAC3B,IAAIR,KAAIC,YAAaK,KAAAA,KAAaV,iBAAiBI,KAAIC,SAAUQ,IAAI,GAAC,OAC7DT,KAAIC;GAEbD,KAAIC,UAAWQ;GAAH,OACLA;EAAI;EACZL,EAAA,KAAAD;EAAAC,EAAA,KAAAG;CAAA,OAAAA,KAAAH,EAAA;CAAA,OAPMG;AAON"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Unstable_InteractableStateSchema } from "../types/scopes/interactables.js";
|
|
2
|
+
import { ReadonlyJSONValue } from "assistant-stream/utils";
|
|
3
|
+
//#region src/react/utils/useJSONSchemaDependency.d.ts
|
|
4
|
+
declare function useJSONSchemaDependency(schema: Unstable_InteractableStateSchema): ReadonlyJSONValue;
|
|
5
|
+
//#endregion
|
|
6
|
+
export { useJSONSchemaDependency };
|
|
7
|
+
//# sourceMappingURL=useJSONSchemaDependency.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useJSONSchemaDependency.d.ts","names":[],"sources":["../../../src/react/utils/useJSONSchemaDependency.ts"],"mappings":";;;iBAOgB,wBACd,QAAQ,mCACP"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { isJSONValue } from "../../utils/json/is-json.js";
|
|
2
|
+
import { useJSONEqualValue } from "./useJSONEqual.js";
|
|
3
|
+
import { toJSONSchema } from "assistant-stream";
|
|
4
|
+
import { useMemo } from "@assistant-ui/tap/react-shim";
|
|
5
|
+
//#region src/react/utils/useJSONSchemaDependency.ts
|
|
6
|
+
function useJSONSchemaDependency(schema) {
|
|
7
|
+
const normalizedSchema = useMemo(() => {
|
|
8
|
+
try {
|
|
9
|
+
const jsonSchema = toJSONSchema(schema);
|
|
10
|
+
return isJSONValue(jsonSchema) ? jsonSchema : null;
|
|
11
|
+
} catch {
|
|
12
|
+
return null;
|
|
13
|
+
}
|
|
14
|
+
}, [schema]);
|
|
15
|
+
return useJSONEqualValue(normalizedSchema);
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
export { useJSONSchemaDependency };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=useJSONSchemaDependency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useJSONSchemaDependency.js","names":["useMemo","toJSONSchema","ReadonlyJSONValue","isJSONValue","Unstable_InteractableStateSchema","useJSONEqualValue","useJSONSchemaDependency","schema","normalizedSchema","jsonSchema"],"sources":["../../../src/react/utils/useJSONSchemaDependency.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport { toJSONSchema } from \"assistant-stream\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\nimport { isJSONValue } from \"../../utils/json/is-json\";\nimport type { Unstable_InteractableStateSchema } from \"../types/scopes/interactables\";\nimport { useJSONEqualValue } from \"./useJSONEqual\";\n\nexport function useJSONSchemaDependency(\n schema: Unstable_InteractableStateSchema,\n): ReadonlyJSONValue {\n const normalizedSchema = useMemo(() => {\n try {\n const jsonSchema = toJSONSchema(schema);\n return isJSONValue(jsonSchema) ? jsonSchema : null;\n } catch {\n // Opaque schemas share one fallback so rebuilt instances do not churn registration.\n return null;\n }\n }, [schema]);\n\n return useJSONEqualValue(normalizedSchema);\n}\n"],"mappings":";;;;;AAOA,SAAgBM,wBACdC,QACmB;CACnB,MAAMC,mBAAmBR,cAAc;EACrC,IAAI;GACF,MAAMS,aAAaR,aAAaM,MAAM;GACtC,OAAOJ,YAAYM,UAAU,IAAIA,aAAa;EAChD,QAAQ;GAEN,OAAO;EACT;CACF,GAAG,CAACF,MAAM,CAAC;CAEX,OAAOF,kBAAkBG,gBAAgB;AAC3C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"thread-runtime.d.ts","names":[],"sources":["../../../src/runtime/api/thread-runtime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;KAgDY;EACV;EACA;EACA,YAAY;;KAGF,wBAAwB;EAClC,UACE,SAAS,wBACN,eAAe;;KAoBV;;;;;EAON;EACA;EACA,OAAO;EACP,SAAS;EACT,cAAc;EACd,WAAW;EACX,YAAY;EACZ,YAAY;EACZ;;KAoCM,2BAA2B,sBACrC,mBACA;EAEA,eAAe,uBAAuB;;KAG5B,+BAA+B,sBACzC,qBACA;KAGU;;;;;WAKD;;;;;;WAOA,UAAU;;;;WAKV;;;;WAKA;;;;WAKA;;;;WAKA,cAAc;;;;WAKd,mBAAmB;;;;;;WAOnB,OAAO;;;;WAKP,sBAAsB;;;;WAKtB;;;;WAKA,QAAQ;WAER,OAAO;;;;;;cAOL,gCACX,SAAS,KAAK;cASH,iBACX,SAAS,mBACT,qBAAqB,wBACpB;KAiBS;;;;WAID,MAAM;;;;WAKN,UAAU;;;;EAKnB,YAAY;;;;;;;;;;;;;;;;;EAkBZ,OAAO,SAAS;EAEhB,cAAc,2BAA2B;;;;;EAMzC,SAAS,QAAQ;;;;;EAMjB,UAAU,QAAQ;;;;;;;EAQlB;;;;;;;EAQA,oBAAoB;EAEpB,UAAU,uBAAuB;EACjC;;;;;;;EAOA;EACA,mBAAmB;EAEnB,UAAU;EACV,OAAO,YAAY;;;;;;EAOnB,MAAM,2BAA2B;EAEjC,kBAAkB,cAAc;EAChC,eAAe,oBAAoB;;;;EAKnC;EAEA;EACA;EACA;EACA,qBAAqB,uBAAuB;EAC5C;EACA;EAEA,YAAY,UAAU,wBACpB,OAAO,GACP,UAAU,2BAA2B,KACpC;;cAGQ,6BAA6B;MAC7B,QAAI;MAIJ,4BAJI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QAvQL,OAAA;;wBAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;IAkDc,eAAA,uBAAa;;IA8NnB,iBAAA;;mBADF;mBAGA;EAMf,YAAA,eAAe,0BACf,uBAAuB;YAwCf;WA4BM,UAAQ;EAEjB,YAAQ;EAIR,OAAO,SAAS;EAchB,cAAc,2BAAiB;EAI/B,UAAU;EAIV,mBAAe;EAIf,SAAS,QAAQ;EAIjB,UAAU,QAAQ;EAIlB;EAIA,oBAAoB;EAIpB;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA,qBAAqB,uBAAoB;EAIzC;EAIA;EAIA,UAAM;EAIN,OAAO,MAAM;EAIb,MAAM,2BAA2B;EAIjC,kBAAkB,cAAW;EAsB7B,eAAe,oBAAiB;UAW/B;UA2CA;EAKD,YAAY,UAAU,wBAC3B,OAAO,GACP,UAAU,2BAA2B,KACpC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EventSubscriptionSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject } from "../../subscribable/subscribable.js";
|
|
1
|
+
import { EventSubscriptionSubject, NestedSubscriptionSubject, SKIP_UPDATE, ShallowMemoizeSubject, runCleanups } from "../../subscribable/subscribable.js";
|
|
2
2
|
import { isMessageNotSentError } from "../../types/error.js";
|
|
3
3
|
import { symbolInnerMessage } from "../utils/external-store-message.js";
|
|
4
4
|
import { ThreadComposerRuntimeImpl } from "./composer-runtime.js";
|
|
@@ -86,10 +86,7 @@ var ThreadRuntimeImpl = class {
|
|
|
86
86
|
subscribe: (callback) => {
|
|
87
87
|
const sub1 = threadBinding.subscribe(callback);
|
|
88
88
|
const sub2 = threadListItemBinding.subscribe(callback);
|
|
89
|
-
return () =>
|
|
90
|
-
sub1();
|
|
91
|
-
sub2();
|
|
92
|
-
};
|
|
89
|
+
return () => runCleanups([sub1, sub2]);
|
|
93
90
|
}
|
|
94
91
|
});
|
|
95
92
|
this._stateBinding = stateBinding;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"thread-runtime.js","names":["ThreadSuggestion","RuntimeCapabilities","ThreadRuntimeCore","SpeechState","VoiceSessionState","ThreadRuntimeEventCallback","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ExportedMessageRepository","ThreadMessageLike","MessageRuntime","MessageRuntimeImpl","MessageState","NestedSubscriptionSubject","ShallowMemoizeSubject","SKIP_UPDATE","SubscribableWithState","ThreadComposerRuntime","ThreadComposerRuntimeImpl","MessageRuntimePath","ThreadListItemRuntimePath","ThreadRuntimePath","ThreadListItemState","AppendMessage","ThreadMessage","Unsubscribe","isMessageNotSentError","RunConfig","EventSubscriptionSubject","symbolInnerMessage","ModelContext","ChatModelRunOptions","ChatModelRunResult","ReadonlyJSONValue","CreateStartRunConfig","parentId","sourceId","runConfig","CreateResumeRunConfig","stream","options","AsyncGenerator","toResumeRunConfig","message","toStartRunConfig","CreateAppendMessage","role","content","attachments","metadata","createdAt","Date","startRun","toAppendMessage","messages","at","id","type","text","custom","undefined","ThreadRuntimeCoreBinding","outerSubscribe","callback","ThreadListItemRuntimeBinding","ThreadState","threadId","isDisabled","isLoading","isRunning","capabilities","state","suggestions","extras","speech","voice","getThreadRuntimeCoreIsRunning","runtime","Pick","lastMessage","status","getThreadState","threadListItemState","Object","freeze","ThreadRuntime","path","composer","getState","append","deleteMessage","messageId","Promise","config","resumeRun","exportExternalState","importExternalState","subscribe","cancelRun","unstable_notifySessionReset","getModelContext","export","import","repository","reset","initialMessages","getMessageByIndex","idx","getMessageById","stopSpeaking","connectVoice","disconnectVoice","getVoiceVolume","subscribeVoiceVolume","muteVoice","unmuteVoice","unstable_on","event","E","ThreadRuntimeImpl","_threadBinding","__internal_threadBinding","getStateState","_stateBinding","constructor","threadBinding","threadListItemBinding","stateBinding","sub1","sub2","ref","composerSource","__internal_bindMethods","bind","task","resolve","catch","error","data","Error","_getMessageRuntime","messageSelector","index","JSON","stringify","speechState","thread","branches","getBranches","isLast","branchNumber","indexOf","branchCount","length","_eventSubscriptionSubjects","Map","subject","get","binding","set","payload"],"sources":["../../../src/runtime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { isMessageNotSentError } from \"../../types/error\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n /**\n * An omitted value or `undefined` selects the current tail.\n * `null` selects a root branch.\n */\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId:\n message.parentId === undefined\n ? (messages.at(-1)?.id ?? null)\n : message.parentId,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\n/**\n * The canonical `isRunning` derivation. A runtime that tracks run state itself\n * reports it directly; the rest fall back to the trailing assistant message.\n */\nexport const getThreadRuntimeCoreIsRunning = (\n runtime: Pick<ThreadRuntimeCore, \"isRunning\" | \"messages\">,\n): boolean => {\n if (runtime.isRunning !== undefined) return runtime.isRunning;\n const lastMessage = runtime.messages.at(-1);\n return (\n lastMessage?.role === \"assistant\" && lastMessage.status.type === \"running\"\n );\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning: getThreadRuntimeCoreIsRunning(runtime),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n deleteMessage(messageId: string): void | Promise<void>;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n /**\n * Notifies the runtime that the adapter discarded its backing session.\n * Clears session-scoped tool-invocation state without run-cancel side\n * effects such as composer draft restoration. Internal API for\n * external-store adapter authors.\n */\n unstable_notifySessionReset(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n\n connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n private readonly _stateBinding: ShallowMemoizeSubject<\n ThreadState,\n ThreadRuntimePath\n >;\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => {\n sub1();\n sub2();\n };\n },\n });\n\n this._stateBinding = stateBinding;\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.deleteMessage = this.deleteMessage.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.unstable_notifySessionReset =\n this.unstable_notifySessionReset.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\n }\n\n public readonly composer;\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n const task = this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n // An undispatched send is reported to the composer, so it is a control\n // signal rather than a failure to surface; every other rejection keeps\n // reaching the host untouched.\n void Promise.resolve(task).catch((error) => {\n if (!isMessageNotSentError(error)) throw error;\n });\n }\n\n public deleteMessage(messageId: string) {\n return this._threadBinding.getState().deleteMessage(messageId);\n }\n\n public subscribe(callback: () => void) {\n return this._stateBinding.subscribe(callback);\n }\n\n public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public unstable_notifySessionReset() {\n this._threadBinding.getState().unstable_notifySessionReset();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n}\n"],"mappings":";;;;;;AA2DA,MAAM2C,qBAAqBC,YAAoD;CAC7E,OAAO;EACLR,UAAUQ,QAAQR,YAAY;EAC9BC,UAAUO,QAAQP,Y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["ThreadSuggestion","RuntimeCapabilities","ThreadRuntimeCore","SpeechState","VoiceSessionState","ThreadRuntimeEventCallback","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ExportedMessageRepository","ThreadMessageLike","MessageRuntime","MessageRuntimeImpl","MessageState","NestedSubscriptionSubject","runCleanups","ShallowMemoizeSubject","SKIP_UPDATE","SubscribableWithState","ThreadComposerRuntime","ThreadComposerRuntimeImpl","MessageRuntimePath","ThreadListItemRuntimePath","ThreadRuntimePath","ThreadListItemState","AppendMessage","ThreadMessage","Unsubscribe","isMessageNotSentError","RunConfig","EventSubscriptionSubject","symbolInnerMessage","ModelContext","ChatModelRunOptions","ChatModelRunResult","ReadonlyJSONValue","CreateStartRunConfig","parentId","sourceId","runConfig","CreateResumeRunConfig","stream","options","AsyncGenerator","toResumeRunConfig","message","toStartRunConfig","CreateAppendMessage","role","content","attachments","metadata","createdAt","Date","startRun","toAppendMessage","messages","at","id","type","text","custom","undefined","ThreadRuntimeCoreBinding","outerSubscribe","callback","ThreadListItemRuntimeBinding","ThreadState","threadId","isDisabled","isLoading","isRunning","capabilities","state","suggestions","extras","speech","voice","getThreadRuntimeCoreIsRunning","runtime","Pick","lastMessage","status","getThreadState","threadListItemState","Object","freeze","ThreadRuntime","path","composer","getState","append","deleteMessage","messageId","Promise","config","resumeRun","exportExternalState","importExternalState","subscribe","cancelRun","unstable_notifySessionReset","getModelContext","export","import","repository","reset","initialMessages","getMessageByIndex","idx","getMessageById","stopSpeaking","connectVoice","disconnectVoice","getVoiceVolume","subscribeVoiceVolume","muteVoice","unmuteVoice","unstable_on","event","E","ThreadRuntimeImpl","_threadBinding","__internal_threadBinding","getStateState","_stateBinding","constructor","threadBinding","threadListItemBinding","stateBinding","sub1","sub2","ref","composerSource","__internal_bindMethods","bind","task","resolve","catch","error","data","Error","_getMessageRuntime","messageSelector","index","JSON","stringify","speechState","thread","branches","getBranches","isLast","branchNumber","indexOf","branchCount","length","_eventSubscriptionSubjects","Map","subject","get","binding","set","payload"],"sources":["../../../src/runtime/api/thread-runtime.ts"],"sourcesContent":["import type {\n ThreadSuggestion,\n RuntimeCapabilities,\n ThreadRuntimeCore,\n SpeechState,\n VoiceSessionState,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../utils/message-repository\";\nimport type { ThreadMessageLike } from \"../utils/thread-message-like\";\nimport {\n type MessageRuntime,\n MessageRuntimeImpl,\n type MessageState,\n} from \"./message-runtime\";\nimport { NestedSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport {\n runCleanups,\n ShallowMemoizeSubject,\n SKIP_UPDATE,\n} from \"../../subscribable/subscribable\";\nimport type { SubscribableWithState } from \"../../subscribable/subscribable\";\nimport {\n type ThreadComposerRuntime,\n ThreadComposerRuntimeImpl,\n} from \"./composer-runtime\";\nimport type {\n MessageRuntimePath,\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n} from \"./paths\";\nimport type { ThreadListItemState } from \"./bindings\";\nimport type { AppendMessage, ThreadMessage } from \"../../types/message\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { isMessageNotSentError } from \"../../types/error\";\nimport type { RunConfig } from \"../../types/message\";\nimport { EventSubscriptionSubject } from \"../../subscribable/subscribable\";\nimport { symbolInnerMessage } from \"../utils/external-store-message\";\nimport type { ModelContext } from \"../../model-context/types\";\nimport type {\n ChatModelRunOptions,\n ChatModelRunResult,\n} from \"../utils/chat-model-adapter\";\nimport type { ReadonlyJSONValue } from \"assistant-stream/utils\";\n\nexport type CreateStartRunConfig = {\n parentId: string | null;\n sourceId?: string | null | undefined;\n runConfig?: RunConfig | undefined;\n};\n\nexport type CreateResumeRunConfig = CreateStartRunConfig & {\n stream?: (\n options: ChatModelRunOptions,\n ) => AsyncGenerator<ChatModelRunResult, void, unknown>;\n};\n\nconst toResumeRunConfig = (message: CreateResumeRunConfig): ResumeRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n ...(message.stream ? { stream: message.stream } : {}),\n };\n};\n\nconst toStartRunConfig = (message: CreateStartRunConfig): StartRunConfig => {\n return {\n parentId: message.parentId ?? null,\n sourceId: message.sourceId ?? null,\n runConfig: message.runConfig ?? {},\n };\n};\n\nexport type CreateAppendMessage =\n | string\n | {\n /**\n * An omitted value or `undefined` selects the current tail.\n * `null` selects a root branch.\n */\n parentId?: string | null | undefined;\n sourceId?: string | null | undefined;\n role?: AppendMessage[\"role\"] | undefined;\n content: AppendMessage[\"content\"];\n attachments?: AppendMessage[\"attachments\"] | undefined;\n metadata?: AppendMessage[\"metadata\"] | undefined;\n createdAt?: Date | undefined;\n runConfig?: AppendMessage[\"runConfig\"] | undefined;\n startRun?: boolean | undefined;\n };\n\nconst toAppendMessage = (\n messages: readonly ThreadMessage[],\n message: CreateAppendMessage,\n): AppendMessage => {\n if (typeof message === \"string\") {\n return {\n createdAt: new Date(),\n parentId: messages.at(-1)?.id ?? null,\n sourceId: null,\n runConfig: {},\n role: \"user\",\n content: [{ type: \"text\", text: message }],\n attachments: [],\n metadata: { custom: {} },\n };\n }\n\n return {\n createdAt: message.createdAt ?? new Date(),\n parentId:\n message.parentId === undefined\n ? (messages.at(-1)?.id ?? null)\n : message.parentId,\n sourceId: message.sourceId ?? null,\n role: message.role ?? \"user\",\n content: message.content,\n attachments: message.attachments ?? [],\n metadata: message.metadata ?? { custom: {} },\n runConfig: message.runConfig ?? {},\n startRun: message.startRun,\n } as AppendMessage;\n};\n\nexport type ThreadRuntimeCoreBinding = SubscribableWithState<\n ThreadRuntimeCore,\n ThreadRuntimePath\n> & {\n outerSubscribe(callback: () => void): Unsubscribe;\n};\n\nexport type ThreadListItemRuntimeBinding = SubscribableWithState<\n ThreadListItemState,\n ThreadListItemRuntimePath\n>;\n\nexport type ThreadState = {\n /**\n * The thread ID.\n * @deprecated This field is deprecated and will be removed in 0.12.0. Use `useThreadListItem().id` instead.\n */\n readonly threadId: string;\n\n /**\n * The thread metadata.\n *\n * @deprecated Use `useThreadListItem()` instead. This field is deprecated and will be removed in 0.12.0.\n */\n readonly metadata: ThreadListItemState;\n\n /**\n * Whether the thread is disabled. Disabled threads cannot receive new messages.\n */\n readonly isDisabled: boolean;\n\n /**\n * Whether the thread is loading its history.\n */\n readonly isLoading: boolean;\n\n /**\n * Whether the thread is running. A thread is considered running when there is an active stream connection to the backend.\n */\n readonly isRunning: boolean;\n\n /**\n * The capabilities of the thread, such as whether the thread supports editing, branch switching, etc.\n */\n readonly capabilities: RuntimeCapabilities;\n\n /**\n * The messages in the currently selected branch of the thread.\n */\n readonly messages: readonly ThreadMessage[];\n\n /**\n * The thread state.\n *\n * @deprecated This feature is experimental\n */\n readonly state: ReadonlyJSONValue;\n\n /**\n * Follow up message suggestions to show the user.\n */\n readonly suggestions: readonly ThreadSuggestion[];\n\n /**\n * Custom extra information provided by the runtime.\n */\n readonly extras: unknown;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n readonly speech: SpeechState | undefined;\n\n readonly voice: VoiceSessionState | undefined;\n};\n\n/**\n * The canonical `isRunning` derivation. A runtime that tracks run state itself\n * reports it directly; the rest fall back to the trailing assistant message.\n */\nexport const getThreadRuntimeCoreIsRunning = (\n runtime: Pick<ThreadRuntimeCore, \"isRunning\" | \"messages\">,\n): boolean => {\n if (runtime.isRunning !== undefined) return runtime.isRunning;\n const lastMessage = runtime.messages.at(-1);\n return (\n lastMessage?.role === \"assistant\" && lastMessage.status.type === \"running\"\n );\n};\n\nexport const getThreadState = (\n runtime: ThreadRuntimeCore,\n threadListItemState: ThreadListItemState,\n): ThreadState => {\n return Object.freeze({\n threadId: threadListItemState.id,\n metadata: threadListItemState,\n capabilities: runtime.capabilities,\n isDisabled: runtime.isDisabled,\n isLoading: runtime.isLoading,\n isRunning: getThreadRuntimeCoreIsRunning(runtime),\n messages: runtime.messages,\n state: runtime.state,\n suggestions: runtime.suggestions,\n extras: runtime.extras,\n speech: runtime.speech,\n voice: runtime.voice,\n });\n};\n\nexport type ThreadRuntime = {\n /**\n * The selector for the thread runtime.\n */\n readonly path: ThreadRuntimePath;\n\n /**\n * The thread composer runtime.\n */\n readonly composer: ThreadComposerRuntime;\n\n /**\n * Gets a snapshot of the thread state.\n */\n getState(): ThreadState;\n\n /**\n * Append a new message to the thread.\n *\n * @example ```ts\n * // append a new user message with the text \"Hello, world!\"\n * threadRuntime.append(\"Hello, world!\");\n * ```\n *\n * @example ```ts\n * // append a new assistant message with the text \"Hello, world!\"\n * threadRuntime.append({\n * role: \"assistant\",\n * content: [{ type: \"text\", text: \"Hello, world!\" }],\n * });\n * ```\n */\n append(message: CreateAppendMessage): void;\n\n deleteMessage(messageId: string): void | Promise<void>;\n\n /**\n * Start a new run with the given configuration.\n * @param config The configuration for starting the run\n */\n startRun(config: CreateStartRunConfig): void;\n\n /**\n * Resume a run with the given configuration.\n * @param config The configuration for resuming the run\n **/\n resumeRun(config: CreateResumeRunConfig): void;\n\n /**\n * Export the thread state in the external store format.\n * For AI SDK runtimes, this returns the AI SDK message format.\n * For other runtimes, this may return different formats or throw an error.\n * @returns The thread state in the external format (typed as any)\n */\n exportExternalState(): any;\n\n /**\n * Import thread state from the external store format.\n * For AI SDK runtimes, this accepts AI SDK messages.\n * For other runtimes, this may accept different formats or throw an error.\n * @param state The thread state in the external format (typed as any)\n */\n importExternalState(state: any): void;\n\n subscribe(callback: () => void): Unsubscribe;\n cancelRun(): void;\n /**\n * Notifies the runtime that the adapter discarded its backing session.\n * Clears session-scoped tool-invocation state without run-cancel side\n * effects such as composer draft restoration. Internal API for\n * external-store adapter authors.\n */\n unstable_notifySessionReset(): void;\n getModelContext(): ModelContext;\n\n export(): ExportedMessageRepository;\n import(repository: ExportedMessageRepository): void;\n\n /**\n * Reset the thread with optional initial messages.\n *\n * @param initialMessages - Optional array of initial messages to populate the thread\n */\n reset(initialMessages?: readonly ThreadMessageLike[]): void;\n\n getMessageByIndex(idx: number): MessageRuntime;\n getMessageById(messageId: string): MessageRuntime;\n\n /**\n * @deprecated This API is still under active development and might change without notice.\n */\n stopSpeaking(): void;\n\n connectVoice(): void;\n disconnectVoice(): void;\n getVoiceVolume(): number;\n subscribeVoiceVolume(callback: () => void): Unsubscribe;\n muteVoice(): void;\n unmuteVoice(): void;\n\n unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe;\n};\n\nexport class ThreadRuntimeImpl implements ThreadRuntime {\n public get path() {\n return this._threadBinding.path;\n }\n\n public get __internal_threadBinding() {\n return this._threadBinding;\n }\n\n private readonly _threadBinding: ThreadRuntimeCoreBinding & {\n getStateState(): ThreadState;\n };\n private readonly _stateBinding: ShallowMemoizeSubject<\n ThreadState,\n ThreadRuntimePath\n >;\n\n constructor(\n threadBinding: ThreadRuntimeCoreBinding,\n threadListItemBinding: ThreadListItemRuntimeBinding,\n ) {\n const stateBinding = new ShallowMemoizeSubject({\n path: threadBinding.path,\n getState: () =>\n getThreadState(\n threadBinding.getState(),\n threadListItemBinding.getState(),\n ),\n subscribe: (callback) => {\n const sub1 = threadBinding.subscribe(callback);\n const sub2 = threadListItemBinding.subscribe(callback);\n return () => runCleanups([sub1, sub2]);\n },\n });\n\n this._stateBinding = stateBinding;\n this._threadBinding = {\n path: threadBinding.path,\n getState: () => threadBinding.getState(),\n getStateState: () => stateBinding.getState(),\n outerSubscribe: (callback) => threadBinding.outerSubscribe(callback),\n subscribe: (callback) => threadBinding.subscribe(callback),\n };\n\n this.composer = new ThreadComposerRuntimeImpl(\n new NestedSubscriptionSubject({\n path: {\n ...this.path,\n ref: `${this.path.ref}.composer`,\n composerSource: \"thread\",\n },\n getState: () => this._threadBinding.getState().composer,\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n );\n\n this.__internal_bindMethods();\n }\n\n protected __internal_bindMethods() {\n this.append = this.append.bind(this);\n this.deleteMessage = this.deleteMessage.bind(this);\n this.resumeRun = this.resumeRun.bind(this);\n this.importExternalState = this.importExternalState.bind(this);\n this.exportExternalState = this.exportExternalState.bind(this);\n this.startRun = this.startRun.bind(this);\n this.cancelRun = this.cancelRun.bind(this);\n this.unstable_notifySessionReset =\n this.unstable_notifySessionReset.bind(this);\n this.stopSpeaking = this.stopSpeaking.bind(this);\n this.connectVoice = this.connectVoice.bind(this);\n this.disconnectVoice = this.disconnectVoice.bind(this);\n this.muteVoice = this.muteVoice.bind(this);\n this.unmuteVoice = this.unmuteVoice.bind(this);\n this.getVoiceVolume = this.getVoiceVolume.bind(this);\n this.subscribeVoiceVolume = this.subscribeVoiceVolume.bind(this);\n this.export = this.export.bind(this);\n this.import = this.import.bind(this);\n this.reset = this.reset.bind(this);\n this.getMessageByIndex = this.getMessageByIndex.bind(this);\n this.getMessageById = this.getMessageById.bind(this);\n this.subscribe = this.subscribe.bind(this);\n this.unstable_on = this.unstable_on.bind(this);\n this.getModelContext = this.getModelContext.bind(this);\n this.getState = this.getState.bind(this);\n }\n\n public readonly composer;\n\n public getState() {\n return this._threadBinding.getStateState();\n }\n\n public append(message: CreateAppendMessage) {\n const task = this._threadBinding\n .getState()\n .append(\n toAppendMessage(this._threadBinding.getState().messages, message),\n );\n // An undispatched send is reported to the composer, so it is a control\n // signal rather than a failure to surface; every other rejection keeps\n // reaching the host untouched.\n void Promise.resolve(task).catch((error) => {\n if (!isMessageNotSentError(error)) throw error;\n });\n }\n\n public deleteMessage(messageId: string) {\n return this._threadBinding.getState().deleteMessage(messageId);\n }\n\n public subscribe(callback: () => void) {\n return this._stateBinding.subscribe(callback);\n }\n\n public getModelContext() {\n return this._threadBinding.getState().getModelContext();\n }\n\n public startRun(config: CreateStartRunConfig) {\n return this._threadBinding.getState().startRun(toStartRunConfig(config));\n }\n\n public resumeRun(config: CreateResumeRunConfig) {\n return this._threadBinding.getState().resumeRun(toResumeRunConfig(config));\n }\n\n public exportExternalState() {\n return this._threadBinding.getState().exportExternalState();\n }\n\n public importExternalState(state: any) {\n this._threadBinding.getState().importExternalState(state);\n }\n\n public cancelRun() {\n this._threadBinding.getState().cancelRun();\n }\n\n public unstable_notifySessionReset() {\n this._threadBinding.getState().unstable_notifySessionReset();\n }\n\n public stopSpeaking() {\n return this._threadBinding.getState().stopSpeaking();\n }\n\n public connectVoice() {\n this._threadBinding.getState().connectVoice();\n }\n\n public disconnectVoice() {\n this._threadBinding.getState().disconnectVoice();\n }\n\n public getVoiceVolume() {\n return this._threadBinding.getState().getVoiceVolume();\n }\n\n public subscribeVoiceVolume(callback: () => void) {\n return this._threadBinding.getState().subscribeVoiceVolume(callback);\n }\n\n public muteVoice() {\n this._threadBinding.getState().muteVoice();\n }\n\n public unmuteVoice() {\n this._threadBinding.getState().unmuteVoice();\n }\n\n public export() {\n return this._threadBinding.getState().export();\n }\n\n public import(data: ExportedMessageRepository) {\n this._threadBinding.getState().import(data);\n }\n\n public reset(initialMessages?: readonly ThreadMessageLike[]) {\n this._threadBinding.getState().reset(initialMessages);\n }\n\n public getMessageByIndex(idx: number) {\n if (idx < 0) throw new Error(\"Message index must be >= 0\");\n\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[${idx}]`,\n messageSelector: { type: \"index\", index: idx },\n },\n () => {\n const messages = this._threadBinding.getState().messages;\n const message = messages[idx];\n if (!message) return undefined;\n return {\n message,\n parentId: messages[idx - 1]?.id ?? null,\n index: idx,\n };\n },\n );\n }\n\n public getMessageById(messageId: string) {\n return this._getMessageRuntime(\n {\n ...this.path,\n ref: `${this.path.ref}.messages[messageId=${JSON.stringify(messageId)}]`,\n messageSelector: { type: \"messageId\", messageId: messageId },\n },\n () => this._threadBinding.getState().getMessageById(messageId),\n );\n }\n\n private _getMessageRuntime(\n path: MessageRuntimePath,\n callback: () =>\n | { parentId: string | null; message: ThreadMessage; index: number }\n | undefined,\n ) {\n return new MessageRuntimeImpl(\n new ShallowMemoizeSubject({\n path,\n getState: () => {\n const { message, parentId, index } = callback() ?? {};\n\n const { messages, speech: speechState } =\n this._threadBinding.getState();\n\n if (!message || parentId === undefined || index === undefined)\n return SKIP_UPDATE;\n\n const thread = this._threadBinding.getState();\n\n const branches = thread.getBranches(message.id);\n\n return {\n ...message,\n ...{ [symbolInnerMessage]: (message as any)[symbolInnerMessage] },\n\n index,\n isLast: messages.at(-1)?.id === message.id,\n parentId,\n\n branchNumber: branches.indexOf(message.id) + 1,\n branchCount: branches.length,\n\n speech:\n speechState?.messageId === message.id ? speechState : undefined,\n } satisfies MessageState;\n },\n subscribe: (callback) => this._threadBinding.subscribe(callback),\n }),\n this._threadBinding,\n );\n }\n\n private _eventSubscriptionSubjects = new Map<\n string,\n EventSubscriptionSubject<ThreadRuntimeEventType>\n >();\n\n public unstable_on<E extends ThreadRuntimeEventType>(\n event: E,\n callback: ThreadRuntimeEventCallback<E>,\n ): Unsubscribe {\n let subject = this._eventSubscriptionSubjects.get(event);\n if (!subject) {\n subject = new EventSubscriptionSubject<ThreadRuntimeEventType>({\n event,\n binding: this._threadBinding,\n });\n this._eventSubscriptionSubjects.set(event, subject);\n }\n return subject.subscribe(callback as (payload?: unknown) => void);\n }\n}\n"],"mappings":";;;;;;AA4DA,MAAM4C,qBAAqBC,YAAoD;CAC7E,OAAO;EACLR,UAAUQ,QAAQR,YAAY;EAC9BC,UAAUO,QAAQP,YAAY;EAC9BC,WAAWM,QAAQN,aAAa,CAAC;EACjC,GAAIM,QAAQJ,SAAS,EAAEA,QAAQI,QAAQJ,OAAO,IAAI,CAAC;CACrD;AACF;AAEA,MAAMK,oBAAoBD,YAAkD;CAC1E,OAAO;EACLR,UAAUQ,QAAQR,YAAY;EAC9BC,UAAUO,QAAQP,YAAY;EAC9BC,WAAWM,QAAQN,aAAa,CAAC;CACnC;AACF;AAoBA,MAAMgB,mBACJC,UACAX,YACkB;CAClB,IAAI,OAAOA,YAAY,UACrB,OAAO;EACLO,2BAAW,IAAIC,KAAK;EACpBhB,UAAUmB,SAASC,GAAG,EAAE,C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aAAayB,KAAAA,KAAakF,UAAUlF,KAAAA,GAClD,OAAO7C;IAIT,MAAMoI,WAFS,KAAK3B,eAAehC,SAElB0D,CAAM,CAACE,YAAYzG,QAAQa,EAAE;IAE9C,OAAO;KACL,GAAGb;MACGd,qBAAsBc,QAAgBd;KAE5CiH;KACAO,QAAQ/F,SAASC,GAAG,EAAE,CAAC,EAAEC,OAAOb,QAAQa;KACxCrB;KAEAmH,cAAcH,SAASI,QAAQ5G,QAAQa,EAAE,IAAI;KAC7CgG,aAAaL,SAASM;KAEtB/E,QACEuE,aAAatD,cAAchD,QAAQa,KAAKyF,cAAcrF,KAAAA;IAC1D;GACF;GACAqC,YAAYlC,aAAa,KAAKyD,eAAevB,UAAUlC,QAAQ;EACjE,CAAC,GACD,KAAKyD,cACP;CACF;CAEA,6CAAqC,IAAImC,IAGvC;CAEF,YACEtC,OACAtD,UACa;EACb,IAAI6F,UAAU,KAAKF,2BAA2BG,IAAIxC,KAAK;EACvD,IAAI,CAACuC,SAAS;GACZA,UAAU,IAAIhI,yBAAiD;IAC7DyF;IACAyC,SAAS,KAAKtC;GAChB,CAAC;GACD,KAAKkC,2BAA2BK,IAAI1C,OAAOuC,OAAO;EACpD;EACA,OAAOA,QAAQ3D,UAAUlC,QAAuC;CAClE;AACF"}
|
|
@@ -93,6 +93,7 @@ declare abstract class BaseComposerRuntimeCore extends BaseSubscribable implemen
|
|
|
93
93
|
private _isActiveSession;
|
|
94
94
|
startDictation(): void;
|
|
95
95
|
stopDictation(): void;
|
|
96
|
+
private _stopDictationSession;
|
|
96
97
|
private _cleanupDictation;
|
|
97
98
|
private _eventSubscribers;
|
|
98
99
|
protected _notifyEventSubscribers<E extends ComposerRuntimeEventType>(event: E, payload: ComposerRuntimeEventPayload[E]): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":";;;;;;;;;;uBAqCsB,gCACZ,4BACG;WAEK;qBAEG,wBAAwB;qBACxB,uBAAuB;YAEhC,2BACR;IAAY;MAAa,SAAS;;KAClC,SAAS,GAAG,kBAAkB,sCAAsC;MAW3D;UAIH;MACG,wBAAW;YAIZ,eAAe,gBAAgB;eAKrB;eACA;MAET;UAIH;MAEJ;UAII;MAEJ;UAII;MAEJ,aAAS;UAIL;MAEJ,SAAK;EAIF,SAAS,OAAO;EAOhB,QAAQ;UAWP;EASD,QAAQ,MAAM;EAOd,aAAa,WAAW;YAOrB;UACF;UACA;UACA;UAEA;UAIA;UAIA;UAOM;EAQD,SAAK;EA8BL,oBAAgB;
|
|
1
|
+
{"version":3,"file":"base-composer-runtime-core.d.ts","names":[],"sources":["../../../src/runtime/base/base-composer-runtime-core.ts"],"mappings":";;;;;;;;;;uBAqCsB,gCACZ,4BACG;WAEK;qBAEG,wBAAwB;qBACxB,uBAAuB;YAEhC,2BACR;IAAY;MAAa,SAAS;;KAClC,SAAS,GAAG,kBAAkB,sCAAsC;MAW3D;UAIH;MACG,wBAAW;YAIZ,eAAe,gBAAgB;eAKrB;eACA;MAET;UAIH;MAEJ;UAII;MAEJ;UAII;MAEJ,aAAS;UAIL;MAEJ,SAAK;EAIF,SAAS,OAAO;EAOhB,QAAQ;UAWP;EASD,QAAQ,MAAM;EAOd,aAAa,WAAW;YAOrB;UACF;UACA;UACA;UAEA;UAIA;UAIA;UAOM;EAQD,SAAK;EA8BL,oBAAgB;EAYhB,KAAK,UAAU,cAAW;;;;;;;;;EA8GhC,aAAa;IAClB;IACA,QAAQ;IACR,uBAAuB;;;;;;;EAsBlB,aAAa;IAClB;IACA,QAAQ;IACR,uBAAuB;;UAuBjB;EAcD;MAII,kBAAkB;EAItB,cACL,sBACA,YAAY;EAEP,gBAAgB;qBAEJ,WACjB,SAAS,KAAK,yCACd,UAAU,qBACF;qBACS;EAEb,cAAc,kBAAkB,OAAO,mBAAgB;UAsJrD;EAuBF,iBAAiB,uBAAoB;UAmCnC;UACA;UACA;UACA;UACA;UACA;UACA;UACA;MAEG,aAAa;UAIhB;EAUD;EAyGA;UASC;UAmBA;UAoCA;YAKE,wBAAwB,UAAU,0BAC1C,OAAO,GACP,SAAS,4BAA4B;EAQhC,YAAY,UAAU,0BAC3B,OAAO,GACP,UAAU,6BAA6B"}
|
|
@@ -103,7 +103,7 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
103
103
|
const adapter = this.getAttachmentAdapter();
|
|
104
104
|
if (adapter) {
|
|
105
105
|
const pending = this._attachments.filter((a) => !isAttachmentComplete(a));
|
|
106
|
-
await Promise.all(pending.map((a) => adapter.remove(a)));
|
|
106
|
+
await Promise.all(pending.map(async (a) => adapter.remove(a)));
|
|
107
107
|
}
|
|
108
108
|
}
|
|
109
109
|
async reset() {
|
|
@@ -121,14 +121,18 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
121
121
|
}
|
|
122
122
|
async clearAttachments() {
|
|
123
123
|
this._cancelAllAttachmentAdds();
|
|
124
|
+
if (this._isSending) for (const attachment of this._attachments) this._removedDuringSend.add(attachment.id);
|
|
124
125
|
const task = this._onClearAttachments();
|
|
125
126
|
this.setAttachments([]);
|
|
126
127
|
await task;
|
|
127
128
|
}
|
|
128
129
|
async send(options) {
|
|
129
130
|
if (!this.canSend || this._isSending) return;
|
|
130
|
-
if (this._dictationSession) {
|
|
131
|
+
if (this._dictationSession) try {
|
|
131
132
|
this._dictationSession.cancel();
|
|
133
|
+
} catch (error) {
|
|
134
|
+
console.error("[assistant-ui] Dictation session cancel threw", error);
|
|
135
|
+
} finally {
|
|
132
136
|
this._cleanupDictation();
|
|
133
137
|
}
|
|
134
138
|
const adapter = this.getAttachmentAdapter();
|
|
@@ -386,16 +390,26 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
386
390
|
startDictation() {
|
|
387
391
|
const adapter = this.getDictationAdapter();
|
|
388
392
|
if (!adapter) throw new Error("Dictation adapter not configured");
|
|
393
|
+
const isReplacing = this._dictationSession !== void 0;
|
|
389
394
|
if (this._dictationSession) {
|
|
390
|
-
|
|
391
|
-
this.
|
|
392
|
-
this.
|
|
393
|
-
this._dictationSession = void 0;
|
|
395
|
+
const oldSession = this._dictationSession;
|
|
396
|
+
this._cleanupDictation({ notify: false });
|
|
397
|
+
this._stopDictationSession(oldSession);
|
|
394
398
|
}
|
|
395
399
|
const inputDisabled = adapter.disableInputDuringDictation ?? false;
|
|
396
400
|
this._dictationBaseText = this._text;
|
|
397
401
|
this._currentInterimText = "";
|
|
398
|
-
|
|
402
|
+
let session;
|
|
403
|
+
try {
|
|
404
|
+
session = adapter.listen();
|
|
405
|
+
} catch (error) {
|
|
406
|
+
if (isReplacing) try {
|
|
407
|
+
this._notifySubscribers();
|
|
408
|
+
} catch (notifyError) {
|
|
409
|
+
console.error("[assistant-ui] Dictation replacement rollback notification threw", notifyError);
|
|
410
|
+
}
|
|
411
|
+
throw error;
|
|
412
|
+
}
|
|
399
413
|
this._dictationSession = session;
|
|
400
414
|
const sessionId = ++this._dictationSessionIdCounter;
|
|
401
415
|
this._activeDictationSessionId = sessionId;
|
|
@@ -453,20 +467,42 @@ var BaseComposerRuntimeCore = class extends BaseSubscribable {
|
|
|
453
467
|
const session = this._dictationSession;
|
|
454
468
|
const sessionId = this._activeDictationSessionId;
|
|
455
469
|
const cleanup = () => this._cleanupDictation({ sessionId });
|
|
456
|
-
|
|
470
|
+
this._stopDictationSession(session, cleanup);
|
|
471
|
+
}
|
|
472
|
+
_stopDictationSession(session, onSettled = () => {}) {
|
|
473
|
+
let task;
|
|
474
|
+
try {
|
|
475
|
+
task = session.stop();
|
|
476
|
+
} catch (error) {
|
|
477
|
+
console.error("[assistant-ui] Dictation session stop threw", error);
|
|
478
|
+
onSettled();
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
task.then(onSettled, (error) => {
|
|
482
|
+
console.error("[assistant-ui] Dictation session stop rejected", error);
|
|
483
|
+
onSettled();
|
|
484
|
+
});
|
|
457
485
|
}
|
|
458
486
|
_cleanupDictation(options) {
|
|
459
487
|
if (options?.sessionId !== void 0 && options.sessionId !== this._activeDictationSessionId || this._isCleaningDictation) return;
|
|
460
488
|
this._isCleaningDictation = true;
|
|
489
|
+
const runCleanup = (cleanup) => {
|
|
490
|
+
try {
|
|
491
|
+
cleanup();
|
|
492
|
+
} catch (error) {
|
|
493
|
+
console.error("[assistant-ui] Dictation cleanup threw", error);
|
|
494
|
+
}
|
|
495
|
+
};
|
|
461
496
|
try {
|
|
462
|
-
|
|
497
|
+
const unsubscribes = this._dictationUnsubscribes;
|
|
463
498
|
this._dictationUnsubscribes = [];
|
|
464
499
|
this._dictationSession = void 0;
|
|
465
500
|
this._activeDictationSessionId = void 0;
|
|
466
501
|
this._dictation = void 0;
|
|
467
502
|
this._dictationBaseText = "";
|
|
468
503
|
this._currentInterimText = "";
|
|
469
|
-
|
|
504
|
+
for (const unsubscribe of unsubscribes) runCleanup(unsubscribe);
|
|
505
|
+
if (options?.notify !== false) runCleanup(() => this._notifySubscribers());
|
|
470
506
|
} finally {
|
|
471
507
|
this._isCleaningDictation = false;
|
|
472
508
|
}
|