@assistant-ui/react 0.14.28 → 0.15.0
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/client/ExternalThread.d.ts +11 -1
- package/dist/client/ExternalThread.d.ts.map +1 -1
- package/dist/client/ExternalThread.js +762 -516
- package/dist/client/ExternalThread.js.map +1 -1
- package/dist/client/InMemoryThreadList.js +3 -3
- package/dist/client/InMemoryThreadList.js.map +1 -1
- package/dist/context/index.d.ts +1 -8
- package/dist/context/index.js +1 -8
- package/dist/index.d.ts +1 -8
- package/dist/index.js +1 -8
- package/dist/legacy-runtime/cloud/auiV0.d.ts +12 -1
- package/dist/legacy-runtime/cloud/auiV0.d.ts.map +1 -1
- package/dist/legacy-runtime/cloud/auiV0.js +2 -1
- package/dist/legacy-runtime/cloud/auiV0.js.map +1 -1
- package/dist/legacy-runtime/runtime-cores/assistant-transport/commandQueue.d.ts +1 -1
- package/dist/legacy-runtime/runtime-cores/assistant-transport/commandQueue.js +7 -6
- package/dist/legacy-runtime/runtime-cores/assistant-transport/commandQueue.js.map +1 -1
- package/dist/legacy-runtime/runtime-cores/assistant-transport/runManager.d.ts.map +1 -1
- package/dist/legacy-runtime/runtime-cores/assistant-transport/runManager.js +30 -15
- package/dist/legacy-runtime/runtime-cores/assistant-transport/runManager.js.map +1 -1
- package/dist/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.d.ts.map +1 -1
- package/dist/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.js +11 -7
- package/dist/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.js.map +1 -1
- package/dist/legacy-runtime/runtime-cores/assistant-transport/useConvertedState.js +1 -0
- package/dist/legacy-runtime/runtime-cores/assistant-transport/useConvertedState.js.map +1 -1
- package/dist/mcp-apps/McpAppRenderer.js +1 -1
- package/dist/mcp-apps/McpAppRenderer.js.map +1 -1
- package/dist/model-context/makeAssistantVisible.js +26 -25
- package/dist/model-context/makeAssistantVisible.js.map +1 -1
- package/dist/primitives/actionBar/ActionBarExportMarkdown.js +3 -3
- package/dist/primitives/actionBar/ActionBarExportMarkdown.js.map +1 -1
- package/dist/primitives/actionBar/ActionBarRoot.js +3 -3
- package/dist/primitives/actionBar/ActionBarRoot.js.map +1 -1
- package/dist/primitives/actionBar/useActionBarFloatStatus.d.ts +7 -6
- package/dist/primitives/actionBar/useActionBarFloatStatus.d.ts.map +1 -1
- package/dist/primitives/actionBar/useActionBarFloatStatus.js +10 -11
- package/dist/primitives/actionBar/useActionBarFloatStatus.js.map +1 -1
- package/dist/primitives/attachment/AttachmentRemove.js +4 -3
- package/dist/primitives/attachment/AttachmentRemove.js.map +1 -1
- package/dist/primitives/chainOfThought/ChainOfThoughtAccordionTrigger.js +4 -3
- package/dist/primitives/chainOfThought/ChainOfThoughtAccordionTrigger.js.map +1 -1
- package/dist/primitives/composer/ComposerAddAttachment.d.ts.map +1 -1
- package/dist/primitives/composer/ComposerAddAttachment.js +11 -5
- package/dist/primitives/composer/ComposerAddAttachment.js.map +1 -1
- package/dist/primitives/composer/ComposerAttachmentDropzone.d.ts.map +1 -1
- package/dist/primitives/composer/ComposerAttachmentDropzone.js +2 -4
- package/dist/primitives/composer/ComposerAttachmentDropzone.js.map +1 -1
- package/dist/primitives/composer/ComposerInput.js +18 -16
- package/dist/primitives/composer/ComposerInput.js.map +1 -1
- package/dist/primitives/composer/ComposerQuote.js +1 -1
- package/dist/primitives/composer/ComposerQuote.js.map +1 -1
- package/dist/primitives/composer/ComposerSend.js +1 -0
- package/dist/primitives/composer/ComposerSend.js.map +1 -1
- package/dist/primitives/composer/ComposerStopDictation.js +4 -3
- package/dist/primitives/composer/ComposerStopDictation.js.map +1 -1
- package/dist/primitives/composer/trigger/triggerSelectionResource.d.ts.map +1 -1
- package/dist/primitives/composer/trigger/triggerSelectionResource.js +3 -3
- package/dist/primitives/composer/trigger/triggerSelectionResource.js.map +1 -1
- package/dist/primitives/message/MessagePartsGrouped.d.ts.map +1 -1
- package/dist/primitives/message/MessagePartsGrouped.js +67 -89
- package/dist/primitives/message/MessagePartsGrouped.js.map +1 -1
- package/dist/primitives/message/MessageRoot.js +3 -3
- package/dist/primitives/message/MessageRoot.js.map +1 -1
- package/dist/primitives/queueItem/QueueItemRemove.js +4 -3
- package/dist/primitives/queueItem/QueueItemRemove.js.map +1 -1
- package/dist/primitives/queueItem/QueueItemSteer.js +4 -3
- package/dist/primitives/queueItem/QueueItemSteer.js.map +1 -1
- package/dist/primitives/selectionToolbar/SelectionToolbarQuote.js +1 -1
- package/dist/primitives/selectionToolbar/SelectionToolbarQuote.js.map +1 -1
- package/dist/primitives/suggestion/SuggestionTrigger.js +17 -15
- package/dist/primitives/suggestion/SuggestionTrigger.js.map +1 -1
- package/dist/primitives/thread/ThreadScrollToBottom.js +1 -0
- package/dist/primitives/thread/ThreadScrollToBottom.js.map +1 -1
- package/dist/unstable/useComposerInput.js +2 -2
- package/dist/unstable/useComposerInput.js.map +1 -1
- package/dist/unstable/useComposerInputHistory.js +6 -6
- package/dist/unstable/useComposerInputHistory.js.map +1 -1
- package/dist/unstable/useMentionAdapter.js +1 -1
- package/dist/unstable/useMentionAdapter.js.map +1 -1
- package/dist/utils/hooks/useOnResizeContent.js +1 -0
- package/dist/utils/hooks/useOnResizeContent.js.map +1 -1
- package/dist/utils/hooks/useSizeHandle.js +1 -0
- package/dist/utils/hooks/useSizeHandle.js.map +1 -1
- package/dist/utils/smooth/SmoothContext.js +3 -3
- package/dist/utils/smooth/SmoothContext.js.map +1 -1
- package/dist/utils/smooth/useSmooth.d.ts.map +1 -1
- package/dist/utils/smooth/useSmooth.js +3 -3
- package/dist/utils/smooth/useSmooth.js.map +1 -1
- package/package.json +9 -9
- package/src/client/ExternalThread.ts +345 -56
- package/src/client/InMemoryThreadList.ts +3 -3
- package/src/context/index.ts +0 -44
- package/src/legacy-runtime/cloud/auiV0.ts +14 -0
- package/src/legacy-runtime/runtime-cores/assistant-transport/commandQueue.ts +4 -1
- package/src/legacy-runtime/runtime-cores/assistant-transport/runManager.ts +37 -10
- package/src/legacy-runtime/runtime-cores/assistant-transport/transport-delivery.test.tsx +79 -0
- package/src/legacy-runtime/runtime-cores/assistant-transport/transport-parentid.test.tsx +97 -0
- package/src/legacy-runtime/runtime-cores/assistant-transport/transport-scheduling.test.ts +113 -2
- package/src/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransport.spec.md +10 -2
- package/src/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.test.tsx +185 -0
- package/src/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.ts +21 -5
- package/src/mcp-apps/McpAppRenderer.tsx +1 -1
- package/src/model-context/makeAssistantVisible.test.tsx +1 -1
- package/src/model-context/makeAssistantVisible.tsx +1 -1
- package/src/primitives/actionBar/ActionBarExportMarkdown.tsx +1 -1
- package/src/primitives/actionBar/useActionBarFloatStatus.ts +7 -5
- package/src/primitives/attachment/AttachmentRemove.ts +1 -1
- package/src/primitives/chainOfThought/ChainOfThoughtAccordionTrigger.ts +1 -1
- package/src/primitives/composer/ComposerAddAttachment.test.tsx +108 -0
- package/src/primitives/composer/ComposerAddAttachment.ts +11 -5
- package/src/primitives/composer/ComposerAttachmentDropzone.test.tsx +5 -4
- package/src/primitives/composer/ComposerAttachmentDropzone.tsx +4 -3
- package/src/primitives/composer/ComposerInput.test.tsx +104 -7
- package/src/primitives/composer/ComposerInput.tsx +22 -20
- package/src/primitives/composer/ComposerQuote.tsx +1 -1
- package/src/primitives/composer/ComposerStopDictation.ts +1 -1
- package/src/primitives/composer/trigger/triggerSelectionResource.ts +7 -9
- package/src/primitives/message/MessagePartsGrouped.tsx +6 -8
- package/src/primitives/message/MessageRoot.tsx +1 -1
- package/src/primitives/queueItem/QueueItemRemove.ts +1 -1
- package/src/primitives/queueItem/QueueItemSteer.ts +1 -1
- package/src/primitives/selectionToolbar/SelectionToolbarQuote.tsx +1 -1
- package/src/primitives/suggestion/SuggestionTrigger.ts +9 -9
- package/src/tests/DataRenderers.test.tsx +212 -0
- package/src/tests/RemoteThreadListRuntime.adapterProvider.test.tsx +1 -11
- package/src/tests/RemoteThreadListRuntime.deferredProvider.test.tsx +3 -3
- package/src/tests/external-thread-attachments.test.tsx +300 -11
- package/src/tests/external-thread-branches.test.tsx +10 -10
- package/src/tests/external-thread-parity.test.tsx +230 -0
- package/src/tests/generative-ui.test.tsx +1 -46
- package/src/tests/local-runtime-queue.test.tsx +29 -34
- package/src/tests/messagePartSwitchRace.test.tsx +46 -15
- package/src/tests/messagePartTypeMismatch.test.tsx +2 -2
- package/src/tests/threadMessageById.test.tsx +0 -7
- package/src/unstable/useComposerInput.test.tsx +2 -2
- package/src/unstable/useComposerInput.ts +2 -2
- package/src/unstable/useComposerInputHistory.test.tsx +3 -3
- package/src/unstable/useComposerInputHistory.ts +6 -6
- package/src/unstable/useMentionAdapter.ts +1 -1
- package/src/utils/smooth/SmoothContext.tsx +1 -1
- package/src/utils/smooth/useSmooth.test.tsx +1 -1
- package/src/utils/smooth/useSmooth.ts +8 -5
- package/dist/context/react/utils/createStateHookForRuntime.d.ts +0 -34
- package/dist/context/react/utils/createStateHookForRuntime.d.ts.map +0 -1
- package/dist/context/react/utils/createStateHookForRuntime.js +0 -21
- package/dist/context/react/utils/createStateHookForRuntime.js.map +0 -1
- package/dist/legacy-runtime/hooks/AssistantContext.d.ts +0 -74
- package/dist/legacy-runtime/hooks/AssistantContext.d.ts.map +0 -1
- package/dist/legacy-runtime/hooks/AssistantContext.js +0 -29
- package/dist/legacy-runtime/hooks/AssistantContext.js.map +0 -1
- package/dist/legacy-runtime/hooks/AttachmentContext.d.ts +0 -1007
- package/dist/legacy-runtime/hooks/AttachmentContext.d.ts.map +0 -1
- package/dist/legacy-runtime/hooks/AttachmentContext.js +0 -47
- package/dist/legacy-runtime/hooks/AttachmentContext.js.map +0 -1
- package/dist/legacy-runtime/hooks/ComposerContext.d.ts +0 -141
- package/dist/legacy-runtime/hooks/ComposerContext.d.ts.map +0 -1
- package/dist/legacy-runtime/hooks/ComposerContext.js +0 -65
- package/dist/legacy-runtime/hooks/ComposerContext.js.map +0 -1
- package/dist/legacy-runtime/hooks/MessageContext.d.ts +0 -155
- package/dist/legacy-runtime/hooks/MessageContext.d.ts.map +0 -1
- package/dist/legacy-runtime/hooks/MessageContext.js +0 -68
- package/dist/legacy-runtime/hooks/MessageContext.js.map +0 -1
- package/dist/legacy-runtime/hooks/MessagePartContext.d.ts +0 -44
- package/dist/legacy-runtime/hooks/MessagePartContext.d.ts.map +0 -1
- package/dist/legacy-runtime/hooks/MessagePartContext.js +0 -26
- package/dist/legacy-runtime/hooks/MessagePartContext.js.map +0 -1
- package/dist/legacy-runtime/hooks/ThreadContext.d.ts +0 -139
- package/dist/legacy-runtime/hooks/ThreadContext.d.ts.map +0 -1
- package/dist/legacy-runtime/hooks/ThreadContext.js +0 -84
- package/dist/legacy-runtime/hooks/ThreadContext.js.map +0 -1
- package/dist/legacy-runtime/hooks/ThreadListItemContext.d.ts +0 -44
- package/dist/legacy-runtime/hooks/ThreadListItemContext.d.ts.map +0 -1
- package/dist/legacy-runtime/hooks/ThreadListItemContext.js +0 -26
- package/dist/legacy-runtime/hooks/ThreadListItemContext.js.map +0 -1
- package/src/context/react/utils/createStateHookForRuntime.ts +0 -82
- package/src/legacy-runtime/hooks/AssistantContext.ts +0 -67
- package/src/legacy-runtime/hooks/AttachmentContext.ts +0 -99
- package/src/legacy-runtime/hooks/ComposerContext.ts +0 -131
- package/src/legacy-runtime/hooks/MessageContext.ts +0 -127
- package/src/legacy-runtime/hooks/MessagePartContext.ts +0 -32
- package/src/legacy-runtime/hooks/ThreadContext.ts +0 -120
- package/src/legacy-runtime/hooks/ThreadListItemContext.ts +0 -36
- package/src/tests/BaseComposerRuntimeCore.test.ts +0 -621
- package/src/tests/BaseSubscribable.test.ts +0 -54
- package/src/tests/DataRenderers.test.ts +0 -355
- package/src/tests/ExternalStoreThreadRuntimeCore.test.ts +0 -685
- package/src/tests/LocalThreadRuntimeCore.test.ts +0 -324
- package/src/tests/auiV0Encode.test.ts +0 -188
- package/src/tests/external-message-converter.test.ts +0 -346
- package/src/tests/shouldContinue.test.ts +0 -122
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auiV0.js","names":["CompleteAttachment","DataMessagePart","FileMessagePart","ImageMessagePart","MessageStatus","SourceProviderMetadata","ThreadMessage","TextMessagePart","Unstable_AudioMessagePart","fromThreadMessageLike","CloudMessage","isJSONValue","ReadonlyJSONObject","ReadonlyJSONValue","ExportedMessageRepositoryItem","AuiV0MessagePart","type","text","sourceType","id","url","title","providerMetadata","mediaType","filename","toolCallId","toolName","args","result","isError","argsText","image","data","mimeType","AuiV0AttachmentPart","AuiV0Attachment","name","contentType","status","content","AuiV0Message","role","attachments","metadata","unstable_state","unstable_annotations","unstable_data","steps","usage","inputTokens","outputTokens","custom","encodeAttachmentPart","part","console","warn","JSON","stringify","unhandledType","Error","encodeAttachments","message","length","undefined","map","auiV0Encode","reason","auiV0Decode","cloudMessage","format","payload","createdAt","created_at","parentId","parent_id"],"sources":["../../../src/legacy-runtime/cloud/auiV0.ts"],"sourcesContent":["import type {\n CompleteAttachment,\n DataMessagePart,\n FileMessagePart,\n ImageMessagePart,\n MessageStatus,\n SourceProviderMetadata,\n ThreadMessage,\n TextMessagePart,\n Unstable_AudioMessagePart,\n} from \"@assistant-ui/core\";\nimport { fromThreadMessageLike } from \"../runtime-cores/external-store/ThreadMessageLike\";\nimport type { CloudMessage } from \"assistant-cloud\";\nimport { isJSONValue } from \"@assistant-ui/core/internal\";\nimport type {\n ReadonlyJSONObject,\n ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\nimport type { ExportedMessageRepositoryItem } from \"../runtime-cores/utils/MessageRepository\";\n\ntype AuiV0MessagePart =\n | {\n readonly type: \"text\";\n readonly text: string;\n }\n | {\n readonly type: \"reasoning\";\n readonly text: string;\n }\n | {\n readonly type: \"source\";\n readonly sourceType: \"url\";\n readonly id: string;\n readonly url: string;\n readonly title?: string;\n readonly providerMetadata?: SourceProviderMetadata;\n }\n | {\n readonly type: \"source\";\n readonly sourceType: \"document\";\n readonly id: string;\n readonly title: string;\n readonly mediaType: string;\n readonly filename?: string;\n readonly providerMetadata?: SourceProviderMetadata;\n }\n | {\n readonly type: \"tool-call\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly args: ReadonlyJSONObject;\n readonly result?: ReadonlyJSONValue;\n readonly isError?: true;\n }\n | {\n readonly type: \"tool-call\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly argsText: string;\n readonly result?: ReadonlyJSONValue;\n readonly isError?: true;\n }\n | {\n readonly type: \"image\";\n readonly image: string;\n }\n | {\n readonly type: \"file\";\n readonly data: string;\n readonly mimeType: string;\n readonly filename?: string;\n };\n\ntype AuiV0AttachmentPart =\n | TextMessagePart\n | ImageMessagePart\n | FileMessagePart\n | Unstable_AudioMessagePart\n | DataMessagePart<ReadonlyJSONValue>;\n\ntype AuiV0Attachment = {\n readonly id: string;\n readonly type: CompleteAttachment[\"type\"];\n readonly name: string;\n readonly contentType?: string;\n readonly status: CompleteAttachment[\"status\"];\n readonly content: readonly AuiV0AttachmentPart[];\n};\n\ntype AuiV0Message = {\n readonly role: \"assistant\" | \"user\" | \"system\";\n readonly status?: MessageStatus;\n readonly content: readonly AuiV0MessagePart[];\n readonly attachments?: readonly AuiV0Attachment[];\n readonly metadata: {\n readonly unstable_state?: ReadonlyJSONValue;\n readonly unstable_annotations: readonly ReadonlyJSONValue[];\n readonly unstable_data: readonly ReadonlyJSONValue[];\n readonly steps: readonly {\n readonly usage?: {\n readonly inputTokens: number;\n readonly outputTokens: number;\n };\n }[];\n readonly custom: ReadonlyJSONObject;\n };\n};\n\nconst encodeAttachmentPart = (\n part: CompleteAttachment[\"content\"][number],\n): AuiV0AttachmentPart => {\n const type = part.type;\n switch (type) {\n case \"text\":\n case \"image\":\n case \"file\":\n case \"audio\":\n return part;\n\n case \"data\": {\n if (!isJSONValue(part.data)) {\n console.warn(`attachment data is not JSON! ${JSON.stringify(part)}`);\n }\n return { ...part, data: part.data as ReadonlyJSONValue };\n }\n\n default: {\n const unhandledType: never = type;\n throw new Error(\n `Attachment part type not supported by aui/v0: ${unhandledType}`,\n );\n }\n }\n};\n\nconst encodeAttachments = (\n message: ThreadMessage,\n): readonly AuiV0Attachment[] | undefined => {\n if (message.role !== \"user\" || message.attachments.length === 0) {\n return undefined;\n }\n\n return message.attachments.map(\n ({ id, type, name, contentType, status, content }) => ({\n id,\n type,\n name,\n status,\n ...(contentType != null ? { contentType } : undefined),\n content: content.map(encodeAttachmentPart),\n }),\n );\n};\n\nexport function auiV0Encode(message: ThreadMessage): AuiV0Message {\n // info: ID and createdAt are ignored (we use the server value instead)\n const status: MessageStatus | undefined =\n message.status?.type === \"running\"\n ? { type: \"incomplete\", reason: \"cancelled\" }\n : message.status;\n const attachments = encodeAttachments(message);\n\n return {\n role: message.role,\n content: message.content.map((part) => {\n const type = part.type;\n switch (type) {\n case \"text\":\n return { type: \"text\", text: part.text };\n\n case \"reasoning\":\n return { type: \"reasoning\", text: part.text };\n\n case \"source\":\n if (part.sourceType === \"url\") {\n return {\n type: \"source\",\n sourceType: \"url\",\n id: part.id,\n url: part.url,\n ...(part.title != null ? { title: part.title } : undefined),\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : undefined),\n };\n }\n\n return {\n type: \"source\",\n sourceType: \"document\",\n id: part.id,\n title: part.title,\n mediaType: part.mediaType,\n ...(part.filename != null\n ? { filename: part.filename }\n : undefined),\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : undefined),\n };\n\n case \"tool-call\": {\n if (!isJSONValue(part.result)) {\n console.warn(\n `tool-call result is not JSON! ${JSON.stringify(part)}`,\n );\n }\n return {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n ...(JSON.stringify(part.args) === part.argsText\n ? { args: part.args }\n : { argsText: part.argsText }),\n ...(part.result\n ? { result: part.result as ReadonlyJSONValue }\n : undefined),\n ...(part.isError ? { isError: true } : undefined),\n };\n }\n\n case \"image\":\n return { type: \"image\", image: part.image };\n\n case \"file\":\n return {\n type: \"file\",\n data: part.data,\n mimeType: part.mimeType,\n ...(part.filename ? { filename: part.filename } : undefined),\n };\n\n default: {\n const unhandledType: \"audio\" | \"data\" | \"generative-ui\" = type;\n throw new Error(\n `Message part type not supported by aui/v0: ${unhandledType}`,\n );\n }\n }\n }),\n metadata: message.metadata as AuiV0Message[\"metadata\"],\n ...(status ? { status } : undefined),\n ...(attachments ? { attachments } : undefined),\n };\n}\n\nexport function auiV0Decode(\n cloudMessage: CloudMessage & { format: \"aui/v0\" },\n): ExportedMessageRepositoryItem {\n const payload = cloudMessage.content as unknown as AuiV0Message;\n const message = fromThreadMessageLike(\n {\n id: cloudMessage.id,\n createdAt: cloudMessage.created_at,\n ...payload,\n },\n cloudMessage.id,\n { type: \"complete\", reason: \"unknown\" },\n );\n\n return {\n parentId: cloudMessage.parent_id,\n message,\n };\n}\n"],"mappings":";;;AA4GA,MAAMoD,wBACJC,SACwB;CACxB,MAAMrC,OAAOqC,KAAKrC;CAClB,QAAQA,MAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,SACH,OAAOqC;EAET,KAAK;GACH,IAAI,CAAC1C,YAAY0C,KAAKrB,IAAI,GACxBsB,QAAQC,KAAK,gCAAgCC,KAAKC,UAAUJ,IAAI,GAAG;GAErE,OAAO;IAAE,GAAGA;IAAMrB,MAAMqB,KAAKrB;GAA0B;EAGzD,SAEE,MAAM,IAAI2B,MACR,iDAAiDD,MACnD;CAEJ;AACF;AAEA,MAAME,qBACJC,YAC2C;CAC3C,IAAIA,QAAQpB,SAAS,UAAUoB,QAAQnB,YAAYoB,WAAW,GAC5D;CAGF,OAAOD,QAAQnB,YAAYsB,KACxB,EAAE7C,IAAIH,MAAMoB,MAAMC,aAAaC,QAAQC,eAAe;EACrDpB;EACAH;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,GACtD;KAEF,OAAO;MACLrC,MAAM;MACNS,YAAY4B,KAAK5B;MACjBC,UAAU2B,KAAK3B;MACf,GAAI8B,KAAKC,UAAUJ,KAAK1B,IAAI,MAAM0B,KAAKvB,WACnC,EAAEH,MAAM0B,KAAK1B,KAAK,IAClB,EAAEG,UAAUuB,KAAKvB,SAAS;MAC9B,GAAIuB,KAAKzB,SACL,EAAEA,QAAQyB,KAAKzB,OAA4B,IAC3CmC,KAAAA;MACJ,GAAIV,KAAKxB,UAAU,EAAEA,SAAS,KAAK,IAAIkC,KAAAA;KACzC;IAGF,KAAK,SACH,OAAO;KAAE/C,MAAM;KAASe,OAAOsB,KAAKtB;IAAM;IAE5C,KAAK,QACH,OAAO;KACLf,MAAM;KACNgB,MAAMqB,KAAKrB;KACXC,UAAUoB,KAAKpB;KACf,GAAIoB,KAAK7B,WAAW,EAAEA,UAAU6B,KAAK7B,SAAS,IAAIuC,KAAAA;IACpD;IAEF,SAEE,MAAM,IAAIJ,MACR,8CAA8CD,MAChD;GAEJ;EACF,CAAC;EACDf,UAAUkB,QAAQlB;EAClB,GAAIL,SAAS,EAAEA,OAAO,IAAIyB,KAAAA;EAC1B,GAAIrB,cAAc,EAAEA,YAAY,IAAIqB,KAAAA;CACtC;AACF;AAEA,SAAgBI,YACdC,cAC+B;CAC/B,MAAME,UAAUF,aAAa7B;CAC7B,MAAMsB,UAAUpD,sBACd;EACEU,IAAIiD,aAAajD;EACjBoD,WAAWH,aAAaI;EACxB,GAAGF;CACL,GACAF,aAAajD,IACb;EAAEH,MAAM;EAAYkD,QAAQ;CAAU,CACxC;CAEA,OAAO;EACLO,UAAUL,aAAaM;EACvBb;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"auiV0.js","names":["CompleteAttachment","DataMessagePart","FileMessagePart","ImageMessagePart","MessageStatus","SourceProviderMetadata","ThreadMessage","TextMessagePart","ToolApprovalOption","Unstable_AudioMessagePart","fromThreadMessageLike","CloudMessage","isJSONValue","ReadonlyJSONObject","ReadonlyJSONValue","ExportedMessageRepositoryItem","AuiV0ToolApproval","id","approved","reason","isAutomatic","options","optionId","resolution","AuiV0MessagePart","type","text","sourceType","url","title","providerMetadata","mediaType","filename","toolCallId","toolName","args","result","isError","approval","argsText","image","data","mimeType","AuiV0AttachmentPart","AuiV0Attachment","name","contentType","status","content","AuiV0Message","role","attachments","metadata","unstable_state","unstable_annotations","unstable_data","steps","usage","inputTokens","outputTokens","custom","encodeAttachmentPart","part","console","warn","JSON","stringify","unhandledType","Error","encodeAttachments","message","length","undefined","map","auiV0Encode","auiV0Decode","cloudMessage","format","payload","createdAt","created_at","parentId","parent_id"],"sources":["../../../src/legacy-runtime/cloud/auiV0.ts"],"sourcesContent":["import type {\n CompleteAttachment,\n DataMessagePart,\n FileMessagePart,\n ImageMessagePart,\n MessageStatus,\n SourceProviderMetadata,\n ThreadMessage,\n TextMessagePart,\n ToolApprovalOption,\n Unstable_AudioMessagePart,\n} from \"@assistant-ui/core\";\nimport { fromThreadMessageLike } from \"../runtime-cores/external-store/ThreadMessageLike\";\nimport type { CloudMessage } from \"assistant-cloud\";\nimport { isJSONValue } from \"@assistant-ui/core/internal\";\nimport type {\n ReadonlyJSONObject,\n ReadonlyJSONValue,\n} from \"assistant-stream/utils\";\nimport type { ExportedMessageRepositoryItem } from \"../runtime-cores/utils/MessageRepository\";\n\ntype AuiV0ToolApproval = {\n readonly id: string;\n readonly approved?: boolean;\n readonly reason?: string;\n readonly isAutomatic?: boolean;\n readonly options?: readonly ToolApprovalOption[];\n readonly optionId?: string;\n readonly resolution?: \"cancelled\" | \"expired\";\n};\n\ntype AuiV0MessagePart =\n | {\n readonly type: \"text\";\n readonly text: string;\n }\n | {\n readonly type: \"reasoning\";\n readonly text: string;\n }\n | {\n readonly type: \"source\";\n readonly sourceType: \"url\";\n readonly id: string;\n readonly url: string;\n readonly title?: string;\n readonly providerMetadata?: SourceProviderMetadata;\n }\n | {\n readonly type: \"source\";\n readonly sourceType: \"document\";\n readonly id: string;\n readonly title: string;\n readonly mediaType: string;\n readonly filename?: string;\n readonly providerMetadata?: SourceProviderMetadata;\n }\n | {\n readonly type: \"tool-call\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly args: ReadonlyJSONObject;\n readonly result?: ReadonlyJSONValue;\n readonly isError?: true;\n readonly approval?: AuiV0ToolApproval;\n }\n | {\n readonly type: \"tool-call\";\n readonly toolCallId: string;\n readonly toolName: string;\n readonly argsText: string;\n readonly result?: ReadonlyJSONValue;\n readonly isError?: true;\n readonly approval?: AuiV0ToolApproval;\n }\n | {\n readonly type: \"image\";\n readonly image: string;\n }\n | {\n readonly type: \"file\";\n readonly data: string;\n readonly mimeType: string;\n readonly filename?: string;\n };\n\ntype AuiV0AttachmentPart =\n | TextMessagePart\n | ImageMessagePart\n | FileMessagePart\n | Unstable_AudioMessagePart\n | DataMessagePart<ReadonlyJSONValue>;\n\ntype AuiV0Attachment = {\n readonly id: string;\n readonly type: CompleteAttachment[\"type\"];\n readonly name: string;\n readonly contentType?: string;\n readonly status: CompleteAttachment[\"status\"];\n readonly content: readonly AuiV0AttachmentPart[];\n};\n\ntype AuiV0Message = {\n readonly role: \"assistant\" | \"user\" | \"system\";\n readonly status?: MessageStatus;\n readonly content: readonly AuiV0MessagePart[];\n readonly attachments?: readonly AuiV0Attachment[];\n readonly metadata: {\n readonly unstable_state?: ReadonlyJSONValue;\n readonly unstable_annotations: readonly ReadonlyJSONValue[];\n readonly unstable_data: readonly ReadonlyJSONValue[];\n readonly steps: readonly {\n readonly usage?: {\n readonly inputTokens: number;\n readonly outputTokens: number;\n };\n }[];\n readonly custom: ReadonlyJSONObject;\n };\n};\n\nconst encodeAttachmentPart = (\n part: CompleteAttachment[\"content\"][number],\n): AuiV0AttachmentPart => {\n const type = part.type;\n switch (type) {\n case \"text\":\n case \"image\":\n case \"file\":\n case \"audio\":\n return part;\n\n case \"data\": {\n if (!isJSONValue(part.data)) {\n console.warn(`attachment data is not JSON! ${JSON.stringify(part)}`);\n }\n return { ...part, data: part.data as ReadonlyJSONValue };\n }\n\n default: {\n const unhandledType: never = type;\n throw new Error(\n `Attachment part type not supported by aui/v0: ${unhandledType}`,\n );\n }\n }\n};\n\nconst encodeAttachments = (\n message: ThreadMessage,\n): readonly AuiV0Attachment[] | undefined => {\n if (message.role !== \"user\" || message.attachments.length === 0) {\n return undefined;\n }\n\n return message.attachments.map(\n ({ id, type, name, contentType, status, content }) => ({\n id,\n type,\n name,\n status,\n ...(contentType != null ? { contentType } : undefined),\n content: content.map(encodeAttachmentPart),\n }),\n );\n};\n\nexport function auiV0Encode(message: ThreadMessage): AuiV0Message {\n // info: ID and createdAt are ignored (we use the server value instead)\n const status: MessageStatus | undefined =\n message.status?.type === \"running\"\n ? { type: \"incomplete\", reason: \"cancelled\" }\n : message.status;\n const attachments = encodeAttachments(message);\n\n return {\n role: message.role,\n content: message.content.map((part) => {\n const type = part.type;\n switch (type) {\n case \"text\":\n return { type: \"text\", text: part.text };\n\n case \"reasoning\":\n return { type: \"reasoning\", text: part.text };\n\n case \"source\":\n if (part.sourceType === \"url\") {\n return {\n type: \"source\",\n sourceType: \"url\",\n id: part.id,\n url: part.url,\n ...(part.title != null ? { title: part.title } : undefined),\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : undefined),\n };\n }\n\n return {\n type: \"source\",\n sourceType: \"document\",\n id: part.id,\n title: part.title,\n mediaType: part.mediaType,\n ...(part.filename != null\n ? { filename: part.filename }\n : undefined),\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : undefined),\n };\n\n case \"tool-call\": {\n if (!isJSONValue(part.result)) {\n console.warn(\n `tool-call result is not JSON! ${JSON.stringify(part)}`,\n );\n }\n return {\n type: \"tool-call\",\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n ...(JSON.stringify(part.args) === part.argsText\n ? { args: part.args }\n : { argsText: part.argsText }),\n ...(part.result\n ? { result: part.result as ReadonlyJSONValue }\n : undefined),\n ...(part.isError ? { isError: true } : undefined),\n ...(part.approval ? { approval: part.approval } : undefined),\n };\n }\n\n case \"image\":\n return { type: \"image\", image: part.image };\n\n case \"file\":\n return {\n type: \"file\",\n data: part.data,\n mimeType: part.mimeType,\n ...(part.filename ? { filename: part.filename } : undefined),\n };\n\n default: {\n const unhandledType: \"audio\" | \"data\" | \"generative-ui\" = type;\n throw new Error(\n `Message part type not supported by aui/v0: ${unhandledType}`,\n );\n }\n }\n }),\n metadata: message.metadata as AuiV0Message[\"metadata\"],\n ...(status ? { status } : undefined),\n ...(attachments ? { attachments } : undefined),\n };\n}\n\nexport function auiV0Decode(\n cloudMessage: CloudMessage & { format: \"aui/v0\" },\n): ExportedMessageRepositoryItem {\n const payload = cloudMessage.content as unknown as AuiV0Message;\n const message = fromThreadMessageLike(\n {\n id: cloudMessage.id,\n createdAt: cloudMessage.created_at,\n ...payload,\n },\n cloudMessage.id,\n { type: \"complete\", reason: \"unknown\" },\n );\n\n return {\n parentId: cloudMessage.parent_id,\n message,\n };\n}\n"],"mappings":";;;AAyHA,MAAM6D,wBACJC,SACwB;CACxB,MAAMrC,OAAOqC,KAAKrC;CAClB,QAAQA,MAAR;EACE,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,SACH,OAAOqC;EAET,KAAK;GACH,IAAI,CAAClD,YAAYkD,KAAKrB,IAAI,GACxBsB,QAAQC,KAAK,gCAAgCC,KAAKC,UAAUJ,IAAI,GAAG;GAErE,OAAO;IAAE,GAAGA;IAAMrB,MAAMqB,KAAKrB;GAA0B;EAGzD,SAEE,MAAM,IAAI2B,MACR,iDAAiDD,MACnD;CAEJ;AACF;AAEA,MAAME,qBACJC,YAC2C;CAC3C,IAAIA,QAAQpB,SAAS,UAAUoB,QAAQnB,YAAYoB,WAAW,GAC5D;CAGF,OAAOD,QAAQnB,YAAYsB,KACxB,EAAExD,IAAIQ,MAAMoB,MAAMC,aAAaC,QAAQC,eAAe;EACrD/B;EACAQ;EACAoB;EACAE;EACA,GAAID,eAAe,OAAO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MACNQ,YAAY6B,KAAK7B;MACjBC,UAAU4B,KAAK5B;MACf,GAAI+B,KAAKC,UAAUJ,KAAK3B,IAAI,MAAM2B,KAAKvB,WACnC,EAAEJ,MAAM2B,KAAK3B,KAAK,IAClB,EAAEI,UAAUuB,KAAKvB,SAAS;MAC9B,GAAIuB,KAAK1B,SACL,EAAEA,QAAQ0B,KAAK1B,OAA4B,IAC3CoC,KAAAA;MACJ,GAAIV,KAAKzB,UAAU,EAAEA,SAAS,KAAK,IAAImC,KAAAA;MACvC,GAAIV,KAAKxB,WAAW,EAAEA,UAAUwB,KAAKxB,SAAS,IAAIkC,KAAAA;KACpD;IAGF,KAAK,SACH,OAAO;KAAE/C,MAAM;KAASe,OAAOsB,KAAKtB;IAAM;IAE5C,KAAK,QACH,OAAO;KACLf,MAAM;KACNgB,MAAMqB,KAAKrB;KACXC,UAAUoB,KAAKpB;KACf,GAAIoB,KAAK9B,WAAW,EAAEA,UAAU8B,KAAK9B,SAAS,IAAIwC,KAAAA;IACpD;IAEF,SAEE,MAAM,IAAIJ,MACR,8CAA8CD,MAChD;GAEJ;EACF,CAAC;EACDf,UAAUkB,QAAQlB;EAClB,GAAIL,SAAS,EAAEA,OAAO,IAAIyB,KAAAA;EAC1B,GAAIrB,cAAc,EAAEA,YAAY,IAAIqB,KAAAA;CACtC;AACF;AAEA,SAAgBG,YACdC,cAC+B;CAC/B,MAAME,UAAUF,aAAa5B;CAC7B,MAAMsB,UAAU5D,sBACd;EACEO,IAAI2D,aAAa3D;EACjB8D,WAAWH,aAAaI;EACxB,GAAGF;CACL,GACAF,aAAa3D,IACb;EAAEQ,MAAM;EAAYN,QAAQ;CAAU,CACxC;CAEA,OAAO;EACL8D,UAAUL,aAAaM;EACvBZ;CACF;AACF"}
|
|
@@ -4,7 +4,7 @@ declare const createInitialQueueState: () => CommandQueueState;
|
|
|
4
4
|
declare const useCommandQueue: (opts: {
|
|
5
5
|
onQueue: () => void;
|
|
6
6
|
}) => {
|
|
7
|
-
state: CommandQueueState;
|
|
7
|
+
readonly state: CommandQueueState;
|
|
8
8
|
enqueue: (command: AssistantTransportCommand, options?: {
|
|
9
9
|
schedule?: boolean;
|
|
10
10
|
}) => void;
|
|
@@ -36,16 +36,17 @@ const useCommandQueue = (opts) => {
|
|
|
36
36
|
};
|
|
37
37
|
rerender((prev_1) => prev_1 + 1);
|
|
38
38
|
};
|
|
39
|
-
const reset = useCallback(() => {
|
|
40
|
-
queueStateRef.current = createInitialQueueState();
|
|
41
|
-
rerender((prev_2) => prev_2 + 1);
|
|
42
|
-
}, []);
|
|
43
39
|
return {
|
|
44
|
-
state
|
|
40
|
+
get state() {
|
|
41
|
+
return queueStateRef.current;
|
|
42
|
+
},
|
|
45
43
|
enqueue,
|
|
46
44
|
flush,
|
|
47
45
|
markDelivered,
|
|
48
|
-
reset
|
|
46
|
+
reset: useCallback(() => {
|
|
47
|
+
queueStateRef.current = createInitialQueueState();
|
|
48
|
+
rerender((prev_2) => prev_2 + 1);
|
|
49
|
+
}, [])
|
|
49
50
|
};
|
|
50
51
|
};
|
|
51
52
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commandQueue.js","names":["useState","useCallback","useRef","useEffect","AssistantTransportCommand","CommandQueueState","QueuedCommand","createInitialQueueState","queued","inTransit","useCommandQueue","opts","onQueue","onQueueRef","current","rerender","queueStateRef","enqueue","command","options","schedule","prev","flush","length","markDelivered","reset","state"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/commandQueue.ts"],"sourcesContent":["import { useState, useCallback, useRef, useEffect } from \"react\";\nimport type {\n AssistantTransportCommand,\n CommandQueueState,\n QueuedCommand,\n} from \"./types\";\n\nexport const createInitialQueueState = (): CommandQueueState => ({\n queued: [],\n inTransit: [],\n});\n\nexport const useCommandQueue = (opts: { onQueue: () => void }) => {\n const onQueueRef = useRef(opts.onQueue);\n useEffect(() => {\n onQueueRef.current = opts.onQueue;\n });\n\n const [, rerender] = useState(0);\n const queueStateRef = useRef<CommandQueueState>(createInitialQueueState());\n\n const enqueue = (\n command: AssistantTransportCommand,\n options?: { schedule?: boolean },\n ) => {\n queueStateRef.current = {\n queued: [...queueStateRef.current.queued, command],\n inTransit: queueStateRef.current.inTransit,\n };\n rerender((prev) => prev + 1);\n\n if (options?.schedule !== false) onQueueRef.current();\n };\n\n const flush = (): QueuedCommand[] => {\n if (queueStateRef.current.queued.length === 0) return [];\n\n const queued = queueStateRef.current.queued;\n queueStateRef.current = {\n queued: [],\n inTransit: [...queueStateRef.current.inTransit, ...queued],\n };\n rerender((prev) => prev + 1);\n\n return queued;\n };\n\n const markDelivered = () => {\n queueStateRef.current = { ...queueStateRef.current, inTransit: [] };\n rerender((prev) => prev + 1);\n };\n\n const reset = useCallback(() => {\n queueStateRef.current = createInitialQueueState();\n rerender((prev) => prev + 1);\n }, []);\n\n return {\n state
|
|
1
|
+
{"version":3,"file":"commandQueue.js","names":["useState","useCallback","useRef","useEffect","AssistantTransportCommand","CommandQueueState","QueuedCommand","createInitialQueueState","queued","inTransit","useCommandQueue","opts","onQueue","onQueueRef","current","rerender","queueStateRef","enqueue","command","options","schedule","prev","flush","length","markDelivered","reset","state"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/commandQueue.ts"],"sourcesContent":["import { useState, useCallback, useRef, useEffect } from \"react\";\nimport type {\n AssistantTransportCommand,\n CommandQueueState,\n QueuedCommand,\n} from \"./types\";\n\nexport const createInitialQueueState = (): CommandQueueState => ({\n queued: [],\n inTransit: [],\n});\n\nexport const useCommandQueue = (opts: { onQueue: () => void }) => {\n const onQueueRef = useRef(opts.onQueue);\n useEffect(() => {\n onQueueRef.current = opts.onQueue;\n });\n\n const [, rerender] = useState(0);\n const queueStateRef = useRef<CommandQueueState>(createInitialQueueState());\n\n const enqueue = (\n command: AssistantTransportCommand,\n options?: { schedule?: boolean },\n ) => {\n queueStateRef.current = {\n queued: [...queueStateRef.current.queued, command],\n inTransit: queueStateRef.current.inTransit,\n };\n rerender((prev) => prev + 1);\n\n if (options?.schedule !== false) onQueueRef.current();\n };\n\n const flush = (): QueuedCommand[] => {\n if (queueStateRef.current.queued.length === 0) return [];\n\n const queued = queueStateRef.current.queued;\n queueStateRef.current = {\n queued: [],\n inTransit: [...queueStateRef.current.inTransit, ...queued],\n };\n rerender((prev) => prev + 1);\n\n return queued;\n };\n\n const markDelivered = () => {\n queueStateRef.current = { ...queueStateRef.current, inTransit: [] };\n rerender((prev) => prev + 1);\n };\n\n const reset = useCallback(() => {\n queueStateRef.current = createInitialQueueState();\n rerender((prev) => prev + 1);\n }, []);\n\n return {\n // live getter — callbacks firing between renders must not see a stale snapshot\n get state() {\n return queueStateRef.current;\n },\n enqueue,\n flush,\n markDelivered,\n reset,\n };\n};\n"],"mappings":";;AAOA,MAAaO,iCAAoD;CAC/DC,QAAQ,CAAA;CACRC,WAAW,CAAA;AACb;AAEA,MAAaC,mBAAmBC,SAAkC;CAChE,MAAME,aAAaX,OAAOS,KAAKC,OAAO;CACtCT,gBAAgB;EACdU,WAAWC,UAAUH,KAAKC;CAC5B,CAAC;CAED,MAAM,GAAGG,YAAYf,SAAS,CAAC;CAC/B,MAAMgB,gBAAgBd,OAA0BK,wBAAwB,CAAC;CAEzE,MAAMU,WACJC,SACAC,YACG;EACHH,cAAcF,UAAU;GACtBN,QAAQ,CAAC,GAAGQ,cAAcF,QAAQN,QAAQU,OAAO;GACjDT,WAAWO,cAAcF,QAAQL;EACnC;EACAM,UAAUM,SAASA,OAAO,CAAC;EAE3B,IAAIF,SAASC,aAAa,OAAOP,WAAWC,QAAQ;CACtD;CAEA,MAAMQ,cAA+B;EACnC,IAAIN,cAAcF,QAAQN,OAAOe,WAAW,GAAG,OAAO,CAAA;EAEtD,MAAMf,SAASQ,cAAcF,QAAQN;EACrCQ,cAAcF,UAAU;GACtBN,QAAQ,CAAA;GACRC,WAAW,CAAC,GAAGO,cAAcF,QAAQL,WAAW,GAAGD,MAAM;EAC3D;EACAO,UAAUM,WAASA,SAAO,CAAC;EAE3B,OAAOb;CACT;CAEA,MAAMgB,sBAAsB;EAC1BR,cAAcF,UAAU;GAAE,GAAGE,cAAcF;GAASL,WAAW,CAAA;EAAG;EAClEM,UAAUM,WAASA,SAAO,CAAC;CAC7B;CAOA,OAAO;EAEL,IAAIK,QAAQ;GACV,OAAOV,cAAcF;EACvB;EACAG;EACAK;EACAE;EACAC,OAbYxB,kBAAkB;GAC9Be,cAAcF,UAAUP,wBAAwB;GAChDQ,UAAUM,WAASA,SAAO,CAAC;EAC7B,GAAG,CAAA,CAUDI;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runManager.d.ts","names":[],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/runManager.ts"],"mappings":";KAGY,aAAa;EACvB;EACA;EACA;;
|
|
1
|
+
{"version":3,"file":"runManager.d.ts","names":[],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/runManager.ts"],"mappings":";KAGY,aAAa;EACvB;EACA;EACA;;iBAKc,cAAc;EAC5B,QAAQ,QAAQ,gBAAgB;EAChC;EACA;EACA,YAAY,OAAO,iBAAiB;IAClC"}
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { useLatestRef } from "./useLatestRef.js";
|
|
2
|
-
import { useCallback, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "@assistant-ui/tap/react-shim";
|
|
3
3
|
//#region src/legacy-runtime/runtime-cores/assistant-transport/runManager.ts
|
|
4
|
+
const disposeReason = Symbol("assistant-transport-dispose");
|
|
4
5
|
function useRunManager(config) {
|
|
5
6
|
const [isRunning, setIsRunning] = useState(false);
|
|
6
7
|
const stateRef = useRef({
|
|
7
8
|
pending: false,
|
|
9
|
+
disposed: false,
|
|
8
10
|
abortController: null
|
|
9
11
|
});
|
|
10
12
|
const onRunRef = useLatestRef(config.onRun);
|
|
@@ -16,19 +18,22 @@ function useRunManager(config) {
|
|
|
16
18
|
stateRef.current.pending = false;
|
|
17
19
|
const ac = new AbortController();
|
|
18
20
|
stateRef.current.abortController = ac;
|
|
21
|
+
const disposeAborted = () => ac.signal.reason === disposeReason;
|
|
19
22
|
queueMicrotask(async () => {
|
|
20
23
|
try {
|
|
21
|
-
await onRunRef.current(ac.signal);
|
|
24
|
+
if (!disposeAborted()) await onRunRef.current(ac.signal);
|
|
22
25
|
} catch (error) {
|
|
23
|
-
stateRef.current.
|
|
24
|
-
|
|
25
|
-
|
|
26
|
+
if (!disposeAborted() && !stateRef.current.disposed) {
|
|
27
|
+
stateRef.current.pending = false;
|
|
28
|
+
if (ac.signal.aborted) onCancelRef.current?.();
|
|
29
|
+
else await onErrorRef.current?.(error);
|
|
30
|
+
}
|
|
26
31
|
} finally {
|
|
27
|
-
onFinishRef.current?.();
|
|
28
|
-
if (stateRef.current.pending) startRun();
|
|
32
|
+
if (!disposeAborted() && !stateRef.current.disposed) onFinishRef.current?.();
|
|
33
|
+
if (!stateRef.current.disposed && stateRef.current.pending) startRun();
|
|
29
34
|
else {
|
|
30
35
|
setIsRunning(false);
|
|
31
|
-
stateRef.current.abortController = null;
|
|
36
|
+
if (stateRef.current.abortController === ac) stateRef.current.abortController = null;
|
|
32
37
|
}
|
|
33
38
|
}
|
|
34
39
|
});
|
|
@@ -38,15 +43,25 @@ function useRunManager(config) {
|
|
|
38
43
|
onErrorRef,
|
|
39
44
|
onCancelRef
|
|
40
45
|
]);
|
|
46
|
+
const schedule = useCallback(() => {
|
|
47
|
+
if (stateRef.current.disposed) return;
|
|
48
|
+
if (stateRef.current.abortController) {
|
|
49
|
+
stateRef.current.pending = true;
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
startRun();
|
|
53
|
+
}, [startRun]);
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
stateRef.current.disposed = false;
|
|
56
|
+
return () => {
|
|
57
|
+
stateRef.current.disposed = true;
|
|
58
|
+
stateRef.current.pending = false;
|
|
59
|
+
stateRef.current.abortController?.abort(disposeReason);
|
|
60
|
+
};
|
|
61
|
+
}, []);
|
|
41
62
|
return {
|
|
42
63
|
isRunning,
|
|
43
|
-
schedule
|
|
44
|
-
if (stateRef.current.abortController) {
|
|
45
|
-
stateRef.current.pending = true;
|
|
46
|
-
return;
|
|
47
|
-
}
|
|
48
|
-
startRun();
|
|
49
|
-
}, [startRun]),
|
|
64
|
+
schedule,
|
|
50
65
|
cancel: useCallback(() => {
|
|
51
66
|
stateRef.current.pending = false;
|
|
52
67
|
stateRef.current.abortController?.abort();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"runManager.js","names":["useCallback","useRef","useState","useLatestRef","RunManager","Readonly","isRunning","schedule","cancel","useRunManager","config","onRun","signal","AbortSignal","Promise","onFinish","onCancel","onError","error","Error","setIsRunning","stateRef","pending","abortController","AbortController","onRunRef","onFinishRef","onCancelRef","onErrorRef","startRun","current","ac","queueMicrotask","aborted","abort"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/runManager.ts"],"sourcesContent":["import { useCallback, useRef, useState } from \"react\";\nimport { useLatestRef } from \"./useLatestRef\";\n\nexport type RunManager = Readonly<{\n isRunning: boolean;\n schedule: () => void;\n cancel: () => void;\n}>;\n\nexport function useRunManager(config: {\n onRun: (signal: AbortSignal) => Promise<void>;\n onFinish?: (() => void) | undefined;\n onCancel?: (() => void) | undefined;\n onError?: ((error: Error) => void | Promise<void>) | undefined;\n}): RunManager {\n const [isRunning, setIsRunning] = useState(false);\n const stateRef = useRef({\n pending: false,\n abortController: null as AbortController | null,\n });\n const onRunRef = useLatestRef(config.onRun);\n const onFinishRef = useLatestRef(config.onFinish);\n const onCancelRef = useLatestRef(config.onCancel);\n const onErrorRef = useLatestRef(config.onError);\n\n const startRun = useCallback(() => {\n setIsRunning(true);\n stateRef.current.pending = false;\n const ac = new AbortController();\n stateRef.current.abortController = ac;\n\n queueMicrotask(async () => {\n try {\n await onRunRef.current(ac.signal);\n } catch (error) {\n stateRef.current.pending = false;\n
|
|
1
|
+
{"version":3,"file":"runManager.js","names":["useCallback","useEffect","useRef","useState","useLatestRef","RunManager","Readonly","isRunning","schedule","cancel","disposeReason","Symbol","useRunManager","config","onRun","signal","AbortSignal","Promise","onFinish","onCancel","onError","error","Error","setIsRunning","stateRef","pending","disposed","abortController","AbortController","onRunRef","onFinishRef","onCancelRef","onErrorRef","startRun","current","ac","disposeAborted","reason","queueMicrotask","aborted","abort"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/runManager.ts"],"sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\nimport { useLatestRef } from \"./useLatestRef\";\n\nexport type RunManager = Readonly<{\n isRunning: boolean;\n schedule: () => void;\n cancel: () => void;\n}>;\n\nconst disposeReason = Symbol(\"assistant-transport-dispose\");\n\nexport function useRunManager(config: {\n onRun: (signal: AbortSignal) => Promise<void>;\n onFinish?: (() => void) | undefined;\n onCancel?: (() => void) | undefined;\n onError?: ((error: Error) => void | Promise<void>) | undefined;\n}): RunManager {\n const [isRunning, setIsRunning] = useState(false);\n const stateRef = useRef({\n pending: false,\n disposed: false,\n abortController: null as AbortController | null,\n });\n const onRunRef = useLatestRef(config.onRun);\n const onFinishRef = useLatestRef(config.onFinish);\n const onCancelRef = useLatestRef(config.onCancel);\n const onErrorRef = useLatestRef(config.onError);\n\n const startRun = useCallback(() => {\n setIsRunning(true);\n stateRef.current.pending = false;\n const ac = new AbortController();\n stateRef.current.abortController = ac;\n\n // The dispose marker rides on the abort reason so a settling run detects\n // its own disposal even after an effect cycle re-arms the manager.\n const disposeAborted = () => ac.signal.reason === disposeReason;\n\n queueMicrotask(async () => {\n try {\n if (!disposeAborted()) {\n await onRunRef.current(ac.signal);\n }\n } catch (error) {\n if (!disposeAborted() && !stateRef.current.disposed) {\n stateRef.current.pending = false;\n if (ac.signal.aborted) {\n onCancelRef.current?.();\n } else {\n await onErrorRef.current?.(error as Error);\n }\n }\n } finally {\n if (!disposeAborted() && !stateRef.current.disposed) {\n onFinishRef.current?.();\n }\n if (!stateRef.current.disposed && stateRef.current.pending) {\n startRun();\n } else {\n setIsRunning(false);\n if (stateRef.current.abortController === ac) {\n stateRef.current.abortController = null;\n }\n }\n }\n });\n }, [onRunRef, onFinishRef, onErrorRef, onCancelRef]);\n\n const schedule = useCallback(() => {\n if (stateRef.current.disposed) return;\n if (stateRef.current.abortController) {\n // Coalesce multiple schedules while running into a single follow-up run.\n stateRef.current.pending = true;\n return;\n }\n startRun();\n }, [startRun]);\n\n // Strict-mode effects run setup / cleanup / setup on the same instance;\n // arming on setup undoes the cleanup's dispose.\n useEffect(() => {\n stateRef.current.disposed = false;\n return () => {\n stateRef.current.disposed = true;\n stateRef.current.pending = false;\n stateRef.current.abortController?.abort(disposeReason);\n };\n }, []);\n\n const cancel = useCallback(() => {\n stateRef.current.pending = false;\n stateRef.current.abortController?.abort();\n }, []);\n\n return {\n isRunning,\n schedule,\n cancel,\n };\n}\n"],"mappings":";;;AASA,MAAMU,gBAAgBC,OAAO,6BAA6B;AAE1D,SAAgBC,cAAcC,QAKf;CACb,MAAM,CAACN,WAAWgB,gBAAgBpB,SAAS,KAAK;CAChD,MAAMqB,WAAWtB,OAAO;EACtBuB,SAAS;EACTC,UAAU;EACVC,iBAAiB;CACnB,CAAC;CACD,MAAME,WAAWzB,aAAaS,OAAOC,KAAK;CAC1C,MAAMgB,cAAc1B,aAAaS,OAAOK,QAAQ;CAChD,MAAMa,cAAc3B,aAAaS,OAAOM,QAAQ;CAChD,MAAMa,aAAa5B,aAAaS,OAAOO,OAAO;CAE9C,MAAMa,WAAWjC,kBAAkB;EACjCuB,aAAa,IAAI;EACjBC,SAASU,QAAQT,UAAU;EAC3B,MAAMU,KAAK,IAAIP,gBAAgB;EAC/BJ,SAASU,QAAQP,kBAAkBQ;EAInC,MAAMC,uBAAuBD,GAAGpB,OAAOsB,WAAW3B;EAElD4B,eAAe,YAAY;GACzB,IAAI;IACF,IAAI,CAACF,eAAe,GAClB,MAAMP,SAASK,QAAQC,GAAGpB,MAAM;GAEpC,SAASM,OAAO;IACd,IAAI,CAACe,eAAe,KAAK,CAACZ,SAASU,QAAQR,UAAU;KACnDF,SAASU,QAAQT,UAAU;KAC3B,IAAIU,GAAGpB,OAAOwB,SACZR,YAAYG,UAAU;UAEtB,MAAMF,WAAWE,UAAUb,KAAc;IAE7C;GACF,UAAU;IACR,IAAI,CAACe,eAAe,KAAK,CAACZ,SAASU,QAAQR,UACzCI,YAAYI,UAAU;IAExB,IAAI,CAACV,SAASU,QAAQR,YAAYF,SAASU,QAAQT,SACjDQ,SAAS;SACJ;KACLV,aAAa,KAAK;KAClB,IAAIC,SAASU,QAAQP,oBAAoBQ,IACvCX,SAASU,QAAQP,kBAAkB;IAEvC;GACF;EACF,CAAC;CACH,GAAG;EAACE;EAAUC;EAAaE;EAAYD;CAAW,CAAC;CAEnD,MAAMvB,WAAWR,kBAAkB;EACjC,IAAIwB,SAASU,QAAQR,UAAU;EAC/B,IAAIF,SAASU,QAAQP,iBAAiB;GAEpCH,SAASU,QAAQT,UAAU;GAC3B;EACF;EACAQ,SAAS;CACX,GAAG,CAACA,QAAQ,CAAC;CAIbhC,gBAAgB;EACduB,SAASU,QAAQR,WAAW;EAC5B,aAAa;GACXF,SAASU,QAAQR,WAAW;GAC5BF,SAASU,QAAQT,UAAU;GAC3BD,SAASU,QAAQP,iBAAiBa,MAAM9B,aAAa;EACvD;CACF,GAAG,CAAA,CAAE;CAOL,OAAO;EACLH;EACAC;EACAC,QARaT,kBAAkB;GAC/BwB,SAASU,QAAQT,UAAU;GAC3BD,SAASU,QAAQP,iBAAiBa,MAAM;EAC1C,GAAG,CAAA,CAKD/B;CACF;AACF"}
|
package/dist/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAssistantTransportRuntime.d.ts","names":[],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.ts"],"mappings":";;;;cA8Fa,yCAGH,SAAS;iBAOH,8BAA8B;iBAC9B,2BAA2B,GACzC,WAAW,OAAO,sBAAsB,IACvC;;;;
|
|
1
|
+
{"version":3,"file":"useAssistantTransportRuntime.d.ts","names":[],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.ts"],"mappings":";;;;cA8Fa,yCAGH,SAAS;iBAOH,8BAA8B;iBAC9B,2BAA2B,GACzC,WAAW,OAAO,sBAAsB,IACvC;;;;cA6RU,+BAAgC,GAC3C,SAAS,0BAA0B,OAClC"}
|
package/dist/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.js
CHANGED
|
@@ -43,12 +43,12 @@ const useAssistantTransportSendCommand = () => {
|
|
|
43
43
|
const $ = c(2);
|
|
44
44
|
const aui = useAui();
|
|
45
45
|
let t0;
|
|
46
|
-
if ($[0] !== aui) {
|
|
46
|
+
if ($[0] !== aui.thread) {
|
|
47
47
|
t0 = (command) => {
|
|
48
|
-
const extras = aui.thread
|
|
48
|
+
const extras = aui.thread.getState().extras;
|
|
49
49
|
asAssistantTransportExtras(extras).sendCommand(command);
|
|
50
50
|
};
|
|
51
|
-
$[0] = aui;
|
|
51
|
+
$[0] = aui.thread;
|
|
52
52
|
$[1] = t0;
|
|
53
53
|
} else t0 = $[1];
|
|
54
54
|
return t0;
|
|
@@ -71,7 +71,9 @@ const useAssistantTransportThreadRuntime = (options) => {
|
|
|
71
71
|
resumeFlagRef.current = false;
|
|
72
72
|
setIsReplaying(false);
|
|
73
73
|
const commands = isResume ? [] : commandQueue.flush();
|
|
74
|
-
if (commands.length === 0 && !isResume)
|
|
74
|
+
if (commands.length === 0 && !isResume) return;
|
|
75
|
+
const parentId = isResume ? void 0 : parentIdRef.current;
|
|
76
|
+
if (!isResume) parentIdRef.current = void 0;
|
|
75
77
|
const headers = await createRequestHeaders(options.headers);
|
|
76
78
|
const bodyValue = typeof options.body === "function" ? await options.body() : options.body;
|
|
77
79
|
const context = runtime.thread.getModelContext();
|
|
@@ -81,7 +83,7 @@ const useAssistantTransportThreadRuntime = (options) => {
|
|
|
81
83
|
system: context.system,
|
|
82
84
|
tools: context.tools ? toToolsJSONSchema(context.tools) : void 0,
|
|
83
85
|
threadId,
|
|
84
|
-
...
|
|
86
|
+
...parentId !== void 0 && { parentId },
|
|
85
87
|
callSettings: context.callSettings,
|
|
86
88
|
config: context.config,
|
|
87
89
|
...context.callSettings,
|
|
@@ -122,6 +124,8 @@ const useAssistantTransportThreadRuntime = (options) => {
|
|
|
122
124
|
rerender((prev) => prev + 1);
|
|
123
125
|
}
|
|
124
126
|
if (err) throw new Error(err);
|
|
127
|
+
if (!markedDelivered) commandQueue.markDelivered();
|
|
128
|
+
if (isResume && commandQueue.state.queued.length > 0) runManager.schedule();
|
|
125
129
|
},
|
|
126
130
|
onFinish: options.onFinish,
|
|
127
131
|
onCancel: () => {
|
|
@@ -189,8 +193,8 @@ const useAssistantTransportThreadRuntime = (options) => {
|
|
|
189
193
|
const command_1 = convertAppendMessageToCommand(message_0);
|
|
190
194
|
commandQueue.enqueue(command_1, { schedule: message_0.startRun ?? message_0.role === "user" });
|
|
191
195
|
} },
|
|
192
|
-
...commandQueue.state.queued.length > 0 && { onReload: async (
|
|
193
|
-
parentIdRef.current =
|
|
196
|
+
...commandQueue.state.queued.length > 0 && { onReload: async (parentId_0) => {
|
|
197
|
+
parentIdRef.current = parentId_0;
|
|
194
198
|
runManager.schedule();
|
|
195
199
|
} },
|
|
196
200
|
onCancel: async () => {
|
package/dist/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAssistantTransportRuntime.js","names":["c","_c","AppendMessage","ReadonlyJSONObject","ReadonlyJSONValue","asAsyncIterableStream","useExternalStoreRuntime","AssistantRuntime","AddToolResultOptions","useMemo","useRef","useState","AssistantMessageAccumulator","DataStreamDecoder","AssistantTransportDecoder","unstable_createInitialMessage","createInitialMessage","toToolsJSONSchema","AssistantTransportOptions","AddMessageCommand","AddToolResultCommand","UserMessagePart","QueuedCommand","AssistantTransportCommand","SendCommandsRequestBody","useCommandQueue","createReplayBoundaryStream","useReplayRenderWait","useRunManager","useConvertedState","ToolExecutionStatus","createRequestHeaders","useRemoteThreadListRuntime","InMemoryThreadListAdapter","useAui","useAuiState","UserExternalState","convertAppendMessageToCommand","message","role","Error","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","parentId","sourceId","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","state","asAssistantTransportExtras","extras","useAssistantTransportSendCommand","$","aui","t0","thread","getState","transportExtras","useAssistantTransportState","selector","T","t","s","useAssistantTransportThreadRuntime","options","agentStateRef","initialState","rerender","resumeFlagRef","isReplaying","setIsReplaying","waitForReplayRender","parentIdRef","undefined","commandQueue","onQueue","runManager","schedule","threadId","threadListItem","remoteId","onRun","signal","AbortSignal","isResume","current","commands","flush","length","headers","bodyValue","body","context","runtime","getModelContext","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","status","setReplaying","waitForRender","protocol","decoder","err","stream","pipeThrough","initialMessage","unstable_state","throttle","onError","error","markedDelivered","chunk","metadata","markDelivered","prev","onFinish","onCancel","cmds","inTransit","queued","reset","updateState","updater","inTransitCmds","queuedCmds","toolStatuses","setToolStatuses","pendingCommands","converted","converter","isRunning","messages","isLoading","adapters","unstable_enableToolInvocations","enqueue","onNew","Promise","startRun","capabilities","edit","onEdit","onReload","cancel","onResume","onAddToolResult","toolOptions","toolCallId","result","toolName","isError","artifact","modelContent","onLoadExternalState","useAssistantTransportRuntime","runtimeHook","RuntimeHook","adapter","allowNesting"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport type { AppendMessage } from \"@assistant-ui/core\";\nimport {\n type ReadonlyJSONObject,\n type ReadonlyJSONValue,\n asAsyncIterableStream,\n} from \"assistant-stream/utils\";\nimport { useExternalStoreRuntime } from \"../external-store/useExternalStoreRuntime\";\nimport type { AssistantRuntime } from \"../../runtime/AssistantRuntime\";\nimport type { AddToolResultOptions } from \"@assistant-ui/core\";\nimport { useMemo, useRef, useState } from \"react\";\nimport {\n AssistantMessageAccumulator,\n DataStreamDecoder,\n AssistantTransportDecoder,\n unstable_createInitialMessage as createInitialMessage,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type {\n AssistantTransportOptions,\n AddMessageCommand,\n AddToolResultCommand,\n UserMessagePart,\n QueuedCommand,\n AssistantTransportCommand,\n SendCommandsRequestBody,\n} from \"./types\";\nimport { useCommandQueue } from \"./commandQueue\";\nimport {\n createReplayBoundaryStream,\n useReplayRenderWait,\n} from \"./replayBoundaryStream\";\nimport { useRunManager } from \"./runManager\";\nimport { useConvertedState } from \"./useConvertedState\";\nimport type { ToolExecutionStatus } from \"@assistant-ui/core\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport { useRemoteThreadListRuntime } from \"../remote-thread-list/useRemoteThreadListRuntime\";\nimport { InMemoryThreadListAdapter } from \"@assistant-ui/core\";\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport type { UserExternalState } from \"../../../augmentations\";\n\nconst convertAppendMessageToCommand = (\n message: AppendMessage,\n): AddMessageCommand => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n return {\n type: \"add-message\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst symbolAssistantTransportExtras = Symbol(\"assistant-transport-extras\");\ntype AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n state: UserExternalState;\n};\n\nconst asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using useAssistantTransportRuntime\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nexport const useAssistantTransportSendCommand = () => {\n const aui = useAui();\n\n return (command: AssistantTransportCommand) => {\n const extras = aui.thread().getState().extras;\n const transportExtras = asAssistantTransportExtras(extras);\n transportExtras.sendCommand(command);\n };\n};\n\nexport function useAssistantTransportState(): UserExternalState;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(asAssistantTransportExtras(s.thread.extras).state),\n );\n}\n\nconst useAssistantTransportThreadRuntime = <T>(\n options: AssistantTransportOptions<T>,\n): AssistantRuntime => {\n const agentStateRef = useRef(options.initialState);\n const [, rerender] = useState(0);\n const resumeFlagRef = useRef(false);\n const [isReplaying, setIsReplaying] = useState(false);\n const waitForReplayRender = useReplayRenderWait();\n const parentIdRef = useRef<string | null | undefined>(undefined);\n const commandQueue = useCommandQueue({\n onQueue: () => runManager.schedule(),\n });\n\n const threadId = useAuiState((s) => s.threadListItem.remoteId);\n\n const runManager = useRunManager({\n onRun: async (signal: AbortSignal) => {\n const isResume = resumeFlagRef.current;\n resumeFlagRef.current = false;\n setIsReplaying(false);\n const commands: QueuedCommand[] = isResume ? [] : commandQueue.flush();\n if (commands.length === 0 && !isResume)\n throw new Error(\"No commands to send\");\n\n const headers = await createRequestHeaders(options.headers);\n const bodyValue =\n typeof options.body === \"function\"\n ? await options.body()\n : options.body;\n const context = runtime.thread.getModelContext();\n\n let requestBody: Record<string, unknown> = {\n commands,\n state: agentStateRef.current,\n system: context.system,\n tools: context.tools ? toToolsJSONSchema(context.tools) : undefined,\n threadId,\n ...(parentIdRef.current !== undefined && {\n parentId: parentIdRef.current,\n }),\n // nested (new format, aligned with AssistantChatTransport)\n callSettings: context.callSettings,\n config: context.config,\n // @deprecated spread at top level — use nested `callSettings`/`config` instead. Will be removed in a future version.\n ...context.callSettings,\n ...context.config,\n ...(bodyValue ?? {}),\n };\n\n if (options.prepareSendCommandsRequest) {\n requestBody = await options.prepareSendCommandsRequest(\n requestBody as SendCommandsRequestBody,\n );\n }\n\n const response = await fetch(\n isResume ? options.resumeApi! : options.api,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n },\n );\n\n options.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, {\n setReplaying: setIsReplaying,\n waitForRender: waitForReplayRender,\n });\n\n // Select decoder based on protocol option\n const protocol = options.protocol ?? \"data-stream\";\n const decoder =\n protocol === \"assistant-transport\"\n ? new AssistantTransportDecoder()\n : new DataStreamDecoder();\n\n let err: string | undefined;\n const stream = body.pipeThrough(decoder).pipeThrough(\n new AssistantMessageAccumulator({\n initialMessage: createInitialMessage({\n unstable_state:\n (agentStateRef.current as ReadonlyJSONValue) ?? null,\n }),\n throttle: isResume,\n onError: (error) => {\n err = error;\n },\n }),\n );\n\n let markedDelivered = false;\n\n for await (const chunk of asAsyncIterableStream(stream)) {\n if (chunk.metadata.unstable_state === agentStateRef.current) continue;\n\n if (!markedDelivered) {\n commandQueue.markDelivered();\n markedDelivered = true;\n }\n\n agentStateRef.current = chunk.metadata.unstable_state as T;\n rerender((prev) => prev + 1);\n }\n\n if (err) {\n throw new Error(err);\n }\n },\n onFinish: options.onFinish,\n onCancel: () => {\n setIsReplaying(false);\n const cmds = [\n ...commandQueue.state.inTransit,\n ...commandQueue.state.queued,\n ];\n\n commandQueue.reset();\n\n options.onCancel?.({\n commands: cmds,\n updateState: (updater) => {\n agentStateRef.current = updater(agentStateRef.current);\n rerender((prev) => prev + 1);\n },\n });\n },\n onError: async (error) => {\n setIsReplaying(false);\n const inTransitCmds = [...commandQueue.state.inTransit];\n const queuedCmds = [...commandQueue.state.queued];\n\n commandQueue.reset();\n\n try {\n await options.onError?.(error as Error, {\n commands: inTransitCmds,\n updateState: (updater) => {\n agentStateRef.current = updater(agentStateRef.current);\n rerender((prev) => prev + 1);\n },\n });\n } finally {\n options.onCancel?.({\n commands: queuedCmds,\n updateState: (updater) => {\n agentStateRef.current = updater(agentStateRef.current);\n rerender((prev) => prev + 1);\n },\n error: error as Error,\n });\n }\n },\n });\n\n // Tool execution status state\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n\n // Reactive conversion of agent state + connection metadata → UI state\n const pendingCommands = useMemo(\n () => [...commandQueue.state.inTransit, ...commandQueue.state.queued],\n [commandQueue.state],\n );\n const converted = useConvertedState(\n options.converter,\n agentStateRef.current,\n pendingCommands,\n runManager.isRunning,\n toolStatuses,\n );\n\n // Create runtime\n const runtime = useExternalStoreRuntime({\n messages: converted.messages,\n state: converted.state,\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n adapters: options.adapters,\n unstable_enableToolInvocations: true,\n setToolStatuses,\n extras: {\n [symbolAssistantTransportExtras]: true,\n sendCommand: (command: AssistantTransportCommand) => {\n commandQueue.enqueue(command);\n },\n state: agentStateRef.current as UserExternalState,\n } satisfies AssistantTransportExtras,\n onNew: async (message: AppendMessage): Promise<void> => {\n parentIdRef.current = message.parentId;\n const command = convertAppendMessageToCommand(message);\n commandQueue.enqueue(command, {\n schedule: message.startRun ?? message.role === \"user\",\n });\n },\n ...(options.capabilities?.edit && {\n onEdit: async (message: AppendMessage): Promise<void> => {\n parentIdRef.current = message.parentId;\n const command = convertAppendMessageToCommand(message);\n commandQueue.enqueue(command, {\n schedule: message.startRun ?? message.role === \"user\",\n });\n },\n }),\n ...(commandQueue.state.queued.length > 0 && {\n onReload: async (parentId: string | null) => {\n parentIdRef.current = parentId;\n runManager.schedule();\n },\n }),\n onCancel: async () => {\n runManager.cancel();\n },\n onResume: async () => {\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n resumeFlagRef.current = true;\n runManager.schedule();\n },\n onAddToolResult: async (\n toolOptions: AddToolResultOptions,\n ): Promise<void> => {\n const command: AddToolResultCommand = {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n result: toolOptions.result as ReadonlyJSONObject,\n toolName: toolOptions.toolName,\n isError: toolOptions.isError,\n ...(toolOptions.artifact && { artifact: toolOptions.artifact }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n };\n\n commandQueue.enqueue(command);\n },\n onLoadExternalState: async (state) => {\n agentStateRef.current = state as T;\n rerender((prev) => prev + 1);\n },\n });\n\n return runtime;\n};\n\n/**\n * @alpha This is an experimental API that is subject to change.\n */\nexport const useAssistantTransportRuntime = <T>(\n options: AssistantTransportOptions<T>,\n): AssistantRuntime => {\n const runtime = useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useAssistantTransportThreadRuntime(options);\n },\n adapter: new InMemoryThreadListAdapter(),\n allowNesting: true,\n });\n return runtime;\n};\n"],"mappings":";;;;;;;;;;;;;;AA0CA,MAAMqC,iCACJC,YACsB;CACtB,IAAIA,QAAQC,SAAS,QACnB,MAAM,IAAIC,MAAM,kCAAkC;CAEpD,MAAMC,QAA2B,CAAA;CACjC,MAAMC,UAAU,CACd,GAAGJ,QAAQI,SACX,GAAIJ,QAAQK,aAAaC,SAASC,MAAMA,EAAEH,OAAO,KAAK,CAAA,CAAG;CAE3D,KAAK,MAAMI,eAAeJ,SACxB,IAAII,YAAYC,SAAS,QACvBN,MAAMO,KAAK;EAAED,MAAM;EAAQE,MAAMH,YAAYG;CAA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"useAssistantTransportRuntime.js","names":["c","_c","AppendMessage","ReadonlyJSONObject","ReadonlyJSONValue","asAsyncIterableStream","useExternalStoreRuntime","AssistantRuntime","AddToolResultOptions","useMemo","useRef","useState","AssistantMessageAccumulator","DataStreamDecoder","AssistantTransportDecoder","unstable_createInitialMessage","createInitialMessage","toToolsJSONSchema","AssistantTransportOptions","AddMessageCommand","AddToolResultCommand","UserMessagePart","QueuedCommand","AssistantTransportCommand","SendCommandsRequestBody","useCommandQueue","createReplayBoundaryStream","useReplayRenderWait","useRunManager","useConvertedState","ToolExecutionStatus","createRequestHeaders","useRemoteThreadListRuntime","InMemoryThreadListAdapter","useAui","useAuiState","UserExternalState","convertAppendMessageToCommand","message","role","Error","parts","content","attachments","flatMap","a","contentPart","type","push","text","image","parentId","sourceId","symbolAssistantTransportExtras","Symbol","AssistantTransportExtras","sendCommand","command","state","asAssistantTransportExtras","extras","useAssistantTransportSendCommand","$","aui","t0","thread","getState","transportExtras","useAssistantTransportState","selector","T","t","s","useAssistantTransportThreadRuntime","options","agentStateRef","initialState","rerender","resumeFlagRef","isReplaying","setIsReplaying","waitForReplayRender","parentIdRef","undefined","commandQueue","onQueue","runManager","schedule","threadId","threadListItem","remoteId","onRun","signal","AbortSignal","isResume","current","commands","flush","length","headers","bodyValue","body","context","runtime","getModelContext","requestBody","Record","system","tools","callSettings","config","prepareSendCommandsRequest","response","fetch","resumeApi","api","method","JSON","stringify","onResponse","ok","status","setReplaying","waitForRender","protocol","decoder","err","stream","pipeThrough","initialMessage","unstable_state","throttle","onError","error","markedDelivered","chunk","metadata","markDelivered","prev","queued","onFinish","onCancel","cmds","inTransit","reset","updateState","updater","inTransitCmds","queuedCmds","toolStatuses","setToolStatuses","pendingCommands","converted","converter","isRunning","messages","isLoading","adapters","unstable_enableToolInvocations","enqueue","onNew","Promise","startRun","capabilities","edit","onEdit","onReload","cancel","onResume","onAddToolResult","toolOptions","toolCallId","result","toolName","isError","artifact","modelContent","onLoadExternalState","useAssistantTransportRuntime","runtimeHook","RuntimeHook","adapter","allowNesting"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/useAssistantTransportRuntime.ts"],"sourcesContent":["\"use client\";\n\nimport type { AppendMessage } from \"@assistant-ui/core\";\nimport {\n type ReadonlyJSONObject,\n type ReadonlyJSONValue,\n asAsyncIterableStream,\n} from \"assistant-stream/utils\";\nimport { useExternalStoreRuntime } from \"../external-store/useExternalStoreRuntime\";\nimport type { AssistantRuntime } from \"../../runtime/AssistantRuntime\";\nimport type { AddToolResultOptions } from \"@assistant-ui/core\";\nimport { useMemo, useRef, useState } from \"react\";\nimport {\n AssistantMessageAccumulator,\n DataStreamDecoder,\n AssistantTransportDecoder,\n unstable_createInitialMessage as createInitialMessage,\n toToolsJSONSchema,\n} from \"assistant-stream\";\nimport type {\n AssistantTransportOptions,\n AddMessageCommand,\n AddToolResultCommand,\n UserMessagePart,\n QueuedCommand,\n AssistantTransportCommand,\n SendCommandsRequestBody,\n} from \"./types\";\nimport { useCommandQueue } from \"./commandQueue\";\nimport {\n createReplayBoundaryStream,\n useReplayRenderWait,\n} from \"./replayBoundaryStream\";\nimport { useRunManager } from \"./runManager\";\nimport { useConvertedState } from \"./useConvertedState\";\nimport type { ToolExecutionStatus } from \"@assistant-ui/core\";\nimport { createRequestHeaders } from \"@assistant-ui/core\";\nimport { useRemoteThreadListRuntime } from \"../remote-thread-list/useRemoteThreadListRuntime\";\nimport { InMemoryThreadListAdapter } from \"@assistant-ui/core\";\nimport { useAui, useAuiState } from \"@assistant-ui/store\";\nimport type { UserExternalState } from \"../../../augmentations\";\n\nconst convertAppendMessageToCommand = (\n message: AppendMessage,\n): AddMessageCommand => {\n if (message.role !== \"user\")\n throw new Error(\"Only user messages are supported\");\n\n const parts: UserMessagePart[] = [];\n const content = [\n ...message.content,\n ...(message.attachments?.flatMap((a) => a.content) ?? []),\n ];\n for (const contentPart of content) {\n if (contentPart.type === \"text\") {\n parts.push({ type: \"text\", text: contentPart.text });\n } else if (contentPart.type === \"image\") {\n parts.push({ type: \"image\", image: contentPart.image });\n }\n }\n\n return {\n type: \"add-message\",\n message: {\n role: \"user\",\n parts,\n },\n parentId: message.parentId,\n sourceId: message.sourceId,\n };\n};\n\nconst symbolAssistantTransportExtras = Symbol(\"assistant-transport-extras\");\ntype AssistantTransportExtras = {\n [symbolAssistantTransportExtras]: true;\n sendCommand: (command: AssistantTransportCommand) => void;\n state: UserExternalState;\n};\n\nconst asAssistantTransportExtras = (\n extras: unknown,\n): AssistantTransportExtras => {\n if (\n typeof extras !== \"object\" ||\n extras == null ||\n !(symbolAssistantTransportExtras in extras)\n )\n throw new Error(\n \"This method can only be called when you are using useAssistantTransportRuntime\",\n );\n\n return extras as AssistantTransportExtras;\n};\n\nexport const useAssistantTransportSendCommand = () => {\n const aui = useAui();\n\n return (command: AssistantTransportCommand) => {\n const extras = aui.thread.getState().extras;\n const transportExtras = asAssistantTransportExtras(extras);\n transportExtras.sendCommand(command);\n };\n};\n\nexport function useAssistantTransportState(): UserExternalState;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T,\n): T;\nexport function useAssistantTransportState<T>(\n selector: (state: UserExternalState) => T = (t) => t as T,\n): T | UserExternalState {\n return useAuiState((s) =>\n selector(asAssistantTransportExtras(s.thread.extras).state),\n );\n}\n\nconst useAssistantTransportThreadRuntime = <T>(\n options: AssistantTransportOptions<T>,\n): AssistantRuntime => {\n const agentStateRef = useRef(options.initialState);\n const [, rerender] = useState(0);\n const resumeFlagRef = useRef(false);\n const [isReplaying, setIsReplaying] = useState(false);\n const waitForReplayRender = useReplayRenderWait();\n const parentIdRef = useRef<string | null | undefined>(undefined);\n const commandQueue = useCommandQueue({\n onQueue: () => runManager.schedule(),\n });\n\n const threadId = useAuiState((s) => s.threadListItem.remoteId);\n\n const runManager = useRunManager({\n onRun: async (signal: AbortSignal) => {\n const isResume = resumeFlagRef.current;\n resumeFlagRef.current = false;\n setIsReplaying(false);\n const commands: QueuedCommand[] = isResume ? [] : commandQueue.flush();\n if (commands.length === 0 && !isResume) return;\n\n // The flushed batch consumes the parentId; read it alongside the flush\n // (before any awaits) so a mid-run append keeps its own value. Resume\n // runs send no commands, so they neither send nor consume it.\n const parentId = isResume ? undefined : parentIdRef.current;\n if (!isResume) parentIdRef.current = undefined;\n\n const headers = await createRequestHeaders(options.headers);\n const bodyValue =\n typeof options.body === \"function\"\n ? await options.body()\n : options.body;\n const context = runtime.thread.getModelContext();\n\n let requestBody: Record<string, unknown> = {\n commands,\n state: agentStateRef.current,\n system: context.system,\n tools: context.tools ? toToolsJSONSchema(context.tools) : undefined,\n threadId,\n ...(parentId !== undefined && {\n parentId,\n }),\n // nested (new format, aligned with AssistantChatTransport)\n callSettings: context.callSettings,\n config: context.config,\n // @deprecated spread at top level — use nested `callSettings`/`config` instead. Will be removed in a future version.\n ...context.callSettings,\n ...context.config,\n ...(bodyValue ?? {}),\n };\n\n if (options.prepareSendCommandsRequest) {\n requestBody = await options.prepareSendCommandsRequest(\n requestBody as SendCommandsRequestBody,\n );\n }\n\n const response = await fetch(\n isResume ? options.resumeApi! : options.api,\n {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n },\n );\n\n options.onResponse?.(response);\n\n if (!response.ok) {\n throw new Error(`Status ${response.status}: ${await response.text()}`);\n }\n\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const body = await createReplayBoundaryStream(response, {\n setReplaying: setIsReplaying,\n waitForRender: waitForReplayRender,\n });\n\n // Select decoder based on protocol option\n const protocol = options.protocol ?? \"data-stream\";\n const decoder =\n protocol === \"assistant-transport\"\n ? new AssistantTransportDecoder()\n : new DataStreamDecoder();\n\n let err: string | undefined;\n const stream = body.pipeThrough(decoder).pipeThrough(\n new AssistantMessageAccumulator({\n initialMessage: createInitialMessage({\n unstable_state:\n (agentStateRef.current as ReadonlyJSONValue) ?? null,\n }),\n throttle: isResume,\n onError: (error) => {\n err = error;\n },\n }),\n );\n\n let markedDelivered = false;\n\n for await (const chunk of asAsyncIterableStream(stream)) {\n if (chunk.metadata.unstable_state === agentStateRef.current) continue;\n\n if (!markedDelivered) {\n commandQueue.markDelivered();\n markedDelivered = true;\n }\n\n agentStateRef.current = chunk.metadata.unstable_state as T;\n rerender((prev) => prev + 1);\n }\n\n if (err) {\n throw new Error(err);\n }\n\n // A successful run confirms delivery even when no state-changing\n // chunk was observed.\n if (!markedDelivered) {\n commandQueue.markDelivered();\n }\n\n // commands that coalesced into this resume run must not starve\n if (isResume && commandQueue.state.queued.length > 0) {\n runManager.schedule();\n }\n },\n onFinish: options.onFinish,\n onCancel: () => {\n setIsReplaying(false);\n const cmds = [\n ...commandQueue.state.inTransit,\n ...commandQueue.state.queued,\n ];\n\n commandQueue.reset();\n\n options.onCancel?.({\n commands: cmds,\n updateState: (updater) => {\n agentStateRef.current = updater(agentStateRef.current);\n rerender((prev) => prev + 1);\n },\n });\n },\n onError: async (error) => {\n setIsReplaying(false);\n const inTransitCmds = [...commandQueue.state.inTransit];\n const queuedCmds = [...commandQueue.state.queued];\n\n commandQueue.reset();\n\n try {\n await options.onError?.(error as Error, {\n commands: inTransitCmds,\n updateState: (updater) => {\n agentStateRef.current = updater(agentStateRef.current);\n rerender((prev) => prev + 1);\n },\n });\n } finally {\n options.onCancel?.({\n commands: queuedCmds,\n updateState: (updater) => {\n agentStateRef.current = updater(agentStateRef.current);\n rerender((prev) => prev + 1);\n },\n error: error as Error,\n });\n }\n },\n });\n\n // Tool execution status state\n const [toolStatuses, setToolStatuses] = useState<\n Record<string, ToolExecutionStatus>\n >({});\n\n // Reactive conversion of agent state + connection metadata → UI state\n const pendingCommands = useMemo(\n () => [...commandQueue.state.inTransit, ...commandQueue.state.queued],\n [commandQueue.state],\n );\n const converted = useConvertedState(\n options.converter,\n agentStateRef.current,\n pendingCommands,\n runManager.isRunning,\n toolStatuses,\n );\n\n // Create runtime\n const runtime = useExternalStoreRuntime({\n messages: converted.messages,\n state: converted.state,\n isRunning: converted.isRunning,\n isLoading: isReplaying,\n adapters: options.adapters,\n unstable_enableToolInvocations: true,\n setToolStatuses,\n extras: {\n [symbolAssistantTransportExtras]: true,\n sendCommand: (command: AssistantTransportCommand) => {\n commandQueue.enqueue(command);\n },\n state: agentStateRef.current as UserExternalState,\n } satisfies AssistantTransportExtras,\n onNew: async (message: AppendMessage): Promise<void> => {\n parentIdRef.current = message.parentId;\n const command = convertAppendMessageToCommand(message);\n commandQueue.enqueue(command, {\n schedule: message.startRun ?? message.role === \"user\",\n });\n },\n ...(options.capabilities?.edit && {\n onEdit: async (message: AppendMessage): Promise<void> => {\n parentIdRef.current = message.parentId;\n const command = convertAppendMessageToCommand(message);\n commandQueue.enqueue(command, {\n schedule: message.startRun ?? message.role === \"user\",\n });\n },\n }),\n ...(commandQueue.state.queued.length > 0 && {\n onReload: async (parentId: string | null) => {\n parentIdRef.current = parentId;\n runManager.schedule();\n },\n }),\n onCancel: async () => {\n runManager.cancel();\n },\n onResume: async () => {\n if (!options.resumeApi)\n throw new Error(\"Must pass resumeApi to options to resume runs\");\n\n resumeFlagRef.current = true;\n runManager.schedule();\n },\n onAddToolResult: async (\n toolOptions: AddToolResultOptions,\n ): Promise<void> => {\n const command: AddToolResultCommand = {\n type: \"add-tool-result\",\n toolCallId: toolOptions.toolCallId,\n result: toolOptions.result as ReadonlyJSONObject,\n toolName: toolOptions.toolName,\n isError: toolOptions.isError,\n ...(toolOptions.artifact && { artifact: toolOptions.artifact }),\n ...(toolOptions.modelContent !== undefined && {\n modelContent: toolOptions.modelContent,\n }),\n };\n\n commandQueue.enqueue(command);\n },\n onLoadExternalState: async (state) => {\n agentStateRef.current = state as T;\n rerender((prev) => prev + 1);\n },\n });\n\n return runtime;\n};\n\n/**\n * @alpha This is an experimental API that is subject to change.\n */\nexport const useAssistantTransportRuntime = <T>(\n options: AssistantTransportOptions<T>,\n): AssistantRuntime => {\n const runtime = useRemoteThreadListRuntime({\n runtimeHook: function RuntimeHook() {\n return useAssistantTransportThreadRuntime(options);\n },\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AAYD,YAAYC;IACxBC,QAAQF,YAAYE;IACpBC,UAAUH,YAAYG;IACtBC,SAASJ,YAAYI;IACrB,GAAIJ,YAAYK,YAAY,EAAEA,UAAUL,YAAYK,SAAS;IAC7D,GAAIL,YAAYM,iBAAiB7F,KAAAA,KAAa,EAC5C6F,cAAcN,YAAYM,aAC5B;GACF;GAEA5F,aAAa2E,QAAQtG,SAAO;EAC9B;EACAwH,qBAAqB,OAAOvH,UAAU;GACpCiB,cAAcoB,UAAUrC;GACxBmB,UAAU6D,WAASA,SAAO,CAAC;EAC7B;CACF,CAAC;CAED,OAAOnC;AACT;;;;AAKA,MAAa2E,gCACXxG,YACqB;CAQrB,OAPgB1C,2BAA2B;EACzCmJ,aAAa,SAASC,cAAc;GAClC,OAAO3G,mCAAmCC,OAAO;EACnD;EACA2G,SAAS,IAAIpJ,0BAA0B;EACvCqJ,cAAc;CAChB,CACO/E;AACT"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { c } from "@assistant-ui/tap/react-shim/compiler-runtime";
|
|
2
|
+
import "@assistant-ui/tap/react-shim";
|
|
2
3
|
//#region src/legacy-runtime/runtime-cores/assistant-transport/useConvertedState.ts
|
|
3
4
|
function useConvertedState(converter, agentState, pendingCommands, isSending, toolStatuses) {
|
|
4
5
|
const $ = c(6);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useConvertedState.js","names":["useMemo","AssistantTransportCommand","AssistantTransportState","AssistantTransportStateConverter","ToolExecutionStatus","useConvertedState","converter","agentState","pendingCommands","isSending","toolStatuses","$","_c","t0"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/useConvertedState.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportState,\n AssistantTransportStateConverter,\n} from \"./types\";\nimport type { ToolExecutionStatus } from \"@assistant-ui/core\";\n\nexport function useConvertedState<T>(\n converter: AssistantTransportStateConverter<T>,\n agentState: T,\n pendingCommands: AssistantTransportCommand[],\n isSending: boolean,\n toolStatuses: Record<string, ToolExecutionStatus>,\n): AssistantTransportState {\n return useMemo(\n () => converter(agentState, { pendingCommands, isSending, toolStatuses }),\n [converter, agentState, pendingCommands, isSending, toolStatuses],\n );\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"useConvertedState.js","names":["useMemo","AssistantTransportCommand","AssistantTransportState","AssistantTransportStateConverter","ToolExecutionStatus","useConvertedState","converter","agentState","pendingCommands","isSending","toolStatuses","$","_c","t0"],"sources":["../../../../src/legacy-runtime/runtime-cores/assistant-transport/useConvertedState.ts"],"sourcesContent":["import { useMemo } from \"react\";\nimport type {\n AssistantTransportCommand,\n AssistantTransportState,\n AssistantTransportStateConverter,\n} from \"./types\";\nimport type { ToolExecutionStatus } from \"@assistant-ui/core\";\n\nexport function useConvertedState<T>(\n converter: AssistantTransportStateConverter<T>,\n agentState: T,\n pendingCommands: AssistantTransportCommand[],\n isSending: boolean,\n toolStatuses: Record<string, ToolExecutionStatus>,\n): AssistantTransportState {\n return useMemo(\n () => converter(agentState, { pendingCommands, isSending, toolStatuses }),\n [converter, agentState, pendingCommands, isSending, toolStatuses],\n );\n}\n"],"mappings":";;;AAQA,SAAOK,kBAAAC,WAAAC,YAAAC,iBAAAC,WAAAC,cAAA;CAAA,MAAAC,IAAAC,EAAA,CAAA;CAAA,IAAAC;CAAA,IAAAF,EAAA,OAAAJ,cAAAI,EAAA,OAAAL,aAAAK,EAAA,OAAAF,aAAAE,EAAA,OAAAH,mBAAAG,EAAA,OAAAD,cAAA;EAQGG,KAAAP,UAAUC,YAAY;GAAAC;GAAAC;GAAAC;EAA2C,CAAC;EAACC,EAAA,KAAAJ;EAAAI,EAAA,KAAAL;EAAAK,EAAA,KAAAF;EAAAE,EAAA,KAAAH;EAAAG,EAAA,KAAAD;EAAAC,EAAA,KAAAE;CAAA,OAAAA,KAAAF,EAAA;CAAA,OAAnEE;AAAmE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"McpAppRenderer.js","names":["useEffect","useMemo","useRef","useState","MutableRefObject","ReactNode","McpAppMetadata","ToolCallMessagePartComponent","ToolCallMessagePartProps","useAui","useResource","resource","ResourceElement","McpAppFrame","McpAppBridgeHandlers","McpAppHostContext","McpAppHostInfo","McpAppResource","McpAppSandboxConfig","McpAppsHost","getMcpAppFromToolPart","isRecord","McpAppRendererOptions","host","sandbox","maxHeight","hostInfo","hostContext","fallback","loadingFallback","errorFallback","error","Error","LoadedResourceState","resourceUri","serverId","getInput","part","status","type","argsText","args","undefined","defaultOpenLink","url","window","open","extractSendMessageText","params","obj","Record","InlineRenderer","internalsRef","optionsRef","opts","current","aui","app","cachedAppRef","appForRender","loadedResource","setLoadedResource","serverIdRef","cancelled","targetUri","targetServerId","loadResource","uri","then","res","catch","String","bridgeHandlers","openLink","sendMessage","text","ok","reason","thread","append","content","callTool","readResource","listResources","loadedResourceForApp","appResource","result","useMcpAppRenderer","options","render","Render","props","displayName","McpAppRenderer"],"sources":["../../src/mcp-apps/McpAppRenderer.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n type MutableRefObject,\n type ReactNode,\n} from \"react\";\nimport type { McpAppMetadata } from \"@assistant-ui/core\";\nimport type {\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n} from \"@assistant-ui/core/react\";\nimport { useAui } from \"@assistant-ui/store\";\n\nimport { useResource, resource, type ResourceElement } from \"@assistant-ui/tap\";\nimport { McpAppFrame } from \"./app-frame\";\nimport type {\n McpAppBridgeHandlers,\n McpAppHostContext,\n McpAppHostInfo,\n McpAppResource,\n McpAppSandboxConfig,\n McpAppsHost,\n} from \"./types\";\nimport { getMcpAppFromToolPart } from \"./utils\";\nimport { isRecord } from \"@assistant-ui/core/internal\";\n\nexport type McpAppRendererOptions = {\n /**\n * Provides the data-plane operations the widget can request\n * (`loadResource`, `callTool`, `readResource`, `listResources`). Use\n * `McpAppsRemoteHost({ url })` for the default HTTP-route convention.\n */\n host: ResourceElement<McpAppsHost>;\n /** Sandbox + container styling. Passes through to SafeContentFrame. */\n sandbox?: McpAppSandboxConfig;\n /**\n * Upper bound (in pixels) applied to the widget-driven auto-resize height.\n * Defaults to 800.\n */\n maxHeight?: number;\n /** Identifies the host to the widget in the `ui/initialize` response. */\n hostInfo?: McpAppHostInfo;\n /** Delivered to the widget on initialize and pushed via `notifications/host_context/changed` on change. */\n hostContext?: McpAppHostContext;\n /** Rendered when no MCP app is on the part, or while load is in flight / failed (unless overridden). */\n fallback?: ReactNode;\n /** Rendered while the resource is loading. Defaults to `fallback`. */\n loadingFallback?: ReactNode;\n /** Rendered when the resource load rejects. Defaults to `fallback`. */\n errorFallback?: ReactNode | ((error: Error) => ReactNode);\n};\n\ntype LoadedResourceState = {\n resourceUri: string;\n serverId?: string;\n resource?: McpAppResource;\n error?: Error;\n};\n\nfunction getInput(part: {\n status: { type: string };\n argsText: string;\n args: unknown;\n}): unknown {\n if (\n part.status.type === \"running\" &&\n (part.argsText === \"\" || part.argsText === \"{}\")\n ) {\n return undefined;\n }\n return part.args;\n}\n\nconst defaultOpenLink = ({ url }: { url: string }) => {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n};\n\nfunction extractSendMessageText(params: unknown): string | undefined {\n if (typeof params === \"string\") return params;\n if (!params || typeof params !== \"object\") return undefined;\n const obj = params as Record<string, unknown>;\n if (typeof obj[\"prompt\"] === \"string\") return obj[\"prompt\"];\n if (typeof obj[\"text\"] === \"string\") return obj[\"text\"];\n if (typeof obj[\"message\"] === \"string\") return obj[\"message\"];\n return undefined;\n}\n\nfunction InlineRenderer({\n part,\n internalsRef,\n optionsRef,\n}: {\n part: ToolCallMessagePartProps;\n internalsRef: MutableRefObject<{ host: McpAppsHost }>;\n optionsRef: MutableRefObject<McpAppRendererOptions>;\n}) {\n const opts = optionsRef.current;\n const aui = useAui();\n const app = getMcpAppFromToolPart(part);\n const cachedAppRef = useRef<McpAppMetadata | undefined>(undefined);\n if (\n app != null &&\n (cachedAppRef.current?.resourceUri !== app.resourceUri ||\n cachedAppRef.current?.serverId !== app.serverId)\n ) {\n cachedAppRef.current = app;\n }\n const appForRender = app ?? cachedAppRef.current;\n\n const [loadedResource, setLoadedResource] = useState<LoadedResourceState>();\n\n const resourceUri = appForRender?.resourceUri;\n const serverId = appForRender?.serverId;\n const serverIdRef = useRef<string | undefined>(undefined);\n serverIdRef.current = serverId;\n useEffect(() => {\n if (appForRender == null || resourceUri == null) return;\n let cancelled = false;\n const targetUri = resourceUri;\n const targetServerId = serverId;\n\n internalsRef.current.host\n .loadResource({\n uri: targetUri,\n ...(targetServerId ? { serverId: targetServerId } : {}),\n })\n .then((res) => {\n if (!cancelled)\n setLoadedResource({\n resourceUri: targetUri,\n ...(targetServerId !== undefined\n ? { serverId: targetServerId }\n : {}),\n resource: res,\n });\n })\n .catch((error: unknown) => {\n if (!cancelled) {\n setLoadedResource({\n resourceUri: targetUri,\n ...(targetServerId !== undefined\n ? { serverId: targetServerId }\n : {}),\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n cancelled = true;\n };\n // oxlint-disable-next-line react/exhaustive-deps -- re-fetch only when URI or server identity changes; appForRender identity is unstable and internalsRef is a stable ref\n }, [resourceUri, serverId]);\n\n const bridgeHandlers = useMemo<McpAppBridgeHandlers>(\n () => ({\n openLink: defaultOpenLink,\n sendMessage: (params) => {\n const text = extractSendMessageText(params);\n if (!text) return { ok: false, reason: \"unrecognised params shape\" };\n aui.thread().append({ content: [{ type: \"text\", text }] });\n return { ok: true };\n },\n callTool: (params) =>\n internalsRef.current.host.callTool({\n ...params,\n ...(serverIdRef.current ? { serverId: serverIdRef.current } : {}),\n }),\n readResource: (params) =>\n internalsRef.current.host.readResource({\n ...params,\n ...(serverIdRef.current ? { serverId: serverIdRef.current } : {}),\n }),\n listResources: (params) => {\n if (!serverIdRef.current) {\n return internalsRef.current.host.listResources(params);\n }\n return internalsRef.current.host.listResources({\n ...(isRecord(params) ? params : {}),\n serverId: serverIdRef.current,\n });\n },\n }),\n [aui, internalsRef],\n );\n\n const loadedResourceForApp =\n loadedResource?.resourceUri === appForRender?.resourceUri &&\n loadedResource?.serverId === appForRender?.serverId\n ? loadedResource\n : undefined;\n const appResource = loadedResourceForApp?.resource;\n const error = loadedResourceForApp?.error;\n\n const fallback = opts.fallback ?? null;\n if (appForRender == null) {\n return <>{fallback}</>;\n }\n if (error != null) {\n const errorFallback = opts.errorFallback;\n if (errorFallback === undefined) return <>{fallback}</>;\n if (typeof errorFallback === \"function\") return <>{errorFallback(error)}</>;\n return <>{errorFallback}</>;\n }\n if (appResource == null) {\n return <>{opts.loadingFallback ?? fallback}</>;\n }\n\n return (\n <McpAppFrame\n app={appForRender}\n resource={appResource}\n input={getInput(part)}\n output={part.result}\n sandbox={opts.sandbox}\n handlers={bridgeHandlers}\n hostInfo={opts.hostInfo}\n hostContext={opts.hostContext}\n maxHeight={opts.maxHeight}\n />\n );\n}\n\n/**\n * Creates a tool-call renderer for MCP Apps embedded in assistant messages.\n *\n * Compose this into the `Tools` resource through its `mcpApp` option. When a\n * tool-call part carries `mcp.app` metadata for a `ui://` resource, the\n * renderer loads that resource from the configured host and displays it in a\n * sandboxed frame.\n */\nconst useMcpAppRenderer = (\n options: McpAppRendererOptions,\n): { readonly render: ToolCallMessagePartComponent } => {\n const host = useResource(options.host);\n\n const optionsRef = useRef<McpAppRendererOptions>(options);\n optionsRef.current = options;\n\n const internalsRef = useRef<{ host: McpAppsHost }>({ host });\n internalsRef.current = { host };\n\n const render = useMemo((): ToolCallMessagePartComponent => {\n const Render: ToolCallMessagePartComponent = (props) => (\n <InlineRenderer\n part={props}\n internalsRef={internalsRef}\n optionsRef={optionsRef}\n />\n );\n Render.displayName = \"McpAppRenderer\";\n return Render;\n }, []);\n\n return { render };\n};\n\nexport const McpAppRenderer = resource(useMcpAppRenderer);\n"],"mappings":";;;;;;;;;AA+DA,SAASoC,SAASC,MAIN;CACV,IACEA,KAA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CAC3D6B,aAAaG,UAAU,EAAEhC,KAAK;CAc9B,OAAO,EAAEkE,QAZMxF,cAA4C;EACzD,MAAMyF,UAAwCC,UAC5C,oBAAC,gBAAD;GACE,MAAMA;GACQvC;GACFC;EAAW,CAAA;EAG3BqC,OAAOE,cAAc;EACrB,OAAOF;CACT,GAAG,CAAA,CAEMD,EAAO;AAClB;AAEA,MAAaI,iBAAiBlF,SAAS4E,iBAAiB"}
|
|
1
|
+
{"version":3,"file":"McpAppRenderer.js","names":["useEffect","useMemo","useRef","useState","MutableRefObject","ReactNode","McpAppMetadata","ToolCallMessagePartComponent","ToolCallMessagePartProps","useAui","useResource","resource","ResourceElement","McpAppFrame","McpAppBridgeHandlers","McpAppHostContext","McpAppHostInfo","McpAppResource","McpAppSandboxConfig","McpAppsHost","getMcpAppFromToolPart","isRecord","McpAppRendererOptions","host","sandbox","maxHeight","hostInfo","hostContext","fallback","loadingFallback","errorFallback","error","Error","LoadedResourceState","resourceUri","serverId","getInput","part","status","type","argsText","args","undefined","defaultOpenLink","url","window","open","extractSendMessageText","params","obj","Record","InlineRenderer","internalsRef","optionsRef","opts","current","aui","app","cachedAppRef","appForRender","loadedResource","setLoadedResource","serverIdRef","cancelled","targetUri","targetServerId","loadResource","uri","then","res","catch","String","bridgeHandlers","openLink","sendMessage","text","ok","reason","thread","append","content","callTool","readResource","listResources","loadedResourceForApp","appResource","result","useMcpAppRenderer","options","render","Render","props","displayName","McpAppRenderer"],"sources":["../../src/mcp-apps/McpAppRenderer.tsx"],"sourcesContent":["\"use client\";\n\nimport {\n useEffect,\n useMemo,\n useRef,\n useState,\n type MutableRefObject,\n type ReactNode,\n} from \"react\";\nimport type { McpAppMetadata } from \"@assistant-ui/core\";\nimport type {\n ToolCallMessagePartComponent,\n ToolCallMessagePartProps,\n} from \"@assistant-ui/core/react\";\nimport { useAui } from \"@assistant-ui/store\";\n\nimport { useResource, resource, type ResourceElement } from \"@assistant-ui/tap\";\nimport { McpAppFrame } from \"./app-frame\";\nimport type {\n McpAppBridgeHandlers,\n McpAppHostContext,\n McpAppHostInfo,\n McpAppResource,\n McpAppSandboxConfig,\n McpAppsHost,\n} from \"./types\";\nimport { getMcpAppFromToolPart } from \"./utils\";\nimport { isRecord } from \"@assistant-ui/core/internal\";\n\nexport type McpAppRendererOptions = {\n /**\n * Provides the data-plane operations the widget can request\n * (`loadResource`, `callTool`, `readResource`, `listResources`). Use\n * `McpAppsRemoteHost({ url })` for the default HTTP-route convention.\n */\n host: ResourceElement<McpAppsHost>;\n /** Sandbox + container styling. Passes through to SafeContentFrame. */\n sandbox?: McpAppSandboxConfig;\n /**\n * Upper bound (in pixels) applied to the widget-driven auto-resize height.\n * Defaults to 800.\n */\n maxHeight?: number;\n /** Identifies the host to the widget in the `ui/initialize` response. */\n hostInfo?: McpAppHostInfo;\n /** Delivered to the widget on initialize and pushed via `notifications/host_context/changed` on change. */\n hostContext?: McpAppHostContext;\n /** Rendered when no MCP app is on the part, or while load is in flight / failed (unless overridden). */\n fallback?: ReactNode;\n /** Rendered while the resource is loading. Defaults to `fallback`. */\n loadingFallback?: ReactNode;\n /** Rendered when the resource load rejects. Defaults to `fallback`. */\n errorFallback?: ReactNode | ((error: Error) => ReactNode);\n};\n\ntype LoadedResourceState = {\n resourceUri: string;\n serverId?: string;\n resource?: McpAppResource;\n error?: Error;\n};\n\nfunction getInput(part: {\n status: { type: string };\n argsText: string;\n args: unknown;\n}): unknown {\n if (\n part.status.type === \"running\" &&\n (part.argsText === \"\" || part.argsText === \"{}\")\n ) {\n return undefined;\n }\n return part.args;\n}\n\nconst defaultOpenLink = ({ url }: { url: string }) => {\n window.open(url, \"_blank\", \"noopener,noreferrer\");\n};\n\nfunction extractSendMessageText(params: unknown): string | undefined {\n if (typeof params === \"string\") return params;\n if (!params || typeof params !== \"object\") return undefined;\n const obj = params as Record<string, unknown>;\n if (typeof obj[\"prompt\"] === \"string\") return obj[\"prompt\"];\n if (typeof obj[\"text\"] === \"string\") return obj[\"text\"];\n if (typeof obj[\"message\"] === \"string\") return obj[\"message\"];\n return undefined;\n}\n\nfunction InlineRenderer({\n part,\n internalsRef,\n optionsRef,\n}: {\n part: ToolCallMessagePartProps;\n internalsRef: MutableRefObject<{ host: McpAppsHost }>;\n optionsRef: MutableRefObject<McpAppRendererOptions>;\n}) {\n const opts = optionsRef.current;\n const aui = useAui();\n const app = getMcpAppFromToolPart(part);\n const cachedAppRef = useRef<McpAppMetadata | undefined>(undefined);\n if (\n app != null &&\n (cachedAppRef.current?.resourceUri !== app.resourceUri ||\n cachedAppRef.current?.serverId !== app.serverId)\n ) {\n cachedAppRef.current = app;\n }\n const appForRender = app ?? cachedAppRef.current;\n\n const [loadedResource, setLoadedResource] = useState<LoadedResourceState>();\n\n const resourceUri = appForRender?.resourceUri;\n const serverId = appForRender?.serverId;\n const serverIdRef = useRef<string | undefined>(undefined);\n serverIdRef.current = serverId;\n useEffect(() => {\n if (appForRender == null || resourceUri == null) return;\n let cancelled = false;\n const targetUri = resourceUri;\n const targetServerId = serverId;\n\n internalsRef.current.host\n .loadResource({\n uri: targetUri,\n ...(targetServerId ? { serverId: targetServerId } : {}),\n })\n .then((res) => {\n if (!cancelled)\n setLoadedResource({\n resourceUri: targetUri,\n ...(targetServerId !== undefined\n ? { serverId: targetServerId }\n : {}),\n resource: res,\n });\n })\n .catch((error: unknown) => {\n if (!cancelled) {\n setLoadedResource({\n resourceUri: targetUri,\n ...(targetServerId !== undefined\n ? { serverId: targetServerId }\n : {}),\n error: error instanceof Error ? error : new Error(String(error)),\n });\n }\n });\n\n return () => {\n cancelled = true;\n };\n // oxlint-disable-next-line react/exhaustive-deps -- re-fetch only when URI or server identity changes; appForRender identity is unstable and internalsRef is a stable ref\n }, [resourceUri, serverId]);\n\n const bridgeHandlers = useMemo<McpAppBridgeHandlers>(\n () => ({\n openLink: defaultOpenLink,\n sendMessage: (params) => {\n const text = extractSendMessageText(params);\n if (!text) return { ok: false, reason: \"unrecognised params shape\" };\n aui.thread.append({ content: [{ type: \"text\", text }] });\n return { ok: true };\n },\n callTool: (params) =>\n internalsRef.current.host.callTool({\n ...params,\n ...(serverIdRef.current ? { serverId: serverIdRef.current } : {}),\n }),\n readResource: (params) =>\n internalsRef.current.host.readResource({\n ...params,\n ...(serverIdRef.current ? { serverId: serverIdRef.current } : {}),\n }),\n listResources: (params) => {\n if (!serverIdRef.current) {\n return internalsRef.current.host.listResources(params);\n }\n return internalsRef.current.host.listResources({\n ...(isRecord(params) ? params : {}),\n serverId: serverIdRef.current,\n });\n },\n }),\n [aui, internalsRef],\n );\n\n const loadedResourceForApp =\n loadedResource?.resourceUri === appForRender?.resourceUri &&\n loadedResource?.serverId === appForRender?.serverId\n ? loadedResource\n : undefined;\n const appResource = loadedResourceForApp?.resource;\n const error = loadedResourceForApp?.error;\n\n const fallback = opts.fallback ?? null;\n if (appForRender == null) {\n return <>{fallback}</>;\n }\n if (error != null) {\n const errorFallback = opts.errorFallback;\n if (errorFallback === undefined) return <>{fallback}</>;\n if (typeof errorFallback === \"function\") return <>{errorFallback(error)}</>;\n return <>{errorFallback}</>;\n }\n if (appResource == null) {\n return <>{opts.loadingFallback ?? fallback}</>;\n }\n\n return (\n <McpAppFrame\n app={appForRender}\n resource={appResource}\n input={getInput(part)}\n output={part.result}\n sandbox={opts.sandbox}\n handlers={bridgeHandlers}\n hostInfo={opts.hostInfo}\n hostContext={opts.hostContext}\n maxHeight={opts.maxHeight}\n />\n );\n}\n\n/**\n * Creates a tool-call renderer for MCP Apps embedded in assistant messages.\n *\n * Compose this into the `Tools` resource through its `mcpApp` option. When a\n * tool-call part carries `mcp.app` metadata for a `ui://` resource, the\n * renderer loads that resource from the configured host and displays it in a\n * sandboxed frame.\n */\nconst useMcpAppRenderer = (\n options: McpAppRendererOptions,\n): { readonly render: ToolCallMessagePartComponent } => {\n const host = useResource(options.host);\n\n const optionsRef = useRef<McpAppRendererOptions>(options);\n optionsRef.current = options;\n\n const internalsRef = useRef<{ host: McpAppsHost }>({ host });\n internalsRef.current = { host };\n\n const render = useMemo((): ToolCallMessagePartComponent => {\n const Render: ToolCallMessagePartComponent = (props) => (\n <InlineRenderer\n part={props}\n internalsRef={internalsRef}\n optionsRef={optionsRef}\n />\n );\n Render.displayName = \"McpAppRenderer\";\n return Render;\n }, []);\n\n return { render };\n};\n\nexport const McpAppRenderer = resource(useMcpAppRenderer);\n"],"mappings":";;;;;;;;;AA+DA,SAASoC,SAASC,MAIN;CACV,IACEA,KAAKC,OAAOC,SAAS,cACpBF,KAAKG,aAAa,MAAMH,KAAKG,aAAa,OAE3C;CAEF,OAAOH,KAAKI;AACd;AAEA,MAAME,mBAAmB,EAAEC,UAA2B;CACpDC,OAAOC,KAAKF,KAAK,UAAU,qBAAqB;AAClD;AAEA,SAASG,uBAAuBC,QAAqC;CACnE,IAAI,OAAOA,WAAW,UAAU,OAAOA;CACvC,IAAI,CAACA,UAAU,OAAOA,WAAW,UAAU,OAAON,KAAAA;CAClD,MAAMO,MAAMD;CACZ,IAAI,OAAOC,IAAI,cAAc,UAAU,OAAOA,IAAI;CAClD,IAAI,OAAOA,IAAI,YAAY,UAAU,OAAOA,IAAI;CAChD,IAAI,OAAOA,IAAI,eAAe,UAAU,OAAOA,IAAI;AAErD;AAEA,SAASE,eAAe,EACtBd,MACAe,cACAC,cAKC;CACD,MAAMC,OAAOD,WAAWE;CACxB,MAAMC,MAAM/C,OAAO;CACnB,MAAMgD,MAAMrC,sBAAsBiB,IAAI;CACtC,MAAMqB,eAAexD,OAAmCwC,KAAAA,CAAS;CACjE,IACEe,OAAO,SACNC,aAAaH,SAASrB,gBAAgBuB,IAAIvB,eACzCwB,aAAaH,SAASpB,aAAasB,IAAItB,WAEzCuB,aAAaH,UAAUE;CAEzB,MAAME,eAAeF,OAAOC,aAAaH;CAEzC,MAAM,CAACK,gBAAgBC,qBAAqB1D,SAA8B;CAE1E,MAAM+B,cAAcyB,cAAczB;CAClC,MAAMC,WAAWwB,cAAcxB;CAC/B,MAAM2B,cAAc5D,OAA2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UAAUlB,KAAK5B;EACf,aAAa4B,KAAK3B;EAClB,WAAW2B,KAAK7B;CAAU,CAAA;AAGhC;;;;;;;;;AAUA,MAAM8D,qBACJC,YACsD;CACtD,MAAMjE,OAAOb,YAAY8E,QAAQjE,IAAI;CAErC,MAAM8B,aAAanD,OAA8BsF,OAAO;CACxDnC,WAAWE,UAAUiC;CAErB,MAAMpC,eAAelD,OAA8B,EAAEqB,KAAK,CAAC;CAC3D6B,aAAaG,UAAU,EAAEhC,KAAK;CAc9B,OAAO,EAAEkE,QAZMxF,cAA4C;EACzD,MAAMyF,UAAwCC,UAC5C,oBAAC,gBAAD;GACE,MAAMA;GACQvC;GACFC;EAAW,CAAA;EAG3BqC,OAAOE,cAAc;EACrB,OAAOF;CACT,GAAG,CAAA,CAEMD,EAAO;AAClB;AAEA,MAAaI,iBAAiBlF,SAAS4E,iBAAiB"}
|
|
@@ -52,7 +52,7 @@ const edit = tool({
|
|
|
52
52
|
const ReadableContext = createContext(false);
|
|
53
53
|
const makeAssistantVisible = (Component, config) => {
|
|
54
54
|
const ReadableComponent = forwardRef((props, outerRef) => {
|
|
55
|
-
const $ = c(
|
|
55
|
+
const $ = c(15);
|
|
56
56
|
const isNestedReadable = useContext(ReadableContext);
|
|
57
57
|
const clickId = useId();
|
|
58
58
|
const componentRef = useRef(null);
|
|
@@ -64,46 +64,47 @@ const makeAssistantVisible = (Component, config) => {
|
|
|
64
64
|
} else t0 = $[0];
|
|
65
65
|
const { clickable, editable } = t0;
|
|
66
66
|
let t1;
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
t1 = () => aui.modelContext().register({ getModelContext: () => ({
|
|
67
|
+
if ($[1] !== aui.modelContext || $[2] !== isNestedReadable) {
|
|
68
|
+
t1 = () => aui.modelContext.register({ getModelContext: () => ({
|
|
70
69
|
tools: {
|
|
71
70
|
...clickable ? { click } : {},
|
|
72
71
|
...editable ? { edit } : {}
|
|
73
72
|
},
|
|
74
73
|
system: !isNestedReadable ? componentRef.current?.outerHTML : void 0
|
|
75
74
|
}) });
|
|
75
|
+
$[1] = aui.modelContext;
|
|
76
|
+
$[2] = isNestedReadable;
|
|
77
|
+
$[3] = t1;
|
|
78
|
+
} else t1 = $[3];
|
|
79
|
+
let t2;
|
|
80
|
+
if ($[4] !== aui || $[5] !== isNestedReadable) {
|
|
76
81
|
t2 = [
|
|
77
82
|
isNestedReadable,
|
|
78
83
|
aui,
|
|
79
84
|
clickable,
|
|
80
85
|
editable
|
|
81
86
|
];
|
|
82
|
-
$[
|
|
83
|
-
$[
|
|
84
|
-
$[
|
|
85
|
-
|
|
86
|
-
} else {
|
|
87
|
-
t1 = $[3];
|
|
88
|
-
t2 = $[4];
|
|
89
|
-
}
|
|
87
|
+
$[4] = aui;
|
|
88
|
+
$[5] = isNestedReadable;
|
|
89
|
+
$[6] = t2;
|
|
90
|
+
} else t2 = $[6];
|
|
90
91
|
useEffect(t1, t2);
|
|
91
92
|
const ref = useComposedRefs(componentRef, outerRef);
|
|
92
93
|
const t3 = props;
|
|
93
94
|
let t4;
|
|
94
95
|
let t5;
|
|
95
|
-
if ($[
|
|
96
|
+
if ($[7] !== clickId) {
|
|
96
97
|
t4 = config?.clickable ? { "data-click-id": clickId } : {};
|
|
97
98
|
t5 = config?.editable ? { "data-edit-id": clickId } : {};
|
|
98
|
-
$[
|
|
99
|
-
$[
|
|
100
|
-
$[
|
|
99
|
+
$[7] = clickId;
|
|
100
|
+
$[8] = t4;
|
|
101
|
+
$[9] = t5;
|
|
101
102
|
} else {
|
|
102
|
-
t4 = $[
|
|
103
|
-
t5 = $[
|
|
103
|
+
t4 = $[8];
|
|
104
|
+
t5 = $[9];
|
|
104
105
|
}
|
|
105
106
|
let t6;
|
|
106
|
-
if ($[
|
|
107
|
+
if ($[10] !== ref || $[11] !== t3 || $[12] !== t4 || $[13] !== t5) {
|
|
107
108
|
t6 = /* @__PURE__ */ jsx(ReadableContext.Provider, {
|
|
108
109
|
value: true,
|
|
109
110
|
children: /* @__PURE__ */ jsx(Component, {
|
|
@@ -113,12 +114,12 @@ const makeAssistantVisible = (Component, config) => {
|
|
|
113
114
|
ref
|
|
114
115
|
})
|
|
115
116
|
});
|
|
116
|
-
$[
|
|
117
|
-
$[
|
|
118
|
-
$[
|
|
119
|
-
$[
|
|
120
|
-
$[
|
|
121
|
-
} else t6 = $[
|
|
117
|
+
$[10] = ref;
|
|
118
|
+
$[11] = t3;
|
|
119
|
+
$[12] = t4;
|
|
120
|
+
$[13] = t5;
|
|
121
|
+
$[14] = t6;
|
|
122
|
+
} else t6 = $[14];
|
|
122
123
|
return t6;
|
|
123
124
|
});
|
|
124
125
|
ReadableComponent.displayName = Component.displayName;
|