@athenaintel/react 0.23.2 → 0.23.3

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.
Files changed (87) hide show
  1. package/README.md +40 -1
  2. package/dist/chat/AthenaChat.cjs +129 -29
  3. package/dist/chat/AthenaChat.cjs.map +1 -1
  4. package/dist/chat/AthenaChat.d.ts +32 -1
  5. package/dist/chat/AthenaChat.js +130 -30
  6. package/dist/chat/AthenaChat.js.map +1 -1
  7. package/dist/chat/athena-composer-controls.js +1 -1
  8. package/dist/chat/statewire-client-tools.cjs +20 -0
  9. package/dist/chat/statewire-client-tools.cjs.map +1 -1
  10. package/dist/chat/statewire-client-tools.d.ts +27 -0
  11. package/dist/chat/statewire-client-tools.js +20 -0
  12. package/dist/chat/statewire-client-tools.js.map +1 -1
  13. package/dist/chat/use-athena-run-live.cjs.map +1 -1
  14. package/dist/chat/use-athena-run-live.d.ts +7 -0
  15. package/dist/chat/use-athena-run-live.js.map +1 -1
  16. package/dist/chat-ui/composer/tiptap-composer.cjs +16 -1
  17. package/dist/chat-ui/composer/tiptap-composer.cjs.map +1 -1
  18. package/dist/chat-ui/composer/tiptap-composer.js +16 -1
  19. package/dist/chat-ui/composer/tiptap-composer.js.map +1 -1
  20. package/dist/composer/composer-handoff.cjs +121 -0
  21. package/dist/composer/composer-handoff.cjs.map +1 -0
  22. package/dist/composer/composer-handoff.d.ts +89 -0
  23. package/dist/composer/composer-handoff.js +121 -0
  24. package/dist/composer/composer-handoff.js.map +1 -0
  25. package/dist/composer/index.d.ts +2 -0
  26. package/dist/composer/useAppendToComposer.cjs +19 -7
  27. package/dist/composer/useAppendToComposer.cjs.map +1 -1
  28. package/dist/composer/useAppendToComposer.d.ts +22 -4
  29. package/dist/composer/useAppendToComposer.js +20 -8
  30. package/dist/composer/useAppendToComposer.js.map +1 -1
  31. package/dist/composer/useSendMessage.cjs +26 -8
  32. package/dist/composer/useSendMessage.cjs.map +1 -1
  33. package/dist/composer/useSendMessage.d.ts +8 -0
  34. package/dist/composer/useSendMessage.js +27 -9
  35. package/dist/composer/useSendMessage.js.map +1 -1
  36. package/dist/diagnostics/athena-diagnostics.cjs.map +1 -1
  37. package/dist/diagnostics/athena-diagnostics.d.ts +1 -1
  38. package/dist/diagnostics/athena-diagnostics.js.map +1 -1
  39. package/dist/diagnostics/errors.cjs +2 -0
  40. package/dist/diagnostics/errors.cjs.map +1 -1
  41. package/dist/diagnostics/errors.d.ts +2 -0
  42. package/dist/diagnostics/errors.js +2 -0
  43. package/dist/diagnostics/errors.js.map +1 -1
  44. package/dist/dictation/DictationStrip.cjs +60 -0
  45. package/dist/dictation/DictationStrip.cjs.map +1 -0
  46. package/dist/dictation/DictationStrip.d.ts +25 -0
  47. package/dist/dictation/DictationStrip.js +60 -0
  48. package/dist/dictation/DictationStrip.js.map +1 -0
  49. package/dist/dictation/audio-level-history.cjs +68 -0
  50. package/dist/dictation/audio-level-history.cjs.map +1 -0
  51. package/dist/dictation/audio-level-history.d.ts +27 -0
  52. package/dist/dictation/audio-level-history.js +68 -0
  53. package/dist/dictation/audio-level-history.js.map +1 -0
  54. package/dist/dictation/dictation-controls.cjs +60 -0
  55. package/dist/dictation/dictation-controls.cjs.map +1 -0
  56. package/dist/dictation/dictation-controls.d.ts +15 -0
  57. package/dist/dictation/dictation-controls.js +60 -0
  58. package/dist/dictation/dictation-controls.js.map +1 -0
  59. package/dist/dictation/dictation-engine.cjs +128 -0
  60. package/dist/dictation/dictation-engine.cjs.map +1 -0
  61. package/dist/dictation/dictation-engine.d.ts +87 -0
  62. package/dist/dictation/dictation-engine.js +128 -0
  63. package/dist/dictation/dictation-engine.js.map +1 -0
  64. package/dist/dictation/dictation-state.cjs +68 -0
  65. package/dist/dictation/dictation-state.cjs.map +1 -0
  66. package/dist/dictation/dictation-state.d.ts +58 -0
  67. package/dist/dictation/dictation-state.js +68 -0
  68. package/dist/dictation/dictation-state.js.map +1 -0
  69. package/dist/dictation/use-dictation.cjs +204 -0
  70. package/dist/dictation/use-dictation.cjs.map +1 -0
  71. package/dist/dictation/use-dictation.d.ts +47 -0
  72. package/dist/dictation/use-dictation.js +204 -0
  73. package/dist/dictation/use-dictation.js.map +1 -0
  74. package/dist/index.cjs +13 -0
  75. package/dist/index.cjs.map +1 -1
  76. package/dist/index.d.ts +11 -0
  77. package/dist/index.js +13 -0
  78. package/dist/index.js.map +1 -1
  79. package/dist/packages/react/package.json.cjs +1 -1
  80. package/dist/packages/react/package.json.js +1 -1
  81. package/dist/provider/AthenaProvider.cjs +42 -3
  82. package/dist/provider/AthenaProvider.cjs.map +1 -1
  83. package/dist/provider/AthenaProvider.d.ts +1 -1
  84. package/dist/provider/AthenaProvider.js +43 -4
  85. package/dist/provider/AthenaProvider.js.map +1 -1
  86. package/dist/styles.css +1 -1
  87. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tiptap-composer.js","sources":["../../../src/chat-ui/composer/tiptap-composer.tsx"],"sourcesContent":["/**\n * Tiptap Composer — Full Olympus mention system integration\n *\n * Uses the ported Olympus infrastructure:\n * - MentionSuggestionList (with scope navigation, breadcrumbs, keyboard nav)\n * - MentionSuggestionPopup (Floating UI positioning)\n * - MentionSuggestionsExtension (Tiptap @ trigger)\n * - MentionExtension (inline mention chips)\n * - useMentionSuggestions (full Olympus categories + async data)\n *\n * Auth credentials for GraphQL are provided via MentionAuthCtx, and the host\n * app (Chrome side panel, Office task pane, the SDK's AthenaChat) supplies any\n * host-only mention items — browser tabs through `webpages`, its own Tools /\n * Toolkits list through `tools`.\n *\n * The draft serializes to Markdown through `tiptap-markdown` — the serializer\n * the Olympus chat composer sends with — so pasted hyperlinks keep their URL,\n * formatting marks survive, paragraphs stay separated, and a mention is the\n * `[@Name](url)` link the message renderer parses back into a chip.\n */\n\nimport { athenaDiagnostics } from \"../../diagnostics/athena-diagnostics\";\nimport {\n clipboardHasMeaningfulText,\n extractPastedImages,\n} from \"../../composer/clipboard\";\nimport {\n useRef,\n useState,\n useCallback,\n useEffect,\n forwardRef,\n useImperativeHandle,\n type DragEvent as ReactDragEvent,\n} from \"react\";\nimport { useEditor, EditorContent } from \"@tiptap/react\";\nimport Placeholder from \"@tiptap/extension-placeholder\";\nimport { Extension, type Editor } from \"@tiptap/core\";\nimport { unstable_useComposerInput, useAui } from \"@assistant-ui/react\";\nimport { LoaderCircleIcon, XIcon } from \"lucide-react\";\nimport { cn } from \"../../lib/utils\";\nimport { CHAT_TEXT_CLASS, createChatTextExtensions } from \"../rich-text/chat-text-schema\";\nimport {\n MentionSuggestionsExtension,\n type MentionSuggestionCallbacks,\n type MentionSuggestionRenderProps,\n} from \"../mentions/suggestions/mention-suggestions.extension\";\nimport { MentionSuggestionPopup } from \"../mentions/suggestions/components/mention-suggestion-popup\";\nimport {\n MentionSuggestionList,\n} from \"../mentions/suggestions/components/mention-suggestion-list\";\nimport {\n useMentionSuggestions,\n type MentionRootCategory,\n} from \"../mentions/suggestions/data/use-mention-suggestions\";\nimport type {\n MentionTool,\n MenuItem,\n WebpageMention,\n} from \"../mentions/suggestions/data/types\";\nimport type { KeyboardNavigationHandle } from \"../mentions/suggestions/components/use-keyboard-navigation\";\nimport {\n registerChatAssetMentionHandler,\n type UploadedChatAsset,\n} from \"@athenaintel/agent-runtime\";\nimport { PendingAttachmentUploads } from \"./pending-attachment-uploads\";\n\n// ── Submit keybind extension ──\n\nconst SubmitKeybind = Extension.create<{ onSubmit: () => void; isMentionOpen: () => boolean }>({\n name: \"submitKeybind\",\n priority: 1000,\n addOptions() {\n return { onSubmit: () => {}, isMentionOpen: () => false };\n },\n addKeyboardShortcuts() {\n return {\n Enter: () => {\n // Don't submit when the mention popup is open — let it handle Enter\n if (this.options.isMentionOpen()) return false;\n // Let the schema's keymaps continue lists, insert code newlines, and\n // split paragraphs inside structured blocks, as in the web composer.\n if ([\"listItem\", \"taskItem\", \"codeBlock\", \"table\", \"blockquote\"].some(\n (node) => this.editor.isActive(node),\n )) return false;\n this.options.onSubmit();\n return true;\n },\n \"Shift-Enter\": () => {\n return this.editor.commands.newlineInCode() || this.editor.commands.setHardBreak();\n },\n };\n },\n});\n\n// ── CSS for mention chips + editor ──\n\nconst MENTION_STYLES = `\n .image-preview-composer .mention-chip[data-display-as-preview=\"true\"] {\n display: none;\n }\n /* Scoped to this editor: hosts render other ProseMirror instances on the\n same page (AthenaChat's message renderer), which must keep their own\n height and placeholder rules. */\n .athena-chat-composer .ProseMirror {\n outline: none;\n min-height: 36px;\n max-height: 120px;\n overflow-y: auto;\n }\n .athena-chat-composer .ProseMirror p.is-editor-empty:first-child::before {\n content: attr(data-placeholder);\n float: left;\n color: #9ca3af;\n pointer-events: none;\n height: 0;\n }\n /* The paper appearance (the SDK thread): a taller resting height, room for\n about eight lines before the draft scrolls, and a placeholder at 35% of\n the text colour. Same specificity as the rules above, so order decides. */\n .athena-chat-composer--paper .ProseMirror {\n min-height: 44px;\n max-height: 12rem;\n }\n .athena-chat-composer--paper .ProseMirror p.is-editor-empty:first-child::before {\n color: color-mix(in srgb, currentColor 35%, transparent);\n }\n`;\n\n/**\n * The editor's look. `default` is what the Chrome extension and Office add-in\n * render; `paper` pairs with `ChatComposerDock appearance=\"paper\"`.\n */\nexport type TiptapComposerAppearance = \"default\" | \"paper\";\n\ninterface MarkdownStorage {\n getMarkdown(): string;\n}\n\n/** The draft as it is sent: Markdown, mentions as `[@Name](url)` links. */\nexport function serializeDraft(editor: Editor): string {\n return (editor.storage as { markdown: MarkdownStorage }).markdown.getMarkdown();\n}\n\n/**\n * A host's own intake for the files pasted into or dropped on the composer\n * (AthenaChat uploads them into its attachment pills). Without `onDrop` the\n * composer leaves drops untouched so an enclosing drop zone receives them.\n */\nexport interface ComposerFileIntake {\n onPaste: (files: readonly File[]) => void;\n onDrop?: (files: readonly File[]) => void;\n}\n\n// ── Main component ──\n\nexport interface TiptapComposerHandle {\n submit: () => Promise<void>;\n addAttachment: (file: File) => Promise<void>;\n insertAssetMention: (asset: UploadedChatAsset) => void;\n /**\n * Focuses the editor and types the `@` trigger at the caret (after a space\n * when the caret follows a word), opening the mention menu — the toolbar's\n * `@` button. A no-op while the editor is disabled or the menu is open.\n * Optional on the type so hosts' handle stand-ins written before it keep\n * type-checking; the composer itself always provides it.\n */\n openMentionMenu?: () => void;\n}\n\nexport interface TiptapComposerProps {\n placeholder?: string;\n threadId: string;\n disabled?: boolean;\n /** Editor look; defaults to the side-panel / task-pane editor. */\n appearance?: TiptapComposerAppearance;\n /** Host-provided browser-tab mentions; empty in hosts without tab access. */\n webpages?: readonly WebpageMention[];\n /**\n * Host-provided Tools / Toolkits mention candidates. When set they replace\n * the server tool catalog for those categories (see `useMentionSuggestions`).\n */\n tools?: readonly MentionTool[];\n rootCategories?: readonly MentionRootCategory[];\n onDraftStateChange?: (hasDraft: boolean) => void;\n /** Show local image thumbnails while mention-backed uploads are in the draft. */\n showImagePreviews?: boolean;\n /** Surface paste/drop attachment failures in host UI as well as diagnostics. */\n onAttachmentError?: (message: string) => void;\n /**\n * Host-owned intake for pasted and dropped files. Without it the composer\n * attaches them itself through `aui.composer.addAttachment`.\n */\n fileIntake?: ComposerFileIntake;\n /**\n * Awaited before every submit (Enter and the imperative handle), after the\n * composer's own pending uploads have settled: a host whose uploads live\n * outside the composer (AthenaChat's attachment pills) resolves once they\n * land, so a send never leaves without its attachment.\n */\n waitForHostUploads?: () => Promise<void> | void;\n /**\n * Optional submit interception: called with the serialized draft — possibly\n * empty, for a host composing its own extras into the send — before the\n * composer-runtime send. Return `true` when the host consumed the draft\n * through another lane (e.g. a live voice session) — the editor clears and\n * the normal send is skipped. Return `false` to fall through unchanged.\n */\n interceptSubmit?: (text: string) => boolean | Promise<boolean>;\n /**\n * Called after a draft has left the editor — through the composer-runtime\n * send or a host interception — from Enter and the imperative handle alike.\n * Hosts use it for per-send UI such as a first-use keyboard hint.\n */\n onSubmitted?: () => void;\n}\n\nconst NO_WEBPAGES: readonly WebpageMention[] = [];\n\ninterface ComposerImagePreview {\n key: string;\n file: File;\n name: string;\n src: string;\n assetId?: string;\n}\n\nfunction revokeImagePreview(src: string): void {\n if (typeof URL.revokeObjectURL === \"function\") URL.revokeObjectURL(src);\n}\n\nfunction ImagePreviewStrip({\n previews,\n onRemove,\n}: {\n previews: readonly ComposerImagePreview[];\n onRemove: (preview: ComposerImagePreview) => void;\n}) {\n if (previews.length === 0) return null;\n\n return (\n <div\n className=\"flex w-full gap-2 overflow-x-auto px-1.5 pb-1 pt-1.5\"\n role=\"list\"\n aria-label=\"Image attachments\"\n >\n {previews.map((preview) => {\n const uploading = preview.assetId === undefined;\n return (\n <div\n key={preview.key}\n className=\"group relative h-16 w-[clamp(76px,30vw,112px)] shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 shadow-sm\"\n role=\"listitem\"\n >\n <img\n src={preview.src}\n alt={preview.name}\n className=\"size-full object-cover\"\n />\n <div className=\"absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-black/75 to-transparent px-1.5 pb-1 pt-4 text-[10px] font-medium text-white\">\n {preview.name}\n </div>\n {uploading ? (\n <span\n className=\"absolute left-1 top-1 inline-flex size-5 items-center justify-center rounded-full bg-black/65 text-white\"\n title=\"Uploading image\"\n >\n <LoaderCircleIcon className=\"size-3 animate-spin\" />\n </span>\n ) : (\n <button\n type=\"button\"\n onClick={() => onRemove(preview)}\n className=\"absolute right-1 top-1 inline-flex size-5 items-center justify-center rounded-full bg-black/65 text-white opacity-80 transition-opacity hover:bg-black/80 hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white\"\n aria-label={`Remove ${preview.name}`}\n title=\"Remove image\"\n >\n <XIcon className=\"size-3\" />\n </button>\n )}\n </div>\n );\n })}\n </div>\n );\n}\n\nexport const TiptapComposer = forwardRef<\n TiptapComposerHandle,\n TiptapComposerProps\n>(\n (\n {\n placeholder = \"Message Athena... (type @ to mention)\",\n threadId,\n disabled = false,\n appearance = \"default\",\n webpages = NO_WEBPAGES,\n tools,\n rootCategories,\n onDraftStateChange,\n showImagePreviews = false,\n onAttachmentError,\n fileIntake,\n waitForHostUploads,\n interceptSubmit,\n onSubmitted,\n },\n outerRef,\n ) => {\n const aui = useAui();\n const composerInput = unstable_useComposerInput();\n const applyingRuntimeTextRef = useRef(false);\n // What this editor last mirrored into the composer runtime; a value equal to\n // it is our own echo and needs no re-serialization or restore.\n const lastEmittedMarkdownRef = useRef<string | null>(null);\n const listRef = useRef<KeyboardNavigationHandle>(null);\n const pendingUploadsRef = useRef(new PendingAttachmentUploads());\n const submitInFlightRef = useRef(false);\n const imagePreviewsRef = useRef<ComposerImagePreview[]>([]);\n const [imagePreviews, setImagePreviews] = useState<ComposerImagePreview[]>([]);\n\n const replaceImagePreviews = useCallback((next: ComposerImagePreview[]) => {\n imagePreviewsRef.current = next;\n setImagePreviews(next);\n }, []);\n\n const removeImagePreviews = useCallback(\n (shouldRemove: (preview: ComposerImagePreview) => boolean) => {\n const kept: ComposerImagePreview[] = [];\n let removed = false;\n for (const preview of imagePreviewsRef.current) {\n if (shouldRemove(preview)) {\n revokeImagePreview(preview.src);\n removed = true;\n } else kept.push(preview);\n }\n if (removed) replaceImagePreviews(kept);\n },\n [replaceImagePreviews],\n );\n\n const clearImagePreviews = useCallback(() => {\n removeImagePreviews(() => true);\n }, [removeImagePreviews]);\n\n useEffect(() => clearImagePreviews(), [clearImagePreviews, threadId]);\n useEffect(\n () => () => {\n for (const preview of imagePreviewsRef.current) {\n revokeImagePreview(preview.src);\n }\n imagePreviewsRef.current = [];\n },\n [],\n );\n\n const { store } = useMentionSuggestions({ webpages, tools, rootCategories });\n\n // Popup state\n const [popupOpen, setPopupOpen] = useState(false);\n const popupOpenRef = useRef(false);\n const [popupProps, setPopupProps] = useState<MentionSuggestionRenderProps | null>(null);\n\n // Suggestion callbacks — drive the popup lifecycle\n const callbacksRef = useRef<MentionSuggestionCallbacks>({\n onStart: (props) => {\n setPopupOpen(true);\n popupOpenRef.current = true;\n setPopupProps(props);\n },\n onUpdate: (props) => {\n setPopupProps(props);\n },\n onKeyDown: (event) => {\n // Route keyboard events to the MentionSuggestionList\n return listRef.current?.onKeyDown(event) ?? false;\n },\n onExit: () => {\n setPopupOpen(false);\n popupOpenRef.current = false;\n setPopupProps(null);\n },\n });\n\n // Editor ref — needed because handleSubmit is created before useEditor returns\n const editorRef = useRef<ReturnType<typeof useEditor>>(null);\n\n // Submit via composer runtime so attachments (screenshots, files) are included.\n // aui.composer.setText() + aui.composer.send() bundles text + pending attachments.\n //\n // Statewire turns a send during an active run into a queued command. Do not\n // cancel first: cancellation aborts the shared run for every connected\n // client and turns a normal queued follow-up into a destructive stop.\n const handleSubmit = useCallback(async () => {\n if (disabled) return;\n if (submitInFlightRef.current) return;\n submitInFlightRef.current = true;\n try {\n await pendingUploadsRef.current.waitForIdle();\n await waitForHostUploads?.();\n const ed = editorRef.current;\n if (!ed) return;\n const text = serializeDraft(ed).trim();\n\n // Interception carries TEXT only: a draft with pending attachments\n // (screenshots, files) must ride the composer-runtime send that\n // bundles them, or the attachments would silently vanish. Attachment\n // state is read only when a host actually intercepts. It runs before\n // the empty check because a host may compose extras of its own into\n // an otherwise empty draft (AthenaChat's quote and attachment pills).\n if (interceptSubmit) {\n const hasAttachments =\n (aui.composer.getState().attachments?.length ?? 0) > 0;\n if (!hasAttachments && (await interceptSubmit(text))) {\n ed.commands.clearContent();\n clearImagePreviews();\n onDraftStateChange?.(false);\n onSubmitted?.();\n return;\n }\n }\n\n if (!text) return;\n if (!composerInput.canSend) return;\n\n composerInput.setText(text);\n composerInput.send({ steer: false });\n\n ed.commands.clearContent();\n clearImagePreviews();\n onDraftStateChange?.(false);\n onSubmitted?.();\n } finally {\n submitInFlightRef.current = false;\n }\n }, [\n clearImagePreviews,\n composerInput,\n disabled,\n interceptSubmit,\n onDraftStateChange,\n onSubmitted,\n waitForHostUploads,\n ]);\n\n const handleSubmitRef = useRef(handleSubmit);\n handleSubmitRef.current = handleSubmit;\n\n const addAttachment = useCallback(\n (file: File) => {\n let previewKey: string | undefined;\n if (\n showImagePreviews &&\n file.type.startsWith(\"image/\") &&\n typeof URL.createObjectURL === \"function\"\n ) {\n previewKey = crypto.randomUUID();\n replaceImagePreviews([\n ...imagePreviewsRef.current,\n {\n key: previewKey,\n file,\n name: file.name || \"Pasted image\",\n src: URL.createObjectURL(file),\n },\n ]);\n }\n\n return pendingUploadsRef.current\n .track(aui.composer.addAttachment(file))\n .catch((error: unknown) => {\n if (previewKey) {\n removeImagePreviews((preview) => preview.key === previewKey);\n }\n throw error;\n });\n },\n [aui, removeImagePreviews, replaceImagePreviews, showImagePreviews],\n );\n\n // Handle paste events — intercept images from clipboard and add as attachments\n const handlePaste = useCallback(\n (_view: unknown, event: ClipboardEvent) => {\n const clipboardData = event.clipboardData;\n if (!clipboardData) return false;\n\n const images = extractPastedImages({ clipboardData });\n if (images.length === 0) return false;\n // Office and spreadsheet copies put the cells' text beside a bitmap of\n // them: the text is what the user copied, so the editor's native paste\n // keeps it and the incidental screenshot is left alone. A copied image\n // file's own name (Finder, Explorer) is not such text.\n if (\n clipboardHasMeaningfulText({\n clipboardData,\n pastedFileNames: images.map((image) => image.originalName),\n })\n ) {\n return false;\n }\n event.preventDefault();\n\n const files = images.map((image) => image.file);\n if (fileIntake) {\n fileIntake.onPaste(files);\n return true;\n }\n for (const file of files) {\n void addAttachment(file).catch((error: unknown) => {\n onAttachmentError?.(\"Couldn’t paste that image.\");\n athenaDiagnostics.error(\n \"composer.attachment.error\",\n error,\n { code: \"attachment_failed\", message: \"Pasted image upload failed\" },\n { source: \"paste\", type: file.type },\n );\n });\n }\n return true;\n },\n [addAttachment, fileIntake, onAttachmentError],\n );\n\n // Without a host intake the composer attaches dropped images itself; a host\n // intake without `onDrop` leaves drops to the enclosing drop zone.\n const addDroppedImages = useCallback(\n (files: FileList | readonly File[]) => {\n const images = Array.from(files).filter((file) =>\n file.type.startsWith(\"image/\"),\n );\n if (images.length === 0) return false;\n if (fileIntake) {\n if (!fileIntake.onDrop) return false;\n fileIntake.onDrop(images);\n return true;\n }\n for (const file of images) {\n void addAttachment(file).catch((error: unknown) => {\n onAttachmentError?.(\"Couldn’t attach that dropped image.\");\n athenaDiagnostics.error(\n \"composer.attachment.error\",\n error,\n { code: \"attachment_failed\", message: \"Dropped image upload failed\" },\n { source: \"drop\", type: file.type },\n );\n });\n }\n return true;\n },\n [addAttachment, fileIntake, onAttachmentError],\n );\n\n // ProseMirror owns drops that land in the editable surface. The React\n // wrapper below catches the rest of the composer area; defaultPrevented\n // keeps one gesture from being attached twice.\n const handleDrop = useCallback(\n (_view: unknown, event: DragEvent) => {\n const files = event.dataTransfer?.files;\n if (!files?.length) return false;\n const handled = addDroppedImages(files);\n if (handled) event.preventDefault();\n return handled;\n },\n [addDroppedImages],\n );\n\n const handleComposerDrop = useCallback(\n (event: ReactDragEvent<HTMLDivElement>) => {\n if (event.defaultPrevented) return;\n if (addDroppedImages(event.dataTransfer.files)) event.preventDefault();\n },\n [addDroppedImages],\n );\n\n const editor = useEditor({\n editable: !disabled,\n extensions: [\n ...createChatTextExtensions(),\n Placeholder.configure({ placeholder }),\n MentionSuggestionsExtension.configure({\n store,\n callbacks: callbacksRef.current,\n }),\n SubmitKeybind.configure({\n onSubmit: () => void handleSubmitRef.current(),\n isMentionOpen: () => popupOpenRef.current,\n }),\n ],\n editorProps: {\n attributes: {\n class: cn(CHAT_TEXT_CLASS, \"w-full resize-none bg-transparent px-1.5 py-2 outline-none\"),\n \"data-testid\": \"athena-chat-composer\",\n },\n handlePaste,\n handleDrop,\n },\n onUpdate: ({ editor: updatedEditor }) => {\n const nextText = serializeDraft(updatedEditor);\n lastEmittedMarkdownRef.current = nextText;\n if (!applyingRuntimeTextRef.current) {\n composerInput.setText(nextText);\n }\n onDraftStateChange?.(nextText.trim().length > 0);\n\n if (showImagePreviews) {\n const mentionedAssetIds = new Set<string>();\n updatedEditor.state.doc.descendants((node) => {\n if (\n node.type.name === \"mention\" &&\n node.attrs.type === \"asset\" &&\n typeof node.attrs.id === \"string\"\n ) {\n mentionedAssetIds.add(node.attrs.id);\n }\n });\n removeImagePreviews(\n (preview) =>\n preview.assetId !== undefined &&\n !mentionedAssetIds.has(preview.assetId),\n );\n }\n },\n immediatelyRender: false,\n });\n\n // Keep ref in sync so handleSubmit always has the editor\n editorRef.current = editor;\n\n useEffect(() => {\n editor?.setEditable(!disabled);\n }, [disabled, editor]);\n\n // This rich editor replaces ComposerPrimitive.Input, so it must mirror its\n // draft into assistant-ui's composer state. Statewire restores that state\n // when a send is rejected during reconnect, and a host may write to it\n // (`useAppendToComposer`); mirroring it back into Tiptap — parsed as the\n // Markdown it was serialized to, mention links included — preserves the\n // user's message instead of leaving an empty composer. Our own echo is\n // skipped on the ref; a restore's re-serialization may differ from the\n // value byte-for-byte, so the ref takes that form to stop a second pass.\n useEffect(() => {\n if (!editor) return;\n const value = composerInput.value;\n if (value === lastEmittedMarkdownRef.current) return;\n const currentMarkdown = serializeDraft(editor);\n lastEmittedMarkdownRef.current = currentMarkdown;\n if (value === currentMarkdown) return;\n // React node views flush their mounts synchronously. Restore outside\n // React's effect phase, and cancel a restore superseded by a newer draft.\n let cancelled = false;\n queueMicrotask(() => {\n if (cancelled || editor.isDestroyed) return;\n applyingRuntimeTextRef.current = true;\n try {\n editor.commands.setContent(value);\n lastEmittedMarkdownRef.current = serializeDraft(editor);\n } finally {\n applyingRuntimeTextRef.current = false;\n }\n onDraftStateChange?.(value.trim().length > 0);\n });\n return () => { cancelled = true; };\n }, [composerInput.value, editor, onDraftStateChange]);\n\n const insertAssetMention = useCallback(\n (asset: UploadedChatAsset, sourceFile?: File) => {\n const currentEditor = editorRef.current;\n if (!currentEditor) throw new Error(\"The chat composer is not ready.\");\n currentEditor\n .chain()\n .focus()\n .insertContent({\n type: \"mention\",\n attrs: {\n type: \"asset\",\n name: asset.title,\n id: asset.id,\n assetType: asset.assetType,\n displayAsPreview:\n showImagePreviews && sourceFile?.type.startsWith(\"image/\"),\n },\n })\n // A text node, not a string: the Markdown extension parses string\n // content as Markdown, which would drop a lone space.\n .insertContent({ type: \"text\", text: \" \" })\n .run();\n\n if (\n showImagePreviews &&\n sourceFile?.type.startsWith(\"image/\") &&\n typeof URL.createObjectURL === \"function\"\n ) {\n const existing = imagePreviewsRef.current.find(\n (preview) => preview.file === sourceFile,\n );\n if (existing) {\n replaceImagePreviews(\n imagePreviewsRef.current.map((preview) =>\n preview.key === existing.key\n ? { ...preview, assetId: asset.id, name: asset.title }\n : preview,\n ),\n );\n } else {\n replaceImagePreviews([\n ...imagePreviewsRef.current,\n {\n key: crypto.randomUUID(),\n file: sourceFile,\n name: asset.title,\n src: URL.createObjectURL(sourceFile),\n assetId: asset.id,\n },\n ]);\n }\n }\n },\n [replaceImagePreviews, showImagePreviews],\n );\n\n const removeImagePreview = useCallback(\n (preview: ComposerImagePreview) => {\n if (!preview.assetId) return;\n const currentEditor = editorRef.current;\n if (!currentEditor) return;\n const positions: Array<{ from: number; to: number }> = [];\n currentEditor.state.doc.descendants((node, position) => {\n if (\n node.type.name === \"mention\" &&\n node.attrs.type === \"asset\" &&\n node.attrs.id === preview.assetId\n ) {\n positions.push({ from: position, to: position + node.nodeSize });\n }\n });\n let transaction = currentEditor.state.tr;\n for (const position of positions.reverse()) {\n transaction = transaction.delete(position.from, position.to);\n }\n if (transaction.docChanged) currentEditor.view.dispatch(transaction);\n removeImagePreviews((candidate) => candidate.key === preview.key);\n currentEditor.commands.focus();\n },\n [removeImagePreviews],\n );\n\n useEffect(\n () => registerChatAssetMentionHandler(threadId, insertAssetMention),\n [insertAssetMention, threadId],\n );\n\n const openMentionMenu = useCallback(() => {\n if (disabled) return;\n const currentEditor = editorRef.current;\n if (!currentEditor || currentEditor.isDestroyed) return;\n if (popupOpenRef.current) {\n currentEditor.commands.focus();\n return;\n }\n // The suggestion plugin only opens on an `@` that starts a word\n // (`allowedPrefixes`), so a trigger typed right after text — or after a\n // mention chip, which `textBetween` reports as its leaf text — gets the\n // separating space a user would type.\n const { from } = currentEditor.state.selection;\n const before =\n from > 0\n ? currentEditor.state.doc.textBetween(from - 1, from, \"\\0\", \"\\0\")\n : \"\";\n const needsSpace = before.length > 0 && !/[\\s([{\"']/.test(before);\n currentEditor\n .chain()\n .focus()\n .insertContent({ type: \"text\", text: needsSpace ? \" @\" : \"@\" })\n .run();\n }, [disabled]);\n\n useImperativeHandle(\n outerRef,\n () => ({\n submit: handleSubmit,\n addAttachment,\n insertAssetMention,\n openMentionMenu,\n }),\n [addAttachment, handleSubmit, insertAssetMention, openMentionMenu],\n );\n\n return (\n <>\n <style>{MENTION_STYLES}</style>\n <div\n className={cn(\n \"athena-chat-composer flex-1 min-w-0\",\n appearance === \"paper\" && \"athena-chat-composer--paper\",\n showImagePreviews && \"image-preview-composer\",\n )}\n aria-label=\"Message composer\"\n aria-disabled={disabled}\n onDragOver={(event) => {\n if (Array.from(event.dataTransfer.types).includes(\"Files\")) {\n event.preventDefault();\n event.dataTransfer.dropEffect = \"copy\";\n }\n }}\n onDrop={handleComposerDrop}\n >\n <ImagePreviewStrip\n previews={imagePreviews}\n onRemove={removeImagePreview}\n />\n <EditorContent editor={editor} />\n </div>\n\n {/* Olympus-style mention popup */}\n {popupOpen && popupProps && editor && (\n <MentionSuggestionPopup clientRect={popupProps.clientRect}>\n <MentionSuggestionList\n ref={listRef}\n store={store}\n editor={editor}\n query={popupProps.query}\n command={(item: MenuItem) => popupProps.command(item)}\n closeMenu={() => {\n setPopupOpen(false);\n editor.commands.focus();\n }}\n />\n </MentionSuggestionPopup>\n )}\n </>\n );\n },\n);\n\nTiptapComposer.displayName = \"TiptapComposer\";\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqEA,MAAM,gBAAgB,UAAU,OAA+D;AAAA,EAC7F,MAAM;AAAA,EACN,UAAU;AAAA,EACV,aAAa;AACX,WAAO,EAAE,UAAU,MAAM;AAAA,IAAC,GAAG,eAAe,MAAM,MAAA;AAAA,EACpD;AAAA,EACA,uBAAuB;AACrB,WAA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
