@agent-native/core 0.59.0 → 0.60.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/a2a/index.d.ts +2 -0
- package/dist/a2a/index.d.ts.map +1 -1
- package/dist/a2a/index.js +1 -0
- package/dist/a2a/index.js.map +1 -1
- package/dist/a2a/invoke.d.ts +63 -0
- package/dist/a2a/invoke.d.ts.map +1 -0
- package/dist/a2a/invoke.js +157 -0
- package/dist/a2a/invoke.js.map +1 -0
- package/dist/agent/run-store.d.ts +15 -0
- package/dist/agent/run-store.d.ts.map +1 -1
- package/dist/agent/run-store.js +28 -0
- package/dist/agent/run-store.js.map +1 -1
- package/dist/chat-threads/store.d.ts +21 -0
- package/dist/chat-threads/store.d.ts.map +1 -1
- package/dist/chat-threads/store.js +128 -0
- package/dist/chat-threads/store.js.map +1 -1
- package/dist/cli/agent.d.ts +23 -0
- package/dist/cli/agent.d.ts.map +1 -0
- package/dist/cli/agent.js +300 -0
- package/dist/cli/agent.js.map +1 -0
- package/dist/cli/agents.d.ts +14 -0
- package/dist/cli/agents.d.ts.map +1 -0
- package/dist/cli/agents.js +95 -0
- package/dist/cli/agents.js.map +1 -0
- package/dist/cli/code-agent-executor.d.ts.map +1 -1
- package/dist/cli/code-agent-executor.js +264 -2
- package/dist/cli/code-agent-executor.js.map +1 -1
- package/dist/cli/create.d.ts +3 -2
- package/dist/cli/create.d.ts.map +1 -1
- package/dist/cli/create.js +154 -83
- package/dist/cli/create.js.map +1 -1
- package/dist/cli/index.js +50 -2
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/invoke.d.ts +26 -0
- package/dist/cli/invoke.d.ts.map +1 -0
- package/dist/cli/invoke.js +227 -0
- package/dist/cli/invoke.js.map +1 -0
- package/dist/cli/templates-meta.d.ts +1 -1
- package/dist/cli/templates-meta.d.ts.map +1 -1
- package/dist/cli/templates-meta.js +9 -8
- package/dist/cli/templates-meta.js.map +1 -1
- package/dist/cli/workspacify.d.ts +1 -1
- package/dist/cli/workspacify.d.ts.map +1 -1
- package/dist/cli/workspacify.js +6 -6
- package/dist/cli/workspacify.js.map +1 -1
- package/dist/client/AgentPanel.js +1 -1
- package/dist/client/AgentPanel.js.map +1 -1
- package/dist/client/AssistantChat.d.ts.map +1 -1
- package/dist/client/AssistantChat.js +8 -2
- package/dist/client/AssistantChat.js.map +1 -1
- package/dist/client/NewWorkspaceAppFlow.d.ts.map +1 -1
- package/dist/client/NewWorkspaceAppFlow.js +5 -4
- package/dist/client/NewWorkspaceAppFlow.js.map +1 -1
- package/dist/client/agent-chat-adapter.d.ts.map +1 -1
- package/dist/client/agent-chat-adapter.js +65 -12
- package/dist/client/agent-chat-adapter.js.map +1 -1
- package/dist/client/blocks/library/diagram.d.ts.map +1 -1
- package/dist/client/blocks/library/diagram.js +23 -17
- package/dist/client/blocks/library/diagram.js.map +1 -1
- package/dist/client/blocks/types.d.ts +2 -0
- package/dist/client/blocks/types.d.ts.map +1 -1
- package/dist/client/blocks/types.js.map +1 -1
- package/dist/client/chat/index.d.ts +1 -1
- package/dist/client/chat/index.d.ts.map +1 -1
- package/dist/client/chat/index.js.map +1 -1
- package/dist/client/extensions/ExtensionViewer.js +1 -1
- package/dist/client/extensions/ExtensionViewer.js.map +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/notifications/NotificationsBell.d.ts +3 -1
- package/dist/client/notifications/NotificationsBell.d.ts.map +1 -1
- package/dist/client/notifications/NotificationsBell.js +7 -3
- package/dist/client/notifications/NotificationsBell.js.map +1 -1
- package/dist/client/use-chat-threads.d.ts +13 -0
- package/dist/client/use-chat-threads.d.ts.map +1 -1
- package/dist/client/use-chat-threads.js +41 -0
- package/dist/client/use-chat-threads.js.map +1 -1
- package/dist/integrations/plugin.d.ts.map +1 -1
- package/dist/integrations/plugin.js +2 -2
- package/dist/integrations/plugin.js.map +1 -1
- package/dist/onboarding/default-steps.d.ts.map +1 -1
- package/dist/onboarding/default-steps.js +102 -0
- package/dist/onboarding/default-steps.js.map +1 -1
- package/dist/org/auto-join-domain.d.ts +11 -3
- package/dist/org/auto-join-domain.d.ts.map +1 -1
- package/dist/org/auto-join-domain.js +7 -6
- package/dist/org/auto-join-domain.js.map +1 -1
- package/dist/org/context.d.ts.map +1 -1
- package/dist/org/context.js +68 -32
- package/dist/org/context.js.map +1 -1
- package/dist/org/migrations.d.ts.map +1 -1
- package/dist/org/migrations.js +6 -0
- package/dist/org/migrations.js.map +1 -1
- package/dist/provider-api/actions/github-repo-files.d.ts +84 -0
- package/dist/provider-api/actions/github-repo-files.d.ts.map +1 -0
- package/dist/provider-api/actions/github-repo-files.js +213 -0
- package/dist/provider-api/actions/github-repo-files.js.map +1 -0
- package/dist/provider-api/github-repo.d.ts +11 -0
- package/dist/provider-api/github-repo.d.ts.map +1 -0
- package/dist/provider-api/github-repo.js +553 -0
- package/dist/provider-api/github-repo.js.map +1 -0
- package/dist/provider-api/index.d.ts +184 -11
- package/dist/provider-api/index.d.ts.map +1 -1
- package/dist/provider-api/index.js +519 -0
- package/dist/provider-api/index.js.map +1 -1
- package/dist/scripts/docs/search.d.ts.map +1 -1
- package/dist/scripts/docs/search.js +38 -13
- package/dist/scripts/docs/search.js.map +1 -1
- package/dist/secrets/register-framework-secrets.d.ts.map +1 -1
- package/dist/secrets/register-framework-secrets.js +11 -0
- package/dist/secrets/register-framework-secrets.js.map +1 -1
- package/dist/server/agent-chat-plugin.d.ts +32 -0
- package/dist/server/agent-chat-plugin.d.ts.map +1 -1
- package/dist/server/agent-chat-plugin.js +297 -2
- package/dist/server/agent-chat-plugin.js.map +1 -1
- package/dist/server/auth-marketing.d.ts.map +1 -1
- package/dist/server/auth-marketing.js +17 -7
- package/dist/server/auth-marketing.js.map +1 -1
- package/dist/server/auth.d.ts.map +1 -1
- package/dist/server/auth.js +6 -0
- package/dist/server/auth.js.map +1 -1
- package/dist/server/core-routes-plugin.d.ts.map +1 -1
- package/dist/server/core-routes-plugin.js +18 -98
- package/dist/server/core-routes-plugin.js.map +1 -1
- package/dist/styles/blocks.css +30 -8
- package/dist/styles/rich-markdown-editor.css +10 -4
- package/dist/templates/{starter-shell-sync.spec.ts → chat-shell-sync.spec.ts} +21 -21
- package/dist/templates/default/.agents/skills/actions/SKILL.md +5 -5
- package/dist/templates/default/.agents/skills/agent-native-docs/SKILL.md +63 -0
- package/dist/templates/default/AGENTS.md +22 -1
- package/dist/templates/default/actions/hello.ts +1 -1
- package/dist/templates/default/actions/navigate.ts +1 -1
- package/dist/templates/default/actions/view-screen.ts +1 -1
- package/dist/templates/headless/.agents/skills/agent-native-docs/SKILL.md +63 -0
- package/dist/templates/headless/.env.example +4 -0
- package/dist/templates/headless/.prettierrc +5 -0
- package/dist/templates/headless/AGENTS.md +58 -0
- package/dist/templates/headless/DEVELOPING.md +22 -0
- package/dist/templates/headless/_gitignore +36 -0
- package/dist/templates/headless/actions/hello.ts +14 -0
- package/dist/templates/headless/actions/run.ts +3 -0
- package/dist/templates/headless/package.json +22 -0
- package/dist/templates/headless/tsconfig.json +7 -0
- package/dist/templates/ui-primitives-sync.spec.ts +2 -2
- package/dist/templates/workspace-core/.agents/skills/actions/SKILL.md +5 -5
- package/dist/templates/workspace-core/.agents/skills/agent-native-docs/SKILL.md +63 -0
- package/dist/templates/workspace-core/.agents/skills/client-side-routing/SKILL.md +9 -0
- package/dist/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +93 -0
- package/dist/templates/workspace-core/.agents/skills/context-awareness/SKILL.md +11 -1
- package/dist/templates/workspace-core/.agents/skills/secrets/SKILL.md +1 -1
- package/dist/templates/workspace-core/AGENTS.md +20 -3
- package/dist/templates/workspace-core/src/server/index.ts +1 -1
- package/dist/templates/workspace-root/AGENTS.md +25 -5
- package/dist/templates/workspace-root/README.md +7 -7
- package/dist/triggers/dispatcher.d.ts +2 -3
- package/dist/triggers/dispatcher.d.ts.map +1 -1
- package/dist/triggers/dispatcher.js +2 -3
- package/dist/triggers/dispatcher.js.map +1 -1
- package/dist/triggers/routes.d.ts +38 -0
- package/dist/triggers/routes.d.ts.map +1 -0
- package/dist/triggers/routes.js +202 -0
- package/dist/triggers/routes.js.map +1 -0
- package/dist/vite/client.d.ts +2 -1
- package/dist/vite/client.d.ts.map +1 -1
- package/dist/vite/client.js +121 -2
- package/dist/vite/client.js.map +1 -1
- package/docs/AGENTS.md +57 -0
- package/docs/SKILL.md +40 -0
- package/docs/content/a2a-protocol.md +1 -1
- package/docs/content/actions.md +48 -8
- package/docs/content/agent-surfaces.md +76 -14
- package/docs/content/cli-adapters.md +1 -1
- package/docs/content/cloneable-saas.md +5 -4
- package/docs/content/code-agents-ui.md +1 -1
- package/docs/content/components.md +1 -1
- package/docs/content/context-awareness.md +15 -3
- package/docs/content/creating-templates.md +15 -7
- package/docs/content/drop-in-agent.md +1 -1
- package/docs/content/faq.md +6 -4
- package/docs/content/getting-started.md +63 -73
- package/docs/content/key-concepts.md +24 -24
- package/docs/content/native-chat-ui.md +4 -4
- package/docs/content/pure-agent-apps.md +34 -10
- package/docs/content/security.md +1 -1
- package/docs/content/server.md +1 -1
- package/docs/content/template-chat.md +85 -0
- package/docs/content/template-dispatch.md +1 -1
- package/docs/content/tracking.md +1 -1
- package/docs/content/what-is-agent-native.md +7 -6
- package/package.json +10 -1
- package/src/templates/{starter-shell-sync.spec.ts → chat-shell-sync.spec.ts} +21 -21
- package/src/templates/default/.agents/skills/actions/SKILL.md +5 -5
- package/src/templates/default/.agents/skills/agent-native-docs/SKILL.md +63 -0
- package/src/templates/default/AGENTS.md +22 -1
- package/src/templates/default/actions/hello.ts +1 -1
- package/src/templates/default/actions/navigate.ts +1 -1
- package/src/templates/default/actions/view-screen.ts +1 -1
- package/src/templates/headless/.agents/skills/agent-native-docs/SKILL.md +63 -0
- package/src/templates/headless/.env.example +4 -0
- package/src/templates/headless/.prettierrc +5 -0
- package/src/templates/headless/AGENTS.md +58 -0
- package/src/templates/headless/DEVELOPING.md +22 -0
- package/src/templates/headless/_gitignore +36 -0
- package/src/templates/headless/actions/hello.ts +14 -0
- package/src/templates/headless/actions/run.ts +3 -0
- package/src/templates/headless/package.json +22 -0
- package/src/templates/headless/tsconfig.json +7 -0
- package/src/templates/ui-primitives-sync.spec.ts +2 -2
- package/src/templates/workspace-core/.agents/skills/actions/SKILL.md +5 -5
- package/src/templates/workspace-core/.agents/skills/agent-native-docs/SKILL.md +63 -0
- package/src/templates/workspace-core/.agents/skills/client-side-routing/SKILL.md +9 -0
- package/src/templates/workspace-core/.agents/skills/composable-mini-apps/SKILL.md +93 -0
- package/src/templates/workspace-core/.agents/skills/context-awareness/SKILL.md +11 -1
- package/src/templates/workspace-core/.agents/skills/secrets/SKILL.md +1 -1
- package/src/templates/workspace-core/AGENTS.md +20 -3
- package/src/templates/workspace-core/src/server/index.ts +1 -1
- package/src/templates/workspace-root/AGENTS.md +25 -5
- package/src/templates/workspace-root/README.md +7 -7
- package/docs/content/template-starter.md +0 -78
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantChat.js","sourceRoot":"","sources":["../../src/client/AssistantChat.tsx"],"names":[],"mappings":";AAAA,OAAc,EACZ,QAAQ,EACR,MAAM,EACN,SAAS,EACT,WAAW,EACX,OAAO,EACP,eAAe,EACf,UAAU,EACV,mBAAmB,GACpB,MAAM,OAAO,CAAC;AACf,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,gBAAgB,EAChB,SAAS,EACT,MAAM,EACN,WAAW,EACX,kBAAkB,EAClB,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAM7B,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EACL,sBAAsB,GAEvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,6BAA6B,GAE9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,EA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kCAAkC,IACjC,QAAQ,EAAE,GAAG,KAAK,IAAI,EAAE,IAAI,QAAQ,IAAI,EAAE,EAAE,EAC5C,aAAa,EAAC,eAAe,YAE7B,KAAC,kBAAkB,IACjB,GAAG,EAAE,GAAG,KACJ,KAAK,EACT,YAAY,EAAE,YAAY,EAC1B,YAAY,EAAE,YAAY,EAC1B,gBAAgB,EAAE,gBAAgB,EAClC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,QAAQ,GAClB,GACiC,GAChB,GACP,GACO,CAC5B,CAAC;AACJ,CAAC,CAAC,CAAC","sourcesContent":["import React, {\n useState,\n useRef,\n useEffect,\n useCallback,\n useMemo,\n useLayoutEffect,\n forwardRef,\n useImperativeHandle,\n} from \"react\";\nimport {\n AssistantRuntimeProvider,\n useLocalRuntime,\n useThreadRuntime,\n useThread,\n useAui,\n useComposer,\n useComposerRuntime,\n ThreadPrimitive,\n} from \"@assistant-ui/react\";\nimport type {\n Attachment,\n ChatModelAdapter,\n ExportedMessageRepository,\n} from \"@assistant-ui/react\";\nimport { CompositeAttachmentAdapter } from \"@assistant-ui/react\";\nimport {\n createAgentChatAdapter,\n type AgentChatSurfaceKind,\n} from \"./agent-chat-adapter.js\";\nimport {\n createAgentChatRuntimeAdapter,\n type AgentChatRuntime,\n} from \"./chat/runtime.js\";\nimport {\n appendAgentChatContextToMessage,\n formatAgentChatContextItemsForPrompt,\n normalizeAgentChatContextItem,\n publishAgentChatContextItems,\n refreshAgentChatContext,\n type AgentChatContextItem,\n} from \"./agent-chat.js\";\nimport {\n useAgentDynamicSuggestionsResult,\n type AgentDynamicSuggestionsOption,\n} from \"./dynamic-suggestions.js\";\nimport type { ReasoningEffort } from \"../shared/reasoning-effort.js\";\nimport type {\n ChatThreadScope,\n ChatThreadSnapshot,\n} from \"./use-chat-threads.js\";\nimport { useAgentEngineConfigured } from \"./use-agent-engine-configured.js\";\nimport { getActiveRun } from \"./active-run-state.js\";\nimport {\n AgentAutoContinueSignal,\n type ContentPart,\n readSSEStreamRaw,\n settleInterruptedToolCalls,\n} from \"./sse-event-processor.js\";\nimport { captureError } from \"./analytics.js\";\nimport {\n AssistantMessageListErrorBoundary,\n AssistantUiStaleIndexErrorBoundary,\n} from \"./assistant-ui-recovery.js\";\nimport { cn } from \"./utils.js\";\nimport { useNearBottomAutoscroll } from \"./conversation/index.js\";\nimport { TextAttachmentAdapter } from \"./composer/attachment-accept.js\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from \"./components/ui/tooltip.js\";\nimport { AGENT_CHAT_VIEW_TRANSITION_PREPARE_EVENT } from \"./chat-view-transition.js\";\nimport {\n GuidedQuestionFlow,\n useGuidedQuestionFlow,\n} from \"./guided-questions.js\";\nimport { useDevMode } from \"./use-dev-mode.js\";\nimport { agentNativePath } from \"./api-path.js\";\nimport {\n TiptapComposer,\n type ComposerSubmitIntent,\n type TiptapComposerHandle,\n} from \"./composer/TiptapComposer.js\";\nimport { AgentComposerFrame } from \"./composer/AgentComposerFrame.js\";\nimport type {\n AgentComposerLayoutVariant,\n Reference,\n} from \"./composer/types.js\";\nimport { isPastedTextAttachmentName } from \"./composer/pasted-text.js\";\nimport { PastedTextChip } from \"./composer/PastedTextChip.js\";\nimport { ContextMeter } from \"./context-xray/ContextMeter.js\";\nimport {\n IconMessage,\n IconX,\n IconPlayerStop,\n IconChevronDown,\n IconTerminal,\n IconAlertTriangle,\n IconRefresh,\n} from \"@tabler/icons-react\";\n// ─── chat/ module imports ─────────────────────────────────────────────────────\nimport {\n DownscalingImageAttachmentAdapter,\n BinaryDocumentAttachmentAdapter,\n MAX_ESTIMATED_BODY_BYTES,\n AGGRESSIVE_MAX_IMAGE_DIMENSION,\n AGGRESSIVE_JPEG_QUALITY,\n transcodeImageToDataURL,\n createAgentImageAttachments,\n serializeQueuedAttachments,\n estimateAttachmentBodyBytes,\n type QueuedAttachment,\n} from \"./chat/attachment-adapters.js\";\nimport { TextStreamingContext } from \"./chat/markdown-renderer.js\";\nimport {\n ChatRunningContext,\n ApprovalContext,\n type ApprovalContextValue,\n ReconnectStreamMessage,\n} from \"./chat/tool-call-display.js\";\nimport {\n CheckpointContext,\n MessageActionsContext,\n UserMessage,\n AssistantMessage,\n SelectionAttachedPill,\n RunningActivityStatus,\n} from \"./chat/message-components.js\";\nimport {\n BuilderSetupCard,\n LoopLimitContinueCard,\n RunErrorRecoveryCard,\n PlanModeCallout,\n getLoopLimitMetadata,\n getRunErrorMetadata,\n getRequestModeMetadata,\n type LoopLimitInfo,\n type RunErrorInfo,\n} from \"./chat/run-recovery.js\";\nimport {\n repoHasAssistantMessage,\n getRepoMessages,\n getRepoMessage,\n shouldImportServerThreadData,\n} from \"./chat/repo-helpers.js\";\n\nexport {\n AssistantMessageListErrorBoundary,\n AssistantUiStaleIndexErrorBoundary,\n assistantUiRecoverableRenderErrorKind,\n isAssistantUiRecoverableRenderError,\n isAssistantUiStaleIndexError,\n} from \"./assistant-ui-recovery.js\";\n\nexport { displayableUserMessageText } from \"./chat/message-components.js\";\n\nconst useBrowserLayoutEffect =\n typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nexport type AgentRequestMode = \"act\" | \"plan\";\nexport type AgentRecoveryAction = \"continue\" | \"retry\";\nexport interface AssistantChatSendOptions {\n trackInRunsTray?: boolean;\n requestMode?: AgentRequestMode;\n}\n\nfunction createUserMessageRunConfig(\n references?: Reference[],\n requestMode?: AgentRequestMode,\n recoveryAction?: AgentRecoveryAction,\n trackInRunsTray?: boolean,\n approvedToolCalls?: string[],\n) {\n const custom: {\n references?: Reference[];\n requestMode?: AgentRequestMode;\n trackInRunsTray?: boolean;\n approvedToolCalls?: string[];\n } = {};\n if (references && references.length > 0) {\n custom.references = references;\n }\n if (requestMode) {\n custom.requestMode = requestMode;\n }\n if (trackInRunsTray) {\n custom.trackInRunsTray = true;\n }\n if (approvedToolCalls && approvedToolCalls.length > 0) {\n custom.approvedToolCalls = approvedToolCalls;\n }\n const options: {\n runConfig?: { custom: typeof custom };\n metadata?: { custom: { agentNativeRecoveryAction: AgentRecoveryAction } };\n } = {};\n if (Object.keys(custom).length > 0) {\n options.runConfig = { custom };\n }\n if (recoveryAction) {\n options.metadata = {\n custom: { agentNativeRecoveryAction: recoveryAction },\n };\n }\n return options;\n}\n\nconst PENDING_SELECTION_KEY = \"pending-selection-context\";\nconst ACTIVE_RUN_CLEAR_TIMEOUT_MS = 5_000;\nconst ACTIVE_RUN_POLL_INTERVAL_MS = 150;\n\ntype ActiveRunLookup = {\n active?: boolean;\n runId?: string;\n threadId?: string;\n status?: string;\n heartbeatAt?: number | null;\n};\n\nfunction activeRunLooksStale(runInfo: ActiveRunLookup): boolean {\n const heartbeatAt =\n typeof runInfo.heartbeatAt === \"number\" ? runInfo.heartbeatAt : null;\n return (\n runInfo.status === \"running\" &&\n heartbeatAt != null &&\n Date.now() - heartbeatAt > 5000\n );\n}\n\nfunction cloneContentParts(content: ContentPart[]): ContentPart[] {\n return content.map((part) =>\n part.type === \"text\"\n ? { ...part }\n : {\n ...part,\n args: { ...part.args },\n ...(part.mcpApp ? { mcpApp: { ...part.mcpApp } } : {}),\n ...(part.chatUI ? { chatUI: { ...part.chatUI } } : {}),\n },\n );\n}\n\nfunction clearPendingSelection() {\n fetch(\n agentNativePath(\n `/_agent-native/application-state/${PENDING_SELECTION_KEY}`,\n ),\n {\n method: \"DELETE\",\n keepalive: true,\n headers: { \"X-Agent-Native-CSRF\": \"1\" },\n },\n ).catch(() => {});\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"agent-panel:selection-cleared\"));\n }\n}\n\n// Thread ids the server has already told us don't exist (a prior mount's\n// /threads/:id probe returned 404). Module-scoped so it survives remounts:\n// re-probing a known-absent thread on every navigation just re-spams DevTools\n// with 404s for a thread that has no server row yet (e.g. a freshly created,\n// not-yet-sent chat). Reset on a full page reload.\nconst knownAbsentThreadIds = new Set<string>();\n\nasync function waitForThreadRunToClear(apiUrl: string, threadId?: string) {\n if (!threadId) return;\n const deadline = Date.now() + ACTIVE_RUN_CLEAR_TIMEOUT_MS;\n\n while (Date.now() < deadline) {\n try {\n const res = await fetch(\n `${apiUrl}/runs/active?threadId=${encodeURIComponent(threadId)}`,\n );\n if (res.ok) {\n const info = await res.json();\n const heartbeatAt =\n typeof info?.heartbeatAt === \"number\" ? info.heartbeatAt : null;\n const stale =\n info?.status === \"running\" &&\n heartbeatAt != null &&\n Date.now() - heartbeatAt > 5000;\n if (!info?.active || info?.status !== \"running\" || stale) return;\n }\n } catch {\n // Transient poll failure — try again until the short grace period ends.\n }\n\n await new Promise((resolve) =>\n window.setTimeout(resolve, ACTIVE_RUN_POLL_INTERVAL_MS),\n );\n }\n}\n\n// ─── Composer Attachment Preview ─────────────────────────────────────────────\n\nfunction getImageAttachmentSrc(attachment: Attachment): string | null {\n if (attachment.type !== \"image\") return null;\n\n // Prefer the hosted URL when the server already uploaded this attachment.\n const uploadUrl = (attachment as any).metadata?.uploadUrl as\n | string\n | undefined;\n if (uploadUrl) return uploadUrl;\n\n if (\"file\" in attachment && attachment.file) {\n return URL.createObjectURL(attachment.file);\n }\n\n const imagePart = attachment.content?.find((part) => part.type === \"image\");\n return imagePart && \"image\" in imagePart ? imagePart.image : null;\n}\n\nfunction ComposerAttachmentPreviewCard({\n attachment,\n onRemove,\n}: {\n attachment: Attachment;\n onRemove: (id: string) => void;\n}) {\n const [imageSrc, setImageSrc] = useState<string | null>(null);\n\n useEffect(() => {\n const nextSrc = getImageAttachmentSrc(attachment);\n setImageSrc(nextSrc);\n\n return () => {\n if (nextSrc?.startsWith(\"blob:\")) {\n URL.revokeObjectURL(nextSrc);\n }\n };\n }, [attachment]);\n\n if (isPastedTextAttachmentName(attachment.name)) {\n return <PastedTextChip attachment={attachment} onRemove={onRemove} />;\n }\n\n const isImage = !!imageSrc;\n\n return (\n <div\n className={cn(\n \"group relative overflow-hidden border border-border/70 bg-muted/50 text-foreground\",\n isImage\n ? \"h-20 w-20 rounded-xl shadow-[0_12px_30px_-18px_rgba(0,0,0,0.7)]\"\n : \"inline-flex max-w-[220px] items-center gap-2 rounded-lg px-2.5 py-2 text-xs\",\n )}\n >\n {isImage ? (\n <>\n <img\n src={imageSrc}\n alt={attachment.name}\n className=\"h-full w-full object-cover\"\n />\n <div className=\"pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent px-2 py-1.5\">\n <div className=\"truncate text-[10px] font-medium text-white/95\">\n {attachment.name}\n </div>\n </div>\n </>\n ) : (\n <>\n <div className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-background text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground\">\n {attachment.name.split(\".\").pop() || \"file\"}\n </div>\n <div className=\"min-w-0\">\n <div className=\"truncate font-medium\">{attachment.name}</div>\n <div className=\"text-[11px] text-muted-foreground\">\n {attachment.contentType || attachment.type}\n </div>\n </div>\n </>\n )}\n <button\n type=\"button\"\n onClick={() => onRemove(attachment.id)}\n className={cn(\n \"absolute flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-background/95 text-muted-foreground shadow-sm transition hover:text-foreground\",\n isImage\n ? \"right-1.5 top-1.5 opacity-100 md:opacity-0 md:group-hover:opacity-100\"\n : \"right-1.5 top-1.5\",\n )}\n aria-label={`Remove ${attachment.name}`}\n >\n <IconX className=\"h-3 w-3\" />\n </button>\n </div>\n );\n}\n\nfunction ComposerAttachmentPreviewStrip() {\n const attachments = useComposer((state) => state.attachments);\n const aui = useAui();\n\n const handleRemove = useCallback(\n (id: string) => {\n void aui.composer().attachment({ id }).remove();\n },\n [aui],\n );\n\n if (attachments.length === 0) return null;\n\n return (\n <div className=\"flex flex-wrap gap-2 px-2 pt-2\">\n {attachments.map((attachment) => (\n <ComposerAttachmentPreviewCard\n key={attachment.id}\n attachment={attachment}\n onRemove={handleRemove}\n />\n ))}\n </div>\n );\n}\n\nfunction getMessageText(message: unknown): string {\n const msg = (message as { message?: unknown })?.message ?? message;\n const content = (msg as { content?: unknown })?.content;\n if (Array.isArray(content)) {\n return content\n .filter((p: any) => p?.type === \"text\" && typeof p.text === \"string\")\n .map((p: any) => p.text)\n .join(\"\\n\")\n .trim();\n }\n return typeof content === \"string\" ? content.trim() : \"\";\n}\n\nfunction contentPartFollowKey(part: any): string {\n const type = typeof part?.type === \"string\" ? part.type : \"unknown\";\n if (type === \"text\") return `t:${String(part.text ?? \"\").length}`;\n if (type === \"tool-call\") {\n return [\n \"tool\",\n part.toolCallId ?? \"\",\n part.toolName ?? \"\",\n part.status?.type ?? \"\",\n String(part.argsText ?? \"\").length,\n String(part.result ?? \"\").length,\n part.mcpApp ? 1 : 0,\n part.chatUI?.renderer ?? \"\",\n ].join(\":\");\n }\n if (type === \"image\") return `image:${String(part.image ?? \"\").length}`;\n return `${type}:${String(part.text ?? part.result ?? \"\").length}`;\n}\n\nfunction contentFollowKey(content: unknown): string {\n if (typeof content === \"string\") return `t:${content.length}`;\n if (Array.isArray(content))\n return content.map(contentPartFollowKey).join(\"|\");\n return \"\";\n}\n\nfunction messageFollowKey(message: unknown): string {\n const msg = ((message as { message?: unknown })?.message ?? message) as {\n id?: unknown;\n role?: unknown;\n status?: { type?: unknown; reason?: unknown };\n content?: unknown;\n };\n return [\n String(msg?.id ?? \"\"),\n String(msg?.role ?? \"\"),\n String(msg?.status?.type ?? \"\"),\n String(msg?.status?.reason ?? \"\"),\n contentFollowKey(msg?.content),\n ].join(\",\");\n}\n\nfunction queuedMessageFollowKey(message: {\n id: string;\n text: string;\n images?: string[];\n attachments?: QueuedAttachment[];\n references?: Reference[];\n requestMode?: AgentRequestMode;\n recoveryAction?: AgentRecoveryAction;\n}): string {\n return [\n message.id,\n message.text.length,\n message.images?.length ?? 0,\n message.attachments?.length ?? 0,\n message.references?.length ?? 0,\n message.requestMode ?? \"\",\n message.recoveryAction ?? \"\",\n ].join(\":\");\n}\n\nfunction reconnectContentFollowKey(content: ContentPart[]): string {\n return content.map(contentPartFollowKey).join(\"|\");\n}\n\nconst RECOVERY_USER_MESSAGE_PREFIXES = [\n \"Continue from where you left off\",\n \"Continue from where you stopped\",\n \"Retry the previous request from a clean approach\",\n];\n\nfunction getRecoveryActionMetadata(\n message: unknown,\n): AgentRecoveryAction | null {\n const meta = (message as { metadata?: unknown })?.metadata as\n | { custom?: { agentNativeRecoveryAction?: unknown } }\n | undefined;\n const action = meta?.custom?.agentNativeRecoveryAction;\n return action === \"continue\" || action === \"retry\" ? action : null;\n}\n\nfunction isRecoveryUserMessage(message: unknown): boolean {\n if (getRecoveryActionMetadata(message)) return true;\n const text = getMessageText(message);\n return RECOVERY_USER_MESSAGE_PREFIXES.some((prefix) =>\n text.startsWith(prefix),\n );\n}\n\nexport function latestNonRecoveryUserMessageText(\n messages: readonly unknown[],\n): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i] as { role?: unknown };\n if (message?.role !== \"user\") continue;\n if (isRecoveryUserMessage(message)) continue;\n const text = getMessageText(message);\n if (text) return text;\n }\n return \"\";\n}\n\nexport function resolveAssistantChatSubmitIntent({\n isRunning,\n requestedIntent,\n}: {\n isRunning: boolean;\n requestedIntent?: ComposerSubmitIntent;\n}): ComposerSubmitIntent {\n if (isRunning) return \"queued\";\n return requestedIntent ?? \"immediate\";\n}\n\ntype QueuedMessage = {\n id: string;\n text: string;\n images?: string[];\n attachments?: QueuedAttachment[];\n references?: Reference[];\n requestMode?: AgentRequestMode;\n recoveryAction?: AgentRecoveryAction;\n trackInRunsTray?: boolean;\n};\n\n// ─── Main Component ─────────────────────────────────────────────────────────\n\nexport interface AssistantChatHandle {\n /** Programmatically send a message into this chat */\n sendMessage(\n text: string,\n images?: string[],\n options?: AssistantChatSendOptions,\n ): void;\n /** Programmatically prefill the composer without submitting. */\n prefillMessage(text: string): void;\n /** Add or replace keyed context for the next composer submission. */\n setComposerContextItem(item: AgentChatContextItem): void;\n /** Remove a keyed context item from the composer. */\n removeComposerContextItem(key: string): void;\n /** Clear all staged context items from the composer. */\n clearComposerContextItems(): void;\n /** Programmatically send a recovery prompt without replacing the original request. */\n sendRecoveryMessage(\n text: string,\n recoveryAction: AgentRecoveryAction,\n images?: string[],\n ): void;\n /** Queue a message to send after the current run finishes */\n queueMessage(text: string, images?: string[]): void;\n /** Whether the chat is currently running */\n isRunning(): boolean;\n /** Focus the composer input */\n focusComposer(): void;\n /** Export the currently visible client-side thread for operations like fork. */\n exportThreadSnapshot(): ChatThreadSnapshot | null;\n}\n\nexport interface AssistantChatAdapterContext {\n apiUrl: string;\n tabId?: string;\n threadId?: string;\n modelRef: { current: string | undefined };\n engineRef: { current: string | undefined };\n effortRef: { current: ReasoningEffort | undefined };\n execModeRef: { current: \"build\" | \"plan\" | undefined };\n browserTabId?: string;\n scopeRef: { current: ChatThreadScope | null | undefined };\n surface: AgentChatSurfaceKind;\n}\n\nexport interface AssistantChatProps {\n /** API endpoint URL. Default: \"/_agent-native/agent-chat\" */\n apiUrl?: string;\n /** Stable tab identifier passed to the adapter for event correlation */\n tabId?: string;\n /** Stable browser tab id used for tab-scoped app-state context. */\n browserTabId?: string;\n /** Thread ID for SQL-backed persistence. When set, messages are loaded from and saved to the server. */\n threadId?: string;\n /** Resource scope to include with chat requests for server-side context. */\n contextScope?: ChatThreadScope | null;\n /** Whether this chat owns the active visible composer context snapshot. */\n isActiveComposer?: boolean;\n /**\n * Identifies which surface hosts this chat. Defaults to \"app\", which keeps\n * dev filesystem/bash code-editing tools out of in-product sidebars.\n */\n agentChatSurface?: AgentChatSurfaceKind;\n /** Placeholder text for empty state */\n emptyStateText?: string;\n /** Suggestion prompts shown when no messages */\n suggestions?: string[];\n /** Context-aware suggestions merged with `suggestions`. Enabled by default. */\n dynamicSuggestions?: AgentDynamicSuggestionsOption;\n /** Optional content rendered in the empty state, above the suggestion buttons.\n * Used by MultiTabAssistantChat to surface \"previous chats for this design\"\n * when the current thread is empty but the scope has other threads. */\n emptyStateAddon?: React.ReactNode;\n /** Whether to show the header bar. Default: true */\n showHeader?: boolean;\n /** CSS class for the outer container */\n className?: string;\n /** Callback when user clicks \"Use CLI\" button */\n onSwitchToCli?: () => void;\n /** Callback when message count changes */\n onMessageCountChange?: (count: number) => void;\n /** Callback to save thread data to the server (provided by useChatThreads) */\n onSaveThread?: (\n threadId: string,\n data: {\n threadData: string;\n title: string;\n preview: string;\n messageCount: number;\n },\n ) => void;\n /** Callback to generate a title from the first user message */\n onGenerateTitle?: (threadId: string, message: string) => void;\n /** Optional content rendered just above the composer input */\n composerSlot?: React.ReactNode;\n /** Class applied to the shared composer area for host-specific sizing/skin. */\n composerAreaClassName?: string;\n /** Placeholder for the shared composer in its normal idle state. */\n composerPlaceholder?: string;\n /** Visual density for the shared composer shell. */\n composerLayoutVariant?: AgentComposerLayoutVariant;\n /** Center the composer on a fresh empty chat instead of pinning it low. */\n centerComposerWhenEmpty?: boolean;\n /** Hide the default empty-state icon/text/suggestions for custom start screens. */\n emptyStateDisplay?: \"default\" | \"hidden\";\n /** Optional content rendered inside the composer toolbar after the attach button. */\n composerToolbarSlot?: React.ReactNode;\n /** Optional action rendered beside the voice/send controls. */\n composerExtraActionButton?: React.ReactNode;\n /** Disable the composer for capability-gated surfaces while still showing history. */\n composerDisabled?: boolean;\n /** Placeholder to show while the composer is disabled by the host surface. */\n composerDisabledPlaceholder?: string;\n /** When true, skip the restore skeleton (used for freshly created threads with no messages) */\n isNewThread?: boolean;\n /** Called when a slash command (e.g. /clear, /help) is executed */\n onSlashCommand?: (command: string) => void;\n /** Current execution mode (build/plan) */\n execMode?: \"build\" | \"plan\";\n /** Callback to change execution mode */\n onExecModeChange?: (mode: \"build\" | \"plan\") => void;\n /** Disable Plan mode while leaving Act mode available. */\n planModeDisabled?: boolean;\n /** Explanation shown next to the disabled Plan option. */\n planModeDisabledReason?: string;\n /** Selected model override for this conversation (undefined = use server default) */\n selectedModel?: string;\n /** Default model from server config (shown in picker when no override is set) */\n defaultModel?: string;\n /** Selected engine override for this conversation */\n selectedEngine?: string;\n /** Selected reasoning effort override for this conversation */\n selectedEffort?: ReasoningEffort;\n /** Available engine/model list for the model picker */\n availableModels?: Array<{\n engine: string;\n label: string;\n models: string[];\n configured: boolean;\n }>;\n /** Callback when user picks a model from the picker */\n onModelChange?: (model: string, engine: string) => void;\n /** Callback when user picks a reasoning effort from the picker */\n onEffortChange?: (effort: ReasoningEffort) => void;\n /** Callback when user clicks \"Fork Chat\" in the message actions menu */\n onForkChat?: () => void | boolean | Promise<void | boolean>;\n /** Override Builder/provider connect routing for embedded hosts. */\n onConnectProvider?: () => void;\n /**\n * Controls the shared composer + menu. Sidebar keeps the full menu by default;\n * hosts without the sidebar provider stack can use upload-only.\n */\n plusMenuMode?: \"full\" | \"upload-only\" | \"hidden\";\n /**\n * Enable framework provider/env status checks. Embedded hosts that provide\n * model/provider state through another transport can disable these probes.\n */\n providerStatusChecksEnabled?: boolean;\n /**\n * Advanced host override for non-HTTP transports. Defaults to the production\n * sidebar SSE adapter when omitted.\n */\n createAdapter?: (context: AssistantChatAdapterContext) => ChatModelAdapter;\n /**\n * Bring-your-own agent runtime. When supplied, AssistantChat keeps the\n * standard composer/transcript/tool rendering shell but sends turns through\n * this runtime instead of the built-in Agent-Native SSE endpoint. If\n * `createAdapter` is also supplied, the adapter override takes precedence.\n */\n runtime?: AgentChatRuntime;\n /**\n * Explicitly recreate an injected adapter when the host transport identity\n * changes. Omit for the production sidebar so parent rerenders do not reset\n * active chats.\n */\n adapterReloadKey?: unknown;\n /**\n * Advanced host override for thread replay. Defaults to SQL thread fetch when\n * `threadId` is set, or sessionStorage for legacy tab chats.\n */\n loadHistoryRepository?: () => Promise<ExportedMessageRepository | null>;\n /** Re-run `loadHistoryRepository` when the host's external transcript changes. */\n historyReloadKey?: string | number | null;\n /** Smooth the last assistant message while an external transcript is updating. */\n externalStreaming?: boolean;\n}\n\nexport const CHAT_STORAGE_PREFIX = \"agent-chat:\";\nconst THREAD_SNAPSHOT_CACHE_PREFIX = `${CHAT_STORAGE_PREFIX}thread-snapshot:`;\n\nfunction threadSnapshotCacheKey(apiUrl: string, threadId: string): string {\n return `${THREAD_SNAPSHOT_CACHE_PREFIX}${apiUrl}:${threadId}`;\n}\n\nfunction normalizeCachedThreadSnapshot(\n value: unknown,\n): ChatThreadSnapshot | null {\n if (!value || typeof value !== \"object\") return null;\n const snapshot = value as Partial<ChatThreadSnapshot>;\n if (typeof snapshot.threadData !== \"string\") return null;\n return {\n threadData: snapshot.threadData,\n title: typeof snapshot.title === \"string\" ? snapshot.title : \"\",\n preview: typeof snapshot.preview === \"string\" ? snapshot.preview : \"\",\n messageCount:\n typeof snapshot.messageCount === \"number\" &&\n Number.isFinite(snapshot.messageCount)\n ? snapshot.messageCount\n : 0,\n };\n}\n\nfunction readCachedThreadSnapshot(\n apiUrl: string,\n threadId?: string,\n): ChatThreadSnapshot | null {\n if (!threadId || typeof sessionStorage === \"undefined\") return null;\n try {\n const raw = sessionStorage.getItem(\n threadSnapshotCacheKey(apiUrl, threadId),\n );\n return raw ? normalizeCachedThreadSnapshot(JSON.parse(raw)) : null;\n } catch {\n return null;\n }\n}\n\nfunction writeCachedThreadSnapshot(\n apiUrl: string,\n threadId: string | undefined,\n snapshot: ChatThreadSnapshot,\n) {\n if (!threadId || typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.setItem(\n threadSnapshotCacheKey(apiUrl, threadId),\n JSON.stringify(snapshot),\n );\n } catch {}\n}\n\n/** Remove persisted chat for a given tabId (or \"default\"). */\nexport function clearChatStorage(tabId?: string) {\n try {\n sessionStorage.removeItem(`${CHAT_STORAGE_PREFIX}${tabId || \"default\"}`);\n } catch {}\n}\n\n/**\n * Ensure all messages in a thread repository have required fields.\n * assistant-ui accesses `message.metadata.submittedFeedback` and\n * `lastMessage.status.type` without null-checking, so server-constructed\n * messages missing these fields crash.\n */\nfunction ensureMessageMetadata(repo: any): any {\n if (!repo?.messages || !Array.isArray(repo.messages)) return repo;\n for (const entry of repo.messages) {\n // Handle both wrapped ({ message: { ... } }) and flat ({ role, ... }) formats\n const msg = entry?.message ?? entry;\n if (!msg) continue;\n if (!msg.metadata) {\n msg.metadata = {};\n }\n if (msg.role === \"assistant\") {\n const statusType =\n msg.status && typeof msg.status === \"object\"\n ? (msg.status as { type?: unknown }).type\n : undefined;\n const isTerminal =\n statusType === \"complete\" || statusType === \"incomplete\";\n if (!isTerminal) {\n const runError =\n msg.metadata?.custom?.runError ?? msg.metadata?.runError;\n msg.status = runError\n ? { type: \"incomplete\", reason: \"error\" }\n : { type: \"complete\", reason: \"stop\" };\n }\n if (\n Array.isArray(msg.content) &&\n (isTerminal ||\n msg.status?.type === \"complete\" ||\n msg.status?.type === \"incomplete\")\n ) {\n settleInterruptedToolCalls(msg.content);\n }\n }\n }\n return repo;\n}\n\n// Re-export for backwards compatibility\nimport {\n extractThreadMeta,\n normalizeThreadRepository,\n} from \"../agent/thread-data-builder.js\";\nexport { extractThreadMeta };\n\n/**\n * Strip raw base64 payload from attachment content parts when a hosted URL\n * already exists in the same content entry. This keeps the periodic thread\n * save payload compact — the server already stored the URL reference when it\n * processed the POST, and re-shipping multi-megabyte base64 strings on every\n * 5-second poll save balloons the SQL thread_data column unnecessarily.\n *\n * Only strips the raw base64 data-URL string from `content[].image` / `content[].data`\n * when a `metadata.uploadUrl` reference is present on the same attachment object,\n * so the transcript can still render from the hosted URL after hydration.\n */\nfunction stripBase64FromRepo(repo: unknown): unknown {\n if (!repo || typeof repo !== \"object\") return repo;\n const r = repo as Record<string, unknown>;\n if (!Array.isArray(r.messages)) return repo;\n\n const messages = r.messages.map((entry: unknown) => {\n if (!entry || typeof entry !== \"object\") return entry;\n const e = entry as Record<string, unknown>;\n const msg = (e.message ?? e) as Record<string, unknown> | null;\n if (!msg || typeof msg !== \"object\") return entry;\n\n const attachments = msg.attachments;\n if (!Array.isArray(attachments)) return entry;\n\n const strippedAttachments = attachments.map((att: unknown) => {\n if (!att || typeof att !== \"object\") return att;\n const a = att as Record<string, unknown>;\n const meta = a.metadata as Record<string, unknown> | undefined;\n // Only strip when we have a hosted upload URL confirmed by the server.\n if (!meta?.uploadUrl) return att;\n\n if (!Array.isArray(a.content)) return att;\n const strippedContent = a.content.map((part: unknown) => {\n if (!part || typeof part !== \"object\") return part;\n const p = part as Record<string, unknown>;\n // Replace the raw base64 image data-URL with the hosted URL.\n if (\n p.type === \"image\" &&\n typeof p.image === \"string\" &&\n p.image.startsWith(\"data:\")\n ) {\n return { ...p, image: meta.uploadUrl };\n }\n // Replace the raw base64 file data with a stripped marker.\n if (\n p.type === \"file\" &&\n typeof p.data === \"string\" &&\n p.data.startsWith(\"data:\")\n ) {\n const { data: _d, ...rest } = p;\n return { ...rest, url: meta.uploadUrl };\n }\n return part;\n });\n return { ...a, content: strippedContent };\n });\n\n const strippedMsg = { ...msg, attachments: strippedAttachments };\n if (e.message !== undefined) {\n return { ...e, message: strippedMsg };\n }\n return strippedMsg;\n });\n\n return { ...r, messages };\n}\n\nconst AssistantChatInner = forwardRef<\n AssistantChatHandle,\n AssistantChatProps & { apiUrl: string }\n>(function AssistantChatInner(\n {\n emptyStateText,\n suggestions,\n dynamicSuggestions,\n emptyStateAddon,\n showHeader = true,\n onSwitchToCli,\n className,\n apiUrl,\n tabId,\n browserTabId,\n threadId,\n contextScope,\n isActiveComposer = true,\n onMessageCountChange,\n onSaveThread,\n onGenerateTitle,\n composerSlot,\n composerAreaClassName,\n composerPlaceholder,\n composerLayoutVariant = \"default\",\n centerComposerWhenEmpty = false,\n emptyStateDisplay = \"default\",\n composerToolbarSlot,\n composerExtraActionButton,\n composerDisabled = false,\n composerDisabledPlaceholder,\n isNewThread,\n onSlashCommand,\n execMode,\n onExecModeChange,\n planModeDisabled,\n planModeDisabledReason,\n selectedModel,\n defaultModel,\n selectedEffort,\n availableModels,\n onModelChange,\n onEffortChange,\n onForkChat,\n onConnectProvider,\n plusMenuMode = \"full\",\n providerStatusChecksEnabled = true,\n loadHistoryRepository,\n historyReloadKey,\n externalStreaming = false,\n },\n ref,\n) {\n const thread = useThread();\n const threadRuntime = useThreadRuntime();\n const composerRuntime = useComposerRuntime();\n const isRuntimeRunning = thread.isRunning;\n const messages = thread.messages;\n const { suggestions: resolvedSuggestions } = useAgentDynamicSuggestionsResult(\n {\n staticSuggestions: suggestions,\n dynamicSuggestions,\n browserTabId,\n scope: contextScope,\n enabled: messages.length === 0,\n },\n );\n const messageListResetKey = useMemo(\n () => messages.map((message) => message.id).join(\"|\"),\n [messages],\n );\n\n // Chat-wide drag-and-drop: users expect to drop a file anywhere on the agent\n // sidebar (thread, header, composer) and have it attach — same as ChatGPT,\n // Claude.ai, Linear, Slack, etc. Tiptap's own `handleDrop` only fires inside\n // the contenteditable; drops on the message thread or the composer\n // attachment strip otherwise navigate to the file (browser default), which\n // is why \"upload does nothing\" — the chat refreshes to the dropped image.\n const [dropActive, setDropActive] = useState(false);\n // Inline error shown just above the composer for attachment failures\n // (unsupported format, size cap, body-size rejection, drop errors).\n // Cleared on the next message send.\n const [composerError, setComposerError] = useState<string | null>(null);\n const dropDepthRef = useRef(0);\n const handleChatDragEnter = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n e.preventDefault();\n dropDepthRef.current += 1;\n setDropActive(true);\n }, []);\n const handleChatDragOver = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n e.preventDefault();\n if (e.dataTransfer) e.dataTransfer.dropEffect = \"copy\";\n }, []);\n const handleChatDragLeave = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n dropDepthRef.current = Math.max(0, dropDepthRef.current - 1);\n if (dropDepthRef.current === 0) setDropActive(false);\n }, []);\n const handleChatDropCapture = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n dropDepthRef.current = 0;\n setDropActive(false);\n }, []);\n const handleChatDrop = useCallback(\n (e: React.DragEvent) => {\n const files = Array.from(e.dataTransfer?.files ?? []);\n if (files.length === 0) return;\n dropDepthRef.current = 0;\n setDropActive(false);\n if (e.defaultPrevented) return;\n e.preventDefault();\n e.stopPropagation();\n // Mirror TiptapComposer's paste/drop name-uniqueness so consecutive\n // screenshots (all named `image.png`) don't collide on the\n // SimpleImageAttachmentAdapter id.\n const attachments = files.map((file) => {\n if (!file.type.startsWith(\"image/\")) return file;\n const uniqueName = `${Date.now()}-${Math.random().toString(36).slice(2)}-${file.name}`;\n return new File([file], uniqueName, { type: file.type });\n });\n void Promise.all(\n attachments.map((file) => composerRuntime.addAttachment(file)),\n ).catch((error) => {\n const msg =\n error instanceof Error\n ? error.message\n : \"Could not add the dropped file. Try a different format.\";\n setComposerError(msg);\n });\n },\n [composerRuntime, setComposerError],\n );\n\n // Patch the underlying assistant-ui MessageRepository so addOrUpdateMessage\n // can't throw \"Parent message not found\" mid-run. assistant-ui calls\n // `repository.clear()` from `runtime.import()` and from `resetHead(null)`,\n // and on a few async paths (history-adapter load, branch reset, repeat\n // imports) the repo can be cleared between the `append` that added the\n // user message and the `performRoundtrip` call that tries to record the\n // assistant placeholder against that user message's id. The internal-bug\n // throw turns into an unhandled rejection that Sentry captures from the\n // assets.agent-native.com prompt composer (AGENT-NATIVE-BROWSER-18). Fix\n // it by relinking to the current head whenever the requested parent has\n // gone missing instead of throwing.\n useEffect(() => {\n const repo = (threadRuntime as any)?.__internal_threadBinding?.getState?.()\n ?.repository as\n | { addOrUpdateMessage?: (parentId: any, message: any) => void }\n | undefined;\n if (!repo || typeof repo.addOrUpdateMessage !== \"function\") return;\n const patched = repo as any;\n if (patched.__agentNativePatched) return;\n patched.__agentNativePatched = true;\n const original = repo.addOrUpdateMessage.bind(repo);\n repo.addOrUpdateMessage = function (parentId: any, message: any) {\n try {\n return original(parentId, message);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (parentId && msg.includes(\"Parent message not found\")) {\n const fallbackParent = (this as any).head?.current?.id ?? null;\n if (fallbackParent && fallbackParent !== parentId) {\n return original(fallbackParent, message);\n }\n return original(null, message);\n }\n throw err;\n }\n };\n }, [threadRuntime]);\n const missingApiKey = useAgentEngineConfigured(\n providerStatusChecksEnabled,\n ).missing;\n const isComposerDisabled = missingApiKey || composerDisabled;\n // Increments each time the user clicks the (disabled) composer while no LLM\n // is connected — `BuilderSetupCard` watches this to replay a one-shot bounce.\n const [missingKeyBouncePulse, setMissingKeyBouncePulse] = useState(0);\n const [authError, setAuthError] = useState<{\n sessionExpired?: boolean;\n } | null>(null);\n const [authSessionAvailable, setAuthSessionAvailable] = useState(false);\n const [queuedMessages, setQueuedMessages] = useState<QueuedMessage[]>([]);\n const queuedMessagesRef = useRef<QueuedMessage[]>([]);\n const queueDirtyRef = useRef(false);\n const queueMutationVersionRef = useRef(0);\n const dequeueInFlightRef = useRef(false);\n const [composerContextItems, setComposerContextItems] = useState<\n AgentChatContextItem[]\n >([]);\n const composerContextItemsRef = useRef<AgentChatContextItem[]>([]);\n const isActiveComposerRef = useRef(isActiveComposer);\n isActiveComposerRef.current = isActiveComposer;\n const publishComposerContextItems = useCallback(\n (items: AgentChatContextItem[]) => {\n if (!isActiveComposerRef.current) return;\n publishAgentChatContextItems(items);\n },\n [],\n );\n const updateComposerContextItems = useCallback(\n (updater: (previous: AgentChatContextItem[]) => AgentChatContextItem[]) => {\n setComposerContextItems((previous) => {\n const next = updater(previous);\n composerContextItemsRef.current = next;\n publishComposerContextItems(next);\n return next;\n });\n },\n [publishComposerContextItems],\n );\n const stageComposerContextItem = useCallback(\n (rawItem: AgentChatContextItem) => {\n const item = normalizeAgentChatContextItem(rawItem);\n if (!item) return;\n updateComposerContextItems((previous) => {\n const index = previous.findIndex((current) => current.key === item.key);\n if (index === -1) return [...previous, item];\n return previous.map((current, currentIndex) =>\n currentIndex === index ? item : current,\n );\n });\n },\n [updateComposerContextItems],\n );\n const removeComposerContextItem = useCallback(\n (key: string) => {\n updateComposerContextItems((previous) =>\n previous.filter((item) => item.key !== key),\n );\n },\n [updateComposerContextItems],\n );\n const buildComposerContextSubmission = useCallback((text: string) => {\n const context = formatAgentChatContextItemsForPrompt(\n composerContextItemsRef.current,\n );\n if (!context) return { text, includesContext: false };\n return {\n text: appendAgentChatContextToMessage(text, context),\n includesContext: true,\n };\n }, []);\n\n useEffect(() => {\n queuedMessagesRef.current = queuedMessages;\n }, [queuedMessages]);\n\n const applyLocalQueuedMessages = useCallback(\n (updater: (previous: QueuedMessage[]) => QueuedMessage[]) => {\n setQueuedMessages((previous) => {\n const next = updater(previous);\n queuedMessagesRef.current = next;\n queueDirtyRef.current = true;\n queueMutationVersionRef.current += 1;\n return next;\n });\n },\n [],\n );\n\n useEffect(() => {\n if (!isActiveComposer) return;\n let cancelled = false;\n void refreshAgentChatContext().then((state) => {\n if (cancelled || !isActiveComposerRef.current) return;\n composerContextItemsRef.current = state.items;\n setComposerContextItems(state.items);\n });\n return () => {\n cancelled = true;\n };\n }, [isActiveComposer]);\n // Tracks the JSON of the last queue we successfully persisted so the\n // debounced save effect can skip no-op writes (e.g. restore-from-server\n // on mount, or queue state that hasn't actually changed).\n const lastPersistedQueueRef = useRef<string>(\"[]\");\n // Cheap change-guard for `importThreadData`. The real-time sync layer\n // refetches `/threads/:id` (or re-runs `loadHistoryRepository`) on poll /\n // change ticks, on reconnect, and whenever the host's transcript bumps\n // `historyReloadKey`. On a long thread the JSON.parse +\n // normalizeThreadRepository + threadRuntime.export()/import round-trip is\n // CPU-bound and triggers re-render churn even when the content is byte-for-\n // byte identical to what we last imported. We hash the raw incoming payload\n // and skip the whole pipeline when it hasn't advanced, returning the\n // already-imported repo so callers (e.g. the reconnect loop's\n // repoHasAssistantMessage check) see consistent data. Any real change — a\n // new message, an arriving tool result, the server replacing an optimistic\n // copy, or switching threads — produces a different signal and falls\n // through to a full import.\n const lastImportedSignatureRef = useRef<string | null>(null);\n const lastImportedRepoRef = useRef<any>(null);\n const [showContinue, setShowContinue] = useState(false);\n const [loopLimitInfo, setLoopLimitInfo] = useState<LoopLimitInfo | null>(\n null,\n );\n const [runErrorInfo, setRunErrorInfo] = useState<RunErrorInfo | null>(null);\n const [dismissedRunErrorKey, setDismissedRunErrorKey] = useState<\n string | null\n >(null);\n const userStoppedRunRef = useRef<{\n at: number;\n runId?: string;\n } | null>(null);\n const [isReconnecting, setIsReconnecting] = useState(false);\n // True during the 250ms continuation window and startup of the next chunk\n // (adapter's auto-continue delay before POSTing the next chunk).\n const [isAutoResuming, setIsAutoResuming] = useState(false);\n const [reconnectContent, setReconnectContent] = useState<ContentPart[]>([]);\n // When stop is clicked during reconnect, keep content visible (don't wipe it)\n const [reconnectFrozen, setReconnectFrozen] = useState(false);\n const reconnectRunIdRef = useRef<string | null>(null);\n const reconnectAbortRef = useRef<AbortController | null>(null);\n // Nuclear stop: user clicked stop. Clears the stop button/indicator AND\n // lets new submissions go through immediately — prevents the \"stuck\n // queueing forever\" state where isReconnecting or isRuntimeRunning gets\n // wedged (e.g. after a tab refresh + stop during reconnect).\n const [forceStopped, setForceStopped] = useState(false);\n // Real running state — drives submission/queue gating. Treat reconnecting\n // to an active run the same as running, UNLESS the user has explicitly\n // clicked stop (forceStopped).\n const isRunning = !forceStopped && (isRuntimeRunning || isReconnecting);\n const textStreaming = isRunning || externalStreaming;\n // UI-only running state — drives the stop button and thinking indicator.\n const showRunningInUI = isRunning;\n const lastBroadcastRunningRef = useRef(isRunning);\n const tiptapRef = useRef<TiptapComposerHandle>(null);\n // Stable ref to the \"stop active run\" action so addToQueue can abort\n // a running turn without adding many unstable closure deps to its dep list.\n const stopActiveRunRef = useRef<() => void>(() => {});\n\n useEffect(() => {\n if (lastBroadcastRunningRef.current === isRunning) return;\n lastBroadcastRunningRef.current = isRunning;\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning, tabId: tabId || threadId },\n }),\n );\n }, [isRunning, tabId, threadId]);\n\n // ─── Chat persistence ──────────────────────────────────────────────\n const hasRestoredRef = useRef(false);\n const [initialCachedThreadSnapshot] = useState(() =>\n readCachedThreadSnapshot(apiUrl, threadId),\n );\n const hasImportedInitialCachedSnapshotRef = useRef(false);\n const [isRestoring, setIsRestoring] = useState(\n !!(threadId || loadHistoryRepository) &&\n !isNewThread &&\n !initialCachedThreadSnapshot,\n );\n const onSaveThreadRef = useRef(onSaveThread);\n onSaveThreadRef.current = onSaveThread;\n const onGenerateTitleRef = useRef(onGenerateTitle);\n onGenerateTitleRef.current = onGenerateTitle;\n const titleGeneratedRef = useRef(false);\n\n const importThreadData = useCallback(\n (threadData: unknown, options?: { markTitleGenerated?: boolean }): any => {\n // Cheap-signal short-circuit: if the raw payload is identical to the\n // last one we imported, there is nothing new to parse, normalize, or\n // re-import into the runtime. Reuse the already-imported repo so callers\n // still get back a stable result without the CPU + re-render cost. We\n // still honor `markTitleGenerated` because a re-fetch carrying the same\n // content can legitimately confirm a title is settled.\n const signature =\n typeof threadData === \"string\"\n ? threadData\n : (() => {\n try {\n return JSON.stringify(threadData);\n } catch {\n return null;\n }\n })();\n if (\n signature !== null &&\n signature === lastImportedSignatureRef.current\n ) {\n if (options?.markTitleGenerated) {\n titleGeneratedRef.current = true;\n }\n return lastImportedRepoRef.current;\n }\n\n const repo = normalizeThreadRepository(\n typeof threadData === \"string\" ? JSON.parse(threadData) : threadData,\n );\n // Whether this payload settled into the runtime (either imported, or\n // had no messages to import). Only then is it safe to remember its\n // signature as the canonical \"last imported\" — a payload that\n // `shouldImportServerThreadData` deliberately rejected (e.g. it\n // regressed message count) must NOT be cached, so an identical re-fetch\n // re-evaluates against the runtime exactly as before instead of\n // short-circuiting to the rejected repo.\n let settled = true;\n if (repo?.messages?.length > 0) {\n let shouldImport = true;\n try {\n shouldImport = shouldImportServerThreadData(\n normalizeThreadRepository(threadRuntime.export()),\n repo,\n );\n } catch {\n shouldImport = true;\n }\n if (shouldImport) {\n if (options?.markTitleGenerated) {\n titleGeneratedRef.current = true;\n }\n threadRuntime.import(ensureMessageMetadata(repo));\n } else {\n settled = false;\n }\n }\n if (Array.isArray(repo?.queuedMessages)) {\n const incomingQueue = repo.queuedMessages as QueuedMessage[];\n const incomingSerialized = JSON.stringify(incomingQueue);\n const currentSerialized = JSON.stringify(queuedMessagesRef.current);\n if (\n !queueDirtyRef.current ||\n incomingSerialized === currentSerialized\n ) {\n queuedMessagesRef.current = incomingQueue;\n setQueuedMessages(incomingQueue);\n lastPersistedQueueRef.current = incomingSerialized;\n queueDirtyRef.current = false;\n }\n }\n if (settled && signature !== null) {\n lastImportedSignatureRef.current = signature;\n lastImportedRepoRef.current = repo;\n }\n return repo;\n },\n [threadRuntime],\n );\n\n const refreshThreadFromServer = useCallback(async (): Promise<any | null> => {\n if (loadHistoryRepository) {\n try {\n const repo = await loadHistoryRepository();\n if (!repo) return null;\n return importThreadData(repo);\n } catch {\n return null;\n }\n }\n if (!threadId) return null;\n try {\n const refreshRes = await fetch(\n `${apiUrl}/threads/${encodeURIComponent(threadId)}`,\n );\n if (!refreshRes.ok) return null;\n const refreshData = await refreshRes.json();\n if (!refreshData.threadData) return null;\n return importThreadData(refreshData.threadData);\n } catch {\n return null;\n }\n }, [apiUrl, importThreadData, loadHistoryRepository, threadId]);\n\n const cacheCurrentThreadSnapshot = useCallback(() => {\n if (!threadId || messages.length === 0) return;\n const repo = threadRuntime.export();\n const threadData = JSON.stringify(stripBase64FromRepo(repo));\n const { title, preview } = extractThreadMeta(repo);\n writeCachedThreadSnapshot(apiUrl, threadId, {\n threadData,\n title,\n preview,\n messageCount: messages.length,\n });\n }, [apiUrl, messages.length, threadId, threadRuntime]);\n\n useBrowserLayoutEffect(() => {\n if (hasImportedInitialCachedSnapshotRef.current) return;\n if (!initialCachedThreadSnapshot) return;\n hasImportedInitialCachedSnapshotRef.current = true;\n try {\n importThreadData(initialCachedThreadSnapshot.threadData, {\n markTitleGenerated: Boolean(initialCachedThreadSnapshot.title),\n });\n } finally {\n setIsRestoring(false);\n }\n }, [importThreadData, initialCachedThreadSnapshot]);\n\n useEffect(() => {\n window.addEventListener(\n AGENT_CHAT_VIEW_TRANSITION_PREPARE_EVENT,\n cacheCurrentThreadSnapshot,\n );\n return () => {\n window.removeEventListener(\n AGENT_CHAT_VIEW_TRANSITION_PREPARE_EVENT,\n cacheCurrentThreadSnapshot,\n );\n };\n }, [cacheCurrentThreadSnapshot]);\n\n const wasRecentlyStoppedRun = useCallback((runId?: string): boolean => {\n const stopped = userStoppedRunRef.current;\n return Boolean(\n stopped &&\n Date.now() - stopped.at < 10_000 &&\n (!stopped.runId || !runId || stopped.runId === runId),\n );\n }, []);\n\n const startReconnectToRun = useCallback(\n (runInfo: ActiveRunLookup): boolean => {\n if (!threadId || !runInfo.runId || runInfo.status !== \"running\") {\n return false;\n }\n const runId = String(runInfo.runId);\n if (wasRecentlyStoppedRun(runId)) return false;\n if (reconnectRunIdRef.current === runId) return true;\n\n reconnectRunIdRef.current = runId;\n setIsReconnecting(true);\n setReconnectFrozen(false);\n setReconnectContent([]);\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: true, tabId: tabId || threadId },\n }),\n );\n\n const abortCtrl = new AbortController();\n reconnectAbortRef.current = abortCtrl;\n\n const watchdog = setInterval(async () => {\n try {\n const res = await fetch(\n `${apiUrl}/runs/active?threadId=${encodeURIComponent(threadId)}`,\n );\n if (!res.ok) {\n abortCtrl.abort();\n clearInterval(watchdog);\n return;\n }\n const info = (await res.json()) as ActiveRunLookup;\n if (info.status !== \"running\" || activeRunLooksStale(info)) {\n abortCtrl.abort();\n clearInterval(watchdog);\n }\n } catch {\n // Network blip — keep polling.\n }\n }, 1000);\n\n let reconnectTimedOut = false;\n const maxReconnectTimer = setTimeout(() => {\n reconnectTimedOut = true;\n abortCtrl.abort();\n clearInterval(watchdog);\n }, 20_000);\n\n const streamReconnect = async () => {\n let noProgressDuringReconnect = false;\n let latestContent: ContentPart[] = [];\n try {\n const sseRes = await fetch(\n `${apiUrl}/runs/${encodeURIComponent(runId)}/events?after=0`,\n { signal: abortCtrl.signal },\n );\n if (sseRes.ok && sseRes.body) {\n const content: ContentPart[] = [];\n latestContent = content;\n const toolCallCounter = { value: 0 };\n\n let rafPending = false;\n let latestSnapshot: ContentPart[] = [];\n const scheduleUpdate = (snapshot: ContentPart[]) => {\n latestSnapshot = snapshot;\n if (rafPending) return;\n rafPending = true;\n requestAnimationFrame(() => {\n rafPending = false;\n setReconnectContent(latestSnapshot);\n });\n };\n\n await readSSEStreamRaw(\n sseRes.body,\n content,\n toolCallCounter,\n tabId,\n scheduleUpdate,\n );\n setReconnectContent([...content]);\n }\n } catch (err) {\n if (\n err instanceof AgentAutoContinueSignal &&\n err.reason === \"no_progress\"\n ) {\n noProgressDuringReconnect = true;\n } else if (\n reconnectTimedOut &&\n err instanceof Error &&\n err.name === \"AbortError\"\n ) {\n noProgressDuringReconnect = true;\n }\n } finally {\n clearInterval(watchdog);\n clearTimeout(maxReconnectTimer);\n }\n\n if (noProgressDuringReconnect && reconnectRunIdRef.current === runId) {\n captureError(new Error(\"agent-chat:reconnect_no_progress\"), {\n tags: {\n context: \"agent-native-chat\",\n errorCode: \"reconnect_no_progress\",\n reconnectTimedOut: String(reconnectTimedOut),\n },\n extra: {\n runId,\n threadId: threadId ?? null,\n tabId: tabId ?? null,\n contentLength: latestContent.length,\n },\n });\n try {\n await fetch(`${apiUrl}/runs/${encodeURIComponent(runId)}/abort`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ reason: \"no_progress\" }),\n });\n } catch {\n // Best effort — the important part is unwinding the UI.\n }\n settleInterruptedToolCalls(latestContent);\n setReconnectContent([...latestContent]);\n setReconnectFrozen(latestContent.length > 0);\n setRunErrorInfo({\n message:\n \"The previous agent run stopped producing visible progress while reconnecting, so it was stopped before it could keep looping.\",\n errorCode: \"reconnect_no_progress\",\n recoverable: true,\n runId,\n });\n setDismissedRunErrorKey(null);\n reconnectAbortRef.current = null;\n setIsReconnecting(false);\n reconnectRunIdRef.current = null;\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: false, tabId: tabId || threadId },\n }),\n );\n return;\n }\n\n setReconnectFrozen(true);\n let loaded = false;\n for (let attempt = 0; attempt < 10; attempt++) {\n await new Promise((r) => setTimeout(r, 500));\n if (reconnectRunIdRef.current !== runId) break;\n const repo = await refreshThreadFromServer();\n if (repoHasAssistantMessage(repo)) {\n setReconnectContent([]);\n setReconnectFrozen(false);\n loaded = true;\n break;\n }\n }\n\n if (reconnectRunIdRef.current === runId) {\n reconnectAbortRef.current = null;\n setIsReconnecting(false);\n reconnectRunIdRef.current = null;\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: false, tabId: tabId || threadId },\n }),\n );\n }\n if (!loaded) {\n await refreshThreadFromServer();\n }\n };\n\n void streamReconnect();\n return true;\n },\n [apiUrl, refreshThreadFromServer, tabId, threadId, wasRecentlyStoppedRun],\n );\n\n const reconnectActiveRunForThread =\n useCallback(async (): Promise<boolean> => {\n if (!threadId) return false;\n try {\n const runRes = await fetch(\n `${apiUrl}/runs/active?threadId=${encodeURIComponent(threadId)}`,\n );\n if (!runRes.ok) return false;\n const runInfo = (await runRes.json()) as ActiveRunLookup;\n if (\n !runInfo.active ||\n runInfo.status !== \"running\" ||\n activeRunLooksStale(runInfo)\n ) {\n await refreshThreadFromServer();\n return false;\n }\n return startReconnectToRun(runInfo);\n } catch {\n return false;\n }\n }, [apiUrl, refreshThreadFromServer, startReconnectToRun, threadId]);\n\n useEffect(() => {\n if (!threadId || !isNewThread) return;\n // A restored tab can be reclassified as client-only after the thread list\n // loads. Once that happens, there is no server row to restore, so show the\n // empty composer instead of leaving the per-thread restore skeleton up.\n setIsRestoring(false);\n }, [isNewThread, threadId]);\n\n // Restore messages from server on mount (when threadId is set). The\n // server is the single source of truth — we don't hydrate from localStorage\n // first, so what the user sees in the chat panel always matches what the\n // history list (and the agent) sees on disk.\n useEffect(() => {\n if (hasRestoredRef.current) return;\n hasRestoredRef.current = true;\n\n if (loadHistoryRepository) {\n (async () => {\n try {\n const repo = await loadHistoryRepository();\n if (repo) {\n importThreadData(repo, { markTitleGenerated: true });\n }\n titleGeneratedRef.current = true;\n } catch {\n // Start fresh\n } finally {\n setIsRestoring(false);\n }\n })();\n } else if (threadId && isNewThread) {\n // Client-created empty tabs do not have a server row until the first\n // message is sent. Avoid probing /threads/:id on mount; that request\n // can only 404 and makes normal app startup look broken in DevTools.\n setIsRestoring(false);\n } else if (threadId && knownAbsentThreadIds.has(threadId)) {\n // A prior mount already learned this thread has no server row (404).\n // Skip the re-probe so remounts don't re-spam 404s for the same id.\n setIsRestoring(false);\n } else if (threadId) {\n (async () => {\n try {\n const res = await fetch(\n `${apiUrl}/threads/${encodeURIComponent(threadId)}`,\n );\n if (res.ok) {\n const data = await res.json();\n if (data.threadData) {\n const repo = importThreadData(data.threadData, {\n markTitleGenerated: true,\n });\n if (repo) {\n const { title, preview } = extractThreadMeta(repo);\n writeCachedThreadSnapshot(apiUrl, threadId, {\n threadData:\n typeof data.threadData === \"string\"\n ? data.threadData\n : JSON.stringify(data.threadData),\n title: data.title || title,\n preview,\n messageCount: Array.isArray(repo.messages)\n ? repo.messages.length\n : 0,\n });\n }\n }\n // Also skip title generation if thread already has a title\n if (data.title) {\n titleGeneratedRef.current = true;\n }\n } else if (res.status === 404) {\n // No server row for this thread yet — remember it so later remounts\n // skip the probe instead of re-fetching a known 404.\n knownAbsentThreadIds.add(threadId);\n }\n } catch {\n // Start fresh\n } finally {\n // Clear the skeleton as soon as the persisted messages are imported.\n // The active-run reconnect probe below must NOT gate first paint — it\n // only matters when a run is mid-flight (e.g. after a hot reload), and\n // it streams on top of the already-rendered messages.\n setIsRestoring(false);\n }\n // Reconnect to an in-progress run after the skeleton has cleared, so a\n // background `/runs/active` probe never delays showing the conversation.\n try {\n await reconnectActiveRunForThread();\n } catch {\n // No active run to reconnect to.\n }\n })();\n } else {\n // Legacy: restore from sessionStorage\n const storageKey = `${CHAT_STORAGE_PREFIX}${tabId || \"default\"}`;\n try {\n const saved = sessionStorage.getItem(storageKey);\n if (saved) {\n const repo = JSON.parse(saved);\n if (repo?.messages?.length > 0) {\n threadRuntime.import(ensureMessageMetadata(repo));\n }\n }\n } catch {}\n setIsRestoring(false);\n }\n }, [\n threadId,\n tabId,\n apiUrl,\n threadRuntime,\n importThreadData,\n reconnectActiveRunForThread,\n loadHistoryRepository,\n isNewThread,\n ]);\n\n useEffect(() => {\n if (\n !loadHistoryRepository ||\n !hasRestoredRef.current ||\n isRestoring ||\n isRunning\n ) {\n return;\n }\n let cancelled = false;\n void loadHistoryRepository()\n .then((repo) => {\n if (cancelled || !repo) return;\n importThreadData(repo, { markTitleGenerated: true });\n })\n .catch(() => undefined);\n return () => {\n cancelled = true;\n };\n }, [\n historyReloadKey,\n importThreadData,\n isRestoring,\n isRunning,\n loadHistoryRepository,\n ]);\n\n // If assistant-ui stops the local runtime while the background server run is\n // still alive, immediately switch into the same reconnect path used after a\n // reload. Otherwise the composer unlocks, the next send hits a 409, and the\n // user sees \"still working\" even though the UI stopped updating.\n const prevRuntimeRunningForReconnectRef = useRef(isRuntimeRunning);\n useEffect(() => {\n const wasRuntimeRunning = prevRuntimeRunningForReconnectRef.current;\n prevRuntimeRunningForReconnectRef.current = isRuntimeRunning;\n if (\n !wasRuntimeRunning ||\n isRuntimeRunning ||\n !threadId ||\n forceStopped ||\n isReconnecting ||\n wasRecentlyStoppedRun()\n ) {\n return;\n }\n\n let cancelled = false;\n const timer = window.setTimeout(() => {\n if (!cancelled) {\n void reconnectActiveRunForThread();\n }\n }, 250);\n return () => {\n cancelled = true;\n window.clearTimeout(timer);\n };\n }, [\n forceStopped,\n isReconnecting,\n isRuntimeRunning,\n reconnectActiveRunForThread,\n threadId,\n wasRecentlyStoppedRun,\n ]);\n\n // Generate a title when the first user message is sent\n useEffect(() => {\n if (!hasRestoredRef.current) return;\n if (titleGeneratedRef.current) return;\n if (messages.length === 0) return;\n\n const firstUserMsg = messages.find((m) => m.role === \"user\");\n if (!firstUserMsg) return;\n\n // Extract text from the first user message\n const text =\n \"content\" in firstUserMsg\n ? Array.isArray(firstUserMsg.content)\n ? firstUserMsg.content\n .filter((p: any) => p.type === \"text\")\n .map((p: any) => p.text)\n .join(\" \")\n : typeof firstUserMsg.content === \"string\"\n ? firstUserMsg.content\n : \"\"\n : \"\";\n\n if (!text.trim()) return;\n titleGeneratedRef.current = true;\n if (threadId) {\n onGenerateTitleRef.current?.(threadId, text.trim());\n }\n }, [messages, threadId]);\n\n // Periodically save thread data while the agent is running so refreshes\n // don't lose messages. Saves every 5 seconds while running.\n const savedTitleRef = useRef(\"\");\n const lastSaveTimeRef = useRef(0);\n useEffect(() => {\n if (!hasRestoredRef.current) return;\n if (!isRunning) return;\n if (messages.length === 0) return;\n if (!threadId || !onSaveThreadRef.current) return;\n\n const now = Date.now();\n const timeSinceLastSave = now - lastSaveTimeRef.current;\n if (timeSinceLastSave < 5000) return;\n\n const repo = threadRuntime.export();\n const { title, preview } = extractThreadMeta(repo);\n const threadData = JSON.stringify(stripBase64FromRepo(repo));\n const snapshot = {\n threadData,\n title,\n preview,\n messageCount: messages.length,\n };\n\n lastSaveTimeRef.current = now;\n savedTitleRef.current = title;\n writeCachedThreadSnapshot(apiUrl, threadId, snapshot);\n onSaveThreadRef.current(threadId, snapshot);\n }, [apiUrl, messages, isRunning, threadId, threadRuntime]);\n\n // Persist full thread data after each completed response\n useEffect(() => {\n if (!hasRestoredRef.current) return;\n if (isRunning) return;\n if (messages.length === 0) return;\n\n const repo = threadRuntime.export();\n\n if (threadId && onSaveThreadRef.current) {\n // Save to server via the hook callback\n const { title, preview } = extractThreadMeta(repo);\n const threadData = JSON.stringify(stripBase64FromRepo(repo));\n const snapshot = {\n threadData,\n title,\n preview,\n messageCount: messages.length,\n };\n savedTitleRef.current = title;\n writeCachedThreadSnapshot(apiUrl, threadId, snapshot);\n onSaveThreadRef.current(threadId, snapshot);\n } else {\n // Legacy: save to sessionStorage\n const storageKey = `${CHAT_STORAGE_PREFIX}${tabId || \"default\"}`;\n try {\n sessionStorage.setItem(storageKey, JSON.stringify(repo));\n } catch {}\n }\n }, [apiUrl, messages, isRunning, threadId, tabId, threadRuntime]);\n\n useEffect(() => {\n onMessageCountChange?.(messages.length);\n }, [messages.length, onMessageCountChange]);\n\n // Persist queued messages to the server so they survive reloads. Debounced\n // to 300ms so typing-and-queuing-rapidly doesn't hammer the endpoint.\n // Stores them in thread_data.queuedMessages via POST /threads/:id/queued.\n useEffect(() => {\n if (!threadId) return;\n if (!hasRestoredRef.current) return;\n const serialized = JSON.stringify(queuedMessages);\n if (serialized === lastPersistedQueueRef.current) return;\n const queueVersion = queueMutationVersionRef.current;\n const timer = setTimeout(() => {\n (async () => {\n try {\n const res = await fetch(\n `${apiUrl}/threads/${encodeURIComponent(threadId)}/queued`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ queuedMessages }),\n },\n );\n if (res.ok) {\n lastPersistedQueueRef.current = serialized;\n if (queueMutationVersionRef.current === queueVersion) {\n queueDirtyRef.current = false;\n }\n }\n } catch {\n // Best-effort — next queue change will retry.\n }\n })();\n }, 300);\n return () => clearTimeout(timer);\n }, [queuedMessages, threadId, apiUrl]);\n\n // Nudge the shared hook to re-check after a Builder connect.\n const handleBuilderConnected = useCallback(() => {\n window.dispatchEvent(new Event(\"agent-engine:configured-changed\"));\n }, []);\n\n // Listen for auth error events from the adapter\n const checkAuthSession = useCallback(async () => {\n try {\n const res = await fetch(agentNativePath(\"/_agent-native/auth/session\"), {\n cache: \"no-store\",\n });\n if (!res.ok) return false;\n const data = await res.json().catch(() => null);\n const hasSession = !!data && !data.error;\n setAuthSessionAvailable(hasSession);\n if (hasSession) {\n setAuthError(null);\n }\n return hasSession;\n } catch {\n return false;\n }\n }, []);\n\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as\n | {\n reason?: string;\n tabId?: string;\n threadId?: string;\n }\n | undefined;\n const eventTabId =\n typeof detail?.tabId === \"string\" ? detail.tabId : null;\n const eventThreadId =\n typeof detail?.threadId === \"string\" ? detail.threadId : null;\n if (\n (eventTabId || eventThreadId) &&\n eventTabId !== tabId &&\n eventThreadId !== threadId\n ) {\n return;\n }\n setAuthSessionAvailable(false);\n setAuthError({ sessionExpired: detail?.reason === \"session-expired\" });\n void checkAuthSession();\n };\n window.addEventListener(\"agent-chat:auth-error\", handler);\n return () => window.removeEventListener(\"agent-chat:auth-error\", handler);\n }, [checkAuthSession, tabId, threadId]);\n\n useEffect(() => {\n if (!authError) return;\n // Auto-recovery (`checkAuthSession`) runs immediately + at 250ms. If the\n // card is still showing 3 seconds later, recovery failed and the user\n // is about to hit \"Refresh chat\" — that's the \"Reload UI required\"\n // symptom we want signal on.\n const stuckCapture = window.setTimeout(() => {\n captureError(new Error(\"agent-chat:auth_error_card_stuck\"), {\n tags: {\n context: \"agent-native-chat\",\n errorCode: \"auth_error_card\",\n sessionAvailable: String(authSessionAvailable),\n sessionExpired: String(!!authError.sessionExpired),\n },\n extra: {\n threadId: threadId ?? null,\n tabId: tabId ?? null,\n },\n });\n }, 3000);\n const handler = () => void checkAuthSession();\n const timer = window.setTimeout(handler, 250);\n window.addEventListener(\"focus\", handler);\n window.addEventListener(\"agent-engine:configured-changed\", handler);\n return () => {\n window.clearTimeout(stuckCapture);\n window.clearTimeout(timer);\n window.removeEventListener(\"focus\", handler);\n window.removeEventListener(\"agent-engine:configured-changed\", handler);\n };\n }, [authError, authSessionAvailable, checkAuthSession, tabId, threadId]);\n\n // Listen for loop-limit events from the adapter\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail;\n if (!tabId || detail?.tabId === tabId) {\n setLoopLimitInfo({\n ...(typeof detail?.maxIterations === \"number\"\n ? { maxIterations: detail.maxIterations }\n : {}),\n });\n setShowContinue(true);\n }\n };\n window.addEventListener(\"agent-chat:loop-limit\", handler);\n return () => window.removeEventListener(\"agent-chat:loop-limit\", handler);\n }, [tabId]);\n\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as RunErrorInfo & {\n tabId?: string;\n };\n if (tabId && detail?.tabId && detail.tabId !== tabId) return;\n if (!detail?.message) return;\n const stopped = userStoppedRunRef.current;\n if (\n stopped &&\n Date.now() - stopped.at < 10_000 &&\n (!stopped.runId || !detail.runId || stopped.runId === detail.runId)\n ) {\n return;\n }\n setRunErrorInfo({\n message: detail.message,\n ...(detail.details ? { details: detail.details } : {}),\n ...(detail.errorCode ? { errorCode: detail.errorCode } : {}),\n ...(detail.runId ? { runId: detail.runId } : {}),\n ...(detail.recoverable ? { recoverable: detail.recoverable } : {}),\n });\n setDismissedRunErrorKey(null);\n };\n window.addEventListener(\"agent-chat:run-error\", handler);\n return () => window.removeEventListener(\"agent-chat:run-error\", handler);\n }, [tabId]);\n\n // Real activity means the next chunk has started — leave the auto-resume\n // (\"Resuming\") state so the indicator settles back to \"Thinking\". The\n // activity label itself is intentionally not surfaced: the running\n // indicator stays a steady \"Thinking\" rather than flipping through\n // transient step labels.\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as {\n label?: string;\n tool?: string;\n tabId?: string;\n };\n if (tabId && detail?.tabId && detail.tabId !== tabId) return;\n if (typeof detail?.label === \"string\" && detail.label.trim()) {\n setIsAutoResuming(false);\n }\n };\n window.addEventListener(\"agent-chat:activity\", handler);\n return () => window.removeEventListener(\"agent-chat:activity\", handler);\n }, [tabId]);\n\n // Show \"Resuming…\" during the adapter's auto-continuation window (the\n // ~250ms gap between the end of one serverless chunk and the POST for the\n // next). The adapter dispatches `agent-chat:auto-continue` at that moment.\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as { tabId?: string };\n if (tabId && detail?.tabId && detail.tabId !== tabId) return;\n setIsAutoResuming(true);\n };\n window.addEventListener(\"agent-chat:auto-continue\", handler);\n return () =>\n window.removeEventListener(\"agent-chat:auto-continue\", handler);\n }, [tabId]);\n\n // Clear auto-resume state when the run stops.\n useEffect(() => {\n if (!isRunning) {\n setIsAutoResuming(false);\n }\n }, [isRunning]);\n\n // Auto-dequeue: when the agent is idle, send the next queued message. This\n // intentionally does not depend on observing the running -> idle transition:\n // restored queues can exist after a reload where this component never saw the\n // previous run as active.\n useEffect(() => {\n if (isRestoring || isRunning || queuedMessages.length === 0) {\n return;\n }\n if (dequeueInFlightRef.current) return;\n\n const next = queuedMessages[0];\n if (!next) return;\n\n dequeueInFlightRef.current = true;\n let cancelled = false;\n let started = false;\n const timer = window.setTimeout(() => {\n started = true;\n void (async () => {\n let removedForAppend = false;\n let appended = false;\n try {\n // In serverless/cross-isolate deployments the client can receive the\n // terminal SSE event a beat before SQL has marked the previous run\n // complete. Starting the queued turn during that window can reconnect\n // to the old run and replay the old answer under the new prompt.\n await waitForThreadRunToClear(apiUrl, threadId);\n if (cancelled) return;\n\n if (queuedMessagesRef.current[0]?.id !== next.id) {\n return;\n }\n\n // Keep the placeholder visible while waiting. Remove it only when the\n // append is about to begin, so queue stalls don't look like the chat\n // silently ate the next message.\n applyLocalQueuedMessages((prev) =>\n prev.filter((message) => message.id !== next.id),\n );\n removedForAppend = true;\n\n const imageAttachments = createAgentImageAttachments(next.images);\n const messageAttachments =\n next.attachments && next.attachments.length > 0\n ? next.attachments\n : (imageAttachments ?? []);\n threadRuntime.append({\n role: \"user\",\n content: [{ type: \"text\", text: next.text }],\n ...(messageAttachments.length > 0\n ? { attachments: messageAttachments }\n : {}),\n ...createUserMessageRunConfig(\n next.references,\n next.requestMode,\n next.recoveryAction,\n next.trackInRunsTray,\n ),\n } as Parameters<typeof threadRuntime.append>[0]);\n appended = true;\n } catch (err) {\n if (\n removedForAppend &&\n !queuedMessagesRef.current.some((message) => message.id === next.id)\n ) {\n applyLocalQueuedMessages((prev) => [next, ...prev]);\n }\n captureError(err, {\n tags: {\n source: \"agent-chat-client\",\n phase: \"dequeue-message\",\n },\n extra: {\n threadId: threadId ?? null,\n queuedMessageId: next.id,\n },\n });\n } finally {\n if (appended) {\n window.setTimeout(() => {\n dequeueInFlightRef.current = false;\n }, 500);\n } else {\n dequeueInFlightRef.current = false;\n }\n }\n })();\n }, 100);\n\n return () => {\n cancelled = true;\n window.clearTimeout(timer);\n if (!started) {\n dequeueInFlightRef.current = false;\n }\n };\n }, [\n apiUrl,\n applyLocalQueuedMessages,\n isRestoring,\n isRunning,\n queuedMessages,\n threadId,\n threadRuntime,\n ]);\n\n // Clear frozen reconnect content + forceStopped only on the false→true\n // transition of isRuntimeRunning (i.e. a NEW run is actually starting).\n // Reacting to \"isRuntimeRunning is currently true\" would clear the\n // nuclear-stop flag immediately after the user clicks stop, since\n // cancellation is async and isRuntimeRunning is still true at that moment.\n const prevIsRuntimeRunningRef = useRef(isRuntimeRunning);\n useEffect(() => {\n const wasRunning = prevIsRuntimeRunningRef.current;\n prevIsRuntimeRunningRef.current = isRuntimeRunning;\n if (isRuntimeRunning && !wasRunning) {\n if (reconnectFrozen) {\n setReconnectFrozen(false);\n setReconnectContent([]);\n }\n if (forceStopped) {\n setForceStopped(false);\n }\n }\n }, [isRuntimeRunning, reconnectFrozen, forceStopped]);\n\n // Same transition guard for isReconnecting: only clear forceStopped on\n // the false→true edge (a new reconnect starting on page load).\n const prevIsReconnectingRef = useRef(isReconnecting);\n useEffect(() => {\n const wasReconnecting = prevIsReconnectingRef.current;\n prevIsReconnectingRef.current = isReconnecting;\n if (isReconnecting && !wasReconnecting && forceStopped) {\n setForceStopped(false);\n }\n }, [isReconnecting, forceStopped]);\n\n const materializeFrozenReconnectContent = useCallback(() => {\n if (!reconnectFrozen || reconnectContent.length === 0) return;\n try {\n const frozenContent = cloneContentParts(reconnectContent);\n settleInterruptedToolCalls(frozenContent);\n const repo = normalizeThreadRepository(threadRuntime.export());\n const messages = getRepoMessages(repo);\n const lastEntry = messages[messages.length - 1];\n const lastMessage = getRepoMessage(lastEntry);\n const parentId =\n typeof repo.headId === \"string\"\n ? repo.headId\n : typeof lastMessage?.id === \"string\"\n ? lastMessage.id\n : null;\n const runId = runErrorInfo?.runId ?? reconnectRunIdRef.current;\n const id = `reconnect-${runId ?? Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n repo.messages = [\n ...messages,\n {\n parentId,\n message: {\n id,\n role: \"assistant\",\n createdAt: new Date(),\n content: frozenContent,\n status: { type: \"complete\", reason: \"stop\" },\n metadata: {\n custom: {\n reconnectFrozen: true,\n ...(runId ? { runId } : {}),\n },\n },\n },\n },\n ];\n repo.headId = id;\n\n threadRuntime.import(ensureMessageMetadata(repo));\n setReconnectFrozen(false);\n setReconnectContent([]);\n } catch (err) {\n captureError(err, {\n tags: {\n source: \"agent-chat-client\",\n phase: \"materialize-reconnect-content\",\n },\n extra: {\n threadId: threadId ?? null,\n tabId: tabId ?? null,\n reconnectParts: reconnectContent.length,\n },\n });\n }\n }, [\n reconnectFrozen,\n reconnectContent,\n runErrorInfo?.runId,\n tabId,\n threadId,\n threadRuntime,\n ]);\n\n // Abort the active server run (identical to what the Stop button does) so\n // an immediate-while-running send can proceed cleanly without a 409 race.\n // Captured in a stable ref so addToQueue can call it without listing\n // all the stop-related state in its own dep array.\n const stopActiveRun = useCallback(() => {\n setForceStopped(true);\n const activeRun = getActiveRun();\n const runIdToAbort = reconnectRunIdRef.current ?? activeRun?.runId;\n userStoppedRunRef.current = {\n at: Date.now(),\n ...(runIdToAbort ? { runId: runIdToAbort } : {}),\n };\n setRunErrorInfo(null);\n setDismissedRunErrorKey(null);\n if (runIdToAbort) {\n fetch(`${apiUrl}/runs/${encodeURIComponent(runIdToAbort)}/abort`, {\n method: \"POST\",\n }).catch(() => {});\n }\n if (isReconnecting) {\n reconnectAbortRef.current?.abort();\n reconnectAbortRef.current = null;\n reconnectRunIdRef.current = null;\n setIsReconnecting(false);\n setReconnectFrozen(reconnectContent.length > 0);\n }\n threadRuntime.cancelRun();\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: false, tabId: tabId || threadId },\n }),\n );\n }\n }, [\n apiUrl,\n isReconnecting,\n reconnectContent.length,\n tabId,\n threadId,\n threadRuntime,\n ]);\n // Keep the ref current so addToQueue can call it without a stale closure.\n stopActiveRunRef.current = stopActiveRun;\n\n const addToQueue = useCallback(\n async (\n text: string,\n images?: string[],\n references?: Reference[],\n attachments?: ReadonlyArray<unknown>,\n requestMode?: AgentRequestMode,\n intent: ComposerSubmitIntent = \"queued\",\n recoveryAction?: AgentRecoveryAction,\n includeComposerContext = false,\n trackInRunsTray = false,\n ) => {\n materializeFrozenReconnectContent();\n setShowContinue(false);\n setLoopLimitInfo(null);\n setRunErrorInfo(null);\n setDismissedRunErrorKey(null);\n setComposerError(null);\n userStoppedRunRef.current = null;\n // Selection context attached via Cmd+I is one-shot — clear it as soon\n // as the user actually sends a message so it can't be re-used.\n clearPendingSelection();\n // Sending a message is an explicit user action — always anchor to the\n // bottom so the new message and any reply land in view, even if the\n // user had scrolled up to read history. The sticky-bottom override\n // exists to stop streaming from yanking the viewport, not to swallow\n // direct sends.\n markNearBottom();\n const submitted = includeComposerContext\n ? buildComposerContextSubmission(text)\n : { text, includesContext: false };\n const submittedText = submitted.text;\n let queuedAttachments: Awaited<\n ReturnType<typeof serializeQueuedAttachments>\n >;\n try {\n queuedAttachments = await serializeQueuedAttachments(attachments);\n } catch (err) {\n const msg =\n err instanceof Error\n ? err.message\n : \"Attachment could not be processed.\";\n setComposerError(msg);\n return;\n }\n const imageAttachments = createAgentImageAttachments(images);\n const allAttachments = [\n ...(queuedAttachments ?? []),\n ...(imageAttachments ?? []),\n ];\n\n // ── Body-size guard (Fix 3) ─────────────────────────────────────\n // Estimate the total serialized attachment payload. If it exceeds the\n // Vercel/Netlify body limit, progressively re-compress images until\n // the payload fits, then reject the largest remaining file if still over.\n let messageAttachments = allAttachments;\n {\n const allDataUrls = allAttachments.flatMap((a) =>\n a.content\n .filter(\n (c): c is { type: \"image\"; image: string } => c.type === \"image\",\n )\n .map((c) => c.image),\n );\n if (\n estimateAttachmentBodyBytes(allDataUrls) > MAX_ESTIMATED_BODY_BYTES\n ) {\n // Re-compress image attachments more aggressively.\n const recompressed: typeof allAttachments = [];\n let stillOver = false;\n for (const att of allAttachments) {\n if (\n att.type === \"image\" &&\n att.content.length === 1 &&\n att.content[0].type === \"image\"\n ) {\n // Find the original File from the queued attachments input.\n const rawAtt = (attachments ?? []).find(\n (r) => (r as any).id === att.id,\n ) as { file?: File } | undefined;\n const rawFile = rawAtt?.file;\n if (rawFile && typeof document !== \"undefined\") {\n try {\n const recompressedUrl = await transcodeImageToDataURL(\n rawFile,\n {\n maxDimension: AGGRESSIVE_MAX_IMAGE_DIMENSION,\n jpegQuality: AGGRESSIVE_JPEG_QUALITY,\n },\n );\n recompressed.push({\n ...att,\n content: [{ type: \"image\", image: recompressedUrl }],\n });\n continue;\n } catch {\n // Could not recompress — keep original and flag overflow\n stillOver = true;\n }\n } else {\n stillOver = true;\n }\n }\n recompressed.push(att);\n }\n // Re-estimate after recompression.\n const recompressedUrls = recompressed.flatMap((a) =>\n a.content\n .filter(\n (c): c is { type: \"image\"; image: string } =>\n c.type === \"image\",\n )\n .map((c) => c.image),\n );\n if (\n stillOver ||\n estimateAttachmentBodyBytes(recompressedUrls) >\n MAX_ESTIMATED_BODY_BYTES\n ) {\n // Find the largest attachment and reject it.\n let largestIdx = -1;\n let largestSize = 0;\n for (let i = 0; i < recompressed.length; i++) {\n const url =\n recompressed[i].content.find(\n (c): c is { type: \"image\"; image: string } =>\n c.type === \"image\",\n )?.image ?? \"\";\n if (url.length > largestSize) {\n largestSize = url.length;\n largestIdx = i;\n }\n }\n if (largestIdx >= 0) {\n const rejected = recompressed[largestIdx];\n setComposerError(\n `\"${rejected.name}\" makes the message too large to send (combined attachments must be under ${Math.round(MAX_ESTIMATED_BODY_BYTES / 1024 / 1024)} MB). Remove it or use a smaller image.`,\n );\n return;\n }\n }\n messageAttachments = recompressed;\n }\n }\n // ── End body-size guard ──────────────────────────────────────────\n // Snapshot the exec mode at enqueue time when the caller didn't\n // pass an explicit override. Without this, a plan-mode message that\n // sits in the queue runs as 'act' if the user flips the global toggle\n // before the queue flushes — turning a read-only message into a write.\n const effectiveRequestMode: AgentRequestMode | undefined =\n requestMode ??\n (execMode === \"plan\"\n ? \"plan\"\n : execMode === \"build\"\n ? \"act\"\n : undefined);\n if (isRunning && intent === \"immediate\") {\n // Explicit interrupt path: abort the active server run, then let the\n // auto-dequeue path append this message once the run is clear. Normal\n // composer sends while running resolve to \"queued\" before reaching here.\n applyLocalQueuedMessages((prev) => [\n ...prev,\n {\n id:\n typeof crypto !== \"undefined\" && crypto.randomUUID\n ? crypto.randomUUID()\n : `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n text: submittedText,\n images,\n attachments:\n messageAttachments.length > 0 ? messageAttachments : undefined,\n references,\n requestMode: effectiveRequestMode,\n recoveryAction,\n trackInRunsTray,\n },\n ]);\n stopActiveRunRef.current();\n } else if (isRunning && intent === \"queued\") {\n applyLocalQueuedMessages((prev) => [\n ...prev,\n {\n id:\n typeof crypto !== \"undefined\" && crypto.randomUUID\n ? crypto.randomUUID()\n : `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n text: submittedText,\n images,\n attachments:\n messageAttachments.length > 0 ? messageAttachments : undefined,\n references,\n requestMode: effectiveRequestMode,\n recoveryAction,\n trackInRunsTray,\n },\n ]);\n } else {\n threadRuntime.append({\n role: \"user\",\n content: [{ type: \"text\", text: submittedText }],\n ...(messageAttachments.length > 0\n ? { attachments: messageAttachments }\n : {}),\n ...createUserMessageRunConfig(\n references,\n effectiveRequestMode,\n recoveryAction,\n trackInRunsTray,\n ),\n } as Parameters<typeof threadRuntime.append>[0]);\n }\n if (submitted.includesContext) {\n updateComposerContextItems(() => []);\n }\n },\n [\n applyLocalQueuedMessages,\n buildComposerContextSubmission,\n execMode,\n isRunning,\n materializeFrozenReconnectContent,\n threadRuntime,\n updateComposerContextItems,\n ],\n );\n\n // Expose imperative handle\n useImperativeHandle(\n ref,\n () => ({\n sendMessage(\n text: string,\n images?: string[],\n options?: AssistantChatSendOptions,\n ) {\n addToQueue(\n text,\n images,\n undefined,\n undefined,\n options?.requestMode,\n \"queued\",\n undefined,\n false,\n options?.trackInRunsTray === true,\n );\n },\n prefillMessage(text: string) {\n tiptapRef.current?.setText(text);\n tiptapRef.current?.focus();\n },\n setComposerContextItem(item: AgentChatContextItem) {\n stageComposerContextItem(item);\n tiptapRef.current?.focus();\n },\n removeComposerContextItem(key: string) {\n removeComposerContextItem(key);\n },\n clearComposerContextItems() {\n updateComposerContextItems(() => []);\n },\n sendRecoveryMessage(\n text: string,\n recoveryAction: AgentRecoveryAction,\n images?: string[],\n ) {\n addToQueue(\n text,\n images,\n undefined,\n undefined,\n undefined,\n \"queued\",\n recoveryAction,\n );\n },\n queueMessage(text: string, images?: string[]) {\n addToQueue(text, images);\n },\n isRunning() {\n return thread.isRunning;\n },\n focusComposer() {\n tiptapRef.current?.focus();\n },\n exportThreadSnapshot() {\n if (messages.length === 0) return null;\n const repo = threadRuntime.export();\n const { title, preview } = extractThreadMeta(repo);\n return {\n threadData: JSON.stringify(repo),\n title,\n preview,\n messageCount: messages.length,\n };\n },\n }),\n [\n addToQueue,\n messages.length,\n stageComposerContextItem,\n thread.isRunning,\n threadRuntime,\n ],\n );\n\n const autoscrollFollowKey = useMemo(\n () =>\n [\n messages.map(messageFollowKey).join(\";\"),\n `q:${queuedMessages.map(queuedMessageFollowKey).join(\"|\")}`,\n `r:${reconnectContentFollowKey(reconnectContent)}`,\n ].join(\";;\"),\n [messages, queuedMessages, reconnectContent],\n );\n\n const {\n scrollRef,\n isNearBottomRef,\n showScrollToBottom,\n markNearBottom,\n scrollToBottom,\n scrollToBottomAfterPaint,\n } = useNearBottomAutoscroll<HTMLDivElement>({\n followKey: autoscrollFollowKey,\n streaming: textStreaming,\n });\n\n const scrollToBottomWhileLayoutSettles = useCallback(() => {\n scrollToBottomAfterPaint();\n const el = scrollRef.current;\n if (!el || typeof ResizeObserver === \"undefined\") return undefined;\n\n let stopped = false;\n const observer = new ResizeObserver(() => {\n if (!stopped && isNearBottomRef.current) scrollToBottom();\n });\n observer.observe(el);\n const timeout = window.setTimeout(() => {\n stopped = true;\n observer.disconnect();\n if (isNearBottomRef.current) scrollToBottom();\n }, 1600);\n\n return () => {\n stopped = true;\n window.clearTimeout(timeout);\n observer.disconnect();\n };\n }, [isNearBottomRef, scrollToBottom, scrollToBottomAfterPaint]);\n\n // Scroll to bottom when a restored thread finishes loading\n const wasRestoringRef = useRef(isRestoring);\n useEffect(() => {\n const wasRestoring = wasRestoringRef.current;\n wasRestoringRef.current = isRestoring;\n if (wasRestoring && !isRestoring) {\n return scrollToBottomWhileLayoutSettles();\n }\n }, [isRestoring, scrollToBottomWhileLayoutSettles]);\n\n useEffect(() => {\n if (!textStreaming && isNearBottomRef.current) {\n scrollToBottomAfterPaint();\n }\n }, [textStreaming, scrollToBottomAfterPaint]);\n\n const { isDevMode: cpDevMode } = useDevMode(apiUrl);\n const checkpointCtx = useMemo(\n () => ({ apiUrl, devMode: cpDevMode, threadId }),\n [apiUrl, cpDevMode, threadId],\n );\n const messageActionsCtx = useMemo(() => ({ onForkChat }), [onForkChat]);\n const lastMessageLoopLimit = useMemo(() => {\n const last = messages[messages.length - 1];\n if (!last || last.role !== \"assistant\") return null;\n return getLoopLimitMetadata(last);\n }, [messages]);\n const lastMessageRunError = useMemo(() => {\n const last = messages[messages.length - 1];\n if (!last || last.role !== \"assistant\") return null;\n return getRunErrorMetadata(last);\n }, [messages]);\n const lastUserText = useMemo(\n () => latestNonRecoveryUserMessageText(messages),\n [messages],\n );\n const latestMessage = messages[messages.length - 1];\n const latestMessageRole = latestMessage?.role;\n const latestAssistantWasPlan =\n latestMessageRole === \"assistant\" &&\n getRequestModeMetadata(latestMessage) === \"plan\";\n const showPlanModeCallout =\n execMode === \"plan\" &&\n !planModeDisabled &&\n !isComposerDisabled &&\n !showRunningInUI;\n const canImplementPlan = showPlanModeCallout && latestAssistantWasPlan;\n const contextXRayEnabled = Boolean(\n threadId &&\n (messages.length > 0 || isReconnecting || reconnectContent.length > 0),\n );\n const handleImplementPlan = useCallback(() => {\n onExecModeChange?.(\"build\");\n void addToQueue(\n \"Implement the plan.\",\n undefined,\n undefined,\n undefined,\n \"act\",\n );\n }, [addToQueue, onExecModeChange]);\n const handleSwitchToAct = useCallback(() => {\n onExecModeChange?.(\"build\");\n }, [onExecModeChange]);\n const visibleLoopLimit = showContinue\n ? (loopLimitInfo ?? lastMessageLoopLimit ?? {})\n : lastMessageLoopLimit;\n const visibleRunError = runErrorInfo ?? lastMessageRunError;\n const visibleRunErrorKey = visibleRunError\n ? `${visibleRunError.runId ?? \"\"}:${visibleRunError.errorCode ?? \"\"}:${visibleRunError.message}`\n : null;\n const shouldShowRunError =\n !!visibleRunError &&\n !showRunningInUI &&\n visibleRunErrorKey !== dismissedRunErrorKey &&\n !(\n userStoppedRunRef.current &&\n Date.now() - userStoppedRunRef.current.at < 10_000 &&\n (!userStoppedRunRef.current.runId ||\n !visibleRunError.runId ||\n userStoppedRunRef.current.runId === visibleRunError.runId)\n );\n const hasActiveChatWork =\n showRunningInUI ||\n isAutoResuming ||\n queuedMessages.length > 0 ||\n reconnectContent.length > 0;\n const isFreshEmptyChat =\n messages.length === 0 &&\n !hasActiveChatWork &&\n !isRestoring &&\n !isReconnecting &&\n !authError;\n const centeredEmptyState = centerComposerWhenEmpty && isFreshEmptyChat;\n const showEmptyState =\n messages.length === 0 && !isReconnecting && !hasActiveChatWork;\n const showComposerSlot =\n Boolean(composerSlot) && (!centerComposerWhenEmpty || centeredEmptyState);\n\n // Clarifying-question surface: the `ask-question` action writes a\n // GuidedQuestionPayload to application_state under \"guided-questions\". The\n // hook polls that key, and on submit/skip composes the answer as a normal\n // user turn (via the shared sendToAgentChat) and clears the persisted key so\n // the question does not reappear.\n const {\n questions: guidedQuestions,\n title: guidedQuestionsTitle,\n description: guidedQuestionsDescription,\n skipLabel: guidedQuestionsSkipLabel,\n submitLabel: guidedQuestionsSubmitLabel,\n handleSubmit: handleGuidedQuestionsSubmit,\n handleSkip: handleGuidedQuestionsSkip,\n } = useGuidedQuestionFlow({\n stateKey: \"guided-questions\",\n queryKey: [\"guided-questions\"],\n ...(browserTabId ? { browserTabId } : {}),\n });\n\n // Human-in-the-loop approvals: when the user approves a paused `needsApproval`\n // tool call, re-issue the turn carrying the call's approval key so the server\n // gate lets that specific call run. Reuses the same append path as recovery /\n // queued messages (no hand-written fetch).\n const approvalCtx = useMemo<ApprovalContextValue>(\n () => ({\n onApprove: (approvalKey: string) => {\n threadRuntime.append({\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: \"Approved. Go ahead and run the requested action.\",\n },\n ],\n ...createUserMessageRunConfig(\n undefined,\n execMode === \"plan\"\n ? \"plan\"\n : execMode === \"build\"\n ? \"act\"\n : undefined,\n undefined,\n undefined,\n [approvalKey],\n ),\n } as Parameters<typeof threadRuntime.append>[0]);\n },\n }),\n [threadRuntime, execMode],\n );\n\n return (\n <CheckpointContext.Provider value={checkpointCtx}>\n <MessageActionsContext.Provider value={messageActionsCtx}>\n <ApprovalContext.Provider value={approvalCtx}>\n <ChatRunningContext.Provider value={isRunning}>\n <TextStreamingContext.Provider value={textStreaming}>\n <div\n data-agent-empty-state={\n centeredEmptyState ? \"centered\" : undefined\n }\n className={cn(\n \"relative flex flex-1 flex-col h-full min-h-0 text-foreground\",\n className,\n )}\n onDragEnter={handleChatDragEnter}\n onDragOver={handleChatDragOver}\n onDragLeave={handleChatDragLeave}\n onDropCapture={handleChatDropCapture}\n onDrop={handleChatDrop}\n >\n {dropActive && (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-md border-2 border-dashed border-primary/70 bg-primary/5 backdrop-blur-[1px]\"\n >\n <span className=\"rounded-md bg-background/90 px-3 py-1.5 text-xs font-medium text-foreground shadow-sm\">\n Drop to attach\n </span>\n </div>\n )}\n {showHeader && (\n <div className=\"flex h-11 shrink-0 items-center justify-between border-b border-border px-4\">\n <span className=\"text-[13px] font-medium text-muted-foreground\">\n Agent\n </span>\n <div className=\"flex items-center gap-1\">\n {onSwitchToCli && (\n <TooltipProvider delayDuration={200}>\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n onClick={onSwitchToCli}\n aria-label=\"Switch to CLI\"\n className=\"flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground px-2 py-1 rounded-md hover:bg-accent\"\n >\n <IconTerminal className=\"h-3.5 w-3.5\" />\n CLI\n </button>\n </TooltipTrigger>\n <TooltipContent>Switch to CLI</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n )}\n </div>\n </div>\n )}\n\n {/* Messages area */}\n <div\n ref={scrollRef}\n className=\"agent-chat-scroll flex-1 overflow-y-auto overflow-x-hidden min-h-0\"\n >\n {authError ? (\n <div className=\"flex flex-col items-center justify-center h-full px-4 gap-3\">\n <div className=\"flex h-10 w-10 items-center justify-center rounded-full bg-muted\">\n {authSessionAvailable ? (\n <IconRefresh className=\"h-5 w-5 text-muted-foreground\" />\n ) : (\n <IconMessage className=\"h-5 w-5 text-muted-foreground\" />\n )}\n </div>\n <div className=\"text-center max-w-[280px]\">\n <p className=\"text-sm font-medium text-foreground mb-1\">\n {authSessionAvailable\n ? \"Chat session needs refresh\"\n : authError.sessionExpired\n ? \"Session expired\"\n : \"Authentication required\"}\n </p>\n <p className=\"text-xs text-muted-foreground leading-relaxed\">\n {authSessionAvailable\n ? \"You're signed in, but this chat connection needs to reconnect.\"\n : authError.sessionExpired\n ? \"Your session may have expired. Log out and log back in to reconnect.\"\n : \"You need to log in to use the agent.\"}\n </p>\n </div>\n <div className=\"flex gap-2\">\n {!authError.sessionExpired && !authSessionAvailable && (\n <button\n onClick={() => {\n const ret =\n window.location.pathname +\n window.location.search;\n window.location.href =\n agentNativePath(\"/_agent-native/sign-in\") +\n `?return=${encodeURIComponent(ret)}`;\n }}\n className=\"text-xs text-background bg-foreground hover:opacity-90 px-3 py-1.5 rounded-md\"\n >\n Log in\n </button>\n )}\n {authError.sessionExpired && !authSessionAvailable && (\n <button\n onClick={async () => {\n try {\n await fetch(\n agentNativePath(\"/_agent-native/auth/logout\"),\n {\n method: \"POST\",\n },\n );\n } catch {}\n window.location.reload();\n }}\n className=\"text-xs text-destructive hover:text-destructive/80 px-3 py-1.5 rounded-md border border-destructive/30 hover:bg-destructive/10\"\n >\n Log out\n </button>\n )}\n <button\n onClick={() => {\n setAuthError(null);\n window.location.reload();\n }}\n className={\n authSessionAvailable\n ? \"text-xs text-background bg-foreground hover:opacity-90 px-3 py-1.5 rounded-md\"\n : \"text-xs text-muted-foreground hover:text-foreground px-3 py-1.5 rounded-md border border-border hover:bg-accent\"\n }\n >\n Refresh chat\n </button>\n </div>\n </div>\n ) : isRestoring ? (\n <div className=\"flex flex-col gap-3 p-4\">\n <div className=\"flex justify-end\">\n <div className=\"h-8 w-32 rounded-lg bg-muted animate-pulse\" />\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <div className=\"h-4 w-48 rounded bg-muted animate-pulse\" />\n <div className=\"h-4 w-64 rounded bg-muted animate-pulse\" />\n <div className=\"h-4 w-40 rounded bg-muted animate-pulse\" />\n </div>\n </div>\n ) : showEmptyState ? (\n <div\n className={cn(\n \"agent-empty-state\",\n emptyStateDisplay === \"hidden\"\n ? \"sr-only\"\n : \"flex h-full flex-col items-center justify-center gap-4 px-4 py-16\",\n )}\n >\n <div className=\"flex h-10 w-10 items-center justify-center rounded-full bg-muted\">\n <IconMessage className=\"h-5 w-5 text-muted-foreground\" />\n </div>\n <p className=\"sr-only\">\n {emptyStateText ?? \"How can I help you?\"}\n </p>\n {emptyStateAddon}\n {resolvedSuggestions && resolvedSuggestions.length > 0 ? (\n <div className=\"flex flex-col gap-1.5 w-full max-w-[280px]\">\n {resolvedSuggestions.map((suggestion) => (\n <button\n key={suggestion}\n onClick={() => {\n threadRuntime.append({\n role: \"user\",\n content: [{ type: \"text\", text: suggestion }],\n });\n }}\n className=\"w-full rounded-lg border border-border px-3 py-2 text-left text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground\"\n >\n {suggestion}\n </button>\n ))}\n </div>\n ) : null}\n </div>\n ) : (\n <div className=\"agent-thread-content flex flex-col gap-4 px-4 py-4\">\n <AssistantMessageListErrorBoundary\n resetKey={messageListResetKey}\n >\n <ThreadPrimitive.Messages\n components={{\n UserMessage,\n AssistantMessage,\n }}\n />\n </AssistantMessageListErrorBoundary>\n {visibleLoopLimit && !showRunningInUI && (\n <LoopLimitContinueCard\n info={visibleLoopLimit}\n onContinue={() => {\n setShowContinue(false);\n setLoopLimitInfo(null);\n addToQueue(\n \"Continue from where you left off.\",\n undefined,\n undefined,\n undefined,\n undefined,\n \"queued\",\n \"continue\",\n );\n }}\n />\n )}\n {shouldShowRunError && visibleRunError && (\n <RunErrorRecoveryCard\n info={visibleRunError}\n onContinue={() => {\n setRunErrorInfo(null);\n addToQueue(\n \"Continue from where you stopped. Use the partial work above, verify what succeeded, and finish the original request. Do not rerun the exact same failed tool input unless the failure was transient or the user explicitly asked for an exact rerun. Prefer dedicated app actions over raw database edits when they exist.\",\n undefined,\n undefined,\n undefined,\n undefined,\n \"queued\",\n \"continue\",\n );\n }}\n onRetry={() => {\n setRunErrorInfo(null);\n addToQueue(\n lastUserText\n ? `Retry the previous request from a clean approach. Do not rerun the exact same failed tool input unless the failure was transient or the user explicitly asked for an exact rerun. If a provider query failed because of schema, syntax, or type mismatch, diagnose the error and adjust the query first.\\n\\nOriginal request:\\n\\n${lastUserText}`\n : \"Retry the previous request from a clean approach. Do not rerun the exact same failed tool input unless the failure was transient or the user explicitly asked for an exact rerun. If a provider query failed because of schema, syntax, or type mismatch, diagnose the error and adjust the query first.\",\n undefined,\n undefined,\n undefined,\n undefined,\n \"queued\",\n \"retry\",\n );\n }}\n onFork={onForkChat}\n onDismiss={() => {\n if (visibleRunErrorKey) {\n setDismissedRunErrorKey(visibleRunErrorKey);\n }\n setRunErrorInfo(null);\n }}\n />\n )}\n {(isReconnecting || reconnectFrozen) &&\n reconnectContent.length > 0 && (\n <ReconnectStreamMessage content={reconnectContent} />\n )}\n {showRunningInUI && (\n <RunningActivityStatus\n label={\n isReconnecting\n ? \"Reconnecting\"\n : isAutoResuming\n ? \"Resuming\"\n : // Keep a steady \"Thinking\" while the model works —\n // never flip through transient activity labels\n // (e.g. \"Contacting model\", \"Preparing X action\").\n \"Thinking\"\n }\n />\n )}\n {queuedMessages.map((msg) => {\n const displayText = msg.text\n .replace(/<context>[\\s\\S]*?<\\/context>\\n?/g, \"\")\n .trim();\n return (\n <div\n key={msg.id}\n className=\"group flex items-start justify-end gap-1.5\"\n >\n <button\n type=\"button\"\n onClick={() =>\n applyLocalQueuedMessages((prev) =>\n prev.filter((m) => m.id !== msg.id),\n )\n }\n aria-label=\"Remove from queue\"\n className=\"mt-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-border bg-background text-muted-foreground opacity-0 shadow-sm transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100\"\n >\n <IconX className=\"h-3 w-3\" />\n </button>\n <div className=\"max-w-[85%] rounded-lg bg-accent/50 px-3 py-2 text-sm leading-relaxed text-foreground/60 whitespace-pre-wrap break-words\">\n {displayText}\n {msg.images && msg.images.length > 0 && (\n <div className=\"flex flex-wrap gap-1.5 mt-1.5\">\n {msg.images.map((img, j) => (\n <img\n key={j}\n src={img}\n alt=\"\"\n className=\"h-12 w-12 rounded object-cover border border-border/50\"\n />\n ))}\n </div>\n )}\n </div>\n </div>\n );\n })}\n </div>\n )}\n </div>\n\n {/* Scroll to bottom button */}\n {showScrollToBottom && (\n <div className=\"shrink-0 flex justify-center -mb-1\">\n <button\n type=\"button\"\n onClick={scrollToBottom}\n className=\"flex h-7 w-7 items-center justify-center rounded-full border border-border bg-background shadow-sm hover:bg-accent\"\n aria-label=\"Scroll to bottom\"\n >\n <IconChevronDown className=\"h-3.5 w-3.5 text-muted-foreground\" />\n </button>\n </div>\n )}\n\n {showComposerSlot ? composerSlot : null}\n {guidedQuestions && guidedQuestions.length > 0 && (\n <div className=\"shrink-0 px-3 pb-2 pt-1\">\n <div className=\"rounded-lg border border-border bg-card/60 shadow-sm\">\n <GuidedQuestionFlow\n questions={guidedQuestions}\n onSubmit={handleGuidedQuestionsSubmit}\n onSkip={handleGuidedQuestionsSkip}\n {...(guidedQuestionsTitle\n ? { title: guidedQuestionsTitle }\n : {})}\n {...(guidedQuestionsDescription\n ? { description: guidedQuestionsDescription }\n : {})}\n {...(guidedQuestionsSkipLabel\n ? { skipLabel: guidedQuestionsSkipLabel }\n : {})}\n {...(guidedQuestionsSubmitLabel\n ? { submitLabel: guidedQuestionsSubmitLabel }\n : {})}\n className=\"h-auto items-stretch justify-stretch bg-transparent\"\n />\n </div>\n </div>\n )}\n {showPlanModeCallout && (\n <PlanModeCallout\n canImplementPlan={canImplementPlan}\n onImplementPlan={handleImplementPlan}\n onSwitchToAct={handleSwitchToAct}\n />\n )}\n <SelectionAttachedPill />\n {/* Inline attachment / body-size error */}\n {composerError && (\n <div\n role=\"alert\"\n className=\"shrink-0 mx-3 mb-1.5 flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive\"\n >\n <IconAlertTriangle className=\"h-3.5 w-3.5 mt-0.5 shrink-0\" />\n <span className=\"flex-1 leading-snug\">{composerError}</span>\n <button\n type=\"button\"\n aria-label=\"Dismiss error\"\n onClick={() => setComposerError(null)}\n className=\"shrink-0 opacity-70 hover:opacity-100\"\n >\n <IconX className=\"h-3 w-3\" />\n </button>\n </div>\n )}\n {/* Input area */}\n <AgentComposerFrame\n layoutVariant={composerLayoutVariant}\n className={cn(\n composerAreaClassName,\n missingApiKey && \"cursor-pointer\",\n isComposerDisabled && \"opacity-70\",\n )}\n onClick={\n missingApiKey\n ? () => setMissingKeyBouncePulse((p) => p + 1)\n : undefined\n }\n >\n <ComposerAttachmentPreviewStrip />\n <TiptapComposer\n focusRef={tiptapRef}\n disabled={isComposerDisabled}\n placeholder={\n missingApiKey\n ? \"Connect AI below to start chatting...\"\n : composerDisabled\n ? (composerDisabledPlaceholder ??\n \"Open Desktop to use this chat.\")\n : isRunning\n ? queuedMessages.length > 0\n ? `${queuedMessages.length} queued — send a follow-up...`\n : \"Send a follow-up...\"\n : composerPlaceholder\n }\n onSubmit={\n isRunning || composerContextItems.length > 0\n ? (text, references, attachments, options) =>\n void addToQueue(\n text,\n undefined,\n references.length > 0 ? references : undefined,\n attachments,\n undefined,\n resolveAssistantChatSubmitIntent({\n isRunning,\n requestedIntent: options?.intent,\n }),\n undefined,\n true,\n )\n : undefined\n }\n onSlashCommand={onSlashCommand}\n execMode={execMode}\n onExecModeChange={onExecModeChange}\n planModeDisabled={planModeDisabled}\n planModeDisabledReason={planModeDisabledReason}\n selectedModel={selectedModel ?? defaultModel}\n selectedEffort={selectedEffort}\n availableModels={availableModels}\n onModelChange={onModelChange}\n onEffortChange={onEffortChange}\n onConnectProvider={onConnectProvider}\n toolbarSlot={composerToolbarSlot}\n contextItems={composerContextItems}\n onRemoveContextItem={removeComposerContextItem}\n plusMenuMode={plusMenuMode}\n layoutVariant={composerLayoutVariant}\n providerConnectStatusEnabled={providerStatusChecksEnabled}\n draftScope={threadId || tabId}\n interceptBuildRequestsForBuilder\n onAttachmentError={setComposerError}\n extraActionButton={\n contextXRayEnabled ||\n composerExtraActionButton ||\n showRunningInUI ? (\n <>\n {contextXRayEnabled && (\n <ContextMeter threadId={threadId} />\n )}\n {composerExtraActionButton}\n {showRunningInUI && (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n onClick={stopActiveRun}\n className=\"shrink-0 flex h-7 w-7 items-center justify-center rounded-md bg-muted text-foreground hover:bg-muted/80\"\n >\n <IconPlayerStop className=\"h-3.5 w-3.5\" />\n </button>\n </TooltipTrigger>\n <TooltipContent>Stop generating</TooltipContent>\n </Tooltip>\n )}\n </>\n ) : undefined\n }\n />\n </AgentComposerFrame>\n {missingApiKey && !authError ? (\n <BuilderSetupCard\n onConnected={handleBuilderConnected}\n bouncePulse={missingKeyBouncePulse}\n />\n ) : null}\n </div>\n </TextStreamingContext.Provider>\n </ChatRunningContext.Provider>\n </ApprovalContext.Provider>\n </MessageActionsContext.Provider>\n </CheckpointContext.Provider>\n );\n});\n\nexport const AssistantChat = forwardRef<\n AssistantChatHandle,\n AssistantChatProps\n>(function AssistantChat(\n {\n apiUrl = agentNativePath(\"/_agent-native/agent-chat\"),\n tabId,\n browserTabId,\n threadId,\n contextScope,\n isActiveComposer,\n ...props\n },\n ref,\n) {\n const modelRef = useRef<string | undefined>(props.selectedModel);\n modelRef.current = props.selectedModel;\n const engineRef = useRef<string | undefined>(props.selectedEngine);\n engineRef.current = props.selectedEngine;\n const effortRef = useRef<ReasoningEffort | undefined>(props.selectedEffort);\n effortRef.current = props.selectedEffort;\n const execModeRef = useRef<\"build\" | \"plan\" | undefined>(props.execMode);\n execModeRef.current = props.execMode;\n const scopeRef = useRef<ChatThreadScope | null | undefined>(contextScope);\n scopeRef.current = contextScope;\n const surface = props.agentChatSurface ?? \"app\";\n const createAdapterRef = useRef(props.createAdapter);\n createAdapterRef.current = props.createAdapter;\n const runtimeRef = useRef(props.runtime);\n runtimeRef.current = props.runtime;\n\n const adapter = useMemo(\n () => {\n const context: AssistantChatAdapterContext = {\n apiUrl,\n tabId,\n threadId,\n modelRef,\n engineRef,\n effortRef,\n execModeRef,\n browserTabId,\n scopeRef,\n surface,\n };\n const createAdapter = createAdapterRef.current;\n if (createAdapter) return createAdapter(context);\n const runtime = runtimeRef.current;\n if (runtime) {\n return createAgentChatRuntimeAdapter(runtime, {\n sessionId: threadId ?? tabId,\n threadId,\n modelRef,\n effortRef,\n });\n }\n return createAgentChatAdapter(context);\n },\n // Adapter factories must be memoized and use refs for changing values.\n // `adapterReloadKey` is an explicit opt-in for embedded hosts whose\n // transport identity can change without changing tab/thread ids.\n [\n apiUrl,\n tabId,\n threadId,\n browserTabId,\n surface,\n props.runtime,\n props.adapterReloadKey,\n ],\n );\n const attachmentAdapter = useMemo(\n () =>\n new CompositeAttachmentAdapter([\n new DownscalingImageAttachmentAdapter(),\n new BinaryDocumentAttachmentAdapter(),\n new TextAttachmentAdapter(),\n ]),\n [],\n );\n const runtime = useLocalRuntime(adapter, {\n adapters: { attachments: attachmentAdapter },\n });\n\n return (\n <AssistantRuntimeProvider runtime={runtime}>\n <TooltipProvider delayDuration={200}>\n <ThreadPrimitive.Root className=\"flex flex-1 flex-col h-full min-h-0 overflow-x-hidden\">\n <AssistantUiStaleIndexErrorBoundary\n resetKey={`${tabId ?? \"\"}:${threadId ?? \"\"}`}\n componentName=\"AssistantChat\"\n >\n <AssistantChatInner\n ref={ref}\n {...props}\n browserTabId={browserTabId}\n contextScope={contextScope}\n isActiveComposer={isActiveComposer}\n apiUrl={apiUrl}\n tabId={tabId}\n threadId={threadId}\n />\n </AssistantUiStaleIndexErrorBoundary>\n </ThreadPrimitive.Root>\n </TooltipProvider>\n </AssistantRuntimeProvider>\n );\n});\n"]}
|
|
1
|
+
{"version":3,"file":"AssistantChat.js","sourceRoot":"","sources":["../../src/client/AssistantChat.tsx"],"names":[],"mappings":";AAAA,OAAc,EACZ,QAAQ,EACR,MAAM,EACN,SAAS,EACT,WAAW,EACX,OAAO,EACP,eAAe,EACf,UAAU,EACV,mBAAmB,GACpB,MAAM,OAAO,CAAC;AACf,OAAO,EACL,wBAAwB,EACxB,eAAe,EACf,gBAAgB,EAChB,SAAS,EACT,MAAM,EACN,WAAW,EACX,kBAAkB,EAClB,eAAe,GAChB,MAAM,qBAAqB,CAAC;AAM7B,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EACL,sBAAsB,GAEvB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,6BAA6B,GAE9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EAC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AC,OAAO,EAAE;QACvC,QAAQ,EAAE,EAAE,WAAW,EAAE,iBAAiB,EAAE;KAC7C,CAAC,CAAC;IAEH,OAAO,CACL,KAAC,wBAAwB,IAAC,OAAO,EAAE,OAAO,YACxC,KAAC,eAAe,IAAC,aAAa,EAAE,GAAG,YACjC,KAAC,eAAe,CAAC,IAAI,IAAC,SAAS,EAAC,uDAAuD,YACrF,KAAC,kCAAkC,IACjC,QAAQ,EAAE,GAAG,KAAK,IAAI,EAAE,IAAI,QAAQ,IAAI,EAAE,EAAE,EAC5C,aAAa,EAAC,eAAe,YAE7B,KAAC,kBAAkB,IACjB,GAAG,EAAE,GAAG,KACJ,KAAK,EACT,YAAY,EAAE,YAAY,EAC1B,YAAY,EAAE,YAAY,EAC1B,gBAAgB,EAAE,gBAAgB,EAClC,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,QAAQ,GAClB,GACiC,GAChB,GACP,GACO,CAC5B,CAAC;AACJ,CAAC,CAAC,CAAC","sourcesContent":["import React, {\n useState,\n useRef,\n useEffect,\n useCallback,\n useMemo,\n useLayoutEffect,\n forwardRef,\n useImperativeHandle,\n} from \"react\";\nimport {\n AssistantRuntimeProvider,\n useLocalRuntime,\n useThreadRuntime,\n useThread,\n useAui,\n useComposer,\n useComposerRuntime,\n ThreadPrimitive,\n} from \"@assistant-ui/react\";\nimport type {\n Attachment,\n ChatModelAdapter,\n ExportedMessageRepository,\n} from \"@assistant-ui/react\";\nimport { CompositeAttachmentAdapter } from \"@assistant-ui/react\";\nimport {\n createAgentChatAdapter,\n type AgentChatSurfaceKind,\n} from \"./agent-chat-adapter.js\";\nimport {\n createAgentChatRuntimeAdapter,\n type AgentChatRuntime,\n} from \"./chat/runtime.js\";\nimport {\n appendAgentChatContextToMessage,\n formatAgentChatContextItemsForPrompt,\n normalizeAgentChatContextItem,\n publishAgentChatContextItems,\n refreshAgentChatContext,\n type AgentChatContextItem,\n} from \"./agent-chat.js\";\nimport {\n useAgentDynamicSuggestionsResult,\n type AgentDynamicSuggestionsOption,\n} from \"./dynamic-suggestions.js\";\nimport type { ReasoningEffort } from \"../shared/reasoning-effort.js\";\nimport type {\n ChatThreadScope,\n ChatThreadSnapshot,\n} from \"./use-chat-threads.js\";\nimport { useAgentEngineConfigured } from \"./use-agent-engine-configured.js\";\nimport { getActiveRun } from \"./active-run-state.js\";\nimport {\n AgentAutoContinueSignal,\n type ContentPart,\n readSSEStreamRaw,\n settleInterruptedToolCalls,\n} from \"./sse-event-processor.js\";\nimport { captureError } from \"./analytics.js\";\nimport {\n AssistantMessageListErrorBoundary,\n AssistantUiStaleIndexErrorBoundary,\n} from \"./assistant-ui-recovery.js\";\nimport { cn } from \"./utils.js\";\nimport { useNearBottomAutoscroll } from \"./conversation/index.js\";\nimport { TextAttachmentAdapter } from \"./composer/attachment-accept.js\";\nimport {\n Tooltip,\n TooltipContent,\n TooltipProvider,\n TooltipTrigger,\n} from \"./components/ui/tooltip.js\";\nimport { AGENT_CHAT_VIEW_TRANSITION_PREPARE_EVENT } from \"./chat-view-transition.js\";\nimport {\n GuidedQuestionFlow,\n useGuidedQuestionFlow,\n} from \"./guided-questions.js\";\nimport { useDevMode } from \"./use-dev-mode.js\";\nimport { agentNativePath } from \"./api-path.js\";\nimport {\n TiptapComposer,\n type ComposerSubmitIntent,\n type TiptapComposerHandle,\n} from \"./composer/TiptapComposer.js\";\nimport { AgentComposerFrame } from \"./composer/AgentComposerFrame.js\";\nimport type {\n AgentComposerLayoutVariant,\n Reference,\n} from \"./composer/types.js\";\nimport { isPastedTextAttachmentName } from \"./composer/pasted-text.js\";\nimport { PastedTextChip } from \"./composer/PastedTextChip.js\";\nimport { ContextMeter } from \"./context-xray/ContextMeter.js\";\nimport {\n IconMessage,\n IconX,\n IconPlayerStop,\n IconChevronDown,\n IconTerminal,\n IconAlertTriangle,\n IconRefresh,\n} from \"@tabler/icons-react\";\n// ─── chat/ module imports ─────────────────────────────────────────────────────\nimport {\n DownscalingImageAttachmentAdapter,\n BinaryDocumentAttachmentAdapter,\n MAX_ESTIMATED_BODY_BYTES,\n AGGRESSIVE_MAX_IMAGE_DIMENSION,\n AGGRESSIVE_JPEG_QUALITY,\n transcodeImageToDataURL,\n createAgentImageAttachments,\n serializeQueuedAttachments,\n estimateAttachmentBodyBytes,\n type QueuedAttachment,\n} from \"./chat/attachment-adapters.js\";\nimport { TextStreamingContext } from \"./chat/markdown-renderer.js\";\nimport {\n ChatRunningContext,\n ApprovalContext,\n type ApprovalContextValue,\n ReconnectStreamMessage,\n} from \"./chat/tool-call-display.js\";\nimport {\n CheckpointContext,\n MessageActionsContext,\n UserMessage,\n AssistantMessage,\n SelectionAttachedPill,\n RunningActivityStatus,\n} from \"./chat/message-components.js\";\nimport {\n BuilderSetupCard,\n LoopLimitContinueCard,\n RunErrorRecoveryCard,\n PlanModeCallout,\n getLoopLimitMetadata,\n getRunErrorMetadata,\n getRequestModeMetadata,\n type LoopLimitInfo,\n type RunErrorInfo,\n} from \"./chat/run-recovery.js\";\nimport {\n repoHasAssistantMessage,\n getRepoMessages,\n getRepoMessage,\n shouldImportServerThreadData,\n} from \"./chat/repo-helpers.js\";\n\nexport {\n AssistantMessageListErrorBoundary,\n AssistantUiStaleIndexErrorBoundary,\n assistantUiRecoverableRenderErrorKind,\n isAssistantUiRecoverableRenderError,\n isAssistantUiStaleIndexError,\n} from \"./assistant-ui-recovery.js\";\n\nexport { displayableUserMessageText } from \"./chat/message-components.js\";\n\nconst useBrowserLayoutEffect =\n typeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nexport type AgentRequestMode = \"act\" | \"plan\";\nexport type AgentRecoveryAction = \"continue\" | \"retry\";\nexport interface AssistantChatSendOptions {\n trackInRunsTray?: boolean;\n requestMode?: AgentRequestMode;\n}\n\nfunction createUserMessageRunConfig(\n references?: Reference[],\n requestMode?: AgentRequestMode,\n recoveryAction?: AgentRecoveryAction,\n trackInRunsTray?: boolean,\n approvedToolCalls?: string[],\n queuedMessageId?: string,\n) {\n const custom: {\n references?: Reference[];\n requestMode?: AgentRequestMode;\n trackInRunsTray?: boolean;\n agentNativeQueuedMessageId?: string;\n approvedToolCalls?: string[];\n } = {};\n if (references && references.length > 0) {\n custom.references = references;\n }\n if (requestMode) {\n custom.requestMode = requestMode;\n }\n if (trackInRunsTray) {\n custom.trackInRunsTray = true;\n }\n if (queuedMessageId) {\n custom.agentNativeQueuedMessageId = queuedMessageId;\n }\n if (approvedToolCalls && approvedToolCalls.length > 0) {\n custom.approvedToolCalls = approvedToolCalls;\n }\n const options: {\n runConfig?: { custom: typeof custom };\n metadata?: { custom: { agentNativeRecoveryAction: AgentRecoveryAction } };\n } = {};\n if (Object.keys(custom).length > 0) {\n options.runConfig = { custom };\n }\n if (recoveryAction) {\n options.metadata = {\n custom: { agentNativeRecoveryAction: recoveryAction },\n };\n }\n return options;\n}\n\nconst PENDING_SELECTION_KEY = \"pending-selection-context\";\nconst ACTIVE_RUN_CLEAR_TIMEOUT_MS = 5_000;\nconst ACTIVE_RUN_POLL_INTERVAL_MS = 150;\n\ntype ActiveRunLookup = {\n active?: boolean;\n runId?: string;\n threadId?: string;\n status?: string;\n heartbeatAt?: number | null;\n};\n\nfunction activeRunLooksStale(runInfo: ActiveRunLookup): boolean {\n const heartbeatAt =\n typeof runInfo.heartbeatAt === \"number\" ? runInfo.heartbeatAt : null;\n return (\n runInfo.status === \"running\" &&\n heartbeatAt != null &&\n Date.now() - heartbeatAt > 5000\n );\n}\n\nfunction cloneContentParts(content: ContentPart[]): ContentPart[] {\n return content.map((part) =>\n part.type === \"text\"\n ? { ...part }\n : {\n ...part,\n args: { ...part.args },\n ...(part.mcpApp ? { mcpApp: { ...part.mcpApp } } : {}),\n ...(part.chatUI ? { chatUI: { ...part.chatUI } } : {}),\n },\n );\n}\n\nfunction clearPendingSelection() {\n fetch(\n agentNativePath(\n `/_agent-native/application-state/${PENDING_SELECTION_KEY}`,\n ),\n {\n method: \"DELETE\",\n keepalive: true,\n headers: { \"X-Agent-Native-CSRF\": \"1\" },\n },\n ).catch(() => {});\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(new CustomEvent(\"agent-panel:selection-cleared\"));\n }\n}\n\n// Thread ids the server has already told us don't exist (a prior mount's\n// /threads/:id probe returned 404). Module-scoped so it survives remounts:\n// re-probing a known-absent thread on every navigation just re-spams DevTools\n// with 404s for a thread that has no server row yet (e.g. a freshly created,\n// not-yet-sent chat). Reset on a full page reload.\nconst knownAbsentThreadIds = new Set<string>();\n\nasync function waitForThreadRunToClear(apiUrl: string, threadId?: string) {\n if (!threadId) return;\n const deadline = Date.now() + ACTIVE_RUN_CLEAR_TIMEOUT_MS;\n\n while (Date.now() < deadline) {\n try {\n const res = await fetch(\n `${apiUrl}/runs/active?threadId=${encodeURIComponent(threadId)}`,\n );\n if (res.ok) {\n const info = await res.json();\n const heartbeatAt =\n typeof info?.heartbeatAt === \"number\" ? info.heartbeatAt : null;\n const stale =\n info?.status === \"running\" &&\n heartbeatAt != null &&\n Date.now() - heartbeatAt > 5000;\n if (!info?.active || info?.status !== \"running\" || stale) return;\n }\n } catch {\n // Transient poll failure — try again until the short grace period ends.\n }\n\n await new Promise((resolve) =>\n window.setTimeout(resolve, ACTIVE_RUN_POLL_INTERVAL_MS),\n );\n }\n}\n\n// ─── Composer Attachment Preview ─────────────────────────────────────────────\n\nfunction getImageAttachmentSrc(attachment: Attachment): string | null {\n if (attachment.type !== \"image\") return null;\n\n // Prefer the hosted URL when the server already uploaded this attachment.\n const uploadUrl = (attachment as any).metadata?.uploadUrl as\n | string\n | undefined;\n if (uploadUrl) return uploadUrl;\n\n if (\"file\" in attachment && attachment.file) {\n return URL.createObjectURL(attachment.file);\n }\n\n const imagePart = attachment.content?.find((part) => part.type === \"image\");\n return imagePart && \"image\" in imagePart ? imagePart.image : null;\n}\n\nfunction ComposerAttachmentPreviewCard({\n attachment,\n onRemove,\n}: {\n attachment: Attachment;\n onRemove: (id: string) => void;\n}) {\n const [imageSrc, setImageSrc] = useState<string | null>(null);\n\n useEffect(() => {\n const nextSrc = getImageAttachmentSrc(attachment);\n setImageSrc(nextSrc);\n\n return () => {\n if (nextSrc?.startsWith(\"blob:\")) {\n URL.revokeObjectURL(nextSrc);\n }\n };\n }, [attachment]);\n\n if (isPastedTextAttachmentName(attachment.name)) {\n return <PastedTextChip attachment={attachment} onRemove={onRemove} />;\n }\n\n const isImage = !!imageSrc;\n\n return (\n <div\n className={cn(\n \"group relative overflow-hidden border border-border/70 bg-muted/50 text-foreground\",\n isImage\n ? \"h-20 w-20 rounded-xl shadow-[0_12px_30px_-18px_rgba(0,0,0,0.7)]\"\n : \"inline-flex max-w-[220px] items-center gap-2 rounded-lg px-2.5 py-2 text-xs\",\n )}\n >\n {isImage ? (\n <>\n <img\n src={imageSrc}\n alt={attachment.name}\n className=\"h-full w-full object-cover\"\n />\n <div className=\"pointer-events-none absolute inset-x-0 bottom-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent px-2 py-1.5\">\n <div className=\"truncate text-[10px] font-medium text-white/95\">\n {attachment.name}\n </div>\n </div>\n </>\n ) : (\n <>\n <div className=\"flex h-8 w-8 shrink-0 items-center justify-center rounded-md bg-background text-[10px] font-semibold uppercase tracking-[0.12em] text-muted-foreground\">\n {attachment.name.split(\".\").pop() || \"file\"}\n </div>\n <div className=\"min-w-0\">\n <div className=\"truncate font-medium\">{attachment.name}</div>\n <div className=\"text-[11px] text-muted-foreground\">\n {attachment.contentType || attachment.type}\n </div>\n </div>\n </>\n )}\n <button\n type=\"button\"\n onClick={() => onRemove(attachment.id)}\n className={cn(\n \"absolute flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-background/95 text-muted-foreground shadow-sm transition hover:text-foreground\",\n isImage\n ? \"right-1.5 top-1.5 opacity-100 md:opacity-0 md:group-hover:opacity-100\"\n : \"right-1.5 top-1.5\",\n )}\n aria-label={`Remove ${attachment.name}`}\n >\n <IconX className=\"h-3 w-3\" />\n </button>\n </div>\n );\n}\n\nfunction ComposerAttachmentPreviewStrip() {\n const attachments = useComposer((state) => state.attachments);\n const aui = useAui();\n\n const handleRemove = useCallback(\n (id: string) => {\n void aui.composer().attachment({ id }).remove();\n },\n [aui],\n );\n\n if (attachments.length === 0) return null;\n\n return (\n <div className=\"flex flex-wrap gap-2 px-2 pt-2\">\n {attachments.map((attachment) => (\n <ComposerAttachmentPreviewCard\n key={attachment.id}\n attachment={attachment}\n onRemove={handleRemove}\n />\n ))}\n </div>\n );\n}\n\nfunction getMessageText(message: unknown): string {\n const msg = (message as { message?: unknown })?.message ?? message;\n const content = (msg as { content?: unknown })?.content;\n if (Array.isArray(content)) {\n return content\n .filter((p: any) => p?.type === \"text\" && typeof p.text === \"string\")\n .map((p: any) => p.text)\n .join(\"\\n\")\n .trim();\n }\n return typeof content === \"string\" ? content.trim() : \"\";\n}\n\nfunction contentPartFollowKey(part: any): string {\n const type = typeof part?.type === \"string\" ? part.type : \"unknown\";\n if (type === \"text\") return `t:${String(part.text ?? \"\").length}`;\n if (type === \"tool-call\") {\n return [\n \"tool\",\n part.toolCallId ?? \"\",\n part.toolName ?? \"\",\n part.status?.type ?? \"\",\n String(part.argsText ?? \"\").length,\n String(part.result ?? \"\").length,\n part.mcpApp ? 1 : 0,\n part.chatUI?.renderer ?? \"\",\n ].join(\":\");\n }\n if (type === \"image\") return `image:${String(part.image ?? \"\").length}`;\n return `${type}:${String(part.text ?? part.result ?? \"\").length}`;\n}\n\nfunction contentFollowKey(content: unknown): string {\n if (typeof content === \"string\") return `t:${content.length}`;\n if (Array.isArray(content))\n return content.map(contentPartFollowKey).join(\"|\");\n return \"\";\n}\n\nfunction messageFollowKey(message: unknown): string {\n const msg = ((message as { message?: unknown })?.message ?? message) as {\n id?: unknown;\n role?: unknown;\n status?: { type?: unknown; reason?: unknown };\n content?: unknown;\n };\n return [\n String(msg?.id ?? \"\"),\n String(msg?.role ?? \"\"),\n String(msg?.status?.type ?? \"\"),\n String(msg?.status?.reason ?? \"\"),\n contentFollowKey(msg?.content),\n ].join(\",\");\n}\n\nfunction queuedMessageFollowKey(message: {\n id: string;\n text: string;\n images?: string[];\n attachments?: QueuedAttachment[];\n references?: Reference[];\n requestMode?: AgentRequestMode;\n recoveryAction?: AgentRecoveryAction;\n}): string {\n return [\n message.id,\n message.text.length,\n message.images?.length ?? 0,\n message.attachments?.length ?? 0,\n message.references?.length ?? 0,\n message.requestMode ?? \"\",\n message.recoveryAction ?? \"\",\n ].join(\":\");\n}\n\nfunction reconnectContentFollowKey(content: ContentPart[]): string {\n return content.map(contentPartFollowKey).join(\"|\");\n}\n\nconst RECOVERY_USER_MESSAGE_PREFIXES = [\n \"Continue from where you left off\",\n \"Continue from where you stopped\",\n \"Retry the previous request from a clean approach\",\n];\n\nfunction getRecoveryActionMetadata(\n message: unknown,\n): AgentRecoveryAction | null {\n const meta = (message as { metadata?: unknown })?.metadata as\n | { custom?: { agentNativeRecoveryAction?: unknown } }\n | undefined;\n const action = meta?.custom?.agentNativeRecoveryAction;\n return action === \"continue\" || action === \"retry\" ? action : null;\n}\n\nfunction isRecoveryUserMessage(message: unknown): boolean {\n if (getRecoveryActionMetadata(message)) return true;\n const text = getMessageText(message);\n return RECOVERY_USER_MESSAGE_PREFIXES.some((prefix) =>\n text.startsWith(prefix),\n );\n}\n\nexport function latestNonRecoveryUserMessageText(\n messages: readonly unknown[],\n): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i] as { role?: unknown };\n if (message?.role !== \"user\") continue;\n if (isRecoveryUserMessage(message)) continue;\n const text = getMessageText(message);\n if (text) return text;\n }\n return \"\";\n}\n\nexport function resolveAssistantChatSubmitIntent({\n isRunning,\n requestedIntent,\n}: {\n isRunning: boolean;\n requestedIntent?: ComposerSubmitIntent;\n}): ComposerSubmitIntent {\n if (isRunning) return \"queued\";\n return requestedIntent ?? \"immediate\";\n}\n\ntype QueuedMessage = {\n id: string;\n text: string;\n images?: string[];\n attachments?: QueuedAttachment[];\n references?: Reference[];\n requestMode?: AgentRequestMode;\n recoveryAction?: AgentRecoveryAction;\n trackInRunsTray?: boolean;\n};\n\n// ─── Main Component ─────────────────────────────────────────────────────────\n\nexport interface AssistantChatHandle {\n /** Programmatically send a message into this chat */\n sendMessage(\n text: string,\n images?: string[],\n options?: AssistantChatSendOptions,\n ): void;\n /** Programmatically prefill the composer without submitting. */\n prefillMessage(text: string): void;\n /** Add or replace keyed context for the next composer submission. */\n setComposerContextItem(item: AgentChatContextItem): void;\n /** Remove a keyed context item from the composer. */\n removeComposerContextItem(key: string): void;\n /** Clear all staged context items from the composer. */\n clearComposerContextItems(): void;\n /** Programmatically send a recovery prompt without replacing the original request. */\n sendRecoveryMessage(\n text: string,\n recoveryAction: AgentRecoveryAction,\n images?: string[],\n ): void;\n /** Queue a message to send after the current run finishes */\n queueMessage(text: string, images?: string[]): void;\n /** Whether the chat is currently running */\n isRunning(): boolean;\n /** Focus the composer input */\n focusComposer(): void;\n /** Export the currently visible client-side thread for operations like fork. */\n exportThreadSnapshot(): ChatThreadSnapshot | null;\n}\n\nexport interface AssistantChatAdapterContext {\n apiUrl: string;\n tabId?: string;\n threadId?: string;\n modelRef: { current: string | undefined };\n engineRef: { current: string | undefined };\n effortRef: { current: ReasoningEffort | undefined };\n execModeRef: { current: \"build\" | \"plan\" | undefined };\n browserTabId?: string;\n scopeRef: { current: ChatThreadScope | null | undefined };\n surface: AgentChatSurfaceKind;\n}\n\nexport interface AssistantChatProps {\n /** API endpoint URL. Default: \"/_agent-native/agent-chat\" */\n apiUrl?: string;\n /** Stable tab identifier passed to the adapter for event correlation */\n tabId?: string;\n /** Stable browser tab id used for tab-scoped app-state context. */\n browserTabId?: string;\n /** Thread ID for SQL-backed persistence. When set, messages are loaded from and saved to the server. */\n threadId?: string;\n /** Resource scope to include with chat requests for server-side context. */\n contextScope?: ChatThreadScope | null;\n /** Whether this chat owns the active visible composer context snapshot. */\n isActiveComposer?: boolean;\n /**\n * Identifies which surface hosts this chat. Defaults to \"app\", which keeps\n * dev filesystem/bash code-editing tools out of in-product sidebars.\n */\n agentChatSurface?: AgentChatSurfaceKind;\n /** Placeholder text for empty state */\n emptyStateText?: string;\n /** Suggestion prompts shown when no messages */\n suggestions?: string[];\n /** Context-aware suggestions merged with `suggestions`. Enabled by default. */\n dynamicSuggestions?: AgentDynamicSuggestionsOption;\n /** Optional content rendered in the empty state, above the suggestion buttons.\n * Used by MultiTabAssistantChat to surface \"previous chats for this design\"\n * when the current thread is empty but the scope has other threads. */\n emptyStateAddon?: React.ReactNode;\n /** Whether to show the header bar. Default: true */\n showHeader?: boolean;\n /** CSS class for the outer container */\n className?: string;\n /** Callback when user clicks \"Use CLI\" button */\n onSwitchToCli?: () => void;\n /** Callback when message count changes */\n onMessageCountChange?: (count: number) => void;\n /** Callback to save thread data to the server (provided by useChatThreads) */\n onSaveThread?: (\n threadId: string,\n data: {\n threadData: string;\n title: string;\n preview: string;\n messageCount: number;\n },\n ) => void;\n /** Callback to generate a title from the first user message */\n onGenerateTitle?: (threadId: string, message: string) => void;\n /** Optional content rendered just above the composer input */\n composerSlot?: React.ReactNode;\n /** Class applied to the shared composer area for host-specific sizing/skin. */\n composerAreaClassName?: string;\n /** Placeholder for the shared composer in its normal idle state. */\n composerPlaceholder?: string;\n /** Visual density for the shared composer shell. */\n composerLayoutVariant?: AgentComposerLayoutVariant;\n /** Center the composer on a fresh empty chat instead of pinning it low. */\n centerComposerWhenEmpty?: boolean;\n /** Hide the default empty-state icon/text/suggestions for custom start screens. */\n emptyStateDisplay?: \"default\" | \"hidden\";\n /** Optional content rendered inside the composer toolbar after the attach button. */\n composerToolbarSlot?: React.ReactNode;\n /** Optional action rendered beside the voice/send controls. */\n composerExtraActionButton?: React.ReactNode;\n /** Disable the composer for capability-gated surfaces while still showing history. */\n composerDisabled?: boolean;\n /** Placeholder to show while the composer is disabled by the host surface. */\n composerDisabledPlaceholder?: string;\n /** When true, skip the restore skeleton (used for freshly created threads with no messages) */\n isNewThread?: boolean;\n /** Called when a slash command (e.g. /clear, /help) is executed */\n onSlashCommand?: (command: string) => void;\n /** Current execution mode (build/plan) */\n execMode?: \"build\" | \"plan\";\n /** Callback to change execution mode */\n onExecModeChange?: (mode: \"build\" | \"plan\") => void;\n /** Disable Plan mode while leaving Act mode available. */\n planModeDisabled?: boolean;\n /** Explanation shown next to the disabled Plan option. */\n planModeDisabledReason?: string;\n /** Selected model override for this conversation (undefined = use server default) */\n selectedModel?: string;\n /** Default model from server config (shown in picker when no override is set) */\n defaultModel?: string;\n /** Selected engine override for this conversation */\n selectedEngine?: string;\n /** Selected reasoning effort override for this conversation */\n selectedEffort?: ReasoningEffort;\n /** Available engine/model list for the model picker */\n availableModels?: Array<{\n engine: string;\n label: string;\n models: string[];\n configured: boolean;\n }>;\n /** Callback when user picks a model from the picker */\n onModelChange?: (model: string, engine: string) => void;\n /** Callback when user picks a reasoning effort from the picker */\n onEffortChange?: (effort: ReasoningEffort) => void;\n /** Callback when user clicks \"Fork Chat\" in the message actions menu */\n onForkChat?: () => void | boolean | Promise<void | boolean>;\n /** Override Builder/provider connect routing for embedded hosts. */\n onConnectProvider?: () => void;\n /**\n * Controls the shared composer + menu. Sidebar keeps the full menu by default;\n * hosts without the sidebar provider stack can use upload-only.\n */\n plusMenuMode?: \"full\" | \"upload-only\" | \"hidden\";\n /**\n * Enable framework provider/env status checks. Embedded hosts that provide\n * model/provider state through another transport can disable these probes.\n */\n providerStatusChecksEnabled?: boolean;\n /**\n * Advanced host override for non-HTTP transports. Defaults to the production\n * sidebar SSE adapter when omitted.\n */\n createAdapter?: (context: AssistantChatAdapterContext) => ChatModelAdapter;\n /**\n * Bring-your-own agent runtime. When supplied, AssistantChat keeps the\n * standard composer/transcript/tool rendering shell but sends turns through\n * this runtime instead of the built-in Agent-Native SSE endpoint. If\n * `createAdapter` is also supplied, the adapter override takes precedence.\n */\n runtime?: AgentChatRuntime;\n /**\n * Explicitly recreate an injected adapter when the host transport identity\n * changes. Omit for the production sidebar so parent rerenders do not reset\n * active chats.\n */\n adapterReloadKey?: unknown;\n /**\n * Advanced host override for thread replay. Defaults to SQL thread fetch when\n * `threadId` is set, or sessionStorage for legacy tab chats.\n */\n loadHistoryRepository?: () => Promise<ExportedMessageRepository | null>;\n /** Re-run `loadHistoryRepository` when the host's external transcript changes. */\n historyReloadKey?: string | number | null;\n /** Smooth the last assistant message while an external transcript is updating. */\n externalStreaming?: boolean;\n}\n\nexport const CHAT_STORAGE_PREFIX = \"agent-chat:\";\nconst THREAD_SNAPSHOT_CACHE_PREFIX = `${CHAT_STORAGE_PREFIX}thread-snapshot:`;\n\nfunction threadSnapshotCacheKey(apiUrl: string, threadId: string): string {\n return `${THREAD_SNAPSHOT_CACHE_PREFIX}${apiUrl}:${threadId}`;\n}\n\nfunction normalizeCachedThreadSnapshot(\n value: unknown,\n): ChatThreadSnapshot | null {\n if (!value || typeof value !== \"object\") return null;\n const snapshot = value as Partial<ChatThreadSnapshot>;\n if (typeof snapshot.threadData !== \"string\") return null;\n return {\n threadData: snapshot.threadData,\n title: typeof snapshot.title === \"string\" ? snapshot.title : \"\",\n preview: typeof snapshot.preview === \"string\" ? snapshot.preview : \"\",\n messageCount:\n typeof snapshot.messageCount === \"number\" &&\n Number.isFinite(snapshot.messageCount)\n ? snapshot.messageCount\n : 0,\n };\n}\n\nfunction readCachedThreadSnapshot(\n apiUrl: string,\n threadId?: string,\n): ChatThreadSnapshot | null {\n if (!threadId || typeof sessionStorage === \"undefined\") return null;\n try {\n const raw = sessionStorage.getItem(\n threadSnapshotCacheKey(apiUrl, threadId),\n );\n return raw ? normalizeCachedThreadSnapshot(JSON.parse(raw)) : null;\n } catch {\n return null;\n }\n}\n\nfunction writeCachedThreadSnapshot(\n apiUrl: string,\n threadId: string | undefined,\n snapshot: ChatThreadSnapshot,\n) {\n if (!threadId || typeof sessionStorage === \"undefined\") return;\n try {\n sessionStorage.setItem(\n threadSnapshotCacheKey(apiUrl, threadId),\n JSON.stringify(snapshot),\n );\n } catch {}\n}\n\n/** Remove persisted chat for a given tabId (or \"default\"). */\nexport function clearChatStorage(tabId?: string) {\n try {\n sessionStorage.removeItem(`${CHAT_STORAGE_PREFIX}${tabId || \"default\"}`);\n } catch {}\n}\n\n/**\n * Ensure all messages in a thread repository have required fields.\n * assistant-ui accesses `message.metadata.submittedFeedback` and\n * `lastMessage.status.type` without null-checking, so server-constructed\n * messages missing these fields crash.\n */\nfunction ensureMessageMetadata(repo: any): any {\n if (!repo?.messages || !Array.isArray(repo.messages)) return repo;\n for (const entry of repo.messages) {\n // Handle both wrapped ({ message: { ... } }) and flat ({ role, ... }) formats\n const msg = entry?.message ?? entry;\n if (!msg) continue;\n if (!msg.metadata) {\n msg.metadata = {};\n }\n if (msg.role === \"assistant\") {\n const statusType =\n msg.status && typeof msg.status === \"object\"\n ? (msg.status as { type?: unknown }).type\n : undefined;\n const isTerminal =\n statusType === \"complete\" || statusType === \"incomplete\";\n if (!isTerminal) {\n const runError =\n msg.metadata?.custom?.runError ?? msg.metadata?.runError;\n msg.status = runError\n ? { type: \"incomplete\", reason: \"error\" }\n : { type: \"complete\", reason: \"stop\" };\n }\n if (\n Array.isArray(msg.content) &&\n (isTerminal ||\n msg.status?.type === \"complete\" ||\n msg.status?.type === \"incomplete\")\n ) {\n settleInterruptedToolCalls(msg.content);\n }\n }\n }\n return repo;\n}\n\n// Re-export for backwards compatibility\nimport {\n extractThreadMeta,\n normalizeThreadRepository,\n} from \"../agent/thread-data-builder.js\";\nexport { extractThreadMeta };\n\n/**\n * Strip raw base64 payload from attachment content parts when a hosted URL\n * already exists in the same content entry. This keeps the periodic thread\n * save payload compact — the server already stored the URL reference when it\n * processed the POST, and re-shipping multi-megabyte base64 strings on every\n * 5-second poll save balloons the SQL thread_data column unnecessarily.\n *\n * Only strips the raw base64 data-URL string from `content[].image` / `content[].data`\n * when a `metadata.uploadUrl` reference is present on the same attachment object,\n * so the transcript can still render from the hosted URL after hydration.\n */\nfunction stripBase64FromRepo(repo: unknown): unknown {\n if (!repo || typeof repo !== \"object\") return repo;\n const r = repo as Record<string, unknown>;\n if (!Array.isArray(r.messages)) return repo;\n\n const messages = r.messages.map((entry: unknown) => {\n if (!entry || typeof entry !== \"object\") return entry;\n const e = entry as Record<string, unknown>;\n const msg = (e.message ?? e) as Record<string, unknown> | null;\n if (!msg || typeof msg !== \"object\") return entry;\n\n const attachments = msg.attachments;\n if (!Array.isArray(attachments)) return entry;\n\n const strippedAttachments = attachments.map((att: unknown) => {\n if (!att || typeof att !== \"object\") return att;\n const a = att as Record<string, unknown>;\n const meta = a.metadata as Record<string, unknown> | undefined;\n // Only strip when we have a hosted upload URL confirmed by the server.\n if (!meta?.uploadUrl) return att;\n\n if (!Array.isArray(a.content)) return att;\n const strippedContent = a.content.map((part: unknown) => {\n if (!part || typeof part !== \"object\") return part;\n const p = part as Record<string, unknown>;\n // Replace the raw base64 image data-URL with the hosted URL.\n if (\n p.type === \"image\" &&\n typeof p.image === \"string\" &&\n p.image.startsWith(\"data:\")\n ) {\n return { ...p, image: meta.uploadUrl };\n }\n // Replace the raw base64 file data with a stripped marker.\n if (\n p.type === \"file\" &&\n typeof p.data === \"string\" &&\n p.data.startsWith(\"data:\")\n ) {\n const { data: _d, ...rest } = p;\n return { ...rest, url: meta.uploadUrl };\n }\n return part;\n });\n return { ...a, content: strippedContent };\n });\n\n const strippedMsg = { ...msg, attachments: strippedAttachments };\n if (e.message !== undefined) {\n return { ...e, message: strippedMsg };\n }\n return strippedMsg;\n });\n\n return { ...r, messages };\n}\n\nconst AssistantChatInner = forwardRef<\n AssistantChatHandle,\n AssistantChatProps & { apiUrl: string }\n>(function AssistantChatInner(\n {\n emptyStateText,\n suggestions,\n dynamicSuggestions,\n emptyStateAddon,\n showHeader = true,\n onSwitchToCli,\n className,\n apiUrl,\n tabId,\n browserTabId,\n threadId,\n contextScope,\n isActiveComposer = true,\n onMessageCountChange,\n onSaveThread,\n onGenerateTitle,\n composerSlot,\n composerAreaClassName,\n composerPlaceholder,\n composerLayoutVariant = \"default\",\n centerComposerWhenEmpty = false,\n emptyStateDisplay = \"default\",\n composerToolbarSlot,\n composerExtraActionButton,\n composerDisabled = false,\n composerDisabledPlaceholder,\n isNewThread,\n onSlashCommand,\n execMode,\n onExecModeChange,\n planModeDisabled,\n planModeDisabledReason,\n selectedModel,\n defaultModel,\n selectedEffort,\n availableModels,\n onModelChange,\n onEffortChange,\n onForkChat,\n onConnectProvider,\n plusMenuMode = \"full\",\n providerStatusChecksEnabled = true,\n loadHistoryRepository,\n historyReloadKey,\n externalStreaming = false,\n },\n ref,\n) {\n const thread = useThread();\n const threadRuntime = useThreadRuntime();\n const composerRuntime = useComposerRuntime();\n const isRuntimeRunning = thread.isRunning;\n const messages = thread.messages;\n const { suggestions: resolvedSuggestions } = useAgentDynamicSuggestionsResult(\n {\n staticSuggestions: suggestions,\n dynamicSuggestions,\n browserTabId,\n scope: contextScope,\n enabled: messages.length === 0,\n },\n );\n const messageListResetKey = useMemo(\n () => messages.map((message) => message.id).join(\"|\"),\n [messages],\n );\n\n // Chat-wide drag-and-drop: users expect to drop a file anywhere on the agent\n // sidebar (thread, header, composer) and have it attach — same as ChatGPT,\n // Claude.ai, Linear, Slack, etc. Tiptap's own `handleDrop` only fires inside\n // the contenteditable; drops on the message thread or the composer\n // attachment strip otherwise navigate to the file (browser default), which\n // is why \"upload does nothing\" — the chat refreshes to the dropped image.\n const [dropActive, setDropActive] = useState(false);\n // Inline error shown just above the composer for attachment failures\n // (unsupported format, size cap, body-size rejection, drop errors).\n // Cleared on the next message send.\n const [composerError, setComposerError] = useState<string | null>(null);\n const dropDepthRef = useRef(0);\n const handleChatDragEnter = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n e.preventDefault();\n dropDepthRef.current += 1;\n setDropActive(true);\n }, []);\n const handleChatDragOver = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n e.preventDefault();\n if (e.dataTransfer) e.dataTransfer.dropEffect = \"copy\";\n }, []);\n const handleChatDragLeave = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n dropDepthRef.current = Math.max(0, dropDepthRef.current - 1);\n if (dropDepthRef.current === 0) setDropActive(false);\n }, []);\n const handleChatDropCapture = useCallback((e: React.DragEvent) => {\n if (!Array.from(e.dataTransfer?.types ?? []).includes(\"Files\")) return;\n dropDepthRef.current = 0;\n setDropActive(false);\n }, []);\n const handleChatDrop = useCallback(\n (e: React.DragEvent) => {\n const files = Array.from(e.dataTransfer?.files ?? []);\n if (files.length === 0) return;\n dropDepthRef.current = 0;\n setDropActive(false);\n if (e.defaultPrevented) return;\n e.preventDefault();\n e.stopPropagation();\n // Mirror TiptapComposer's paste/drop name-uniqueness so consecutive\n // screenshots (all named `image.png`) don't collide on the\n // SimpleImageAttachmentAdapter id.\n const attachments = files.map((file) => {\n if (!file.type.startsWith(\"image/\")) return file;\n const uniqueName = `${Date.now()}-${Math.random().toString(36).slice(2)}-${file.name}`;\n return new File([file], uniqueName, { type: file.type });\n });\n void Promise.all(\n attachments.map((file) => composerRuntime.addAttachment(file)),\n ).catch((error) => {\n const msg =\n error instanceof Error\n ? error.message\n : \"Could not add the dropped file. Try a different format.\";\n setComposerError(msg);\n });\n },\n [composerRuntime, setComposerError],\n );\n\n // Patch the underlying assistant-ui MessageRepository so addOrUpdateMessage\n // can't throw \"Parent message not found\" mid-run. assistant-ui calls\n // `repository.clear()` from `runtime.import()` and from `resetHead(null)`,\n // and on a few async paths (history-adapter load, branch reset, repeat\n // imports) the repo can be cleared between the `append` that added the\n // user message and the `performRoundtrip` call that tries to record the\n // assistant placeholder against that user message's id. The internal-bug\n // throw turns into an unhandled rejection that Sentry captures from the\n // assets.agent-native.com prompt composer (AGENT-NATIVE-BROWSER-18). Fix\n // it by relinking to the current head whenever the requested parent has\n // gone missing instead of throwing.\n useEffect(() => {\n const repo = (threadRuntime as any)?.__internal_threadBinding?.getState?.()\n ?.repository as\n | { addOrUpdateMessage?: (parentId: any, message: any) => void }\n | undefined;\n if (!repo || typeof repo.addOrUpdateMessage !== \"function\") return;\n const patched = repo as any;\n if (patched.__agentNativePatched) return;\n patched.__agentNativePatched = true;\n const original = repo.addOrUpdateMessage.bind(repo);\n repo.addOrUpdateMessage = function (parentId: any, message: any) {\n try {\n return original(parentId, message);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (parentId && msg.includes(\"Parent message not found\")) {\n const fallbackParent = (this as any).head?.current?.id ?? null;\n if (fallbackParent && fallbackParent !== parentId) {\n return original(fallbackParent, message);\n }\n return original(null, message);\n }\n if (msg.includes(\"same id already exists\")) {\n return;\n }\n throw err;\n }\n };\n }, [threadRuntime]);\n const missingApiKey = useAgentEngineConfigured(\n providerStatusChecksEnabled,\n ).missing;\n const isComposerDisabled = missingApiKey || composerDisabled;\n // Increments each time the user clicks the (disabled) composer while no LLM\n // is connected — `BuilderSetupCard` watches this to replay a one-shot bounce.\n const [missingKeyBouncePulse, setMissingKeyBouncePulse] = useState(0);\n const [authError, setAuthError] = useState<{\n sessionExpired?: boolean;\n } | null>(null);\n const [authSessionAvailable, setAuthSessionAvailable] = useState(false);\n const [queuedMessages, setQueuedMessages] = useState<QueuedMessage[]>([]);\n const queuedMessagesRef = useRef<QueuedMessage[]>([]);\n const queueDirtyRef = useRef(false);\n const queueMutationVersionRef = useRef(0);\n const dequeueInFlightRef = useRef(false);\n const [composerContextItems, setComposerContextItems] = useState<\n AgentChatContextItem[]\n >([]);\n const composerContextItemsRef = useRef<AgentChatContextItem[]>([]);\n const isActiveComposerRef = useRef(isActiveComposer);\n isActiveComposerRef.current = isActiveComposer;\n const publishComposerContextItems = useCallback(\n (items: AgentChatContextItem[]) => {\n if (!isActiveComposerRef.current) return;\n publishAgentChatContextItems(items);\n },\n [],\n );\n const updateComposerContextItems = useCallback(\n (updater: (previous: AgentChatContextItem[]) => AgentChatContextItem[]) => {\n setComposerContextItems((previous) => {\n const next = updater(previous);\n composerContextItemsRef.current = next;\n publishComposerContextItems(next);\n return next;\n });\n },\n [publishComposerContextItems],\n );\n const stageComposerContextItem = useCallback(\n (rawItem: AgentChatContextItem) => {\n const item = normalizeAgentChatContextItem(rawItem);\n if (!item) return;\n updateComposerContextItems((previous) => {\n const index = previous.findIndex((current) => current.key === item.key);\n if (index === -1) return [...previous, item];\n return previous.map((current, currentIndex) =>\n currentIndex === index ? item : current,\n );\n });\n },\n [updateComposerContextItems],\n );\n const removeComposerContextItem = useCallback(\n (key: string) => {\n updateComposerContextItems((previous) =>\n previous.filter((item) => item.key !== key),\n );\n },\n [updateComposerContextItems],\n );\n const buildComposerContextSubmission = useCallback((text: string) => {\n const context = formatAgentChatContextItemsForPrompt(\n composerContextItemsRef.current,\n );\n if (!context) return { text, includesContext: false };\n return {\n text: appendAgentChatContextToMessage(text, context),\n includesContext: true,\n };\n }, []);\n\n useEffect(() => {\n queuedMessagesRef.current = queuedMessages;\n }, [queuedMessages]);\n\n const applyLocalQueuedMessages = useCallback(\n (updater: (previous: QueuedMessage[]) => QueuedMessage[]) => {\n setQueuedMessages((previous) => {\n const next = updater(previous);\n queuedMessagesRef.current = next;\n queueDirtyRef.current = true;\n queueMutationVersionRef.current += 1;\n return next;\n });\n },\n [],\n );\n\n useEffect(() => {\n if (!isActiveComposer) return;\n let cancelled = false;\n void refreshAgentChatContext().then((state) => {\n if (cancelled || !isActiveComposerRef.current) return;\n composerContextItemsRef.current = state.items;\n setComposerContextItems(state.items);\n });\n return () => {\n cancelled = true;\n };\n }, [isActiveComposer]);\n // Tracks the JSON of the last queue we successfully persisted so the\n // debounced save effect can skip no-op writes (e.g. restore-from-server\n // on mount, or queue state that hasn't actually changed).\n const lastPersistedQueueRef = useRef<string>(\"[]\");\n // Cheap change-guard for `importThreadData`. The real-time sync layer\n // refetches `/threads/:id` (or re-runs `loadHistoryRepository`) on poll /\n // change ticks, on reconnect, and whenever the host's transcript bumps\n // `historyReloadKey`. On a long thread the JSON.parse +\n // normalizeThreadRepository + threadRuntime.export()/import round-trip is\n // CPU-bound and triggers re-render churn even when the content is byte-for-\n // byte identical to what we last imported. We hash the raw incoming payload\n // and skip the whole pipeline when it hasn't advanced, returning the\n // already-imported repo so callers (e.g. the reconnect loop's\n // repoHasAssistantMessage check) see consistent data. Any real change — a\n // new message, an arriving tool result, the server replacing an optimistic\n // copy, or switching threads — produces a different signal and falls\n // through to a full import.\n const lastImportedSignatureRef = useRef<string | null>(null);\n const lastImportedRepoRef = useRef<any>(null);\n const [showContinue, setShowContinue] = useState(false);\n const [loopLimitInfo, setLoopLimitInfo] = useState<LoopLimitInfo | null>(\n null,\n );\n const [runErrorInfo, setRunErrorInfo] = useState<RunErrorInfo | null>(null);\n const [dismissedRunErrorKey, setDismissedRunErrorKey] = useState<\n string | null\n >(null);\n const userStoppedRunRef = useRef<{\n at: number;\n runId?: string;\n } | null>(null);\n const [isReconnecting, setIsReconnecting] = useState(false);\n // True during the 250ms continuation window and startup of the next chunk\n // (adapter's auto-continue delay before POSTing the next chunk).\n const [isAutoResuming, setIsAutoResuming] = useState(false);\n const [reconnectContent, setReconnectContent] = useState<ContentPart[]>([]);\n // When stop is clicked during reconnect, keep content visible (don't wipe it)\n const [reconnectFrozen, setReconnectFrozen] = useState(false);\n const reconnectRunIdRef = useRef<string | null>(null);\n const reconnectAbortRef = useRef<AbortController | null>(null);\n // Nuclear stop: user clicked stop. Clears the stop button/indicator AND\n // lets new submissions go through immediately — prevents the \"stuck\n // queueing forever\" state where isReconnecting or isRuntimeRunning gets\n // wedged (e.g. after a tab refresh + stop during reconnect).\n const [forceStopped, setForceStopped] = useState(false);\n // Real running state — drives submission/queue gating. Treat reconnecting\n // to an active run the same as running, UNLESS the user has explicitly\n // clicked stop (forceStopped).\n const isRunning = !forceStopped && (isRuntimeRunning || isReconnecting);\n const textStreaming = isRunning || externalStreaming;\n // UI-only running state — drives the stop button and thinking indicator.\n const showRunningInUI = isRunning;\n const lastBroadcastRunningRef = useRef(isRunning);\n const tiptapRef = useRef<TiptapComposerHandle>(null);\n // Stable ref to the \"stop active run\" action so addToQueue can abort\n // a running turn without adding many unstable closure deps to its dep list.\n const stopActiveRunRef = useRef<() => void>(() => {});\n\n useEffect(() => {\n if (lastBroadcastRunningRef.current === isRunning) return;\n lastBroadcastRunningRef.current = isRunning;\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning, tabId: tabId || threadId },\n }),\n );\n }, [isRunning, tabId, threadId]);\n\n // ─── Chat persistence ──────────────────────────────────────────────\n const hasRestoredRef = useRef(false);\n const [initialCachedThreadSnapshot] = useState(() =>\n readCachedThreadSnapshot(apiUrl, threadId),\n );\n const hasImportedInitialCachedSnapshotRef = useRef(false);\n const [isRestoring, setIsRestoring] = useState(\n !!(threadId || loadHistoryRepository) &&\n !isNewThread &&\n !initialCachedThreadSnapshot,\n );\n const onSaveThreadRef = useRef(onSaveThread);\n onSaveThreadRef.current = onSaveThread;\n const onGenerateTitleRef = useRef(onGenerateTitle);\n onGenerateTitleRef.current = onGenerateTitle;\n const titleGeneratedRef = useRef(false);\n\n const importThreadData = useCallback(\n (threadData: unknown, options?: { markTitleGenerated?: boolean }): any => {\n // Cheap-signal short-circuit: if the raw payload is identical to the\n // last one we imported, there is nothing new to parse, normalize, or\n // re-import into the runtime. Reuse the already-imported repo so callers\n // still get back a stable result without the CPU + re-render cost. We\n // still honor `markTitleGenerated` because a re-fetch carrying the same\n // content can legitimately confirm a title is settled.\n const signature =\n typeof threadData === \"string\"\n ? threadData\n : (() => {\n try {\n return JSON.stringify(threadData);\n } catch {\n return null;\n }\n })();\n if (\n signature !== null &&\n signature === lastImportedSignatureRef.current\n ) {\n if (options?.markTitleGenerated) {\n titleGeneratedRef.current = true;\n }\n return lastImportedRepoRef.current;\n }\n\n const repo = normalizeThreadRepository(\n typeof threadData === \"string\" ? JSON.parse(threadData) : threadData,\n );\n // Whether this payload settled into the runtime (either imported, or\n // had no messages to import). Only then is it safe to remember its\n // signature as the canonical \"last imported\" — a payload that\n // `shouldImportServerThreadData` deliberately rejected (e.g. it\n // regressed message count) must NOT be cached, so an identical re-fetch\n // re-evaluates against the runtime exactly as before instead of\n // short-circuiting to the rejected repo.\n let settled = true;\n if (repo?.messages?.length > 0) {\n let shouldImport = true;\n try {\n shouldImport = shouldImportServerThreadData(\n normalizeThreadRepository(threadRuntime.export()),\n repo,\n );\n } catch {\n shouldImport = true;\n }\n if (shouldImport) {\n if (options?.markTitleGenerated) {\n titleGeneratedRef.current = true;\n }\n threadRuntime.import(ensureMessageMetadata(repo));\n } else {\n settled = false;\n }\n }\n if (Array.isArray(repo?.queuedMessages)) {\n const incomingQueue = repo.queuedMessages as QueuedMessage[];\n const incomingSerialized = JSON.stringify(incomingQueue);\n const currentSerialized = JSON.stringify(queuedMessagesRef.current);\n if (\n !queueDirtyRef.current ||\n incomingSerialized === currentSerialized\n ) {\n queuedMessagesRef.current = incomingQueue;\n setQueuedMessages(incomingQueue);\n lastPersistedQueueRef.current = incomingSerialized;\n queueDirtyRef.current = false;\n }\n }\n if (settled && signature !== null) {\n lastImportedSignatureRef.current = signature;\n lastImportedRepoRef.current = repo;\n }\n return repo;\n },\n [threadRuntime],\n );\n\n const refreshThreadFromServer = useCallback(async (): Promise<any | null> => {\n if (loadHistoryRepository) {\n try {\n const repo = await loadHistoryRepository();\n if (!repo) return null;\n return importThreadData(repo);\n } catch {\n return null;\n }\n }\n if (!threadId) return null;\n try {\n const refreshRes = await fetch(\n `${apiUrl}/threads/${encodeURIComponent(threadId)}`,\n );\n if (!refreshRes.ok) return null;\n const refreshData = await refreshRes.json();\n if (!refreshData.threadData) return null;\n return importThreadData(refreshData.threadData);\n } catch {\n return null;\n }\n }, [apiUrl, importThreadData, loadHistoryRepository, threadId]);\n\n const cacheCurrentThreadSnapshot = useCallback(() => {\n if (!threadId || messages.length === 0) return;\n const repo = threadRuntime.export();\n const threadData = JSON.stringify(stripBase64FromRepo(repo));\n const { title, preview } = extractThreadMeta(repo);\n writeCachedThreadSnapshot(apiUrl, threadId, {\n threadData,\n title,\n preview,\n messageCount: messages.length,\n });\n }, [apiUrl, messages.length, threadId, threadRuntime]);\n\n useBrowserLayoutEffect(() => {\n if (hasImportedInitialCachedSnapshotRef.current) return;\n if (!initialCachedThreadSnapshot) return;\n hasImportedInitialCachedSnapshotRef.current = true;\n try {\n importThreadData(initialCachedThreadSnapshot.threadData, {\n markTitleGenerated: Boolean(initialCachedThreadSnapshot.title),\n });\n } finally {\n setIsRestoring(false);\n }\n }, [importThreadData, initialCachedThreadSnapshot]);\n\n useEffect(() => {\n window.addEventListener(\n AGENT_CHAT_VIEW_TRANSITION_PREPARE_EVENT,\n cacheCurrentThreadSnapshot,\n );\n return () => {\n window.removeEventListener(\n AGENT_CHAT_VIEW_TRANSITION_PREPARE_EVENT,\n cacheCurrentThreadSnapshot,\n );\n };\n }, [cacheCurrentThreadSnapshot]);\n\n const wasRecentlyStoppedRun = useCallback((runId?: string): boolean => {\n const stopped = userStoppedRunRef.current;\n return Boolean(\n stopped &&\n Date.now() - stopped.at < 10_000 &&\n (!stopped.runId || !runId || stopped.runId === runId),\n );\n }, []);\n\n const startReconnectToRun = useCallback(\n (runInfo: ActiveRunLookup): boolean => {\n if (!threadId || !runInfo.runId || runInfo.status !== \"running\") {\n return false;\n }\n const runId = String(runInfo.runId);\n if (wasRecentlyStoppedRun(runId)) return false;\n if (reconnectRunIdRef.current === runId) return true;\n\n reconnectRunIdRef.current = runId;\n setIsReconnecting(true);\n setReconnectFrozen(false);\n setReconnectContent([]);\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: true, tabId: tabId || threadId },\n }),\n );\n\n const abortCtrl = new AbortController();\n reconnectAbortRef.current = abortCtrl;\n\n const watchdog = setInterval(async () => {\n try {\n const res = await fetch(\n `${apiUrl}/runs/active?threadId=${encodeURIComponent(threadId)}`,\n );\n if (!res.ok) {\n abortCtrl.abort();\n clearInterval(watchdog);\n return;\n }\n const info = (await res.json()) as ActiveRunLookup;\n if (info.status !== \"running\" || activeRunLooksStale(info)) {\n abortCtrl.abort();\n clearInterval(watchdog);\n }\n } catch {\n // Network blip — keep polling.\n }\n }, 1000);\n\n let reconnectTimedOut = false;\n const maxReconnectTimer = setTimeout(() => {\n reconnectTimedOut = true;\n abortCtrl.abort();\n clearInterval(watchdog);\n }, 20_000);\n\n const streamReconnect = async () => {\n let noProgressDuringReconnect = false;\n let latestContent: ContentPart[] = [];\n try {\n const sseRes = await fetch(\n `${apiUrl}/runs/${encodeURIComponent(runId)}/events?after=0`,\n { signal: abortCtrl.signal },\n );\n if (sseRes.ok && sseRes.body) {\n const content: ContentPart[] = [];\n latestContent = content;\n const toolCallCounter = { value: 0 };\n\n let rafPending = false;\n let latestSnapshot: ContentPart[] = [];\n const scheduleUpdate = (snapshot: ContentPart[]) => {\n latestSnapshot = snapshot;\n if (rafPending) return;\n rafPending = true;\n requestAnimationFrame(() => {\n rafPending = false;\n setReconnectContent(latestSnapshot);\n });\n };\n\n await readSSEStreamRaw(\n sseRes.body,\n content,\n toolCallCounter,\n tabId,\n scheduleUpdate,\n );\n setReconnectContent([...content]);\n }\n } catch (err) {\n if (\n err instanceof AgentAutoContinueSignal &&\n err.reason === \"no_progress\"\n ) {\n noProgressDuringReconnect = true;\n } else if (\n reconnectTimedOut &&\n err instanceof Error &&\n err.name === \"AbortError\"\n ) {\n noProgressDuringReconnect = true;\n }\n } finally {\n clearInterval(watchdog);\n clearTimeout(maxReconnectTimer);\n }\n\n if (noProgressDuringReconnect && reconnectRunIdRef.current === runId) {\n captureError(new Error(\"agent-chat:reconnect_no_progress\"), {\n tags: {\n context: \"agent-native-chat\",\n errorCode: \"reconnect_no_progress\",\n reconnectTimedOut: String(reconnectTimedOut),\n },\n extra: {\n runId,\n threadId: threadId ?? null,\n tabId: tabId ?? null,\n contentLength: latestContent.length,\n },\n });\n try {\n await fetch(`${apiUrl}/runs/${encodeURIComponent(runId)}/abort`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ reason: \"no_progress\" }),\n });\n } catch {\n // Best effort — the important part is unwinding the UI.\n }\n settleInterruptedToolCalls(latestContent);\n setReconnectContent([...latestContent]);\n setReconnectFrozen(latestContent.length > 0);\n setRunErrorInfo({\n message:\n \"The previous agent run stopped producing visible progress while reconnecting, so it was stopped before it could keep looping.\",\n errorCode: \"reconnect_no_progress\",\n recoverable: true,\n runId,\n });\n setDismissedRunErrorKey(null);\n reconnectAbortRef.current = null;\n setIsReconnecting(false);\n reconnectRunIdRef.current = null;\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: false, tabId: tabId || threadId },\n }),\n );\n return;\n }\n\n setReconnectFrozen(true);\n let loaded = false;\n for (let attempt = 0; attempt < 10; attempt++) {\n await new Promise((r) => setTimeout(r, 500));\n if (reconnectRunIdRef.current !== runId) break;\n const repo = await refreshThreadFromServer();\n if (repoHasAssistantMessage(repo)) {\n setReconnectContent([]);\n setReconnectFrozen(false);\n loaded = true;\n break;\n }\n }\n\n if (reconnectRunIdRef.current === runId) {\n reconnectAbortRef.current = null;\n setIsReconnecting(false);\n reconnectRunIdRef.current = null;\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: false, tabId: tabId || threadId },\n }),\n );\n }\n if (!loaded) {\n await refreshThreadFromServer();\n }\n };\n\n void streamReconnect();\n return true;\n },\n [apiUrl, refreshThreadFromServer, tabId, threadId, wasRecentlyStoppedRun],\n );\n\n const reconnectActiveRunForThread =\n useCallback(async (): Promise<boolean> => {\n if (!threadId) return false;\n try {\n const runRes = await fetch(\n `${apiUrl}/runs/active?threadId=${encodeURIComponent(threadId)}`,\n );\n if (!runRes.ok) return false;\n const runInfo = (await runRes.json()) as ActiveRunLookup;\n if (\n !runInfo.active ||\n runInfo.status !== \"running\" ||\n activeRunLooksStale(runInfo)\n ) {\n await refreshThreadFromServer();\n return false;\n }\n return startReconnectToRun(runInfo);\n } catch {\n return false;\n }\n }, [apiUrl, refreshThreadFromServer, startReconnectToRun, threadId]);\n\n useEffect(() => {\n if (!threadId || !isNewThread) return;\n // A restored tab can be reclassified as client-only after the thread list\n // loads. Once that happens, there is no server row to restore, so show the\n // empty composer instead of leaving the per-thread restore skeleton up.\n setIsRestoring(false);\n }, [isNewThread, threadId]);\n\n // Restore messages from server on mount (when threadId is set). The\n // server is the single source of truth — we don't hydrate from localStorage\n // first, so what the user sees in the chat panel always matches what the\n // history list (and the agent) sees on disk.\n useEffect(() => {\n if (hasRestoredRef.current) return;\n hasRestoredRef.current = true;\n\n if (loadHistoryRepository) {\n (async () => {\n try {\n const repo = await loadHistoryRepository();\n if (repo) {\n importThreadData(repo, { markTitleGenerated: true });\n }\n titleGeneratedRef.current = true;\n } catch {\n // Start fresh\n } finally {\n setIsRestoring(false);\n }\n })();\n } else if (threadId && isNewThread) {\n // Client-created empty tabs do not have a server row until the first\n // message is sent. Avoid probing /threads/:id on mount; that request\n // can only 404 and makes normal app startup look broken in DevTools.\n setIsRestoring(false);\n } else if (threadId && knownAbsentThreadIds.has(threadId)) {\n // A prior mount already learned this thread has no server row (404).\n // Skip the re-probe so remounts don't re-spam 404s for the same id.\n setIsRestoring(false);\n } else if (threadId) {\n (async () => {\n try {\n const res = await fetch(\n `${apiUrl}/threads/${encodeURIComponent(threadId)}`,\n );\n if (res.ok) {\n const data = await res.json();\n if (data.threadData) {\n const repo = importThreadData(data.threadData, {\n markTitleGenerated: true,\n });\n if (repo) {\n const { title, preview } = extractThreadMeta(repo);\n writeCachedThreadSnapshot(apiUrl, threadId, {\n threadData:\n typeof data.threadData === \"string\"\n ? data.threadData\n : JSON.stringify(data.threadData),\n title: data.title || title,\n preview,\n messageCount: Array.isArray(repo.messages)\n ? repo.messages.length\n : 0,\n });\n }\n }\n // Also skip title generation if thread already has a title\n if (data.title) {\n titleGeneratedRef.current = true;\n }\n } else if (res.status === 404) {\n // No server row for this thread yet — remember it so later remounts\n // skip the probe instead of re-fetching a known 404.\n knownAbsentThreadIds.add(threadId);\n }\n } catch {\n // Start fresh\n } finally {\n // Clear the skeleton as soon as the persisted messages are imported.\n // The active-run reconnect probe below must NOT gate first paint — it\n // only matters when a run is mid-flight (e.g. after a hot reload), and\n // it streams on top of the already-rendered messages.\n setIsRestoring(false);\n }\n // Reconnect to an in-progress run after the skeleton has cleared, so a\n // background `/runs/active` probe never delays showing the conversation.\n try {\n await reconnectActiveRunForThread();\n } catch {\n // No active run to reconnect to.\n }\n })();\n } else {\n // Legacy: restore from sessionStorage\n const storageKey = `${CHAT_STORAGE_PREFIX}${tabId || \"default\"}`;\n try {\n const saved = sessionStorage.getItem(storageKey);\n if (saved) {\n const repo = JSON.parse(saved);\n if (repo?.messages?.length > 0) {\n threadRuntime.import(ensureMessageMetadata(repo));\n }\n }\n } catch {}\n setIsRestoring(false);\n }\n }, [\n threadId,\n tabId,\n apiUrl,\n threadRuntime,\n importThreadData,\n reconnectActiveRunForThread,\n loadHistoryRepository,\n isNewThread,\n ]);\n\n useEffect(() => {\n if (\n !loadHistoryRepository ||\n !hasRestoredRef.current ||\n isRestoring ||\n isRunning\n ) {\n return;\n }\n let cancelled = false;\n void loadHistoryRepository()\n .then((repo) => {\n if (cancelled || !repo) return;\n importThreadData(repo, { markTitleGenerated: true });\n })\n .catch(() => undefined);\n return () => {\n cancelled = true;\n };\n }, [\n historyReloadKey,\n importThreadData,\n isRestoring,\n isRunning,\n loadHistoryRepository,\n ]);\n\n // If assistant-ui stops the local runtime while the background server run is\n // still alive, immediately switch into the same reconnect path used after a\n // reload. Otherwise the composer unlocks, the next send hits a 409, and the\n // user sees \"still working\" even though the UI stopped updating.\n const prevRuntimeRunningForReconnectRef = useRef(isRuntimeRunning);\n useEffect(() => {\n const wasRuntimeRunning = prevRuntimeRunningForReconnectRef.current;\n prevRuntimeRunningForReconnectRef.current = isRuntimeRunning;\n if (\n !wasRuntimeRunning ||\n isRuntimeRunning ||\n !threadId ||\n forceStopped ||\n isReconnecting ||\n wasRecentlyStoppedRun()\n ) {\n return;\n }\n\n let cancelled = false;\n const timer = window.setTimeout(() => {\n if (!cancelled) {\n void reconnectActiveRunForThread();\n }\n }, 250);\n return () => {\n cancelled = true;\n window.clearTimeout(timer);\n };\n }, [\n forceStopped,\n isReconnecting,\n isRuntimeRunning,\n reconnectActiveRunForThread,\n threadId,\n wasRecentlyStoppedRun,\n ]);\n\n // Generate a title when the first user message is sent\n useEffect(() => {\n if (!hasRestoredRef.current) return;\n if (titleGeneratedRef.current) return;\n if (messages.length === 0) return;\n\n const firstUserMsg = messages.find((m) => m.role === \"user\");\n if (!firstUserMsg) return;\n\n // Extract text from the first user message\n const text =\n \"content\" in firstUserMsg\n ? Array.isArray(firstUserMsg.content)\n ? firstUserMsg.content\n .filter((p: any) => p.type === \"text\")\n .map((p: any) => p.text)\n .join(\" \")\n : typeof firstUserMsg.content === \"string\"\n ? firstUserMsg.content\n : \"\"\n : \"\";\n\n if (!text.trim()) return;\n titleGeneratedRef.current = true;\n if (threadId) {\n onGenerateTitleRef.current?.(threadId, text.trim());\n }\n }, [messages, threadId]);\n\n // Periodically save thread data while the agent is running so refreshes\n // don't lose messages. Saves every 5 seconds while running.\n const savedTitleRef = useRef(\"\");\n const lastSaveTimeRef = useRef(0);\n useEffect(() => {\n if (!hasRestoredRef.current) return;\n if (!isRunning) return;\n if (messages.length === 0) return;\n if (!threadId || !onSaveThreadRef.current) return;\n\n const now = Date.now();\n const timeSinceLastSave = now - lastSaveTimeRef.current;\n if (timeSinceLastSave < 5000) return;\n\n const repo = threadRuntime.export();\n const { title, preview } = extractThreadMeta(repo);\n const threadData = JSON.stringify(stripBase64FromRepo(repo));\n const snapshot = {\n threadData,\n title,\n preview,\n messageCount: messages.length,\n };\n\n lastSaveTimeRef.current = now;\n savedTitleRef.current = title;\n writeCachedThreadSnapshot(apiUrl, threadId, snapshot);\n onSaveThreadRef.current(threadId, snapshot);\n }, [apiUrl, messages, isRunning, threadId, threadRuntime]);\n\n // Persist full thread data after each completed response\n useEffect(() => {\n if (!hasRestoredRef.current) return;\n if (isRunning) return;\n if (messages.length === 0) return;\n\n const repo = threadRuntime.export();\n\n if (threadId && onSaveThreadRef.current) {\n // Save to server via the hook callback\n const { title, preview } = extractThreadMeta(repo);\n const threadData = JSON.stringify(stripBase64FromRepo(repo));\n const snapshot = {\n threadData,\n title,\n preview,\n messageCount: messages.length,\n };\n savedTitleRef.current = title;\n writeCachedThreadSnapshot(apiUrl, threadId, snapshot);\n onSaveThreadRef.current(threadId, snapshot);\n } else {\n // Legacy: save to sessionStorage\n const storageKey = `${CHAT_STORAGE_PREFIX}${tabId || \"default\"}`;\n try {\n sessionStorage.setItem(storageKey, JSON.stringify(repo));\n } catch {}\n }\n }, [apiUrl, messages, isRunning, threadId, tabId, threadRuntime]);\n\n useEffect(() => {\n onMessageCountChange?.(messages.length);\n }, [messages.length, onMessageCountChange]);\n\n // Persist queued messages to the server so they survive reloads. Debounced\n // to 300ms so typing-and-queuing-rapidly doesn't hammer the endpoint.\n // Stores them in thread_data.queuedMessages via POST /threads/:id/queued.\n useEffect(() => {\n if (!threadId) return;\n if (!hasRestoredRef.current) return;\n const serialized = JSON.stringify(queuedMessages);\n if (serialized === lastPersistedQueueRef.current) return;\n const queueVersion = queueMutationVersionRef.current;\n const timer = setTimeout(() => {\n (async () => {\n try {\n const res = await fetch(\n `${apiUrl}/threads/${encodeURIComponent(threadId)}/queued`,\n {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ queuedMessages }),\n },\n );\n if (res.ok) {\n lastPersistedQueueRef.current = serialized;\n if (queueMutationVersionRef.current === queueVersion) {\n queueDirtyRef.current = false;\n }\n }\n } catch {\n // Best-effort — next queue change will retry.\n }\n })();\n }, 300);\n return () => clearTimeout(timer);\n }, [queuedMessages, threadId, apiUrl]);\n\n // Nudge the shared hook to re-check after a Builder connect.\n const handleBuilderConnected = useCallback(() => {\n window.dispatchEvent(new Event(\"agent-engine:configured-changed\"));\n }, []);\n\n // Listen for auth error events from the adapter\n const checkAuthSession = useCallback(async () => {\n try {\n const res = await fetch(agentNativePath(\"/_agent-native/auth/session\"), {\n cache: \"no-store\",\n });\n if (!res.ok) return false;\n const data = await res.json().catch(() => null);\n const hasSession = !!data && !data.error;\n setAuthSessionAvailable(hasSession);\n if (hasSession) {\n setAuthError(null);\n }\n return hasSession;\n } catch {\n return false;\n }\n }, []);\n\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as\n | {\n reason?: string;\n tabId?: string;\n threadId?: string;\n }\n | undefined;\n const eventTabId =\n typeof detail?.tabId === \"string\" ? detail.tabId : null;\n const eventThreadId =\n typeof detail?.threadId === \"string\" ? detail.threadId : null;\n if (\n (eventTabId || eventThreadId) &&\n eventTabId !== tabId &&\n eventThreadId !== threadId\n ) {\n return;\n }\n setAuthSessionAvailable(false);\n setAuthError({ sessionExpired: detail?.reason === \"session-expired\" });\n void checkAuthSession();\n };\n window.addEventListener(\"agent-chat:auth-error\", handler);\n return () => window.removeEventListener(\"agent-chat:auth-error\", handler);\n }, [checkAuthSession, tabId, threadId]);\n\n useEffect(() => {\n if (!authError) return;\n // Auto-recovery (`checkAuthSession`) runs immediately + at 250ms. If the\n // card is still showing 3 seconds later, recovery failed and the user\n // is about to hit \"Refresh chat\" — that's the \"Reload UI required\"\n // symptom we want signal on.\n const stuckCapture = window.setTimeout(() => {\n captureError(new Error(\"agent-chat:auth_error_card_stuck\"), {\n tags: {\n context: \"agent-native-chat\",\n errorCode: \"auth_error_card\",\n sessionAvailable: String(authSessionAvailable),\n sessionExpired: String(!!authError.sessionExpired),\n },\n extra: {\n threadId: threadId ?? null,\n tabId: tabId ?? null,\n },\n });\n }, 3000);\n const handler = () => void checkAuthSession();\n const timer = window.setTimeout(handler, 250);\n window.addEventListener(\"focus\", handler);\n window.addEventListener(\"agent-engine:configured-changed\", handler);\n return () => {\n window.clearTimeout(stuckCapture);\n window.clearTimeout(timer);\n window.removeEventListener(\"focus\", handler);\n window.removeEventListener(\"agent-engine:configured-changed\", handler);\n };\n }, [authError, authSessionAvailable, checkAuthSession, tabId, threadId]);\n\n // Listen for loop-limit events from the adapter\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail;\n if (!tabId || detail?.tabId === tabId) {\n setLoopLimitInfo({\n ...(typeof detail?.maxIterations === \"number\"\n ? { maxIterations: detail.maxIterations }\n : {}),\n });\n setShowContinue(true);\n }\n };\n window.addEventListener(\"agent-chat:loop-limit\", handler);\n return () => window.removeEventListener(\"agent-chat:loop-limit\", handler);\n }, [tabId]);\n\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as RunErrorInfo & {\n tabId?: string;\n };\n if (tabId && detail?.tabId && detail.tabId !== tabId) return;\n if (!detail?.message) return;\n const stopped = userStoppedRunRef.current;\n if (\n stopped &&\n Date.now() - stopped.at < 10_000 &&\n (!stopped.runId || !detail.runId || stopped.runId === detail.runId)\n ) {\n return;\n }\n setRunErrorInfo({\n message: detail.message,\n ...(detail.details ? { details: detail.details } : {}),\n ...(detail.errorCode ? { errorCode: detail.errorCode } : {}),\n ...(detail.runId ? { runId: detail.runId } : {}),\n ...(detail.recoverable ? { recoverable: detail.recoverable } : {}),\n });\n setDismissedRunErrorKey(null);\n };\n window.addEventListener(\"agent-chat:run-error\", handler);\n return () => window.removeEventListener(\"agent-chat:run-error\", handler);\n }, [tabId]);\n\n // Real activity means the next chunk has started — leave the auto-resume\n // (\"Resuming\") state so the indicator settles back to \"Thinking\". The\n // activity label itself is intentionally not surfaced: the running\n // indicator stays a steady \"Thinking\" rather than flipping through\n // transient step labels.\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as {\n label?: string;\n tool?: string;\n tabId?: string;\n };\n if (tabId && detail?.tabId && detail.tabId !== tabId) return;\n if (typeof detail?.label === \"string\" && detail.label.trim()) {\n setIsAutoResuming(false);\n }\n };\n window.addEventListener(\"agent-chat:activity\", handler);\n return () => window.removeEventListener(\"agent-chat:activity\", handler);\n }, [tabId]);\n\n // Show \"Resuming…\" during the adapter's auto-continuation window (the\n // ~250ms gap between the end of one serverless chunk and the POST for the\n // next). The adapter dispatches `agent-chat:auto-continue` at that moment.\n useEffect(() => {\n const handler = (e: Event) => {\n const detail = (e as CustomEvent).detail as { tabId?: string };\n if (tabId && detail?.tabId && detail.tabId !== tabId) return;\n setIsAutoResuming(true);\n };\n window.addEventListener(\"agent-chat:auto-continue\", handler);\n return () =>\n window.removeEventListener(\"agent-chat:auto-continue\", handler);\n }, [tabId]);\n\n // Clear auto-resume state when the run stops.\n useEffect(() => {\n if (!isRunning) {\n setIsAutoResuming(false);\n }\n }, [isRunning]);\n\n // Auto-dequeue: when the agent is idle, send the next queued message. This\n // intentionally does not depend on observing the running -> idle transition:\n // restored queues can exist after a reload where this component never saw the\n // previous run as active.\n useEffect(() => {\n if (isRestoring || isRunning || queuedMessages.length === 0) {\n return;\n }\n if (dequeueInFlightRef.current) return;\n\n const next = queuedMessages[0];\n if (!next) return;\n\n dequeueInFlightRef.current = true;\n let cancelled = false;\n let started = false;\n const timer = window.setTimeout(() => {\n started = true;\n void (async () => {\n let removedForAppend = false;\n let appended = false;\n try {\n // In serverless/cross-isolate deployments the client can receive the\n // terminal SSE event a beat before SQL has marked the previous run\n // complete. Starting the queued turn during that window can reconnect\n // to the old run and replay the old answer under the new prompt.\n await waitForThreadRunToClear(apiUrl, threadId);\n if (cancelled) return;\n\n if (queuedMessagesRef.current[0]?.id !== next.id) {\n return;\n }\n\n // Keep the placeholder visible while waiting. Remove it only when the\n // append is about to begin, so queue stalls don't look like the chat\n // silently ate the next message.\n applyLocalQueuedMessages((prev) =>\n prev.filter((message) => message.id !== next.id),\n );\n removedForAppend = true;\n\n const imageAttachments = createAgentImageAttachments(next.images);\n const messageAttachments =\n next.attachments && next.attachments.length > 0\n ? next.attachments\n : (imageAttachments ?? []);\n threadRuntime.append({\n role: \"user\",\n content: [{ type: \"text\", text: next.text }],\n ...(messageAttachments.length > 0\n ? { attachments: messageAttachments }\n : {}),\n ...createUserMessageRunConfig(\n next.references,\n next.requestMode,\n next.recoveryAction,\n next.trackInRunsTray,\n undefined,\n next.id,\n ),\n } as Parameters<typeof threadRuntime.append>[0]);\n appended = true;\n } catch (err) {\n if (\n removedForAppend &&\n !queuedMessagesRef.current.some((message) => message.id === next.id)\n ) {\n applyLocalQueuedMessages((prev) => [next, ...prev]);\n }\n captureError(err, {\n tags: {\n source: \"agent-chat-client\",\n phase: \"dequeue-message\",\n },\n extra: {\n threadId: threadId ?? null,\n queuedMessageId: next.id,\n },\n });\n } finally {\n if (appended) {\n window.setTimeout(() => {\n dequeueInFlightRef.current = false;\n }, 500);\n } else {\n dequeueInFlightRef.current = false;\n }\n }\n })();\n }, 100);\n\n return () => {\n cancelled = true;\n window.clearTimeout(timer);\n if (!started) {\n dequeueInFlightRef.current = false;\n }\n };\n }, [\n apiUrl,\n applyLocalQueuedMessages,\n isRestoring,\n isRunning,\n queuedMessages,\n threadId,\n threadRuntime,\n ]);\n\n // Clear frozen reconnect content + forceStopped only on the false→true\n // transition of isRuntimeRunning (i.e. a NEW run is actually starting).\n // Reacting to \"isRuntimeRunning is currently true\" would clear the\n // nuclear-stop flag immediately after the user clicks stop, since\n // cancellation is async and isRuntimeRunning is still true at that moment.\n const prevIsRuntimeRunningRef = useRef(isRuntimeRunning);\n useEffect(() => {\n const wasRunning = prevIsRuntimeRunningRef.current;\n prevIsRuntimeRunningRef.current = isRuntimeRunning;\n if (isRuntimeRunning && !wasRunning) {\n if (reconnectFrozen) {\n setReconnectFrozen(false);\n setReconnectContent([]);\n }\n if (forceStopped) {\n setForceStopped(false);\n }\n }\n }, [isRuntimeRunning, reconnectFrozen, forceStopped]);\n\n // Same transition guard for isReconnecting: only clear forceStopped on\n // the false→true edge (a new reconnect starting on page load).\n const prevIsReconnectingRef = useRef(isReconnecting);\n useEffect(() => {\n const wasReconnecting = prevIsReconnectingRef.current;\n prevIsReconnectingRef.current = isReconnecting;\n if (isReconnecting && !wasReconnecting && forceStopped) {\n setForceStopped(false);\n }\n }, [isReconnecting, forceStopped]);\n\n const materializeFrozenReconnectContent = useCallback(() => {\n if (!reconnectFrozen || reconnectContent.length === 0) return;\n try {\n const frozenContent = cloneContentParts(reconnectContent);\n settleInterruptedToolCalls(frozenContent);\n const repo = normalizeThreadRepository(threadRuntime.export());\n const messages = getRepoMessages(repo);\n const lastEntry = messages[messages.length - 1];\n const lastMessage = getRepoMessage(lastEntry);\n const parentId =\n typeof repo.headId === \"string\"\n ? repo.headId\n : typeof lastMessage?.id === \"string\"\n ? lastMessage.id\n : null;\n const runId = runErrorInfo?.runId ?? reconnectRunIdRef.current;\n const id = `reconnect-${runId ?? Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n repo.messages = [\n ...messages,\n {\n parentId,\n message: {\n id,\n role: \"assistant\",\n createdAt: new Date(),\n content: frozenContent,\n status: { type: \"complete\", reason: \"stop\" },\n metadata: {\n custom: {\n reconnectFrozen: true,\n ...(runId ? { runId } : {}),\n },\n },\n },\n },\n ];\n repo.headId = id;\n\n threadRuntime.import(ensureMessageMetadata(repo));\n setReconnectFrozen(false);\n setReconnectContent([]);\n } catch (err) {\n captureError(err, {\n tags: {\n source: \"agent-chat-client\",\n phase: \"materialize-reconnect-content\",\n },\n extra: {\n threadId: threadId ?? null,\n tabId: tabId ?? null,\n reconnectParts: reconnectContent.length,\n },\n });\n }\n }, [\n reconnectFrozen,\n reconnectContent,\n runErrorInfo?.runId,\n tabId,\n threadId,\n threadRuntime,\n ]);\n\n // Abort the active server run (identical to what the Stop button does) so\n // an immediate-while-running send can proceed cleanly without a 409 race.\n // Captured in a stable ref so addToQueue can call it without listing\n // all the stop-related state in its own dep array.\n const stopActiveRun = useCallback(() => {\n setForceStopped(true);\n const activeRun = getActiveRun();\n const runIdToAbort = reconnectRunIdRef.current ?? activeRun?.runId;\n userStoppedRunRef.current = {\n at: Date.now(),\n ...(runIdToAbort ? { runId: runIdToAbort } : {}),\n };\n setRunErrorInfo(null);\n setDismissedRunErrorKey(null);\n if (runIdToAbort) {\n fetch(`${apiUrl}/runs/${encodeURIComponent(runIdToAbort)}/abort`, {\n method: \"POST\",\n }).catch(() => {});\n }\n if (isReconnecting) {\n reconnectAbortRef.current?.abort();\n reconnectAbortRef.current = null;\n reconnectRunIdRef.current = null;\n setIsReconnecting(false);\n setReconnectFrozen(reconnectContent.length > 0);\n }\n threadRuntime.cancelRun();\n if (typeof window !== \"undefined\") {\n window.dispatchEvent(\n new CustomEvent(\"agentNative.chatRunning\", {\n detail: { isRunning: false, tabId: tabId || threadId },\n }),\n );\n }\n }, [\n apiUrl,\n isReconnecting,\n reconnectContent.length,\n tabId,\n threadId,\n threadRuntime,\n ]);\n // Keep the ref current so addToQueue can call it without a stale closure.\n stopActiveRunRef.current = stopActiveRun;\n\n const addToQueue = useCallback(\n async (\n text: string,\n images?: string[],\n references?: Reference[],\n attachments?: ReadonlyArray<unknown>,\n requestMode?: AgentRequestMode,\n intent: ComposerSubmitIntent = \"queued\",\n recoveryAction?: AgentRecoveryAction,\n includeComposerContext = false,\n trackInRunsTray = false,\n ) => {\n materializeFrozenReconnectContent();\n setShowContinue(false);\n setLoopLimitInfo(null);\n setRunErrorInfo(null);\n setDismissedRunErrorKey(null);\n setComposerError(null);\n userStoppedRunRef.current = null;\n // Selection context attached via Cmd+I is one-shot — clear it as soon\n // as the user actually sends a message so it can't be re-used.\n clearPendingSelection();\n // Sending a message is an explicit user action — always anchor to the\n // bottom so the new message and any reply land in view, even if the\n // user had scrolled up to read history. The sticky-bottom override\n // exists to stop streaming from yanking the viewport, not to swallow\n // direct sends.\n markNearBottom();\n const submitted = includeComposerContext\n ? buildComposerContextSubmission(text)\n : { text, includesContext: false };\n const submittedText = submitted.text;\n let queuedAttachments: Awaited<\n ReturnType<typeof serializeQueuedAttachments>\n >;\n try {\n queuedAttachments = await serializeQueuedAttachments(attachments);\n } catch (err) {\n const msg =\n err instanceof Error\n ? err.message\n : \"Attachment could not be processed.\";\n setComposerError(msg);\n return;\n }\n const imageAttachments = createAgentImageAttachments(images);\n const allAttachments = [\n ...(queuedAttachments ?? []),\n ...(imageAttachments ?? []),\n ];\n\n // ── Body-size guard (Fix 3) ─────────────────────────────────────\n // Estimate the total serialized attachment payload. If it exceeds the\n // Vercel/Netlify body limit, progressively re-compress images until\n // the payload fits, then reject the largest remaining file if still over.\n let messageAttachments = allAttachments;\n {\n const allDataUrls = allAttachments.flatMap((a) =>\n a.content\n .filter(\n (c): c is { type: \"image\"; image: string } => c.type === \"image\",\n )\n .map((c) => c.image),\n );\n if (\n estimateAttachmentBodyBytes(allDataUrls) > MAX_ESTIMATED_BODY_BYTES\n ) {\n // Re-compress image attachments more aggressively.\n const recompressed: typeof allAttachments = [];\n let stillOver = false;\n for (const att of allAttachments) {\n if (\n att.type === \"image\" &&\n att.content.length === 1 &&\n att.content[0].type === \"image\"\n ) {\n // Find the original File from the queued attachments input.\n const rawAtt = (attachments ?? []).find(\n (r) => (r as any).id === att.id,\n ) as { file?: File } | undefined;\n const rawFile = rawAtt?.file;\n if (rawFile && typeof document !== \"undefined\") {\n try {\n const recompressedUrl = await transcodeImageToDataURL(\n rawFile,\n {\n maxDimension: AGGRESSIVE_MAX_IMAGE_DIMENSION,\n jpegQuality: AGGRESSIVE_JPEG_QUALITY,\n },\n );\n recompressed.push({\n ...att,\n content: [{ type: \"image\", image: recompressedUrl }],\n });\n continue;\n } catch {\n // Could not recompress — keep original and flag overflow\n stillOver = true;\n }\n } else {\n stillOver = true;\n }\n }\n recompressed.push(att);\n }\n // Re-estimate after recompression.\n const recompressedUrls = recompressed.flatMap((a) =>\n a.content\n .filter(\n (c): c is { type: \"image\"; image: string } =>\n c.type === \"image\",\n )\n .map((c) => c.image),\n );\n if (\n stillOver ||\n estimateAttachmentBodyBytes(recompressedUrls) >\n MAX_ESTIMATED_BODY_BYTES\n ) {\n // Find the largest attachment and reject it.\n let largestIdx = -1;\n let largestSize = 0;\n for (let i = 0; i < recompressed.length; i++) {\n const url =\n recompressed[i].content.find(\n (c): c is { type: \"image\"; image: string } =>\n c.type === \"image\",\n )?.image ?? \"\";\n if (url.length > largestSize) {\n largestSize = url.length;\n largestIdx = i;\n }\n }\n if (largestIdx >= 0) {\n const rejected = recompressed[largestIdx];\n setComposerError(\n `\"${rejected.name}\" makes the message too large to send (combined attachments must be under ${Math.round(MAX_ESTIMATED_BODY_BYTES / 1024 / 1024)} MB). Remove it or use a smaller image.`,\n );\n return;\n }\n }\n messageAttachments = recompressed;\n }\n }\n // ── End body-size guard ──────────────────────────────────────────\n // Snapshot the exec mode at enqueue time when the caller didn't\n // pass an explicit override. Without this, a plan-mode message that\n // sits in the queue runs as 'act' if the user flips the global toggle\n // before the queue flushes — turning a read-only message into a write.\n const effectiveRequestMode: AgentRequestMode | undefined =\n requestMode ??\n (execMode === \"plan\"\n ? \"plan\"\n : execMode === \"build\"\n ? \"act\"\n : undefined);\n if (isRunning && intent === \"immediate\") {\n // Explicit interrupt path: abort the active server run, then let the\n // auto-dequeue path append this message once the run is clear. Normal\n // composer sends while running resolve to \"queued\" before reaching here.\n applyLocalQueuedMessages((prev) => [\n ...prev,\n {\n id:\n typeof crypto !== \"undefined\" && crypto.randomUUID\n ? crypto.randomUUID()\n : `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n text: submittedText,\n images,\n attachments:\n messageAttachments.length > 0 ? messageAttachments : undefined,\n references,\n requestMode: effectiveRequestMode,\n recoveryAction,\n trackInRunsTray,\n },\n ]);\n stopActiveRunRef.current();\n } else if (isRunning && intent === \"queued\") {\n applyLocalQueuedMessages((prev) => [\n ...prev,\n {\n id:\n typeof crypto !== \"undefined\" && crypto.randomUUID\n ? crypto.randomUUID()\n : `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n text: submittedText,\n images,\n attachments:\n messageAttachments.length > 0 ? messageAttachments : undefined,\n references,\n requestMode: effectiveRequestMode,\n recoveryAction,\n trackInRunsTray,\n },\n ]);\n } else {\n threadRuntime.append({\n role: \"user\",\n content: [{ type: \"text\", text: submittedText }],\n ...(messageAttachments.length > 0\n ? { attachments: messageAttachments }\n : {}),\n ...createUserMessageRunConfig(\n references,\n effectiveRequestMode,\n recoveryAction,\n trackInRunsTray,\n ),\n } as Parameters<typeof threadRuntime.append>[0]);\n }\n if (submitted.includesContext) {\n updateComposerContextItems(() => []);\n }\n },\n [\n applyLocalQueuedMessages,\n buildComposerContextSubmission,\n execMode,\n isRunning,\n materializeFrozenReconnectContent,\n threadRuntime,\n updateComposerContextItems,\n ],\n );\n\n // Expose imperative handle\n useImperativeHandle(\n ref,\n () => ({\n sendMessage(\n text: string,\n images?: string[],\n options?: AssistantChatSendOptions,\n ) {\n addToQueue(\n text,\n images,\n undefined,\n undefined,\n options?.requestMode,\n \"queued\",\n undefined,\n false,\n options?.trackInRunsTray === true,\n );\n },\n prefillMessage(text: string) {\n tiptapRef.current?.setText(text);\n tiptapRef.current?.focus();\n },\n setComposerContextItem(item: AgentChatContextItem) {\n stageComposerContextItem(item);\n tiptapRef.current?.focus();\n },\n removeComposerContextItem(key: string) {\n removeComposerContextItem(key);\n },\n clearComposerContextItems() {\n updateComposerContextItems(() => []);\n },\n sendRecoveryMessage(\n text: string,\n recoveryAction: AgentRecoveryAction,\n images?: string[],\n ) {\n addToQueue(\n text,\n images,\n undefined,\n undefined,\n undefined,\n \"queued\",\n recoveryAction,\n );\n },\n queueMessage(text: string, images?: string[]) {\n addToQueue(text, images);\n },\n isRunning() {\n return thread.isRunning;\n },\n focusComposer() {\n tiptapRef.current?.focus();\n },\n exportThreadSnapshot() {\n if (messages.length === 0) return null;\n const repo = threadRuntime.export();\n const { title, preview } = extractThreadMeta(repo);\n return {\n threadData: JSON.stringify(repo),\n title,\n preview,\n messageCount: messages.length,\n };\n },\n }),\n [\n addToQueue,\n messages.length,\n stageComposerContextItem,\n thread.isRunning,\n threadRuntime,\n ],\n );\n\n const autoscrollFollowKey = useMemo(\n () =>\n [\n messages.map(messageFollowKey).join(\";\"),\n `q:${queuedMessages.map(queuedMessageFollowKey).join(\"|\")}`,\n `r:${reconnectContentFollowKey(reconnectContent)}`,\n ].join(\";;\"),\n [messages, queuedMessages, reconnectContent],\n );\n\n const {\n scrollRef,\n isNearBottomRef,\n showScrollToBottom,\n markNearBottom,\n scrollToBottom,\n scrollToBottomAfterPaint,\n } = useNearBottomAutoscroll<HTMLDivElement>({\n followKey: autoscrollFollowKey,\n streaming: textStreaming,\n });\n\n const scrollToBottomWhileLayoutSettles = useCallback(() => {\n scrollToBottomAfterPaint();\n const el = scrollRef.current;\n if (!el || typeof ResizeObserver === \"undefined\") return undefined;\n\n let stopped = false;\n const observer = new ResizeObserver(() => {\n if (!stopped && isNearBottomRef.current) scrollToBottom();\n });\n observer.observe(el);\n const timeout = window.setTimeout(() => {\n stopped = true;\n observer.disconnect();\n if (isNearBottomRef.current) scrollToBottom();\n }, 1600);\n\n return () => {\n stopped = true;\n window.clearTimeout(timeout);\n observer.disconnect();\n };\n }, [isNearBottomRef, scrollToBottom, scrollToBottomAfterPaint]);\n\n // Scroll to bottom when a restored thread finishes loading\n const wasRestoringRef = useRef(isRestoring);\n useEffect(() => {\n const wasRestoring = wasRestoringRef.current;\n wasRestoringRef.current = isRestoring;\n if (wasRestoring && !isRestoring) {\n return scrollToBottomWhileLayoutSettles();\n }\n }, [isRestoring, scrollToBottomWhileLayoutSettles]);\n\n useEffect(() => {\n if (!textStreaming && isNearBottomRef.current) {\n scrollToBottomAfterPaint();\n }\n }, [textStreaming, scrollToBottomAfterPaint]);\n\n const { isDevMode: cpDevMode } = useDevMode(apiUrl);\n const checkpointCtx = useMemo(\n () => ({ apiUrl, devMode: cpDevMode, threadId }),\n [apiUrl, cpDevMode, threadId],\n );\n const messageActionsCtx = useMemo(() => ({ onForkChat }), [onForkChat]);\n const lastMessageLoopLimit = useMemo(() => {\n const last = messages[messages.length - 1];\n if (!last || last.role !== \"assistant\") return null;\n return getLoopLimitMetadata(last);\n }, [messages]);\n const lastMessageRunError = useMemo(() => {\n const last = messages[messages.length - 1];\n if (!last || last.role !== \"assistant\") return null;\n return getRunErrorMetadata(last);\n }, [messages]);\n const lastUserText = useMemo(\n () => latestNonRecoveryUserMessageText(messages),\n [messages],\n );\n const latestMessage = messages[messages.length - 1];\n const latestMessageRole = latestMessage?.role;\n const latestAssistantWasPlan =\n latestMessageRole === \"assistant\" &&\n getRequestModeMetadata(latestMessage) === \"plan\";\n const showPlanModeCallout =\n execMode === \"plan\" &&\n !planModeDisabled &&\n !isComposerDisabled &&\n !showRunningInUI;\n const canImplementPlan = showPlanModeCallout && latestAssistantWasPlan;\n const contextXRayEnabled = Boolean(\n threadId &&\n (messages.length > 0 || isReconnecting || reconnectContent.length > 0),\n );\n const handleImplementPlan = useCallback(() => {\n onExecModeChange?.(\"build\");\n void addToQueue(\n \"Implement the plan.\",\n undefined,\n undefined,\n undefined,\n \"act\",\n );\n }, [addToQueue, onExecModeChange]);\n const handleSwitchToAct = useCallback(() => {\n onExecModeChange?.(\"build\");\n }, [onExecModeChange]);\n const visibleLoopLimit = showContinue\n ? (loopLimitInfo ?? lastMessageLoopLimit ?? {})\n : lastMessageLoopLimit;\n const visibleRunError = runErrorInfo ?? lastMessageRunError;\n const visibleRunErrorKey = visibleRunError\n ? `${visibleRunError.runId ?? \"\"}:${visibleRunError.errorCode ?? \"\"}:${visibleRunError.message}`\n : null;\n const shouldShowRunError =\n !!visibleRunError &&\n !showRunningInUI &&\n visibleRunErrorKey !== dismissedRunErrorKey &&\n !(\n userStoppedRunRef.current &&\n Date.now() - userStoppedRunRef.current.at < 10_000 &&\n (!userStoppedRunRef.current.runId ||\n !visibleRunError.runId ||\n userStoppedRunRef.current.runId === visibleRunError.runId)\n );\n const hasActiveChatWork =\n showRunningInUI ||\n isAutoResuming ||\n queuedMessages.length > 0 ||\n reconnectContent.length > 0;\n const isFreshEmptyChat =\n messages.length === 0 &&\n !hasActiveChatWork &&\n !isRestoring &&\n !isReconnecting &&\n !authError;\n const centeredEmptyState = centerComposerWhenEmpty && isFreshEmptyChat;\n const showEmptyState =\n messages.length === 0 && !isReconnecting && !hasActiveChatWork;\n const showComposerSlot =\n Boolean(composerSlot) && (!centerComposerWhenEmpty || centeredEmptyState);\n\n // Clarifying-question surface: the `ask-question` action writes a\n // GuidedQuestionPayload to application_state under \"guided-questions\". The\n // hook polls that key, and on submit/skip composes the answer as a normal\n // user turn (via the shared sendToAgentChat) and clears the persisted key so\n // the question does not reappear.\n const {\n questions: guidedQuestions,\n title: guidedQuestionsTitle,\n description: guidedQuestionsDescription,\n skipLabel: guidedQuestionsSkipLabel,\n submitLabel: guidedQuestionsSubmitLabel,\n handleSubmit: handleGuidedQuestionsSubmit,\n handleSkip: handleGuidedQuestionsSkip,\n } = useGuidedQuestionFlow({\n stateKey: \"guided-questions\",\n queryKey: [\"guided-questions\"],\n ...(browserTabId ? { browserTabId } : {}),\n });\n\n // Human-in-the-loop approvals: when the user approves a paused `needsApproval`\n // tool call, re-issue the turn carrying the call's approval key so the server\n // gate lets that specific call run. Reuses the same append path as recovery /\n // queued messages (no hand-written fetch).\n const approvalCtx = useMemo<ApprovalContextValue>(\n () => ({\n onApprove: (approvalKey: string) => {\n threadRuntime.append({\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: \"Approved. Go ahead and run the requested action.\",\n },\n ],\n ...createUserMessageRunConfig(\n undefined,\n execMode === \"plan\"\n ? \"plan\"\n : execMode === \"build\"\n ? \"act\"\n : undefined,\n undefined,\n undefined,\n [approvalKey],\n ),\n } as Parameters<typeof threadRuntime.append>[0]);\n },\n }),\n [threadRuntime, execMode],\n );\n\n return (\n <CheckpointContext.Provider value={checkpointCtx}>\n <MessageActionsContext.Provider value={messageActionsCtx}>\n <ApprovalContext.Provider value={approvalCtx}>\n <ChatRunningContext.Provider value={isRunning}>\n <TextStreamingContext.Provider value={textStreaming}>\n <div\n data-agent-empty-state={\n centeredEmptyState ? \"centered\" : undefined\n }\n className={cn(\n \"relative flex flex-1 flex-col h-full min-h-0 text-foreground\",\n className,\n )}\n onDragEnter={handleChatDragEnter}\n onDragOver={handleChatDragOver}\n onDragLeave={handleChatDragLeave}\n onDropCapture={handleChatDropCapture}\n onDrop={handleChatDrop}\n >\n {dropActive && (\n <div\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-0 z-50 flex items-center justify-center rounded-md border-2 border-dashed border-primary/70 bg-primary/5 backdrop-blur-[1px]\"\n >\n <span className=\"rounded-md bg-background/90 px-3 py-1.5 text-xs font-medium text-foreground shadow-sm\">\n Drop to attach\n </span>\n </div>\n )}\n {showHeader && (\n <div className=\"flex h-11 shrink-0 items-center justify-between border-b border-border px-4\">\n <span className=\"text-[13px] font-medium text-muted-foreground\">\n Agent\n </span>\n <div className=\"flex items-center gap-1\">\n {onSwitchToCli && (\n <TooltipProvider delayDuration={200}>\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n onClick={onSwitchToCli}\n aria-label=\"Switch to CLI\"\n className=\"flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground px-2 py-1 rounded-md hover:bg-accent\"\n >\n <IconTerminal className=\"h-3.5 w-3.5\" />\n CLI\n </button>\n </TooltipTrigger>\n <TooltipContent>Switch to CLI</TooltipContent>\n </Tooltip>\n </TooltipProvider>\n )}\n </div>\n </div>\n )}\n\n {/* Messages area */}\n <div\n ref={scrollRef}\n className=\"agent-chat-scroll flex-1 overflow-y-auto overflow-x-hidden min-h-0\"\n >\n {authError ? (\n <div className=\"flex flex-col items-center justify-center h-full px-4 gap-3\">\n <div className=\"flex h-10 w-10 items-center justify-center rounded-full bg-muted\">\n {authSessionAvailable ? (\n <IconRefresh className=\"h-5 w-5 text-muted-foreground\" />\n ) : (\n <IconMessage className=\"h-5 w-5 text-muted-foreground\" />\n )}\n </div>\n <div className=\"text-center max-w-[280px]\">\n <p className=\"text-sm font-medium text-foreground mb-1\">\n {authSessionAvailable\n ? \"Chat session needs refresh\"\n : authError.sessionExpired\n ? \"Session expired\"\n : \"Authentication required\"}\n </p>\n <p className=\"text-xs text-muted-foreground leading-relaxed\">\n {authSessionAvailable\n ? \"You're signed in, but this chat connection needs to reconnect.\"\n : authError.sessionExpired\n ? \"Your session may have expired. Log out and log back in to reconnect.\"\n : \"You need to log in to use the agent.\"}\n </p>\n </div>\n <div className=\"flex gap-2\">\n {!authError.sessionExpired && !authSessionAvailable && (\n <button\n onClick={() => {\n const ret =\n window.location.pathname +\n window.location.search;\n window.location.href =\n agentNativePath(\"/_agent-native/sign-in\") +\n `?return=${encodeURIComponent(ret)}`;\n }}\n className=\"text-xs text-background bg-foreground hover:opacity-90 px-3 py-1.5 rounded-md\"\n >\n Log in\n </button>\n )}\n {authError.sessionExpired && !authSessionAvailable && (\n <button\n onClick={async () => {\n try {\n await fetch(\n agentNativePath(\"/_agent-native/auth/logout\"),\n {\n method: \"POST\",\n },\n );\n } catch {}\n window.location.reload();\n }}\n className=\"text-xs text-destructive hover:text-destructive/80 px-3 py-1.5 rounded-md border border-destructive/30 hover:bg-destructive/10\"\n >\n Log out\n </button>\n )}\n <button\n onClick={() => {\n setAuthError(null);\n window.location.reload();\n }}\n className={\n authSessionAvailable\n ? \"text-xs text-background bg-foreground hover:opacity-90 px-3 py-1.5 rounded-md\"\n : \"text-xs text-muted-foreground hover:text-foreground px-3 py-1.5 rounded-md border border-border hover:bg-accent\"\n }\n >\n Refresh chat\n </button>\n </div>\n </div>\n ) : isRestoring ? (\n <div className=\"flex flex-col gap-3 p-4\">\n <div className=\"flex justify-end\">\n <div className=\"h-8 w-32 rounded-lg bg-muted animate-pulse\" />\n </div>\n <div className=\"flex flex-col gap-1.5\">\n <div className=\"h-4 w-48 rounded bg-muted animate-pulse\" />\n <div className=\"h-4 w-64 rounded bg-muted animate-pulse\" />\n <div className=\"h-4 w-40 rounded bg-muted animate-pulse\" />\n </div>\n </div>\n ) : showEmptyState ? (\n <div\n className={cn(\n \"agent-empty-state\",\n emptyStateDisplay === \"hidden\"\n ? \"sr-only\"\n : \"flex h-full flex-col items-center justify-center gap-4 px-4 py-16\",\n )}\n >\n <div className=\"flex h-10 w-10 items-center justify-center rounded-full bg-muted\">\n <IconMessage className=\"h-5 w-5 text-muted-foreground\" />\n </div>\n <p className=\"sr-only\">\n {emptyStateText ?? \"How can I help you?\"}\n </p>\n {emptyStateAddon}\n {resolvedSuggestions && resolvedSuggestions.length > 0 ? (\n <div className=\"flex flex-col gap-1.5 w-full max-w-[280px]\">\n {resolvedSuggestions.map((suggestion) => (\n <button\n key={suggestion}\n onClick={() => {\n threadRuntime.append({\n role: \"user\",\n content: [{ type: \"text\", text: suggestion }],\n });\n }}\n className=\"w-full rounded-lg border border-border px-3 py-2 text-left text-[13px] text-muted-foreground hover:bg-accent hover:text-foreground\"\n >\n {suggestion}\n </button>\n ))}\n </div>\n ) : null}\n </div>\n ) : (\n <div className=\"agent-thread-content flex flex-col gap-4 px-4 py-4\">\n <AssistantMessageListErrorBoundary\n resetKey={messageListResetKey}\n >\n <ThreadPrimitive.Messages\n components={{\n UserMessage,\n AssistantMessage,\n }}\n />\n </AssistantMessageListErrorBoundary>\n {visibleLoopLimit && !showRunningInUI && (\n <LoopLimitContinueCard\n info={visibleLoopLimit}\n onContinue={() => {\n setShowContinue(false);\n setLoopLimitInfo(null);\n addToQueue(\n \"Continue from where you left off.\",\n undefined,\n undefined,\n undefined,\n undefined,\n \"queued\",\n \"continue\",\n );\n }}\n />\n )}\n {shouldShowRunError && visibleRunError && (\n <RunErrorRecoveryCard\n info={visibleRunError}\n onContinue={() => {\n setRunErrorInfo(null);\n addToQueue(\n \"Continue from where you stopped. Use the partial work above, verify what succeeded, and finish the original request. Do not rerun the exact same failed tool input unless the failure was transient or the user explicitly asked for an exact rerun. Prefer dedicated app actions over raw database edits when they exist.\",\n undefined,\n undefined,\n undefined,\n undefined,\n \"queued\",\n \"continue\",\n );\n }}\n onRetry={() => {\n setRunErrorInfo(null);\n addToQueue(\n lastUserText\n ? `Retry the previous request from a clean approach. Do not rerun the exact same failed tool input unless the failure was transient or the user explicitly asked for an exact rerun. If a provider query failed because of schema, syntax, or type mismatch, diagnose the error and adjust the query first.\\n\\nOriginal request:\\n\\n${lastUserText}`\n : \"Retry the previous request from a clean approach. Do not rerun the exact same failed tool input unless the failure was transient or the user explicitly asked for an exact rerun. If a provider query failed because of schema, syntax, or type mismatch, diagnose the error and adjust the query first.\",\n undefined,\n undefined,\n undefined,\n undefined,\n \"queued\",\n \"retry\",\n );\n }}\n onFork={onForkChat}\n onDismiss={() => {\n if (visibleRunErrorKey) {\n setDismissedRunErrorKey(visibleRunErrorKey);\n }\n setRunErrorInfo(null);\n }}\n />\n )}\n {(isReconnecting || reconnectFrozen) &&\n reconnectContent.length > 0 && (\n <ReconnectStreamMessage content={reconnectContent} />\n )}\n {showRunningInUI && (\n <RunningActivityStatus\n label={\n isReconnecting\n ? \"Reconnecting\"\n : isAutoResuming\n ? \"Resuming\"\n : // Keep a steady \"Thinking\" while the model works —\n // never flip through transient activity labels\n // (e.g. \"Contacting model\", \"Preparing X action\").\n \"Thinking\"\n }\n />\n )}\n {queuedMessages.map((msg) => {\n const displayText = msg.text\n .replace(/<context>[\\s\\S]*?<\\/context>\\n?/g, \"\")\n .trim();\n return (\n <div\n key={msg.id}\n className=\"group flex items-start justify-end gap-1.5\"\n >\n <button\n type=\"button\"\n onClick={() =>\n applyLocalQueuedMessages((prev) =>\n prev.filter((m) => m.id !== msg.id),\n )\n }\n aria-label=\"Remove from queue\"\n className=\"mt-1.5 flex h-5 w-5 items-center justify-center rounded-full border border-border bg-background text-muted-foreground opacity-0 shadow-sm transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100\"\n >\n <IconX className=\"h-3 w-3\" />\n </button>\n <div className=\"max-w-[85%] rounded-lg bg-accent/50 px-3 py-2 text-sm leading-relaxed text-foreground/60 whitespace-pre-wrap break-words\">\n {displayText}\n {msg.images && msg.images.length > 0 && (\n <div className=\"flex flex-wrap gap-1.5 mt-1.5\">\n {msg.images.map((img, j) => (\n <img\n key={j}\n src={img}\n alt=\"\"\n className=\"h-12 w-12 rounded object-cover border border-border/50\"\n />\n ))}\n </div>\n )}\n </div>\n </div>\n );\n })}\n </div>\n )}\n </div>\n\n {/* Scroll to bottom button */}\n {showScrollToBottom && (\n <div className=\"shrink-0 flex justify-center -mb-1\">\n <button\n type=\"button\"\n onClick={scrollToBottom}\n className=\"flex h-7 w-7 items-center justify-center rounded-full border border-border bg-background shadow-sm hover:bg-accent\"\n aria-label=\"Scroll to bottom\"\n >\n <IconChevronDown className=\"h-3.5 w-3.5 text-muted-foreground\" />\n </button>\n </div>\n )}\n\n {showComposerSlot ? composerSlot : null}\n {guidedQuestions && guidedQuestions.length > 0 && (\n <div className=\"shrink-0 px-3 pb-2 pt-1\">\n <div className=\"rounded-lg border border-border bg-card/60 shadow-sm\">\n <GuidedQuestionFlow\n questions={guidedQuestions}\n onSubmit={handleGuidedQuestionsSubmit}\n onSkip={handleGuidedQuestionsSkip}\n {...(guidedQuestionsTitle\n ? { title: guidedQuestionsTitle }\n : {})}\n {...(guidedQuestionsDescription\n ? { description: guidedQuestionsDescription }\n : {})}\n {...(guidedQuestionsSkipLabel\n ? { skipLabel: guidedQuestionsSkipLabel }\n : {})}\n {...(guidedQuestionsSubmitLabel\n ? { submitLabel: guidedQuestionsSubmitLabel }\n : {})}\n className=\"h-auto items-stretch justify-stretch bg-transparent\"\n />\n </div>\n </div>\n )}\n {showPlanModeCallout && (\n <PlanModeCallout\n canImplementPlan={canImplementPlan}\n onImplementPlan={handleImplementPlan}\n onSwitchToAct={handleSwitchToAct}\n />\n )}\n <SelectionAttachedPill />\n {/* Inline attachment / body-size error */}\n {composerError && (\n <div\n role=\"alert\"\n className=\"shrink-0 mx-3 mb-1.5 flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive\"\n >\n <IconAlertTriangle className=\"h-3.5 w-3.5 mt-0.5 shrink-0\" />\n <span className=\"flex-1 leading-snug\">{composerError}</span>\n <button\n type=\"button\"\n aria-label=\"Dismiss error\"\n onClick={() => setComposerError(null)}\n className=\"shrink-0 opacity-70 hover:opacity-100\"\n >\n <IconX className=\"h-3 w-3\" />\n </button>\n </div>\n )}\n {/* Input area */}\n <AgentComposerFrame\n layoutVariant={composerLayoutVariant}\n className={cn(\n composerAreaClassName,\n missingApiKey && \"cursor-pointer\",\n isComposerDisabled && \"opacity-70\",\n )}\n onClick={\n missingApiKey\n ? () => setMissingKeyBouncePulse((p) => p + 1)\n : undefined\n }\n >\n <ComposerAttachmentPreviewStrip />\n <TiptapComposer\n focusRef={tiptapRef}\n disabled={isComposerDisabled}\n placeholder={\n missingApiKey\n ? \"Connect AI below to start chatting...\"\n : composerDisabled\n ? (composerDisabledPlaceholder ??\n \"Open Desktop to use this chat.\")\n : isRunning\n ? queuedMessages.length > 0\n ? `${queuedMessages.length} queued — send a follow-up...`\n : \"Send a follow-up...\"\n : composerPlaceholder\n }\n onSubmit={\n isRunning || composerContextItems.length > 0\n ? (text, references, attachments, options) =>\n void addToQueue(\n text,\n undefined,\n references.length > 0 ? references : undefined,\n attachments,\n undefined,\n resolveAssistantChatSubmitIntent({\n isRunning,\n requestedIntent: options?.intent,\n }),\n undefined,\n true,\n )\n : undefined\n }\n onSlashCommand={onSlashCommand}\n execMode={execMode}\n onExecModeChange={onExecModeChange}\n planModeDisabled={planModeDisabled}\n planModeDisabledReason={planModeDisabledReason}\n selectedModel={selectedModel ?? defaultModel}\n selectedEffort={selectedEffort}\n availableModels={availableModels}\n onModelChange={onModelChange}\n onEffortChange={onEffortChange}\n onConnectProvider={onConnectProvider}\n toolbarSlot={composerToolbarSlot}\n contextItems={composerContextItems}\n onRemoveContextItem={removeComposerContextItem}\n plusMenuMode={plusMenuMode}\n layoutVariant={composerLayoutVariant}\n providerConnectStatusEnabled={providerStatusChecksEnabled}\n draftScope={threadId || tabId}\n interceptBuildRequestsForBuilder\n onAttachmentError={setComposerError}\n extraActionButton={\n contextXRayEnabled ||\n composerExtraActionButton ||\n showRunningInUI ? (\n <>\n {contextXRayEnabled && (\n <ContextMeter threadId={threadId} />\n )}\n {composerExtraActionButton}\n {showRunningInUI && (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n onClick={stopActiveRun}\n className=\"shrink-0 flex h-7 w-7 items-center justify-center rounded-md bg-muted text-foreground hover:bg-muted/80\"\n >\n <IconPlayerStop className=\"h-3.5 w-3.5\" />\n </button>\n </TooltipTrigger>\n <TooltipContent>Stop generating</TooltipContent>\n </Tooltip>\n )}\n </>\n ) : undefined\n }\n />\n </AgentComposerFrame>\n {missingApiKey && !authError ? (\n <BuilderSetupCard\n onConnected={handleBuilderConnected}\n bouncePulse={missingKeyBouncePulse}\n />\n ) : null}\n </div>\n </TextStreamingContext.Provider>\n </ChatRunningContext.Provider>\n </ApprovalContext.Provider>\n </MessageActionsContext.Provider>\n </CheckpointContext.Provider>\n );\n});\n\nexport const AssistantChat = forwardRef<\n AssistantChatHandle,\n AssistantChatProps\n>(function AssistantChat(\n {\n apiUrl = agentNativePath(\"/_agent-native/agent-chat\"),\n tabId,\n browserTabId,\n threadId,\n contextScope,\n isActiveComposer,\n ...props\n },\n ref,\n) {\n const modelRef = useRef<string | undefined>(props.selectedModel);\n modelRef.current = props.selectedModel;\n const engineRef = useRef<string | undefined>(props.selectedEngine);\n engineRef.current = props.selectedEngine;\n const effortRef = useRef<ReasoningEffort | undefined>(props.selectedEffort);\n effortRef.current = props.selectedEffort;\n const execModeRef = useRef<\"build\" | \"plan\" | undefined>(props.execMode);\n execModeRef.current = props.execMode;\n const scopeRef = useRef<ChatThreadScope | null | undefined>(contextScope);\n scopeRef.current = contextScope;\n const surface = props.agentChatSurface ?? \"app\";\n const createAdapterRef = useRef(props.createAdapter);\n createAdapterRef.current = props.createAdapter;\n const runtimeRef = useRef(props.runtime);\n runtimeRef.current = props.runtime;\n\n const adapter = useMemo(\n () => {\n const context: AssistantChatAdapterContext = {\n apiUrl,\n tabId,\n threadId,\n modelRef,\n engineRef,\n effortRef,\n execModeRef,\n browserTabId,\n scopeRef,\n surface,\n };\n const createAdapter = createAdapterRef.current;\n if (createAdapter) return createAdapter(context);\n const runtime = runtimeRef.current;\n if (runtime) {\n return createAgentChatRuntimeAdapter(runtime, {\n sessionId: threadId ?? tabId,\n threadId,\n modelRef,\n effortRef,\n });\n }\n return createAgentChatAdapter(context);\n },\n // Adapter factories must be memoized and use refs for changing values.\n // `adapterReloadKey` is an explicit opt-in for embedded hosts whose\n // transport identity can change without changing tab/thread ids.\n [\n apiUrl,\n tabId,\n threadId,\n browserTabId,\n surface,\n props.runtime,\n props.adapterReloadKey,\n ],\n );\n const attachmentAdapter = useMemo(\n () =>\n new CompositeAttachmentAdapter([\n new DownscalingImageAttachmentAdapter(),\n new BinaryDocumentAttachmentAdapter(),\n new TextAttachmentAdapter(),\n ]),\n [],\n );\n const runtime = useLocalRuntime(adapter, {\n adapters: { attachments: attachmentAdapter },\n });\n\n return (\n <AssistantRuntimeProvider runtime={runtime}>\n <TooltipProvider delayDuration={200}>\n <ThreadPrimitive.Root className=\"flex flex-1 flex-col h-full min-h-0 overflow-x-hidden\">\n <AssistantUiStaleIndexErrorBoundary\n resetKey={`${tabId ?? \"\"}:${threadId ?? \"\"}`}\n componentName=\"AssistantChat\"\n >\n <AssistantChatInner\n ref={ref}\n {...props}\n browserTabId={browserTabId}\n contextScope={contextScope}\n isActiveComposer={isActiveComposer}\n apiUrl={apiUrl}\n tabId={tabId}\n threadId={threadId}\n />\n </AssistantUiStaleIndexErrorBoundary>\n </ThreadPrimitive.Root>\n </TooltipProvider>\n </AssistantRuntimeProvider>\n );\n});\n"]}
|