1
+ {"version":3,"file":"tiptap-composer.js","sources":["../../../src/chat-ui/composer/tiptap-composer.tsx"],"sourcesContent":["/**\n * Tiptap Composer — Full Olympus mention system integration\n *\n * Uses the ported Olympus infrastructure:\n * - MentionSuggestionList (with scope navigation, breadcrumbs, keyboard nav)\n * - MentionSuggestionPopup (Floating UI positioning)\n * - MentionSuggestionsExtension (Tiptap @ trigger)\n * - MentionExtension (inline mention chips)\n * - useMentionSuggestions (full Olympus categories + async data)\n *\n * Auth credentials for GraphQL are provided via MentionAuthCtx, and the host\n * app (Chrome side panel, Office task pane, the SDK's AthenaChat) supplies any\n * host-only mention items — browser tabs through `webpages`, its own Tools /\n * Toolkits list through `tools`.\n *\n * The draft serializes to Markdown through `tiptap-markdown` — the serializer\n * the Olympus chat composer sends with — so pasted hyperlinks keep their URL,\n * formatting marks survive, paragraphs stay separated, and a mention is the\n * `[@Name](url)` link the message renderer parses back into a chip.\n */\n\nimport { athenaDiagnostics } from \"../../diagnostics/athena-diagnostics\";\nimport {\n clipboardHasMeaningfulText,\n extractPastedImages,\n} from \"../../composer/clipboard\";\nimport {\n useRef,\n useState,\n useCallback,\n useEffect,\n forwardRef,\n useImperativeHandle,\n type DragEvent as ReactDragEvent,\n} from \"react\";\nimport { useEditor, EditorContent } from \"@tiptap/react\";\nimport Placeholder from \"@tiptap/extension-placeholder\";\nimport { Extension, type Editor } from \"@tiptap/core\";\nimport { unstable_useComposerInput, useAui } from \"@assistant-ui/react\";\nimport { useComposerHandoffStore } from \"../../composer/composer-handoff\";\nimport { LoaderCircleIcon, XIcon } from \"lucide-react\";\nimport { cn } from \"../../lib/utils\";\nimport { CHAT_TEXT_CLASS, createChatTextExtensions } from \"../rich-text/chat-text-schema\";\nimport {\n MentionSuggestionsExtension,\n type MentionSuggestionCallbacks,\n type MentionSuggestionRenderProps,\n} from \"../mentions/suggestions/mention-suggestions.extension\";\nimport { MentionSuggestionPopup } from \"../mentions/suggestions/components/mention-suggestion-popup\";\nimport {\n MentionSuggestionList,\n} from \"../mentions/suggestions/components/mention-suggestion-list\";\nimport {\n useMentionSuggestions,\n type MentionRootCategory,\n} from \"../mentions/suggestions/data/use-mention-suggestions\";\nimport type {\n MentionTool,\n MenuItem,\n WebpageMention,\n} from \"../mentions/suggestions/data/types\";\nimport type { KeyboardNavigationHandle } from \"../mentions/suggestions/components/use-keyboard-navigation\";\nimport {\n registerChatAssetMentionHandler,\n type UploadedChatAsset,\n} from \"@athenaintel/agent-runtime\";\nimport { PendingAttachmentUploads } from \"./pending-attachment-uploads\";\n\n// ── Submit keybind extension ──\n\nconst SubmitKeybind = Extension.create<{ onSubmit: () => void; isMentionOpen: () => boolean }>({\n name: \"submitKeybind\",\n priority: 1000,\n addOptions() {\n return { onSubmit: () => {}, isMentionOpen: () => false };\n },\n addKeyboardShortcuts() {\n return {\n Enter: () => {\n // Don't submit when the mention popup is open — let it handle Enter\n if (this.options.isMentionOpen()) return false;\n // Let the schema's keymaps continue lists, insert code newlines, and\n // split paragraphs inside structured blocks, as in the web composer.\n if ([\"listItem\", \"taskItem\", \"codeBlock\", \"table\", \"blockquote\"].some(\n (node) => this.editor.isActive(node),\n )) return false;\n this.options.onSubmit();\n return true;\n },\n \"Shift-Enter\": () => {\n return this.editor.commands.newlineInCode() || this.editor.commands.setHardBreak();\n },\n };\n },\n});\n\n// ── CSS for mention chips + editor ──\n\nconst MENTION_STYLES = `\n .image-preview-composer .mention-chip[data-display-as-preview=\"true\"] {\n display: none;\n }\n /* Scoped to this editor: hosts render other ProseMirror instances on the\n same page (AthenaChat's message renderer), which must keep their own\n height and placeholder rules. */\n .athena-chat-composer .ProseMirror {\n outline: none;\n min-height: 36px;\n max-height: 120px;\n overflow-y: auto;\n }\n .athena-chat-composer .ProseMirror p.is-editor-empty:first-child::before {\n content: attr(data-placeholder);\n float: left;\n color: #9ca3af;\n pointer-events: none;\n height: 0;\n }\n /* The paper appearance (the SDK thread): a taller resting height, room for\n about eight lines before the draft scrolls, and a placeholder at 35% of\n the text colour. Same specificity as the rules above, so order decides. */\n .athena-chat-composer--paper .ProseMirror {\n min-height: 44px;\n max-height: 12rem;\n }\n .athena-chat-composer--paper .ProseMirror p.is-editor-empty:first-child::before {\n color: color-mix(in srgb, currentColor 35%, transparent);\n }\n`;\n\n/**\n * The editor's look. `default` is what the Chrome extension and Office add-in\n * render; `paper` pairs with `ChatComposerDock appearance=\"paper\"`.\n */\nexport type TiptapComposerAppearance = \"default\" | \"paper\";\n\ninterface MarkdownStorage {\n getMarkdown(): string;\n}\n\n/** The draft as it is sent: Markdown, mentions as `[@Name](url)` links. */\nexport function serializeDraft(editor: Editor): string {\n return (editor.storage as { markdown: MarkdownStorage }).markdown.getMarkdown();\n}\n\n/**\n * A host's own intake for the files pasted into or dropped on the composer\n * (AthenaChat uploads them into its attachment pills). Without `onDrop` the\n * composer leaves drops untouched so an enclosing drop zone receives them.\n */\nexport interface ComposerFileIntake {\n onPaste: (files: readonly File[]) => void;\n onDrop?: (files: readonly File[]) => void;\n}\n\n// ── Main component ──\n\nexport interface TiptapComposerHandle {\n submit: () => Promise<void>;\n addAttachment: (file: File) => Promise<void>;\n insertAssetMention: (asset: UploadedChatAsset) => void;\n /**\n * Focuses the editor and types the `@` trigger at the caret (after a space\n * when the caret follows a word), opening the mention menu — the toolbar's\n * `@` button. A no-op while the editor is disabled or the menu is open.\n * Optional on the type so hosts' handle stand-ins written before it keep\n * type-checking; the composer itself always provides it.\n */\n openMentionMenu?: () => void;\n}\n\nexport interface TiptapComposerProps {\n placeholder?: string;\n threadId: string;\n disabled?: boolean;\n /** Editor look; defaults to the side-panel / task-pane editor. */\n appearance?: TiptapComposerAppearance;\n /** Host-provided browser-tab mentions; empty in hosts without tab access. */\n webpages?: readonly WebpageMention[];\n /**\n * Host-provided Tools / Toolkits mention candidates. When set they replace\n * the server tool catalog for those categories (see `useMentionSuggestions`).\n */\n tools?: readonly MentionTool[];\n rootCategories?: readonly MentionRootCategory[];\n onDraftStateChange?: (hasDraft: boolean) => void;\n /** Show local image thumbnails while mention-backed uploads are in the draft. */\n showImagePreviews?: boolean;\n /** Surface paste/drop attachment failures in host UI as well as diagnostics. */\n onAttachmentError?: (message: string) => void;\n /**\n * Host-owned intake for pasted and dropped files. Without it the composer\n * attaches them itself through `aui.composer.addAttachment`.\n */\n fileIntake?: ComposerFileIntake;\n /**\n * Awaited before every submit (Enter and the imperative handle), after the\n * composer's own pending uploads have settled: a host whose uploads live\n * outside the composer (AthenaChat's attachment pills) resolves once they\n * land, so a send never leaves without its attachment.\n */\n waitForHostUploads?: () => Promise<void> | void;\n /**\n * Optional submit interception: called with the serialized draft — possibly\n * empty, for a host composing its own extras into the send — before the\n * composer-runtime send. Return `true` when the host consumed the draft\n * through another lane (e.g. a live voice session) — the editor clears and\n * the normal send is skipped. Return `false` to fall through unchanged.\n */\n interceptSubmit?: (text: string) => boolean | Promise<boolean>;\n /**\n * Called after a draft has left the editor — through the composer-runtime\n * send or a host interception — from Enter and the imperative handle alike.\n * Hosts use it for per-send UI such as a first-use keyboard hint.\n */\n onSubmitted?: () => void;\n}\n\nconst NO_WEBPAGES: readonly WebpageMention[] = [];\n\ninterface ComposerImagePreview {\n key: string;\n file: File;\n name: string;\n src: string;\n assetId?: string;\n}\n\nfunction revokeImagePreview(src: string): void {\n if (typeof URL.revokeObjectURL === \"function\") URL.revokeObjectURL(src);\n}\n\nfunction ImagePreviewStrip({\n previews,\n onRemove,\n}: {\n previews: readonly ComposerImagePreview[];\n onRemove: (preview: ComposerImagePreview) => void;\n}) {\n if (previews.length === 0) return null;\n\n return (\n <div\n className=\"flex w-full gap-2 overflow-x-auto px-1.5 pb-1 pt-1.5\"\n role=\"list\"\n aria-label=\"Image attachments\"\n >\n {previews.map((preview) => {\n const uploading = preview.assetId === undefined;\n return (\n <div\n key={preview.key}\n className=\"group relative h-16 w-[clamp(76px,30vw,112px)] shrink-0 overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100 shadow-sm\"\n role=\"listitem\"\n >\n <img\n src={preview.src}\n alt={preview.name}\n className=\"size-full object-cover\"\n />\n <div className=\"absolute inset-x-0 bottom-0 truncate bg-gradient-to-t from-black/75 to-transparent px-1.5 pb-1 pt-4 text-[10px] font-medium text-white\">\n {preview.name}\n </div>\n {uploading ? (\n <span\n className=\"absolute left-1 top-1 inline-flex size-5 items-center justify-center rounded-full bg-black/65 text-white\"\n title=\"Uploading image\"\n >\n <LoaderCircleIcon className=\"size-3 animate-spin\" />\n </span>\n ) : (\n <button\n type=\"button\"\n onClick={() => onRemove(preview)}\n className=\"absolute right-1 top-1 inline-flex size-5 items-center justify-center rounded-full bg-black/65 text-white opacity-80 transition-opacity hover:bg-black/80 hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white\"\n aria-label={`Remove ${preview.name}`}\n title=\"Remove image\"\n >\n <XIcon className=\"size-3\" />\n </button>\n )}\n </div>\n );\n })}\n </div>\n );\n}\n\nexport const TiptapComposer = forwardRef<\n TiptapComposerHandle,\n TiptapComposerProps\n>(\n (\n {\n placeholder = \"Message Athena... (type @ to mention)\",\n threadId,\n disabled = false,\n appearance = \"default\",\n webpages = NO_WEBPAGES,\n tools,\n rootCategories,\n onDraftStateChange,\n showImagePreviews = false,\n onAttachmentError,\n fileIntake,\n waitForHostUploads,\n interceptSubmit,\n onSubmitted,\n },\n outerRef,\n ) => {\n const aui = useAui();\n const composerInput = unstable_useComposerInput();\n const handoff = useComposerHandoffStore();\n const applyingRuntimeTextRef = useRef(false);\n // What this editor last mirrored into the composer runtime; a value equal to\n // it is our own echo and needs no re-serialization or restore.\n const lastEmittedMarkdownRef = useRef<string | null>(null);\n const listRef = useRef<KeyboardNavigationHandle>(null);\n const pendingUploadsRef = useRef(new PendingAttachmentUploads());\n const submitInFlightRef = useRef(false);\n const imagePreviewsRef = useRef<ComposerImagePreview[]>([]);\n const [imagePreviews, setImagePreviews] = useState<ComposerImagePreview[]>([]);\n\n const replaceImagePreviews = useCallback((next: ComposerImagePreview[]) => {\n imagePreviewsRef.current = next;\n setImagePreviews(next);\n }, []);\n\n const removeImagePreviews = useCallback(\n (shouldRemove: (preview: ComposerImagePreview) => boolean) => {\n const kept: ComposerImagePreview[] = [];\n let removed = false;\n for (const preview of imagePreviewsRef.current) {\n if (shouldRemove(preview)) {\n revokeImagePreview(preview.src);\n removed = true;\n } else kept.push(preview);\n }\n if (removed) replaceImagePreviews(kept);\n },\n [replaceImagePreviews],\n );\n\n const clearImagePreviews = useCallback(() => {\n removeImagePreviews(() => true);\n }, [removeImagePreviews]);\n\n useEffect(() => clearImagePreviews(), [clearImagePreviews, threadId]);\n useEffect(\n () => () => {\n for (const preview of imagePreviewsRef.current) {\n revokeImagePreview(preview.src);\n }\n imagePreviewsRef.current = [];\n },\n [],\n );\n\n const { store } = useMentionSuggestions({ webpages, tools, rootCategories });\n\n // Popup state\n const [popupOpen, setPopupOpen] = useState(false);\n const popupOpenRef = useRef(false);\n const [popupProps, setPopupProps] = useState<MentionSuggestionRenderProps | null>(null);\n\n // Suggestion callbacks — drive the popup lifecycle\n const callbacksRef = useRef<MentionSuggestionCallbacks>({\n onStart: (props) => {\n setPopupOpen(true);\n popupOpenRef.current = true;\n setPopupProps(props);\n },\n onUpdate: (props) => {\n setPopupProps(props);\n },\n onKeyDown: (event) => {\n // Route keyboard events to the MentionSuggestionList\n return listRef.current?.onKeyDown(event) ?? false;\n },\n onExit: () => {\n setPopupOpen(false);\n popupOpenRef.current = false;\n setPopupProps(null);\n },\n });\n\n // Editor ref — needed because handleSubmit is created before useEditor returns\n const editorRef = useRef<ReturnType<typeof useEditor>>(null);\n\n // Submit via composer runtime so attachments (screenshots, files) are included.\n // aui.composer.setText() + aui.composer.send() bundles text + pending attachments.\n //\n // Statewire turns a send during an active run into a queued command. Do not\n // cancel first: cancellation aborts the shared run for every connected\n // client and turns a normal queued follow-up into a destructive stop.\n const handleSubmit = useCallback(async () => {\n if (disabled) return;\n if (submitInFlightRef.current) return;\n submitInFlightRef.current = true;\n try {\n await pendingUploadsRef.current.waitForIdle();\n await waitForHostUploads?.();\n const ed = editorRef.current;\n if (!ed) return;\n const text = serializeDraft(ed).trim();\n\n // Interception carries TEXT only: a draft with pending attachments\n // (screenshots, files) must ride the composer-runtime send that\n // bundles them, or the attachments would silently vanish. Attachment\n // state is read only when a host actually intercepts. It runs before\n // the empty check because a host may compose extras of its own into\n // an otherwise empty draft (AthenaChat's quote and attachment pills).\n if (interceptSubmit) {\n const hasAttachments =\n (aui.composer.getState().attachments?.length ?? 0) > 0;\n if (!hasAttachments && (await interceptSubmit(text))) {\n ed.commands.clearContent();\n clearImagePreviews();\n onDraftStateChange?.(false);\n onSubmitted?.();\n return;\n }\n }\n\n if (!text) return;\n if (!composerInput.canSend) return;\n\n composerInput.setText(text);\n composerInput.send({ steer: false });\n\n ed.commands.clearContent();\n clearImagePreviews();\n onDraftStateChange?.(false);\n onSubmitted?.();\n } finally {\n submitInFlightRef.current = false;\n }\n }, [\n clearImagePreviews,\n composerInput,\n disabled,\n interceptSubmit,\n onDraftStateChange,\n onSubmitted,\n waitForHostUploads,\n ]);\n\n const handleSubmitRef = useRef(handleSubmit);\n handleSubmitRef.current = handleSubmit;\n\n const addAttachment = useCallback(\n (file: File) => {\n let previewKey: string | undefined;\n if (\n showImagePreviews &&\n file.type.startsWith(\"image/\") &&\n typeof URL.createObjectURL === \"function\"\n ) {\n previewKey = crypto.randomUUID();\n replaceImagePreviews([\n ...imagePreviewsRef.current,\n {\n key: previewKey,\n file,\n name: file.name || \"Pasted image\",\n src: URL.createObjectURL(file),\n },\n ]);\n }\n\n return pendingUploadsRef.current\n .track(aui.composer.addAttachment(file))\n .catch((error: unknown) => {\n if (previewKey) {\n removeImagePreviews((preview) => preview.key === previewKey);\n }\n throw error;\n });\n },\n [aui, removeImagePreviews, replaceImagePreviews, showImagePreviews],\n );\n\n // Handle paste events — intercept images from clipboard and add as attachments\n const handlePaste = useCallback(\n (_view: unknown, event: ClipboardEvent) => {\n const clipboardData = event.clipboardData;\n if (!clipboardData) return false;\n\n const images = extractPastedImages({ clipboardData });\n if (images.length === 0) return false;\n // Office and spreadsheet copies put the cells' text beside a bitmap of\n // them: the text is what the user copied, so the editor's native paste\n // keeps it and the incidental screenshot is left alone. A copied image\n // file's own name (Finder, Explorer) is not such text.\n if (\n clipboardHasMeaningfulText({\n clipboardData,\n pastedFileNames: images.map((image) => image.originalName),\n })\n ) {\n return false;\n }\n event.preventDefault();\n\n const files = images.map((image) => image.file);\n if (fileIntake) {\n fileIntake.onPaste(files);\n return true;\n }\n for (const file of files) {\n void addAttachment(file).catch((error: unknown) => {\n onAttachmentError?.(\"Couldn’t paste that image.\");\n athenaDiagnostics.error(\n \"composer.attachment.error\",\n error,\n { code: \"attachment_failed\", message: \"Pasted image upload failed\" },\n { source: \"paste\", type: file.type },\n );\n });\n }\n return true;\n },\n [addAttachment, fileIntake, onAttachmentError],\n );\n\n // Without a host intake the composer attaches dropped images itself; a host\n // intake without `onDrop` leaves drops to the enclosing drop zone.\n const addDroppedImages = useCallback(\n (files: FileList | readonly File[]) => {\n const images = Array.from(files).filter((file) =>\n file.type.startsWith(\"image/\"),\n );\n if (images.length === 0) return false;\n if (fileIntake) {\n if (!fileIntake.onDrop) return false;\n fileIntake.onDrop(images);\n return true;\n }\n for (const file of images) {\n void addAttachment(file).catch((error: unknown) => {\n onAttachmentError?.(\"Couldn’t attach that dropped image.\");\n athenaDiagnostics.error(\n \"composer.attachment.error\",\n error,\n { code: \"attachment_failed\", message: \"Dropped image upload failed\" },\n { source: \"drop\", type: file.type },\n );\n });\n }\n return true;\n },\n [addAttachment, fileIntake, onAttachmentError],\n );\n\n // ProseMirror owns drops that land in the editable surface. The React\n // wrapper below catches the rest of the composer area; defaultPrevented\n // keeps one gesture from being attached twice.\n const handleDrop = useCallback(\n (_view: unknown, event: DragEvent) => {\n const files = event.dataTransfer?.files;\n if (!files?.length) return false;\n const handled = addDroppedImages(files);\n if (handled) event.preventDefault();\n return handled;\n },\n [addDroppedImages],\n );\n\n const handleComposerDrop = useCallback(\n (event: ReactDragEvent<HTMLDivElement>) => {\n if (event.defaultPrevented) return;\n if (addDroppedImages(event.dataTransfer.files)) event.preventDefault();\n },\n [addDroppedImages],\n );\n\n const editor = useEditor({\n editable: !disabled,\n extensions: [\n ...createChatTextExtensions(),\n Placeholder.configure({ placeholder }),\n MentionSuggestionsExtension.configure({\n store,\n callbacks: callbacksRef.current,\n }),\n SubmitKeybind.configure({\n onSubmit: () => void handleSubmitRef.current(),\n isMentionOpen: () => popupOpenRef.current,\n }),\n ],\n editorProps: {\n attributes: {\n class: cn(CHAT_TEXT_CLASS, \"w-full resize-none bg-transparent px-1.5 py-2 outline-none\"),\n \"data-testid\": \"athena-chat-composer\",\n },\n handlePaste,\n handleDrop,\n },\n onUpdate: ({ editor: updatedEditor }) => {\n const nextText = serializeDraft(updatedEditor);\n lastEmittedMarkdownRef.current = nextText;\n if (!applyingRuntimeTextRef.current) {\n composerInput.setText(nextText);\n }\n onDraftStateChange?.(nextText.trim().length > 0);\n\n if (showImagePreviews) {\n const mentionedAssetIds = new Set<string>();\n updatedEditor.state.doc.descendants((node) => {\n if (\n node.type.name === \"mention\" &&\n node.attrs.type === \"asset\" &&\n typeof node.attrs.id === \"string\"\n ) {\n mentionedAssetIds.add(node.attrs.id);\n }\n });\n removeImagePreviews(\n (preview) =>\n preview.assetId !== undefined &&\n !mentionedAssetIds.has(preview.assetId),\n );\n }\n },\n immediatelyRender: false,\n });\n\n // Keep ref in sync so handleSubmit always has the editor\n editorRef.current = editor;\n\n useEffect(() => {\n editor?.setEditable(!disabled);\n }, [disabled, editor]);\n\n // This rich editor replaces ComposerPrimitive.Input, so it must mirror its\n // draft into assistant-ui's composer state. Statewire restores that state\n // when a send is rejected during reconnect, and a host may write to it\n // (`useAppendToComposer`); mirroring it back into Tiptap — parsed as the\n // Markdown it was serialized to, mention links included — preserves the\n // user's message instead of leaving an empty composer. Our own echo is\n // skipped on the ref; a restore's re-serialization may differ from the\n // value byte-for-byte, so the ref takes that form to stop a second pass.\n useEffect(() => {\n if (!editor) return;\n const value = composerInput.value;\n if (value === lastEmittedMarkdownRef.current) return;\n const currentMarkdown = serializeDraft(editor);\n lastEmittedMarkdownRef.current = currentMarkdown;\n if (value === currentMarkdown) return;\n // React node views flush their mounts synchronously. Restore outside\n // React's effect phase, and cancel a restore superseded by a newer draft.\n let cancelled = false;\n queueMicrotask(() => {\n if (cancelled || editor.isDestroyed) return;\n applyingRuntimeTextRef.current = true;\n try {\n editor.commands.setContent(value);\n lastEmittedMarkdownRef.current = serializeDraft(editor);\n } finally {\n applyingRuntimeTextRef.current = false;\n }\n onDraftStateChange?.(value.trim().length > 0);\n // A host prefill (`useAppendToComposer(..., { focus: true })`) asked\n // for the caret after its text: now that the text is on screen.\n if (handoff?.focusOnNextMirror) {\n handoff.focusOnNextMirror = false;\n editor.commands.focus(\"end\");\n }\n });\n return () => { cancelled = true; };\n }, [composerInput.value, editor, handoff, onDraftStateChange]);\n\n // Lets host UI outside the chat place the caret at the end of the draft\n // (`useAppendToComposer` focus option) without reaching into the DOM.\n useEffect(() => {\n if (!editor || !handoff) return;\n handoff.focusEnd = () => {\n if (!editor.isDestroyed) editor.commands.focus(\"end\");\n };\n return () => {\n handoff.focusEnd = null;\n };\n }, [editor, handoff]);\n\n const insertAssetMention = useCallback(\n (asset: UploadedChatAsset, sourceFile?: File) => {\n const currentEditor = editorRef.current;\n if (!currentEditor) throw new Error(\"The chat composer is not ready.\");\n currentEditor\n .chain()\n .focus()\n .insertContent({\n type: \"mention\",\n attrs: {\n type: \"asset\",\n name: asset.title,\n id: asset.id,\n assetType: asset.assetType,\n displayAsPreview:\n showImagePreviews && sourceFile?.type.startsWith(\"image/\"),\n },\n })\n // A text node, not a string: the Markdown extension parses string\n // content as Markdown, which would drop a lone space.\n .insertContent({ type: \"text\", text: \" \" })\n .run();\n\n if (\n showImagePreviews &&\n sourceFile?.type.startsWith(\"image/\") &&\n typeof URL.createObjectURL === \"function\"\n ) {\n const existing = imagePreviewsRef.current.find(\n (preview) => preview.file === sourceFile,\n );\n if (existing) {\n replaceImagePreviews(\n imagePreviewsRef.current.map((preview) =>\n preview.key === existing.key\n ? { ...preview, assetId: asset.id, name: asset.title }\n : preview,\n ),\n );\n } else {\n replaceImagePreviews([\n ...imagePreviewsRef.current,\n {\n key: crypto.randomUUID(),\n file: sourceFile,\n name: asset.title,\n src: URL.createObjectURL(sourceFile),\n assetId: asset.id,\n },\n ]);\n }\n }\n },\n [replaceImagePreviews, showImagePreviews],\n );\n\n const removeImagePreview = useCallback(\n (preview: ComposerImagePreview) => {\n if (!preview.assetId) return;\n const currentEditor = editorRef.current;\n if (!currentEditor) return;\n const positions: Array<{ from: number; to: number }> = [];\n currentEditor.state.doc.descendants((node, position) => {\n if (\n node.type.name === \"mention\" &&\n node.attrs.type === \"asset\" &&\n node.attrs.id === preview.assetId\n ) {\n positions.push({ from: position, to: position + node.nodeSize });\n }\n });\n let transaction = currentEditor.state.tr;\n for (const position of positions.reverse()) {\n transaction = transaction.delete(position.from, position.to);\n }\n if (transaction.docChanged) currentEditor.view.dispatch(transaction);\n removeImagePreviews((candidate) => candidate.key === preview.key);\n currentEditor.commands.focus();\n },\n [removeImagePreviews],\n );\n\n useEffect(\n () => registerChatAssetMentionHandler(threadId, insertAssetMention),\n [insertAssetMention, threadId],\n );\n\n const openMentionMenu = useCallback(() => {\n if (disabled) return;\n const currentEditor = editorRef.current;\n if (!currentEditor || currentEditor.isDestroyed) return;\n if (popupOpenRef.current) {\n currentEditor.commands.focus();\n return;\n }\n // The suggestion plugin only opens on an `@` that starts a word\n // (`allowedPrefixes`), so a trigger typed right after text — or after a\n // mention chip, which `textBetween` reports as its leaf text — gets the\n // separating space a user would type.\n const { from } = currentEditor.state.selection;\n const before =\n from > 0\n ? currentEditor.state.doc.textBetween(from - 1, from, \"\\0\", \"\\0\")\n : \"\";\n const needsSpace = before.length > 0 && !/[\\s([{\"']/.test(before);\n currentEditor\n .chain()\n .focus()\n .insertContent({ type: \"text\", text: needsSpace ? \" @\" : \"@\" })\n .run();\n }, [disabled]);\n\n useImperativeHandle(\n outerRef,\n () => ({\n submit: handleSubmit,\n addAttachment,\n insertAssetMention,\n openMentionMenu,\n }),\n [addAttachment, handleSubmit, insertAssetMention, openMentionMenu],\n );\n\n return (\n <>\n <style>{MENTION_STYLES}</style>\n <div\n className={cn(\n \"athena-chat-composer flex-1 min-w-0\",\n appearance === \"paper\" && \"athena-chat-composer--paper\",\n showImagePreviews && \"image-preview-composer\",\n )}\n aria-label=\"Message composer\"\n aria-disabled={disabled}\n onDragOver={(event) => {\n if (Array.from(event.dataTransfer.types).includes(\"Files\")) {\n event.preventDefault();\n event.dataTransfer.dropEffect = \"copy\";\n }\n }}\n onDrop={handleComposerDrop}\n >\n <ImagePreviewStrip\n previews={imagePreviews}\n onRemove={removeImagePreview}\n />\n <EditorContent editor={editor} />\n </div>\n\n {/* Olympus-style mention popup */}\n {popupOpen && popupProps && editor && (\n <MentionSuggestionPopup clientRect={popupProps.clientRect}>\n <MentionSuggestionList\n ref={listRef}\n store={store}\n editor={editor}\n query={popupProps.query}\n command={(item: MenuItem) => popupProps.command(item)}\n closeMenu={() => {\n setPopupOpen(false);\n editor.commands.focus();\n }}\n />\n </MentionSuggestionPopup>\n )}\n </>\n );\n },\n);\n\nTiptapComposer.displayName = \"TiptapComposer\";\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsEA,MAAM,gBAAgB,UAAU,OAA+D;AAAA,EAC7F,MAAM;AAAA,EACN,UAAU;AAAA,EACV,aAAa;AACX,WAAO,EAAE,UAAU,MAAM;AAAA,IAAC,GAAG,eAAe,MAAM,MAAA;AAAA,EACpD;AAAA,EACA,uBAAuB;AACrB,WAAO;AAAA,MACL,OAAO,MAAM;AAEX,YAAI,KAAK,QAAQ,cAAA,EAAiB,QAAO;AAGzC,YAAI,CAAC,YAAY,YAAY,aAAa,SAAS,YAAY,EAAE;AAAA,UAC/D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WAAW;AAAA,UAClB,SAAS,CAAC,SAAmB,WAAW,QAAQ,IAAI;AAAA,UACpD,WAAW,MAAM;AACf,yBAAa,KAAK;AAClB,mBAAO,SAAS,MAAA;AAAA,UAClB;AAAA,QAAA;AAAA,MAAA,EACF,CACF;AAAA,IAAA,GAEJ;AAAA,EAEF;AACF;AAEA,eAAe,cAAc;"}
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const react$1 = require("react");
4
+ const react = require("@assistant-ui/react");
5
+ const athenaDiagnostics = require("../diagnostics/athena-diagnostics.cjs");
6
+ const errors = require("../diagnostics/errors.cjs");
7
+ const statewireThreadList = require("../threads/statewire-thread-list.cjs");
8
+ function createComposerHandoffStore() {
9
+ return { pending: [], focusOnNextMirror: false, focusEnd: null };
10
+ }
11
+ const ComposerHandoffContext = react$1.createContext(null);
12
+ function useComposerHandoffStore() {
13
+ return react$1.useContext(ComposerHandoffContext);
14
+ }
15
+ function useComposerReady() {
16
+ const list = statewireThreadList.useAthenaStatewireThreadList();
17
+ const threadLoading = react.useAuiState((s) => {
18
+ var _a;
19
+ return ((_a = s.optional.thread) == null ? void 0 : _a.isLoading) ?? false;
20
+ });
21
+ return !((list == null ? void 0 : list.isLoading) ?? false) && !threadLoading;
22
+ }
23
+ function mergeComposerDraft({
24
+ current,
25
+ write
26
+ }) {
27
+ if (write.replace || !current) return write.text;
28
+ return `${current}
29
+ ${write.text}`;
30
+ }
31
+ function applyComposerWrite({
32
+ target,
33
+ store,
34
+ write
35
+ }) {
36
+ var _a;
37
+ const current = target.composer.getState().text ?? "";
38
+ const next = mergeComposerDraft({ current, write });
39
+ target.composer.setText(next);
40
+ if (write.focus && store) {
41
+ if (next === current) (_a = store.focusEnd) == null ? void 0 : _a.call(store);
42
+ else store.focusOnNextMirror = true;
43
+ }
44
+ athenaDiagnostics.athenaDiagnostics.emit("composer.handoff", {
45
+ level: "debug",
46
+ data: { phase: "applied", send: write.send, focus: write.focus, chars: next.length }
47
+ });
48
+ if (write.send) {
49
+ return Promise.resolve(target.composer.send({ steer: false })).then(() => void 0);
50
+ }
51
+ return void 0;
52
+ }
53
+ function queueComposerWrite({
54
+ store,
55
+ write
56
+ }) {
57
+ const last = store.pending[store.pending.length - 1];
58
+ const foldable = last !== void 0 && !last.send && !write.send && !write.replace && last.threadId === write.threadId && last.resolve === void 0 && write.resolve === void 0;
59
+ if (foldable) {
60
+ last.text = mergeComposerDraft({ current: last.text, write });
61
+ last.focus = last.focus || write.focus;
62
+ } else {
63
+ store.pending.push(write);
64
+ }
65
+ athenaDiagnostics.athenaDiagnostics.emit("composer.handoff", {
66
+ level: "debug",
67
+ data: { phase: "deferred", send: write.send, focus: write.focus, queued: store.pending.length }
68
+ });
69
+ }
70
+ function dropWrite({ write, reason }) {
71
+ var _a;
72
+ const error = new errors.AthenaSdkError({
73
+ code: "composer_write_dropped",
74
+ message: `A composer ${write.send ? "send" : "draft"} queued before the chat was ready was dropped: ${reason}.`,
75
+ hint: "Make the write again from the chat that is active now.",
76
+ context: { threadId: write.threadId, send: write.send }
77
+ });
78
+ athenaDiagnostics.athenaDiagnostics.emit("composer.handoff", {
79
+ level: "warn",
80
+ error,
81
+ data: { phase: "dropped", send: write.send, reason, threadId: write.threadId }
82
+ });
83
+ (_a = write.reject) == null ? void 0 : _a.call(write, error);
84
+ }
85
+ function drainComposerHandoff({
86
+ store,
87
+ target,
88
+ threadId
89
+ }) {
90
+ var _a;
91
+ const writes = store.pending;
92
+ if (writes.length === 0) return;
93
+ store.pending = [];
94
+ for (const write of writes) {
95
+ if (write.threadId !== null && threadId !== null && write.threadId !== threadId) {
96
+ dropWrite({ write, reason: `it was made for thread ${write.threadId}, thread ${threadId} is active` });
97
+ continue;
98
+ }
99
+ const outcome = applyComposerWrite({ target, store, write });
100
+ (_a = write.resolve) == null ? void 0 : _a.call(write, outcome);
101
+ }
102
+ }
103
+ function clearComposerHandoff({
104
+ store,
105
+ reason
106
+ }) {
107
+ const writes = store.pending;
108
+ if (writes.length === 0) return;
109
+ store.pending = [];
110
+ for (const write of writes) dropWrite({ write, reason });
111
+ }
112
+ exports.ComposerHandoffContext = ComposerHandoffContext;
113
+ exports.applyComposerWrite = applyComposerWrite;
114
+ exports.clearComposerHandoff = clearComposerHandoff;
115
+ exports.createComposerHandoffStore = createComposerHandoffStore;
116
+ exports.drainComposerHandoff = drainComposerHandoff;
117
+ exports.mergeComposerDraft = mergeComposerDraft;
118
+ exports.queueComposerWrite = queueComposerWrite;
119
+ exports.useComposerHandoffStore = useComposerHandoffStore;
120
+ exports.useComposerReady = useComposerReady;
121
+ //# sourceMappingURL=composer-handoff.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composer-handoff.cjs","sources":["../../src/composer/composer-handoff.ts"],"sourcesContent":["/**\n * Composer handoff: writes to the chat composer from host UI that lives\n * outside `<AthenaChat>` (a sidebar, an agenda card, a workflow button).\n *\n * Two problems it solves for `useAppendToComposer` / `useSendMessage`:\n *\n * 1. A write before the chat is ready is lost. While the thread list is still\n * resolving the active thread, or the thread's history is still loading,\n * the composer the hooks write to belongs to a mount that is about to be\n * replaced (thread-list mode keys the statewire subtree by thread), and\n * the draft goes with it. The store below lives ABOVE that mount, so a\n * write made too early waits here and the ready mount drains it.\n * 2. A prefilled draft should put the caret after the text so the user can\n * keep typing or dictating. The Tiptap editor mirrors runtime text on a\n * later tick; the `focusOnNextMirror` flag asks it to focus at the end\n * right after that mirror lands, instead of the host guessing a delay.\n *\n * Every queued write is bound to the statewire thread it was made for and\n * drains only into that thread's mount; a thread switch, an identity change\n * or a provider unmount drops what waits with a `composer_write_dropped`\n * error, never into another user's or another thread's composer.\n */\nimport { createContext, useContext } from 'react';\nimport { useAuiState } from '@assistant-ui/react';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport { useAthenaStatewireThreadList } from '../threads/statewire-thread-list';\n\n/** The slice of the assistant-ui client the handoff writes to. */\nexport interface ComposerTarget {\n composer: {\n getState: () => { text: string };\n setText: (text: string) => void;\n send: (options?: { steer?: boolean }) => unknown;\n };\n}\n\nexport interface ComposerWrite {\n text: string;\n /** Replace the draft instead of appending on a new line. */\n replace: boolean;\n /** Submit right after writing. */\n send: boolean;\n /** Put the caret at the end of the draft once the editor shows it. */\n focus: boolean;\n /** The statewire thread the write was made for; it drains only into that thread's mount. */\n threadId: string | null;\n /** Settled once the write has been applied (and, for `send`, with the send's outcome). */\n resolve?: (outcome: Promise<void> | void) => void;\n /** Settled with `composer_write_dropped` when the write can no longer land. */\n reject?: (error: AthenaSdkError) => void;\n}\n\nexport interface ComposerHandoffStore {\n /** Writes waiting for a ready composer, oldest first. Adjacent plain appends fold together. */\n pending: ComposerWrite[];\n /** Set by a `focus` write; the editor consumes it after mirroring the draft. */\n focusOnNextMirror: boolean;\n /** Registered by the mounted editor: place the caret at the end of the draft. */\n focusEnd: (() => void) | null;\n}\n\nexport function createComposerHandoffStore(): ComposerHandoffStore {\n return { pending: [], focusOnNextMirror: false, focusEnd: null };\n}\n\nexport const ComposerHandoffContext = createContext<ComposerHandoffStore | null>(null);\n\n/** The provider's handoff store, or null outside `AthenaProvider`. */\nexport function useComposerHandoffStore(): ComposerHandoffStore | null {\n return useContext(ComposerHandoffContext);\n}\n\n/**\n * Whether a composer write lands now: in thread-list mode the list has\n * resolved which thread is active, and that thread's history has loaded.\n * Until then the composer the hooks write to is the one of a mount that is\n * about to be replaced, and the draft goes with it.\n *\n * Deliberately not the socket status: a never-started chat sits in\n * `standby` until its first send and must still take a prefill.\n */\nexport function useComposerReady(): boolean {\n const list = useAthenaStatewireThreadList();\n const threadLoading = useAuiState((s) => s.optional.thread?.isLoading ?? false);\n return !(list?.isLoading ?? false) && !threadLoading;\n}\n\n/** The draft after `write`: `replace` (or an empty draft) takes the text as is. */\nexport function mergeComposerDraft({\n current,\n write,\n}: {\n current: string;\n write: Pick<ComposerWrite, 'text' | 'replace'>;\n}): string {\n if (write.replace || !current) return write.text;\n return `${current}\\n${write.text}`;\n}\n\n/**\n * Write into the live composer. Returns the send's outcome for a `send`\n * write so callers can await it.\n */\nexport function applyComposerWrite({\n target,\n store,\n write,\n}: {\n target: ComposerTarget;\n store: ComposerHandoffStore | null;\n write: ComposerWrite;\n}): Promise<void> | void {\n const current = target.composer.getState().text ?? '';\n const next = mergeComposerDraft({ current, write });\n target.composer.setText(next);\n if (write.focus && store) {\n // An unchanged draft never re-mirrors, so focus at once; otherwise the\n // editor focuses itself right after it has shown the new text.\n if (next === current) store.focusEnd?.();\n else store.focusOnNextMirror = true;\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'applied', send: write.send, focus: write.focus, chars: next.length },\n });\n if (write.send) {\n return Promise.resolve(target.composer.send({ steer: false })).then(() => undefined);\n }\n return undefined;\n}\n\n/**\n * Hold a write until the composer is ready. Writes keep their order; a plain\n * append folds into a directly preceding plain append for the same thread\n * (one draft, not two), while a replace or a send is kept as its own step so\n * no message is lost and every send settles on its own.\n */\nexport function queueComposerWrite({\n store,\n write,\n}: {\n store: ComposerHandoffStore;\n write: ComposerWrite;\n}): void {\n const last = store.pending[store.pending.length - 1];\n const foldable =\n last !== undefined &&\n !last.send &&\n !write.send &&\n !write.replace &&\n last.threadId === write.threadId &&\n last.resolve === undefined &&\n write.resolve === undefined;\n if (foldable) {\n last.text = mergeComposerDraft({ current: last.text, write });\n last.focus = last.focus || write.focus;\n } else {\n store.pending.push(write);\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'deferred', send: write.send, focus: write.focus, queued: store.pending.length },\n });\n}\n\nfunction dropWrite({ write, reason }: { write: ComposerWrite; reason: string }): void {\n const error = new AthenaSdkError({\n code: 'composer_write_dropped',\n message: `A composer ${write.send ? 'send' : 'draft'} queued before the chat was ready was dropped: ${reason}.`,\n hint: 'Make the write again from the chat that is active now.',\n context: { threadId: write.threadId, send: write.send },\n });\n athenaDiagnostics.emit('composer.handoff', {\n level: 'warn',\n error,\n data: { phase: 'dropped', send: write.send, reason, threadId: write.threadId },\n });\n write.reject?.(error);\n}\n\n/**\n * Deliver the pending writes, in order, into a now-ready composer. A write\n * made for another thread is dropped (rejected), never applied here.\n */\nexport function drainComposerHandoff({\n store,\n target,\n threadId,\n}: {\n store: ComposerHandoffStore;\n target: ComposerTarget;\n /** The statewire thread of the mount that is draining. */\n threadId: string | null;\n}): void {\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) {\n if (write.threadId !== null && threadId !== null && write.threadId !== threadId) {\n dropWrite({ write, reason: `it was made for thread ${write.threadId}, thread ${threadId} is active` });\n continue;\n }\n const outcome = applyComposerWrite({ target, store, write });\n write.resolve?.(outcome);\n }\n}\n\n/** Drop every pending write (identity changed, provider unmounted). */\nexport function clearComposerHandoff({\n store,\n reason,\n}: {\n store: ComposerHandoffStore;\n reason: string;\n}): void {\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) dropWrite({ write, reason });\n}\n"],"names":["createContext","useContext","useAthenaStatewireThreadList","useAuiState","athenaDiagnostics","AthenaSdkError"],"mappings":";;;;;;;AA8DO,SAAS,6BAAmD;AACjE,SAAO,EAAE,SAAS,CAAA,GAAI,mBAAmB,OAAO,UAAU,KAAA;AAC5D;AAEO,MAAM,yBAAyBA,QAAAA,cAA2C,IAAI;AAG9E,SAAS,0BAAuD;AACrE,SAAOC,QAAAA,WAAW,sBAAsB;AAC1C;AAWO,SAAS,mBAA4B;AAC1C,QAAM,OAAOC,oBAAAA,6BAAA;AACb,QAAM,gBAAgBC,MAAAA,YAAY,CAAC,MAAA;;AAAM,oBAAE,SAAS,WAAX,mBAAmB,cAAa;AAAA,GAAK;AAC9E,SAAO,GAAE,6BAAM,cAAa,UAAU,CAAC;AACzC;AAGO,SAAS,mBAAmB;AAAA,EACjC;AAAA,EACA;AACF,GAGW;AACT,MAAI,MAAM,WAAW,CAAC,gBAA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OAAA;AAAA,EAAO,CAC/F;AACH;AAEA,SAAS,UAAU,EAAE,OAAO,UAA0D;;AACpF,QAAM,QAAQ,IAAIC,sBAAe;AAAA,IAC/B,MAAM;AAAA,IACN,SAAS,cAAc,MAAM,OAAO,SAAS,OAAO,kDAAkD,MAAM;AAAA,IAC5G,MAAM;AAAA,IACN,SAAS,EAAE,UAAU,MAAM,UAAU,MAAM,MAAM,KAAA;AAAA,EAAK,CACvD;AACDD,oBAAAA,kBAAkB,KAAK,oBAAoB;AAAA,IACzC,OAAO;AAAA,IACP;AAAA,IACA,MAAM,EAAE,OAAO,WAAW,MAAM,MAAM,MAAM,QAAQ,UAAU,MAAM,SAAA;AAAA,EAAS,CAC9E;AACD,cAAM,WAAN,+BAAe;AACjB;AAMO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AACF,GAKS;;AACP,QAAM,SAAS,MAAM;AACrB,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,UAAU,CAAA;AAChB,aAAW,SAAS,QAAQ;AAC1B,QAAI,MAAM,aAAa,QAAQ,aAAa,QAAQ,MAAM,aAAa,UAAU;AAC/E,gBAAU,EAAE,OAAO,QAAQ,0BAA0B,MAAM,QAAQ,YAAY,QAAQ,aAAA,CAAc;AACrG;AAAA,IACF;AACA,UAAM,UAAU,mBAAmB,EAAE,QAAQ,OAAO,OAAO;AAC3D,gBAAM,YAAN,+BAAgB;AAAA,EAClB;AACF;AAGO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AACF,GAGS;AACP,QAAM,SAAS,MAAM;AACrB,MAAI,OAAO,WAAW,EAAG;AACzB,QAAM,UAAU,CAAA;AAChB,aAAW,SAAS,OAAQ,WAAU,EAAE,OAAO,QAAQ;AACzD;;;;;;;;;;"}
@@ -0,0 +1,89 @@
1
+ import { AthenaSdkError } from '../diagnostics/errors';
2
+ /** The slice of the assistant-ui client the handoff writes to. */
3
+ export interface ComposerTarget {
4
+ composer: {
5
+ getState: () => {
6
+ text: string;
7
+ };
8
+ setText: (text: string) => void;
9
+ send: (options?: {
10
+ steer?: boolean;
11
+ }) => unknown;
12
+ };
13
+ }
14
+ export interface ComposerWrite {
15
+ text: string;
16
+ /** Replace the draft instead of appending on a new line. */
17
+ replace: boolean;
18
+ /** Submit right after writing. */
19
+ send: boolean;
20
+ /** Put the caret at the end of the draft once the editor shows it. */
21
+ focus: boolean;
22
+ /** The statewire thread the write was made for; it drains only into that thread's mount. */
23
+ threadId: string | null;
24
+ /** Settled once the write has been applied (and, for `send`, with the send's outcome). */
25
+ resolve?: (outcome: Promise<void> | void) => void;
26
+ /** Settled with `composer_write_dropped` when the write can no longer land. */
27
+ reject?: (error: AthenaSdkError) => void;
28
+ }
29
+ export interface ComposerHandoffStore {
30
+ /** Writes waiting for a ready composer, oldest first. Adjacent plain appends fold together. */
31
+ pending: ComposerWrite[];
32
+ /** Set by a `focus` write; the editor consumes it after mirroring the draft. */
33
+ focusOnNextMirror: boolean;
34
+ /** Registered by the mounted editor: place the caret at the end of the draft. */
35
+ focusEnd: (() => void) | null;
36
+ }
37
+ export declare function createComposerHandoffStore(): ComposerHandoffStore;
38
+ export declare const ComposerHandoffContext: import("react").Context<ComposerHandoffStore | null>;
39
+ /** The provider's handoff store, or null outside `AthenaProvider`. */
40
+ export declare function useComposerHandoffStore(): ComposerHandoffStore | null;
41
+ /**
42
+ * Whether a composer write lands now: in thread-list mode the list has
43
+ * resolved which thread is active, and that thread's history has loaded.
44
+ * Until then the composer the hooks write to is the one of a mount that is
45
+ * about to be replaced, and the draft goes with it.
46
+ *
47
+ * Deliberately not the socket status: a never-started chat sits in
48
+ * `standby` until its first send and must still take a prefill.
49
+ */
50
+ export declare function useComposerReady(): boolean;
51
+ /** The draft after `write`: `replace` (or an empty draft) takes the text as is. */
52
+ export declare function mergeComposerDraft({ current, write, }: {
53
+ current: string;
54
+ write: Pick<ComposerWrite, 'text' | 'replace'>;
55
+ }): string;
56
+ /**
57
+ * Write into the live composer. Returns the send's outcome for a `send`
58
+ * write so callers can await it.
59
+ */
60
+ export declare function applyComposerWrite({ target, store, write, }: {
61
+ target: ComposerTarget;
62
+ store: ComposerHandoffStore | null;
63
+ write: ComposerWrite;
64
+ }): Promise<void> | void;
65
+ /**
66
+ * Hold a write until the composer is ready. Writes keep their order; a plain
67
+ * append folds into a directly preceding plain append for the same thread
68
+ * (one draft, not two), while a replace or a send is kept as its own step so
69
+ * no message is lost and every send settles on its own.
70
+ */
71
+ export declare function queueComposerWrite({ store, write, }: {
72
+ store: ComposerHandoffStore;
73
+ write: ComposerWrite;
74
+ }): void;
75
+ /**
76
+ * Deliver the pending writes, in order, into a now-ready composer. A write
77
+ * made for another thread is dropped (rejected), never applied here.
78
+ */
79
+ export declare function drainComposerHandoff({ store, target, threadId, }: {
80
+ store: ComposerHandoffStore;
81
+ target: ComposerTarget;
82
+ /** The statewire thread of the mount that is draining. */
83
+ threadId: string | null;
84
+ }): void;
85
+ /** Drop every pending write (identity changed, provider unmounted). */
86
+ export declare function clearComposerHandoff({ store, reason, }: {
87
+ store: ComposerHandoffStore;
88
+ reason: string;
89
+ }): void;
@@ -0,0 +1,121 @@
1
+ import { createContext, useContext } from "react";
2
+ import { useAuiState } from "@assistant-ui/react";
3
+ import { athenaDiagnostics } from "../diagnostics/athena-diagnostics.js";
4
+ import { AthenaSdkError } from "../diagnostics/errors.js";
5
+ import { useAthenaStatewireThreadList } from "../threads/statewire-thread-list.js";
6
+ function createComposerHandoffStore() {
7
+ return { pending: [], focusOnNextMirror: false, focusEnd: null };
8
+ }
9
+ const ComposerHandoffContext = createContext(null);
10
+ function useComposerHandoffStore() {
11
+ return useContext(ComposerHandoffContext);
12
+ }
13
+ function useComposerReady() {
14
+ const list = useAthenaStatewireThreadList();
15
+ const threadLoading = useAuiState((s) => {
16
+ var _a;
17
+ return ((_a = s.optional.thread) == null ? void 0 : _a.isLoading) ?? false;
18
+ });
19
+ return !((list == null ? void 0 : list.isLoading) ?? false) && !threadLoading;
20
+ }
21
+ function mergeComposerDraft({
22
+ current,
23
+ write
24
+ }) {
25
+ if (write.replace || !current) return write.text;
26
+ return `${current}
27
+ ${write.text}`;
28
+ }
29
+ function applyComposerWrite({
30
+ target,
31
+ store,
32
+ write
33
+ }) {
34
+ var _a;
35
+ const current = target.composer.getState().text ?? "";
36
+ const next = mergeComposerDraft({ current, write });
37
+ target.composer.setText(next);
38
+ if (write.focus && store) {
39
+ if (next === current) (_a = store.focusEnd) == null ? void 0 : _a.call(store);
40
+ else store.focusOnNextMirror = true;
41
+ }
42
+ athenaDiagnostics.emit("composer.handoff", {
43
+ level: "debug",
44
+ data: { phase: "applied", send: write.send, focus: write.focus, chars: next.length }
45
+ });
46
+ if (write.send) {
47
+ return Promise.resolve(target.composer.send({ steer: false })).then(() => void 0);
48
+ }
49
+ return void 0;
50
+ }
51
+ function queueComposerWrite({
52
+ store,
53
+ write
54
+ }) {
55
+ const last = store.pending[store.pending.length - 1];
56
+ const foldable = last !== void 0 && !last.send && !write.send && !write.replace && last.threadId === write.threadId && last.resolve === void 0 && write.resolve === void 0;
57
+ if (foldable) {
58
+ last.text = mergeComposerDraft({ current: last.text, write });
59
+ last.focus = last.focus || write.focus;
60
+ } else {
61
+ store.pending.push(write);
62
+ }
63
+ athenaDiagnostics.emit("composer.handoff", {
64
+ level: "debug",
65
+ data: { phase: "deferred", send: write.send, focus: write.focus, queued: store.pending.length }
66
+ });
67
+ }
68
+ function dropWrite({ write, reason }) {
69
+ var _a;
70
+ const error = new AthenaSdkError({
71
+ code: "composer_write_dropped",
72
+ message: `A composer ${write.send ? "send" : "draft"} queued before the chat was ready was dropped: ${reason}.`,
73
+ hint: "Make the write again from the chat that is active now.",
74
+ context: { threadId: write.threadId, send: write.send }
75
+ });
76
+ athenaDiagnostics.emit("composer.handoff", {
77
+ level: "warn",
78
+ error,
79
+ data: { phase: "dropped", send: write.send, reason, threadId: write.threadId }
80
+ });
81
+ (_a = write.reject) == null ? void 0 : _a.call(write, error);
82
+ }
83
+ function drainComposerHandoff({
84
+ store,
85
+ target,
86
+ threadId
87
+ }) {
88
+ var _a;
89
+ const writes = store.pending;
90
+ if (writes.length === 0) return;
91
+ store.pending = [];
92
+ for (const write of writes) {
93
+ if (write.threadId !== null && threadId !== null && write.threadId !== threadId) {
94
+ dropWrite({ write, reason: `it was made for thread ${write.threadId}, thread ${threadId} is active` });
95
+ continue;
96
+ }
97
+ const outcome = applyComposerWrite({ target, store, write });
98
+ (_a = write.resolve) == null ? void 0 : _a.call(write, outcome);
99
+ }
100
+ }
101
+ function clearComposerHandoff({
102
+ store,
103
+ reason
104
+ }) {
105
+ const writes = store.pending;
106
+ if (writes.length === 0) return;
107
+ store.pending = [];
108
+ for (const write of writes) dropWrite({ write, reason });
109
+ }
110
+ export {
111
+ ComposerHandoffContext,
112
+ applyComposerWrite,
113
+ clearComposerHandoff,
114
+ createComposerHandoffStore,
115
+ drainComposerHandoff,
116
+ mergeComposerDraft,
117
+ queueComposerWrite,
118
+ useComposerHandoffStore,
119
+ useComposerReady
120
+ };
121
+ //# sourceMappingURL=composer-handoff.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composer-handoff.js","sources":["../../src/composer/composer-handoff.ts"],"sourcesContent":["/**\n * Composer handoff: writes to the chat composer from host UI that lives\n * outside `<AthenaChat>` (a sidebar, an agenda card, a workflow button).\n *\n * Two problems it solves for `useAppendToComposer` / `useSendMessage`:\n *\n * 1. A write before the chat is ready is lost. While the thread list is still\n * resolving the active thread, or the thread's history is still loading,\n * the composer the hooks write to belongs to a mount that is about to be\n * replaced (thread-list mode keys the statewire subtree by thread), and\n * the draft goes with it. The store below lives ABOVE that mount, so a\n * write made too early waits here and the ready mount drains it.\n * 2. A prefilled draft should put the caret after the text so the user can\n * keep typing or dictating. The Tiptap editor mirrors runtime text on a\n * later tick; the `focusOnNextMirror` flag asks it to focus at the end\n * right after that mirror lands, instead of the host guessing a delay.\n *\n * Every queued write is bound to the statewire thread it was made for and\n * drains only into that thread's mount; a thread switch, an identity change\n * or a provider unmount drops what waits with a `composer_write_dropped`\n * error, never into another user's or another thread's composer.\n */\nimport { createContext, useContext } from 'react';\nimport { useAuiState } from '@assistant-ui/react';\nimport { athenaDiagnostics } from '../diagnostics/athena-diagnostics';\nimport { AthenaSdkError } from '../diagnostics/errors';\nimport { useAthenaStatewireThreadList } from '../threads/statewire-thread-list';\n\n/** The slice of the assistant-ui client the handoff writes to. */\nexport interface ComposerTarget {\n composer: {\n getState: () => { text: string };\n setText: (text: string) => void;\n send: (options?: { steer?: boolean }) => unknown;\n };\n}\n\nexport interface ComposerWrite {\n text: string;\n /** Replace the draft instead of appending on a new line. */\n replace: boolean;\n /** Submit right after writing. */\n send: boolean;\n /** Put the caret at the end of the draft once the editor shows it. */\n focus: boolean;\n /** The statewire thread the write was made for; it drains only into that thread's mount. */\n threadId: string | null;\n /** Settled once the write has been applied (and, for `send`, with the send's outcome). */\n resolve?: (outcome: Promise<void> | void) => void;\n /** Settled with `composer_write_dropped` when the write can no longer land. */\n reject?: (error: AthenaSdkError) => void;\n}\n\nexport interface ComposerHandoffStore {\n /** Writes waiting for a ready composer, oldest first. Adjacent plain appends fold together. */\n pending: ComposerWrite[];\n /** Set by a `focus` write; the editor consumes it after mirroring the draft. */\n focusOnNextMirror: boolean;\n /** Registered by the mounted editor: place the caret at the end of the draft. */\n focusEnd: (() => void) | null;\n}\n\nexport function createComposerHandoffStore(): ComposerHandoffStore {\n return { pending: [], focusOnNextMirror: false, focusEnd: null };\n}\n\nexport const ComposerHandoffContext = createContext<ComposerHandoffStore | null>(null);\n\n/** The provider's handoff store, or null outside `AthenaProvider`. */\nexport function useComposerHandoffStore(): ComposerHandoffStore | null {\n return useContext(ComposerHandoffContext);\n}\n\n/**\n * Whether a composer write lands now: in thread-list mode the list has\n * resolved which thread is active, and that thread's history has loaded.\n * Until then the composer the hooks write to is the one of a mount that is\n * about to be replaced, and the draft goes with it.\n *\n * Deliberately not the socket status: a never-started chat sits in\n * `standby` until its first send and must still take a prefill.\n */\nexport function useComposerReady(): boolean {\n const list = useAthenaStatewireThreadList();\n const threadLoading = useAuiState((s) => s.optional.thread?.isLoading ?? false);\n return !(list?.isLoading ?? false) && !threadLoading;\n}\n\n/** The draft after `write`: `replace` (or an empty draft) takes the text as is. */\nexport function mergeComposerDraft({\n current,\n write,\n}: {\n current: string;\n write: Pick<ComposerWrite, 'text' | 'replace'>;\n}): string {\n if (write.replace || !current) return write.text;\n return `${current}\\n${write.text}`;\n}\n\n/**\n * Write into the live composer. Returns the send's outcome for a `send`\n * write so callers can await it.\n */\nexport function applyComposerWrite({\n target,\n store,\n write,\n}: {\n target: ComposerTarget;\n store: ComposerHandoffStore | null;\n write: ComposerWrite;\n}): Promise<void> | void {\n const current = target.composer.getState().text ?? '';\n const next = mergeComposerDraft({ current, write });\n target.composer.setText(next);\n if (write.focus && store) {\n // An unchanged draft never re-mirrors, so focus at once; otherwise the\n // editor focuses itself right after it has shown the new text.\n if (next === current) store.focusEnd?.();\n else store.focusOnNextMirror = true;\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'applied', send: write.send, focus: write.focus, chars: next.length },\n });\n if (write.send) {\n return Promise.resolve(target.composer.send({ steer: false })).then(() => undefined);\n }\n return undefined;\n}\n\n/**\n * Hold a write until the composer is ready. Writes keep their order; a plain\n * append folds into a directly preceding plain append for the same thread\n * (one draft, not two), while a replace or a send is kept as its own step so\n * no message is lost and every send settles on its own.\n */\nexport function queueComposerWrite({\n store,\n write,\n}: {\n store: ComposerHandoffStore;\n write: ComposerWrite;\n}): void {\n const last = store.pending[store.pending.length - 1];\n const foldable =\n last !== undefined &&\n !last.send &&\n !write.send &&\n !write.replace &&\n last.threadId === write.threadId &&\n last.resolve === undefined &&\n write.resolve === undefined;\n if (foldable) {\n last.text = mergeComposerDraft({ current: last.text, write });\n last.focus = last.focus || write.focus;\n } else {\n store.pending.push(write);\n }\n athenaDiagnostics.emit('composer.handoff', {\n level: 'debug',\n data: { phase: 'deferred', send: write.send, focus: write.focus, queued: store.pending.length },\n });\n}\n\nfunction dropWrite({ write, reason }: { write: ComposerWrite; reason: string }): void {\n const error = new AthenaSdkError({\n code: 'composer_write_dropped',\n message: `A composer ${write.send ? 'send' : 'draft'} queued before the chat was ready was dropped: ${reason}.`,\n hint: 'Make the write again from the chat that is active now.',\n context: { threadId: write.threadId, send: write.send },\n });\n athenaDiagnostics.emit('composer.handoff', {\n level: 'warn',\n error,\n data: { phase: 'dropped', send: write.send, reason, threadId: write.threadId },\n });\n write.reject?.(error);\n}\n\n/**\n * Deliver the pending writes, in order, into a now-ready composer. A write\n * made for another thread is dropped (rejected), never applied here.\n */\nexport function drainComposerHandoff({\n store,\n target,\n threadId,\n}: {\n store: ComposerHandoffStore;\n target: ComposerTarget;\n /** The statewire thread of the mount that is draining. */\n threadId: string | null;\n}): void {\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) {\n if (write.threadId !== null && threadId !== null && write.threadId !== threadId) {\n dropWrite({ write, reason: `it was made for thread ${write.threadId}, thread ${threadId} is active` });\n continue;\n }\n const outcome = applyComposerWrite({ target, store, write });\n write.resolve?.(outcome);\n }\n}\n\n/** Drop every pending write (identity changed, provider unmounted). */\nexport function clearComposerHandoff({\n store,\n reason,\n}: {\n store: ComposerHandoffStore;\n reason: string;\n}): void {\n const writes = store.pending;\n if (writes.length === 0) return;\n store.pending = [];\n for (const write of writes) dropWrite({ write, reason });\n}\n"],"names":[],"mappings":";;;;;AA8DO,SAAS,6BAAmD;AACjE,SAAO,EAAE,SAAS,CAAA,GAAI,mBAAmB,OAAO,UAAU,KAAA;AAC5D;AAEO,MAAM,yBAAyB,cAA2C,IAAI;AAG9E,SAAS,0BAAuD;AACrE,SAAO,WAAW,sBAAsB;AAC1C;AAWO,SAAS,mBAA4B;AAC1C,QAAM,OAAO,6BAAA;AACb,QAAM,gBAAgB,YAAY,CAAC,MAAA;;AAAM,oBAAE,SAAS,WAAX,mBAAmB,cAAa;A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  export { useAppendToComposer } from './useAppendToComposer';
2
+ export type { AppendToComposerOptions } from './useAppendToComposer';
2
3
  export { useSendMessage } from './useSendMessage';
3
4
  export type { SendMessageOptions } from './useSendMessage';
5
+ export { useComposerReady } from './composer-handoff';
4
6
  export { useComposerAttachment } from './useComposerAttachment';
5
7
  export { useFileUpload } from './useFileUpload';
6
8
  export type { UploadedAsset, UploadProgress, UseFileUploadReturn } from './useFileUpload';
@@ -2,19 +2,31 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const react$1 = require("react");
4
4
  const react = require("@assistant-ui/react");
5
+ const threadIdContext = require("../threads/thread-id-context.cjs");
6
+ const composerHandoff = require("./composer-handoff.cjs");
5
7
  function useAppendToComposer() {
6
8
  const aui = react.useAui();
9
+ const store = composerHandoff.useComposerHandoffStore();
10
+ const threadId = react$1.useContext(threadIdContext.AthenaStatewireThreadIdContext);
11
+ const ready = composerHandoff.useComposerReady();
12
+ const readyRef = react$1.useRef(ready);
13
+ readyRef.current = ready;
7
14
  return react$1.useCallback(
8
15
  (text, opts) => {
9
- if (opts == null ? void 0 : opts.replace) {
10
- aui.composer.setText(text);
11
- } else {
12
- const current = aui.composer.getState().text;
13
- aui.composer.setText(current ? `${current}
14
- ${text}` : text);
16
+ const write = {
17
+ text,
18
+ replace: (opts == null ? void 0 : opts.replace) ?? false,
19
+ send: false,
20
+ focus: (opts == null ? void 0 : opts.focus) ?? false,
21
+ threadId
22
+ };
23
+ if (store && !readyRef.current) {
24
+ composerHandoff.queueComposerWrite({ store, write });
25
+ return;
15
26
  }
27
+ composerHandoff.applyComposerWrite({ target: aui, store, write });
16
28
  },
17
- [aui]
29
+ [aui, store, threadId]
18
30
  );
19
31
  }
20
32
  exports.useAppendToComposer = useAppendToComposer;