@mgamadeus/ddd-agents 0.16.1 → 0.17.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/README.md +111 -8
- package/boundary.json +15 -1
- package/dist/admin-chat-widgets.js +158 -0
- package/dist/admin-chat-widgets.js.map +1 -0
- package/dist/admin.js +90 -63
- package/dist/admin.js.map +1 -1
- package/dist/chat.js +16 -16
- package/dist/chat.js.map +1 -1
- package/dist/chunks/AgentScheduleOrderDraftPanel-DM6pz_hc.js +304 -0
- package/dist/chunks/AgentScheduleOrderDraftPanel-DM6pz_hc.js.map +1 -0
- package/dist/chunks/{ConversationMarkdown-DNQcVuz-.js → ConversationMarkdown-W8NzeAT1.js} +5 -5
- package/dist/chunks/{ConversationMarkdown-DNQcVuz-.js.map → ConversationMarkdown-W8NzeAT1.js.map} +1 -1
- package/dist/chunks/{ConversationMessageInputComposerWidgets-BlpIule7.js → ConversationMessageInputComposerWidgets-BH7axorv.js} +6 -6
- package/dist/chunks/{ConversationMessageInputComposerWidgets-BlpIule7.js.map → ConversationMessageInputComposerWidgets-BH7axorv.js.map} +1 -1
- package/dist/chunks/{VoiceBarsIcon-eODB_UTI.js → VoiceBarsIcon-CT2HQSBH.js} +4 -4
- package/dist/chunks/{VoiceBarsIcon-eODB_UTI.js.map → VoiceBarsIcon-CT2HQSBH.js.map} +1 -1
- package/dist/chunks/{WebSearchResultsConversationWidget-l9Aek_lG.js → WebSearchResultsConversationWidget-BM624Fcx.js} +71 -62
- package/dist/chunks/WebSearchResultsConversationWidget-BM624Fcx.js.map +1 -0
- package/dist/chunks/{agents-http-trace-mappers-rsbGAf2_.js → agents-http-trace-mappers-CuGZOFu-.js} +53 -14
- package/dist/chunks/agents-http-trace-mappers-CuGZOFu-.js.map +1 -0
- package/dist/chunks/{browser-request-interception-D678IemW.js → browser-request-interception-BnOQWLaJ.js} +2 -2
- package/dist/chunks/{browser-request-interception-D678IemW.js.map → browser-request-interception-BnOQWLaJ.js.map} +1 -1
- package/dist/chunks/{canvas-label-context-C1Pc_Ldo.js → canvas-label-context-BKRsrpye.js} +3 -3
- package/dist/chunks/{canvas-label-context-C1Pc_Ldo.js.map → canvas-label-context-BKRsrpye.js.map} +1 -1
- package/dist/chunks/{canvas-reducers-BYArW_Ji.js → canvas-reducers-CZaOPvdt.js} +2 -2
- package/dist/chunks/{canvas-reducers-BYArW_Ji.js.map → canvas-reducers-CZaOPvdt.js.map} +1 -1
- package/dist/chunks/{canvasBodies-BpLPp-S8.js → canvasBodies-CMqo5eHg.js} +4 -4
- package/dist/chunks/{canvasBodies-BpLPp-S8.js.map → canvasBodies-CMqo5eHg.js.map} +1 -1
- package/dist/chunks/{canvasStorage-DSspwRMg.js → canvasStorage-ceJ7yaBd.js} +2 -2
- package/dist/chunks/{canvasStorage-DSspwRMg.js.map → canvasStorage-ceJ7yaBd.js.map} +1 -1
- package/dist/chunks/{content-from-unified-diff-DWyBHRSy.js → content-from-unified-diff-BKdgop63.js} +39 -5
- package/dist/chunks/content-from-unified-diff-BKdgop63.js.map +1 -0
- package/dist/chunks/{contract-DtFmOk91.js → contract-CQ6PO_e8.js} +2 -2
- package/dist/chunks/{contract-DtFmOk91.js.map → contract-CQ6PO_e8.js.map} +1 -1
- package/dist/chunks/{conversation-Cbrqtx-_.js → conversation-VosmRbsr.js} +4 -2
- package/dist/chunks/{conversation-Cbrqtx-_.js.map → conversation-VosmRbsr.js.map} +1 -1
- package/dist/chunks/conversation-trace-fVeh6Lg6.js.map +1 -1
- package/dist/chunks/{widget-name-resolver-DXIE9JUr.js → conversationWidgetRegistry-BW-U_RvC.js} +810 -530
- package/dist/chunks/conversationWidgetRegistry-BW-U_RvC.js.map +1 -0
- package/dist/chunks/{index-DZovGMpG.js → index-DAEGct6X.js} +61 -61
- package/dist/chunks/index-DAEGct6X.js.map +1 -0
- package/dist/chunks/{link-navigation-a_sRfmsj.js → link-navigation-DQWyeNkx.js} +2 -2
- package/dist/chunks/{link-navigation-a_sRfmsj.js.map → link-navigation-DQWyeNkx.js.map} +1 -1
- package/dist/chunks/{withPollingChangeSubscription-Cz3Diolr.js → withPollingChangeSubscription-Ct8kjmlL.js} +19 -2
- package/dist/chunks/withPollingChangeSubscription-Ct8kjmlL.js.map +1 -0
- package/dist/client-testing.js +39 -5
- package/dist/client-testing.js.map +1 -1
- package/dist/client.js +43 -14
- package/dist/client.js.map +1 -1
- package/dist/contract.js +4 -3
- package/dist/files/i18n-keys.json +619 -15
- package/dist/files/widgets/DriveFilesConversationWidget/DriveFilesConversationWidget.md +4 -2
- package/dist/files/widgets/OwnerStepConfirmationConversationWidget/OwnerStepConfirmationConversationWidget.md +54 -0
- package/dist/files/widgets/OwnerStepConfirmationConversationWidget/owner-step-confirmation.preview-fixtures.json +16 -0
- package/dist/image-render.js +8 -8
- package/dist/index.js +16 -16
- package/dist/kit.js +2 -2
- package/dist/preview.js +124 -117
- package/dist/preview.js.map +1 -1
- package/dist/provider.js +2 -2
- package/dist/renderer.js +53 -52
- package/dist/styles.css +46 -0
- package/dist/types/admin/schedules/AgentScheduleOrderDraftPanel.d.ts +45 -0
- package/dist/types/admin/schedules/AgentSchedulesPanel.d.ts +11 -3
- package/dist/types/admin/schedules/agent-schedules-api.d.ts +38 -2
- package/dist/types/admin/schedules/agent-schedules-format.d.ts +22 -1
- package/dist/types/admin/schedules/agent-schedules-types.d.ts +91 -1
- package/dist/types/admin-chat-widgets/ScheduleOrderApprovalConversationWidget.d.ts +37 -0
- package/dist/types/admin-chat-widgets/registerScheduleOrderApprovalWidget.d.ts +11 -0
- package/dist/types/chat/trace/TurnMetaLine.d.ts +5 -3
- package/dist/types/chat/trace/trace-counts.d.ts +2 -0
- package/dist/types/chat/trace/trace-types.d.ts +4 -0
- package/dist/types/client/AgentsConversationClient.d.ts +17 -1
- package/dist/types/client/http/agents-http-mappers.d.ts +4 -2
- package/dist/types/client/http/agents-http-trace-wire.d.ts +2 -0
- package/dist/types/client/http/agents-http-wire.d.ts +24 -0
- package/dist/types/client/testing/createInMemoryAgentsConversationClient.d.ts +13 -1
- package/dist/types/contract/conversation-trace.d.ts +4 -0
- package/dist/types/contract/conversation.d.ts +43 -0
- package/dist/types/entries/admin-chat-widgets.d.ts +2 -0
- package/dist/types/entries/admin.d.ts +4 -2
- package/dist/types/entries/renderer.d.ts +1 -1
- package/dist/types/renderer/widget-tree/composed-node-schema.d.ts +20 -3
- package/dist/types/widgets/DriveFilesConversationWidget/shared/drive-files.d.ts +3 -1
- package/dist/voice.js +2 -2
- package/dist/widgets.js +4 -4
- package/package.json +7 -1
- package/public-api.json +39 -0
- package/dist/chunks/WebSearchResultsConversationWidget-l9Aek_lG.js.map +0 -1
- package/dist/chunks/agents-http-trace-mappers-rsbGAf2_.js.map +0 -1
- package/dist/chunks/content-from-unified-diff-DWyBHRSy.js.map +0 -1
- package/dist/chunks/index-DZovGMpG.js.map +0 -1
- package/dist/chunks/widget-name-resolver-DXIE9JUr.js.map +0 -1
- package/dist/chunks/withPollingChangeSubscription-Cz3Diolr.js.map +0 -1
package/dist/chat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.js","sources":["../src/chat/AgentChatActivityHistory/AgentChatActivityHistory.tsx","../src/chat/AgentChatActivityDots/AgentChatActivityDots.tsx","../src/chat/AgentChatActivityIndicator/AgentChatActivityIndicator.tsx","../src/chat/ConversationClosedBar/ConversationClosedBar.tsx","../src/renderer/canvas/CanvasRestoreOnMount.tsx","../src/renderer/ConversationDeepLinkedWidget.tsx","../src/chat/ConversationMessageInput/ConversationMessageInput.tsx","../src/chat/ConversationLoadingStates.tsx","../src/renderer/markdown-contains-widget.ts","../src/chat/assistant-message-has-renderable-markdown.ts","../src/chat/ConversationMessage/ConversationMessageSystem/ConversationMessageSystemHeader/ConversationMessageSystemHeader.tsx","../src/chat/ConversationMessage/ConversationMessageSystem/ConversationMessageSystem.tsx","../src/chat/controller/turn-initiators.ts","../src/chat/ConversationMessageList/message-times.ts","../src/chat/ConversationMessage/ConversationCallMarkerChip/ConversationCallMarkerChip.tsx","../src/chat/ConversationMessage/ConversationTaskInstructionDisclosure/ConversationTaskInstructionDisclosure.tsx","../src/chat/ConversationMessage/ConversationMessageWidgets/ConversationMessageThinking/ConversationMessageThinking.tsx","../src/chat/ConversationErrorWidget/ConversationErrorWidget.tsx","../src/chat/ConversationMessageList/ConversationMessageList.tsx","../src/chat/ConversationSuggestionWidget/ConversationSuggestionWidget.tsx","../src/chat/ConversationIntroWidget/ConversationIntroWidget.tsx","../src/chat/ConversationScrollToLatestMessageButton/ConversationScrollToLatestMessageButton.tsx","../src/chat/ConversationViewBody/hooks/useIsMessagesBottomOutOfView.ts","../src/chat/ConversationViewBody/hooks/usePinQuestionOnSend.ts","../src/chat/ConversationViewBody/ConversationViewBody.tsx","../src/chat/canvas-layout.ts","../src/chat/CanvasPane/CanvasPane.tsx","../src/chat/CanvasResizeHandle/use-canvas-resize.ts","../src/chat/CanvasResizeHandle/CanvasResizeHandle.tsx","../src/chat/use-canvas-shell-transitions.ts","../src/chat/ConversationView.tsx","../src/chat/controller/merge-activity-elements.ts","../src/chat/controller/activity-ticker.ts","../src/chat/controller/use-activity-ticker.ts","../src/chat/controller/use-conversation-activity.ts","../src/chat/controller/chat-activity-timing.ts","../src/chat/controller/pending-start-request.ts","../src/chat/controller/conversation-change-signal-rules.ts","../src/chat/controller/use-conversation-live-updates.ts","../src/chat/controller/use-conversation-message-pages.ts","../src/chat/trace/running-background-jobs-context.ts","../src/chat/trace/QueuedMessageChip.tsx","../src/chat/controller/use-conversation-scroll-jump.ts","../src/renderer/detect-unrendered-widgets.ts","../src/chat/controller/use-conversation-signals.ts","../src/chat/controller/AgentChatController.tsx","../src/chat/AgentChat/AgentChat.tsx","../src/chat/trace/BackgroundTasksList.tsx","../src/chat/trace/ChangedFilesPane.tsx","../src/chat/trace/ChangeSetCard.tsx","../src/chat/trace/ChangedRecordsList.tsx","../src/chat/trace/ContextRing.tsx","../src/chat/trace/conversation-trace-loader.ts","../src/chat/trace/use-conversation-trace.ts","../src/chat/trace/ConversationChildTrace.tsx","../src/chat/trace/ConsentRequestCard.tsx","../src/chat/trace/RunningBackgroundJobLines.tsx","../src/chat/trace/RunStatusLine.tsx","../src/chat/trace/ConversationTurnTrace.tsx","../src/chat/trace/task-plan-tree.ts","../src/chat/trace/TaskPlanDrawer.tsx","../src/chat/trace/TaskPlanPane.tsx","../src/chat/trace/trace-step-focus.ts","../src/chat/trace/trace-collect.ts","../src/chat/AgentChatActivityStack/AgentChatActivityStack.tsx","../src/chat/controller/use-debounced-semantic-search.ts","../src/chat/controller/use-conversation-search.ts","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/ConversationMessageInputAttachmentsErrorBox.tsx","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/convert-bytes-to-size-string.ts","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/ConversationMessageInputAttachmentPreviewWidget.tsx","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/ConversationMessageInputAttachmentsPreviewStrip.tsx"],"sourcesContent":["import { Text } from \"../../provider/components\";\nimport type { AgentChatActivityHistoryProps } from \"../controller/AgentChatController\";\nimport styles from \"./AgentChatActivityHistory.module.scss\";\n\n/**\n * The package default of a finished turn's kept activity lines under the message that started the turn (`AgentChat`\n * with `keepActivityHistoryAfterAnswer`): one muted line per step, oldest first.\n */\nexport const AgentChatActivityHistory = (props: AgentChatActivityHistoryProps) => {\n const { turn } = props;\n if (turn === null || turn.lines.length === 0) return null;\n return (\n <div className={styles.history} data-testid=\"agent-chat-activity-history\">\n {turn.lines.map((line) => (\n <Text key={`${line.toolCallMessageId}-${line.state}`} role=\"help\" color=\"--agents-fg-light\" translate={false}>\n {line.line}\n </Text>\n ))}\n </div>\n );\n};\n","import { classNames } from \"../../provider/class-names\";\nimport styles from \"./AgentChatActivityDots.module.scss\";\n\n/** How the three dots move: `bounce` hops them in turn (the indicator's default); `pulse` only fades and grows them, calmly. */\nexport type AgentChatActivityDotsVariant = \"bounce\" | \"pulse\";\n\nexport interface AgentChatActivityDotsProps {\n /** Default `bounce`. */\n variant?: AgentChatActivityDotsVariant;\n}\n\n/**\n * The three working dots of the activity components, decorative (`aria-hidden`). Coloured by `--agents-fg-light`;\n * still under `prefers-reduced-motion`.\n */\nexport const AgentChatActivityDots = ({ variant = \"bounce\" }: AgentChatActivityDotsProps) => (\n <div\n className={classNames(styles.dots, variant === \"pulse\" ? styles.pulse : styles.bounce)}\n aria-hidden=\"true\"\n data-agents-activity-dots={variant}\n >\n <span />\n <span />\n <span />\n </div>\n);\n","import { Text } from \"../../provider/components\";\nimport { AgentChatActivityDots, type AgentChatActivityDotsVariant } from \"../AgentChatActivityDots/AgentChatActivityDots\";\nimport type { AgentChatActivityProps } from \"../controller/AgentChatController\";\nimport styles from \"./AgentChatActivityIndicator.module.scss\";\n\nexport interface AgentChatActivityIndicatorProps extends AgentChatActivityProps {\n /** How the dots move: `bounce` (the default) or the calm `pulse`. */\n dotsVariant?: AgentChatActivityDotsVariant;\n}\n\n/**\n * The package default of the agent's activity at the tail of the thread (`AgentChat`'s `ThinkingIndicator`): three\n * dots and the line the activity ticker shows right now — the step the agent works on — while a turn runs; nothing\n * between turns or after a failed one (the error card speaks then). An app with an agent avatar replaces it\n * (host application: the agent's face beside the same ticker lines). `AgentChatActivityStack` is the stacked feed.\n */\nexport const AgentChatActivityIndicator = (props: AgentChatActivityIndicatorProps) => {\n const { active, failed, activityTicker, dotsVariant = \"bounce\" } = props;\n const isWorking = !failed && (active || activityTicker.phase === \"live\");\n if (!isWorking) return null;\n const currentLines = activityTicker.currentTurn?.lines ?? [];\n const currentLine = currentLines.length > 0 ? currentLines[currentLines.length - 1].line : null;\n return (\n <div className={styles.activity} role=\"status\" aria-live=\"polite\" data-testid=\"agent-chat-activity\">\n <AgentChatActivityDots variant={dotsVariant} />\n {currentLine !== null ? (\n <Text role=\"help\" color=\"--agents-fg-light\" translate={false}>\n {currentLine}\n </Text>\n ) : (\n <Text role=\"help\" color=\"--agents-fg-light\">\n Working on it…\n </Text>\n )}\n </div>\n );\n};\n","import { Icon, Text } from \"../../provider/components\";\nimport styles from \"./ConversationClosedBar.module.scss\";\n\nexport interface ConversationClosedBarProps {\n /** The status line; a text key. Default \"This conversation is closed.\". */\n text?: string;\n}\n\n/**\n * The package default in place of the composer on a closed conversation (its run state ended it: COMPLETED or\n * CANCELLED; the server refuses further input). A status line, no action — an app that offers one replaces the bar\n * through `AgentChat`'s `inputReplacementSlot`.\n */\nexport const ConversationClosedBar = (props: ConversationClosedBarProps) => {\n const { text = \"This conversation is closed.\" } = props;\n return (\n <div className={styles.bar} data-testid=\"agent-chat-closed-bar\">\n <Icon name=\"check\" color=\"--agents-success-500\" />\n <Text>{text}</Text>\n </div>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport type { ChatMessage } from \"../../chat/chat-message\";\nimport { normalizeServerMessageToMarkdown } from \"../../chat/normalize-server-message-to-markdown\";\nimport { useConversationWidgetContext } from \"../ConversationWidgetCallbacksContext\";\nimport { conversationWidgetRegistry } from \"../conversationWidgetRegistry\";\nimport { canvasBehaviourOf, canvasKindOpenerWidgetNamesOf } from \"./canvas-behaviours\";\nimport { payloadHashOfInstanceId } from \"./canvas-state\";\nimport { StoredCanvasPointer, clearStoredCanvas, readStoredCanvas } from \"./canvasStorage\";\nimport { findWidgetFencesInMarkdown } from \"./find-widget-fences-in-markdown\";\n\nexport interface CanvasRestoreOnMountProps {\n /** The conversation the host shows. Undefined for a cold chat — nothing to restore. */\n conversationId?: number;\n /** The host's loaded messages. A message-anchored restore waits for THIS conversation's page to be in. */\n messages: ChatMessage[] | null;\n}\n\n/** Does the anchor message still carry a widget that opens this canvas — the same instance, when the id names one? */\nconst anchorMessageCarriesCanvasWidget = (\n pointer: StoredCanvasPointer,\n anchorMessage: ChatMessage,\n): boolean => {\n // The openers the widget registry declares (`opensCanvases`) and those a registered canvas kind names itself.\n const openers = new Set([\n ...conversationWidgetRegistry.widgets\n .filter((entry) => entry.opensCanvases?.includes(pointer.canvasId))\n .map((entry) => entry.name),\n ...canvasKindOpenerWidgetNamesOf(pointer.canvasId),\n ]);\n if (openers.size === 0) return false;\n const payloadHash = payloadHashOfInstanceId(pointer.instanceId);\n return findWidgetFencesInMarkdown(normalizeServerMessageToMarkdown(anchorMessage.message)).some(\n (fence) => openers.has(fence.name) && (payloadHash === undefined || fence.payloadHash === payloadHash),\n );\n};\n\n/**\n * Restores the canvas that was open in this conversation — on a reload, in a new tab, and when the customer comes\n * back to the conversation (A → B → A alike). Must render INSIDE the provider (it dispatches\n * through the context) and runs once per conversation, after the mount reset. A PAGE-anchored canvas (an app's\n * editor opened from a page) needs no message and restores as soon as the conversation id is known. A MESSAGE-anchored\n * canvas waits for the conversation's own messages and has three limits:\n * - the anchor message must be in the loaded page — otherwise the canvas is that far back and irrelevant: the pointer\n * is dropped, nothing is paged in;\n * - a `turn` canvas whose anchor message is no longer the newest assistant message is not restored — its turn is over;\n * - the anchor message must still carry a widget that opens this canvas (a stale or mangled pointer opens nothing).\n */\nexport const CanvasRestoreOnMount = ({ conversationId, messages }: CanvasRestoreOnMountProps) => {\n const { openCanvas } = useConversationWidgetContext();\n const restoredForConversationIdRef = useRef<number | undefined>(undefined);\n\n useEffect(() => {\n if (conversationId === undefined || restoredForConversationIdRef.current === conversationId) return;\n const pointer = readStoredCanvas(conversationId);\n if (pointer === null) {\n restoredForConversationIdRef.current = conversationId;\n return;\n }\n\n const restore = () =>\n openCanvas({\n canvasId: pointer.canvasId,\n instanceId: pointer.instanceId,\n anchor: pointer.anchor,\n origin: \"restoredAfterReload\",\n justDelivered: false,\n ...(pointer.createdEntityId !== undefined ? { createdEntityId: pointer.createdEntityId } : {}),\n });\n\n if (pointer.anchor.kind === \"page\") {\n restoredForConversationIdRef.current = conversationId;\n restore();\n return;\n }\n\n // Right after a switch the slice still holds the PREVIOUS conversation's messages for a beat — wait until the\n // list belongs to this conversation, or the anchor checks would read the wrong transcript.\n if (messages === null || !messages.some((message) => message.conversationId === conversationId)) return;\n restoredForConversationIdRef.current = conversationId;\n\n const anchorMessageId = pointer.anchor.messageId;\n const anchorMessage = messages.find((message) => message.id === anchorMessageId);\n const newestAssistantMessage = [...messages].reverse().find((message) => message.role === \"ASSISTANT\");\n const turnIsOver =\n canvasBehaviourOf(pointer.canvasId)?.lifetime === \"turn\" && newestAssistantMessage?.id !== anchorMessageId;\n if (anchorMessage === undefined || turnIsOver || !anchorMessageCarriesCanvasWidget(pointer, anchorMessage)) {\n clearStoredCanvas(conversationId);\n return;\n }\n restore();\n }, [conversationId, messages, openCanvas]);\n\n return null;\n};\n","import React, { useMemo } from \"react\";\nimport { resolveDeepLinkableWidget } from \"./resolve-deep-linkable-widget\";\nimport { ConversationWidgetFeatureGate } from \"./_access/ConversationWidgetFeatureGate\";\nimport { ConversationWidgetErrorBoundary } from \"./ConversationWidgetErrorBoundary\";\nimport { buildWidgetAgentSpaceKeyProps } from \"./_agent-space/widget-agent-space-key-attribute\";\n\nexport interface ConversationDeepLinkedWidgetProps {\n /** Canonical registry wire name, from `?agentWidget=` or a restored pinned canvas. Unknown / not deep-linkable → nothing renders. */\n widgetName?: string;\n /** The key of the chat's agent space, forwarded to the widget exactly as a markdown attribute would carry it. */\n agentSpaceKey?: number;\n}\n\n/**\n * Mounts ONE registered widget outside the message list — the customer opened it from a page (`?agentWidget=`). The\n * widget receives `openedByPage` (plus `interactive` / `justDelivered`), so a canvas-opening widget (an app's editor\n * widget, `ExampleWidget`) opens its canvas with origin `openedByPage` and a page anchor; nothing is written to the\n * conversation, no message and no signal. (A canvas that was open before a reload comes back through\n * `CanvasRestoreOnMount`, not through this mount.)\n *\n * Rendered with the entry's feature gate and the shared error boundary, but WITHOUT the viewport windowing of\n * {@link ConversationWidgetHost}: there is no message to scroll past here, and a windowed wrapper would unmount a\n * zero-height widget (these widgets render `null` and live entirely in the canvas), taking its canvas with it.\n */\nexport const ConversationDeepLinkedWidget = ({ widgetName, agentSpaceKey }: ConversationDeepLinkedWidgetProps) => {\n const entry = useMemo(() => resolveDeepLinkableWidget(widgetName), [widgetName]);\n if (!entry) return null;\n\n const { component: Component, featureFlag, upsellTrigger } = entry;\n const widget = <Component fresh interactive justDelivered openedByPage {...buildWidgetAgentSpaceKeyProps(agentSpaceKey)} />;\n\n return (\n <ConversationWidgetErrorBoundary widgetName={entry.name}>\n {featureFlag ? (\n <ConversationWidgetFeatureGate\n featureFlag={featureFlag}\n UpsellTrigger={upsellTrigger}\n agentSpaceKeyAttribute={agentSpaceKey}\n >\n {widget}\n </ConversationWidgetFeatureGate>\n ) : (\n widget\n )}\n </ConversationWidgetErrorBoundary>\n );\n};\n","import { Button, GlowFrame, Text, Tooltip } from \"../../provider/components\";\nimport React, {\n useRef,\n useState,\n KeyboardEvent,\n useEffect,\n useImperativeHandle,\n useLayoutEffect,\n useMemo,\n} from \"react\";\nimport styles from \"./ConversationMessageInput.module.scss\";\nimport type { ConversationAttachmentReference } from \"../../contract/conversation\";\nimport { SendMessageHandler } from \"../conversation-send-message\";\nimport { useAgentsTexts } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport { ConversationComposerWidget } from \"../../renderer/conversation-composer-widget\";\nimport { buildMessageTextWithComposerWidgets } from \"../../renderer/composer-widget-fence\";\nimport { conversationWidgetRegistry } from \"../../renderer/conversationWidgetRegistry\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetContext\";\n\n// Half the one-line compact input (8px padding + the 40px send row + 8px): fully round at rest, and the same corners\n// as it grows with the text. The glow and the input share it through --ai-border-radius.\nconst COMPACT_INPUT_RADIUS_PX = 28;\n\n/**\n * Cap on the message a user can send. Covers the longest legitimate business\n * inputs (pasted homepage copy, article drafts, menus ≈ 8k chars) while blocking\n * accidental huge dumps. Typing and pasting past it stay possible — the text is\n * never trimmed — but sending is blocked until the user edits back under the cap.\n */\nexport const MAX_MESSAGE_LENGTH = 10000;\n\n/** The character counter stays hidden until the message approaches the cap. */\nexport const CHARACTER_COUNTER_SHOWN_FROM_LENGTH = Math.floor(MAX_MESSAGE_LENGTH * 0.9);\n\n/**\n * Imperative handle so a host-owned control (e.g. the agent \"+\" menu's \"Generate image\" entry)\n * can put text into the input without owning the contentEditable itself.\n */\nexport interface ConversationMessageInputHandle {\n /** Replaces the input's text and focuses the caret at the end. */\n insertTextIntoInput: (text: string) => void;\n /** Focuses the input, the caret at the end of its text (e.g. after files were dropped on the chat). */\n focusInput?: () => void;\n}\n\nexport interface ConversationMessageInputProps {\n /**\n * Callback when a message is submitted. The text already carries every outgoing composer widget's fence;\n * `options.composerWidgets` lists the same widgets (`outgoingComposerWidgets`, then `hostComposerWidgets`).\n */\n onSendMessage?: SendMessageHandler;\n\n /**\n * Placeholder text for the input\n */\n placeholder?: string;\n\n /**\n * Whether the input is disabled\n */\n disabled?: boolean;\n\n /**\n * Theme color for the input\n */\n themeColor?: string;\n\n /**\n * One-line form: text and send button on the same row inside a pill, growing with the text. The agent dashboard's\n * input; the chat keeps the full form.\n */\n compact?: boolean;\n\n /**\n * The compact form only: the top slot takes a row of its own above the text and the start cluster stands left of the\n * text instead of in the action row. Default false: the compact layout keeps both where the full form has them.\n */\n compactStackedSlots?: boolean;\n\n /**\n * Compact only: shrunk to a small glowing pill showing one line, the placeholder or the start of a draft, its buttons\n * hidden but kept (the agent dashboard while the page is scrolled). The host expands it again on hover, focus or at the\n * top of the page.\n */\n collapsed?: boolean;\n\n /**\n * Compact only: called with the width in px the collapsed pill needs to show the whole translated placeholder on one\n * line, its side padding included, and again whenever that width changes (a font loading, another language). The\n * host gives the pill this width, so the placeholder fits in every language.\n */\n onCollapsedPillWidthChange?: (collapsedPillWidthPx: number) => void;\n\n /**\n * Whether the AI is currently processing a response\n */\n isProcessing?: boolean;\n\n /**\n * Test ID for the component\n */\n testId?: string;\n\n /**\n * Additional CSS classes to apply to the component\n */\n className?: string;\n\n /**\n * Additional CSS classes on the input's own box (the pill in the compact form), inside its glow. A host's decoration\n * drawn over the input (e.g. a host's file-drop ring) gets the input's exact size this way, and its\n * corners from `var(--ai-border-radius)`.\n */\n inputContainerClassName?: string;\n\n /**\n * Extra action controls rendered inside the input's bottom action row, left of the send button —\n * e.g. the agent model picker pill.\n */\n actionsSlot?: React.ReactNode;\n\n /**\n * Action controls pinned to the LEFT edge of the bottom action row (the `actionsSlot` cluster\n * stays right, next to the send button) — e.g. the agent \"+\" attachments menu. In the compact form with\n * `compactStackedSlots` they stand left of the text, on its row.\n */\n actionsSlotStart?: React.ReactNode;\n\n /**\n * Host-owned content rendered above the editable text area, inside the input container —\n * attachment preview cards, validation error boxes, selection chips. Each injected block owns\n * its reveal/collapse animation. In the compact form with `compactStackedSlots` it takes a row of its own above the\n * text.\n */\n topSlot?: React.ReactNode;\n\n /** Shown in place of the send button while there is nothing to send — e.g. the button that starts a voice chat. */\n sendReplacementWhenEmpty?: React.ReactNode;\n\n /** Painted behind the input, over its whole box — e.g. the voice glow of a running voice chat. */\n glowUnderlay?: React.ReactNode;\n\n /**\n * Hard send gate: blocks the send button AND Enter while true, but keeps the text editable\n * (unlike `disabled`/`isProcessing`). The host sets it e.g. while attachment uploads run.\n */\n sendDisabled?: boolean;\n\n /**\n * Uploaded media-library images that ride along in `onSendMessage`'s options object (`attachments`)\n * on the next send. Owned and cleared by the host; ConversationMessageInput only forwards them.\n */\n outgoingAttachmentImages?: ConversationAttachmentReference[];\n\n /**\n * Composer widgets the HOST holds outside the widget context (e.g. a widget built from the files the host uploaded\n * through its own control), sent exactly like `outgoingComposerWidgets`: their fences follow the\n * context's own in the message text and in `options.composerWidgets`. Owned and cleared by the host; Backspace never\n * touches them.\n */\n hostComposerWidgets?: ConversationComposerWidget[];\n\n /**\n * Composer widgets that ride along on the next send — mirrors `outgoingAttachmentImages`. On send their fences\n * are appended to the typed text (`buildMessageTextWithComposerWidgets`) and they ride along in `onSendMessage`'s\n * options object (`composerWidgets`); a widget-only send (empty typed text) is allowed. Backspace on an empty\n * input removes the last part / widget via the widget context directly (`useConversationWidgetContext`).\n */\n outgoingComposerWidgets?: ConversationComposerWidget[];\n\n /** Called right after a successful send — the host clears the composer widgets it owns. */\n onComposerWidgetsSent?: () => void;\n\n /** Imperative handle for host-owned controls to put text into the input. */\n apiRef?: React.Ref<ConversationMessageInputHandle>;\n}\n\nexport const ConversationMessageInput = (props: ConversationMessageInputProps) => {\n const {\n onSendMessage,\n placeholder = \"Ask anything\",\n disabled = false,\n isProcessing = false,\n testId = \"chat-input\",\n className,\n inputContainerClassName,\n actionsSlot,\n actionsSlotStart,\n topSlot,\n sendReplacementWhenEmpty,\n glowUnderlay,\n sendDisabled = false,\n outgoingAttachmentImages,\n hostComposerWidgets,\n outgoingComposerWidgets,\n onComposerWidgetsSent,\n apiRef,\n compact = false,\n compactStackedSlots = false,\n collapsed = false,\n onCollapsedPillWidthChange,\n } = props;\n\n const { removeComposerWidget, replaceComposerWidgetFields } = useConversationWidgetContext();\n\n const [inputValue, setInputValue] = useState(\"\");\n const inputRef = useRef<HTMLSpanElement>(null);\n const isComposingRef = useRef(false);\n // Through the texts of this subtree (an `AgentsProvider` environment's `texts`, else the app-wide ones).\n const texts = useAgentsTexts();\n const translatedPlaceholder = useMemo(() => texts.translate(placeholder), [texts, placeholder]);\n // The send button shows only an icon: its accessible name comes from the package's texts.\n const sendButtonAccessibleName = texts.translate(\"Send message\");\n const collapsedPillSizerRef = useRef<HTMLSpanElement>(null);\n const measuresCollapsedPillWidth = compact && !!onCollapsedPillWidthChange;\n const isCompactStacked = compact && compactStackedSlots;\n\n const isMessageTooLong = inputValue.length > MAX_MESSAGE_LENGTH;\n // Every composer widget the next send carries: the widget context's own, then the host's.\n const composerWidgetsToSend = [...(outgoingComposerWidgets ?? []), ...(hostComposerWidgets ?? [])];\n // Text OR at least one composer widget is enough to send (a fence-only message is allowed).\n const hasSendableContent = inputValue.trim() !== \"\" || composerWidgetsToSend.length > 0;\n\n const focusInputAtEnd = () => {\n if (!inputRef.current) return;\n inputRef.current.focus();\n const sel = window.getSelection();\n const range = document.createRange();\n range.selectNodeContents(inputRef.current);\n range.collapse(false);\n sel?.removeAllRanges();\n sel?.addRange(range);\n };\n\n const setInputText = (text: string) => {\n setInputValue(text);\n if (inputRef.current) {\n inputRef.current.textContent = text;\n focusInputAtEnd();\n }\n };\n\n useImperativeHandle(apiRef, () => ({ insertTextIntoInput: setInputText, focusInput: focusInputAtEnd }));\n\n const handleSendMessage = () => {\n const messageText = buildMessageTextWithComposerWidgets(inputValue, composerWidgetsToSend);\n if (!messageText || disabled || isProcessing || isMessageTooLong || sendDisabled) return;\n\n const accepted = onSendMessage?.(messageText, {\n attachments: outgoingAttachmentImages?.length ? outgoingAttachmentImages : undefined,\n composerWidgets: composerWidgetsToSend.length ? composerWidgetsToSend : undefined,\n });\n // A refused send (a closed conversation, a start still in flight) keeps the text and every composer widget.\n if (accepted === false) return;\n onComposerWidgetsSent?.();\n setInputValue(\"\");\n if (inputRef.current) {\n inputRef.current.textContent = \"\";\n }\n };\n\n // Backspace on an EMPTY input removes the last removable part of the last composer widget (declared via the\n // registry's `removeLastPartFromComposerWidgetFields`), or the whole widget when the entry omits it / nothing is\n // left. Mutates through the widget context directly — `outgoingComposerWidgets` only supplies the \"which\n // widget is last\" snapshot, mirroring the host-owned value ridden into the send.\n const handleBackspaceOnEmptyInput = () => {\n const widgets = outgoingComposerWidgets ?? [];\n const lastWidget = widgets[widgets.length - 1];\n if (!lastWidget) return;\n\n const entry = conversationWidgetRegistry.widgets.find((candidate) => candidate.name === lastWidget.widgetName);\n const removeLastPart = entry?.removeLastPartFromComposerWidgetFields;\n if (!removeLastPart) {\n removeComposerWidget(lastWidget.composerWidgetId);\n return;\n }\n const nextFields = removeLastPart(lastWidget.fields);\n if (nextFields === null) {\n removeComposerWidget(lastWidget.composerWidgetId);\n } else {\n replaceComposerWidgetFields(lastWidget.composerWidgetId, nextFields);\n }\n };\n\n const handleKeyPress = (e: KeyboardEvent) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n if (isComposingRef.current) return;\n e.preventDefault();\n handleSendMessage();\n return;\n }\n if (e.key === \"Backspace\" && inputValue === \"\" && (outgoingComposerWidgets?.length ?? 0) > 0) {\n e.preventDefault();\n handleBackspaceOnEmptyInput();\n }\n };\n\n const handleInput = () => {\n if (isComposingRef.current) return;\n if (!inputRef.current) return;\n setInputValue(inputRef.current.textContent || \"\");\n };\n\n const handleCompositionStart = () => {\n isComposingRef.current = true;\n };\n\n const handleCompositionEnd = () => {\n isComposingRef.current = false;\n handleInput();\n };\n\n const handleContainerMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {\n const target = e.target as HTMLElement;\n // Let clicks on the editable span itself fall through — browser positions the caret at the click point.\n if (target === inputRef.current || inputRef.current?.contains(target)) return;\n // Let clicks on buttons (send, any future action buttons) fall through untouched.\n if (target.closest(\"button\")) return;\n // Dead space click: redirect focus to end of input, but only when editing is allowed.\n if (disabled || isProcessing) return;\n e.preventDefault();\n focusInputAtEnd();\n };\n\n // Before the first paint, so the pill never shows at a width that cuts the placeholder off; again when the sizer's\n // text changes width.\n useLayoutEffect(() => {\n const collapsedPillSizer = collapsedPillSizerRef.current;\n if (!collapsedPillSizer || !onCollapsedPillWidthChange) return;\n const reportCollapsedPillWidth = () =>\n onCollapsedPillWidthChange(Math.ceil(collapsedPillSizer.getBoundingClientRect().width));\n reportCollapsedPillWidth();\n const resizeObserver = new ResizeObserver(reportCollapsedPillWidth);\n resizeObserver.observe(collapsedPillSizer);\n return () => resizeObserver.disconnect();\n }, [measuresCollapsedPillWidth, onCollapsedPillWidthChange]);\n\n const wasProcessingRef = useRef(isProcessing);\n useEffect(() => {\n if (wasProcessingRef.current && !isProcessing && !disabled) {\n inputRef.current?.focus();\n }\n wasProcessingRef.current = isProcessing;\n }, [isProcessing, disabled]);\n\n useEffect(() => {\n const handlePasteEvent = (e: ClipboardEvent) => {\n e.preventDefault();\n\n // Plain text (works across modern browsers)\n const text = e.clipboardData?.getData(\"text/plain\");\n\n if (!text) {\n return;\n }\n\n // Insert text at caret position\n if (document.queryCommandSupported?.(\"insertText\")) {\n document.execCommand(\"insertText\", false, text);\n } else {\n // Fallback for newer/stricter environments\n const sel = window.getSelection();\n if (!sel || sel.rangeCount === 0) return;\n sel.deleteFromDocument();\n sel.getRangeAt(0).insertNode(document.createTextNode(text));\n sel.collapseToEnd();\n }\n // The fallback path mutates the DOM directly and fires no input event,\n // so sync state explicitly (harmless duplicate after execCommand).\n setInputValue(inputRef.current?.textContent || \"\");\n };\n const currentInput = inputRef.current;\n currentInput?.addEventListener(\"paste\", handlePasteEvent);\n\n return () => {\n currentInput?.removeEventListener(\"paste\", handlePasteEvent);\n };\n }, []);\n\n return (\n <div className={className}>\n {glowUnderlay}\n {/* Without its own base the glow takes the inherited --ai-base-color: the agent's own base colour on an agent surface, the\n category colour in an AI-extension category conversation (ConversationViewBody), the theme's AI colour\n elsewhere. */}\n <GlowFrame\n className={classNames(styles.aiGlow)}\n color={isMessageTooLong ? \"var(--agents-danger-500)\" : undefined}\n borderRadius={compact ? COMPACT_INPUT_RADIUS_PX : undefined}\n borderWidth={2}\n blurWidth={6}\n >\n <div\n className={classNames(\n styles.inputContainer,\n {\n [styles.compact]: compact,\n [styles.compactStacked]: isCompactStacked,\n [styles.compactWithActionsStart]: isCompactStacked && !!actionsSlotStart,\n [styles.collapsed]: compact && collapsed,\n },\n inputContainerClassName,\n )}\n onMouseDown={handleContainerMouseDown}\n >\n {/* Stacked compact form: one flex row, the top slot wraps onto a row of its own above it, and the start\n cluster stands left of the text instead of in the action row. */}\n {isCompactStacked && !!topSlot && <div className={styles.compactTopSlot}>{topSlot}</div>}\n {!isCompactStacked && topSlot}\n {isCompactStacked && !!actionsSlotStart && (\n <div className={styles.compactActionsStart}>{actionsSlotStart}</div>\n )}\n <span\n ref={inputRef}\n contentEditable={!(disabled || isProcessing)}\n onInput={handleInput}\n onCompositionStart={handleCompositionStart}\n onCompositionEnd={handleCompositionEnd}\n onKeyDown={handleKeyPress}\n // The placeholder shows while the input is empty, focused or not: the chat focuses the input after every\n // turn, and a focused empty input without it read as a field without purpose.\n className={`${styles.editableInput} ${!inputValue ? styles.showPlaceholder : \"\"}`}\n data-placeholder={translatedPlaceholder}\n data-testid={`${testId}-textarea`}\n ></span>\n\n {/* Meta row above the actions: the character counter lives on its own line\n so it never crowds the send/attachment buttons on small screens. */}\n {inputValue.length >= CHARACTER_COUNTER_SHOWN_FROM_LENGTH && (\n <div className={styles.statusRow}>\n <Text\n role=\"caption\"\n translate={false}\n color={isMessageTooLong ? \"var(--agents-danger-500)\" : \"var(--agents-fg-lightest)\"}\n className={styles.characterCounter}\n testId={`${testId}-character-counter`}\n >\n {`${inputValue.length.toLocaleString()} / ${MAX_MESSAGE_LENGTH.toLocaleString()}`}\n </Text>\n </div>\n )}\n\n <div className={styles.actions}>\n {!isCompactStacked && !!actionsSlotStart && <div className={styles.actionsStart}>{actionsSlotStart}</div>}\n {/* <div className={styles.buttons}> */}\n {/* TODO: Implement emoji functionality */}\n {/* <Button\n type={ButtonTypes.muted}\n onClick={() => {\n }}\n testId={`${testId}-voice-button`}\n disabled={disabled || isProcessing}\n icon={IconNames.audioMicrophone}\n rounded\n /> */}\n {/* Over the cap: send is disabled and hovering it shows the popover with the\n reason. The wrapper carries the not-allowed cursor and routes hover past\n the disabled button to the popover (see .sendBlocked in the module scss). */}\n {actionsSlot}\n {sendReplacementWhenEmpty && !hasSendableContent ? (\n sendReplacementWhenEmpty\n ) : (\n <div className={classNames(styles.ownAction, { [styles.sendBlocked]: isMessageTooLong })}>\n <Tooltip\n text={isMessageTooLong ? \"Your message is over the %maxLength% character limit\" : undefined}\n replacements={{ maxLength: MAX_MESSAGE_LENGTH.toLocaleString() }}\n placement=\"top\"\n >\n <Button\n variant={\n hasSendableContent && !isMessageTooLong && !sendDisabled ? \"shimmer\" : \"muted\"\n }\n onClick={handleSendMessage}\n icon=\"arrowUp\"\n testId={`${testId}-send-button`}\n ariaLabel={sendButtonAccessibleName}\n disabled={!hasSendableContent || disabled || isProcessing || isMessageTooLong || sendDisabled}\n size={hasSendableContent && !isMessageTooLong && !sendDisabled ? \"medium\" : undefined}\n rounded\n />\n </Tooltip>\n </div>\n )}\n {/* </div> */}\n </div>\n </div>\n </GlowFrame>\n {measuresCollapsedPillWidth && (\n <span ref={collapsedPillSizerRef} className={styles.collapsedPillSizer} aria-hidden=\"true\">\n {translatedPlaceholder}\n </span>\n )}\n </div>\n );\n};\n","import { Skeleton } from \"../provider/components\";\nimport React from \"react\";\nimport styles from \"./Conversation.module.scss\";\nimport loadingStyles from \"./ConversationLoadingStates.module.scss\";\n\nconst SKEL_RADIUS = \"var(--agents-skeleton-radius)\";\n\nexport const NoConversationLoading = () => {\n return (\n <div className={styles.extensionIntro}>\n <Skeleton className={loadingStyles.avatar} borderRadius={SKEL_RADIUS} />\n <Skeleton className={loadingStyles.title} />\n <Skeleton className={loadingStyles.subtitle} />\n <div className={styles.suggestions}>\n {Array.from({ length: 3 }, (_, index) => (\n <Skeleton key={index} className={loadingStyles.suggestionCard} borderRadius={SKEL_RADIUS} />\n ))}\n </div>\n </div>\n );\n};\n\nexport const ConversationLoading = () => {\n return (\n <div className={styles.chatMessages}>\n <Skeleton className={loadingStyles.userBubble} borderRadius={SKEL_RADIUS} />\n <div className={loadingStyles.messageHeader}>\n <Skeleton className={loadingStyles.messageAvatar} borderRadius={SKEL_RADIUS} />\n <Skeleton className={loadingStyles.messageAuthor} />\n </div>\n <Skeleton className={loadingStyles.messageBody} borderRadius={SKEL_RADIUS} />\n </div>\n );\n};\n","import { conversationWidgetRegistry, getConversationWidgetRegistryRevision } from \"./conversationWidgetRegistry\";\nimport { parseWidgetJsonObject } from \"./widget-fence-json\";\nimport { WIDGET_FENCE_LANG } from \"./widget-fence-syntax\";\nimport { resolveCanonicalWidgetName } from \"./widget-name-resolver\";\n\n/**\n * Does a message's markdown carry a widget? The conversation asks this to reset the drawer when a fresh widget message\n * arrives, and to decide whether a reloaded last message should re-open its canvas (see ConversationMessageWidgets).\n *\n * Lives in its own file rather than in `conversationWidgetRegistry.ts` so the registry stays import-free: a registry →\n * resolver import back would be a cycle whose evaluation order decides whether the app boots. The registry is read\n * lazily for the same reason (a widget can import AgentChat, which imports this file).\n */\n\nlet widgetNames: ReadonlySet<string> | undefined;\nlet widgetNamesRevision = -1;\n\n// Every registered widget name, canonical. Read lazily — see the note above and in widget-name-resolver.ts.\nconst getWidgetNames = (): ReadonlySet<string> => {\n if (widgetNames === undefined || widgetNamesRevision !== getConversationWidgetRegistryRevision()) {\n widgetNames = new Set(conversationWidgetRegistry.widgets.map((widget) => widget.name));\n widgetNamesRevision = getConversationWidgetRegistryRevision();\n }\n return widgetNames;\n};\n\n// Matches the widget name at the start of a line in the stored `::Name` form (and the `:::Name`\n// form old messages may carry); a single-colon inline node doesn't match (min two colons).\nconst WIDGET_NODE_RE = /^[ \\t]*:{2,3}([A-Za-z][\\w]*)/gm;\n\n// Fenced code blocks must not count as widgets — remark-directive never parses\n// its nodes inside them. The open-fence variant drops a still-unterminated\n// fence so streamed partial markdown doesn't match either.\nconst CLOSED_CODE_FENCE_RE = /```[\\s\\S]*?```/g;\nconst OPEN_CODE_FENCE_RE = /```[\\s\\S]*$/;\n\n// A closed ```widget fence — the agent's widget syntax (see remarkWidgetFencePlugin). Only a CLOSED fence counts:\n// a still-streaming open fence has no terminating ``` yet and must not match prematurely. Built from the shared\n// lang constant so \"``` widget\" (a space before the lang — remark accepts it) resolves the same as everywhere else.\nconst CLOSED_WIDGET_FENCE_RE = new RegExp(\"```[ \\\\t]*\" + WIDGET_FENCE_LANG + \"\\\\s*([\\\\s\\\\S]*?)```\", \"g\");\n\n/**\n * True when the markdown contains at least one widget — either a `::Name` / `:::Name` node OR a closed ```widget\n * fence whose `type` resolves to a registered widget. BOTH forms go through `resolveCanonicalWidgetName`, so a stored\n * message written as `::ExampleWidgetDirective{…}` or `{\"type\":\"ExampleWidgetDirective\"}` counts exactly like the\n * canonical `::ExampleWidget` — the drawer resets for old conversations too.\n */\nexport const markdownContainsWidget = (markdown: string): boolean => widgetNamesInMarkdown(markdown).length > 0;\n\n/**\n * The CANONICAL names of every registered widget the markdown carries, in order of appearance, one entry per\n * occurrence (both syntaxes, legacy `…Directive` spellings resolved). The message list reads it to tell a superseded\n * widget from the live one: a later message carrying a widget of the SAME name retires the earlier one's controls.\n */\nexport const widgetNamesInMarkdown = (markdown: string): string[] => {\n if (!markdown) {\n return [];\n }\n const names: string[] = [];\n for (const match of markdown.matchAll(CLOSED_WIDGET_FENCE_RE)) {\n // malformed fence body → not a renderable widget; a surplus trailing `}` / `]` is read as the backend reads it\n const parsed = parseWidgetJsonObject(match[1]);\n const type = parsed?.type;\n const canonicalName = typeof type === \"string\" ? resolveCanonicalWidgetName(type, getWidgetNames()) : null;\n if (canonicalName) {\n names.push(canonicalName);\n }\n }\n const withoutCode = markdown.replace(CLOSED_CODE_FENCE_RE, \"\").replace(OPEN_CODE_FENCE_RE, \"\");\n for (const match of withoutCode.matchAll(WIDGET_NODE_RE)) {\n const canonicalName = resolveCanonicalWidgetName(match[1], getWidgetNames());\n if (canonicalName) {\n names.push(canonicalName);\n }\n }\n return names;\n};\n","import { normalizeServerMessageToMarkdown } from \"./normalize-server-message-to-markdown\";\n\n/**\n * Whether the whole markdown is one bare JSON object with a string `type`. Normalization already fenced every\n * registered widget type, so what is left is a type no widget renders — model noise like `{\"type\":\"no-op\"}`\n * (GPT-6 Luna), never owner-facing text.\n */\nconst isBareUnknownTypeJson = (markdown: string): boolean => {\n if (!markdown.startsWith(\"{\")) return false;\n let parsed: unknown;\n try {\n parsed = JSON.parse(markdown);\n } catch {\n return false;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n return typeof (parsed as Record<string, unknown>).type === \"string\";\n};\n\n/**\n * True when an assistant message's stored content yields markdown that actually renders something.\n *\n * Not every ASSISTANT row carries text. An agentic run persists one ASSISTANT/TEXT turn per step, and a step\n * that only called a tool stores `message: \"\"` (13 such turns in a 30-message run); a payload whose parts are\n * all blank text likewise normalizes to \"\". Such a row would render an empty markdown container that still\n * consumed a full `$x3` gap in the message list, so ConversationMessageList drops it instead — the per-turn agentic\n * trace those rows carry is the admin console's job (AgentConversationInspector), not the customer chat's.\n *\n * The null/blank short-circuit also keeps normalizeServerMessageToMarkdown's \"unrecognized message shape\"\n * console warning from firing on every one of those rows.\n */\nexport const assistantMessageHasRenderableMarkdown = (message: unknown): boolean => {\n if (message == null) return false;\n if (typeof message === \"string\" && message.trim() === \"\") return false;\n const markdown = normalizeServerMessageToMarkdown(message).trim();\n return markdown !== \"\" && !isBareUnknownTypeJson(markdown);\n};\n","import { Button, Icon, Text } from \"../../../../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity } from \"../../../chat-assistant-identity\";\nimport React, { memo, useMemo } from \"react\";\nimport styles from \"./ConversationMessageSystemHeader.module.scss\";\n\nexport interface ConversationMessageSystemHeaderProps {\n aiPromptExtensionCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantIdentity;\n onExpandContentClick?: () => void;\n isContentExpanded?: boolean;\n}\n\nexport const ConversationMessageSystemHeader = memo((props: ConversationMessageSystemHeaderProps) => {\n const { aiPromptExtensionCategory, aiPromptExtension, isContentExpanded, onExpandContentClick } = props;\n\n return (\n <div className={styles.responseHeaderLayout}>\n <div className={styles.responseHeader}>\n <span className={styles.iconContainer}>\n <Icon color=\"var(--agents-fg-on-accent)\" name=\"wizard\" />\n </span>\n <div>\n <Text role=\"help\" weight=\"bold\">\n {aiPromptExtension?.name ?? \"AI Extensions\"}\n </Text>\n {aiPromptExtensionCategory !== undefined ? (\n <Text role=\"caption\">{aiPromptExtensionCategory?.name} System</Text>\n ) : null}\n {aiPromptExtensionCategory === undefined ? (\n <Text role=\"caption\">System</Text>\n ) : null}\n </div>\n </div>\n <div className={styles.responseHeaderAction}>\n <Button\n variant=\"muted\"\n icon={isContentExpanded ? \"caretUp\" : \"caretDown\"}\n onClick={onExpandContentClick}\n />\n </div>\n </div>\n );\n});\n","import React, { memo, useState } from \"react\";\nimport type { ChatAssistantCategory } from \"../../chat-assistant-identity\";\nimport styles from \"./ConversationMessageSystem.module.scss\";\nimport { Markdown } from \"../../../provider/components\";\nimport { ConversationMessageSystemHeader } from \"./ConversationMessageSystemHeader/ConversationMessageSystemHeader\";\n\nexport interface ConversationMessageSystemProps {\n aiPromptExtensionCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantCategory;\n message: string;\n}\n\nexport const ConversationMessageSystem = memo((props: ConversationMessageSystemProps) => {\n const { aiPromptExtensionCategory, aiPromptExtension, message } = props;\n\n const [isContentExpanded, setIsContentExpanded] = useState(false);\n\n return (\n <div className={styles.responseContainer}>\n <ConversationMessageSystemHeader\n aiPromptExtensionCategory={aiPromptExtensionCategory}\n aiPromptExtension={aiPromptExtension}\n onExpandContentClick={() => setIsContentExpanded((v) => !v)}\n isContentExpanded={isContentExpanded}\n />\n\n <div style={{ display: isContentExpanded ? undefined : \"none\" }}>\n <div className={styles.responseMessage}>\n <Markdown markdown={message} />\n </div>\n </div>\n </div>\n );\n});\n","import { assistantMessageHasRenderableMarkdown } from \"../assistant-message-has-renderable-markdown\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { SIGNAL_SOURCES_THAT_OWE_NO_WORK } from \"../last-wire-message-is-unanswered-user-message\";\n\n/**\n * Whether a message can start a turn of the agent: the owner's own message, or a signal that owes work (a widget\n * click, a nudge). Tool-result reports, bookkeeping rows (ERROR, CHECKPOINT) and the signals that owe no work never\n * start one. Which of these messages did start a turn is the server's word (its trace names the message of each\n * turn); the chat offers the per-turn slot after each of them.\n */\nexport const isTurnInitiatorMessage = (message: ChatMessage): boolean => {\n if (message.messageType === \"ERROR\" || message.messageType === \"CHECKPOINT\" || message.messageType === \"TOOL_MESSAGE\") {\n return false;\n }\n if (message.messageType === \"SIGNAL\") return !SIGNAL_SOURCES_THAT_OWE_NO_WORK.includes(message.signalSource ?? \"\");\n if (message.role !== \"USER\") return false;\n if (message.messageType === \"TOOL_CALL\") return false;\n return !(message.message ?? \"\").startsWith(\"/toolresult \");\n};\n\n/** The agent's answer to the owner: an assistant text the chat shows. */\nconst isAssistantAnswer = (message: ChatMessage): boolean =>\n message.role === \"ASSISTANT\" &&\n (message.messageType === \"TEXT\" || message.messageType == null) &&\n assistantMessageHasRenderableMarkdown(message.message);\n\nexport interface TurnsInFlight {\n /** The message that started the turn in flight; null when none runs or it is not known yet. */\n liveTurnMessageId: number | null;\n /** The owner's messages sent while that turn ran, still unanswered: the agent reads them after the current step. */\n queuedMessages: ChatMessage[];\n}\n\nconst NO_TURN_IN_FLIGHT: TurnsInFlight = { liveTurnMessageId: null, queuedMessages: [] };\n\n/**\n * The turn in flight and the owner's messages queued behind it, from the loaded messages. The messages that can start\n * a turn and stand after the agent's newest answer are the candidates: the one the activity read named\n * (`namedTurnMessageId`), else the oldest of them, started the turn in flight; every owner message after it waits.\n * Nothing is in flight while no turn runs.\n */\nexport const findTurnsInFlight = (\n messages: ChatMessage[] | null,\n isTurnRunning: boolean,\n namedTurnMessageId: number | null,\n): TurnsInFlight => {\n if (!isTurnRunning || !messages?.length) return NO_TURN_IN_FLIGHT;\n let firstIndexAfterNewestAnswer = 0;\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (isAssistantAnswer(messages[index])) {\n firstIndexAfterNewestAnswer = index + 1;\n break;\n }\n }\n const candidates = messages.slice(firstIndexAfterNewestAnswer).filter(isTurnInitiatorMessage);\n if (candidates.length === 0 && namedTurnMessageId === null) {\n // A turn runs, yet every message that can start one stands before the newest answer: an answer in parts (the agent\n // wrote a line and works on, a nudge of the loop follows), or the turn the server started for an owner message\n // that arrived during the previous turn (it stands above that turn's answer). Until the activity read names the\n // turn (one read window), the newest such message holds it, so the run's status line never drops out in between.\n const newestInitiator = messages.slice(0, firstIndexAfterNewestAnswer).filter(isTurnInitiatorMessage).at(-1);\n return { liveTurnMessageId: typeof newestInitiator?.id === \"number\" ? newestInitiator.id : null, queuedMessages: [] };\n }\n const namedPosition =\n namedTurnMessageId === null ? -1 : candidates.findIndex((candidate) => candidate.id === namedTurnMessageId);\n // A turn the activity read named but whose message stands before the newest answer (an answer in parts): every\n // candidate after that answer waits behind it.\n const isNamedBeforeCandidates = namedTurnMessageId !== null && namedPosition === -1;\n const livePosition = isNamedBeforeCandidates ? -1 : Math.max(namedPosition, 0);\n const liveCandidate = isNamedBeforeCandidates ? undefined : candidates[livePosition];\n const liveTurnMessageId = isNamedBeforeCandidates ? namedTurnMessageId : typeof liveCandidate?.id === \"number\" ? liveCandidate.id : null;\n return {\n liveTurnMessageId,\n // Only the owner's own words show as queued; a signal behind the running turn has no bubble.\n queuedMessages: candidates.slice(livePosition + 1).filter((candidate) => candidate.role === \"USER\" && candidate.messageType !== \"SIGNAL\"),\n };\n};\n","import { useMemo } from \"react\";\nimport { useAgentsOwnerSettings } from \"../../provider/AgentsProvider\";\nimport { translateText } from \"../../provider/environment\";\nimport { readTraceMoment } from \"../trace/trace-format\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { isTurnInitiatorMessage } from \"../controller/turn-initiators\";\nimport { PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES } from \"../last-wire-message-is-unanswered-user-message\";\n\n/**\n * When what was written in the chat: the day separators, the time heads after a pause, the \"finished HH:MM\" under a\n * long turn's answer and the exact time of each message.\n *\n * - `turns` (B): a separator before the first message of each day (\"Today · 09:58\"; without the time when a voice chat\n * marker opens the day, it shows its own), a time head (\"10:31\") before a message that starts a turn more than\n * {@link MESSAGE_TIME_PAUSE_MS} after the message before it. The agent's own steps and run time never cause one: the\n * answer stays with its question, and a turn that took longer than the pause ends with \"finished 10:24\" under its\n * answer. The exact time of each message on hover / keyboard focus, on touch by a tap.\n * - `everyMessage` (C): `turns` plus a quiet time under every message.\n */\nexport type MessageTimesMode = \"turns\" | \"everyMessage\";\n\n/** The pause between two messages after which the next turn gets a time head, and the turn length that earns \"finished\". */\nexport const MESSAGE_TIME_PAUSE_MS = 20 * 60 * 1000;\n\n/** What stands at one message of the list (by its index); every field is absent when nothing does. */\nexport interface MessageTimeMarks {\n /** The message's moment (ms); null for a message without one (the owner's message before the server stored it). */\n moment: number | null;\n /** A day separator stands before the message; `withTime` names the time in it (\"Today · 09:58\"). */\n daySeparator?: { withTime: boolean };\n /** A time head stands before the message (a turn after a pause). */\n timeHead?: boolean;\n /** \"finished HH:MM\" stands under the message: the last answer of a turn that ran longer than the pause. */\n finishedAt?: number;\n}\n\n/** A voice chat (phone call) lifecycle marker: the list shows it as a centred chip that carries its own time. */\nexport const isCallMarkerMessage = (message: ChatMessage): boolean =>\n message.messageType === \"SIGNAL\" && PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES.includes(message.signalSource ?? \"\");\n\n/**\n * The time marks of a message list (pure). `isShown` says which messages the list renders as a row; `dayKeyOf` maps a\n * moment to its calendar day in the owner's time zone; `isTurnRunning` keeps the newest turn open (no \"finished\" before\n * it ended).\n */\nexport const buildMessageTimeMarks = (\n messages: readonly ChatMessage[],\n isShown: (message: ChatMessage) => boolean,\n dayKeyOf: (moment: number) => string,\n isTurnRunning: boolean,\n): MessageTimeMarks[] => {\n // `createdAt` is the moment; `createdDate` is a calendar date only and would read as midnight\n const marks: MessageTimeMarks[] = messages.map((message) => ({ moment: readTraceMoment(message.createdAt) }));\n let previousMoment: number | null = null;\n let previousDayKey: string | null = null;\n let turnStartedAt: number | null = null;\n let lastAnswerIndexOfTurn: number | null = null;\n const closeTurn = () => {\n if (turnStartedAt === null || lastAnswerIndexOfTurn === null) return;\n const answeredAt = marks[lastAnswerIndexOfTurn].moment;\n if (answeredAt !== null && answeredAt - turnStartedAt > MESSAGE_TIME_PAUSE_MS) marks[lastAnswerIndexOfTurn].finishedAt = answeredAt;\n };\n messages.forEach((message, index) => {\n const moment = marks[index].moment;\n if (moment === null) return;\n const isCallMarker = isCallMarkerMessage(message);\n const startsTurn = isTurnInitiatorMessage(message);\n const shown = isShown(message);\n // separators stand before a row the owner sees or before the message that started a turn (its trace follows it)\n if (shown || startsTurn || isCallMarker) {\n const dayKey = dayKeyOf(moment);\n if (dayKey !== previousDayKey) {\n marks[index].daySeparator = { withTime: !isCallMarker };\n previousDayKey = dayKey;\n } else if ((startsTurn || isCallMarker) && previousMoment !== null && moment - previousMoment > MESSAGE_TIME_PAUSE_MS) {\n // a voice chat marker is a time head of its own (it shows its time)\n if (!isCallMarker) marks[index].timeHead = true;\n }\n }\n if (startsTurn) {\n closeTurn();\n turnStartedAt = moment;\n lastAnswerIndexOfTurn = null;\n }\n if (shown && message.role === \"ASSISTANT\" && turnStartedAt !== null) lastAnswerIndexOfTurn = index;\n // every message moves the clock, the agent's tool steps too: a pause is a pause of the whole conversation\n previousMoment = moment;\n });\n if (!isTurnRunning) closeTurn();\n return marks;\n};\n\n/** The words and figures of the message times in the owner's locale and time zone. */\nexport interface MessageTimeFormat {\n /** The clock time of a moment: `09:58`. */\n time: (moment: number) => string;\n /** The exact moment with the zone: `Mo., 30. Nov. 2026, 09:58:14 MEZ`. */\n exact: (moment: number) => string;\n /** The day of a moment for a separator: `Today`, `Yesterday`, `Mo., 24. Nov.`, `24. Nov. 2025` (another year). */\n day: (moment: number) => string;\n /** The calendar day of a moment in the owner's time zone, as a key (`2026-11-30`). */\n dayKey: (moment: number) => string;\n /** \"finished 10:24\". */\n finished: (moment: number) => string;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/** Builds the formatters (undefined locale / zone: the runtime's). `now` is injected for tests. */\nexport const createMessageTimeFormat = (locale?: string | null, timeZone?: string | null, now: () => number = Date.now): MessageTimeFormat => {\n const localeOrDefault = locale ?? undefined;\n const zone = timeZone ?? undefined;\n const clock = new Intl.DateTimeFormat(localeOrDefault, { hour: \"2-digit\", minute: \"2-digit\", timeZone: zone });\n const exactFormat = new Intl.DateTimeFormat(localeOrDefault, {\n weekday: \"short\",\n day: \"numeric\",\n month: \"short\",\n year: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZoneName: \"short\",\n timeZone: zone,\n });\n const dayOfThisYear = new Intl.DateTimeFormat(localeOrDefault, { weekday: \"short\", day: \"numeric\", month: \"short\", timeZone: zone });\n const dayOfAnotherYear = new Intl.DateTimeFormat(localeOrDefault, { day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: zone });\n const dayKeyParts = new Intl.DateTimeFormat(\"en-CA\", { year: \"numeric\", month: \"2-digit\", day: \"2-digit\", timeZone: zone });\n const dayKey = (moment: number): string => dayKeyParts.format(moment);\n const yearOf = (moment: number): string => dayKey(moment).slice(0, 4);\n return {\n time: (moment) => clock.format(moment),\n exact: (moment) => exactFormat.format(moment),\n dayKey,\n day: (moment) => {\n const today = now();\n const key = dayKey(moment);\n if (key === dayKey(today)) return translateText(\"Today\");\n if (key === dayKey(today - DAY_MS)) return translateText(\"Yesterday\", undefined, \"chat-day\");\n return yearOf(moment) === yearOf(today) ? dayOfThisYear.format(moment) : dayOfAnotherYear.format(moment);\n },\n finished: (moment) => translateText(\"finished %time%\", { time: clock.format(moment) }, \"chat-turn-end\"),\n };\n};\n\n/** The formatters of the owner's locale and time zone (`AgentsEnvironment.useOwnerSettings`), else the runtime's. */\nexport const useMessageTimeFormat = (): MessageTimeFormat => {\n const { locale, dateLocale, timeZone } = useAgentsOwnerSettings();\n const shownLocale = dateLocale ?? locale;\n return useMemo(() => createMessageTimeFormat(shownLocale, timeZone), [shownLocale, timeZone]);\n};\n\n/** `252` → `4:12 min`: the length of a voice chat, compact as the chat's marker shows it. */\nexport const formatCallLength = (durationSeconds: number): string => {\n const safeSeconds = Math.max(0, Math.round(durationSeconds));\n const clock = `${Math.floor(safeSeconds / 60)}:${String(safeSeconds % 60).padStart(2, \"0\")}`;\n return translateText(\"%clock% min\", { clock }, \"voice-call-length\");\n};\n","import { Icon, Text } from \"../../../provider/components\";\nimport { getAgentDisplayName } from \"../../../provider/environment\";\nimport React, { memo } from \"react\";\nimport { VoiceBarsIcon } from \"./VoiceBarsIcon/VoiceBarsIcon\";\nimport styles from \"./ConversationCallMarkerChip.module.scss\";\nimport { textKey } from \"../../../provider/text-key\";\nimport { formatCallLength, useMessageTimeFormat } from \"../../ConversationMessageList/message-times\";\n\nexport interface ConversationCallMarkerChipProps {\n /** PHONE_CALL_STARTED | PHONE_CALL_ENDED — the lifecycle signal's source. */\n signalSource: string;\n /** The signal's model-visible text — carries the duration as `NNNs` and the end reason as `reason <value>`. */\n signalText: string;\n /**\n * When the signal was written (ms). Given, every marker but \"ended\" names its clock time (\"Voice chat started · 21:05\"):\n * the marker is the time head of what follows. Omitted: no time, as before.\n */\n moment?: number | null;\n}\n\ntype CallMarkerState = \"started\" | \"ended\" | \"declined\" | \"missed\" | \"notConnected\";\n\nconst MARKER_LABELS: Readonly<Record<CallMarkerState, { inApp: string; phoneLine: string }>> = {\n started: { inApp: textKey(\"Voice chat started\"), phoneLine: textKey(\"Phone call started\") },\n ended: { inApp: textKey(\"Voice chat ended\"), phoneLine: textKey(\"Phone call ended\") },\n declined: { inApp: textKey(\"You declined a voice chat with %agentName%\"), phoneLine: textKey(\"Phone call declined\") },\n missed: { inApp: textKey(\"You missed a voice chat with %agentName%\"), phoneLine: textKey(\"Phone call not answered\") },\n notConnected: { inApp: textKey(\"Voice chat did not connect\"), phoneLine: textKey(\"Phone call not answered\") },\n};\n\n/** The agent's ring the owner turned down (DECLINED) or let run out (EXPIRED, NOT_ANSWERED) is its own mark in the chat. */\nconst callMarkerStateOf = (isCallEnd: boolean, endReason: string | undefined): CallMarkerState => {\n if (!isCallEnd) return \"started\";\n if (endReason === \"DECLINED\") return \"declined\";\n if (endReason === \"EXPIRED\" || endReason === \"NOT_ANSWERED\") return \"missed\";\n if (endReason === \"FAILED\") return \"notConnected\";\n return \"ended\";\n};\n\n/**\n * Centered marker for a call's lifecycle inside the chat timeline: started, ended (with its duration), declined, missed\n * or not connected; an in-app call is a voice chat with the agent (its voice bars), a phone call keeps the phone. Rendered\n * from the otherwise user-invisible PHONE_CALL_* SIGNAL messages — the label derives from the signal source + the small text contract of AgentVoiceCall::buildLifecycleSignalText (`In-app call …` vs\n * `Phone call …`, duration `NNNs`, reason `reason <value>`); an unparsable text degrades to the plain label.\n */\nexport const ConversationCallMarkerChip = memo(({ signalSource, signalText, moment = null }: ConversationCallMarkerChipProps) => {\n const timeFormat = useMessageTimeFormat();\n const isCallEnd = signalSource === \"PHONE_CALL_ENDED\";\n const isInAppCall = signalText.startsWith(\"In-app call\");\n const endReason = /reason ([A-Za-z_-]+)/.exec(signalText)?.[1];\n const durationSeconds = /(\\d+)s\\b/.exec(signalText)?.[1];\n const markerState = callMarkerStateOf(isCallEnd, endReason);\n const markerLabel = isInAppCall ? MARKER_LABELS[markerState].inApp : MARKER_LABELS[markerState].phoneLine;\n\n return (\n <div className={styles.markerRow} data-testid=\"conversation-call-marker\">\n <span className={styles.markerChip} data-state={markerState}>\n <span className={styles.markerIcon}>\n {isInAppCall ? <VoiceBarsIcon size={16} /> : <Icon name=\"phone\" />}\n </span>\n <Text role=\"caption\" replacements={{ agentName: getAgentDisplayName() }}>\n {markerLabel}\n </Text>\n {markerState === \"ended\" && durationSeconds != null && (\n <span className={styles.markerDuration}>\n <Text role=\"caption\" translate={false}>\n {formatCallLength(Number(durationSeconds))}\n </Text>\n </span>\n )}\n {markerState !== \"ended\" && moment !== null && (\n <time className={styles.markerDuration} dateTime={new Date(moment).toISOString()} title={timeFormat.exact(moment)}>\n <Text role=\"caption\" translate={false}>\n {timeFormat.time(moment)}\n </Text>\n </time>\n )}\n </span>\n </div>\n );\n});\n","import { Button, Text } from \"../../../provider/components\";\nimport React, { useState } from \"react\";\nimport styles from \"./ConversationTaskInstructionDisclosure.module.scss\";\n\nexport interface ConversationTaskInstructionDisclosureProps {\n /** The machine-composed seed instruction of a schedule-spawned run — the full text revealed on expand. */\n instructionText: string;\n}\n\n/**\n * Replaces the owner bubble for the FIRST user message of a SCHEDULE-spawned run conversation (UX overhaul W4\n * item 19). That message is the machine-composed task instruction (the schedule's task text + the previous run's\n * outcome line, see AIConversationSchedule::composeSeedUserMessageText) — NOT something the owner typed, so an\n * owner bubble would misattribute it as the owner's own words. Collapsed by default to a muted\n * \"Show task instruction\" disclosure; expanding reveals the full instruction text for inspection.\n */\nexport const ConversationTaskInstructionDisclosure = ({\n instructionText,\n}: ConversationTaskInstructionDisclosureProps) => {\n const [expanded, setExpanded] = useState(false);\n\n return (\n <div className={styles.disclosure}>\n {expanded ? (\n <div className={styles.instructionPanel}>\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" allowNewLines translate={false}>\n {instructionText}\n </Text>\n </div>\n ) : null}\n <Button variant=\"muted\" onClick={() => setExpanded((wasExpanded) => !wasExpanded)}>\n {expanded ? \"Hide task instruction\" : \"Show task instruction\"}\n </Button>\n </div>\n );\n};\n","import { Text } from \"../../../../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity } from \"../../../chat-assistant-identity\";\nimport React, { memo, useState, useEffect } from \"react\";\nimport styles from \"./ConversationMessageThinking.module.scss\";\nimport { ConversationMessageHeader } from \"../ConversationMessageHeader/ConversationMessageHeader\";\n\nconst loadingStateMessages = [\n \"Gathering business data…\",\n \"Planning what to do…\",\n \"Working on it…\",\n \"Clarifying response…\",\n \"Almost ready…\",\n \"Something new came up…\",\n];\n\nexport interface ConversationMessageThinkingProps {\n aiPromptExtensionCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantIdentity;\n}\n\nexport const ConversationMessageThinking = memo((props: ConversationMessageThinkingProps) => {\n const { aiPromptExtensionCategory, aiPromptExtension } = props;\n const [currentIndex, setCurrentIndex] = useState(0);\n\n useEffect(() => {\n const interval = setInterval(() => {\n setCurrentIndex((prevIndex) => (prevIndex + 1) % loadingStateMessages.length);\n }, 2500);\n\n return () => clearInterval(interval);\n }, []);\n\n return (\n <div className={styles.responseContainer}>\n <ConversationMessageHeader\n aiPromptExtensionCategory={aiPromptExtensionCategory}\n aiPromptExtension={aiPromptExtension}\n />\n\n <div className={styles.thinkingMessage}>\n <div className={styles.thinkingDots}>\n <span />\n <span />\n <span />\n </div>\n <Text>{loadingStateMessages[currentIndex]}</Text>\n </div>\n </div>\n );\n});\n","import { Button, Icon, Text } from \"../../provider/components\";\nimport React, { useCallback, useMemo, useState } from \"react\";\nimport styles from \"./ConversationErrorWidget.module.scss\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport { useAgentsBudgetLimit } from \"../../provider/AgentsProvider\";\n\n/** The first day of next month as `DD.MM.YYYY` — the day a monthly budget resets. */\nconst formatFirstDayOfNextMonth = (now: Date): string => {\n const firstDayOfNextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);\n const day = String(firstDayOfNextMonth.getDate()).padStart(2, \"0\");\n const month = String(firstDayOfNextMonth.getMonth() + 1).padStart(2, \"0\");\n return `${day}.${month}.${firstDayOfNextMonth.getFullYear()}`;\n};\n\nexport interface ConversationErrorWidgetProps {\n errorType: ConversationErrorType;\n /** Retry-After seconds of the 429 — only meaningful for RATE_LIMIT; picks the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /**\n * Retry action for a generic run failure whose customer message is persisted but unanswered: the HOST decides eligibility and binds the call to ITS chat slice (the AI-extensions chat and the agent\n * widget mount this card on separate Redux partitions), so the card only renders the action when it is given one.\n * Resolves when the retry was accepted; rejects when there is nothing to retry — the card then keeps showing.\n */\n onRetry?: () => Promise<void>;\n}\n\nexport const ConversationErrorWidget = (props: ConversationErrorWidgetProps) => {\n const { errorType, rateLimitRetryAfterSeconds, onRetry } = props;\n const [retrying, setRetrying] = useState(false);\n // The app's budget: whether an upgrade lifts the limit, and the fair-use wording (resellers that present the AI\n // budget as a fair-use allowance).\n const budgetLimit = useAgentsBudgetLimit();\n const isUpSellPossible = budgetLimit.canUpgrade;\n const showFairUsageMessage = budgetLimit.showsFairUseWording;\n\n const canRetry = errorType === ConversationErrorType.AGENT_ERROR && onRetry !== undefined;\n\n const handleRetry = useCallback(async () => {\n if (!onRetry || retrying) {\n return;\n }\n setRetrying(true);\n try {\n await onRetry();\n // Accepted: the host cleared the card / flipped the thinking indicator; nothing left to do here.\n } catch (error) {\n // Rejected (nothing to retry / conversation gone / network): keep the card, re-enable the action.\n console.warn(\"Conversation retry rejected\", error);\n setRetrying(false);\n }\n }, [onRetry, retrying]);\n\n const { icon, title, description, replacements } = useMemo(() => {\n let title = \"Network error\";\n let description = \"We’re sorry, something went wrong. Please refresh the page or try again later.\";\n let replacements: Record<string, string> | undefined = undefined;\n if (errorType === ConversationErrorType.AI_BUDGET) {\n title = \"Limit reached\";\n if (showFairUsageMessage) {\n description = isUpSellPossible\n ? \"You've reached your fair use limit for this month. This limit will reset on %resetDate%, or you can upgrade now to continue without interruption.\"\n : \"You've reached your fair use limit for this month. This limit will reset on %resetDate%.\";\n replacements = { resetDate: formatFirstDayOfNextMonth(new Date()) };\n } else {\n description = isUpSellPossible\n ? \"You've reached your maximum monthly usage. This limit resets on %limitResetDate%, or you can upgrade now to continue without interruption.\"\n : \"You've reached your maximum monthly usage. This limit resets on %limitResetDate%.\";\n replacements = { limitResetDate: formatFirstDayOfNextMonth(new Date()) };\n }\n }\n if (errorType === ConversationErrorType.RATE_LIMIT) {\n title = \"Usage limit reached\";\n if (!rateLimitRetryAfterSeconds || rateLimitRetryAfterSeconds <= 90) {\n description = \"You've sent a lot of AI requests in a short time. Please wait a minute and try again.\";\n } else if (rateLimitRetryAfterSeconds <= 3600) {\n description =\n \"You've reached your AI usage limit for this hour. Please try again in about %retryAfterMinutes% minutes.\";\n replacements = { retryAfterMinutes: `${Math.ceil(rateLimitRetryAfterSeconds / 60)}` };\n } else {\n description = \"You've reached your AI usage limit for today. Please try again later.\";\n }\n }\n if (errorType === ConversationErrorType.AGENT_ERROR) {\n title = \"Something went wrong\";\n if (canRetry) {\n description = \"We’re sorry, something went wrong. Your message is saved — retry to have it answered.\";\n }\n }\n if (errorType === ConversationErrorType.CONVERSATION_CLOSED) {\n title = \"Conversation closed\";\n description = \"This conversation is completed and closed. Please start a new conversation.\";\n }\n return {\n icon: \"warning\" as const,\n title,\n description,\n replacements,\n };\n }, [errorType, isUpSellPossible, rateLimitRetryAfterSeconds, showFairUsageMessage, canRetry]);\n\n return (\n <div className={styles.errorMessageContainer}>\n <div>\n <div className={styles.errorMessageTitle}>\n <Icon name={icon} />\n <Text weight=\"bold\">{title}</Text>\n </div>\n <Text replacements={replacements}>{description}</Text>\n </div>\n {errorType === ConversationErrorType.AI_BUDGET && isUpSellPossible ? (\n <Button size=\"extraLarge\" onClick={budgetLimit.openUpgrade} variant=\"shimmer\">\n Upgrade Plan\n </Button>\n ) : null}\n {canRetry ? (\n <Button size=\"extraLarge\" onClick={handleRetry} variant=\"shimmer\" disabled={retrying}>\n Retry\n </Button>\n ) : null}\n </div>\n );\n};\n","import { classNames } from \"../../provider/class-names\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity } from \"../chat-assistant-identity\";\nimport React, { Fragment, useMemo, useRef, useState } from \"react\";\nimport {\n ConversationMessageUser,\n ConversationMessageUserTheme,\n} from \"../ConversationMessage/ConversationMessageUser/ConversationMessageUser\";\nimport { ConversationMessageWidgets } from \"../ConversationMessage/ConversationMessageWidgets/ConversationMessageWidgets\";\nimport { widgetNamesInMarkdown } from \"../../renderer/markdown-contains-widget\";\nimport { isWidgetClickSignalSource } from \"../../renderer/widget-click-signal-sources\";\nimport { normalizeServerMessageToMarkdown } from \"../normalize-server-message-to-markdown\";\nimport { assistantMessageHasRenderableMarkdown } from \"../assistant-message-has-renderable-markdown\";\nimport { lastWireMessageIsUnansweredUserMessage } from \"../last-wire-message-is-unanswered-user-message\";\nimport { ConversationMessageSystem } from \"../ConversationMessage/ConversationMessageSystem/ConversationMessageSystem\";\nimport { ConversationCallMarkerChip } from \"../ConversationMessage/ConversationCallMarkerChip/ConversationCallMarkerChip\";\nimport { ConversationTaskInstructionDisclosure } from \"../ConversationMessage/ConversationTaskInstructionDisclosure/ConversationTaskInstructionDisclosure\";\nimport { ConversationMessageThinking } from \"../ConversationMessage/ConversationMessageWidgets/ConversationMessageThinking/ConversationMessageThinking\";\nimport { ConversationErrorWidget } from \"../ConversationErrorWidget/ConversationErrorWidget\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES } from \"../last-wire-message-is-unanswered-user-message\";\nimport styles from \"../Conversation.module.scss\";\nimport timeStyles from \"./ConversationMessageTimes.module.scss\";\nimport { buildMessageTimeMarks, type MessageTimeMarks, type MessageTimesMode, useMessageTimeFormat } from \"./message-times\";\nimport { Ref, RefObject } from \"react\";\n\ninterface ConversationMessageListProps {\n className?: string;\n messages: ChatMessage[] | null;\n currentCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantIdentity;\n isDebugMode: boolean;\n aiThinking: boolean;\n /**\n * Custom node mounted at the tail of the message list instead of the default\n * (thinking-only) ConversationMessageThinking. Rendered permanently — used by\n * A host to show the animated agent face, which idles between turns.\n */\n thinkingIndicator?: React.ReactNode;\n /**\n * Hide the assistant header (icon + name + \"Assistant\") and the copy button\n * on assistant messages. Used by a host, which renders bare messages.\n */\n hideAssistantMeta?: boolean;\n /**\n * Theme for user-message bubbles. When omitted, falls back to the legacy\n * behavior: \"light\" for generic (no-agent) chat, \"default\" otherwise. A host\n * forces \"dark\".\n */\n userMessageTheme?: ConversationMessageUserTheme;\n error: ConversationErrorType | null;\n /** Retry-After seconds of a 429 quota rejection — forwarded to the error card for the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /**\n * Host-bound retry of a FAILED run. Offered on the error card only while the newest wire\n * message is the customer's own, still unanswered — the persisted message is re-driven server-side.\n */\n onRetryFailedRun?: () => Promise<void>;\n messagesBottomRef: RefObject<HTMLDivElement | null>;\n messagesListRef?: Ref<HTMLDivElement | null>;\n /**\n * Opt-in staggered fade-in of a fresh reply's markdown blocks — see useFreshMessageBlockReveal;\n * forwarded to ConversationMessageWidgets. Default off.\n */\n enableFreshMessageBlockReveal?: boolean;\n /**\n * Id of the ONE user message to render as a collapsed task-instruction disclosure instead of an owner bubble:\n * the machine-composed seed instruction of a SCHEDULE-spawned run (UX overhaul W4 item 19). The host resolves\n * the id (AgentChat: first USER message once the history is loaded to its start); undefined renders every\n * user message normally.\n */\n taskInstructionMessageId?: number;\n /**\n * Host content rendered right after one message of the thread — also after a message the list itself does not show\n * (a work signal that started an agent turn). The agent chat puts each turn's activity card under the message that\n * started the turn. The content is a row of the list's flex column, so the list's gap stands above it; the list\n * publishes that gap as `--chat-messages-gap`. Undefined (every other host) renders the rows exactly as before.\n */\n renderAfterMessage?: (message: ChatMessage) => React.ReactNode;\n /**\n * Host content beside each shown assistant message (an avatar face, 24–28 px): it stands left of the message, at its\n * top. Undefined (every other host) renders the assistant messages exactly as before.\n */\n renderAssistantAvatar?: (message: ChatMessage) => React.ReactNode;\n /** The backend refuses every widget signal of a closed conversation, so no widget renders its controls. */\n isConversationClosed?: boolean;\n /**\n * When what was written (`message-times.ts`): `turns` = day separators, a time head after a pause of 20 minutes,\n * \"finished HH:MM\" under a long turn's answer, the exact time of each message on hover / focus / tap; `everyMessage`\n * adds a quiet time under every message (a verbose view). Undefined / null: no times, as before.\n */\n messageTimes?: MessageTimesMode | null;\n}\n\n/** The interactive parts of a message: a tap on them is theirs, never the time line's. */\nconst INTERACTIVE_SELECTOR = \"a, button, input, textarea, select, summary, label, [role='button'], [contenteditable='true']\";\n\n/**\n * Whether the list renders a row for the message (the rules of `renderMessageRow`): the call markers, the owner's\n * messages (not the tool reports), the assistant's messages with text, system rows in the debug mode.\n */\nconst isMessageShownAsRow = (message: ChatMessage, isDebugMode: boolean): boolean => {\n if (message.messageType === \"SIGNAL\") return PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES.includes(message.signalSource ?? \"\");\n if (message.messageType === \"ERROR\") return false;\n if (message.role === \"USER\") return !(message.message ?? \"\").startsWith(\"/toolresult \");\n if (message.role === \"ASSISTANT\") return assistantMessageHasRenderableMarkdown(message.message);\n return message.role === \"SYSTEM\" && isDebugMode;\n};\n\nconst WIDGET_VISIBILITY_WINDOW = 15;\n\n/** The canonical widget names an assistant-role message carries (empty for every other row). */\nconst widgetNamesOfMessage = (message: ChatMessage): string[] =>\n message.role === \"ASSISTANT\" ? widgetNamesInMarkdown(normalizeServerMessageToMarkdown(message.message)) : [];\n\n/**\n * The id of the newest widget-carrying assistant-role message the owner has not answered yet — null when the newest\n * such message is followed by a USER message or by a widget-click signal (the owner moved on; its controls stay\n * read-only after a reload, as before). Walks from the end so the first widget hit is the newest.\n */\nexport const findUnansweredWidgetMessageId = (messages: ChatMessage[]): string | number | null => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message.role === \"USER\") return null;\n if (message.messageType === \"SIGNAL\" && isWidgetClickSignalSource(message.signalSource)) return null;\n if (widgetNamesOfMessage(message).length > 0) return message.id ?? null;\n }\n return null;\n};\n\n/**\n * The ids of every widget-carrying assistant-role message that a LATER assistant-role message supersedes with a\n * widget of the same name. Pure, order-based: the newest widget of a type is the live one.\n */\nexport const findSupersededWidgetMessageIds = (messages: ChatMessage[]): Set<string | number> => {\n const supersededIds = new Set<string | number>();\n const newestMessageIdByWidgetName = new Map<string, string | number>();\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message.id == null) continue;\n for (const widgetName of widgetNamesOfMessage(message)) {\n const newestMessageId = newestMessageIdByWidgetName.get(widgetName);\n if (newestMessageId === undefined) {\n newestMessageIdByWidgetName.set(widgetName, message.id);\n } else if (newestMessageId !== message.id) {\n // a second fence of the same type INSIDE one message is not a successor of itself\n supersededIds.add(message.id);\n }\n }\n }\n return supersededIds;\n};\n\nexport const ConversationMessageList = ({\n className,\n messages,\n currentCategory,\n aiPromptExtension,\n isDebugMode,\n aiThinking,\n thinkingIndicator,\n hideAssistantMeta,\n userMessageTheme,\n error,\n rateLimitRetryAfterSeconds,\n onRetryFailedRun,\n messagesBottomRef,\n messagesListRef,\n enableFreshMessageBlockReveal,\n taskInstructionMessageId,\n renderAfterMessage,\n renderAssistantAvatar,\n isConversationClosed = false,\n messageTimes = null,\n}: ConversationMessageListProps) => {\n const list = messages ?? [];\n const timeFormat = useMessageTimeFormat();\n const timeMarks = useMemo<MessageTimeMarks[] | null>(\n () =>\n messageTimes === null\n ? null\n : buildMessageTimeMarks(messages ?? [], (message) => isMessageShownAsRow(message, isDebugMode), timeFormat.dayKey, aiThinking),\n [messageTimes, messages, isDebugMode, timeFormat, aiThinking],\n );\n // Touch: the message whose time line a tap opened (one at a time; a second tap closes it).\n const [tappedTimeMessageKey, setTappedTimeMessageKey] = useState<string | number | null>(null);\n const hideWidgetsBeforeIndex = Math.max(0, list.length - WIDGET_VISIBILITY_WINDOW);\n const userTheme: ConversationMessageUserTheme =\n userMessageTheme ?? (aiPromptExtension === undefined ? \"light\" : \"default\");\n\n // Reload promotion: on resume-from-history the slice never tags messages `fresh` (those are history), so the\n // newest reply's widgets would render read-only — a customer who reloads mid-setup would find the question's\n // buttons gone. Evaluated ONCE the first time messages arrive: the newest assistant-role message that carries a\n // widget is rendered INTERACTIVE, provided the owner has not answered it yet (no later USER message, no later\n // widget-click signal). \"Newest widget-carrying\", not \"newest assistant message\": a widget a TOOL writes (e.g. a\n // confirm widget of the app's first-run setup) is indexed before the agent's own line under it, so it is never the last\n // message — and read-only it would tell the owner the match \"was already handled\" while the setup waits for that\n // very click. It is NOT rendered `justDelivered`: that flag is the one-shot side-effect gate (canvas open, draft\n // creation) and must never re-fire on a reload — a canvas that was open comes back through the canvas model's own\n // restore, not through this promotion. (Detection lives here, in the render tree — importing the widget registry\n // into the store-init slice case forms a TDZ cycle.)\n const reloadReopenMessageIdRef = useRef<string | number | null | undefined>(undefined);\n if (reloadReopenMessageIdRef.current === undefined && list.length > 0) {\n reloadReopenMessageIdRef.current = findUnansweredWidgetMessageId(list);\n }\n // A widget the owner already moved past: a LATER assistant-role message carrying a widget of the SAME type retires\n // the earlier one's controls (the newest identify widget is the live one — the owner corrected the seed, a new\n // search wrote a new widget; the superseded one must not accept a confirm for the wrong business). Recomputed as\n // the list grows, so it also applies in-session where the slice keeps the earlier message `fresh`.\n const supersededWidgetMessageIds = useMemo(() => findSupersededWidgetMessageIds(messages ?? []), [messages]);\n const renderMessageRow = (message: ChatMessage, index: number): React.ReactNode => {\n const hideWidgets = index < hideWidgetsBeforeIndex;\n // Phone-call lifecycle signals are the ONE user-visible signal kind: the timeline renders them as a\n // centered call marker chip (started / ended + duration / not reached).\n if (message.messageType === \"SIGNAL\" && PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES.includes(message.signalSource ?? \"\")) {\n return (\n <ConversationCallMarkerChip\n key={message.id ?? index}\n signalSource={message.signalSource ?? \"\"}\n signalText={message.message ?? \"\"}\n moment={timeMarks?.[index]?.moment ?? null}\n />\n );\n }\n // Every OTHER out-of-band SIGNAL message (nudge, memory-conflict, widget events) is model-only —\n // never shown to the customer. Stored role=SYSTEM, so this guard precedes the role branches.\n if (message.messageType === \"SIGNAL\") return null;\n // ERROR messages carry the raw internal failure (e.g. a provider 400 with the full error body) — never shown to\n // the customer. The user-facing \"something went wrong\" is the ConversationErrorWidget below, rendered from runState=FAILED.\n if (message.messageType === \"ERROR\") return null;\n\n let messageNode: React.ReactNode = null;\n if (message.role === \"USER\") {\n // Hide tool-result reports from the chat UI (they are model-internal)\n if (message.message?.startsWith(\"/toolresult \")) return null;\n // The SCHEDULE-run seed instruction is machine-composed — render it as a collapsed disclosure, never as\n // the owner's own words (see taskInstructionMessageId).\n messageNode =\n taskInstructionMessageId != null && message.id === taskInstructionMessageId ? (\n <ConversationTaskInstructionDisclosure instructionText={message.message ?? \"\"} />\n ) : (\n <ConversationMessageUser text={message.message ?? \"\"} theme={userTheme} />\n );\n } else if (message.role === \"ASSISTANT\") {\n // A text-less assistant turn has nothing to show the customer, and rendering it anyway emits an empty\n // markdown container that still consumes a full `$x3` message-list gap. Its agentic trace fields are\n // the admin console's concern (AgentConversationInspector, its own timeline), not this chat's.\n if (!assistantMessageHasRenderableMarkdown(message.message)) return null;\n messageNode = (\n <ConversationMessageWidgets\n key={message.id}\n interactive={\n !isConversationClosed &&\n !(message.id != null && supersededWidgetMessageIds.has(message.id)) &&\n ((message.fresh ?? false) || (message.id != null && message.id === reloadReopenMessageIdRef.current))\n }\n justDelivered={message.fresh ?? false}\n aiPromptExtensionCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n message={message.message}\n messageId={message.id}\n hideWidgets={hideWidgets}\n hideAssistantMeta={hideAssistantMeta}\n enableFreshMessageBlockReveal={enableFreshMessageBlockReveal}\n />\n );\n if (renderAssistantAvatar) {\n messageNode = (\n <div key={message.id} className={styles.assistantMessageWithAvatar}>\n <div className={styles.assistantAvatar}>{renderAssistantAvatar(message)}</div>\n <div className={styles.assistantMessageBesideAvatar}>{messageNode}</div>\n </div>\n );\n }\n } else if (message.role === \"SYSTEM\" && isDebugMode) {\n messageNode = (\n <ConversationMessageSystem\n aiPromptExtensionCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n message={message.message!}\n />\n );\n }\n if (messageNode === null) return null;\n\n const rowKey = message.id ?? `pending-${message.role}-${index}`;\n const marks = timeMarks?.[index];\n const moment = marks?.moment ?? null;\n const isTimed = moment !== null && message.role !== \"SYSTEM\";\n const isTimeTapped = isTimed && tappedTimeMessageKey === rowKey;\n // Touch has no hover: a tap on the message (not on a link or a button in it) opens its time line, a second closes it.\n const handleRowClick = isTimed\n ? (event: React.MouseEvent<HTMLDivElement>) => {\n if (typeof window === \"undefined\" || !window.matchMedia?.(\"(hover: none)\").matches) return;\n if ((event.target as Element).closest?.(INTERACTIVE_SELECTOR)) return;\n if (window.getSelection?.()?.toString()) return;\n setTappedTimeMessageKey((current) => (current === rowKey ? null : rowKey));\n }\n : undefined;\n\n // `display: contents`-free anchor row carrying the message id, so search results (and any other consumer) can\n // locate a message in the DOM and scroll it into view. The row is a flex column so user bubbles keep their\n // `align-self: flex-end` right-alignment and assistant messages keep their full width.\n return (\n <div\n key={rowKey}\n className={classNames(styles.messageRow, isTimed && timeStyles.timedRow)}\n data-message-id={message.id ?? undefined}\n // Role marker so the scroll logic can locate the last USER row (the question) to pin it to the top on send.\n data-message-role={message.role}\n onClick={handleRowClick}\n >\n {messageNode}\n {isTimed && moment !== null ? (\n <>\n {/* the exact time: read by screen readers with the message, seen on hover and keyboard focus */}\n <time className={timeStyles.exactTime} dateTime={new Date(moment).toISOString()}>\n {timeFormat.exact(moment)}\n </time>\n {isTimeTapped ? (\n <span className={timeStyles.tappedTime} aria-hidden>\n {timeFormat.exact(moment)}\n </span>\n ) : messageTimes === \"everyMessage\" ? (\n <span className={timeStyles.quietTime} aria-hidden>\n {timeFormat.time(moment)}\n </span>\n ) : null}\n {marks?.finishedAt !== undefined ? (\n <span className={timeStyles.finished} aria-hidden>\n {timeFormat.finished(marks.finishedAt)}\n </span>\n ) : null}\n </>\n ) : null}\n </div>\n );\n };\n\n /** The day separator or the time head that stands before a message (the time marks), else nothing. */\n const renderTimeBefore = (index: number): React.ReactNode => {\n const marks = timeMarks?.[index];\n if (!marks || marks.moment === null) return null;\n const moment = marks.moment;\n if (marks.daySeparator) {\n return (\n <div className={timeStyles.daySeparator} role=\"separator\" data-testid=\"conversation-day-separator\">\n <span className={timeStyles.daySeparatorLabel}>\n <span className={timeStyles.daySeparatorDay}>{timeFormat.day(moment)}</span>\n {marks.daySeparator.withTime ? (\n <>\n <span className={timeStyles.daySeparatorDot} aria-hidden>\n ·\n </span>\n <span className={timeStyles.clock}>{timeFormat.time(moment)}</span>\n </>\n ) : null}\n </span>\n </div>\n );\n }\n if (marks.timeHead) {\n return (\n <div className={classNames(timeStyles.timeHead, timeStyles.clock)} role=\"separator\" data-testid=\"conversation-time-head\">\n {timeFormat.time(moment)}\n </div>\n );\n }\n return null;\n };\n\n return (\n <div className={classNames(styles.chatMessages, className)} ref={messagesListRef}>\n {list.map((message, index) =>\n renderAfterMessage || timeMarks !== null ? (\n // Keyed like the row itself and present for every row, so a node that appears after a message never\n // changes the row's position in the tree (and never remounts the message and its widgets).\n <Fragment key={message.id ?? `pending-${message.role}-${index}`}>\n {renderTimeBefore(index)}\n {renderMessageRow(message, index)}\n {renderAfterMessage?.(message)}\n </Fragment>\n ) : (\n renderMessageRow(message, index)\n ),\n )}\n {/* A custom indicator is always mounted (it idles between turns); the\n default one only appears while the agent is thinking. */}\n {thinkingIndicator ?? (\n (aiThinking ? (\n <ConversationMessageThinking\n aiPromptExtensionCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n />\n ) : null)\n )}\n\n {error !== null ? (\n <ConversationErrorWidget\n errorType={error!}\n rateLimitRetryAfterSeconds={rateLimitRetryAfterSeconds}\n onRetry={\n error === ConversationErrorType.AGENT_ERROR && lastWireMessageIsUnansweredUserMessage(messages)\n ? onRetryFailedRun\n : undefined\n }\n />\n ) : null}\n <div className={styles.messagesBottom} ref={messagesBottomRef} />\n </div>\n );\n};\n","import { Icon, InteractiveSurface, Text } from \"../../provider/components\";\nimport type { ChatAssistantOpening } from \"../chat-assistant-identity\";\nimport React from \"react\";\nimport styles from \"./ConversationSuggestionWidget.module.scss\";\nimport { classNames } from \"../../provider/class-names\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\n\nexport interface ConversationSuggestionWidgetProps {\n suggestion: ChatAssistantOpening;\n onClick?: () => void;\n testId?: string;\n}\n\nexport const ConversationSuggestionWidget = (props: ConversationSuggestionWidgetProps) => {\n const { suggestion, onClick, testId } = props;\n const { AssistantIconBadge } = useAgentsEnvironment();\n\n return (\n <InteractiveSurface hoverable className={classNames(styles.suggestionCard)} testId={testId}>\n <button type=\"button\" className={styles.suggestionCardButton} onClick={onClick}>\n {AssistantIconBadge ? (\n <AssistantIconBadge\n iconName={suggestion.iconClass ?? \"\"}\n color=\"var(--agents-fg-on-accent)\"\n backgroundColor=\"color-mix(in srgb, var(--agents-neutral-000) 20%, transparent)\"\n />\n ) : null}\n <div>\n <Text role=\"help\" weight=\"bold\" color=\"var(--agents-fg-on-accent)\">\n {suggestion.name}\n </Text>\n <Text role=\"caption\" color=\"var(--agents-fg-on-accent)\">\n {suggestion.description}\n </Text>\n </div>\n <Icon color=\"var(--agents-fg-on-accent)\" className={styles.arrowIcon} name=\"arrowRight\" />\n </button>\n </InteractiveSurface>\n );\n};\n","import { Text } from \"../../provider/components\";\nimport type { ChatAssistantIdentity, ChatAssistantOpening } from \"../chat-assistant-identity\";\nimport React from \"react\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport styles from \"../Conversation.module.scss\";\nimport { ConversationSuggestionWidget } from \"../ConversationSuggestionWidget/ConversationSuggestionWidget\";\n\ninterface ConversationIntroWidgetProps {\n aiPromptExtension: ChatAssistantIdentity;\n /** The icon class of the extension, an icon of the app's icon set. */\n aiPromptExtensionIcon: string;\n suggestions?: ChatAssistantOpening[];\n onSuggestionClick: (text: string) => void;\n}\n\nexport const ConversationIntroWidget = ({\n aiPromptExtension,\n aiPromptExtensionIcon,\n suggestions,\n onSuggestionClick,\n}: ConversationIntroWidgetProps) => {\n const { AssistantIconBadge } = useAgentsEnvironment();\n return (\n <div className={styles.extensionIntro}>\n {AssistantIconBadge ? (\n <AssistantIconBadge\n iconName={aiPromptExtensionIcon}\n color=\"var(--agents-fg-on-accent)\"\n backgroundColor=\"var(--agents-assistant-400)\"\n isLarge\n />\n ) : null}\n <Text\n role=\"intro\"\n weight=\"bold\"\n textAlign={\"center\"}\n className={styles.extensionIntroTitle}\n >\n {aiPromptExtension.name}\n </Text>\n <Text\n role=\"body\"\n textAlign={\"center\"}\n color=\"var(--agents-fg-light)\"\n className={styles.extensionIntroDescription}\n >\n {aiPromptExtension.description}\n </Text>\n <div className={styles.suggestions}>\n {suggestions?.map((suggestion, index) => (\n <ConversationSuggestionWidget\n key={\"suggestion_prop_\" + index}\n suggestion={suggestion}\n onClick={() => onSuggestionClick(suggestion.openingText!)}\n />\n ))}\n </div>\n </div>\n );\n};\n","import { Button } from \"../../provider/components\";\nimport { useAgentsTexts } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport React from \"react\";\nimport styles from \"./ConversationScrollToLatestMessageButton.module.scss\";\n\ntype ConversationScrollToLatestMessageButtonProps = {\n visible: boolean;\n onClick: () => void;\n};\n\nexport const ConversationScrollToLatestMessageButton = (props: ConversationScrollToLatestMessageButtonProps) => {\n const { visible, onClick } = props;\n // The button shows only an icon: its accessible name comes from the package's texts.\n const texts = useAgentsTexts();\n return (\n <div className={classNames(styles.scrollToLatest, visible ? styles.visible : undefined)}>\n <Button\n variant=\"muted\"\n icon=\"arrowDown\"\n rounded\n blurred\n size=\"extraLarge\"\n onClick={onClick}\n ariaLabel={texts.translate(\"Scroll to the latest message\")}\n testId=\"chat-scroll-to-latest-button\"\n />\n </div>\n );\n};\n","import { RefObject, useEffect, useState } from \"react\";\n\n/** The button appears once the messagesBottom sentinel is this far below the visible bottom edge. */\nconst SHOW_BUTTON_BELOW_FOLD_PX = 300;\n\nexport const useIsMessagesBottomOutOfView = (\n scrollContainer: HTMLDivElement | null,\n messagesList: HTMLDivElement | null,\n messagesBottomRef: RefObject<HTMLDivElement | null>,\n): boolean => {\n const [isOutOfView, setIsOutOfView] = useState(false);\n\n useEffect(() => {\n const messagesBottomSentinel = messagesBottomRef.current;\n if (!scrollContainer || !messagesBottomSentinel) {\n setIsOutOfView(false);\n return undefined;\n }\n const observer = new IntersectionObserver(\n (entries) => setIsOutOfView(!entries[entries.length - 1].isIntersecting),\n // Extends the root's bottom edge by 300px: the sentinel counts as \"in view\" until it is\n // more than 300px below the fold, so the button only appears after real scrolling up.\n { root: scrollContainer, rootMargin: `0px 0px ${SHOW_BUTTON_BELOW_FOLD_PX}px 0px` },\n );\n observer.observe(messagesBottomSentinel);\n return () => {\n observer.disconnect();\n setIsOutOfView(false);\n };\n }, [scrollContainer, messagesList, messagesBottomRef]);\n\n return isOutOfView;\n};\n","import { MutableRefObject, RefObject, useCallback, useRef } from \"react\";\n\n/**\n * The pin-question-on-send machinery of the AW-107 long-answer reading flow, extracted out of ConversationViewBody\n * so the addon lives in its own file (mirrors hooks/useIsMessagesBottomOutOfView.ts). On send, the user's\n * question is pinned to the top with empty room reserved below it and bottom-follow is suspended for the turn,\n * so the reply reveals from its beginning instead of chasing the bottom.\n *\n * Every method no-ops when `enabled` is false, so the disabled state can never leak a layout write\n * (padding-bottom) or a scroll call even if a caller forgets a gate.\n */\nexport const usePinQuestionOnSend = (options: {\n enabled: boolean;\n scrollContainer: HTMLDivElement | null;\n getMessagesListEl: () => HTMLElement | null;\n messagesBottomRef: RefObject<HTMLDivElement | null>;\n /** ConversationViewBody's followBottom ref — pinning suspends bottom-follow for the turn. */\n followBottomRef: MutableRefObject<boolean>;\n}) => {\n const { enabled, scrollContainer, getMessagesListEl, messagesBottomRef, followBottomRef } = options;\n\n // While a turn's question is pinned at the top (from send until the next send / a manual scroll / a conversation\n // switch), we reserve empty room below it and stop chasing the bottom, so the reply flows in from its beginning.\n const questionPinnedThisTurn = useRef(false);\n\n const lastUserMessageRow = useCallback((): HTMLElement | null => {\n const list = getMessagesListEl();\n if (!list) return null;\n const rows = list.querySelectorAll<HTMLElement>('[data-message-role=\"USER\"]');\n return rows[rows.length - 1] ?? null;\n }, [getMessagesListEl]);\n\n const userMessageRowCount = useCallback((): number => {\n const list = getMessagesListEl();\n return list ? list.querySelectorAll('[data-message-role=\"USER\"]').length : 0;\n }, [getMessagesListEl]);\n\n // Reserve just enough empty room below the question that it can be scrolled fully to the top; the room shrinks to 0\n // once the reply alone fills the viewport. Pure layout write — no scrolling here.\n const reserveRoomBelowQuestion = useCallback(\n (questionRow: HTMLElement) => {\n const container = scrollContainer;\n const list = getMessagesListEl();\n const bottomMarker = messagesBottomRef.current;\n if (!container || !list || !bottomMarker) return;\n const topClearance = parseFloat(getComputedStyle(questionRow).scrollMarginTop) || 0;\n const realBelow = bottomMarker.offsetTop - questionRow.offsetTop; // question + reply/thinking so far\n const reserved = Math.max(0, container.clientHeight - topClearance - realBelow);\n list.style.paddingBottom = `${reserved}px`;\n },\n [scrollContainer, getMessagesListEl, messagesBottomRef],\n );\n\n // Pin the latest question row to the top and hand the space below to the reply. Returns false (no-op) when the\n // addon is disabled or there is no USER row to pin.\n const pinLatestQuestionToTop = useCallback(\n (behavior: ScrollBehavior): boolean => {\n if (!enabled) return false;\n const questionRow = lastUserMessageRow();\n if (!questionRow) return false;\n reserveRoomBelowQuestion(questionRow); // reserve first, so there's room to lift the question all the way up\n questionRow.scrollIntoView({ behavior, block: \"start\", inline: \"nearest\" });\n followBottomRef.current = false;\n questionPinnedThisTurn.current = true;\n return true;\n },\n [enabled, lastUserMessageRow, reserveRoomBelowQuestion, followBottomRef],\n );\n\n // Re-reserve room below the pinned question; no-op when disabled or not pinned. Used by the positioning layout\n // effect and the ResizeObserver as the reply grows.\n const reserveRoomBelowPinnedQuestion = useCallback(() => {\n if (!enabled || !questionPinnedThisTurn.current) return;\n const questionRow = lastUserMessageRow();\n if (questionRow) reserveRoomBelowQuestion(questionRow);\n }, [enabled, lastUserMessageRow, reserveRoomBelowQuestion]);\n\n const isQuestionPinnedThisTurn = useCallback(() => questionPinnedThisTurn.current, []);\n\n // Clear the pin + remove the reserved padding-bottom (conversation switch, scroll-to-latest).\n const endPinnedTurn = useCallback(() => {\n if (!enabled) return;\n questionPinnedThisTurn.current = false;\n getMessagesListEl()?.style.removeProperty(\"padding-bottom\");\n }, [enabled, getMessagesListEl]);\n\n return {\n pinLatestQuestionToTop,\n reserveRoomBelowPinnedQuestion,\n isQuestionPinnedThisTurn,\n endPinnedTurn,\n userMessageRowCount,\n };\n};\n","import { Text } from \"../../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity, ChatAssistantOpening } from \"../chat-assistant-identity\";\nimport { classNames } from \"../../provider/class-names\";\nimport React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport styles from \"./ConversationViewBody.module.scss\";\nimport {\n ConversationMessageInput,\n ConversationMessageInputHandle,\n} from \"../ConversationMessageInput/ConversationMessageInput\";\nimport { ConversationMessageInputComposerWidgets } from \"../ConversationMessageInput/ConversationMessageInputComposerWidgets/ConversationMessageInputComposerWidgets\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetContext\";\nimport type { ConversationAttachmentReference } from \"../../contract/conversation\";\nimport type { ConversationComposerWidget } from \"../../renderer/conversation-composer-widget\";\nimport { SendMessageHandler } from \"../conversation-send-message\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { NoConversationLoading, ConversationLoading } from \"../ConversationLoadingStates\";\nimport { ConversationMessageList } from \"../ConversationMessageList/ConversationMessageList\";\nimport type { MessageTimesMode } from \"../ConversationMessageList/message-times\";\nimport { WidgetWindowRootContext } from \"../../renderer/widget-windowing\";\nimport { ConversationIntroWidget } from \"../ConversationIntroWidget/ConversationIntroWidget\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport { ConversationMessageUserTheme } from \"../ConversationMessage/ConversationMessageUser/ConversationMessageUser\";\nimport { ConversationScrollToLatestMessageButton } from \"../ConversationScrollToLatestMessageButton/ConversationScrollToLatestMessageButton\";\nimport { useIsMessagesBottomOutOfView } from \"./hooks/useIsMessagesBottomOutOfView\";\nimport { usePinQuestionOnSend } from \"./hooks/usePinQuestionOnSend\";\n\nexport interface ConversationViewProps {\n currentCategory?: ChatAssistantCategory; // Type from categories\n aiPromptExtension?: ChatAssistantIdentity; // Type from agents\n suggestions?: ChatAssistantOpening[]; // Type from conversationOpenings\n messages: ChatMessage[] | null; // Type from messages\n aiThinking: boolean;\n error: ConversationErrorType | null;\n /** Retry-After seconds of a 429 quota rejection — forwarded to the error card for the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /** Host-bound retry of a FAILED run — forwarded to the message list / error card. */\n onRetryFailedRun?: () => Promise<void>;\n isDebugMode: boolean;\n categoriesLoaded: boolean;\n conversationId?: number;\n startingNewConversation?: boolean;\n /**\n * Show the message list even when no conversation exists yet. Used by a host,\n * whose fresh (not-yet-created) chat renders its empty message list.\n */\n showMessagesWithoutConversation?: boolean;\n /**\n * Follow the conversation bottom (scroll-on-mount + resize follow). Default true.\n * A host disables it for a fresh chat that has no messages yet, so the view stays\n * anchored at the top.\n */\n autoScroll?: boolean;\n /**\n * Custom node mounted at the tail of the message list instead of the default\n * (thinking-only) ConversationMessageThinking. Rendered permanently — used by\n * A host to show the animated agent face, which idles between turns.\n */\n thinkingIndicator?: React.ReactNode;\n /**\n * Custom background slot rendered absolutely behind the chat content. When\n * provided, the default chat gradient and the AI-Extensions category\n * illustrations are suppressed so the caller owns the entire background\n * (e.g. A host's shader). Pair with a parent that supplies a solid base color\n * if the slot doesn't paint the full canvas itself.\n */\n background?: React.ReactNode;\n /**\n * Opt-in: the host paints the chat's background itself OUTSIDE this component (e.g. the agent's root shader).\n * Keeps the `customBg` visual mode (top blur band) that passing `background` would give, but with\n * no background node here and a transparent pane fill so the host's layer shows through.\n */\n backgroundPaintedByHost?: boolean;\n /**\n * The setup progress stepper (today's only consumer: the agent chat), mounted as a DIRECT CHILD of this\n * view's pane root — a `position: relative` box the size of the chat pane — and outside the scroll container,\n * so it stays put while messages scroll under it. Mounted here rather than in the host's floating top bar for\n * the same reason the top blur band is (see `.contentWrapper::before`): it has to track the chat content\n * column, so it follows the pane when a canvas or a side panel contracts it, which a viewport-positioned\n * overlay cannot — and that pane boundary exists only inside this view's split.\n *\n * The node brings its OWN positioning, stacking and query container (see the stepper's `.progressStepperRow`);\n * this view contributes nothing but the positioned pane root it is mounted in.\n */\n progressStepperSlot?: React.ReactNode;\n /**\n * Host-owned layer shown while files are dragged over the window: this chat takes them. Like `progressStepperSlot`\n * the node positions itself against the pane root; it lies over the messages and under the input.\n */\n fileDropHintSlot?: React.ReactNode;\n /**\n * Optional external ref to the scrollable content wrapper. Forwarded so\n * callers can drive scroll-linked effects (e.g. an animated background\n * that morphs with scroll position) without having to query the DOM.\n */\n scrollRef?: React.Ref<HTMLDivElement>;\n /**\n * Bump to force a scroll to the newest message (via {@link scrollToLatestMessage}, so it clears any pinned turn and\n * re-enables bottom-follow). Each distinct value triggers one scroll; the initial `0`/`undefined` is ignored. Used by\n * the agent to follow the turn a widget/CTA-click signal starts (which posts no visible message of its own).\n */\n scrollToBottomNonce?: number;\n /**\n * Optional external override of the internal bottom-follow flag. Provide it when the host runs its own programmatic\n * scroll away from the bottom (e.g. the agent's search-result jump, which pages older messages in and scrolls to\n * a message far above the bottom): the host sets it `false` for the jump so the resize/message-follow effects stop\n * re-anchoring to the bottom and yanking the view back mid-jump. Left undefined, ConversationViewBody uses its own ref and\n * behaves exactly as before. Shared with the AW-107 pin machinery, so both agree on one flag.\n */\n followBottomRef?: React.MutableRefObject<boolean>;\n /**\n * Optional \"a programmatic jump is in flight\" gate. Set by the host (the agent's search-result jump) for the duration of a\n * jump. While true, the near-bottom onScroll handler does NOT re-enable bottom-follow and the resize ResizeObserver\n * does NOT auto-scroll to the bottom — otherwise, right after the jump the container is still near the bottom, so\n * onScroll would flip follow back on and the follow-up content-resize would yank the view back down. Left undefined,\n * nothing is gated. Distinct from `followBottomRef`: that flag alone is clobbered by onScroll; this gate stops it.\n */\n scrollJumpActiveRef?: React.MutableRefObject<boolean>;\n /**\n * Hide the assistant header (icon + name + \"Assistant\") and the copy button\n * on assistant messages. Used by a host, which renders bare messages.\n */\n hideAssistantMeta?: boolean;\n /**\n * Theme for user-message bubbles, forwarded to ConversationMessageList. A host forces\n * \"dark\"; when omitted the list falls back to its legacy light/default logic.\n */\n userMessageTheme?: ConversationMessageUserTheme;\n /**\n * True when the host (the agent) is minimized to the compact side-panel; forwarded to ConversationViewBody.\n */\n isCompact?: boolean;\n /**\n * Opt-in (agent host only): confine the customBg top blur band to the chat pane instead of the whole viewport —\n * active only while a sibling side panel is docked beside the chat, so the band compresses together with it instead\n * of bleeding across the panel. See `.confineTopBlurBandToChatPane` below.\n */\n confineTopBlurBandToChatPane?: boolean;\n /**\n * Scroll-up older-message pagination (opt-in — mirrors the admin inspector). When `onLoadOlder` is provided, a top\n * sentinel + IntersectionObserver (root = the scroll container) prefetches the next older page ~300px before the\n * top, and the viewport is anchored across the prepend so it doesn't jump. `hasMoreOlder` gates the sentinel;\n * `loadingOlder` shows a small loading row. Left undefined (the default) → no pagination, behaviour unchanged.\n */\n hasMoreOlder?: boolean;\n loadingOlder?: boolean;\n onLoadOlder?: () => void;\n /**\n * Extra action controls rendered inside the chat input's action row, left of the send button —\n * forwarded to ConversationMessageInput (e.g. the agent model picker pill).\n */\n inputActionsSlot?: React.ReactNode;\n /**\n * Action controls pinned to the LEFT edge of the chat input's action row (`inputActionsSlot`\n * stays right) — forwarded to ConversationMessageInput's `actionsSlotStart` (e.g. the agent \"+\" attachments menu).\n */\n inputActionsSlotStart?: React.ReactNode;\n /**\n * Host-owned content rendered inside the chat input above its editable text area — attachment\n * preview cards, validation error boxes. Forwarded to ConversationMessageInput's `topSlot`.\n */\n inputTopSlot?: React.ReactNode;\n /**\n * Hard send gate for the chat input: blocks the send button AND Enter while true, but keeps the\n * text editable. The host sets it e.g. while attachment uploads run.\n */\n inputSendDisabled?: boolean;\n /**\n * Host-owned content rendered IN PLACE of the chat input — the closed-conversation bar of a completed\n * setup conversation (no further input possible). When set, the body renders it instead of ConversationMessageInput,\n * in a wrapper carrying the input's own width, bottom gap and stacking rule — so the node needs no layout of its\n * own, and the background layer cannot paint over it.\n */\n inputReplacementSlot?: React.ReactNode;\n /**\n * Host-owned band right above the chat input, the input overlapping its lower edge — e.g. the running voice chat\n * with its controls. Not rendered while `inputReplacementSlot` replaces the input.\n */\n inputBandSlot?: React.ReactNode;\n /** The chat input's placeholder; the input's own default otherwise. */\n inputPlaceholder?: string;\n /** Forwarded to ConversationMessageInput's `sendReplacementWhenEmpty`. */\n inputSendReplacementWhenEmpty?: React.ReactNode;\n /** Forwarded to ConversationMessageInput's `glowUnderlay`. */\n inputGlowUnderlay?: React.ReactNode;\n /**\n * Host-owned layer over the message column, the same size — e.g. the voice chat's focus mode. The message column\n * stays mounted under it (scroll position and widget state kept); `isContentOverlayShown` switches between them.\n */\n contentOverlaySlot?: React.ReactNode;\n isContentOverlayShown?: boolean;\n /**\n * Uploaded media-library images that ride along in `onSendMessage`'s options object (`attachments`) on the next\n * send. Owned and cleared by the host; forwarded to ConversationMessageInput.\n */\n outgoingAttachmentImages?: ConversationAttachmentReference[];\n /**\n * Composer widgets the host holds outside the widget context (e.g. a widget built from the files the host\n * uploaded), sent like the context's own on the next send. Owned and cleared by the host; forwarded to\n * ConversationMessageInput.\n */\n hostComposerWidgets?: ConversationComposerWidget[];\n /**\n * Imperative handle on the chat input (insertTextIntoInput) so host-owned controls — e.g. the\n * \"+\" menu's \"Generate image\" entry — can put text into it. Forwarded to ConversationMessageInput's `apiRef`.\n */\n conversationMessageInputApiRef?: React.Ref<ConversationMessageInputHandle>;\n /**\n * Keep the chat input editable and sendable while `aiThinking` is true (default false — the input locks for the\n * whole turn); only the first post of a new conversation still locks it, while no conversation id exists yet. Opt\n * in ONLY for a host whose post call stores the message and returns at once, and whose agent checks for unanswered\n * messages when its turn ends, so a message sent mid-turn is answered in the next turn. A host whose post call\n * generates the reply synchronously within the request has no such guard and must leave it off.\n */\n allowSendWhileAiThinking?: boolean;\n /**\n * Opt-in long-answer reading flow (AW-107), default false. When enabled:\n * (1) on send, the question is pinned to the top with room reserved below it so the reply\n * reveals from its beginning instead of chasing the bottom;\n * (2) a scroll-to-latest-message button floats above the input while the bottom is out of view;\n * (3) a fresh static reply's markdown blocks fade in staggered (useFreshMessageBlockReveal).\n * Left off, the chat keeps the classic bottom-follow behavior — AI Extensions stays off;\n * the agent chat opts in.\n */\n enablePinQuestionAndRevealAnswer?: boolean;\n /** New user messages are not sends (a voice chat saves the owner's spoken sentences): keep bottom-follow, no pin. */\n isQuestionPinSuspended?: boolean;\n /**\n * Id of the ONE user message ConversationMessageList renders as a collapsed task-instruction disclosure instead of an\n * owner bubble — the machine-composed seed instruction of a SCHEDULE-spawned run (UX overhaul W4 item 19).\n * Undefined (every host except the agent chat) changes nothing.\n */\n taskInstructionMessageId?: number;\n /**\n * Host content rendered right after one message of the thread, forwarded to ConversationMessageList (the agent chat's\n * activity card under the message that started each turn). Undefined changes nothing.\n */\n renderAfterMessage?: (message: ChatMessage) => React.ReactNode;\n /** Host content beside each shown assistant message (an avatar face), forwarded to ConversationMessageList. */\n renderAssistantAvatar?: (message: ChatMessage) => React.ReactNode;\n /** Forwarded to ConversationMessageList: a closed conversation renders no widget controls. */\n isConversationClosed?: boolean;\n /** Forwarded to ConversationMessageList: when what was written (`MessageTimesMode`). */\n messageTimes?: MessageTimesMode | null;\n onSuggestionClick: (text: string) => void;\n onSendMessage: SendMessageHandler;\n}\n\nexport const ConversationViewBody = (props: ConversationViewProps) => {\n const {\n currentCategory,\n aiPromptExtension,\n suggestions,\n messages,\n aiThinking,\n error,\n rateLimitRetryAfterSeconds,\n onRetryFailedRun,\n isDebugMode,\n categoriesLoaded,\n startingNewConversation,\n conversationId,\n showMessagesWithoutConversation,\n autoScroll = true,\n thinkingIndicator,\n background,\n backgroundPaintedByHost,\n progressStepperSlot,\n fileDropHintSlot,\n scrollRef,\n scrollToBottomNonce,\n followBottomRef,\n scrollJumpActiveRef,\n hideAssistantMeta,\n userMessageTheme,\n isCompact,\n confineTopBlurBandToChatPane,\n hasMoreOlder,\n loadingOlder,\n onLoadOlder,\n inputActionsSlot,\n inputActionsSlotStart,\n inputTopSlot,\n inputSendDisabled,\n inputReplacementSlot,\n inputBandSlot,\n inputPlaceholder,\n inputSendReplacementWhenEmpty,\n inputGlowUnderlay,\n contentOverlaySlot,\n isContentOverlayShown = false,\n outgoingAttachmentImages,\n hostComposerWidgets,\n conversationMessageInputApiRef,\n allowSendWhileAiThinking,\n enablePinQuestionAndRevealAnswer = false,\n isQuestionPinSuspended = false,\n taskInstructionMessageId,\n renderAfterMessage,\n renderAssistantAvatar,\n isConversationClosed,\n messageTimes,\n onSuggestionClick,\n onSendMessage,\n } = props;\n\n // Composer widgets ride the widget context itself (like the deleted selection chip did), so every\n // ConversationView host gets the strip, the outgoing-on-send value and the clear-on-send wiring for free.\n const { composerWidgets, clearComposerWidgets } = useConversationWidgetContext();\n\n const messagesBottom = useRef<HTMLDivElement | null>(null);\n const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(null);\n const [messagesList, setMessagesList] = useState<HTMLDivElement | null>(null);\n // Bottom-follow flag. Uses the host-supplied ref when given (so a host-driven jump can suspend follow, see\n // `followBottomRef` in props), otherwise a local one — identical behaviour when no host overrides it.\n const internalFollowBottom = useRef(true);\n const followBottom = followBottomRef ?? internalFollowBottom;\n // Rendered USER-row count at the last positioning pass — an increase within the same conversation means the user\n // just sent (the pin trigger). Counted from the DOM (not the messages array) so hidden USER messages (/toolresult\n // reports, SIGNAL/ERROR) never miscount and it always matches the row pinLatestQuestionToTop targets.\n const prevUserMessageCount = useRef(0);\n // Last conversationId the positioning effect saw, to tell a real switch / new-chat (re-anchor to bottom) apart from\n // the cold-start id landing mid-turn (undefined → a freshly-created id while pinned → keep the pin).\n const prevConversationId = useRef<number | undefined>(conversationId);\n // Scroll-up pagination (opt-in via onLoadOlder). Capturing the scrollHeight when an older-load starts lets the\n // prepend layout-effect restore the viewport so it doesn't jump when the older page merges in.\n const prependAnchorScrollHeight = useRef<number | null>(null);\n\n // Combined ref callback for the scrollable content wrapper: drives the\n // internal state ref (the auto-scroll / follow-bottom effects depend on it)\n // AND forwards to the caller-supplied `scrollRef` when present. Stable identity\n // so the ref isn't detached/reattached on every render.\n const handleContentWrapperRef = useCallback(\n (el: HTMLDivElement | null) => {\n setScrollContainer(el);\n if (typeof scrollRef === \"function\") scrollRef(el);\n else if (scrollRef) (scrollRef as React.MutableRefObject<HTMLDivElement | null>).current = el;\n },\n [scrollRef],\n );\n\n // The named assistant's theme and background come from the app; the agent chat shows none.\n const { readAssistantThemeClassName, AssistantBackground } = useAgentsEnvironment();\n const colorPalette = useMemo(\n () =>\n currentCategory?.alias\n ? (readAssistantThemeClassName?.(currentCategory.alias) ?? styles.genericChat)\n : styles.genericChat,\n [currentCategory, readAssistantThemeClassName],\n );\n\n const isMessageListVisible =\n (!!messages && (!!conversationId || !!showMessagesWithoutConversation)) ||\n startingNewConversation ||\n (!!error && error !== ConversationErrorType.CONVERSATION_NOT_FOUND);\n\n const isConversationIntroVisible = useMemo(\n () =>\n aiPromptExtension !== undefined &&\n !conversationId &&\n !startingNewConversation &&\n !messages &&\n !(!!error && error !== ConversationErrorType.CONVERSATION_NOT_FOUND),\n [aiPromptExtension, conversationId, startingNewConversation, messages, error],\n );\n\n // The list DOM node. Prefer the state ref (it drives the ResizeObserver effect); fall back to the bottom marker's\n // parent, which is always the .chatMessages list — needed in the layout effect on the render where the list first\n // mounts (setMessagesList hasn't flushed to state yet, but messagesBottom's ref is already committed).\n const getMessagesListEl = useCallback(\n (): HTMLElement | null => messagesList ?? messagesBottom.current?.parentElement ?? null,\n [messagesList],\n );\n\n const {\n pinLatestQuestionToTop,\n reserveRoomBelowPinnedQuestion,\n isQuestionPinnedThisTurn,\n endPinnedTurn,\n userMessageRowCount,\n } = usePinQuestionOnSend({\n enabled: enablePinQuestionAndRevealAnswer,\n scrollContainer,\n getMessagesListEl,\n messagesBottomRef: messagesBottom,\n followBottomRef: followBottom,\n });\n\n // First positioning is instant and pre-paint (layout effect + behavior \"auto\"):\n // opening a conversation lands directly at the bottom with no visible scroll\n // animation. Subsequent message updates scroll smoothly.\n const hasPositionedOnce = useRef(false);\n useLayoutEffect(() => {\n // Older-page prepend (scroll-up pagination): restore the viewport so the freshly-prepended messages don't shift\n // it, and do NOT auto-scroll to the bottom. The anchor is only set when an older-load started, so a conversation\n // switch / live tick never enters this branch.\n if (prependAnchorScrollHeight.current !== null) {\n if (scrollContainer) {\n const delta = scrollContainer.scrollHeight - prependAnchorScrollHeight.current;\n if (delta > 0) scrollContainer.scrollTop += delta;\n }\n prependAnchorScrollHeight.current = null;\n return;\n }\n if (!autoScroll) {\n hasPositionedOnce.current = false;\n return;\n }\n\n // Addon off (default): the classic bottom-follow — re-anchor to the bottom on every message update, exactly the\n // pre-AW-107 behavior (including the old quirk that it scrolls even before the list mounts, no messagesBottom guard).\n if (!enablePinQuestionAndRevealAnswer) {\n followBottom.current = true;\n messagesBottom.current?.scrollIntoView({\n behavior: hasPositionedOnce.current ? \"smooth\" : \"auto\",\n block: \"end\",\n inline: \"nearest\",\n });\n hasPositionedOnce.current = true;\n return;\n }\n\n // A real conversation switch / new-chat / first history load re-anchors to the bottom. The one exception is the\n // cold-start id landing (undefined → a freshly-created id) MID-TURN: the question was already pinned on send, so\n // keep it pinned instead of yanking back to the bottom.\n const conversationChanged = prevConversationId.current !== conversationId;\n const isColdStartIdLanding = prevConversationId.current === undefined && isQuestionPinnedThisTurn();\n prevConversationId.current = conversationId;\n if (conversationChanged && !isColdStartIdLanding) {\n endPinnedTurn();\n followBottom.current = true;\n hasPositionedOnce.current = false;\n }\n\n const userCount = userMessageRowCount();\n\n // First positioning for this conversation. If the list isn't mounted yet (still loading / intro screen), wait for\n // it. A fresh cold-start send (startingNewConversation, nothing positioned yet) pins the first question to the top;\n // opening an existing conversation lands at the bottom, as today.\n if (!hasPositionedOnce.current) {\n if (!messagesBottom.current) return; // list not in the DOM yet — nothing to position\n hasPositionedOnce.current = true;\n prevUserMessageCount.current = userCount;\n if (startingNewConversation && userCount > 0) {\n pinLatestQuestionToTop(\"auto\");\n } else {\n followBottom.current = true;\n messagesBottom.current.scrollIntoView({ behavior: \"auto\", block: \"end\", inline: \"nearest\" });\n }\n return;\n }\n\n // Same conversation, already positioned: a new USER row means the user just sent → pin the new question to the top.\n if (userCount > prevUserMessageCount.current && !isQuestionPinSuspended) {\n prevUserMessageCount.current = userCount;\n pinLatestQuestionToTop(\"smooth\");\n return;\n }\n prevUserMessageCount.current = userCount;\n\n // A later update within the same turn (the reply arriving / growing): keep the question pinned and just re-reserve\n // room — never scroll. Outside a pinned turn (e.g. a background refresh) keep today's bottom-follow.\n if (isQuestionPinnedThisTurn()) {\n reserveRoomBelowPinnedQuestion();\n } else if (followBottom.current) {\n messagesBottom.current?.scrollIntoView({ behavior: \"smooth\", block: \"end\", inline: \"nearest\" });\n }\n }, [\n messages,\n autoScroll,\n scrollContainer,\n conversationId,\n startingNewConversation,\n enablePinQuestionAndRevealAnswer,\n isQuestionPinSuspended,\n userMessageRowCount,\n reserveRoomBelowPinnedQuestion,\n pinLatestQuestionToTop,\n isQuestionPinnedThisTurn,\n endPinnedTurn,\n followBottom,\n ]);\n\n // Capture the scroll height the instant an older-load starts — consumed by the prepend layout-effect above to keep\n // the viewport anchored once the older page merges in.\n useEffect(() => {\n if (loadingOlder && scrollContainer) {\n prependAnchorScrollHeight.current = scrollContainer.scrollHeight;\n }\n }, [loadingOlder, scrollContainer]);\n\n // Scroll-up lazy-load: prefetch the next older page when the user scrolls within ~300px of the top. onLoadOlder is\n // self-guarded (in-flight + hasMoreOlder) by the caller, so repeated scroll ticks near the top don't double-fetch.\n // No-op unless the caller opts in via onLoadOlder.\n useEffect(() => {\n if (!onLoadOlder || !scrollContainer || !hasMoreOlder) return undefined;\n const onScrollNearTop = () => {\n if (scrollContainer.scrollTop <= 300) onLoadOlder();\n };\n scrollContainer.addEventListener(\"scroll\", onScrollNearTop, { passive: true });\n return () => scrollContainer.removeEventListener(\"scroll\", onScrollNearTop);\n }, [onLoadOlder, scrollContainer, hasMoreOlder]);\n\n useEffect(() => {\n if (!autoScroll) return;\n const container = scrollContainer;\n const list = messagesList;\n if (!container || !list) return;\n\n const NEAR_BOTTOM_PX = 80;\n const isNearBottom = () => container.scrollHeight - container.scrollTop - container.clientHeight <= NEAR_BOTTOM_PX;\n\n let animRaf: number | null = null;\n let isProgrammaticScroll = false;\n const cancelAnim = () => {\n if (animRaf !== null) {\n cancelAnimationFrame(animRaf);\n animRaf = null;\n }\n };\n\n // Non-interruptible smooth scroll: if already running, the existing\n // animation just re-reads the target each frame and chases it — no\n // restart, no blink. Only user interaction or unmount cancels it.\n const startSmoothToBottom = (durationMs: number) => {\n if (animRaf !== null) return; // in-flight; target re-read each frame\n const start = container.scrollTop;\n const initialTarget = container.scrollHeight - container.clientHeight;\n if (initialTarget - start <= 0) return;\n const t0 = performance.now();\n const easeOut = (t: number) => 1 - Math.pow(1 - t, 3);\n const tick = (now: number) => {\n const t = Math.min(1, (now - t0) / durationMs);\n const target = container.scrollHeight - container.clientHeight;\n isProgrammaticScroll = true;\n container.scrollTop = start + (target - start) * easeOut(t);\n isProgrammaticScroll = false;\n if (t < 1) {\n animRaf = requestAnimationFrame(tick);\n } else {\n animRaf = null;\n }\n };\n animRaf = requestAnimationFrame(tick);\n };\n\n const disableFollow = () => {\n followBottom.current = false;\n // A pinned turn (AW-107) keeps its pin + reserved room across a manual scroll — we deliberately do NOT clear them\n // here. Dropping the padding on scroll shrank the scroll height and made the viewport jump; and the empty space\n // below a short reply is intentional, so the question holds its place at the top for the whole turn.\n cancelAnim();\n };\n const onScroll = () => {\n if (isProgrammaticScroll) return;\n // A host-driven jump is in flight: don't re-enable follow just because the viewport is still/again near the\n // bottom — that clobbers the jump and lets the resize-follow yank the view back down.\n if (scrollJumpActiveRef?.current) return;\n if (isNearBottom()) followBottom.current = true;\n };\n\n container.addEventListener(\"wheel\", disableFollow, { passive: true });\n container.addEventListener(\"touchmove\", disableFollow, { passive: true });\n container.addEventListener(\"keydown\", disableFollow);\n container.addEventListener(\"scroll\", onScroll, { passive: true });\n\n const observer = new ResizeObserver(() => {\n // A host-driven jump is in flight (search-result jump): the messages settle their heights as they render, which\n // fires this observer — do NOT auto-scroll to the bottom, or the jump gets yanked back down.\n if (scrollJumpActiveRef?.current) return;\n // During a pinned turn the reply grows below the fold: re-reserve room (it shrinks to 0 as the reply fills the\n // viewport) — never scroll, so the question stays put at the top. Inert when the addon is off (pin never set).\n if (isQuestionPinnedThisTurn()) {\n reserveRoomBelowPinnedQuestion();\n return;\n }\n if (!followBottom.current) return;\n startSmoothToBottom(180);\n });\n observer.observe(list);\n // Also react to viewport/pane height changes (window resize, drawer open/close): the list observer won't fire when\n // only the container's height changes, but a pinned turn's reserved room depends on container.clientHeight. Only\n // needed for the addon — leaving it on for the default chat would newly trigger scroll-to-bottom on drawer toggle.\n if (enablePinQuestionAndRevealAnswer) observer.observe(container);\n\n return () => {\n container.removeEventListener(\"wheel\", disableFollow);\n container.removeEventListener(\"touchmove\", disableFollow);\n container.removeEventListener(\"keydown\", disableFollow);\n container.removeEventListener(\"scroll\", onScroll);\n observer.disconnect();\n cancelAnim();\n };\n }, [\n isMessageListVisible,\n scrollContainer,\n messagesList,\n autoScroll,\n enablePinQuestionAndRevealAnswer,\n isQuestionPinnedThisTurn,\n reserveRoomBelowPinnedQuestion,\n followBottom,\n scrollJumpActiveRef,\n ]);\n\n // Only observe the sentinel when the addon is on — a null container makes the hook return false + mount no observer.\n const isMessagesBottomOutOfView = useIsMessagesBottomOutOfView(\n enablePinQuestionAndRevealAnswer ? scrollContainer : null,\n messagesList,\n messagesBottom,\n );\n\n // Jump back to the newest message. Ends a pinned turn: the user is explicitly leaving the pinned\n // question, so bottom-follow takes over again (the ResizeObserver's pinned branch would otherwise\n // keep suppressing it, ConversationViewBody.tsx:396). Dropping the reserved padding here cannot jump the\n // viewport: the button only shows when the viewport is ≥300px ABOVE the sentinel, and the padding\n // lives entirely BELOW it — shrinking scrollHeight below the viewport doesn't move scrollTop.\n const scrollToLatestMessage = useCallback(() => {\n endPinnedTurn();\n followBottom.current = true;\n messagesBottom.current?.scrollIntoView({ behavior: \"smooth\", block: \"end\", inline: \"nearest\" });\n }, [endPinnedTurn, followBottom]);\n\n // Caller-driven scroll-to-bottom (scrollToBottomNonce bumped per widget/CTA-click signal). Goes through\n // scrollToLatestMessage so it clears any pinned turn and re-enables bottom-follow — a raw scrollTo would be\n // suppressed while a turn is pinned. Ignores the initial 0/undefined so it never scrolls on mount.\n useEffect(() => {\n if (!scrollToBottomNonce) return;\n scrollToLatestMessage();\n }, [scrollToBottomNonce, scrollToLatestMessage]);\n\n const messageColumn = (\n <div\n className={styles.contentWrapper}\n // A stable hook for a host's own stylesheet (the default chat drops the top blur band, it has no top bar).\n data-agents-chat-scroll=\"\"\n data-testid=\"chat-messages-scroll\"\n ref={handleContentWrapperRef}\n aria-hidden={isContentOverlayShown || undefined}\n inert={isContentOverlayShown || undefined}\n >\n {!conversationId && !categoriesLoaded && !aiPromptExtension ? (\n <NoConversationLoading />\n ) : null}\n\n {!!conversationId && !messages ? (\n <ConversationLoading />\n ) : null}\n\n {isConversationIntroVisible ? (\n <ConversationIntroWidget\n aiPromptExtension={aiPromptExtension!}\n aiPromptExtensionIcon={aiPromptExtension!.iconClass as string}\n suggestions={suggestions}\n onSuggestionClick={onSuggestionClick}\n />\n ) : null}\n\n {!!loadingOlder ? (\n <span className={styles.olderLoading}>\n <Text>{\"Loading older messages…\"}</Text>\n </span>\n ) : null}\n\n {isMessageListVisible ? (\n <>\n {/* The scroll container (this contentWrapper) is the IntersectionObserver root for widget viewport-windowing. */}\n <WidgetWindowRootContext.Provider value={scrollContainer}>\n <ConversationMessageList\n className={\n enablePinQuestionAndRevealAnswer && (conversationId || startingNewConversation || aiThinking || error)\n ? styles.topAlignedMessages\n : undefined\n }\n messages={messages}\n currentCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n isDebugMode={isDebugMode}\n aiThinking={aiThinking}\n thinkingIndicator={thinkingIndicator}\n hideAssistantMeta={hideAssistantMeta}\n userMessageTheme={userMessageTheme}\n error={error}\n rateLimitRetryAfterSeconds={rateLimitRetryAfterSeconds}\n onRetryFailedRun={onRetryFailedRun}\n messagesBottomRef={messagesBottom}\n messagesListRef={setMessagesList}\n enableFreshMessageBlockReveal={enablePinQuestionAndRevealAnswer}\n taskInstructionMessageId={taskInstructionMessageId}\n renderAfterMessage={renderAfterMessage}\n renderAssistantAvatar={renderAssistantAvatar}\n isConversationClosed={isConversationClosed}\n messageTimes={messageTimes}\n />\n </WidgetWindowRootContext.Provider>\n </>\n ) : null}\n </div>\n );\n\n return (\n <div\n className={classNames(\n styles.chat,\n background || backgroundPaintedByHost ? styles.customBg : colorPalette,\n backgroundPaintedByHost ? styles.backgroundPaintedByHost : undefined,\n isCompact ? styles.chatCompact : undefined,\n confineTopBlurBandToChatPane ? styles.confineTopBlurBandToChatPane : undefined,\n )}\n >\n {background ? (\n <div className={styles.backgroundLayer}>{background}</div>\n ) : backgroundPaintedByHost ? null : (\n AssistantBackground ? (\n <AssistantBackground category={currentCategory} categoryAlias={currentCategory?.alias ?? undefined} />\n ) : null\n )}\n\n {/* Positions itself against this .chat root (see the prop's doc) — no wrapper, no class from here. */}\n {progressStepperSlot}\n {fileDropHintSlot}\n\n {contentOverlaySlot !== undefined ? (\n <div className={styles.contentLayers} data-overlay-shown={isContentOverlayShown || undefined}>\n {messageColumn}\n <div\n className={styles.contentOverlay}\n aria-hidden={!isContentOverlayShown || undefined}\n inert={!isContentOverlayShown || undefined}\n >\n {contentOverlaySlot}\n </div>\n </div>\n ) : (\n messageColumn\n )}\n {enablePinQuestionAndRevealAnswer && (\n <div className={styles.scrollToLatestAnchor}>\n <ConversationScrollToLatestMessageButton\n visible={isMessagesBottomOutOfView}\n onClick={scrollToLatestMessage}\n />\n </div>\n )}\n {/* With allowSendWhileAiThinking the input stays open during a turn, EXCEPT while the cold-start\n startWithMessage POST is in flight: no conversation id exists yet, so the host's send handler would drop a\n second message silently — keep the brief lock for exactly that window. */}\n {inputReplacementSlot ? (\n <div className={styles.inputReplacement}>{inputReplacementSlot}</div>\n ) : (\n <>\n {inputBandSlot}\n <ConversationMessageInput\n className={classNames(styles.input, currentCategory?.alias ? styles.inputInCategory : undefined)}\n isProcessing={allowSendWhileAiThinking ? !!startingNewConversation : aiThinking}\n onSendMessage={onSendMessage}\n actionsSlot={inputActionsSlot}\n actionsSlotStart={inputActionsSlotStart}\n // The composer-widgets strip is one topSlot block like any other — above the host's own blocks\n // (attachment previews sit closest to the text). It reads the widget context itself, so every\n // ConversationView host gets it for free.\n topSlot={\n <>\n <ConversationMessageInputComposerWidgets testId=\"chat-input\" />\n {inputTopSlot}\n </>\n }\n sendDisabled={inputSendDisabled}\n outgoingAttachmentImages={outgoingAttachmentImages}\n hostComposerWidgets={hostComposerWidgets}\n outgoingComposerWidgets={composerWidgets}\n onComposerWidgetsSent={clearComposerWidgets}\n apiRef={conversationMessageInputApiRef}\n placeholder={inputPlaceholder}\n sendReplacementWhenEmpty={inputSendReplacementWhenEmpty}\n glowUnderlay={inputGlowUnderlay}\n />\n </>\n )}\n </div>\n );\n};\n","import type { AgentsCanvasLayout } from \"../provider/environment\";\nimport { useAgentsEnvironment } from \"../provider/AgentsProvider\";\nimport { CANVAS_BOXED_INSET_PX, CHAT_COLUMN_MIN_WIDTH_PX } from \"../renderer/canvas/canvas-behaviours\";\n\n/** `AgentsCanvasLayout` with every member set: the host's value, else the package's own chrome. */\nexport interface ResolvedCanvasLayout {\n readonly showsCloseButton: boolean;\n readonly showsDividerToggle: boolean;\n readonly showsNarrowReopenControl: boolean;\n readonly chatColumnMinWidthPx: number;\n readonly boxedInsetPx: number;\n readonly paneSurface: \"card\" | \"none\";\n}\n\nexport const resolveCanvasLayout = (layout: AgentsCanvasLayout | undefined): ResolvedCanvasLayout => ({\n showsCloseButton: layout?.showsCloseButton ?? true,\n showsDividerToggle: layout?.showsDividerToggle ?? true,\n showsNarrowReopenControl: layout?.showsNarrowReopenControl ?? true,\n chatColumnMinWidthPx: Math.max(0, layout?.chatColumnMinWidthPx ?? CHAT_COLUMN_MIN_WIDTH_PX),\n boxedInsetPx: Math.max(0, layout?.boxedInsetPx ?? CANVAS_BOXED_INSET_PX),\n paneSurface: layout?.paneSurface ?? \"card\",\n});\n\n/** The canvas layout of this subtree's environment (`AgentsEnvironment.canvasLayout`). */\nexport const useCanvasLayout = (): ResolvedCanvasLayout => resolveCanvasLayout(useAgentsEnvironment().canvasLayout);\n","import { Button, LoadingSpinner } from \"../../provider/components\";\nimport { classNames } from \"../../provider/class-names\";\nimport React, { Fragment, useEffect, useState } from \"react\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetContext\";\nimport { ConversationWidgetErrorBoundary } from \"../../renderer/ConversationWidgetErrorBoundary\";\nimport { canvasBehaviourOf } from \"../../renderer/canvas/canvas-behaviours\";\nimport {\n canvasBodies,\n canvasFeatureFlagOf,\n} from \"../../renderer/canvas/canvasBodies\";\nimport { CanvasTitleSlotContext } from \"../../renderer/canvas/canvas-title-slot-context\";\nimport { ConversationWidgetFeatureGate } from \"../../renderer/_access/ConversationWidgetFeatureGate\";\nimport { normalizeServerMessageToMarkdown } from \"../normalize-server-message-to-markdown\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport { useCanvasLayout } from \"../canvas-layout\";\nimport classes from \"./CanvasPane.module.scss\";\n\ninterface CanvasPaneProps {\n /** The host's loaded messages — a message-anchored canvas body parses its fence out of its anchor message. */\n messages: ChatMessage[] | null;\n /** Render as a rounded surface card (agent side-split — the pane is inset below the floating top bar). */\n boxed?: boolean;\n}\n\n// The canvas slides in via a main-thread react-spring animation. Mounting a heavy body (e.g. an app's full list\n// page) DURING that slide blocks the animation frames and makes opening stagger. So we hold the content for a beat — a\n// light loader fills the pane while it slides in, then the body mounts.\nconst CANVAS_OPEN_SETTLE_MS = 350;\n\nconst OpeningLoader = () => (\n // Cheap, content-agnostic placeholder shown while the canvas slides in, so the open animation isn't blocked by the\n // body's mount. A centered spinner (not a content-shaped skeleton) because the canvas hosts many different bodies.\n <div className={classes.openingLoader} aria-hidden>\n <LoadingSpinner />\n </div>\n);\n\n/**\n * The CANVAS PANE — renders the canvas the chat's slice points at (`canvas`, a pointer to its anchor): the body from\n * `canvasBodies`, keyed on `mountGeneration`, geometry from its behaviour (`canvasBehaviourOf`), the canvas's own feature gate and the\n * shared error boundary. A message-anchored body receives its anchor message's markdown and re-reads its widget's\n * payload from it — nothing but the pointer is stored anywhere.\n */\nexport const CanvasPane = ({ messages, boxed = false }: CanvasPaneProps) => {\n const CanvasBodyContainer = useAgentsEnvironment().CanvasBodyContainer ?? Fragment;\n const { canvas, closeCanvas, chatAgentSpaceKey } = useConversationWidgetContext();\n // A host that frames the canvas itself (`AgentsEnvironment.canvasLayout`) may close it from its own chrome and paint\n // its own card.\n const { showsCloseButton, paneSurface } = useCanvasLayout();\n\n // Re-deferred on every open (the mountGeneration changes each time a canvas mounts).\n const mountGeneration = canvas?.mountGeneration;\n const [contentReady, setContentReady] = useState(false);\n const [titleSlot, setTitleSlot] = useState<HTMLDivElement | null>(null);\n useEffect(() => {\n setContentReady(false);\n const timer = window.setTimeout(() => setContentReady(true), CANVAS_OPEN_SETTLE_MS);\n return () => window.clearTimeout(timer);\n }, [mountGeneration]);\n\n if (!canvas) {\n return null;\n }\n const Body = canvasBodies[canvas.canvasId];\n\n const behaviour = canvasBehaviourOf(canvas.canvasId);\n const featureFlag = canvasFeatureFlagOf(canvas.canvasId);\n const anchor = canvas.anchor;\n const anchorMessage =\n anchor.kind === \"message\" ? (messages ?? []).find((message) => message.id === anchor.messageId) : undefined;\n const anchorMessageMarkdown =\n anchorMessage !== undefined ? normalizeServerMessageToMarkdown(anchorMessage.message) : null;\n const hasTitleSlot = !!behaviour?.titleBesideCloseButton;\n const surfaceByHost = paneSurface === \"none\";\n const body = <Body canvas={canvas} agentSpaceKey={chatAgentSpaceKey} anchorMessageMarkdown={anchorMessageMarkdown} />;\n\n return (\n <div\n className={classNames(\n classes.root,\n surfaceByHost ? classes.rootSurfaceByHost : \"\",\n boxed && !surfaceByHost ? classes.rootBoxed : \"\",\n behaviour?.fullBleed ? classes.rootFullBleedContent : \"\",\n behaviour?.overlayCloseButton ? classes.rootOverlayCloseButton : \"\",\n )}\n data-testid=\"chat-canvas-pane\"\n data-canvas-id={canvas.canvasId}\n >\n {showsCloseButton || hasTitleSlot ? (\n <div className={classes.closeButtonRow}>\n {hasTitleSlot && <div ref={setTitleSlot} className={classes.titleSlot} />}\n {showsCloseButton ? (\n <Button\n variant=\"muted\"\n // Floating over the body's dark hero image: the light trigger for dark surfaces.\n inverted={behaviour?.overlayCloseButton}\n onDark={behaviour?.overlayCloseButton}\n icon=\"closeCanvas\"\n iconPosition={\"right\"}\n rounded\n blurred\n // The customer's OWN close: a live re-delivery of this canvas is vetoed until the next send / click.\n onClick={() => closeCanvas(true)}\n >\n Close canvas\n </Button>\n ) : null}\n </div>\n ) : null}\n <div key={canvas.mountGeneration} className={classes.content}>\n {contentReady ? (\n // The app's wrapper of a canvas body (host application: canvas-hosted list pages must not rewrite the page URL).\n <CanvasBodyContainer>\n <CanvasTitleSlotContext.Provider value={hasTitleSlot ? titleSlot : null}>\n <ConversationWidgetErrorBoundary widgetName={`canvas:${canvas.canvasId}`}>\n {featureFlag ? (\n // The canvas owns its gate (not inherited from an opener): a restored or page-opened canvas has no\n // widget mount to inherit it from. A page anchor's agent space is the gate's agent space.\n <ConversationWidgetFeatureGate\n featureFlag={featureFlag}\n agentSpaceKeyAttribute={anchor.kind === \"page\" ? anchor.agentSpaceKey : undefined}\n >\n {body}\n </ConversationWidgetFeatureGate>\n ) : (\n body\n )}\n </ConversationWidgetErrorBoundary>\n </CanvasTitleSlotContext.Provider>\n </CanvasBodyContainer>\n ) : (\n <OpeningLoader />\n )}\n </div>\n </div>\n );\n};\n","import { KeyboardEvent, PointerEvent as ReactPointerEvent, RefObject, useEffect, useRef, useState } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport {\n CANVAS_MIN_WIDTH_PX,\n CHAT_COLUMN_MIN_WIDTH_PX,\n} from \"../../renderer/canvas/canvas-behaviours\";\n\nconst KEY_STEP_PX = 24;\nconst NEAR_PX = 40;\nconst RUBBER_MAX_PX = 44;\nconst RUBBER_K = 70;\nconst MAGNET_PX = 6;\nconst MAGNET_X = 0.4;\nconst MAGNET_Y = 0.12;\nconst DRAG_TRAVEL_PX = 12;\nconst LEAN_PX = DRAG_TRAVEL_PX;\nconst CLOSE_PULL_PX = 64;\nconst ARM_DELAY_MS = 350;\nconst LEAN_REST_MS = 150;\n\n/** `idle` (hidden until the pointer comes near), `hover`, `drag`, `armed` (pulled past the narrowest and held: release closes). */\nexport type CanvasResizeTab = \"idle\" | \"hover\" | \"drag\" | \"armed\";\n\nexport const rubberBand = (distance: number): number =>\n Math.sign(distance) * RUBBER_MAX_PX * (1 - Math.exp(-Math.abs(distance) / RUBBER_K));\n\nexport const canvasWidthLimits = (\n rootWidth: number,\n inset: number,\n chatColumnMinWidthPx: number = CHAT_COLUMN_MIN_WIDTH_PX,\n): { min: number; max: number } => {\n const min = CANVAS_MIN_WIDTH_PX + inset * 2;\n return { min, max: Math.max(min, rootWidth - chatColumnMinWidthPx) };\n};\n\nexport const clampCanvasWidth = (\n width: number,\n rootWidth: number,\n inset: number,\n chatColumnMinWidthPx: number = CHAT_COLUMN_MIN_WIDTH_PX,\n): number => {\n const { min, max } = canvasWidthLimits(rootWidth, inset, chatColumnMinWidthPx);\n return Math.round(Math.min(max, Math.max(min, width)));\n};\n\ninterface UseCanvasResizeOptions {\n /** The split's root: the canvas pane's right edge is its right edge, and `--agents-canvas-width-drag` is written onto it while dragging. */\n rootRef: RefObject<HTMLElement | null>;\n /** The canvas card's inset from its pane edge — the handle sits on the card's edge. */\n inset: number;\n /** The narrowest the chat column gets beside the canvas; default `CHAT_COLUMN_MIN_WIDTH_PX`. */\n chatColumnMinWidthPx?: number;\n /** The pane width the customer set (px), or `null` for the canvas's default split. */\n width: number | null;\n onWidthChange: (width: number | null) => void;\n onClose: () => void;\n}\n\n/**\n * The canvas's left edge drags. The edge follows the pointer through a CSS variable on the split's root (no render per\n * move); the width is committed once on release. Pulled `CLOSE_PULL_PX` past the narrowest and held, the tab arms and\n * release closes the canvas.\n */\nexport const useCanvasResize = (options: UseCanvasResizeOptions) => {\n const { rootRef, inset, width, onWidthChange, onClose } = options;\n const chatColumnMinWidthPx = options.chatColumnMinWidthPx ?? CHAT_COLUMN_MIN_WIDTH_PX;\n const handleRef = useRef<HTMLDivElement>(null);\n const [isHovered, setIsHovered] = useState(false);\n const [isDragging, setIsDragging] = useState(false);\n const [isArmed, setIsArmed] = useState(false);\n const [tabX, setTabX] = useState(0);\n const isDraggingRef = useRef(false);\n const timers = useRef({ arm: 0, lean: 0 });\n const latest = useRef({ inset, chatColumnMinWidthPx, onWidthChange, onClose });\n latest.current = { inset, chatColumnMinWidthPx, onWidthChange, onClose };\n\n useEffect(() => {\n const root = rootRef.current;\n const pendingTimers = timers.current;\n return () => {\n window.clearTimeout(pendingTimers.arm);\n window.clearTimeout(pendingTimers.lean);\n // Unmounted mid-drag (the canvas closed): the split must not keep following a pointer nobody holds.\n delete root?.dataset.resizing;\n root?.style.removeProperty(\"--agents-canvas-width-drag\");\n };\n }, [rootRef]);\n\n const magnetise = (clientX: number | null, clientY: number | null, reach = MAGNET_PX) => {\n const handle = handleRef.current;\n if (!handle) return;\n const rect = handle.getBoundingClientRect();\n const cap = (value: number) => Math.max(-reach, Math.min(reach, value));\n const x = clientX === null ? 0 : cap((clientX - (rect.left + rect.width / 2)) * MAGNET_X);\n const y = clientY === null ? 0 : cap((clientY - (rect.top + rect.height / 2)) * MAGNET_Y);\n handle.style.setProperty(\"--agents-resize-magnet-x\", `${x.toFixed(2)}px`);\n handle.style.setProperty(\"--agents-resize-magnet-y\", `${y.toFixed(2)}px`);\n };\n\n const setNear = (isNear: boolean) => {\n const handle = handleRef.current;\n if (handle && (handle.dataset.near === \"true\") !== isNear) {\n handle.dataset.near = String(isNear);\n }\n };\n\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n const onPointerMove = (event: PointerEvent) => {\n if (isDraggingRef.current) return;\n const rect = handleRef.current?.getBoundingClientRect();\n const isNear =\n !!rect &&\n event.clientY >= rect.top &&\n event.clientY <= rect.bottom &&\n Math.abs(event.clientX - (rect.left + rect.width / 2)) <= NEAR_PX;\n setNear(isNear);\n if (isNear) magnetise(event.clientX, event.clientY);\n else magnetise(null, null);\n };\n const onPointerLeave = () => {\n if (isDraggingRef.current) return;\n setNear(false);\n magnetise(null, null);\n };\n root.addEventListener(\"pointermove\", onPointerMove);\n root.addEventListener(\"pointerleave\", onPointerLeave);\n return () => {\n root.removeEventListener(\"pointermove\", onPointerMove);\n root.removeEventListener(\"pointerleave\", onPointerLeave);\n };\n }, [rootRef]);\n\n const rootWidth = () => rootRef.current?.clientWidth ?? 0;\n const currentWidth = () => {\n const root = rootRef.current;\n const handle = handleRef.current;\n if (!root || !handle) return CANVAS_MIN_WIDTH_PX;\n const handleCenter = handle.getBoundingClientRect().left + handle.offsetWidth / 2;\n return root.getBoundingClientRect().right - handleCenter + latest.current.inset;\n };\n\n const startDrag = (event: ReactPointerEvent<HTMLElement>) => {\n const root = rootRef.current;\n if (event.button !== 0 || !root) return;\n event.preventDefault();\n const handle = event.currentTarget;\n try {\n handle.setPointerCapture(event.pointerId);\n } catch {\n // A pointer the browser does not know (synthetic): the strip still gets its moves while over it.\n }\n const { min, max } = canvasWidthLimits(rootWidth(), latest.current.inset, latest.current.chatColumnMinWidthPx);\n const grabOffset = event.clientX - handle.getBoundingClientRect().left - handle.offsetWidth / 2;\n let lastX = event.clientX;\n let lean = 0;\n let isArmedNow = false;\n let draggedWidth: number | null = null;\n isDraggingRef.current = true;\n setIsDragging(true);\n // Resize mode reads `--agents-canvas-width-drag`: seed it, or a press without a move leaves the split without a width.\n root.style.setProperty(\"--agents-canvas-width-drag\", `${clampCanvasWidth(currentWidth(), rootWidth(), latest.current.inset, latest.current.chatColumnMinWidthPx)}px`);\n root.dataset.resizing = \"true\";\n\n const disarm = () => {\n window.clearTimeout(timers.current.arm);\n timers.current.arm = 0;\n if (isArmedNow) {\n isArmedNow = false;\n setIsArmed(false);\n }\n };\n\n magnetise(null, event.clientY, DRAG_TRAVEL_PX);\n const move = (moveEvent: PointerEvent) => {\n magnetise(null, moveEvent.clientY, DRAG_TRAVEL_PX);\n const desired = root.getBoundingClientRect().right - (moveEvent.clientX - grabOffset) + latest.current.inset;\n const next = clampCanvasWidth(desired, rootWidth(), latest.current.inset, latest.current.chatColumnMinWidthPx);\n draggedWidth = next;\n root.style.setProperty(\"--agents-canvas-width-drag\", `${next}px`);\n\n // Past the narrowest the edge stops and the tab stretches after the pointer; past the widest it holds its lean.\n const beyond = Math.min(max, Math.max(min, desired)) - desired;\n const moved = moveEvent.clientX - lastX;\n if (moved !== 0) lean = Math.sign(moved) * LEAN_PX;\n lastX = moveEvent.clientX;\n const tabFor = (currentLean: number) =>\n beyond > 0 ? Math.max(LEAN_PX, rubberBand(beyond)) : beyond < 0 ? -LEAN_PX : currentLean;\n setTabX(tabFor(lean));\n window.clearTimeout(timers.current.lean);\n timers.current.lean = window.setTimeout(() => {\n lean = 0;\n setTabX(tabFor(0));\n }, LEAN_REST_MS);\n\n if (next === min && beyond >= CLOSE_PULL_PX) {\n if (!isArmedNow && !timers.current.arm) {\n timers.current.arm = window.setTimeout(() => {\n timers.current.arm = 0;\n isArmedNow = true;\n setIsArmed(true);\n }, ARM_DELAY_MS);\n }\n } else {\n disarm();\n }\n };\n\n const finish = () => {\n handle.removeEventListener(\"pointermove\", move);\n handle.removeEventListener(\"pointerup\", finish);\n handle.removeEventListener(\"pointercancel\", finish);\n window.clearTimeout(timers.current.lean);\n const closes = isArmedNow;\n disarm();\n isDraggingRef.current = false;\n setIsDragging(false);\n setTabX(0);\n magnetise(null, null);\n delete root.dataset.resizing;\n // Committed in the same frame the drag variable goes, so the edge never flashes back to the old width.\n flushSync(() => latest.current.onWidthChange(closes ? null : (draggedWidth ?? width)));\n root.style.removeProperty(\"--agents-canvas-width-drag\");\n if (closes) {\n setNear(false);\n setIsHovered(false);\n latest.current.onClose();\n }\n };\n handle.addEventListener(\"pointermove\", move);\n handle.addEventListener(\"pointerup\", finish);\n handle.addEventListener(\"pointercancel\", finish);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {\n const { min, max } = canvasWidthLimits(rootWidth(), inset, chatColumnMinWidthPx);\n const next =\n event.key === \"ArrowLeft\"\n ? currentWidth() + KEY_STEP_PX\n : event.key === \"ArrowRight\"\n ? currentWidth() - KEY_STEP_PX\n : event.key === \"Home\"\n ? max\n : event.key === \"End\"\n ? min\n : null;\n if (next === null) return;\n event.preventDefault();\n onWidthChange(clampCanvasWidth(next, rootWidth(), inset, chatColumnMinWidthPx));\n };\n\n const tab: CanvasResizeTab = isArmed ? \"armed\" : isDragging ? \"drag\" : isHovered ? \"hover\" : \"idle\";\n const { min, max } = canvasWidthLimits(rootWidth(), inset, chatColumnMinWidthPx);\n return {\n tab,\n tabX,\n handleProps: {\n ref: handleRef,\n role: \"separator\",\n \"aria-orientation\": \"vertical\" as const,\n \"aria-valuemin\": min,\n \"aria-valuemax\": Math.round(max),\n \"aria-valuenow\": width ?? undefined,\n tabIndex: 0,\n onPointerDown: startDrag,\n onPointerEnter: () => setIsHovered(true),\n onPointerLeave: () => setIsHovered(false),\n onKeyDown,\n onDoubleClick: () => onWidthChange(null),\n },\n };\n};\n","import { CSSProperties, RefObject } from \"react\";\nimport { translateText } from \"../../provider/environment\";\nimport { useCanvasResize } from \"./use-canvas-resize\";\nimport styles from \"./CanvasResizeHandle.module.scss\";\n\nexport interface CanvasResizeHandleProps {\n rootRef: RefObject<HTMLElement | null>;\n inset: number;\n /** The narrowest the chat column gets (`AgentsCanvasLayout.chatColumnMinWidthPx`); default `CHAT_COLUMN_MIN_WIDTH_PX`. */\n chatColumnMinWidthPx?: number;\n width: number | null;\n onWidthChange: (width: number | null) => void;\n onClose: () => void;\n}\n\n/** The pull tab on the canvas's left edge: drag to resize, pull past the narrowest and hold to close. */\nexport const CanvasResizeHandle = (props: CanvasResizeHandleProps) => {\n const { rootRef, inset, chatColumnMinWidthPx, width, onWidthChange, onClose } = props;\n const { tab, tabX, handleProps } = useCanvasResize({ rootRef, inset, chatColumnMinWidthPx, width, onWidthChange, onClose });\n\n return (\n <div\n {...handleProps}\n className={styles.handle}\n data-tab={tab}\n aria-label={translateText(\"Resize canvas\")}\n >\n <span className={styles.tab} style={{ \"--agents-resize-tab-x\": `${tabX}px` } as CSSProperties} aria-hidden=\"true\">\n <span className={styles.tabCircle} />\n <span className={styles.tabTop} />\n <span className={styles.tabBottom} />\n </span>\n </div>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport { canvasBehaviourOf } from \"../renderer/canvas/canvas-behaviours\";\nimport { useConversationWidgetContext } from \"../renderer/ConversationWidgetContext\";\n\nexport interface CanvasShellTransitionsInput {\n /** The conversation the view shows; undefined for a cold chat that has none yet. */\n conversationId?: number;\n /** The viewport is wide enough for the side split (`useCanvasViable`). */\n canvasViable: boolean;\n}\n\n/**\n * The two SHELL-driven transitions of the canvas model that `ConversationView` owns (the widget-driven ones go through\n * `openCanvas`; the send boundary is the hosts'):\n *\n * - **A conversation switch** (history select / new chat) makes the previous conversation's canvas stale — it is\n * cleared so the new conversation starts with a closed canvas. History replay never auto-opens a canvas (the\n * opening rule rejects replay), and the LEFT conversation keeps its stored pointer for when the customer comes\n * back. Only a REAL switch between two conversations counts. Not the first mount: a canvas the host opened on open\n * (the `?agentWidget=` deep-link, a restored canvas) mounts its widget BEFORE this parent effect runs, and an\n * unconditional reset would tear it down before the customer ever sees it. And not the id ARRIVING on a chat that\n * had none: that is the same conversation, just persisted now (the first send creates it) — closing the customer's\n * pinned work surface at that moment would be wrong.\n * - **The wide → narrow crossing** closes the side-split canvas as a shell close (re-openable, no customer veto).\n * Keyed on `canvasViable` ONLY (the canvas read through a ref) so it fires on the crossing, NOT when the mobile CTA\n * opens a canvas on an already narrow viewport. Skipped for a canvas whose behaviour says `narrowViewport:\n * \"overlay\"`: its widget renders nothing inline, so closing it on the crossing would leave the chat with no content\n * at all — it stays open as the full-screen overlay.\n */\nexport const useCanvasShellTransitions = ({ conversationId, canvasViable }: CanvasShellTransitionsInput): void => {\n const { canvas, closeCanvas, resetCanvas } = useConversationWidgetContext();\n const canvasBehaviour = canvas ? (canvasBehaviourOf(canvas.canvasId) ?? null) : null;\n\n const previousConversationIdRef = useRef(conversationId);\n useEffect(() => {\n const previousConversationId = previousConversationIdRef.current;\n previousConversationIdRef.current = conversationId;\n if (previousConversationId === undefined || previousConversationId === conversationId) return;\n resetCanvas();\n }, [conversationId, resetCanvas]);\n\n const canvasClosesOnNarrowRef = useRef(false);\n canvasClosesOnNarrowRef.current = canvasBehaviour !== null && canvasBehaviour.narrowViewport === \"none\";\n useEffect(() => {\n if (!canvasViable && canvasClosesOnNarrowRef.current) closeCanvas(false);\n }, [canvasViable, closeCanvas]);\n};\n","import { Button, SplitView } from \"../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity, ChatAssistantOpening } from \"./chat-assistant-identity\";\nimport { classNames } from \"../provider/class-names\";\nimport React, { CSSProperties, useRef, useState } from \"react\";\nimport { useCanvasViable } from \"../widgets/CanvasLauncherWidget/use-canvas-viable\";\nimport {\n CANVAS_MIN_WIDTH_PX,\n CHAT_COLUMN_MIN_WIDTH_PX,\n DEFAULT_CANVAS_WIDTH_PERCENT,\n type CanvasId,\n canvasBehaviourOf,\n canvasWidthPercentOf,\n} from \"../renderer/canvas/canvas-behaviours\";\nimport { ConversationViewBody } from \"./ConversationViewBody/ConversationViewBody\";\nimport type { MessageTimesMode } from \"./ConversationMessageList/message-times\";\nimport { ConversationErrorType } from \"./store/conversation-error-type\";\nimport type { ChatMessage } from \"./chat-message\";\nimport { ConversationMessageUserTheme } from \"./ConversationMessage/ConversationMessageUser/ConversationMessageUser\";\nimport { ConversationMessageInputHandle } from \"./ConversationMessageInput/ConversationMessageInput\";\nimport type { ConversationAttachmentReference } from \"../contract/conversation\";\nimport type { ConversationComposerWidget } from \"../renderer/conversation-composer-widget\";\nimport { SendMessageHandler } from \"./conversation-send-message\";\nimport { CanvasPane } from \"./CanvasPane/CanvasPane\";\nimport { CanvasResizeHandle } from \"./CanvasResizeHandle/CanvasResizeHandle\";\nimport { useCanvasShellTransitions } from \"./use-canvas-shell-transitions\";\nimport { useConversationWidgetContext } from \"../renderer/ConversationWidgetContext\";\nimport { CanvasLabelContext } from \"../renderer/canvas/canvas-label-context\";\nimport { useCanvasLayout } from \"./canvas-layout\";\nimport classes from \"./Conversation.module.scss\";\n\nexport interface ConversationViewProps {\n currentCategory?: ChatAssistantCategory; // Type from categories\n aiPromptExtension?: ChatAssistantIdentity; // Type from agents\n suggestions?: ChatAssistantOpening[]; // Type from conversationOpenings\n messages: ChatMessage[] | null; // Type from messages\n aiThinking: boolean;\n error: ConversationErrorType | null;\n /** Retry-After seconds of a 429 quota rejection — forwarded to the error card for the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /**\n * Host-bound retry of a FAILED run: re-drives the persisted, unanswered customer message\n * server-side. Each host binds it to ITS chat slice; forwarded through the body to the message list / error card.\n */\n onRetryFailedRun?: () => Promise<void>;\n /**\n * True when the host (the agent) is minimized to the compact side-panel; forwarded to ConversationViewBody.\n */\n isCompact?: boolean;\n isDebugMode: boolean;\n categoriesLoaded: boolean;\n conversationId?: number;\n startingNewConversation?: boolean;\n /**\n * Show the message list even when no conversation exists yet. Used by a host,\n * whose fresh (not-yet-created) chat renders its empty message list.\n */\n showMessagesWithoutConversation?: boolean;\n /**\n * Follow the conversation bottom (scroll-on-mount + resize follow). Default true.\n * A host disables it for a fresh chat that has no messages yet.\n */\n autoScroll?: boolean;\n /**\n * Custom node mounted at the tail of the message list instead of the default\n * (thinking-only) ConversationMessageThinking. Rendered permanently — used by\n * A host to show the animated agent face, which idles between turns.\n */\n thinkingIndicator?: React.ReactNode;\n /**\n * Hide the assistant header (icon + name + \"Assistant\") and the copy button\n * on assistant messages. Used by a host, which renders bare messages.\n */\n hideAssistantMeta?: boolean;\n /**\n * Theme for user-message bubbles, passed through to ConversationViewBody →\n * ConversationMessageList. A host forces \"dark\"; omitted elsewhere.\n */\n userMessageTheme?: ConversationMessageUserTheme;\n /**\n * Custom background slot passed through to ConversationViewBody. When provided, the\n * default chat gradient and AI-Extensions illustrations are suppressed.\n */\n background?: React.ReactNode;\n /**\n * Opt-in: the host paints the chat's background itself, OUTSIDE this component — passed through to ConversationViewBody,\n * which keeps the same `customBg` visual mode (transparent pane) `background` would give it, minus\n * a background node of its own to render (see ConversationViewBody's `backgroundPaintedByHost`).\n */\n backgroundPaintedByHost?: boolean;\n /**\n * Optional ref forwarded to ConversationViewBody's scrollable content wrapper.\n * Callers use this to drive scroll-linked effects on top of the chat — e.g.\n * `useShaderScrollMorph` for the animated background.\n */\n scrollRef?: React.Ref<HTMLDivElement>;\n /** Bump to force a scroll to the newest message — forwarded to ConversationViewBody (see its `scrollToBottomNonce`). */\n scrollToBottomNonce?: number;\n /**\n * Optional external bottom-follow flag, forwarded to ConversationViewBody (see its `followBottomRef`). A host sets it `false`\n * for a programmatic jump away from the bottom (e.g. the search-result jump) so the follow effects stop yanking the\n * view back. Left undefined, ConversationViewBody uses its own internal flag.\n */\n followBottomRef?: React.MutableRefObject<boolean>;\n /**\n * Optional \"a programmatic jump is in flight\" gate, forwarded to ConversationViewBody (see its `scrollJumpActiveRef`). While\n * true, ConversationViewBody neither re-enables bottom-follow on scroll nor auto-scrolls to the bottom on resize, so the\n * host's jump isn't fought by the near-bottom onScroll handler or the resize-follow. Left undefined → no gating.\n */\n scrollJumpActiveRef?: React.MutableRefObject<boolean>;\n /**\n * Render the chat body alone, without the two-pane ModalSplitView. The split view's\n * second pane is sized for a full-width modal, so in a narrow side panel (e.g. an\n * app's editor drawer) it overlays whatever sits beside the panel — and those hosts\n * don't use widget content-drawers anyway.\n */\n disableSplitView?: boolean;\n /**\n * Opt-in: show the round divider FAB that toggles the canvas (open → close, closed → re-open the last canvas).\n * Off by default — ConversationView is shared (generic AI-extensions chat, a host, agent); only hosts that want the\n * divider toggle (agent) enable it.\n */\n enableCanvasToggle?: boolean;\n /**\n * Opt-in (agent): render the side-split canvas as a rounded surface card (border-radius + surface background)\n * so it sits neatly alongside the left side of the host's floating top bar, instead of a flush full-height pane.\n * Only the card surface is gated here and only while the canvas is a side-split (viewport ≥ 850px); the small\n * inset that keeps the canvas clear of the pane edge applies to every canvas (see CanvasPane `.root`),\n * including the narrow full-screen overlay below 850px (where the host hides its top bar, AW-57).\n */\n boxCanvasBelowTopBar?: boolean;\n /**\n * Opt-in (agent host only): confine the customBg top blur band to the chat pane (position: sticky, sized to\n * the pane) instead of the whole viewport (position: fixed, the default for a custom `background` in full-screen\n * mode). Turn on only while a sibling side panel is docked beside the chat (sideCard mode) — otherwise the band\n * would stay full-viewport-width and bleed over the panel instead of compressing together with the chat. Forwarded\n * straight through to ConversationViewBody, which owns the actual CSS (see its `.confineTopBlurBandToChatPane`).\n */\n confineTopBlurBandToChatPane?: boolean;\n /**\n * The setup progress stepper (today's only consumer: the agent chat), forwarded straight through to\n * ConversationViewBody, which mounts it as a direct child of its positioned pane root — the node brings its own\n * positioning. It lands INSIDE this view's split, so an open canvas contracts it along with the chat; that pane\n * boundary is why the host cannot place the strip itself.\n */\n progressStepperSlot?: React.ReactNode;\n /** See ConversationViewBody: the host's layer while files are dragged over the window. */\n fileDropHintSlot?: React.ReactNode;\n /**\n * Scroll-up older-message pagination (opt-in — forwarded to ConversationViewBody). When `onLoadOlder` is provided, a top\n * sentinel prefetches the next older page and the viewport is anchored across the prepend. Default off.\n */\n hasMoreOlder?: boolean;\n loadingOlder?: boolean;\n onLoadOlder?: () => void;\n /**\n * Extra action controls rendered inside the chat input's action row, left of the send button —\n * spread through to ConversationViewBody → ConversationMessageInput (e.g. the agent model picker pill).\n */\n inputActionsSlot?: React.ReactNode;\n /**\n * Action controls pinned to the LEFT edge of the chat input's action row (`inputActionsSlot`\n * stays right) — spread through to ConversationViewBody → ConversationMessageInput (e.g. the agent \"+\" attachments menu).\n */\n inputActionsSlotStart?: React.ReactNode;\n /**\n * Host-owned content rendered inside the chat input above its editable text area — attachment\n * preview cards, validation error boxes. Spread through to ConversationViewBody → ConversationMessageInput's `topSlot`.\n */\n inputTopSlot?: React.ReactNode;\n /**\n * Hard send gate for the chat input: blocks the send button AND Enter while true, but keeps the\n * text editable. The host sets it e.g. while attachment uploads run.\n */\n inputSendDisabled?: boolean;\n /**\n * Host-owned content rendered IN PLACE of the chat input — the closed-conversation bar of a completed\n * setup conversation (no further input possible). When set, ConversationViewBody renders it instead of ConversationMessageInput.\n */\n inputReplacementSlot?: React.ReactNode;\n /**\n * Host-owned band right above the chat input, the input overlapping its lower edge — e.g. the running voice chat\n * with its controls. Not rendered while `inputReplacementSlot` replaces the input.\n */\n inputBandSlot?: React.ReactNode;\n /** The chat input's placeholder; the input's own default otherwise. */\n inputPlaceholder?: string;\n /** Forwarded to ConversationMessageInput's `sendReplacementWhenEmpty`. */\n inputSendReplacementWhenEmpty?: React.ReactNode;\n /** Forwarded to ConversationMessageInput's `glowUnderlay`. */\n inputGlowUnderlay?: React.ReactNode;\n /**\n * Host-owned layer over the message column, the same size — e.g. the voice chat's focus mode. The message column\n * stays mounted under it (scroll position and widget state kept); `isContentOverlayShown` switches between them.\n */\n contentOverlaySlot?: React.ReactNode;\n isContentOverlayShown?: boolean;\n /**\n * Uploaded media-library images that ride along in `onSendMessage`'s options object (`attachments`) on the next\n * send. Owned and cleared by the host; ConversationView/ConversationMessageInput only forward them.\n */\n outgoingAttachmentImages?: ConversationAttachmentReference[];\n /**\n * Composer widgets the host holds outside the widget context (e.g. a widget built from the files the host\n * uploaded), sent like the context's own on the next send. Owned and cleared by the host;\n * ConversationView/ConversationMessageInput only forward them.\n */\n hostComposerWidgets?: ConversationComposerWidget[];\n /**\n * Imperative handle on the chat input (insertTextIntoInput) so host-owned controls — e.g. the\n * \"+\" menu's \"Generate image\" entry — can put text into it.\n */\n conversationMessageInputApiRef?: React.Ref<ConversationMessageInputHandle>;\n /**\n * Keep the chat input editable and sendable while `aiThinking` is true (default false — the input locks for the\n * whole turn); only the first post of a new conversation still locks it, while no conversation id exists yet. Opt\n * in ONLY for a host whose post call stores the message and returns at once, and whose agent checks for unanswered\n * messages when its turn ends, so a message sent mid-turn is answered in the next turn. A host whose post call\n * generates the reply synchronously within the request has no such guard and must leave it off.\n */\n allowSendWhileAiThinking?: boolean;\n /**\n * Opt-in long-answer reading flow (AW-107), default false — spread through to ConversationViewBody. When enabled:\n * (1) on send, the question is pinned to the top with room reserved below it; (2) a scroll-to-latest-message\n * button floats above the input while the bottom is out of view; (3) a fresh static reply's markdown blocks\n * fade in staggered. AI Extensions stays off; the agent chat opts in.\n */\n enablePinQuestionAndRevealAnswer?: boolean;\n /** Forwarded to ConversationViewBody's `isQuestionPinSuspended`. */\n isQuestionPinSuspended?: boolean;\n /**\n * Id of the ONE user message ConversationMessageList renders as a collapsed task-instruction disclosure instead of an\n * owner bubble — the machine-composed seed instruction of a SCHEDULE-spawned run (UX overhaul W4 item 19).\n * Forwarded through ConversationViewBody. Undefined (every host except the agent chat) changes nothing.\n */\n taskInstructionMessageId?: number;\n /**\n * Host content rendered right after one message of the thread — the agent chat's activity card under the message that\n * started each turn. Forwarded through ConversationViewBody to ConversationMessageList. Undefined changes nothing.\n */\n renderAfterMessage?: (message: ChatMessage) => React.ReactNode;\n /** Host content beside each shown assistant message (an avatar face), forwarded through ConversationViewBody. */\n renderAssistantAvatar?: (message: ChatMessage) => React.ReactNode;\n /** Forwarded through ConversationViewBody to ConversationMessageList: a closed conversation renders no widget controls. */\n isConversationClosed?: boolean;\n /** Forwarded through ConversationViewBody to ConversationMessageList: when what was written (`MessageTimesMode`). */\n messageTimes?: MessageTimesMode | null;\n onSuggestionClick: (text: string) => void;\n onSendMessage: SendMessageHandler;\n}\n\nexport const ConversationView = (props: ConversationViewProps) => {\n const { enableCanvasToggle, boxCanvasBelowTopBar, onSendMessage, conversationId, messages } = props;\n const { canvas, lastClosedCanvas, closeCanvas, reopenLastClosedCanvas, resetCanvasForNewTurn } =\n useConversationWidgetContext();\n const canvasViable = useCanvasViable();\n // The host's frame of the canvas (`AgentsEnvironment.canvasLayout`): its own chrome replaces the package's controls.\n const canvasLayout = useCanvasLayout();\n const chatColumnMinWidthPx = canvasLayout.chatColumnMinWidthPx;\n // The short name the open body reports (`useCanvasLabel`), handed to the SplitView for a host's tab or head.\n const [canvasLabel, setCanvasLabel] = useState<string | null>(null);\n // The canvas is a pointer in the chat's slice; its geometry comes from its behaviour (`canvas-behaviours.ts`).\n const canvasBehaviour = canvas ? (canvasBehaviourOf(canvas.canvasId) ?? null) : null;\n const isCanvasOpen = canvas !== null;\n // The conversation switch clears the canvas; the wide → narrow crossing closes a `narrowViewport: \"none\"` canvas.\n useCanvasShellTransitions({ conversationId, canvasViable });\n\n // A new user message starts a new turn — the previous turn's canvas is now stale, so tear it down AND drop the\n // divider FAB (the reset clears `canReopenDrawer`). Runs before the reply arrives, so a fresh canvas opened by the\n // new reply is unaffected. A PINNED canvas (a work surface for the whole conversation, not one\n // turn's result) survives — that is the only difference to `resetCanvas`.\n const handleSendMessage: SendMessageHandler = (message, options) => {\n resetCanvasForNewTurn();\n onSendMessage(message, options);\n };\n\n // The canvas pane starts at the width its behaviour declares; the customer can pull its left edge (`CanvasResizeHandle`).\n // The split reads the width from `--agents-canvas-width-set` (a percentage, or the clamped pull in px), so a drag moves the edge without a\n // render. The width of the last shown canvas is kept while the pane slides out. The divider toggle + slide derive from it.\n const lastCanvasWidthPercentRef = useRef(DEFAULT_CANVAS_WIDTH_PERCENT);\n if (canvasBehaviour) lastCanvasWidthPercentRef.current = canvasWidthPercentOf(canvasBehaviour);\n const canvasWidthPercent = lastCanvasWidthPercentRef.current;\n const boxCanvas = !!boxCanvasBelowTopBar && canvasViable;\n const canvasInset = boxCanvas ? canvasLayout.boxedInsetPx : 0;\n const splitViewRootRef = useRef<HTMLDivElement>(null);\n // The pull belongs to the canvas it was made on: another canvas starts at its own default split.\n const lastCanvasIdRef = useRef<CanvasId | null>(null);\n if (canvas) lastCanvasIdRef.current = canvas.canvasId;\n const [pulledCanvas, setPulledCanvas] = useState<{ canvasId: CanvasId; width: number } | null>(null);\n const pulledCanvasWidth = pulledCanvas?.canvasId === lastCanvasIdRef.current ? pulledCanvas.width : null;\n const setPulledCanvasWidth = (width: number | null) =>\n setPulledCanvas(width !== null && lastCanvasIdRef.current ? { canvasId: lastCanvasIdRef.current, width } : null);\n const canvasResizable = canvasBehaviour?.layout === \"split\" && canvasViable && !props.isCompact;\n const splitViewRootStyle = {\n \"--agents-canvas-width-set\":\n pulledCanvasWidth === null\n ? canvasLayout.chatColumnMinWidthPx === CHAT_COLUMN_MIN_WIDTH_PX\n ? `${canvasWidthPercent}%`\n : // a host's own chat minimum also caps the default split (the package's minimum is met by every viable split)\n `min(${canvasWidthPercent}%, calc(100% - ${chatColumnMinWidthPx}px))`\n : `clamp(${CANVAS_MIN_WIDTH_PX + canvasInset * 2}px, ${pulledCanvasWidth}px, calc(100% - ${chatColumnMinWidthPx}px))`,\n \"--agents-canvas-inset\": `${canvasInset}px`,\n } as CSSProperties;\n\n // The canvas toggle button on the divider: closes the open canvas (the customer's own close), re-opens the last\n // closed one.\n const toggleCanvas = () => {\n if (canvas) closeCanvas(true);\n else reopenLastClosedCanvas();\n };\n // On a narrow viewport the divider (and its toggle) does not exist: the canvas is a full-screen overlay. The canvases\n // whose widgets render nothing inline would have no way back after a close, so the shell offers its own re-open\n // control over the chat, fed by `lastClosedCanvas`, independent of transcript windowing.\n const showsNarrowReopenControl =\n !!enableCanvasToggle &&\n canvasLayout.showsNarrowReopenControl &&\n !canvasViable &&\n !isCanvasOpen &&\n lastClosedCanvas !== null;\n\n if (props.disableSplitView) {\n return <ConversationViewBody {...props} />;\n }\n\n return (\n <div ref={splitViewRootRef} className={classes.splitViewRoot} style={splitViewRootStyle}>\n {showsNarrowReopenControl ? (\n <div className={classes.canvasReopenControl}>\n <Button\n variant=\"muted\"\n icon=\"maximize\"\n iconPosition={\"left\"}\n rounded\n blurred\n size=\"small\"\n onClick={reopenLastClosedCanvas}\n >\n Re-open canvas\n </Button>\n </div>\n ) : null}\n <SplitView\n isSideOpen={isCanvasOpen}\n coversBelowWidth={850}\n // The canvas toggle button on the divider: closes the open canvas, or re-opens the last closed one. Shown only\n // while a canvas is open or one was closed — otherwise there's nothing to toggle.\n sideToggle={\n enableCanvasToggle &&\n canvasLayout.showsDividerToggle &&\n !canvasResizable &&\n (isCanvasOpen || lastClosedCanvas !== null)\n ? {\n onToggle: toggleCanvas,\n // Centered vertically on the divider.\n verticalPositionPercent: 50,\n // The chat's own re-open control is shown: the split view adds no second one while it covers.\n mainPaneShowsReopen: showsNarrowReopenControl,\n // The canvas pane carries its own close button: no floating toggle over it while it covers the chat.\n sidePaneShowsClose: canvasLayout.showsCloseButton,\n }\n : undefined\n }\n sideLabel={isCanvasOpen && canvasLabel !== null ? canvasLabel : undefined}\n main={{\n width: \"100%\",\n narrowedWidth: \"calc(100% - var(--agents-canvas-width))\",\n // The pane's default inline background (var(--agents-neutral-000)) would occlude a host-painted background layer.\n background: props.backgroundPaintedByHost ? \"transparent\" : undefined,\n content: <ConversationViewBody {...props} onSendMessage={handleSendMessage} />,\n }}\n side={{\n width: \"var(--agents-canvas-width)\",\n narrowedWidth: \"var(--agents-canvas-width)\",\n content: (\n // Boxed only while side-split: below 850px the canvas is a full-screen overlay and stays full-bleed.\n <div\n className={classNames(\n classes.splitViewPane,\n boxCanvas && canvasLayout.paneSurface === \"card\" ? classes.splitViewPaneBoxed : \"\",\n )}\n >\n <CanvasLabelContext.Provider value={setCanvasLabel}>\n <CanvasPane messages={messages} boxed={boxCanvas} />\n </CanvasLabelContext.Provider>\n </div>\n ),\n }}\n />\n {canvasResizable ? (\n <CanvasResizeHandle\n rootRef={splitViewRootRef}\n inset={canvasInset}\n chatColumnMinWidthPx={chatColumnMinWidthPx}\n width={pulledCanvasWidth}\n onWidthChange={setPulledCanvasWidth}\n onClose={() => closeCanvas(true)}\n />\n ) : null}\n </div>\n );\n};\n","import type { ConversationActivityElement } from \"../../contract/conversation\";\n\n/**\n * What the activity read sends per element and the stack reads (`ConversationActivityElement`); every field may be\n * missing on an element a caller builds by hand (stories, specs).\n */\nexport type ActivityLineInput = Partial<ConversationActivityElement>;\n\n/** One row of the stack: the element as the endpoint sent it last, keyed by its tool-call message id. */\nexport type ActivityElement = ActivityLineInput & { toolCallMessageId: number };\n\nconst STATE_RANK: Record<string, number> = { queued: 0, running: 1, finished: 2, failed: 2, skipped: 2 };\n\n/**\n * Merge a response into the stack: a later state replaces an earlier one, a line never disappears once told (an\n * element answered without a line, because the narrator was late, keeps the sentence it already had), and an element\n * the response no longer carries stays (the turn snapshot is complete, so this only happens on a pinned turn that a\n * later turn pushed out of the window). Row order is the endpoint's: the order of the persisted rows.\n */\nexport const mergeActivityElements = (\n previous: ActivityElement[],\n incoming: ActivityLineInput[] | null | undefined,\n): ActivityElement[] => {\n const byId = new Map<number, ActivityElement>(previous.map((element) => [element.toolCallMessageId, element]));\n const ordered: number[] = [];\n (incoming ?? []).forEach((element) => {\n const id = element.toolCallMessageId;\n if (id == null || id <= 0) return;\n ordered.push(id);\n const known = byId.get(id);\n if (!known) {\n byId.set(id, { ...element, toolCallMessageId: id });\n return;\n }\n const knownRank = STATE_RANK[known.state ?? \"queued\"] ?? 0;\n const incomingRank = STATE_RANK[element.state ?? \"queued\"] ?? 0;\n // A state never moves backwards (a stale response after a fresher one).\n if (incomingRank < knownRank) return;\n const stateAdvanced = incomingRank > knownRank || known.state !== element.state;\n byId.set(id, {\n ...known,\n ...element,\n toolCallMessageId: id,\n // The finished line replaces the started one; a missing line keeps what was told, unless the state advanced\n // (then the started sentence would misdescribe a finished step, so the row shows its state alone).\n line: element.line ?? (stateAdvanced ? null : (known.line ?? null)),\n });\n });\n // Rows the response carried, in its order, then rows it no longer carries, in their previous order.\n const carried = new Set(ordered);\n const kept = previous\n .filter((element) => !carried.has(element.toolCallMessageId))\n .map((element) => element.toolCallMessageId);\n return [...kept, ...ordered].map((id) => byId.get(id)!);\n};\n\n/** The rows the customer reads: skipped elements carry nothing. */\nexport const visibleActivityElements = (elements: ActivityElement[]): ActivityElement[] =>\n elements.filter((element) => element.state !== \"skipped\");\n\n/**\n * Whether a response names a turn different from the one pinned locally — the stack must start clean instead of\n * merging the new turn's rows into the previous (already folded) one. False until a turn is pinned, and false while\n * the response has not named a turn yet (a request still in flight for the newly pinned, not-yet-answered turn).\n */\nexport const isDifferentTurn = (pinnedTurnMessageId: number | null, answeredTurnMessageId: number | null): boolean =>\n pinnedTurnMessageId !== null && answeredTurnMessageId !== null && answeredTurnMessageId !== pinnedTurnMessageId;\n","import { ActivityElement, visibleActivityElements } from \"./merge-activity-elements\";\n\n/**\n * The least time a line stands beside the face before the next one takes its place — the concept's rhythm (the agent\n * prototype's ThinkingIndicator swaps its line every 2.2 s), so every sentence can be read between two swaps.\n */\nexport const LINE_PACE_MS = 2200;\n/** The shorter wait while more than {@link BACKLOG_THRESHOLD} lines are queued, so a burst catches up. */\nexport const BACKLOG_LINE_PACE_MS = 1400;\nconst BACKLOG_THRESHOLD = 2;\n/**\n * More queued lines than this are shown at once, oldest first: one narrator answer carries up to 8 lines, and the\n * ticker must never trail the turn by more than a few seconds.\n */\nexport const MAX_WAITING_LINES = 4;\n/** Finished turns kept in the thread at most (keepActivityHistoryAfterAnswer); the oldest one falls away beyond. */\nexport const MAX_KEPT_TURNS = 30;\n\n/** One sentence the ticker shows: the started or the finished line of one step. */\nexport interface ActivityTickerLine {\n toolCallMessageId: number;\n /** The step's state when this line was told: queued / running / finished / failed. */\n state: string;\n line: string;\n kind: string | null;\n /** The delegation helper that ran the step (1-based); null for the assistant's own steps. */\n helperIndex: number | null;\n}\n\n/** Whether the line's step was still at work (queued or running) when the line was told, not finished or failed. */\nexport const isStepStillRunning = (line: ActivityTickerLine): boolean =>\n line.state === \"queued\" || line.state === \"running\";\n\n/**\n * What the ticker shows and what still waits to be shown. The endpoint delivers lines in bursts (one request per 3 s,\n * up to 8 lines per narrator answer); this queue hands them to the screen one at a time.\n */\nexport interface ActivityTickerQueue {\n /** The line each step shows right now, keyed by its tool-call message id. */\n shownLines: Record<number, ActivityTickerLine>;\n /** The steps shown before the newest one, oldest first; never contains {@link currentId}. */\n trailIds: number[];\n /** The step whose line was shown last: the one beside the face. */\n currentId: number | null;\n /** Lines not shown yet, oldest first, at most one per step (a newer line of the same step replaces the waiting one). */\n waitingLines: ActivityTickerLine[];\n /** When the newest line last changed (ms since epoch); the pace counts from here. */\n lastShownAt: number;\n}\n\nexport const EMPTY_ACTIVITY_TICKER_QUEUE: ActivityTickerQueue = {\n shownLines: {},\n trailIds: [],\n currentId: null,\n waitingLines: [],\n lastShownAt: Number.NEGATIVE_INFINITY,\n};\n\n/**\n * The element as a ticker line. An element without a sentence keeps the sentence already told for its step and takes\n * its new state: mergeActivityElements drops the started sentence when a step finishes before the narrator described\n * the finish, and the row must then show its check (or its failure) instead of running on. A step never told has\n * nothing to show.\n */\nconst toTickerLine = (\n element: ActivityElement,\n toldLine: ActivityTickerLine | undefined,\n): ActivityTickerLine | null => {\n const sentence = element.line ?? toldLine?.line;\n if (!sentence) return null;\n return {\n toolCallMessageId: element.toolCallMessageId,\n state: element.state ?? \"queued\",\n line: sentence,\n kind: element.kind ?? null,\n helperIndex: element.helperIndex ?? null,\n };\n};\n\nconst isSameLine = (shown: ActivityTickerLine | undefined, incoming: ActivityTickerLine) =>\n !!shown && shown.state === incoming.state && shown.line === incoming.line;\n\nconst LINE_STATE_RANK: Record<string, number> = { queued: 0, running: 1, finished: 2, failed: 2, skipped: 2 };\n\n/** Whether the incoming line is of an earlier state than the one already told for its step (a stale read). */\nconst isOlderStateThan = (told: ActivityTickerLine | undefined, incoming: ActivityTickerLine) =>\n !!told && (LINE_STATE_RANK[incoming.state] ?? 0) < (LINE_STATE_RANK[told.state] ?? 0);\n\n/** Every shown line in the order it was told, oldest first. */\nexport const shownLinesInOrder = (queue: ActivityTickerQueue): ActivityTickerLine[] =>\n [...queue.trailIds, ...(queue.currentId !== null ? [queue.currentId] : [])]\n .map((stepId) => queue.shownLines[stepId])\n .filter(Boolean);\n\n/**\n * Put one line on screen. A line of a step already told replaces that step's line in place (the history keeps every\n * step once); any other line becomes the newest one, beside the face, and the previous newest one moves up into the\n * trail.\n */\nexport const showActivityLine = (\n queue: ActivityTickerQueue,\n line: ActivityTickerLine,\n now: number,\n): ActivityTickerQueue => {\n const stepId = line.toolCallMessageId;\n const shownLines = { ...queue.shownLines, [stepId]: line };\n if (queue.currentId === stepId) {\n return { ...queue, shownLines, lastShownAt: now };\n }\n if (queue.trailIds.includes(stepId)) {\n return { ...queue, shownLines };\n }\n const trailIds = queue.currentId !== null ? [...queue.trailIds, queue.currentId] : queue.trailIds;\n return { ...queue, shownLines, trailIds, currentId: stepId, lastShownAt: now };\n};\n\n/**\n * Take the endpoint's elements in: every line not shown yet waits in the queue, except the finished line of a step\n * already in the trail, which replaces that row in place at once. Skipped elements and elements of a step never told\n * a sentence never show (only generated sentences appear).\n */\nexport const receiveActivityElements = (\n queue: ActivityTickerQueue,\n elements: ActivityElement[],\n now: number,\n): ActivityTickerQueue => {\n let nextQueue = queue;\n visibleActivityElements(elements).forEach((element) => {\n const stepId = element.toolCallMessageId;\n const waitingLine = nextQueue.waitingLines.find((line) => line.toolCallMessageId === stepId);\n const incomingLine = toTickerLine(element, waitingLine ?? nextQueue.shownLines[stepId]);\n if (!incomingLine) return;\n const toldLine = waitingLine ?? nextQueue.shownLines[stepId];\n // per step the later state wins: a read that arrives out of order never moves a told step back\n if (isSameLine(toldLine, incomingLine) || isOlderStateThan(toldLine, incomingLine)) {\n return;\n }\n if (nextQueue.trailIds.includes(stepId)) {\n nextQueue = {\n ...nextQueue,\n shownLines: { ...nextQueue.shownLines, [stepId]: incomingLine },\n waitingLines: nextQueue.waitingLines.filter((line) => line.toolCallMessageId !== stepId),\n };\n return;\n }\n nextQueue = {\n ...nextQueue,\n waitingLines: waitingLine\n ? nextQueue.waitingLines.map((line) => (line.toolCallMessageId === stepId ? incomingLine : line))\n : [...nextQueue.waitingLines, incomingLine],\n };\n });\n while (nextQueue.waitingLines.length > MAX_WAITING_LINES) {\n const [oldestWaitingLine, ...laterWaitingLines] = nextQueue.waitingLines;\n nextQueue = showActivityLine({ ...nextQueue, waitingLines: laterWaitingLines }, oldestWaitingLine, now);\n }\n return nextQueue;\n};\n\n/**\n * Milliseconds until the next waiting line may be shown; null when nothing waits. The paces default to\n * {@link LINE_PACE_MS} and {@link BACKLOG_LINE_PACE_MS} (a host sets its own through the chat's `activityTiming`).\n */\nexport const msUntilNextActivityLine = (\n queue: ActivityTickerQueue,\n now: number,\n linePaceMs: number = LINE_PACE_MS,\n backlogLinePaceMs: number = BACKLOG_LINE_PACE_MS,\n): number | null => {\n if (queue.waitingLines.length === 0) return null;\n const pace = queue.waitingLines.length > BACKLOG_THRESHOLD ? backlogLinePaceMs : linePaceMs;\n return Math.max(0, queue.lastShownAt + pace - now);\n};\n\n/** Show the oldest waiting line. The caller's timer decides when (see {@link msUntilNextActivityLine}). */\nexport const releaseNextActivityLine = (queue: ActivityTickerQueue, now: number): ActivityTickerQueue => {\n if (queue.waitingLines.length === 0) return queue;\n const [oldestWaitingLine, ...laterWaitingLines] = queue.waitingLines;\n return showActivityLine({ ...queue, waitingLines: laterWaitingLines }, oldestWaitingLine, now);\n};\n\n/** Show every waiting line at once, oldest first — the turn has ended and the answer is on screen. */\nexport const releaseAllActivityLines = (queue: ActivityTickerQueue, now: number): ActivityTickerQueue => {\n const queueWithoutWaitingLines: ActivityTickerQueue = { ...queue, waitingLines: [] };\n return queue.waitingLines.reduce(\n (nextQueue, waitingLine) => showActivityLine(nextQueue, waitingLine, now),\n queueWithoutWaitingLines,\n );\n};\n\n/** Steps the turn has finished or failed, the count the ticker reports. */\nexport const countFinishedSteps = (elements: ActivityElement[]): number =>\n visibleActivityElements(elements).filter((element) => element.state === \"finished\" || element.state === \"failed\")\n .length;\n\n/**\n * Delegation helpers with a step queued or running right now; a helper running several tool calls counts once. The\n * helper number restarts at 1 for every delegate call, so a helper is told apart by the delegate call its steps follow\n * (the endpoint lists each delegate call's helper steps right after it).\n */\nexport const countWorkingHelpers = (elements: ActivityElement[]): number => {\n const workingHelperKeys = new Set<string>();\n let delegateCallId: number | null = null;\n elements.forEach((element) => {\n if (element.helperIndex == null) {\n if (element.kind === \"delegation\" || element.kind === \"background\") delegateCallId = element.toolCallMessageId;\n return;\n }\n if (element.state === \"queued\" || element.state === \"running\") {\n workingHelperKeys.add(`${delegateCallId}:${element.helperIndex}`);\n }\n });\n return workingHelperKeys.size;\n};\n\n/** \"0:42\" / \"2:04\" — elapsed time as a clock, no unit to translate. */\nexport const formatElapsedClock = (elapsedMs: number): string => {\n const elapsedSeconds = Math.max(0, Math.floor(elapsedMs / 1000));\n return `${Math.floor(elapsedSeconds / 60)}:${String(elapsedSeconds % 60).padStart(2, \"0\")}`;\n};\n\n/** Nothing on screen · lines beside the face while the turn runs · the face's success beat after it ended. */\nexport type ActivityTickerPhase = \"idle\" | \"live\" | \"done\";\n\n/** A finished turn whose lines stay in the thread, above its answer, under the message that started it. */\nexport interface KeptActivityTurn {\n turnMessageId: number;\n /** Every line the turn told, oldest first. */\n lines: ActivityTickerLine[];\n}\n\nexport interface ActivityTickerState {\n queue: ActivityTickerQueue;\n phase: ActivityTickerPhase;\n /** The message that started the turn on screen, as the endpoint named it; null until it did. */\n turnMessageId: number | null;\n /** When the running turn started on this screen (ms since epoch), for the elapsed clock; null before any turn. */\n liveSince: number | null;\n /** Finished turns that stay in the thread, oldest first; filled only while the history is kept. */\n keptTurns: KeptActivityTurn[];\n /** The `running` of the previous input, to see where a turn starts and ends. */\n wasRunning: boolean;\n}\n\nexport const INITIAL_ACTIVITY_TICKER_STATE: ActivityTickerState = {\n queue: EMPTY_ACTIVITY_TICKER_QUEUE,\n phase: \"idle\",\n turnMessageId: null,\n liveSince: null,\n keptTurns: [],\n wasRunning: false,\n};\n\nexport type ActivityTickerAction =\n | {\n type: \"elementsReceived\";\n elements: ActivityElement[];\n running: boolean;\n failed: boolean;\n turnMessageId: number | null;\n /** A turn in its success beat that the next turn replaces goes into {@link ActivityTickerState.keptTurns} first. */\n keepHistory: boolean;\n now: number;\n }\n | { type: \"nextLineDue\"; now: number }\n | { type: \"doneBeatOver\"; keepHistory: boolean };\n\n/**\n * Whether a read belongs to another turn than the one on screen: the endpoint names a different turn message, or a\n * turn starts after the previous one left the live phase and its message is not named yet (the read hook unpins the\n * turn on a new start, so a new turn arrives unnamed) or named differently. A read that merely misses a step already\n * shown — a read of fewer rows, an answer that overtook a later one — is the same turn: its lines stay.\n */\nconst isReadOfAnotherTurn = (\n state: ActivityTickerState,\n turnMessageId: number | null,\n turnStarted: boolean,\n): boolean => {\n if (state.turnMessageId !== null && turnMessageId !== null && turnMessageId !== state.turnMessageId) return true;\n return turnStarted && state.phase !== \"live\" && (turnMessageId === null || turnMessageId !== state.turnMessageId);\n};\n\n/**\n * The kept turns plus the turn in its success beat, if it can be placed in the thread (the endpoint named the message\n * that started it). A turn kept before under the same message is replaced: its helpers ended and it ended again.\n */\nconst keptTurnsWithFinishedTurn = (state: ActivityTickerState): KeptActivityTurn[] => {\n const { phase, turnMessageId, queue, keptTurns } = state;\n if (phase !== \"done\" || turnMessageId === null) return keptTurns;\n const finishedTurn: KeptActivityTurn = { turnMessageId, lines: shownLinesInOrder(queue) };\n return [...keptTurns.filter((keptTurn) => keptTurn.turnMessageId !== turnMessageId), finishedTurn].slice(\n -MAX_KEPT_TURNS,\n );\n};\n\n/**\n * The ticker's life across turns. A turn starts when `running` rises: the queue starts clean and the phase goes live.\n * Within a turn the endpoint's snapshot only grows (mergeActivityElements keeps every row it has seen), so a shown step\n * missing from the elements means another turn or another conversation: the queue starts clean. When `running` falls,\n * the waiting lines are shown at once and the face's success beat follows — unless the turn failed or never told a\n * line. After the beat the turn's lines either stay in the thread ({@link KeptActivityTurn}) or are gone, as\n * `keepHistory` says.\n */\nexport const activityTickerReducer = (\n state: ActivityTickerState,\n action: ActivityTickerAction,\n): ActivityTickerState => {\n switch (action.type) {\n case \"elementsReceived\": {\n const { elements, running, failed, keepHistory, now } = action;\n const turnStarted = running && !state.wasRunning;\n const turnEnded = !running && state.wasRunning;\n // Lines already shown in a turn are never dropped: the stack resets only for another turn.\n const startsClean = isReadOfAnotherTurn(state, action.turnMessageId, turnStarted);\n const queue = receiveActivityElements(startsClean ? EMPTY_ACTIVITY_TICKER_QUEUE : state.queue, elements, now);\n let nextState: ActivityTickerState = {\n ...state,\n queue,\n turnMessageId: action.turnMessageId ?? (startsClean ? null : state.turnMessageId),\n wasRunning: running,\n };\n // The turn in its success beat leaves the screen before the next one starts clean: kept in the thread or gone.\n if (startsClean && state.phase === \"done\") {\n nextState = {\n ...nextState,\n phase: \"idle\",\n keptTurns: keepHistory ? keptTurnsWithFinishedTurn(state) : state.keptTurns,\n };\n }\n if (running && startsClean) {\n nextState = { ...nextState, phase: \"live\", liveSince: now };\n }\n if (turnEnded && state.phase === \"live\") {\n const finalQueue = releaseAllActivityLines(queue, now);\n const toldALine = finalQueue.currentId !== null;\n nextState = { ...nextState, queue: finalQueue, phase: toldALine && !failed ? \"done\" : \"idle\" };\n }\n if (failed && nextState.phase === \"done\") {\n nextState = { ...nextState, phase: \"idle\" };\n }\n return nextState;\n }\n case \"nextLineDue\":\n return state.phase === \"live\" ? { ...state, queue: releaseNextActivityLine(state.queue, action.now) } : state;\n case \"doneBeatOver\":\n return state.phase === \"done\"\n ? {\n ...state,\n phase: \"idle\",\n keptTurns: action.keepHistory ? keptTurnsWithFinishedTurn(state) : state.keptTurns,\n }\n : state;\n default:\n return state;\n }\n};\n","import { useEffect, useMemo, useReducer } from \"react\";\n\nimport {\n activityTickerReducer,\n ActivityTickerLine,\n countFinishedSteps,\n countWorkingHelpers,\n ActivityTickerPhase,\n BACKLOG_LINE_PACE_MS,\n INITIAL_ACTIVITY_TICKER_STATE,\n KeptActivityTurn,\n LINE_PACE_MS,\n msUntilNextActivityLine,\n shownLinesInOrder,\n} from \"./activity-ticker\";\nimport { ActivityElement } from \"./merge-activity-elements\";\n\n/**\n * How long the face's success beat rests before the face turns back to idle — counted from the start of the success\n * roll. The ticker keeps or drops the turn's lines once it is over; an app's face times its success roll by it.\n */\nexport const SUCCESS_BEAT_MS = 1400;\n\ninterface UseActivityTickerParams {\n /** The rows of the running turn from {@link useConversationActivity}, in row order. */\n elements: ActivityElement[];\n /** Whether the endpoint says the turn is still in flight. */\n running: boolean;\n /** The message that started the turn, as the endpoint named it; null until it did. */\n turnMessageId?: number | null;\n /** The turn ended in an error: no success beat, nothing kept. */\n failed?: boolean;\n /**\n * After the answer, each finished turn's lines stay in the thread above its answer, under the message that started\n * it; false = they fade out with the line beside the face and nothing remains.\n */\n keepActivityHistoryAfterAnswer?: boolean;\n /** The least time a line stands beside the face. Default `LINE_PACE_MS` (2200). */\n linePaceMs?: number;\n /** The shorter wait while more than two lines are queued. Default `BACKLOG_LINE_PACE_MS` (1400). */\n backlogLinePaceMs?: number;\n /** The success beat's rest. Default {@link SUCCESS_BEAT_MS}. */\n successBeatMs?: number;\n}\n\n/** One turn's lines — the turn running now, in the face's success beat, or kept in the thread. */\nexport interface ActivityTickerTurn {\n /** The message that started the turn: its kept history stands right after it. Null until the endpoint named it. */\n turnMessageId: number | null;\n /** live = the turn runs; done = it ended. */\n phase: \"live\" | \"done\";\n /** Every line told in the turn, oldest first; while live, the last one stands beside the face. */\n lines: ActivityTickerLine[];\n /** Steps finished or failed so far. */\n stepCount: number;\n /** Steps delegation helpers are running right now. */\n helperCount: number;\n /** When the running turn started on this screen (ms since epoch), for the elapsed clock; null once it ended. */\n liveSince: number | null;\n}\n\n/** What the ticker shows right now — read by AgentActivity (the face and its lines) and the history in the thread. */\nexport interface ActivityTicker {\n /** The phase of the turn on screen; the face keeps working while it is live. */\n phase: ActivityTickerPhase;\n /** The turn running now or in the face's success beat; null when idle and before the turn's first line. */\n currentTurn: ActivityTickerTurn | null;\n /**\n * The finished turns whose lines stand in the thread, under the message that started each, oldest first: every kept\n * turn plus the turn in the face's success beat. Empty unless the history is kept; a turn the endpoint never named\n * is never among them (it has no message to stand under).\n */\n historyTurns: ActivityTickerTurn[];\n}\n\nconst toKeptTurn = (keptTurn: KeptActivityTurn): ActivityTickerTurn => ({\n turnMessageId: keptTurn.turnMessageId,\n phase: \"done\",\n lines: keptTurn.lines,\n stepCount: keptTurn.lines.length,\n helperCount: 0,\n liveSince: null,\n});\n\n/**\n * Paces the activity lines of a running turn at the prototype's ThinkingIndicator rhythm. The\n * endpoint delivers lines in bursts; the ticker puts them beside the face one at a time — each stays at least 2.2 s,\n * or 1.4 s while more than two wait — and never falls more than a few lines behind. When the turn ends, the rest is\n * shown at once and the face plays its success beat ({@link SUCCESS_BEAT_MS}); the turn's lines then stay in the\n * thread or are gone, as `keepActivityHistoryAfterAnswer` says. The state machine lives in\n * {@link activityTickerReducer}; this hook only owns the timers.\n */\nexport const useActivityTicker = (params: UseActivityTickerParams): ActivityTicker => {\n const {\n elements,\n running,\n turnMessageId = null,\n failed = false,\n keepActivityHistoryAfterAnswer = false,\n linePaceMs = LINE_PACE_MS,\n backlogLinePaceMs = BACKLOG_LINE_PACE_MS,\n successBeatMs = SUCCESS_BEAT_MS,\n } = params;\n const [state, dispatch] = useReducer(activityTickerReducer, INITIAL_ACTIVITY_TICKER_STATE);\n\n useEffect(() => {\n dispatch({\n type: \"elementsReceived\",\n elements,\n running,\n failed,\n turnMessageId,\n keepHistory: keepActivityHistoryAfterAnswer,\n now: Date.now(),\n });\n // keepActivityHistoryAfterAnswer is read when a turn leaves the screen, it never triggers a receive of its own.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [elements, running, failed, turnMessageId]);\n\n // One timer for the next waiting line; every queue change re-plans it.\n useEffect(() => {\n if (state.phase !== \"live\") return undefined;\n const waitMs = msUntilNextActivityLine(state.queue, Date.now(), linePaceMs, backlogLinePaceMs);\n if (waitMs === null) return undefined;\n const timer = setTimeout(() => dispatch({ type: \"nextLineDue\", now: Date.now() }), waitMs);\n return () => clearTimeout(timer);\n }, [state.phase, state.queue, linePaceMs, backlogLinePaceMs]);\n\n useEffect(() => {\n if (state.phase !== \"done\") return undefined;\n const timer = setTimeout(\n () => dispatch({ type: \"doneBeatOver\", keepHistory: keepActivityHistoryAfterAnswer }),\n successBeatMs,\n );\n return () => clearTimeout(timer);\n }, [state.phase, keepActivityHistoryAfterAnswer, successBeatMs]);\n\n return useMemo(() => {\n const { queue, phase } = state;\n const lines = shownLinesInOrder(queue);\n const currentTurn: ActivityTickerTurn | null =\n phase !== \"idle\" && lines.length > 0\n ? {\n turnMessageId: state.turnMessageId,\n phase,\n lines,\n stepCount: countFinishedSteps(elements),\n helperCount: phase === \"live\" ? countWorkingHelpers(elements) : 0,\n liveSince: phase === \"live\" ? state.liveSince : null,\n }\n : null;\n // Switching the history off takes the kept lines away at once; a turn on screen is never shown twice. The turn in\n // its success beat already stands in the thread, so its lines grow in there as they leave the face.\n const keptTurns = state.keptTurns\n .filter((keptTurn) => currentTurn === null || keptTurn.turnMessageId !== currentTurn.turnMessageId)\n .map(toKeptTurn);\n const finishedTurnOnScreen =\n currentTurn?.phase === \"done\" && currentTurn.turnMessageId !== null ? currentTurn : null;\n const historyTurns = !keepActivityHistoryAfterAnswer\n ? []\n : finishedTurnOnScreen\n ? [...keptTurns, finishedTurnOnScreen]\n : keptTurns;\n return { phase, currentTurn, historyTurns };\n }, [state, elements, keepActivityHistoryAfterAnswer]);\n};\n","import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useAgentsConversationClient } from \"../../client/AgentsConversationClientContext\";\nimport type { ConversationBackgroundJob } from \"../../contract/conversation\";\nimport { ActivityElement, isDifferentTurn, mergeActivityElements } from \"./merge-activity-elements\";\n\n/** At most one activity request per this many milliseconds per conversation, whatever the tick rate. */\nexport const ACTIVITY_REQUEST_WINDOW_MS = 3000;\n/** While a turn runs, a request also fires on this cadence: the floor for a dead signal. */\nexport const RUNNING_FLOOR_MS = 4000;\n/**\n * Once the signal no longer says \"running\", this many failed requests in a row end the turn on screen: an endpoint that\n * keeps failing must not keep the face working and ask again every {@link RUNNING_FLOOR_MS} while the chat is open.\n */\nexport const MAX_FAILED_REQUESTS_AFTER_SIGNAL_ENDED = 3;\n\ntype Params = {\n conversationId: number;\n /** The signal's run status: \"running\" while a turn drives, \"idle\" / \"failed\" when it ended, null before the first read. */\n runStatus: string | null;\n /** Advances on every signal tick the host acts on (its message refetch); each advance asks for the activity too. */\n signalVersion: number;\n enabled?: boolean;\n /** At most one request per this many milliseconds. Default {@link ACTIVITY_REQUEST_WINDOW_MS}. */\n activityRequestWindowMs?: number;\n /** The request cadence while a turn runs. Default {@link RUNNING_FLOOR_MS}. */\n runningFloorMs?: number;\n};\n\ntype Result = {\n /** The rows of the stack in row order; empty before the first turn of this mount. */\n elements: ActivityElement[];\n /** Whether the narrated turn is still in flight. */\n running: boolean;\n /** The message that started the narrated turn, as the endpoint named it; null before its first answer. */\n turnMessageId: number | null;\n /** The background jobs of the conversation whose end is not reported yet, as the newest answer named them. */\n runningBackgroundJobs: ConversationBackgroundJob[];\n /** Asks for the activity at once (after the owner stopped a job), past the throttle. */\n refresh: () => void;\n};\n\n/**\n * What the agent is doing for the customer right now: pulls the conversation client's\n * `getConversationActivity` (`AgentsConversationClientProvider`) while the customer watches a running turn and merges the answer into the stack. Frontend-driven on purpose: nothing is\n * generated for a hidden tab or a closed chat. The turn is pinned when it starts (`turnMessageId` from the first\n * answer), so a message the customer sends mid-turn does not move the window. Debounced to one request per\n * {@link ACTIVITY_REQUEST_WINDOW_MS} (or the host's `activityRequestWindowMs`) with one trailing request after a burst; a terminal status fires one request for\n * the finished lines, and the requests go on until the endpoint answers that the turn ended — then the stack rests\n * until the next turn. A failed run ends the turn with that last request, whatever it answers, and so do\n * {@link MAX_FAILED_REQUESTS_AFTER_SIGNAL_ENDED} failed requests in a row once the signal stopped saying \"running\"\n * (those also drop the background jobs of the last answer, so the floor rests).\n * The answer also names the conversation's background jobs whose end is not reported yet: while it names any, the\n * requests go on at the floor's cadence and on every signal tick, whatever the turn does (a job runs on after the turn\n * that started it answered).\n * Opening a conversation (a new `conversationId`, or `enabled` turning on) reads once at once — on tab return when the\n * tab is hidden — so a job that runs while the conversation rests shows its line without waiting for a signal; with no\n * job and no turn in flight that read is the only one until the next trigger.\n */\nexport const useConversationActivity = ({\n conversationId,\n runStatus,\n signalVersion,\n enabled = true,\n activityRequestWindowMs = ACTIVITY_REQUEST_WINDOW_MS,\n runningFloorMs = RUNNING_FLOOR_MS,\n}: Params): Result => {\n const conversationClient = useAgentsConversationClient();\n const [elements, setElements] = useState<ActivityElement[]>([]);\n const [running, setRunning] = useState(false);\n const [turnMessageId, setTurnMessageId] = useState<number | null>(null);\n const [runningBackgroundJobs, setRunningBackgroundJobs] = useState<ConversationBackgroundJob[]>([]);\n // Whether the newest answer named a background job: the requests go on while one runs, without a turn.\n const hasRunningBackgroundJobsRef = useRef(false);\n const turnMessageIdRef = useRef<number | null>(null);\n const elementsRef = useRef<ActivityElement[]>([]);\n const inFlightRef = useRef(false);\n // The conversation the request in flight reads, and the one shown: an answer for another conversation is dropped.\n const inFlightConversationIdRef = useRef<number | null>(null);\n const conversationIdRef = useRef(conversationId);\n // The conversation the read on opening was made for; null while disabled, so turning on reads again.\n const openedConversationIdRef = useRef<number | null>(null);\n const trailingRef = useRef(false);\n const lastRequestAtRef = useRef(0);\n const trailingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const runningRef = useRef(false);\n // What the endpoint said last about the pinned turn: still running or ended. The signal reports the parent\n // conversation IDLE while its helpers run, so a signal \"running\" after \"idle\" is not by itself a new turn.\n const answeredRunningRef = useRef(false);\n // The signal's run status as the answers read it: they land after the status may have changed.\n const runStatusRef = useRef<string | null>(runStatus);\n const consecutiveFailedRequestsRef = useRef(0);\n // The throttled entry, reachable from the request's own trailing call without a dependency cycle.\n const requestActivityRef = useRef<((immediate?: boolean) => void) | null>(null);\n\n useEffect(() => {\n elementsRef.current = elements;\n }, [elements]);\n\n const performRequest = useCallback(async () => {\n if (!enabled || !Number.isFinite(conversationId) || conversationId <= 0) return;\n if (inFlightRef.current) {\n trailingRef.current = true;\n return;\n }\n inFlightRef.current = true;\n inFlightConversationIdRef.current = conversationId;\n lastRequestAtRef.current = Date.now();\n try {\n const response = await conversationClient.getConversationActivity(conversationId, turnMessageIdRef.current);\n // The viewer switched conversations while this read was out: its answer belongs to the old one.\n if (conversationIdRef.current !== conversationId) return;\n const answeredTurn = response.turnMessageId;\n // A new turn started since the stack was pinned: the rows of the old turn fall away, the new turn starts clean.\n const newTurn = isDifferentTurn(turnMessageIdRef.current, answeredTurn);\n turnMessageIdRef.current = answeredTurn;\n setTurnMessageId(answeredTurn);\n const merged = mergeActivityElements(newTurn ? [] : elementsRef.current, response.elements);\n elementsRef.current = merged;\n setElements(merged);\n const answeredBackgroundJobs = response.runningBackgroundJobs ?? [];\n hasRunningBackgroundJobsRef.current = answeredBackgroundJobs.length > 0;\n setRunningBackgroundJobs(answeredBackgroundJobs);\n consecutiveFailedRequestsRef.current = 0;\n // A failed run has ended, whatever its steps say: a tool call the failure left open answers \"running\" forever.\n answeredRunningRef.current = response.turnRunning && runStatusRef.current !== \"failed\";\n setRunning(answeredRunningRef.current);\n } catch {\n if (conversationIdRef.current !== conversationId) return;\n // best-effort: the states of the next answer replace whatever is missing now — unless the turn is known to have\n // ended (the run failed) or the endpoint keeps failing after the signal stopped saying \"running\".\n consecutiveFailedRequestsRef.current += 1;\n const keepsFailingAfterSignalEnded =\n runStatusRef.current !== \"running\" && consecutiveFailedRequestsRef.current >= MAX_FAILED_REQUESTS_AFTER_SIGNAL_ENDED;\n if (runStatusRef.current === \"failed\" || keepsFailingAfterSignalEnded) {\n answeredRunningRef.current = false;\n setRunning(false);\n }\n if (keepsFailingAfterSignalEnded) {\n // the jobs of the last answer would keep the floor asking and their lines with clock and stop button standing:\n // they go too; the next signal tick or opening reads them again\n hasRunningBackgroundJobsRef.current = false;\n setRunningBackgroundJobs([]);\n }\n } finally {\n inFlightRef.current = false;\n inFlightConversationIdRef.current = null;\n if (trailingRef.current) {\n trailingRef.current = false;\n // held back behind a read of the previous conversation: the opened one reads at once, not after the window\n requestActivityRef.current?.(conversationIdRef.current !== conversationId);\n }\n }\n }, [conversationId, conversationClient, enabled]);\n\n // The one throttle every trigger goes through: at most one request per window, one trailing call for a burst.\n const requestActivity = useCallback(\n (immediate = false) => {\n if (typeof document !== \"undefined\" && document.hidden) return;\n if (immediate) {\n if (trailingTimerRef.current !== null) {\n clearTimeout(trailingTimerRef.current);\n trailingTimerRef.current = null;\n }\n void performRequest();\n return;\n }\n const sinceLast = Date.now() - lastRequestAtRef.current;\n if (sinceLast >= activityRequestWindowMs) {\n void performRequest();\n return;\n }\n if (trailingTimerRef.current === null) {\n trailingTimerRef.current = setTimeout(() => {\n trailingTimerRef.current = null;\n void performRequest();\n }, activityRequestWindowMs - sinceLast);\n }\n },\n [performRequest, activityRequestWindowMs],\n );\n useEffect(() => {\n requestActivityRef.current = requestActivity;\n }, [requestActivity]);\n\n // Turn start: drop whatever the previous (already rested) turn left on screen BEFORE asking again — otherwise the\n // first response for the new turn would merge its rows into the old ones still sitting in state (the bug: sending\n // a new message while the previous turn's stack is still shown left the old rows in place with the new ones\n // appended). Unpin, clear the stack, mark it running so the UI switches to the live ticker at once, then request.\n // Turn end: one last request for the finished lines (the response's own `turnRunning` flips `running` false once\n // that lands, not this effect — so the ticker keeps whatever it has until the terminal answer is in).\n useEffect(() => {\n runStatusRef.current = runStatus;\n const isRunning = runStatus === \"running\";\n const wasRunning = runningRef.current;\n runningRef.current = isRunning;\n if (isRunning && !wasRunning) {\n consecutiveFailedRequestsRef.current = 0;\n // A fresh turn only when the endpoint said the pinned one had ended; while helpers run the parent's signal\n // flips idle and back, and the ticker must keep its rows (a different answered turn resets it anyway).\n if (!answeredRunningRef.current) {\n turnMessageIdRef.current = null;\n setTurnMessageId(null);\n elementsRef.current = [];\n setElements([]);\n }\n setRunning(true);\n requestActivity(true);\n } else if (!isRunning && wasRunning) {\n requestActivity(true);\n }\n }, [runStatus, requestActivity]);\n\n // Every signal tick the host acts on asks for the activity too (throttled above).\n useEffect(() => {\n if (signalVersion > 0 && (runningRef.current || hasRunningBackgroundJobsRef.current)) {\n requestActivity();\n }\n }, [signalVersion, requestActivity]);\n\n // The floor while the turn is in flight (a dead signal, a long tool) and the catch-up on tab return. In flight until\n // the endpoint itself answers that the turn ended, not only while the signal says \"running\": the signal reports the\n // parent idle while its helpers work, a turn can end while the tab is hidden (the terminal request above is then\n // skipped), and that request can fail. Stopping at the signal would leave `running` true until the next turn. The\n // catch in performRequest bounds it: a failed run, or failed requests in a row, set `running` false.\n useEffect(() => {\n if (!enabled || (runStatus !== \"running\" && !running && runningBackgroundJobs.length === 0)) return;\n const interval = setInterval(() => requestActivity(), runningFloorMs);\n const onVisibilityChange = () => {\n if (!document.hidden) requestActivity(true);\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n return () => {\n clearInterval(interval);\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n };\n }, [enabled, runStatus, running, runningBackgroundJobs.length, requestActivity, runningFloorMs]);\n\n // A different conversation: nothing of the old one is shown.\n useEffect(() => {\n conversationIdRef.current = conversationId;\n turnMessageIdRef.current = null;\n setTurnMessageId(null);\n elementsRef.current = [];\n setElements([]);\n setRunning(false);\n hasRunningBackgroundJobsRef.current = false;\n setRunningBackgroundJobs([]);\n consecutiveFailedRequestsRef.current = 0;\n return () => {\n if (trailingTimerRef.current !== null) {\n clearTimeout(trailingTimerRef.current);\n trailingTimerRef.current = null;\n }\n };\n }, [conversationId]);\n\n // Opening a conversation reads once: the route names the running background jobs on every read, also while the\n // conversation rests, so a job that does not wake the agent shows its line at once instead of after the next signal.\n // A hidden tab reads when it shows again. A read already out for this conversation (a turn that runs on opening)\n // counts as this read.\n useEffect(() => {\n if (!enabled || !Number.isFinite(conversationId) || conversationId <= 0) {\n openedConversationIdRef.current = null;\n return;\n }\n if (openedConversationIdRef.current === conversationId) return;\n const readOnOpening = () => {\n openedConversationIdRef.current = conversationId;\n if (inFlightRef.current && inFlightConversationIdRef.current === conversationId) return;\n requestActivity(true);\n };\n if (typeof document === \"undefined\" || !document.hidden) {\n readOnOpening();\n return;\n }\n const onVisibilityChange = () => {\n if (!document.hidden && openedConversationIdRef.current !== conversationId) readOnOpening();\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n return () => document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n }, [conversationId, enabled, requestActivity]);\n\n const refresh = useCallback(() => requestActivity(true), [requestActivity]);\n\n return { elements, running, turnMessageId, runningBackgroundJobs, refresh };\n};\n","import { BACKLOG_LINE_PACE_MS, LINE_PACE_MS } from \"./activity-ticker\";\nimport { SUCCESS_BEAT_MS } from \"./use-activity-ticker\";\nimport { ACTIVITY_REQUEST_WINDOW_MS, RUNNING_FLOOR_MS } from \"./use-conversation-activity\";\n\n/**\n * The timing of the chat's activity lines and of its working indicator, for a host whose delivery differs from the\n * package's polling default. Every field is optional and defaults to the package's value; a value that is no finite\n * number at or above 0 counts as unset.\n *\n * A host with a realtime push that writes `activityUpdatedAt` when the narrator finishes lowers\n * `activityRequestWindowMs` (and the paces), so a narrated line shows as soon as the push arrives instead of after the\n * next 3 s window.\n */\nexport interface AgentChatActivityTiming {\n /** At most one activity read per this many milliseconds per conversation. Default 3000 (`ACTIVITY_REQUEST_WINDOW_MS`). */\n activityRequestWindowMs?: number;\n /** While a turn runs, an activity read also fires on this cadence (the floor for a dead signal). Default 4000 (`RUNNING_FLOOR_MS`). */\n runningFloorMs?: number;\n /** The least time a line stands beside the working face before the next one replaces it. Default 2200 (`LINE_PACE_MS`). */\n linePaceMs?: number;\n /** The shorter wait while more than two lines are queued. Default 1400 (`BACKLOG_LINE_PACE_MS`). */\n backlogLinePaceMs?: number;\n /** How long the face's success beat rests after the turn before it turns idle. Default 1400 (`SUCCESS_BEAT_MS`). */\n successBeatMs?: number;\n}\n\n/** Every timing value set: the resolved form the chat's hooks read. */\nexport type ResolvedAgentChatActivityTiming = Required<AgentChatActivityTiming>;\n\n/** The package's timing: what a chat uses when neither the chat nor the environment names a value. */\nexport const DEFAULT_AGENT_CHAT_ACTIVITY_TIMING: ResolvedAgentChatActivityTiming = {\n activityRequestWindowMs: ACTIVITY_REQUEST_WINDOW_MS,\n runningFloorMs: RUNNING_FLOOR_MS,\n linePaceMs: LINE_PACE_MS,\n backlogLinePaceMs: BACKLOG_LINE_PACE_MS,\n successBeatMs: SUCCESS_BEAT_MS,\n};\n\nconst isUsableMilliseconds = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\n/**\n * The timing of one chat: each field from the first source that sets a usable value — the chat's own\n * (`AgentChat activityTiming`), then the environment's (`AgentsEnvironment.chatActivityTiming`), then the package's.\n */\nexport const resolveAgentChatActivityTiming = (\n ...sources: (AgentChatActivityTiming | null | undefined)[]\n): ResolvedAgentChatActivityTiming => {\n const resolved = { ...DEFAULT_AGENT_CHAT_ACTIVITY_TIMING };\n (Object.keys(resolved) as (keyof ResolvedAgentChatActivityTiming)[]).forEach((key) => {\n const source = sources.find((candidate) => isUsableMilliseconds(candidate?.[key]));\n if (source) resolved[key] = source[key] as number;\n });\n return resolved;\n};\n","/**\n * A start an agent entry point outside the widget handed over: a visible USER message (`message`), or the invisible\n * START signal behind an EMPTY visible message (`signal`), which makes the agent speak first.\n */\nexport interface PendingStartRequest {\n kind: \"message\" | \"signal\";\n text: string;\n}\n\n/**\n * The one start the chat should send from the two hand-over fields (the opening request's `userMessage` and\n * `startSignalText`). The app's openers keep at most one of the two set — each clears the\n * other's leftover on the way in — but the message still wins here if both somehow are, since the customer's own words\n * are the stronger request.\n */\nexport const pickPendingStartRequest = (\n pendingStartUserMessage: string | null,\n pendingStartSignalText: string | null,\n): PendingStartRequest | null => {\n if (pendingStartUserMessage) {\n return { kind: \"message\", text: pendingStartUserMessage };\n }\n if (pendingStartSignalText) {\n return { kind: \"signal\", text: pendingStartSignalText };\n }\n return null;\n};\n\nexport interface ChatStateForPendingStartRequest {\n /** The start an agent entry point outside the widget handed over (`pickPendingStartRequest`). */\n pendingStartRequest: PendingStartRequest | null;\n /** The conversation the widget currently wants open (the chat's `conversationId` prop). */\n activeConversationId: number | null | undefined;\n /** The conversation the chat slice currently holds — set until a new-chat reset clears it. */\n loadedConversationId: number | null | undefined;\n /** A start-with-message POST is already in flight (the chat store's `startingNewConversation`). */\n startingNewConversation: boolean;\n /** The start this chat has already sent, so the same one is never posted twice. */\n alreadySentStartRequest: PendingStartRequest | null;\n}\n\n/**\n * Whether the chat should send `pendingStartRequest` as the start of a NEW conversation right now. Called on every\n * relevant state change — NOT once on mount: the widget is often already open (and mounted) when an entry point\n * outside it hands over a request, which is what BUF-4009 was.\n *\n * \"Not yet\" (false) and \"never\" (false) deliberately look the same to the caller: the request stays in the slice, and\n * this is asked again on the next change. A conversation still being open is the \"not yet\" case — Agent drops to a new\n * chat when a request arrives, because every incentive CTA promises a fresh chat for its job, and this then says yes\n * on the cold chat that follows.\n */\nexport const isChatReadyToSendPendingStartRequest = ({\n pendingStartRequest,\n activeConversationId,\n loadedConversationId,\n startingNewConversation,\n alreadySentStartRequest,\n}: ChatStateForPendingStartRequest): boolean => {\n if (!pendingStartRequest) {\n return false;\n }\n // A conversation is open (or still loaded while the new chat is being set up) — the request must never be appended\n // to it. A start already in flight would be dropped by the send handler's own in-flight guard, losing the request.\n if (activeConversationId || loadedConversationId || startingNewConversation) {\n return false;\n }\n return (\n alreadySentStartRequest?.kind !== pendingStartRequest.kind ||\n alreadySentStartRequest.text !== pendingStartRequest.text\n );\n};\n","import type {\n ConversationChangeSignal,\n ConversationRunStatus,\n ConversationSubscriptionEndReason,\n} from \"../../contract/conversation\";\n\n/** While a turn streams, per-message signals arrive in bursts — the re-read is coalesced to one per this window. */\nexport const LIVE_READ_THROTTLE_MS = 1200;\n/** Grace before the first convergence re-read (lets the terminal status' own immediate read land first). */\nexport const CONVERGENCE_BASE_DELAY_MS = 700;\n/** Backoff ceiling between convergence re-reads. */\nexport const CONVERGENCE_MAX_DELAY_MS = 2500;\n/** Stop re-reading for a missing terminal `lastMessageId` after this many attempts (the next action recovers). */\nexport const CONVERGENCE_MAX_ATTEMPTS = 6;\n\n/** What the live-update rules make the chat do. */\nexport interface ConversationLiveUpdateReads {\n /** Read the rows that changed (the chat's changed-tail read). */\n readChangedMessages: () => void;\n /** Read the conversation's metadata again (title, run state). */\n readConversationMetadata: () => void;\n /** Whether a message is loaded — the convergence check of a terminal signal's `lastMessageId`. */\n hasLoadedMessage: (messageId: number) => boolean;\n /** The run status the chat shows; null once the subscription ended. */\n showRunStatus: (runStatus: ConversationRunStatus | null) => void;\n}\n\nconst isTerminalRunStatus = (runStatus: ConversationRunStatus | null): boolean =>\n runStatus === \"idle\" || runStatus === \"failed\";\n\n/**\n * The package's rules over a conversation's live updates — one instance per subscription:\n * - the first pushed signal reads once (a turn may have moved between the chat's open and the subscription), and is\n * the baseline of the counter and of `summaryUpdatedAt`;\n * - a counter advance reads again, throttled to one read per `LIVE_READ_THROTTLE_MS` with one trailing read;\n * - a terminal status reads at once, re-reads the metadata (on the baseline and on every terminal signal that\n * advances the counter: the server closes a conversation after the turn and publishes one more idle signal), and\n * keeps reading with backoff until the signal's `lastMessageId` is loaded (a reply that beat its own commit);\n * - a changed `summaryUpdatedAt` after the baseline re-reads the metadata only;\n * - a status-check emission (`isStatusCheck`) sets the status, and reads again — at once on a terminal status — only\n * while the push path is not alive (the binding's `isPushPathAlive`; without it: no pushed signal arrived yet) and\n * its status differs from the previous check's;\n * - an ended subscription clears the status.\n * The transport's health (reconnect, a dead path, token refresh) is the binding's.\n */\nexport class ConversationChangeSignalRules {\n protected lastChangeCounter: number | null = null;\n protected hasSummaryBaseline = false;\n protected lastSummaryUpdatedAt: number | null = null;\n protected hasPushedSignalArrived = false;\n protected lastStatusCheckRunStatus: ConversationRunStatus | null = null;\n protected lastReadAt = 0;\n protected trailingReadTimer: ReturnType<typeof setTimeout> | null = null;\n protected convergenceTimer: ReturnType<typeof setTimeout> | null = null;\n protected convergenceAttempt = 0;\n protected convergenceMessageId: number | null = null;\n protected disposed = false;\n\n constructor(protected readonly reads: ConversationLiveUpdateReads) {}\n\n receiveSignal = (signal: ConversationChangeSignal): void => {\n if (this.disposed) return;\n if (signal.isStatusCheck) {\n this.receiveStatusCheck(signal.runStatus, signal.isPushPathAlive ?? this.hasPushedSignalArrived);\n return;\n }\n this.hasPushedSignalArrived = true;\n if (signal.runStatus !== null) {\n this.reads.showRunStatus(signal.runStatus);\n }\n if (!this.hasSummaryBaseline) {\n this.hasSummaryBaseline = true;\n this.lastSummaryUpdatedAt = signal.summaryUpdatedAt;\n } else if (signal.summaryUpdatedAt !== null && signal.summaryUpdatedAt !== this.lastSummaryUpdatedAt) {\n this.lastSummaryUpdatedAt = signal.summaryUpdatedAt;\n this.reads.readConversationMetadata();\n }\n const isTerminal = isTerminalRunStatus(signal.runStatus);\n if (this.lastChangeCounter === null) {\n this.lastChangeCounter = signal.changeCounter;\n this.requestRead(isTerminal);\n if (isTerminal) {\n this.convergeOnMessage(signal.lastMessageId);\n this.reads.readConversationMetadata();\n }\n return;\n }\n const hasCounterAdvanced = signal.changeCounter !== this.lastChangeCounter;\n if (!hasCounterAdvanced && !isTerminal) return;\n this.lastChangeCounter = signal.changeCounter;\n this.requestRead(isTerminal);\n if (isTerminal) {\n this.convergeOnMessage(signal.lastMessageId);\n if (hasCounterAdvanced) this.reads.readConversationMetadata();\n }\n };\n\n receiveEnd = (_reason: ConversationSubscriptionEndReason): void => {\n if (this.disposed) return;\n this.reads.showRunStatus(null);\n };\n\n /** Reads now, bypassing the throttle (the chat's safety poll). */\n readNow = (): void => {\n if (this.disposed) return;\n this.reads.readChangedMessages();\n };\n\n dispose = (): void => {\n this.disposed = true;\n this.clearTrailingRead();\n this.clearConvergence();\n };\n\n protected receiveStatusCheck(runStatus: ConversationRunStatus | null, isPushPathAlive: boolean): void {\n if (runStatus === null) return;\n this.reads.showRunStatus(runStatus);\n if (!isPushPathAlive && runStatus !== this.lastStatusCheckRunStatus) {\n this.requestRead(isTerminalRunStatus(runStatus));\n }\n this.lastStatusCheckRunStatus = runStatus;\n }\n\n /** One coordinated read path: `immediate` (a terminal status) cancels a pending trailing read and reads now. */\n protected requestRead(immediate: boolean): void {\n if (immediate) {\n this.clearTrailingRead();\n this.readThrottled();\n return;\n }\n const sinceLastRead = Date.now() - this.lastReadAt;\n if (sinceLastRead >= LIVE_READ_THROTTLE_MS) {\n this.readThrottled();\n return;\n }\n if (this.trailingReadTimer === null) {\n this.trailingReadTimer = setTimeout(this.readTrailing, LIVE_READ_THROTTLE_MS - sinceLastRead);\n }\n }\n\n protected readThrottled(): void {\n this.lastReadAt = Date.now();\n this.reads.readChangedMessages();\n }\n\n protected readTrailing = (): void => {\n this.trailingReadTimer = null;\n if (this.disposed) return;\n this.readThrottled();\n };\n\n protected clearTrailingRead(): void {\n if (this.trailingReadTimer !== null) {\n clearTimeout(this.trailingReadTimer);\n this.trailingReadTimer = null;\n }\n }\n\n protected convergeOnMessage(messageId: number | null): void {\n this.clearConvergence();\n if (messageId === null) return;\n this.convergenceMessageId = messageId;\n this.convergenceAttempt = 0;\n this.convergenceTimer = setTimeout(this.checkConvergence, CONVERGENCE_BASE_DELAY_MS);\n }\n\n protected checkConvergence = (): void => {\n this.convergenceTimer = null;\n const messageId = this.convergenceMessageId;\n if (this.disposed || messageId === null) return;\n if (this.reads.hasLoadedMessage(messageId)) return;\n if (this.convergenceAttempt >= CONVERGENCE_MAX_ATTEMPTS) return;\n this.convergenceAttempt += 1;\n this.reads.readChangedMessages();\n this.convergenceTimer = setTimeout(\n this.checkConvergence,\n Math.min(CONVERGENCE_BASE_DELAY_MS * this.convergenceAttempt, CONVERGENCE_MAX_DELAY_MS),\n );\n };\n\n protected clearConvergence(): void {\n if (this.convergenceTimer !== null) {\n clearTimeout(this.convergenceTimer);\n this.convergenceTimer = null;\n }\n }\n}\n","import { type Dispatch, type RefObject, type SetStateAction, useCallback, useEffect, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { ConversationRunStatus } from \"../../contract/conversation\";\nimport type { AgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { ConversationChangeSignalRules, type ConversationLiveUpdateReads } from \"./conversation-change-signal-rules\";\nimport type { ConversationMessagePages } from \"./use-conversation-message-pages\";\n\n/** The chat's reads behind the live-update rules: the changed tail and the metadata of the chat store's conversation. */\nclass ChatStoreLiveUpdateReads implements ConversationLiveUpdateReads {\n constructor(\n protected readonly chatStore: AgentsChatStore,\n /** The latest reads of the chat (a ref: their object changes with the older-page load state, the subscription does not). */\n protected readonly messagePagesRef: RefObject<ConversationMessagePages>,\n protected readonly conversationId: number,\n protected readonly setLiveReadCount: Dispatch<SetStateAction<number>>,\n readonly showRunStatus: Dispatch<SetStateAction<ConversationRunStatus | null>>,\n ) {}\n\n readChangedMessages = (): void => {\n this.setLiveReadCount((count) => count + 1);\n this.messagePagesRef.current.refetchChangedTail(this.conversationId);\n };\n\n readConversationMetadata = (): void => {\n void this.messagePagesRef.current.readConversationMetadata(this.conversationId);\n };\n\n hasLoadedMessage = (messageId: number): boolean =>\n (this.chatStore.getState().messages ?? []).some((message) => message.id === messageId);\n}\n\n/** The run status alone, for code outside the chat: no reads behind the rules. */\nclass RunStatusOnlyLiveUpdateReads implements ConversationLiveUpdateReads {\n constructor(readonly showRunStatus: Dispatch<SetStateAction<ConversationRunStatus | null>>) {}\n\n readChangedMessages = (): void => undefined;\n\n readConversationMetadata = (): void => undefined;\n\n hasLoadedMessage = (): boolean => true;\n}\n\nexport interface ConversationLiveUpdatesInputs {\n client: AgentsConversationClient;\n chatStore: AgentsChatStore;\n /** The reads the rules trigger (`useConversationMessagePages`). */\n messagePages: ConversationMessagePages;\n /** The conversation to follow; undefined for a cold chat (no subscription). */\n conversationId: number | undefined;\n}\n\nexport interface ConversationLiveUpdates {\n /** The run status the signal (or the binding's run-state check) reported last; null before the first and once ended. */\n runStatus: ConversationRunStatus | null;\n /** Counts the live reads the rules triggered — the activity read follows it (one activity read per signal tick). */\n liveReadCount: number;\n /** Reads the changed tail now, bypassing the throttle, and counts it (the chat's safety poll). */\n readChangedTailNow: () => void;\n}\n\n/**\n * The chat's live updates over `subscribeToConversationChanges`: one subscription per conversation,\n * the rules of `ConversationChangeSignalRules`, the reads written into the chat store.\n */\nexport const useConversationLiveUpdates = (inputs: ConversationLiveUpdatesInputs): ConversationLiveUpdates => {\n const { client, chatStore, messagePages, conversationId } = inputs;\n const [runStatus, setRunStatus] = useState<ConversationRunStatus | null>(null);\n const [liveReadCount, setLiveReadCount] = useState(0);\n const messagePagesRef = useRef(messagePages);\n messagePagesRef.current = messagePages;\n\n useEffect(() => {\n // A client without a subscription follows nothing here; `AgentChat` fills in the polling default before.\n if (!conversationId || !client.subscribeToConversationChanges) return;\n const rules = new ConversationChangeSignalRules(\n new ChatStoreLiveUpdateReads(chatStore, messagePagesRef, conversationId, setLiveReadCount, setRunStatus),\n );\n const unsubscribe = client.subscribeToConversationChanges(conversationId, rules.receiveSignal, rules.receiveEnd);\n return () => {\n rules.dispose();\n unsubscribe();\n };\n }, [client, chatStore, conversationId]);\n\n const readChangedTailNow = useCallback(() => {\n if (!conversationId) return;\n setLiveReadCount((count) => count + 1);\n messagePagesRef.current.refetchChangedTail(conversationId);\n }, [conversationId]);\n\n return { runStatus, liveReadCount, readChangedTailNow };\n};\n\n/**\n * The run status of a conversation for code outside the chat (the launcher button, the end of a voice call), over the\n * same port function and the same status rules as the chat — without reading any message.\n */\nexport const useAgentsConversationRunStatus = (\n client: AgentsConversationClient,\n conversationId: number | undefined,\n): ConversationRunStatus | null => {\n const [runStatus, setRunStatus] = useState<ConversationRunStatus | null>(null);\n useEffect(() => {\n // A client without a subscription reports nothing; wrap it in `withPollingChangeSubscription` first.\n if (!conversationId || !client.subscribeToConversationChanges) return;\n const rules = new ConversationChangeSignalRules(new RunStatusOnlyLiveUpdateReads(setRunStatus));\n const unsubscribe = client.subscribeToConversationChanges(conversationId, rules.receiveSignal, rules.receiveEnd);\n return () => {\n rules.dispose();\n unsubscribe();\n };\n }, [client, conversationId]);\n return runStatus;\n};\n","import { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { AgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { buildChangedMessagesRequest } from \"./changed-messages-request\";\n\n/** The page size of every message read of the chat: the newest page, the changed tail and an older page. */\nexport const CONVERSATION_MESSAGE_PAGE_SIZE = 50;\n\nexport interface ConversationMessagePages {\n /** Reads the conversation without messages into the store; resolves false when the read was refused. */\n readConversationMetadata: (conversationId: number) => Promise<boolean>;\n /** The newest page an open reads; a changed-tail read asked meanwhile waits for it. */\n fetchOpeningPage: (conversationId: number) => void;\n /** The rows written since the newest loaded one and the rows that can still change (a live update). */\n refetchChangedTail: (conversationId: number) => void;\n /** The page before the oldest loaded message (scroll-up); guarded against a second load and an exhausted history. */\n loadOlder: (conversationId: number | undefined) => Promise<void>;\n /** An older page is on its way. */\n loadingOlder: boolean;\n}\n\n/**\n * The chat's message reads over the conversation client port, written into the chat store: the newest page of an\n * open, the changed tail every live update asks for, an older page on scroll-up, and the metadata read. A changed-tail\n * read asked while the open's newest page is still on its way would read that same page again (nothing is loaded yet,\n * so it has no filter): it is held instead and sent once the page is in, reading past what the page brought, so a\n * reply stored in between still arrives. A failed page read changes nothing (the next live update reads again).\n */\nexport const useConversationMessagePages = (\n chatStore: AgentsChatStore,\n client: AgentsConversationClient,\n pageSize: number = CONVERSATION_MESSAGE_PAGE_SIZE,\n): ConversationMessagePages => {\n const openingPageRef = useRef<{ conversationId: number; refetchOwed: boolean } | null>(null);\n const [loadingOlder, setLoadingOlder] = useState(false);\n const loadingOlderRef = useRef(false);\n\n const readConversationMetadata = useCallback(\n async (conversationId: number): Promise<boolean> => {\n chatStore.dispatch({ type: \"conversationMetadataRequested\", conversationId });\n try {\n const conversation = await client.getConversationMetadata(conversationId);\n chatStore.dispatch({ type: \"conversationMetadataReceived\", conversationId, conversation });\n return true;\n } catch {\n chatStore.dispatch({ type: \"conversationMetadataFailed\", conversationId });\n return false;\n }\n },\n [chatStore, client],\n );\n\n // Reads the store, not the rendered messages: the held read runs before the opened page has re-rendered.\n const fetchChangedTail = useCallback(\n async (conversationId: number): Promise<void> => {\n const changedMessagesRequest = buildChangedMessagesRequest(chatStore.getState().messages, pageSize);\n chatStore.dispatch({ type: \"messagesPageRequested\", conversationId });\n try {\n if (changedMessagesRequest === null) {\n // Nothing loaded yet: the newest page, as on open.\n const page = await client.getNewestMessagesPage(conversationId, pageSize);\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: page.messages,\n hasMoreOlder: page.hasMoreOlder,\n });\n return;\n }\n const changedMessages = await client.getChangedMessages(conversationId, changedMessagesRequest);\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: changedMessages.messages,\n hasMoreOlder: null,\n });\n } catch {\n // A failed live read changes nothing; the next signal reads again.\n }\n },\n [chatStore, client, pageSize],\n );\n\n const fetchOpeningPage = useCallback(\n (conversationId: number) => {\n const openingPage = { conversationId, refetchOwed: false };\n openingPageRef.current = openingPage;\n chatStore.dispatch({ type: \"messagesPageRequested\", conversationId });\n const settleOpeningPage = () => {\n if (openingPageRef.current !== openingPage) return;\n openingPageRef.current = null;\n // A reset since (empty chat, closed window) has nothing left to read into.\n const isStillShown = chatStore.getState().requestedConversationId === conversationId;\n if (openingPage.refetchOwed && isStillShown) {\n void fetchChangedTail(conversationId);\n }\n };\n client\n .getNewestMessagesPage(conversationId, pageSize)\n .then((page) => {\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: page.messages,\n hasMoreOlder: page.hasMoreOlder,\n });\n })\n .catch(() => undefined)\n .then(settleOpeningPage);\n },\n [chatStore, client, pageSize, fetchChangedTail],\n );\n\n const refetchChangedTail = useCallback(\n (conversationId: number) => {\n const openingPage = openingPageRef.current;\n if (openingPage?.conversationId === conversationId) {\n openingPage.refetchOwed = true;\n return;\n }\n void fetchChangedTail(conversationId);\n },\n [fetchChangedTail],\n );\n\n const loadOlder = useCallback(\n async (conversationId: number | undefined): Promise<void> => {\n const { hasMoreOlder, messages } = chatStore.getState();\n if (loadingOlderRef.current || !hasMoreOlder || !conversationId) return;\n const lowestLoadedIndex = (messages ?? [])[0]?.indexInConversation;\n if (lowestLoadedIndex == null) return;\n loadingOlderRef.current = true;\n setLoadingOlder(true);\n chatStore.dispatch({ type: \"messagesPageRequested\", conversationId });\n try {\n const page = await client.getOlderMessagesPage(conversationId, lowestLoadedIndex, pageSize);\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: page.messages,\n hasMoreOlder: page.hasMoreOlder,\n });\n } catch {\n // The scroll-up load stays armed; the next sentinel hit tries again.\n } finally {\n loadingOlderRef.current = false;\n setLoadingOlder(false);\n }\n },\n [chatStore, client, pageSize],\n );\n\n return useMemo(\n () => ({ readConversationMetadata, fetchOpeningPage, refetchChangedTail, loadOlder, loadingOlder }),\n [readConversationMetadata, fetchOpeningPage, refetchChangedTail, loadOlder, loadingOlder],\n );\n};\n","import { createContext, useContext } from \"react\";\nimport type { ConversationBackgroundJob, ConversationBackgroundJobStop } from \"../../contract/conversation\";\n\n/**\n * What the chat knows about the conversation's background jobs, for the trace of a turn: the jobs whose end is not\n * reported yet (from the activity read) and where their lines stand. The chat controller provides it; the turn trace\n * shows the lines under the turn the context names. Without a provider no line is shown.\n */\nexport interface RunningBackgroundJobsContextValue {\n conversationId: number;\n /** The message that started the newest turn of the thread: the lines stand under the trace of that turn. */\n anchorTurnMessageId: number | string | null;\n /** The jobs whose end is not reported yet, oldest first. */\n backgroundJobs: ConversationBackgroundJob[];\n /** Stops one job (`stopBackgroundJob` of the client); without it the lines offer no Stop. */\n stopBackgroundJob?: (backgroundJobId: number) => Promise<ConversationBackgroundJobStop>;\n /** Reads the activity again at once (after a stop). */\n refresh: () => void;\n}\n\nexport const RunningBackgroundJobsContext = createContext<RunningBackgroundJobsContextValue | null>(null);\n\n/** The background jobs of the chat around, or null outside a chat that provides them. */\nexport const useRunningBackgroundJobs = (): RunningBackgroundJobsContextValue | null => useContext(RunningBackgroundJobsContext);\n","import { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface QueuedMessageChipProps {\n /** The queued message, quoted in the chip (above a composer). Without it the chip only says that the message waits. */\n text?: string | null;\n /** The chip stands in a narrow thread (a floating panel). */\n isCompact?: boolean;\n /**\n * The turn is over and took the message up: a quiet label above the message's bubble (\"Sent during the run · taken\n * up in this turn\") instead of the wait; `text` is only its tooltip.\n */\n wasTakenUp?: boolean;\n className?: string;\n}\n\n/**\n * The mark of an owner message sent while a turn runs: the agent reads it at its next step. Under the message in the\n * thread it is one quiet line; with `text` it quotes the message (above a composer).\n */\nexport const QueuedMessageChip = (props: QueuedMessageChipProps) => {\n const { text, isCompact = false, wasTakenUp = false, className } = props;\n if (wasTakenUp) {\n return (\n <div className={classNames(styles.queued, styles.queuedTakenUp, className)} data-testid=\"trace-queued-message-taken-up\" data-compact={isCompact || undefined} title={text ?? undefined}>\n <Icon name=\"stepDone\" pixelSize={12} />\n <span className={styles.queuedText}>\n {translateText(\"Sent during the run\")}\n {isCompact ? null : <> · {translateText(\"taken up in this turn\")}</>}\n </span>\n </div>\n );\n }\n return (\n <div\n className={classNames(styles.queued, !text && styles.queuedInThread, className)}\n role=\"status\"\n data-testid=\"trace-queued-message\"\n data-compact={isCompact || undefined}\n >\n <Icon name=\"stepWaiting\" pixelSize={13} />\n <span className={styles.queuedText}>\n {text ? (\n <>\n {translateText(\"Queued:\")} <span className={styles.queuedQuote}>{text}</span>\n {isCompact ? null : <> · {translateText(\"read at the next step\")}</>}\n </>\n ) : (\n translateText(\"Queued · read at the next step\")\n )}\n </span>\n </div>\n );\n};\n","import { RefObject, useCallback, useEffect, useRef } from \"react\";\nimport type { ChatMessage } from \"../chat-message\";\nimport type { ChatScrollTarget } from \"./chat-scroll-target\";\n\n/** What the scroll follow reads of the activity ticker: its phase and the lines of the turn on screen. */\nexport interface ConversationScrollActivityTicker {\n phase: string;\n currentTurn: { lines: { toolCallMessageId: number; state: string | null }[] } | null;\n}\n\nexport interface ConversationScrollJumpInputs {\n /** The top-bar search's request to scroll a message into view and flash it; re-applied whenever its nonce changes. */\n scrollTarget: ChatScrollTarget | undefined;\n /** The conversation the host asked for (the chat's `conversationId` prop) — the one a request is armed for. */\n conversationId: number | undefined;\n /** The conversation the chat store holds right now; differs from `conversationId` for a beat after a switch. */\n conversation: { id?: number | null } | null;\n /** The loaded messages: every change retries a pending request. */\n messages: ChatMessage[] | null;\n /** The loaded messages as of the last render, read where the retry runs. */\n messagesRef: RefObject<ChatMessage[] | null>;\n /** Whether an older page exists, as of the last render. */\n hasMoreOlderRef: RefObject<boolean>;\n /** Pages the next older page in (self-guarded against concurrent and exhausted loads). */\n loadOlder: () => Promise<void>;\n /** The chat's scroll container (the host may own it, e.g. for a scroll-linked background). */\n chatScrollRef: RefObject<HTMLDivElement | null>;\n /** What the activity ticker shows; a new line scrolls it into view while the chat follows the bottom. */\n activityTicker: ConversationScrollActivityTicker;\n}\n\nexport interface ConversationScrollJump {\n /** Bottom-follow flag shared with ConversationViewBody; false while a jump is armed and after it. */\n followBottomRef: RefObject<boolean>;\n /** \"A programmatic jump is in flight\" gate shared with ConversationViewBody. */\n scrollJumpActiveRef: RefObject<boolean>;\n}\n\n/**\n * The chat's programmatic scrolling: the jump to a requested message (paging older pages in until it is rendered, then\n * the flash once the smooth scroll settled) and keeping the activity ticker in view as it grows. Owns the two refs it\n * shares with ConversationViewBody, which suspend the bottom-follow while a jump is armed.\n */\nexport const useConversationScrollJump = (inputs: ConversationScrollJumpInputs): ConversationScrollJump => {\n const {\n scrollTarget,\n conversationId,\n conversation,\n messages,\n messagesRef,\n hasMoreOlderRef,\n loadOlder,\n chatScrollRef,\n activityTicker,\n } = inputs;\n\n // Scroll-to-message (top-bar search → Agent → here). The requested hit is held in a ref until its message is\n // actually in the DOM: if it sits on an older page that hasn't loaded yet, page older in and retry on each\n // `messages` change. `data-message-id` is stamped on every rendered message by ConversationMessageList; the flash is a\n // transient `data-flash` attribute styled in ConversationMessageList's stylesheet.\n // `armedForConversationId` stamps which conversation the request targeted, so a request that outlives its\n // conversation (e.g. the selected search hit's conversation 404s) can't page through an unrelated one later.\n const pendingScrollRef = useRef<(ChatScrollTarget & { armedForConversationId?: number }) | null>(null);\n // Bottom-follow flag shared with ConversationViewBody. A search-result jump scrolls to a message ABOVE the bottom, then the\n // messages settle their heights (images/markdown) which fires ConversationViewBody's resize bottom-follow. While a jump is\n // armed we hold this false so follow stays suspended for the whole jump (and afterwards — the user is now reading up\n // there, exactly as a manual scroll-up).\n const followBottomRef = useRef(true);\n // \"A programmatic jump is in flight\" gate, shared with ConversationViewBody. Distinct from followBottomRef because the jump\n // must ALSO stop ConversationViewBody's near-bottom onScroll handler from flipping followBottom back to true: right after the\n // click the container is still near the bottom (the smooth scrollIntoView hasn't physically moved yet), so onScroll\n // would re-enable follow and the resize-follow would then yank the view back down. While this is true ConversationViewBody\n // neither re-enables follow on scroll nor auto-scrolls to the bottom on resize. Cleared once the jump settles/disarms.\n const scrollJumpActiveRef = useRef(false);\n\n // Keep the activity ticker in view as it grows — a new line beside the face or a new row above it scrolls it\n // into view with the exact guarded pattern the search-result jump above uses (chatScrollRef query +\n // scrollIntoView), not a second scroller. Keyed on what the ticker SHOWS, not on the endpoint's elements: the ticker\n // releases lines one at a time after they arrive. Skipped while the user has scrolled away (followBottomRef false)\n // or a host jump is already in flight (scrollJumpActiveRef) — the scroll-to-latest button already covers that case,\n // exactly as it does for a growing final answer under the pinned-question addon.\n // `block: \"nearest\"`, never \"end\": during a pinned turn (enablePinQuestionAndRevealAnswer) the room reserved below\n // the question makes the pinned position the scroll bottom, so ConversationViewBody's near-bottom onScroll turns\n // followBottomRef back on. \"end\" then aligned the ticker with the viewport bottom — scrolling UP by the reserved room\n // and dropping the question off the top. \"nearest\" only scrolls once the ticker actually runs below the fold.\n const activitySignatureRef = useRef(\"\");\n useEffect(() => {\n const { phase, currentTurn } = activityTicker;\n const newestLine = currentTurn?.lines[currentTurn.lines.length - 1];\n const signature = `${phase}|${currentTurn?.lines.length}|${newestLine?.toolCallMessageId}:${newestLine?.state}`;\n if (signature === activitySignatureRef.current) return;\n activitySignatureRef.current = signature;\n if (phase !== \"live\" || !followBottomRef.current || scrollJumpActiveRef.current) return;\n const tickerElement = chatScrollRef.current?.querySelector<HTMLElement>('[data-testid=\"agent-activity-ticker\"]');\n tickerElement?.scrollIntoView({ behavior: \"smooth\", block: \"nearest\", inline: \"nearest\" });\n }, [activityTicker, chatScrollRef, followBottomRef, scrollJumpActiveRef]);\n\n // Tracks the in-flight \"remove the flash highlight\" timer so it can be cancelled if a new scroll lands first or the\n // widget unmounts mid-flash (otherwise the callback fires on a detached node).\n const flashTimerRef = useRef<number | null>(null);\n // Tracks the requestAnimationFrame loop that waits for the smooth scroll to settle before the flash starts, so a new\n // scroll request or an unmount can cancel a still-pending wait.\n const scrollSettleRafRef = useRef<number | null>(null);\n const tryScrollToPendingMessage = useCallback(() => {\n const target = pendingScrollRef.current;\n if (!target?.messageId) return;\n // The conversation the request was armed for is gone (load failed / user navigated elsewhere) — disarm rather\n // than hunting a foreign message id through whatever conversation is shown now.\n if (target.armedForConversationId !== conversationId) {\n pendingScrollRef.current = null;\n scrollJumpActiveRef.current = false;\n return;\n }\n // A jump is armed for the current conversation → suspend bottom-follow AND gate ConversationViewBody's follow-re-enable /\n // resize-follow for the whole jump. Re-asserted on every retry (each older-page merge), so even a conversation\n // switch that briefly re-enabled follow can't yank us down.\n followBottomRef.current = false;\n scrollJumpActiveRef.current = true;\n const messageElement = chatScrollRef.current?.querySelector<HTMLElement>(`[data-message-id=\"${target.messageId}\"]`);\n if (messageElement) {\n pendingScrollRef.current = null;\n // Cancel any flash still in flight from a previous jump (its removal timer + settle watcher) and clear the\n // attribute so the animation can restart cleanly on this message.\n if (flashTimerRef.current !== null) window.clearTimeout(flashTimerRef.current);\n if (scrollSettleRafRef.current !== null) window.cancelAnimationFrame(scrollSettleRafRef.current);\n messageElement.removeAttribute(\"data-flash\");\n\n messageElement.scrollIntoView({ behavior: \"smooth\", block: \"center\" });\n\n // Start the flash only AFTER the smooth scroll settles, so the highlight plays on the at-rest message rather\n // than during the travel. Watch the element's viewport position each frame: once it holds still for 3\n // consecutive frames (covers both \"scrolled then stopped\" and \"already in view\"), or a 1.2s safety cap elapses,\n // the scroll has ended → toggle `data-flash` and arm its ~2s removal.\n let lastTop = messageElement.getBoundingClientRect().top;\n let stillFrames = 0;\n const startedAt = performance.now();\n const waitForScrollEnd = () => {\n if (!messageElement.isConnected) {\n scrollSettleRafRef.current = null;\n scrollJumpActiveRef.current = false;\n return;\n }\n const top = messageElement.getBoundingClientRect().top;\n stillFrames = Math.abs(top - lastTop) < 0.5 ? stillFrames + 1 : 0;\n lastTop = top;\n if (stillFrames >= 3 || performance.now() - startedAt > 1200) {\n scrollSettleRafRef.current = null;\n // The jump has come to rest → lift the gate. followBottomRef stays false, so a later content-resize won't\n // yank to the bottom; the user is parked at the target, exactly as after a manual scroll-up.\n scrollJumpActiveRef.current = false;\n messageElement.setAttribute(\"data-flash\", \"true\");\n flashTimerRef.current = window.setTimeout(() => {\n flashTimerRef.current = null;\n if (messageElement.isConnected) messageElement.removeAttribute(\"data-flash\");\n }, 2000);\n return;\n }\n scrollSettleRafRef.current = window.requestAnimationFrame(waitForScrollEnd);\n };\n scrollSettleRafRef.current = window.requestAnimationFrame(waitForScrollEnd);\n return;\n }\n // Conversation just switched (e.g. a cross-conversation search hit selected in the current tab): the slice still\n // holds the PREVIOUS conversation's messages/hasMoreOlder for a beat before the new fetch resolves. Evaluating\n // against that stale data below would misjudge \"exhausted\" and disarm the request too early — wait instead for the\n // messages-change effect to retry once the new conversation's own data actually lands.\n if (String(conversation?.id) !== String(conversationId) || messagesRef.current === null) return;\n // Not rendered yet — if the target is older than the oldest loaded message, page older in; the messages-change\n // effect below retries once that page merges. loadOlder self-guards against concurrent / exhausted loads.\n const lowestLoadedIndex = messagesRef.current[0]?.indexInConversation;\n const targetIsOlderThanLoaded =\n target.indexInConversation == null || lowestLoadedIndex == null || target.indexInConversation < lowestLoadedIndex;\n if (hasMoreOlderRef.current && targetIsOlderThanLoaded) {\n void loadOlder();\n return;\n }\n // Exhausted every older page and still no match (e.g. a deleted/stale message id) — disarm so we don't keep\n // re-querying on every future message change and can't later jump to an unrelated message that reuses the id.\n pendingScrollRef.current = null;\n scrollJumpActiveRef.current = false;\n }, [chatScrollRef, loadOlder, conversation, conversationId]);\n\n // A new scroll request (nonce changed) → arm it and attempt immediately.\n useEffect(() => {\n if (!scrollTarget?.messageId) return;\n // conversationId is read from this render's closure: Agent sets the target conversation and the scroll\n // request in the same state update, so at arm time the prop already names the conversation the hit belongs to.\n pendingScrollRef.current = { ...scrollTarget, armedForConversationId: conversationId };\n tryScrollToPendingMessage();\n // This effect closes over the nonce-triggering render's current conversation and pending message. The nonce bump\n // is deliberately the sole re-run trigger; it reads those current values when it fires.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [scrollTarget?.nonce]);\n\n // Cancel a pending flash-removal timer and scroll-settle watcher on unmount so neither fires after the widget closes.\n useEffect(\n () => () => {\n if (flashTimerRef.current !== null) window.clearTimeout(flashTimerRef.current);\n if (scrollSettleRafRef.current !== null) window.cancelAnimationFrame(scrollSettleRafRef.current);\n },\n [],\n );\n\n // Retry the pending scroll after each message-list change (an older page merged in, or the live reply landed).\n useEffect(() => {\n if (pendingScrollRef.current) tryScrollToPendingMessage();\n }, [messages, tryScrollToPendingMessage]);\n\n return { followBottomRef, scrollJumpActiveRef };\n};\n","import { findBalancedJsonObjectEnd } from \"./balanced-json-object\";\nimport { parseWidgetJsonObject } from \"./widget-fence-json\";\nimport { BARE_WIDGET_LINE_GLOBAL, WIDGET_FENCE_LANG } from \"./widget-fence-syntax\";\nimport { closestWidgetNames, resolveWidgetName } from \"./widget-name-resolver\";\n\n/**\n * The signal provenance for the widget-render-failure corrective signal — distinct from a widget CLICK. Mirrors the\n * backend {@link AIConversationMessage::SIGNAL_SOURCE_FRONTEND_WIDGET_INVALID}; the admin inspector shows it as the\n * signal source and the agent loop treats it as model-visible feedback.\n */\nexport const WIDGET_INVALID_SIGNAL_SOURCE = \"FRONTEND_WIDGET_INVALID\";\n\nexport interface UnrenderedWidget {\n /** The `type` the model wrote. */\n type: string;\n /**\n * What went wrong:\n * - `unknownType`: a widget block (fenced or bare `widget { … }` line) whose type is not a registered widget →\n * dropped, the customer sees NOTHING.\n * - `missingFence`: widget JSON emitted as PLAIN TEXT (no ```widget fence, no `widget` prefix) → the customer sees\n * raw JSON prose.\n */\n kind: \"unknownType\" | \"missingFence\";\n /** The closest valid widget names (deterministic similarity) for a \"did you mean\" — may be empty. */\n suggestions: string[];\n}\n\n// A ```widget fenced block: ```widget <optional trailing> \\n <json> \\n ``` . Non-greedy body; the `m`-less dotall\n// via [\\s\\S] so a multi-line JSON body is captured. Built from the shared lang constant so \"``` widget\" (a space\n// before the lang — remark accepts it) is recognized the same way as the render plugin and the repairer.\nconst WIDGET_FENCE = new RegExp(\"```[ \\\\t]*\" + WIDGET_FENCE_LANG + \"[^\\\\n]*\\\\n([\\\\s\\\\S]*?)```\", \"g\");\n\n// ANY fenced block — stripped before the naked-JSON scan so fenced content (handled widgets, legit code samples)\n// is never re-reported as fence-less.\nconst ANY_FENCE = /```[\\s\\S]*?```/g;\n\n/**\n * Parse a candidate JSON snippet into its `type` string, or null when it isn't an object with a string `type` — read\n * like the render plugin reads a block (`parseWidgetJsonObject`: a surplus trailing `}` / `]` is tolerated).\n */\nconst parseWidgetType = (jsonCandidate: string): string | null => {\n const type = parseWidgetJsonObject(jsonCandidate)?.type;\n return typeof type === \"string\" && type !== \"\" ? type : null;\n};\n\n/**\n * Extract balanced `{…}` JSON candidates that start at a line beginning (after whitespace) in PLAIN text — the shape\n * a model emits when it writes a widget payload without the fence (observed live: the final answer carried\n * `{ \"type\": \"ExampleWidget\", … }` as its own paragraph). A simple brace-balance walk (strings respected) keeps this\n * dependency-free; nested objects are fine. Bare `widget { … }` lines are NOT captured here (they start with the\n * `widget` prefix, not `{`) — remarkWidgetFencePlugin renders those, and the bare-line scan below covers their\n * unknown types.\n */\nconst extractNakedJsonCandidates = (plainText: string): string[] => {\n const candidates: string[] = [];\n const lines = plainText.split(\"\\n\");\n let offset = 0;\n for (const line of lines) {\n const lineStart = offset;\n offset += line.length + 1;\n if (!line.trimStart().startsWith(\"{\")) continue;\n const openIndex = lineStart + line.indexOf(\"{\");\n const jsonObjectEnd = findBalancedJsonObjectEnd(plainText, openIndex);\n if (jsonObjectEnd !== null) {\n candidates.push(plainText.slice(openIndex, jsonObjectEnd + 1));\n }\n }\n return candidates;\n};\n\n/**\n * Find widget-emission failures in an assistant message — the cases where the customer does NOT get the intended\n * widget. Uses the SAME resolveWidgetName as the render plugin, so \"valid\" means exactly \"would have rendered\".\n * Three scan surfaces, two failure classes:\n *\n * 1. `unknownType` — a ```widget fence OR a bare `widget { … }` line (both forms remarkWidgetFencePlugin renders)\n * whose `type` is not a registered widget: the plugin silently DROPS it, the customer sees nothing and the model\n * gets no feedback (a model wrote `type: \"example\"` instead of `ExampleWidget`). A malformed-JSON\n * block is skipped (the plugin drops it too).\n * 2. `missingFence` — widget JSON emitted as PLAIN prose (no fence, no `widget` prefix): nothing intercepts it, so\n * the customer sees raw JSON text (found live: `{ \"type\": \"ExampleWidget\", … }` as a paragraph of the final answer).\n * Reported when the naked JSON's `type` resolves to a VALID widget (the model clearly meant a widget) or is CLOSE\n * to one (similarity shortlist non-empty) — arbitrary JSON without a widget-like `type` is never flagged (no false\n * positives on legitimate JSON content).\n */\nexport const detectUnrenderedWidgets = (messageText: string): UnrenderedWidget[] => {\n const unrendered: UnrenderedWidget[] = [];\n const seenTypes = new Set<string>();\n const report = (type: string, kind: UnrenderedWidget[\"kind\"], suggestions: string[]) => {\n if (seenTypes.has(type)) return;\n seenTypes.add(type);\n unrendered.push({ type, kind, suggestions });\n };\n\n // 1) Rendered-form blocks (```widget fence + bare `widget { … }` line) with an unknown type.\n if (messageText.includes(\"widget\")) {\n for (const renderedFormRegex of [WIDGET_FENCE, BARE_WIDGET_LINE_GLOBAL]) {\n renderedFormRegex.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = renderedFormRegex.exec(messageText)) !== null) {\n const type = parseWidgetType(match[1]);\n if (type === null) continue;\n if (resolveWidgetName(type)) continue; // resolves → it rendered; nothing to report\n report(type, \"unknownType\", closestWidgetNames(type));\n }\n }\n }\n\n // 2) Naked widget JSON outside any fence.\n const plainText = messageText.replace(ANY_FENCE, \"\");\n if (plainText.includes('\"type\"')) {\n for (const jsonCandidate of extractNakedJsonCandidates(plainText)) {\n const type = parseWidgetType(jsonCandidate);\n if (type === null) continue;\n if (resolveWidgetName(type)) {\n report(type, \"missingFence\", []);\n continue;\n }\n const suggestions = closestWidgetNames(type);\n if (suggestions.length > 0) {\n report(type, \"unknownType\", suggestions);\n }\n // No resolution AND nothing close → arbitrary JSON, not a widget attempt — never flagged.\n }\n }\n\n return unrendered;\n};\n\n/**\n * The user-INVISIBLE corrective SIGNAL text for one or more widget-emission failures — tells the model exactly what\n * the customer experienced (nothing rendered / raw JSON prose) and how to fix it. Kept terse; the model already holds\n * the full widget catalog in its instructions.\n */\nexport const buildUnrenderedWidgetSignal = (widgets: UnrenderedWidget[]): string => {\n const parts = widgets.map((widget) => {\n if (widget.kind === \"missingFence\") {\n return `You emitted the \"${widget.type}\" widget as PLAIN JSON text — without the \\`\\`\\`widget code fence it does not render and the customer sees raw JSON prose.`;\n }\n const suggestion =\n widget.suggestions.length > 0 ? ` Closest valid widget names: ${widget.suggestions.join(\", \")}.` : \"\";\n return `\"${widget.type}\" is not a valid widget type, so it did not render and the customer sees nothing.${suggestion}`;\n });\n return (\n `A widget you emitted did not reach the customer. ${parts.join(\" \")} ` +\n \"Re-emit it as a ```widget code block (fence on its own lines) using the EXACT valid widget name that matches your intent.\"\n );\n};\n","import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useRef } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport { isAgentsClientError } from \"../../contract/conversation\";\nimport type { ChatMessage } from \"../chat-message\";\nimport type { SendMessageHandler } from \"../conversation-send-message\";\nimport { normalizeServerMessageToMarkdown } from \"../normalize-server-message-to-markdown\";\nimport type { InjectSignalOptions } from \"../../renderer/ConversationWidgetCallbacksContext\";\nimport {\n buildUnrenderedWidgetSignal,\n detectUnrenderedWidgets,\n WIDGET_INVALID_SIGNAL_SOURCE,\n} from \"../../renderer/detect-unrendered-widgets\";\nimport {\n buildWidgetRenderReportSignal,\n createWidgetRenderReportCollector,\n WIDGET_RENDER_REPORT_SIGNAL_SOURCE,\n type WidgetRenderBlockReport,\n} from \"../../renderer/render-report/widget-render-report-collector\";\n\n/** Max invalid-widget corrective signals per conversation — a too-weak model that keeps emitting bad widgets stops here. */\nconst WIDGET_CORRECTION_CAP = 2;\n\nexport interface ConversationSignalsInputs {\n /** The conversation client the signals go through (`injectSignal`). */\n client: AgentsConversationClient;\n /** The conversation the host asked for (the chat's `conversationId` prop); a signal targets it while none is loaded. */\n conversationId: number | undefined;\n /** The conversation the chat store holds right now. */\n conversation: { id?: number | null } | null;\n /** The loaded messages; the newest settled assistant message is checked for a dropped widget block. */\n messages: ChatMessage[] | null;\n /** The signal's run status (\"running\" | \"idle\" | \"failed\" | null). */\n runStatus: string | null;\n /** A start is in flight; a signal is not sent into a conversation that does not exist yet then. */\n startingNewConversation: boolean;\n /** The run is over; the backend refuses further input. */\n isConversationRunEnded: boolean;\n /** The chat's send — a signal without a conversation starts one through it. */\n handleSendMessage: SendMessageHandler;\n /** Shows the closed-conversation refusal on the error card. */\n rejectAsConversationClosed: () => void;\n /** Re-reads the conversation's metadata (the closed run state locks the widget controls). */\n refetchConversationSummary: () => void;\n /** The chat's jump-to-bottom request counter; a customer's click follows the turn it starts. */\n setScrollToBottomNonce: Dispatch<SetStateAction<number>>;\n}\n\nexport interface ConversationSignals {\n /** Injects a model-visible, customer-invisible signal into the current conversation (the widget context's `injectSignal`). */\n handleInjectSignal: (signalText: string, options?: InjectSignalOptions) => Promise<boolean>;\n /** The widget render report collector of the current conversation (one per conversation). */\n renderReportCollector: ReturnType<typeof createWidgetRenderReportCollector>;\n}\n\n/**\n * The signals the chat sends besides the customer's messages: a widget's injected signal (with the closed-conversation\n * guard and the cold start through a START signal), a context-only signal parked until a turn is observed running,\n * the corrective signal for a widget block the renderer dropped, and the widget render report.\n */\nexport const useConversationSignals = (inputs: ConversationSignalsInputs): ConversationSignals => {\n const {\n client,\n conversationId,\n conversation,\n messages,\n runStatus,\n startingNewConversation,\n isConversationRunEnded,\n handleSendMessage,\n rejectAsConversationClosed,\n refetchConversationSummary,\n setScrollToBottomNonce,\n } = inputs;\n // The conversation actually shown right now, kept in sync every render — read from an `injectSignal` `.catch`\n // so a late-landing rejection for a conversation the customer already left doesn't dispatch onto whatever is\n // open now (see the id check inside `handleInjectSignal`).\n const currentConversationIdRef = useRef<number | null>(null);\n currentConversationIdRef.current = conversation?.id ?? null;\n\n // A `withoutOwnAgentTurn` signal (context riding along a just-posted user message, e.g. advisor-extension\n // instructions) waiting for a turn to be OBSERVED running. Delivered mid-turn it lands in the conversation history\n // without re-driving the agent — the backend only re-drives when the LAST message is an unanswered inbound, and a\n // signal appended before the live turn's reply is no longer last (see the flush effect's strand explanation below;\n // here that strand behavior is exactly what we want: in context from the next turn on, never its own reply).\n // `conversationId` pins the signal to the conversation open at park time: null = parked on a cold start (the\n // paired message creates the conversation, deliver into whichever id lands); a non-null mismatch at flush time\n // means the user switched conversations first — the signal is dropped, never leaked into the other conversation.\n const signalAwaitingRunningTurnRef = useRef<{ signalText: string; conversationId: number | null } | null>(null);\n // Inject a model-visible / user-invisible SIGNAL into the CURRENT conversation and drive one agent turn — the\n // data-back path for a picker widget (\"User selected image A\"). Resilient (swallows errors, never throws\n // into render). The reply lands via the existing realtime signal, exactly like a posted message — no extra handling\n // needed here.\n //\n // NOTE: unlike the message-post path this carries NO admin overrides. The endpoint\n // (AIConversationsController::injectSignal) reads only `signalText` + `signalSource` — it has no `budgetBypass` /\n // `aiModelName` parameter, so the earlier hand-wired call was sending two query params the backend discarded. An\n // impersonating admin's model pick therefore does not apply to a widget-click-driven turn; the conversation's\n // stored model does.\n const handleInjectSignal = useCallback(\n async (signalText: string, options?: InjectSignalOptions): Promise<boolean> => {\n if (!signalText.trim()) return false;\n // CUSTOMER_CLICK (the default when options is omitted, e.g. the briefing widgets' plain signal text) is the\n // customer pressing a widget button; PROGRAMMATIC (park-then-flush ride-alongs, the widget-invalid corrective)\n // never came from a click — it must never surface a refusal or move the scroll position.\n const isCustomerClick = options?.signalOrigin !== \"PROGRAMMATIC\";\n // Same guard as the message path: a closed conversation rejects signals too, so no widget click posts one. A\n // genuine click gets the reason on the error card; a programmatic ride-along is simply dropped, as on any\n // other failure.\n if (isConversationRunEnded) {\n if (isCustomerClick) {\n rejectAsConversationClosed();\n }\n return false;\n }\n // On a real click, scroll the chat to the bottom to follow the turn this signal drives.\n if (isCustomerClick) {\n setScrollToBottomNonce((nonce) => nonce + 1);\n }\n // Context-only signal: deliver it ONLY while a turn is running, so it never drives its own turn / reply. Not\n // running yet (the paired user message's POST is still in flight, or the conversation is still being created on\n // a cold start) — park it until the flush effect below sees \"running\". Dropped if no turn ever starts.\n if (options?.withoutOwnAgentTurn && runStatus !== \"running\") {\n signalAwaitingRunningTurnRef.current = {\n signalText,\n conversationId: conversation?.id ?? conversationId ?? null,\n };\n return false;\n }\n const targetConversationId = conversation?.id ?? conversationId;\n // No conversation yet (e.g. a briefing CTA clicked on the cold dashboard greeting): start one via the\n // start-with-signal path — an EMPTY visible message carrying the click as the invisible START signal, so the\n // agent's first turn already has it and it speaks first (no visible bubble, no deferred re-inject). Once a\n // conversation exists we keep the silent injectSignal behavior below.\n if (!targetConversationId) {\n if (startingNewConversation) return false;\n handleSendMessage(\"\", { startSignalText: signalText });\n return false;\n }\n // No admin-debug overrides here on purpose — see the NOTE on this callback: the endpoint takes neither\n // `budgetBypass` nor `aiModelName`.\n // signalSource defaults server-side to FRONTEND_WIDGET_CLICK; the widget-failover passes FRONTEND_WIDGET_INVALID.\n return client\n .injectSignal(targetConversationId, { text: signalText, source: options?.signalSource })\n .then(() => true)\n .catch((signalRequestError: unknown) => {\n // Best-effort: a failed signal must not break the widget render. The turn simply doesn't advance. A\n // GENUINE widget click is the exception, and only for the one refusal reason the customer can act on\n // (the conversation closed meanwhile) — every other failure stays silent, exactly as before.\n const isConversationClosedRefusal =\n isAgentsClientError(signalRequestError) && signalRequestError.kind === \"closed\";\n // The request targeted a conversation the customer has since left (switched conversations before this\n // late-landing rejection arrived) — don't dispatch onto whatever conversation is open now.\n if (\n isCustomerClick &&\n isConversationClosedRefusal &&\n currentConversationIdRef.current === targetConversationId\n ) {\n rejectAsConversationClosed();\n // The closed runState locks the remaining widget controls.\n refetchConversationSummary();\n }\n return false;\n });\n },\n [\n client,\n conversation,\n conversationId,\n startingNewConversation,\n handleSendMessage,\n runStatus,\n isConversationRunEnded,\n rejectAsConversationClosed,\n refetchConversationSummary,\n setScrollToBottomNonce,\n ],\n );\n\n // Deliver a parked context-only signal the moment its paired turn is observed running (see\n // `signalAwaitingRunningTurnRef`). Re-entering handleInjectSignal with `withoutOwnAgentTurn` while \"running\"\n // passes its park-guard and POSTs. Tiny race stays open: if the turn settles between this observation and the\n // POST landing, the signal becomes the last message and drives one extra turn — rare and harmless (the agent\n // acknowledges the instructions), accepted for an FE-only build.\n useEffect(() => {\n if (runStatus !== \"running\" || !signalAwaitingRunningTurnRef.current) return;\n const parkedSignal = signalAwaitingRunningTurnRef.current;\n signalAwaitingRunningTurnRef.current = null;\n // Parked for a DIFFERENT conversation (the user switched before its turn ran) — drop, don't leak it here.\n if (parkedSignal.conversationId !== null && parkedSignal.conversationId !== conversation?.id) return;\n handleInjectSignal(parkedSignal.signalText, { withoutOwnAgentTurn: true, signalOrigin: \"PROGRAMMATIC\" });\n }, [runStatus, handleInjectSignal, conversation?.id]);\n\n // ── Widget failover ─────────────────────────────────────────────────────────────────────────────────────────────\n // A weaker model can emit a ```widget block whose `type` is not a real widget (a model wrote\n // `type: \"example\"`, not `ExampleWidget`). remarkWidgetFencePlugin silently DROPS it → the customer sees no\n // widget and the model gets no feedback, so it insists \"it should be visible\". Detect the dropped block on the newest\n // SETTLED assistant message and inject a silent corrective SIGNAL (with a similarity \"did you mean\" shortlist) so the\n // model re-emits with a valid name. Guards: (1) only after a live turn we OBSERVED running — never retroactively\n // \"correct\" widgets already in history when a conversation opens; (2) report each message id at most once; (3) cap\n // corrections per conversation so a too-weak model can't loop forever.\n const sawRunningForWidgetCheckRef = useRef(false);\n const reportedWidgetErrorMessageIdsRef = useRef<Set<number>>(new Set());\n const widgetCorrectionCountRef = useRef(0);\n\n useEffect(() => {\n if (runStatus === \"running\") sawRunningForWidgetCheckRef.current = true;\n }, [runStatus]);\n\n useEffect(() => {\n // A new conversation resets the live-turn sighting and the per-conversation correction budget. (The parked\n // context-only signal is NOT cleared here: a cold start legitimately transitions id null→new while the signal\n // waits; cross-conversation leaking is prevented by the id check in its flush effect instead.)\n sawRunningForWidgetCheckRef.current = false;\n reportedWidgetErrorMessageIdsRef.current = new Set();\n widgetCorrectionCountRef.current = 0;\n }, [conversation?.id]);\n\n useEffect(() => {\n if (runStatus !== \"idle\" || !sawRunningForWidgetCheckRef.current) return;\n if (widgetCorrectionCountRef.current >= WIDGET_CORRECTION_CAP || !messages) return;\n const latestAssistantMessage = [...messages]\n .reverse()\n .find(\n (message) => message.role === \"ASSISTANT\" && message.messageType === \"TEXT\",\n );\n const messageId = latestAssistantMessage?.id;\n if (!messageId || !latestAssistantMessage?.message) return;\n if (reportedWidgetErrorMessageIdsRef.current.has(messageId)) return;\n // Feed the SAME normalized text ConversationMarkdown renders (it repairs a fence the model broke mid-text) —\n // scanning the raw stored text here would report a fence the renderer already fixed as unrendered.\n const unrenderedWidgets = detectUnrenderedWidgets(normalizeServerMessageToMarkdown(latestAssistantMessage.message));\n if (unrenderedWidgets.length === 0) return;\n reportedWidgetErrorMessageIdsRef.current.add(messageId);\n widgetCorrectionCountRef.current += 1;\n handleInjectSignal(buildUnrenderedWidgetSignal(unrenderedWidgets), {\n signalSource: WIDGET_INVALID_SIGNAL_SOURCE,\n signalOrigin: \"PROGRAMMATIC\",\n });\n }, [messages, runStatus, handleInjectSignal]);\n\n // ── Widget render report ─────────────────────────────────────────────────────────────────────────\n // Every block of a live-delivered message reports mounted / empty / failed / pending; once a message's blocks settle,\n // ONE context signal tells the model which ones the owner did not see as intended. A clean render sends nothing; the\n // source owes no work, so the signal never drives a turn of its own (the next turn reads it). One collector per\n // conversation, so a switch never reports into the other one.\n const sendWidgetRenderReportRef = useRef<(messageId: string, blocks: WidgetRenderBlockReport[]) => void>(() => {});\n sendWidgetRenderReportRef.current = (messageId: string, blocks: WidgetRenderBlockReport[]) => {\n const renderReportSignalText = buildWidgetRenderReportSignal(messageId, blocks);\n if (renderReportSignalText === null) return;\n handleInjectSignal(renderReportSignalText, {\n signalSource: WIDGET_RENDER_REPORT_SIGNAL_SOURCE,\n signalOrigin: \"PROGRAMMATIC\",\n });\n };\n const renderReportCollector = useMemo(\n () =>\n createWidgetRenderReportCollector({\n onSettled: (messageId, blocks) => sendWidgetRenderReportRef.current(messageId, blocks),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one collector per conversation\n [conversation?.id],\n );\n useEffect(() => () => renderReportCollector.dispose(), [renderReportCollector]);\n\n return { handleInjectSignal, renderReportCollector };\n};\n","import {\n type ComponentType,\n type HTMLAttributes,\n type ReactNode,\n type Ref,\n type RefObject,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport {\n AgentsClientError,\n type ConversationAttachmentReference,\n isAgentsClientError,\n} from \"../../contract/conversation\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport { reportRunningTurn } from \"../../provider/environment\";\nimport { CanvasRestoreOnMount } from \"../../renderer/canvas/CanvasRestoreOnMount\";\nimport { ConversationDeepLinkedWidget } from \"../../renderer/ConversationDeepLinkedWidget\";\nimport { ConversationWidgetProvider } from \"../../renderer/ConversationWidgetContext\";\nimport { WidgetRenderReportCollectorContext } from \"../../renderer/render-report/widget-render-report-collector\";\nimport { resolveDeepLinkableWidget } from \"../../renderer/resolve-deep-linkable-widget\";\nimport type { ChatMessage } from \"../chat-message\";\nimport type { SendMessageHandler } from \"../conversation-send-message\";\nimport type { ConversationMessageInputHandle } from \"../ConversationMessageInput/ConversationMessageInput\";\nimport type { ConversationComposerWidget } from \"../../renderer/conversation-composer-widget\";\nimport type { ComposerLibraryFile } from \"../../renderer/composer-library-file\";\nimport { ConversationView } from \"../ConversationView\";\nimport { findUnansweredWidgetMessageId } from \"../ConversationMessageList/ConversationMessageList\";\nimport type { MessageTimesMode } from \"../ConversationMessageList/message-times\";\nimport type { AgentsChatState } from \"../store/agents-chat-state\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport type { AgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { useAgentsChatSelector } from \"../store/use-agents-chat-store\";\nimport {\n type AgentChatActivityTiming,\n type ResolvedAgentChatActivityTiming,\n resolveAgentChatActivityTiming,\n} from \"./chat-activity-timing\";\nimport type { ChatScrollTarget } from \"./chat-scroll-target\";\nimport { deriveAgentActivity } from \"./derive-agent-activity\";\nimport { isChatReadyToSendPendingStartRequest, type PendingStartRequest, pickPendingStartRequest } from \"./pending-start-request\";\nimport { type ActivityTicker, type ActivityTickerTurn, useActivityTicker } from \"./use-activity-ticker\";\nimport { useConversationActivity } from \"./use-conversation-activity\";\nimport { useConversationLiveUpdates } from \"./use-conversation-live-updates\";\nimport { CONVERSATION_MESSAGE_PAGE_SIZE, useConversationMessagePages } from \"./use-conversation-message-pages\";\nimport { findTurnsInFlight, isTurnInitiatorMessage } from \"./turn-initiators\";\nimport { RunningBackgroundJobsContext, type RunningBackgroundJobsContextValue } from \"../trace/running-background-jobs-context\";\nimport { QueuedMessageChip } from \"../trace/QueuedMessageChip\";\nimport { useConversationScrollJump } from \"./use-conversation-scroll-jump\";\nimport { useConversationSignals } from \"./use-conversation-signals\";\nimport {\n CanvasViabilityContext,\n ElementWidthCanvasViability,\n} from \"../../widgets/CanvasLauncherWidget/use-canvas-viable\";\n\n/** What the host's activity components get: the turn's state and the paced lines of the activity ticker. */\nexport interface AgentChatActivityProps {\n /** A turn is in flight (derived from the messages and the run status). */\n active: boolean;\n /** The chat shows an error card. */\n failed: boolean;\n activityTicker: ActivityTicker;\n /** The agent works on a task: a turn is in flight or the ticker still shows its lines. */\n isAgentWorkingOnTask: boolean;\n /** The key of the agent space the chat is open on. */\n agentSpaceKey: number;\n /** The chat's resolved activity timing (`activityTiming`, the environment's, the package's), for the component's motion. */\n activityTiming?: ResolvedAgentChatActivityTiming;\n /** The chat's store, for a component that reads more of the chat's state (`useAgentsChatSelector`). */\n chatStore: AgentsChatStore;\n /**\n * The newest widget-carrying assistant message the owner has not answered yet (no later owner message, no later\n * widget click) — null when there is none ({@link findUnansweredWidgetMessageId}). Whether that widget waits for an\n * answer is the widget class's `AWAITS_OWNER_INPUT` on the server; the wire does not carry it, so a host that tells\n * questions from other widgets checks the widget names of that message itself.\n */\n unansweredWidgetMessageId: string | number | null;\n}\n\n/** What the host's avatar beside an assistant message gets (`AssistantAvatar`). */\nexport interface AgentChatAssistantAvatarProps {\n message: ChatMessage;\n}\n\n/** What the host's activity history under a message gets: the finished turn that message started, if any. */\nexport interface AgentChatActivityHistoryProps {\n turn: ActivityTickerTurn | null;\n}\n\n/** What the host's trace of one turn gets (`TurnTrace`): the message that started the turn and where the turn stands. */\nexport interface AgentChatTurnTraceProps {\n conversationId: number;\n /** The message that may have started a turn: the owner's message or a signal that owes work. */\n turnMessageId: number | string;\n /** live = the turn this message started runs right now; done = it ended (or the message started none). */\n phase: \"live\" | \"done\";\n /** The chat is the compact side panel: the trace takes its narrow form. */\n isCompact: boolean;\n}\n\n/** What a host does with the composer of a mounted chat (`AgentChat`'s `composerRef`). */\nexport interface AgentChatComposerHandle {\n /**\n * Replaces the composer's draft with `text` (empty clears it) and puts the caret at its end — never sends. Does\n * nothing while the composer is not shown (a closed conversation).\n */\n setComposerDraft: (text: string) => void;\n /** Focuses the composer, the caret at the end of its draft (e.g. after files were dropped on the chat). */\n focusComposer?: () => void;\n}\n\n/** Where the model of the next send comes from — read at send time (an admin's pick can change between renders). */\nexport interface AgentChatSendModelSource {\n readModelForNextSend: () => string | undefined;\n}\n\nexport interface AgentChatControllerProps {\n /** The state handle of this chat instance (created and released by the app). */\n chatStore: AgentsChatStore;\n /** The conversation client this chat reads and sends through. */\n client: AgentsConversationClient;\n /** The key of the agent space new conversations start in. */\n agentSpaceKey: number;\n /** When set, load + resume this existing conversation. Absent = empty chat, lazy-starts on first send. */\n conversationId?: number;\n onNewConversation?: (conversationId: number) => void;\n /** The conversation could not be loaded (missing, deleted, not readable): the host drops to the empty chat. */\n onConversationNotFound?: () => void;\n /** Switch the active conversation — the ConversationSearchResults widget's open-arrow target. */\n onOpenConversation?: (conversationId: number, messageId?: number) => void;\n /** Switch this chat to another conversation of the same agent space in place (a widget linking to related work). */\n onSwitchConversation?: (conversationId: number) => void;\n /** Text inserted into the composer once on mount — never sent automatically. */\n initialComposerPrompt?: string;\n /** A request to scroll a message into view and flash it; re-applied whenever its `nonce` changes. */\n scrollTarget?: ChatScrollTarget;\n /** Each finished turn's activity lines stay in the thread above its answer (rendered by `ActivityHistory`). */\n keepActivityHistoryAfterAnswer?: boolean;\n /**\n * The timing of the activity reads and of the working indicator's lines (the 3 s read window, the line paces, the\n * success beat). Each field the chat leaves out comes from `AgentsEnvironment.chatActivityTiming`, else the package's\n * value. A host whose realtime push writes `activityUpdatedAt` when the narrator finishes lowers the read window, so a\n * narrated line shows at once.\n */\n activityTiming?: AgentChatActivityTiming;\n /** The host shows one conversation the owner may not leave: no starting ideas (the agent speaks first). */\n isPinnedToSingleConversation?: boolean;\n /** App extension of the widget context: the chat is the app's guided first-run setup. */\n isOnboardingSetupConversation?: boolean;\n /** The model of the next send; without it the conversation's own model drives. */\n sendModelSource?: AgentChatSendModelSource;\n /** Called after a send that carried attachments, so the host clears them from the composer. */\n onAttachmentsSent?: () => void;\n /**\n * Called once for every send the chat accepted (typed, a widget's send, the opening request's message), with the\n * text as sent, right when it goes out — e.g. for a host's send animation. A refused send (a closed conversation, a\n * start still in flight) reports nothing.\n */\n onMessageSent?: (messageText: string) => void;\n /**\n * Called after an accepted send that carried composer widgets (the widget context's and `hostComposerWidgets`), with\n * those widgets — the host clears the ones it owns.\n */\n onComposerWidgetsSent?: (composerWidgets: ConversationComposerWidget[]) => void;\n /** Widget callback: put media-library files into the composer (a file library canvas's \"Use in chat\"). */\n attachLibraryFilesToComposer?: (libraryFiles: ComposerLibraryFile[]) => void;\n /** The empty state of a new chat: a synthetic first assistant message (client state only), as markdown. */\n startingIdeasMarkdown?: string;\n /** While true the chat follows the bottom; a rising edge jumps to the newest message (a voice chat). */\n followBottom?: boolean;\n /** The chat's scroll container (the host may own it, e.g. for a scroll-linked background). */\n chatScrollRef: RefObject<HTMLDivElement | null>;\n isCompact?: boolean;\n confineTopBlurBandToChatPane?: boolean;\n /** Class names of the two wrappers around the conversation view (the host's layout). */\n chatAreaClassName?: string;\n chatWrapClassName?: string;\n /** Further props of the chat area element (e.g. a host's file drop zone handlers). */\n chatAreaProps?: Omit<HTMLAttributes<HTMLDivElement>, \"className\" | \"ref\">;\n /** Slots of the conversation view. */\n progressStepperSlot?: ReactNode;\n /** The host's layer while files are dragged over the window (see `ConversationViewBody`'s `fileDropHintSlot`). */\n fileDropHintSlot?: ReactNode;\n inputActionsSlot?: ReactNode;\n inputActionsSlotStart?: ReactNode;\n inputTopSlot?: ReactNode;\n inputSendDisabled?: boolean;\n inputReplacementSlot?: ReactNode;\n inputBandSlot?: ReactNode;\n inputPlaceholder?: string;\n inputSendReplacementWhenEmpty?: ReactNode;\n inputGlowUnderlay?: ReactNode;\n isContentOverlayShown?: boolean;\n isQuestionPinSuspended?: boolean;\n /** The attachments that ride along on the next send. */\n outgoingAttachments?: ConversationAttachmentReference[];\n /** Composer widgets the host holds outside the widget context, sent with the next send (see `ConversationMessageInput`). */\n hostComposerWidgets?: ConversationComposerWidget[];\n /**\n * The agent's activity at the tail of the thread (the agent avatar slot). Always mounted, also between turns: it is\n * the resting avatar under the last message while `active` and `isAgentWorkingOnTask` are false, and the working one\n * during a turn — one instance, never remounted by a turn's start or end.\n */\n ThinkingIndicator: ComponentType<AgentChatActivityProps>;\n /** Shown left of each assistant message, at its top (an avatar face, 24–28 px). Undefined: no avatar. */\n AssistantAvatar?: ComponentType<AgentChatAssistantAvatarProps>;\n /** A layer over the message column (a voice chat's focus mode); shown while `isContentOverlayShown`. */\n ContentOverlay?: ComponentType<AgentChatActivityProps>;\n /** The kept activity lines under the message that started a turn (with `keepActivityHistoryAfterAnswer`). */\n ActivityHistory?: ComponentType<AgentChatActivityHistoryProps>;\n /**\n * The trace of a turn (its step rows), between the message that started the turn and the answer. Mounted once after\n * every message that can start a turn (the owner's messages and the signals that owe work), for turns read from the\n * history as for turns watched live; the component reads the turn's trace by `turnMessageId` and renders nothing for\n * a message that started none. When given it stands in place of `ActivityHistory`. Default: none.\n */\n TurnTrace?: ComponentType<AgentChatTurnTraceProps>;\n /**\n * Marks the owner's messages sent while a turn runs as queued (`QueuedMessageChip` under the message) until the turn\n * ends: the agent reads them after its current step. Default false.\n */\n showsQueuedMessages?: boolean;\n /**\n * When what was written in the thread (`MessageTimesMode`): `turns` = day separators, a time head after a pause,\n * \"finished HH:MM\" under a long turn's answer, the exact time on hover / focus / tap; `everyMessage` adds a quiet time\n * under every message (e.g. the host's verbose view). Default: none.\n */\n messageTimes?: MessageTimesMode | null;\n /** Rendered inside the chat's widget provider (the host's canvas syncs). */\n children?: ReactNode;\n /**\n * The chat renders without the canvas split: no side pane, the message column alone. Default false. Without a canvas\n * surface of the host's own (`hostHasCanvasSurface`), every canvas open is then ignored.\n */\n disableSplitView?: boolean;\n /**\n * Whether a canvas may open in this chat: false ignores every open request (reason `noSurface`), true lets the canvas\n * state open while the host draws it (with `disableSplitView`: in a surface of its own, e.g. `CanvasPane`). Default:\n * true with the split view, false without it.\n */\n hostHasCanvasSurface?: boolean;\n /**\n * The host paints the chat's background behind it (the pane stays transparent, the frosted top band of a floating\n * top bar keeps its look). Default true; false gives the chat the package's own background\n * (`--agents-chat-background`).\n */\n backgroundPaintedByHost?: boolean;\n /** The handle of the composer: put a draft into the mounted chat without a remount (`setComposerDraft`). */\n composerRef?: Ref<AgentChatComposerHandle>;\n}\n\n/** Returns true when the messages contain an ERROR message whose signalSource is AI_BUDGET_REACHED. */\nconst hasBudgetReachedError = (messages: ChatMessage[] | null): boolean =>\n (messages ?? []).some((message) => message.messageType === \"ERROR\" && message.signalSource === \"AI_BUDGET_REACHED\");\n\n/** Every port function rejects with `AgentsClientError`; anything else (a bug) reads as an `other` refusal. */\nconst toAgentsClientErrorOfPort = (failure: unknown): AgentsClientError =>\n isAgentsClientError(failure) ? failure : new AgentsClientError(\"other\");\n\nconst selectMessages = (state: AgentsChatState) => state.messages;\nconst selectError = (state: AgentsChatState) => state.error;\nconst selectRateLimitRetryAfterSeconds = (state: AgentsChatState) => state.rateLimitRetryAfterSeconds;\nconst selectConversation = (state: AgentsChatState) => state.conversation;\nconst selectStartingNewConversation = (state: AgentsChatState) => state.startingNewConversation;\nconst selectCanvas = (state: AgentsChatState) => state.canvas;\nconst selectHasMoreOlder = (state: AgentsChatState) => state.hasMoreOlder;\nconst selectOpeningRequest = (state: AgentsChatState) => state.openingRequest;\n\n/**\n * The agent chat: the controller over the conversation client port and the chat store — open, pages,\n * live updates, sends, signals, the error card and retry, the opening request, the deep-linked widget, the scroll jump\n * and the activity — rendering the conversation view with the host's slots. The drive is async: a reply never comes\n * in the start/post answer, it arrives through the live updates.\n */\nexport const AgentChatController = (props: AgentChatControllerProps) => {\n const {\n chatStore,\n client,\n agentSpaceKey,\n conversationId,\n onNewConversation,\n onConversationNotFound,\n onOpenConversation,\n onSwitchConversation,\n initialComposerPrompt,\n scrollTarget,\n keepActivityHistoryAfterAnswer = false,\n activityTiming,\n isPinnedToSingleConversation = false,\n isOnboardingSetupConversation = false,\n sendModelSource,\n onAttachmentsSent,\n onMessageSent,\n onComposerWidgetsSent,\n attachLibraryFilesToComposer,\n startingIdeasMarkdown,\n followBottom = false,\n chatScrollRef,\n isCompact = false,\n confineTopBlurBandToChatPane = false,\n chatAreaClassName,\n chatWrapClassName,\n chatAreaProps,\n progressStepperSlot,\n fileDropHintSlot,\n inputActionsSlot,\n inputActionsSlotStart,\n inputTopSlot,\n inputSendDisabled,\n inputReplacementSlot,\n inputBandSlot,\n inputPlaceholder,\n inputSendReplacementWhenEmpty,\n inputGlowUnderlay,\n isContentOverlayShown,\n isQuestionPinSuspended,\n outgoingAttachments,\n hostComposerWidgets,\n ThinkingIndicator,\n AssistantAvatar,\n ContentOverlay,\n ActivityHistory,\n TurnTrace,\n showsQueuedMessages = false,\n messageTimes = null,\n children,\n disableSplitView = false,\n hostHasCanvasSurface = !disableSplitView,\n backgroundPaintedByHost = true,\n composerRef,\n } = props;\n\n // The canvas split fits by the width of this chat's own area, not the viewport's (a narrow chat column in a wide\n // window covers the chat with the canvas instead of squeezing a split into it).\n const [canvasViability] = useState(() => new ElementWidthCanvasViability());\n\n // The composer's handle: the initial prompt and a widget's `prefillComposer` put text into it without sending.\n const conversationMessageInputApiRef = useRef<ConversationMessageInputHandle>(null);\n useImperativeHandle(\n composerRef,\n () => ({\n setComposerDraft: (text: string) => conversationMessageInputApiRef.current?.insertTextIntoInput(text),\n focusComposer: () => conversationMessageInputApiRef.current?.focusInput?.(),\n }),\n [],\n );\n useEffect(() => {\n if (!initialComposerPrompt) return;\n conversationMessageInputApiRef.current?.insertTextIntoInput(initialComposerPrompt);\n // Mount-only: a one-shot initial value, not a live prop to keep re-applying.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const messages = useAgentsChatSelector(chatStore, selectMessages);\n const error = useAgentsChatSelector(chatStore, selectError);\n const rateLimitRetryAfterSeconds = useAgentsChatSelector(chatStore, selectRateLimitRetryAfterSeconds);\n const conversation = useAgentsChatSelector(chatStore, selectConversation);\n const startingNewConversation = useAgentsChatSelector(chatStore, selectStartingNewConversation);\n const canvas = useAgentsChatSelector(chatStore, selectCanvas);\n const hasMoreOlder = useAgentsChatSelector(chatStore, selectHasMoreOlder);\n const openingRequest = useAgentsChatSelector(chatStore, selectOpeningRequest);\n const pendingStartUserMessage = openingRequest.userMessage;\n const pendingStartSignalText = openingRequest.startSignalText;\n const pendingStartEntryPointKey = openingRequest.entryPointKey;\n const pendingDeepLinkedWidgetName = openingRequest.deepLinkedWidgetName;\n\n // A terminal runState: the run is over, the server rejects further owner input (the closed bar replaces the input).\n const isConversationRunEnded = conversation?.runState === \"COMPLETED\" || conversation?.runState === \"CANCELLED\";\n\n // The message reads (newest page, changed tail, older page, metadata) over the client, written into the store.\n const messagePages = useConversationMessagePages(chatStore, client, CONVERSATION_MESSAGE_PAGE_SIZE);\n const { readConversationMetadata, fetchOpeningPage, loadOlder, loadingOlder } = messagePages;\n\n // Load an existing conversation: the metadata (no messages, non-destructive) apart from the newest page (merged,\n // never clears — no skeleton flash). A refused metadata read drops the host to the empty chat.\n useEffect(() => {\n if (!conversationId) {\n // Empty chat: reset so a stale conversation can't linger; the first owner message lazy-starts a new one.\n chatStore.dispatch({ type: \"reset\" });\n return;\n }\n if (String(conversation?.id) === String(conversationId)) return;\n chatStore.dispatch({ type: \"reset\" });\n void readConversationMetadata(conversationId).then((wasRead) => {\n if (!wasRead) onConversationNotFound?.();\n });\n fetchOpeningPage(conversationId);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [conversationId]);\n\n // Reset the chat state on unmount so reopening the chat starts clean.\n useEffect(() => {\n return () => {\n chatStore.dispatch({ type: \"reset\" });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const liveConversationId = conversation?.id ?? conversationId;\n\n // The deep-linked widget hand-over (the opening request's `deepLinkedWidgetName`): mounted ONCE per hand-over under\n // a fresh mount key, released once the canvas it declares (`opensCanvases`) is open — never just \"some canvas\" — or\n // after 15 s for a widget that opens none. A cold chat that remounts meanwhile keeps the request.\n const [deepLinkedWidget, setDeepLinkedWidget] = useState<{ name: string; mountKey: number } | undefined>(undefined);\n const mountedHandOverRef = useRef<string | null>(null);\n useEffect(() => {\n if (!pendingDeepLinkedWidgetName) {\n mountedHandOverRef.current = null;\n return;\n }\n if (mountedHandOverRef.current === pendingDeepLinkedWidgetName) return;\n mountedHandOverRef.current = pendingDeepLinkedWidgetName;\n setDeepLinkedWidget((previous) => ({ name: pendingDeepLinkedWidgetName, mountKey: (previous?.mountKey ?? 0) + 1 }));\n }, [pendingDeepLinkedWidgetName]);\n const handedOverOpensCanvas =\n canvas !== null &&\n (resolveDeepLinkableWidget(pendingDeepLinkedWidgetName)?.opensCanvases?.includes(canvas.canvasId) ?? false);\n useEffect(() => {\n if (!pendingDeepLinkedWidgetName) return;\n const releaseHandOver = () =>\n chatStore.dispatch({ type: \"openingRequestSet\", openingRequest: { deepLinkedWidgetName: null } });\n if (handedOverOpensCanvas) {\n releaseHandOver();\n return;\n }\n const release = window.setTimeout(releaseHandOver, 15000);\n return () => window.clearTimeout(release);\n }, [pendingDeepLinkedWidgetName, handedOverOpensCanvas, chatStore]);\n\n const hasMoreOlderRef = useRef(hasMoreOlder);\n hasMoreOlderRef.current = hasMoreOlder;\n const messagesRef = useRef(messages);\n messagesRef.current = messages;\n // Scroll-up pagination: reads the store, so its identity changes only with the conversation (the sentinel's\n // IntersectionObserver is not torn down on every message change).\n const loadOlderOfLiveConversation = useCallback(() => loadOlder(liveConversationId), [loadOlder, liveConversationId]);\n\n // The title lands asynchronously after the first turn: re-read the metadata only (the messages stay as they are).\n const refetchConversationSummary = useCallback(() => {\n if (!liveConversationId) return;\n void readConversationMetadata(liveConversationId);\n }, [readConversationMetadata, liveConversationId]);\n\n // Live updates: the package rules over the client's subscription; the binding owns the transport.\n const { runStatus, liveReadCount, readChangedTailNow } = useConversationLiveUpdates({\n client,\n chatStore,\n messagePages,\n conversationId: liveConversationId,\n });\n\n // What the agent is doing right now, one generated line per step, paced by the ticker.\n const { chatActivityTiming: environmentActivityTiming } = useAgentsEnvironment();\n const resolvedActivityTiming = useMemo(\n () => resolveAgentChatActivityTiming(activityTiming, environmentActivityTiming),\n [activityTiming, environmentActivityTiming],\n );\n const {\n elements: activityElements,\n running: activityRunning,\n turnMessageId: activityTurnMessageId,\n runningBackgroundJobs,\n refresh: refreshActivity,\n } = useConversationActivity({\n conversationId: liveConversationId ?? 0,\n runStatus,\n // Every live read also asks for the activity lines; the hook throttles to one request per read window (3 s default).\n signalVersion: liveReadCount,\n enabled: Boolean(liveConversationId),\n activityRequestWindowMs: resolvedActivityTiming.activityRequestWindowMs,\n runningFloorMs: resolvedActivityTiming.runningFloorMs,\n });\n const activityTicker = useActivityTicker({\n elements: activityElements,\n running: activityRunning,\n turnMessageId: activityTurnMessageId,\n failed: !!error,\n keepActivityHistoryAfterAnswer,\n linePaceMs: resolvedActivityTiming.linePaceMs,\n backlogLinePaceMs: resolvedActivityTiming.backlogLinePaceMs,\n successBeatMs: resolvedActivityTiming.successBeatMs,\n });\n\n // The run status → the error card only (aiThinking follows the derived activity below). messages is a dependency:\n // the ERROR message with signalSource=AI_BUDGET_REACHED lands slightly after the status flips to \"failed\".\n useEffect(() => {\n if (runStatus === \"failed\") {\n chatStore.dispatch({\n type: \"errorSet\",\n error: hasBudgetReachedError(messages) ? ConversationErrorType.AI_BUDGET : ConversationErrorType.AGENT_ERROR,\n });\n } else if (runStatus === \"running\") {\n chatStore.dispatch({ type: \"errorSet\", error: null });\n }\n }, [runStatus, chatStore, messages]);\n\n // Retry of a FAILED run: re-drives the stored, unanswered owner message; accepted → the card goes.\n const handleRetryFailedRun = useCallback(async () => {\n const retryConversationId = conversationId ?? conversation?.id;\n if (!retryConversationId) {\n return;\n }\n await client.retryConversation(retryConversationId);\n chatStore.dispatch({ type: \"errorSet\", error: null });\n }, [conversationId, conversation?.id, client, chatStore]);\n\n // Bumped whenever the chat must jump to the newest content: a widget click that injects a signal, the closed refusal.\n const [scrollToBottomNonce, setScrollToBottomNonce] = useState(0);\n\n // While the host asks to follow the bottom (a voice chat), a question pinned by an earlier send must not keep the\n // new lines below the fold.\n useEffect(() => {\n if (followBottom) setScrollToBottomNonce((nonce) => nonce + 1);\n }, [followBottom]);\n\n /** The closed refusal on the error card, without any request — and the jump, so the card is in view. */\n const rejectAsConversationClosed = useCallback(() => {\n chatStore.dispatch({ type: \"errorSet\", error: ConversationErrorType.CONVERSATION_CLOSED });\n setScrollToBottomNonce((nonce) => nonce + 1);\n }, [chatStore]);\n\n const handleSendMessage = useCallback<SendMessageHandler>(\n (message, { startSignalText, attachments, composerWidgets, entryPointKey }) => {\n // A closed conversation takes no further input — the typed input and every widget send.\n if (isConversationRunEnded) {\n rejectAsConversationClosed();\n return false;\n }\n // The canvas model's SEND boundary: a turn canvas ends, a pinned one stays.\n chatStore.dispatch({ type: \"canvasResetForNewTurn\" });\n const model = sendModelSource?.readModelForNextSend();\n // The optimistic bubble shows the text the server stores (attachments as the binding writes them).\n const sentMessageText = client.composeSentMessageText\n ? client.composeSentMessageText(message, attachments)\n : message;\n // Reported for an accepted send only. Only a send that carried attachments clears them: a widget send and the cold-start greeting carry none and\n // must never wipe what the owner is still composing.\n const reportAcceptedSend = () => {\n if (attachments?.length) onAttachmentsSent?.();\n if (composerWidgets?.length) onComposerWidgetsSent?.(composerWidgets);\n onMessageSent?.(message);\n };\n if (conversation?.id) {\n const postConversationId = conversation.id;\n chatStore.dispatch({ type: \"messagePostRequested\", message: { message: sentMessageText, role: \"USER\" } });\n client\n .postMessage(postConversationId, { text: message, model, attachments })\n .then((posted) =>\n chatStore.dispatch({ type: \"messagePostReceived\", conversationId: postConversationId, posted }),\n )\n .catch((failure: unknown) =>\n chatStore.dispatch({ type: \"messagePostFailed\", error: toAgentsClientErrorOfPort(failure) }),\n );\n reportAcceptedSend();\n return true;\n }\n // No conversation yet — lazy start; `startSignalText` rides along as the invisible start context.\n if (startingNewConversation) return false;\n // The store hands out the start's token (it outlives a remount): its answer applies only while it is pending.\n chatStore.dispatch({ type: \"startRequested\", message: { message: sentMessageText, role: \"USER\" } });\n const startToken = chatStore.getState().pendingStartToken as number;\n client\n .startConversation({ agentSpaceKey, text: message, startSignalText, entryPointKey, model, attachments })\n .then((started) => {\n const isAnswerOfPendingStart = chatStore.getState().pendingStartToken === startToken;\n chatStore.dispatch({ type: \"startReceived\", startToken, started });\n if (!isAnswerOfPendingStart) return;\n // A start that reopened its entry point's recent conversation brings no messages: read its newest page.\n if (started.reopenedExisting) {\n fetchOpeningPage(started.conversation.id);\n }\n onNewConversation?.(started.conversation.id);\n })\n .catch((failure: unknown) => {\n chatStore.dispatch({ type: \"startFailed\", error: toAgentsClientErrorOfPort(failure) });\n });\n reportAcceptedSend();\n return true;\n },\n [\n conversation,\n startingNewConversation,\n chatStore,\n client,\n agentSpaceKey,\n sendModelSource,\n onAttachmentsSent,\n onComposerWidgetsSent,\n onMessageSent,\n isConversationRunEnded,\n rejectAsConversationClosed,\n fetchOpeningPage,\n onNewConversation,\n ],\n );\n\n // The opening request's message or start signal (an entry point outside the chat): posted as the first owner\n // message of a cold chat — keyed on the request, not on mount (the chat may already be open), never into an existing\n // conversation and never while a start is in flight. The send is read through a ref so it can't re-fire.\n const handleSendMessageRef = useRef(handleSendMessage);\n handleSendMessageRef.current = handleSendMessage;\n const sentStartRequestRef = useRef<PendingStartRequest | null>(null);\n const loadedConversationId = conversation?.id;\n useEffect(() => {\n const pendingStartRequest = pickPendingStartRequest(pendingStartUserMessage, pendingStartSignalText);\n if (!pendingStartRequest) {\n // Nothing pending — re-arm, so the SAME entry point can be clicked again.\n sentStartRequestRef.current = null;\n return;\n }\n const isReadyToSend = isChatReadyToSendPendingStartRequest({\n pendingStartRequest,\n activeConversationId: conversationId,\n loadedConversationId,\n startingNewConversation,\n alreadySentStartRequest: sentStartRequestRef.current,\n });\n if (!isReadyToSend) {\n return;\n }\n sentStartRequestRef.current = pendingStartRequest;\n // All cleared: a losing signal left behind would make the host drop the conversation this start just opened.\n chatStore.dispatch({\n type: \"openingRequestSet\",\n openingRequest: { userMessage: null, startSignalText: null, entryPointKey: null },\n });\n const entryPointKey = pendingStartEntryPointKey ?? undefined;\n if (pendingStartRequest.kind === \"signal\") {\n handleSendMessageRef.current(\"\", { startSignalText: pendingStartRequest.text, entryPointKey });\n } else {\n handleSendMessageRef.current(pendingStartRequest.text, { entryPointKey });\n }\n }, [\n pendingStartUserMessage,\n pendingStartSignalText,\n pendingStartEntryPointKey,\n conversationId,\n loadedConversationId,\n startingNewConversation,\n chatStore,\n ]);\n\n // The signals besides the owner's messages: a widget's signal, a parked context-only signal, the corrective signal\n // for a dropped widget block, the widget render report (one collector per conversation).\n const { handleInjectSignal, renderReportCollector } = useConversationSignals({\n client,\n conversationId,\n conversation,\n messages,\n runStatus,\n startingNewConversation,\n isConversationRunEnded,\n handleSendMessage,\n rejectAsConversationClosed,\n refetchConversationSummary,\n setScrollToBottomNonce,\n });\n\n // Scroll-to-message and keeping the activity ticker in view; owns the bottom-follow refs of the view body.\n const { followBottomRef, scrollJumpActiveRef } = useConversationScrollJump({\n scrollTarget,\n conversationId,\n conversation,\n messages,\n messagesRef,\n hasMoreOlderRef,\n loadOlder: loadOlderOfLiveConversation,\n chatScrollRef,\n activityTicker,\n });\n\n const widgetCallbacks = useMemo(\n () => ({\n // Message-only for widgets; resolves true only once the send was accepted (a widget locks on it).\n sendMessageToChat: (message: string) => Promise.resolve(handleSendMessage(message, {}) === true),\n injectSignal: handleInjectSignal,\n prefillComposer: (text: string) => conversationMessageInputApiRef.current?.insertTextIntoInput(text),\n attachLibraryFilesToComposer,\n chatAgentSpaceKey: agentSpaceKey,\n conversationId: liveConversationId,\n onOpenConversation,\n onSwitchConversation,\n isOnboardingSetupConversation,\n }),\n [\n handleSendMessage,\n handleInjectSignal,\n attachLibraryFilesToComposer,\n agentSpaceKey,\n liveConversationId,\n onOpenConversation,\n onSwitchConversation,\n isOnboardingSetupConversation,\n ],\n );\n\n // \"What is the agent doing right now\" — from the live messages and the run status.\n const agentActivity = useMemo(() => deriveAgentActivity(messages, runStatus), [messages, runStatus]);\n\n // The store's aiThinking (the launcher reads it) follows the activity the open chat shows.\n useEffect(() => {\n chatStore.dispatch({ type: \"aiThinkingSet\", aiThinking: agentActivity.active });\n }, [agentActivity.active, chatStore]);\n const isTurnRunning = agentActivity.active || runStatus === \"running\";\n useEffect(() => (isTurnRunning ? reportRunningTurn() : undefined), [isTurnRunning]);\n\n // Changes ONLY when a new message arrives (the merge re-allocates the list with identical content) — the clock of\n // the safety poll below.\n const latestMessageSignature = useMemo(() => {\n const list = messages ?? [];\n const last = list[list.length - 1];\n return `${list.length}:${last?.id ?? \"\"}`;\n }, [messages]);\n\n // The safety poll: one read after a full minute without a new message while a turn is in flight — the floor for a\n // dead live path, never the live path itself.\n useEffect(() => {\n if (!liveConversationId || !agentActivity.active) return;\n const intervalId = setInterval(readChangedTailNow, 60_000);\n return () => clearInterval(intervalId);\n }, [liveConversationId, agentActivity.active, readChangedTailNow, latestMessageSignature]);\n\n // A conversation of a scheduled run: its first owner message is the task's seed, shown collapsed — only when the\n // history is loaded down to its start.\n const isScheduleRunConversation = conversation?.initiatorType === \"SCHEDULE\";\n const taskInstructionMessageId = useMemo(() => {\n if (!isScheduleRunConversation || hasMoreOlder || !messages?.length) return undefined;\n return messages.find((message) => message.role === \"USER\")?.id ?? undefined;\n }, [isScheduleRunConversation, hasMoreOlder, messages]);\n\n // With keepActivityHistoryAfterAnswer, each finished turn's lines stand under the message that started the turn.\n const activityHistoryByTurnMessageId = useMemo(() => {\n const historyTurnsByTurnMessageId = new Map<number, ActivityTickerTurn>();\n activityTicker.historyTurns.forEach((historyTurn) => {\n if (historyTurn.turnMessageId !== null) historyTurnsByTurnMessageId.set(historyTurn.turnMessageId, historyTurn);\n });\n return historyTurnsByTurnMessageId;\n }, [activityTicker.historyTurns]);\n\n // The starting ideas: not on a host pinned to one conversation, not beside an open canvas.\n const showsStartingIdeas =\n startingIdeasMarkdown !== undefined &&\n !conversationId &&\n !messages?.length &&\n !isPinnedToSingleConversation &&\n canvas === null;\n const chatMessages = useMemo(() => {\n if (!showsStartingIdeas) return messages;\n const startingIdeasMessage: ChatMessage = { id: -1, role: \"ASSISTANT\", message: startingIdeasMarkdown, fresh: true };\n return [startingIdeasMessage];\n }, [showsStartingIdeas, startingIdeasMarkdown, messages]);\n\n // The turn in flight and the owner's messages queued behind it (the trace's phase, the queued chips).\n // The activity read's turn counts only while that read says its turn runs: after the turn ended it still names the\n // old turn until the next one is known, and the owner's next message would read as queued behind it.\n const namedLiveTurnMessageId = activityRunning ? (activityTurnMessageId ?? null) : null;\n const turnsInFlight = useMemo(\n () => findTurnsInFlight(messages, isTurnRunning, namedLiveTurnMessageId),\n [messages, isTurnRunning, namedLiveTurnMessageId],\n );\n const hasTurnTraceSlot = TurnTrace !== undefined && liveConversationId !== undefined;\n\n // The background jobs of the conversation stand under the trace of the newest turn of the thread, with a Stop each.\n const backgroundJobsAnchorTurnMessageId = useMemo(() => {\n const threadMessages = messages ?? [];\n for (let position = threadMessages.length - 1; position >= 0; position -= 1) {\n const message = threadMessages[position];\n if (message.id != null && isTurnInitiatorMessage(message) && !turnsInFlight.queuedMessages.includes(message)) return message.id;\n }\n return null;\n }, [messages, turnsInFlight]);\n const { stopBackgroundJob: stopBackgroundJobOfClient } = client;\n const runningBackgroundJobsContextValue = useMemo<RunningBackgroundJobsContextValue | null>(() => {\n if (liveConversationId === undefined) return null;\n return {\n conversationId: liveConversationId,\n anchorTurnMessageId: backgroundJobsAnchorTurnMessageId,\n backgroundJobs: runningBackgroundJobs,\n stopBackgroundJob: stopBackgroundJobOfClient\n ? (backgroundJobId: number) => stopBackgroundJobOfClient(liveConversationId, backgroundJobId)\n : undefined,\n refresh: refreshActivity,\n };\n }, [liveConversationId, backgroundJobsAnchorTurnMessageId, runningBackgroundJobs, stopBackgroundJobOfClient, refreshActivity]);\n const showsKeptActivityHistory = keepActivityHistoryAfterAnswer && ActivityHistory !== undefined && TurnTrace === undefined;\n\n // What stands right after a message: the trace of the turn it started (or the kept activity lines of a host without\n // a trace), and the queued mark of an owner message the running turn has not read yet.\n const renderAfterMessage = useCallback(\n (message: ChatMessage) => {\n // A message queued behind the running turn has started no turn yet: no trace, and the queued mark when asked for.\n const isQueued = turnsInFlight.queuedMessages.includes(message);\n const turnTrace =\n TurnTrace && liveConversationId !== undefined && message.id != null && !isQueued && isTurnInitiatorMessage(message) ? (\n <TurnTrace\n conversationId={liveConversationId}\n turnMessageId={message.id}\n phase={message.id === turnsInFlight.liveTurnMessageId ? \"live\" : \"done\"}\n isCompact={isCompact}\n />\n ) : null;\n const activityHistory =\n showsKeptActivityHistory && ActivityHistory ? (\n <ActivityHistory\n turn={typeof message.id === \"number\" ? (activityHistoryByTurnMessageId.get(message.id) ?? null) : null}\n />\n ) : null;\n if (!isQueued) return turnTrace ?? activityHistory;\n return showsQueuedMessages ? <QueuedMessageChip isCompact={isCompact} /> : null;\n },\n [\n ActivityHistory,\n TurnTrace,\n activityHistoryByTurnMessageId,\n isCompact,\n liveConversationId,\n showsKeptActivityHistory,\n showsQueuedMessages,\n turnsInFlight,\n ],\n );\n const rendersAfterMessages = hasTurnTraceSlot || showsKeptActivityHistory || showsQueuedMessages;\n\n const unansweredWidgetMessageId = useMemo(() => findUnansweredWidgetMessageId(messages ?? []), [messages]);\n const renderAssistantAvatar = useCallback(\n (message: ChatMessage) => (AssistantAvatar ? <AssistantAvatar message={message} /> : null),\n [AssistantAvatar],\n );\n\n const activityProps: AgentChatActivityProps = {\n active: agentActivity.active,\n failed: !!error,\n activityTicker,\n isAgentWorkingOnTask: agentActivity.active || activityTicker.phase === \"live\",\n agentSpaceKey,\n activityTiming: resolvedActivityTiming,\n chatStore,\n unansweredWidgetMessageId,\n };\n\n return (\n <RunningBackgroundJobsContext.Provider value={runningBackgroundJobsContextValue}>\n <CanvasViabilityContext.Provider value={canvasViability}>\n <WidgetRenderReportCollectorContext.Provider value={renderReportCollector}>\n <ConversationWidgetProvider\n callbacks={widgetCallbacks}\n chatStore={chatStore}\n hostHasCanvasSurface={hostHasCanvasSurface}\n >\n {/* The tool a page handed over: renders nothing in the chat itself — such a widget lives in the canvas. */}\n <ConversationDeepLinkedWidget\n key={deepLinkedWidget?.mountKey ?? 0}\n widgetName={deepLinkedWidget?.name}\n agentSpaceKey={agentSpaceKey}\n />\n {/* The canvas that was open in this conversation comes back once ITS messages are in. */}\n <CanvasRestoreOnMount conversationId={liveConversationId} messages={messages} />\n {children}\n <div {...chatAreaProps} className={chatAreaClassName} ref={canvasViability.observe}>\n <div className={chatWrapClassName}>\n <ConversationView\n enableCanvasToggle\n boxCanvasBelowTopBar\n disableSplitView={disableSplitView}\n confineTopBlurBandToChatPane={confineTopBlurBandToChatPane}\n progressStepperSlot={progressStepperSlot}\n fileDropHintSlot={fileDropHintSlot}\n enablePinQuestionAndRevealAnswer\n isQuestionPinSuspended={isQuestionPinSuspended}\n scrollRef={chatScrollRef}\n scrollToBottomNonce={scrollToBottomNonce}\n followBottomRef={followBottomRef}\n scrollJumpActiveRef={scrollJumpActiveRef}\n // The host paints the background at its own root; this pane keeps the transparent custom-background mode.\n backgroundPaintedByHost={backgroundPaintedByHost}\n currentCategory={undefined}\n aiPromptExtension={undefined}\n suggestions={undefined}\n messages={chatMessages}\n aiThinking={agentActivity.active}\n // The input never locks while the agent works: a message posted mid-turn is answered in the next turn.\n allowSendWhileAiThinking\n thinkingIndicator={<ThinkingIndicator {...activityProps} />}\n // Only with something to stand there: otherwise every row would carry an empty slot.\n renderAfterMessage={rendersAfterMessages ? renderAfterMessage : undefined}\n renderAssistantAvatar={AssistantAvatar ? renderAssistantAvatar : undefined}\n hideAssistantMeta\n userMessageTheme=\"dark\"\n error={error}\n rateLimitRetryAfterSeconds={rateLimitRetryAfterSeconds}\n onRetryFailedRun={handleRetryFailedRun}\n isDebugMode={false}\n categoriesLoaded={true}\n conversationId={conversationId ?? conversation?.id ?? undefined}\n startingNewConversation={startingNewConversation}\n showMessagesWithoutConversation\n hasMoreOlder={hasMoreOlder}\n loadingOlder={loadingOlder}\n onLoadOlder={loadOlderOfLiveConversation}\n autoScroll={!!conversationId || (messages?.length ?? 0) > 0}\n isCompact={isCompact}\n inputActionsSlot={inputActionsSlot}\n inputActionsSlotStart={inputActionsSlotStart}\n inputTopSlot={inputTopSlot}\n inputSendDisabled={inputSendDisabled}\n inputReplacementSlot={inputReplacementSlot}\n inputBandSlot={inputBandSlot}\n inputPlaceholder={inputPlaceholder}\n inputSendReplacementWhenEmpty={inputSendReplacementWhenEmpty}\n inputGlowUnderlay={inputGlowUnderlay}\n contentOverlaySlot={ContentOverlay ? <ContentOverlay {...activityProps} /> : undefined}\n isContentOverlayShown={isContentOverlayShown}\n outgoingAttachmentImages={outgoingAttachments}\n hostComposerWidgets={hostComposerWidgets}\n taskInstructionMessageId={taskInstructionMessageId}\n isConversationClosed={isConversationRunEnded}\n messageTimes={messageTimes}\n conversationMessageInputApiRef={conversationMessageInputApiRef}\n onSuggestionClick={() => {}}\n onSendMessage={handleSendMessage}\n />\n </div>\n </div>\n </ConversationWidgetProvider>\n </WidgetRenderReportCollectorContext.Provider>\n </CanvasViabilityContext.Provider>\n </RunningBackgroundJobsContext.Provider>\n );\n};\n","import { type ComponentType, type RefObject, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport {\n AgentsConversationClientProvider,\n useOptionalAgentsConversationClient,\n} from \"../../client/AgentsConversationClientContext\";\nimport type { PollingConversationChangeSubscriptionOptions } from \"../../client/polling/createPollingConversationChangeSubscription\";\nimport { withPollingChangeSubscription } from \"../../client/polling/withPollingChangeSubscription\";\nimport { useAgentsActiveAgentSpaceKey } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport { AgentChatActivityHistory } from \"../AgentChatActivityHistory/AgentChatActivityHistory\";\nimport { AgentChatActivityIndicator } from \"../AgentChatActivityIndicator/AgentChatActivityIndicator\";\nimport { ConversationClosedBar } from \"../ConversationClosedBar/ConversationClosedBar\";\nimport {\n type AgentChatActivityHistoryProps,\n type AgentChatActivityProps,\n AgentChatController,\n type AgentChatControllerProps,\n} from \"../controller/AgentChatController\";\nimport type { AgentsChatState } from \"../store/agents-chat-state\";\nimport { type AgentsChatStore, createAgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { useAgentsChatSelector } from \"../store/use-agents-chat-store\";\nimport styles from \"./AgentChat.module.scss\";\n\n/** The controller's inputs that `AgentChat` fills itself when the app leaves them out. */\ntype DefaultedControllerProps = \"chatStore\" | \"client\" | \"agentSpaceKey\" | \"chatScrollRef\" | \"ThinkingIndicator\";\n\nexport interface AgentChatProps extends Omit<AgentChatControllerProps, DefaultedControllerProps> {\n /** This chat instance's state handle. Default: a store of its own, created on mount and dropped on unmount. */\n chatStore?: AgentsChatStore;\n /**\n * The conversation client. Default: the one `AgentsProvider` (or `AgentsConversationClientProvider`) mounted. A client\n * without `subscribeToConversationChanges` gets the polling default (`withPollingChangeSubscription`).\n */\n client?: AgentsConversationClient;\n /**\n * The intervals of the polling default, for a client without a subscription of its own. Read once per client (when\n * the chat wraps it); ignored for a client that brings its own subscription.\n */\n pollingOptions?: PollingConversationChangeSubscriptionOptions;\n /** The key of the agent space new conversations start in. Default: `AgentsEnvironment.useActiveAgentSpaceKey()`, else 0 (no agent space). */\n agentSpaceKey?: number;\n /** The scroll container of the message list, when the app needs it (a scroll-linked background). Default: internal. */\n chatScrollRef?: RefObject<HTMLDivElement | null>;\n /** The agent's activity at the tail of the thread. Default: `AgentChatActivityIndicator` (dots and the ticker line). */\n ThinkingIndicator?: ComponentType<AgentChatActivityProps>;\n /**\n * The frosted band at the top of the message column that blurs what scrolls under a top bar floating over the chat.\n * Shown, it follows the chat pane (`confineTopBlurBandToChatPane` defaults to true then). Default false: the default\n * chat has no floating top bar.\n */\n showsTopBlurBand?: boolean;\n}\n\nconst selectConversation = (state: AgentsChatState) => state.conversation;\n\n/**\n * The agent chat with the package defaults (`./chat`): `<AgentsProvider client={client}><AgentChat\n * /></AgentsProvider>` is a working chat — message list, composer, activity indicator, error card with retry, canvas\n * pane, quick replies, older pages on scroll-up, the closed bar, live updates over the client's own subscription or,\n * without one, the polling default. Every slot and input of `AgentChatController` can still\n * be passed; what is left out gets its default here. Without `conversationId` the chat starts empty, lazy-starts a\n * conversation on the first send and then follows that conversation by itself (`onNewConversation` reports it).\n */\nexport const AgentChat = (props: AgentChatProps) => {\n const {\n chatStore: appChatStore,\n client: appClient,\n pollingOptions,\n agentSpaceKey: appAgentSpaceKey,\n chatScrollRef: appChatScrollRef,\n ThinkingIndicator = AgentChatActivityIndicator,\n ActivityHistory = AgentChatActivityHistory,\n conversationId: appConversationId,\n onNewConversation,\n inputReplacementSlot,\n chatAreaClassName,\n chatWrapClassName = styles.chatWrap,\n showsTopBlurBand = false,\n confineTopBlurBandToChatPane = showsTopBlurBand,\n ...controllerProps\n } = props;\n\n const mountedClient = useOptionalAgentsConversationClient();\n const givenClient = appClient ?? mountedClient;\n // Live updates for a client without push: the polling default, one wrapper per given client. A client with its\n // own subscription is passed through unchanged.\n const client = useMemo(\n () => (givenClient === null ? null : withPollingChangeSubscription(givenClient, pollingOptions)),\n // The options are read once per client: an inline object must not re-create the subscription on every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [givenClient],\n );\n const [ownChatStore] = useState(createAgentsChatStore);\n const chatStore = appChatStore ?? ownChatStore;\n const environmentAgentSpaceKey = useAgentsActiveAgentSpaceKey();\n const agentSpaceKey = appAgentSpaceKey ?? environmentAgentSpaceKey ?? 0;\n const ownChatScrollRef = useRef<HTMLDivElement | null>(null);\n const chatScrollRef = appChatScrollRef ?? ownChatScrollRef;\n\n // The conversation a lazy start opened, followed until the app names another one.\n const [startedConversationId, setStartedConversationId] = useState<number | undefined>(undefined);\n useEffect(() => {\n setStartedConversationId(undefined);\n }, [appConversationId]);\n const conversationId = appConversationId ?? startedConversationId;\n const handleNewConversation = useCallback(\n (newConversationId: number) => {\n setStartedConversationId(newConversationId);\n onNewConversation?.(newConversationId);\n },\n [onNewConversation],\n );\n\n // A terminal run state: the server takes no further input, the closed bar stands in the composer's place.\n const conversation = useAgentsChatSelector(chatStore, selectConversation);\n const isConversationRunEnded = conversation?.runState === \"COMPLETED\" || conversation?.runState === \"CANCELLED\";\n\n if (client === null) {\n throw new Error(\"AgentChat has no conversation client: pass `client`, or mount it in <AgentsProvider client={…}>.\");\n }\n // The chat's client (with its live updates) reaches every hook below — the package's and the host's slots\n // (`useAgentsConversationClient`), also when it came as the `client` prop and not from a provider.\n return (\n <AgentsConversationClientProvider client={client}>\n <AgentChatController\n {...controllerProps}\n confineTopBlurBandToChatPane={confineTopBlurBandToChatPane}\n chatStore={chatStore}\n client={client}\n agentSpaceKey={agentSpaceKey}\n conversationId={conversationId}\n onNewConversation={handleNewConversation}\n chatScrollRef={chatScrollRef}\n ThinkingIndicator={ThinkingIndicator}\n ActivityHistory={ActivityHistory}\n inputReplacementSlot={inputReplacementSlot ?? (isConversationRunEnded ? <ConversationClosedBar /> : undefined)}\n chatAreaClassName={\n chatAreaClassName ?? classNames(styles.chatArea, showsTopBlurBand ? styles.chatAreaWithTopBlurBand : undefined)\n }\n chatWrapClassName={chatWrapClassName}\n />\n </AgentsConversationClientProvider>\n );\n};\n\nexport type { AgentChatActivityHistoryProps, AgentChatActivityProps };\n","import type { ReactNode } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { formatTraceClock, readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport { readTraceStateLabel, TraceStateIcon, useTraceNow } from \"./trace-parts\";\nimport type { TraceStepState } from \"./trace-types\";\nimport styles from \"./trace-agents.module.scss\";\n\nexport type BackgroundTaskType = \"subAgent\" | \"schedule\" | \"command\" | \"call\";\n\nexport interface BackgroundTask {\n key: string;\n type: BackgroundTaskType;\n /** What runs (\"#2 Check the BARMER price list\", a command, a schedule's name); data, never translated. */\n title: string;\n /** A quiet second line (\"every Monday 08:00\", a working directory). */\n detail?: string | null;\n state: TraceStepState;\n /** When the task started (a server date-time); a running task's clock ticks from it. */\n startedAt?: string | null;\n /** How long a finished task ran. */\n durationMs?: number | null;\n /** The badge's words when the host names the type itself. */\n typeLabel?: string | null;\n /** The conversation of a sub-agent, for a host that opens it. */\n childConversationId?: number | null;\n}\n\nexport interface BackgroundTasksListProps {\n tasks: BackgroundTask[];\n /** The list's title. Default: \"Background tasks\". */\n title?: string | null;\n /** Opens a task (its conversation, its output); with it every row is a button. */\n onOpenTask?: (task: BackgroundTask) => void;\n /** Controls on the right of the head. */\n headerActions?: ReactNode;\n className?: string;\n}\n\nconst TYPE_LABELS: Readonly<Record<BackgroundTaskType, () => string>> = {\n subAgent: () => translateText(\"Sub-agent\"),\n // The noun; the bare key is the verb of a host's button.\n schedule: () => translateText(\"Schedule\", undefined, \"task-type\"),\n command: () => translateText(\"Command\"),\n call: () => translateText(\"Call\"),\n};\n\n/**\n * What a conversation has running beside its turn: sub-agents, schedules, shell commands in the background and calls,\n * one row each with its state, its duration (a clock while it runs) and a badge for its type.\n */\nexport const BackgroundTasksList = (props: BackgroundTasksListProps) => {\n const { tasks, title, onOpenTask, headerActions, className } = props;\n const format = useTraceFormat();\n const runningCount = tasks.filter((task) => task.state === \"running\").length;\n const now = useTraceNow(runningCount > 0);\n\n const describeTime = (task: BackgroundTask): string => {\n const startedAt = readTraceMoment(task.startedAt);\n if (task.state === \"running\" && startedAt !== null) return formatTraceClock(now - startedAt);\n if (task.durationMs != null) return format.duration(task.durationMs);\n return readTraceStateLabel(task.state);\n };\n\n return (\n <div className={classNames(styles.tasks, className)} data-testid=\"trace-background-tasks\">\n <div className={styles.tasksHead}>\n <span className={styles.tasksTitle}>{title || translateText(\"Background tasks\")}</span>\n {runningCount > 0 ? <span className={styles.quiet}>{translateText(\"%count% running\", { count: format.number(runningCount) })}</span> : null}\n {headerActions}\n </div>\n {tasks.length === 0 ? (\n <div className={styles.tasksEmpty}>{translateText(\"Nothing runs in the background.\")}</div>\n ) : (\n <ul className={styles.tasksList}>\n {tasks.map((task) => {\n const content = (\n <>\n <span className={styles.taskState}>\n <TraceStateIcon state={task.state} />\n </span>\n <span className={styles.taskTexts}>\n <span className={styles.taskTitle} title={task.title}>\n {task.title}\n </span>\n {task.detail ? (\n <span className={styles.taskDetail} title={task.detail}>\n {task.detail}\n </span>\n ) : null}\n </span>\n <span className={styles.weight}>{describeTime(task)}</span>\n <span className={styles.taskType}>{task.typeLabel || TYPE_LABELS[task.type]()}</span>\n </>\n );\n return (\n <li key={task.key} data-task-state={task.state} data-task-type={task.type}>\n {onOpenTask ? (\n <button type=\"button\" className={classNames(styles.task, styles.taskInteractive)} onClick={() => onOpenTask(task)}>\n {content}\n </button>\n ) : (\n <div className={styles.task}>{content}</div>\n )}\n </li>\n );\n })}\n </ul>\n )}\n </div>\n );\n};\n","import { type ReactNode, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { FileChangesSummary } from \"./FileChangesSummary\";\nimport { FileEditBlock, type FileEditBlockProps } from \"./FileEditBlock\";\nimport { readTraceFileChangeLetter, readTraceFileChangeWord, useTraceFormat } from \"./trace-format\";\nimport { Icon } from \"../../provider/components\";\nimport { TraceLink, TraceMountChip, TracePath } from \"./trace-parts\";\nimport type { TraceFileChange, TraceLinkComponent } from \"./trace-types\";\nimport styles from \"./trace-files.module.scss\";\n\nexport interface ChangedFilesPaneProps\n extends Pick<\n FileEditBlockProps,\n \"describeMount\" | \"maxLines\" | \"isNarrow\" | \"diffModesBelowHead\" | \"defaultDiffMode\" | \"onLoadFullDiff\" | \"onOpenInViewer\" | \"describeFileType\"\n > {\n /** The changed files, in the order they are listed. */\n fileChanges: TraceFileChange[];\n /**\n * Controls the selected file (its position in `fileChanges`); without it the pane keeps its own, starting at\n * `defaultSelectedIndex`.\n */\n selectedIndex?: number;\n onSelectedIndexChange?: (selectedIndex: number) => void;\n /** The file selected at first when the pane keeps the selection itself. Default 0. */\n defaultSelectedIndex?: number;\n /** A title before the summary in the pane's head (\"Turn 3\"). */\n title?: ReactNode;\n /** Controls on the right of the pane's head (a link to the drive). */\n headerActions?: ReactNode;\n /** A small picture of a changed file, for the preview card of a binary file. */\n renderThumbnail?: (fileChange: TraceFileChange) => ReactNode;\n /** Whether the viewer of `onOpenInViewer` can show this file; \"open\" is offered only then. Default: every file. */\n canOpenInViewer?: (fileChange: TraceFileChange) => boolean;\n /** The route of the screen that shows a changed file in the conversation's sandbox; each row and the file's block link to it. Null: no link. */\n buildSandboxHref?: (fileChange: TraceFileChange) => string | null;\n /** The host's link (an in-app route); a plain anchor otherwise. */\n linkComponent?: TraceLinkComponent;\n className?: string;\n}\n\nconst OPERATION_CLASS_NAMES: Readonly<Record<string, string | undefined>> = {\n ADDED: styles.operationAdded,\n MODIFIED: styles.operationModified,\n DELETED: styles.operationDeleted,\n RENAMED: styles.operationRenamed,\n};\n\n/**\n * The files a turn or a conversation changed: a list with the letter of each operation (A, M, D, R), the path, the\n * mount and the size of the change, and below it the file edit block of the selected file.\n */\nexport const ChangedFilesPane = (props: ChangedFilesPaneProps) => {\n const {\n fileChanges,\n selectedIndex,\n onSelectedIndexChange,\n defaultSelectedIndex = 0,\n title,\n headerActions,\n renderThumbnail,\n canOpenInViewer,\n buildSandboxHref,\n linkComponent,\n className,\n describeMount,\n onOpenInViewer,\n ...fileEditProps\n } = props;\n const format = useTraceFormat();\n const [ownSelectedIndex, setOwnSelectedIndex] = useState(defaultSelectedIndex);\n // A file changed twice is one file of the summary, as in the figures of a turn.\n const fileCount = new Set(fileChanges.map((fileChange) => `${fileChange.mountKind ?? \"\"}:${fileChange.mountName ?? \"\"}:${fileChange.path}`)).size;\n const shownSelectedIndex = Math.min(Math.max(selectedIndex ?? ownSelectedIndex, 0), Math.max(fileChanges.length - 1, 0));\n const selectedFileChange = fileChanges[shownSelectedIndex];\n const linesAdded = fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesAdded ?? 0), 0);\n const linesRemoved = fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesRemoved ?? 0), 0);\n\n const select = (index: number) => {\n setOwnSelectedIndex(index);\n onSelectedIndexChange?.(index);\n };\n const describeExtra = (fileChange: TraceFileChange): ReactNode => {\n if (fileChange.linesAdded != null || fileChange.linesRemoved != null) {\n return (\n <>\n <span className={styles.added}>+{format.number(fileChange.linesAdded ?? 0)}</span>{\" \"}\n <span className={styles.removed}>−{format.number(fileChange.linesRemoved ?? 0)}</span>\n </>\n );\n }\n if (fileChange.changeType === \"RENAMED\" && fileChange.previousPath) return `← ${fileChange.previousPath.split(\"/\").pop() ?? \"\"}`;\n if (fileChange.sizeAfter != null) return format.bytes(fileChange.sizeAfter);\n return null;\n };\n\n return (\n <div className={classNames(styles.pane, className)} data-testid=\"trace-changed-files\">\n <div className={styles.paneHead}>\n {title !== undefined && title !== null ? <span className={styles.paneTitle}>{title}</span> : null}\n <FileChangesSummary fileCount={fileCount} linesAdded={linesAdded} linesRemoved={linesRemoved} />\n <span className={styles.grow} />\n {headerActions}\n </div>\n {fileChanges.length === 0 ? (\n <div className={styles.paneEmpty}>{translateText(\"No files were changed.\")}</div>\n ) : (\n <ul className={styles.paneList}>\n {fileChanges.map((fileChange, index) => {\n const changeType = fileChange.changeType ?? \"MODIFIED\";\n const extra = describeExtra(fileChange);\n const sandboxHref = buildSandboxHref?.(fileChange) ?? null;\n return (\n <li key={`${fileChange.id ?? index}:${fileChange.path}`} className={sandboxHref !== null ? styles.paneFileRow : undefined}>\n <button\n type=\"button\"\n className={classNames(styles.paneFile, index === shownSelectedIndex && styles.paneFileOn)}\n aria-current={index === shownSelectedIndex ? \"true\" : undefined}\n onClick={() => select(index)}\n >\n <span\n className={classNames(styles.operation, styles.operationLetter, OPERATION_CLASS_NAMES[changeType])}\n title={readTraceFileChangeWord(changeType)}\n aria-label={readTraceFileChangeWord(changeType)}\n >\n {readTraceFileChangeLetter(changeType)}\n </span>\n <TracePath path={fileChange.path} isMonospaced isRemoved={changeType === \"DELETED\"} />\n <span className={styles.grow} />\n <TraceMountChip\n mountKind={fileChange.mountKind}\n mountName={fileChange.mountName}\n driveSpaceId={fileChange.driveSpaceId}\n describeMount={describeMount}\n />\n {extra !== null ? <span className={styles.paneFileExtra}>{extra}</span> : null}\n </button>\n {sandboxHref !== null ? (\n // Beside the row's button, never inside it: a link in a button is no valid markup.\n <TraceLink href={sandboxHref} linkComponent={linkComponent} className={styles.paneFileLink} title={translateText(\"Show this file in the sandbox\")}>\n <Icon name=\"terminal\" pixelSize={13} />\n </TraceLink>\n ) : null}\n </li>\n );\n })}\n </ul>\n )}\n {selectedFileChange ? (\n <div className={styles.paneDetail}>\n <FileEditBlock\n {...fileEditProps}\n fileChange={selectedFileChange}\n describeMount={describeMount}\n onOpenInViewer={(canOpenInViewer?.(selectedFileChange) ?? true) ? onOpenInViewer : undefined}\n sandboxHref={buildSandboxHref?.(selectedFileChange) ?? null}\n linkComponent={linkComponent}\n thumbnail={renderThumbnail?.(selectedFileChange)}\n />\n </div>\n ) : null}\n </div>\n );\n};\n","import { type ReactNode, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon, type AgentsIconName } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport stepStyles from \"./trace-steps.module.scss\";\nimport styles from \"./trace-agents.module.scss\";\n\nexport interface ChangeSetChange {\n /** A stable key; default: the row's position. */\n key?: string;\n /** The field's name, in the reader's language. */\n label: string;\n /** The value before; null or absent for a field that had none. */\n before?: string | null;\n /** The value after; null or absent for a field that was cleared. */\n after?: string | null;\n}\n\nexport interface ChangeSetCardProps {\n /** What was changed (\"Ride changed\"), in the reader's language. */\n title: string;\n icon?: AgentsIconName;\n /** The chip of the changed record (`EntityChip`). */\n entity?: ReactNode;\n changes: ChangeSetChange[];\n /** A quiet line under the rows (who changed it, when). */\n note?: ReactNode;\n /** Takes the change back; without it no Undo button. A promise keeps the button disabled until it settles. */\n onUndo?: () => void | Promise<void>;\n /** The change was taken back: the card says so and offers no Undo. */\n isUndone?: boolean;\n /** Further controls beside Undo (a link to the record's history). */\n actions?: ReactNode;\n className?: string;\n}\n\n/**\n * What a turn changed on one record: a row per field with the old value struck through and the new one highlighted,\n * and an Undo button when the host can take the change back.\n */\nexport const ChangeSetCard = (props: ChangeSetCardProps) => {\n const { title, icon = \"toolWrite\", entity, changes, note, onUndo, isUndone = false, actions, className } = props;\n const [isUndoPending, setIsUndoPending] = useState(false);\n const handleUndo = async () => {\n if (!onUndo) return;\n setIsUndoPending(true);\n try {\n await onUndo();\n } finally {\n setIsUndoPending(false);\n }\n };\n return (\n <div className={classNames(styles.changeSet, isUndone && styles.changeSetPending, className)} data-testid=\"trace-change-set\" data-undone={isUndone || undefined}>\n <div className={styles.changeSetHead}>\n <Icon name={icon} pixelSize={15} className={stepStyles.rowIcon} />\n <span className={styles.changeSetTitle}>{title}</span>\n {entity}\n <span className={styles.changeSetGrow} />\n {isUndone ? <span className={stepStyles.badge}>{translateText(\"Undone\")}</span> : null}\n </div>\n <dl className={styles.changes}>\n {changes.map((change, index) => {\n const hasBefore = change.before != null && change.before !== \"\";\n const hasAfter = change.after != null && change.after !== \"\";\n return (\n <div key={change.key ?? index} style={{ display: \"contents\" }} data-testid=\"trace-change\">\n <dt className={styles.changeName}>{change.label}</dt>\n <dd className={classNames(styles.changeValue, hasBefore ? styles.changeOld : styles.changeUnchanged)}>\n {hasBefore ? (\n <>\n <span className={stepStyles.visuallyHidden}>{translateText(\"Before:\")} </span>\n {change.before}\n </>\n ) : (\n \"—\"\n )}\n </dd>\n <dd className={classNames(styles.changeValue, styles.changeArrow)} aria-hidden>\n →\n </dd>\n <dd className={classNames(styles.changeValue, hasAfter ? styles.changeNew : styles.changeUnchanged)}>\n {hasAfter ? (\n <>\n <span className={stepStyles.visuallyHidden}>{translateText(\"After:\")} </span>\n {change.after}\n </>\n ) : (\n \"—\"\n )}\n </dd>\n </div>\n );\n })}\n </dl>\n {note || onUndo || actions ? (\n <div className={styles.changeSetFoot}>\n {note ? <span className={styles.changeSetNote}>{note}</span> : null}\n <span className={styles.changeSetGrow} />\n {actions}\n {onUndo && !isUndone ? (\n <button type=\"button\" className={stepStyles.stopButton} disabled={isUndoPending} onClick={() => void handleUndo()}>\n <Icon name=\"undo\" pixelSize={13} />\n {translateText(\"Undo\")}\n </button>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n};\n","import type { ReactNode } from \"react\";\nimport type { ConversationTraceRecordChangeOperation } from \"../../contract/conversation-trace\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport { ChangeSetCard } from \"./ChangeSetCard\";\nimport { EntityChip } from \"./EntityChip\";\nimport type { TraceChangedRecord } from \"./trace-collect\";\nimport { readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport { readTraceStateLabel, TraceLink } from \"./trace-parts\";\nimport type { TraceEntityDescription, TraceEntityReference, TraceLinkComponent } from \"./trace-types\";\nimport styles from \"./trace-pane.module.scss\";\n\nexport interface ChangedRecordsListProps {\n /** The tool calls that changed or deleted records, in the order they are listed (`collectTraceChangedRecords`). */\n records: TraceChangedRecord[];\n /** The list's title. Default: \"Records changed\". */\n title?: string | null;\n /** The chip of a record a call names; null leaves the reference out. Default: no chips. */\n describeEntity?: (reference: TraceEntityReference) => TraceEntityDescription | null;\n /** The route of a record, for a host that only links (`describeEntity` wins when it names an `href`). */\n buildEntityHref?: (argumentName: string, id: number) => string | null;\n /** The route of the call's step in the host's analysis view; null for none. With it a row offers \"Open in analysis\". */\n buildStepHref?: (record: TraceChangedRecord) => string | null;\n /** The host's link (an in-app route); a plain anchor otherwise. */\n linkComponent?: TraceLinkComponent;\n /** A quiet line under the list. */\n note?: ReactNode;\n /** A changed record in words (`Support directive 41`) for the before → after card; null keeps table and id. */\n describeRecord?: (tableName: string, recordId: number | null) => string | null;\n className?: string;\n}\n\n/** `validUntil` reads \"valid until\", `isActive` \"is active\": a stored column name in words. */\nexport const describeChangedFieldName = (fieldName: string): string =>\n fieldName\n .replace(/_/g, \" \")\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n .toLowerCase()\n .trim();\n\n/** `SupportDirectives` and 41 read \"Support directives 41\": a changed record without the host's words. */\nexport const describeChangedRecord = (tableName: string, recordId: number | null): string => {\n const words = describeChangedFieldName(tableName);\n const label = words.charAt(0).toUpperCase() + words.slice(1);\n return recordId === null ? label : `${label} ${recordId}`;\n};\n\nconst readRecordOperationLabel = (operation: ConversationTraceRecordChangeOperation): string => {\n if (operation === \"CREATED\") return translateText(\"created\", undefined, \"record-change\");\n if (operation === \"DELETED\") return translateText(\"deleted\", undefined, \"record-change\");\n return translateText(\"changed\", undefined, \"record-change\");\n};\n\n/**\n * The records a conversation changed, as far as its trace knows them: one row per tool call that changes or deletes\n * data, with the tool in words, when it ran, the chips of the records its arguments name and a link to its step. A\n * call that failed or still waits for the owner's approval is marked, since it changed nothing (yet). Under a call\n * the server captured writes for, its change set lists every record with each field before → after\n * ({@link ChangeSetCard}); a call stored before the capture shows the row only. No undo is offered.\n */\nexport const ChangedRecordsList = (props: ChangedRecordsListProps) => {\n const { records, title, describeEntity, buildEntityHref, buildStepHref, linkComponent, note, describeRecord, className } = props;\n const format = useTraceFormat();\n if (records.length === 0) return null;\n return (\n <div className={classNames(styles.records, className)} data-testid=\"trace-changed-records\">\n <div className={styles.head}>\n <span className={styles.title}>{title || translateText(\"Records changed\")}</span>\n <span className={styles.grow} />\n <span className={styles.quiet}>{format.number(records.length)}</span>\n </div>\n <ul className={styles.recordsList}>\n {records.map((record) => {\n const startedAt = readTraceMoment(record.startedAt);\n const words = record.toolNameInWords || record.toolName || translateText(\"Used a tool\");\n const stepHref = buildStepHref?.(record) ?? null;\n const chips = record.entityReferences\n .map((reference) => {\n const description = describeEntity?.(reference) ?? null;\n if (description === null) return null;\n return (\n <EntityChip\n key={`${reference.argumentName}:${reference.id}`}\n label={description.label}\n icon={description.icon}\n href={description.href}\n argumentName={reference.argumentName}\n id={reference.id}\n buildEntityHref={buildEntityHref}\n linkComponent={linkComponent}\n />\n );\n })\n .filter((chip) => chip !== null);\n const isQuiet = record.state === \"failed\" || record.state === \"waiting\" || record.state === \"cancelled\";\n return (\n <li\n key={record.key}\n className={classNames(styles.record, isQuiet && styles.recordQuiet)}\n data-record-effect={record.effect}\n data-record-state={record.state}\n >\n <div className={styles.recordHead}>\n <Icon name={record.effect === \"DELETE\" ? \"trash\" : \"toolWrite\"} pixelSize={14} className={styles.recordIcon} />\n <span className={styles.recordTitle} title={record.toolName ?? undefined}>\n {words}\n </span>\n {record.effect === \"DELETE\" ? (\n <span className={classNames(styles.mark, styles.markDelete)}>{translateText(\"deletes data\", undefined, \"tool-effect\")}</span>\n ) : null}\n {record.state === \"waiting\" ? (\n <span className={classNames(styles.mark, styles.markWarning)}>{translateText(\"waits for approval\")}</span>\n ) : null}\n {record.state === \"failed\" ? <span className={classNames(styles.mark, styles.markDanger)}>{readTraceStateLabel(\"failed\")}</span> : null}\n {record.state === \"running\" || record.state === \"cancelled\" ? <span className={styles.mark}>{readTraceStateLabel(record.state)}</span> : null}\n <span className={styles.grow} />\n {startedAt !== null ? <span className={styles.recordTime}>{format.time(startedAt)}</span> : null}\n </div>\n {record.line && record.line !== words ? <div className={styles.recordLine}>{record.line}</div> : null}\n {record.recordChanges.length > 0 || record.omittedRecordChangeCount > 0 ? (\n <div className={styles.recordChangeSets}>\n {record.recordChanges.map((recordChange, recordIndex) => (\n <ChangeSetCard\n key={`${recordChange.tableName}:${recordChange.recordId ?? `new-${recordIndex}`}`}\n title={describeRecord?.(recordChange.tableName, recordChange.recordId) ?? describeChangedRecord(recordChange.tableName, recordChange.recordId)}\n icon={recordChange.operation === \"DELETED\" ? \"trash\" : \"toolWrite\"}\n entity={\n <span\n className={classNames(\n styles.mark,\n recordChange.operation === \"CREATED\" && styles.markCreated,\n recordChange.operation === \"DELETED\" && styles.markDelete,\n )}\n >\n {readRecordOperationLabel(recordChange.operation)}\n </span>\n }\n changes={recordChange.fieldChanges.map((fieldChange) => ({\n key: fieldChange.fieldName,\n label: describeChangedFieldName(fieldChange.fieldName),\n before: fieldChange.before,\n after: fieldChange.after,\n }))}\n note={\n recordChange.omittedFieldCount > 0\n ? translateText(\"%count% more fields\", { count: format.number(recordChange.omittedFieldCount) })\n : undefined\n }\n />\n ))}\n {record.omittedRecordChangeCount > 0 ? (\n <span className={styles.recordLine}>\n {translateText(\"%count% more records\", { count: format.number(record.omittedRecordChangeCount) })}\n </span>\n ) : null}\n </div>\n ) : null}\n {chips.length > 0 || stepHref !== null ? (\n <div className={styles.recordFoot}>\n {chips}\n {stepHref !== null ? (\n <TraceLink href={stepHref} linkComponent={linkComponent} className={styles.recordLink} title={translateText(\"Open this step in the analysis\")}>\n <Icon name=\"external\" pixelSize={12} />\n {translateText(\"Open in analysis\")}\n </TraceLink>\n ) : null}\n </div>\n ) : null}\n </li>\n );\n })}\n </ul>\n {note ? <p className={styles.note}>{note}</p> : null}\n </div>\n );\n};\n","import { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { useTraceFormat } from \"./trace-format\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface ContextRingProps {\n /** The share of the context window in use, 0–100. */\n percent: number;\n /** Tokens in the context and the window's size, named in the label when given. */\n usedTokens?: number | null;\n contextWindowTokens?: number | null;\n /** The figure beside the ring (\"71 %\"). Default true. */\n showsPercent?: boolean;\n /** Edge length of the ring in px. Default 26. */\n size?: number;\n /** Opens what fills the context; with it the ring is a button. */\n onClick?: () => void;\n className?: string;\n}\n\n/**\n * How full the model's context window is, as a ring with its percentage. It names itself to assistive technology\n * (\"Context 71 % full\"), turns amber from 80 % and red from 95 %, and is a button when a click handler is given.\n */\nexport const ContextRing = (props: ContextRingProps) => {\n const { percent, usedTokens, contextWindowTokens, showsPercent = true, size = 26, onClick, className } = props;\n const format = useTraceFormat();\n const shownPercent = Math.round(Math.min(100, Math.max(0, Number.isFinite(percent) ? percent : 0)));\n const strokeWidth = Math.max(3, Math.round(size / 7));\n const radius = (size - strokeWidth) / 2;\n const circumference = 2 * Math.PI * radius;\n const label =\n usedTokens != null && contextWindowTokens != null\n ? translateText(\"Context %percent% % full (%used% of %total% tokens)\", {\n percent: shownPercent,\n used: format.count(usedTokens),\n total: format.count(contextWindowTokens),\n })\n : translateText(\"Context %percent% % full\", { percent: shownPercent });\n const content = (\n <>\n <svg className={styles.ringSvg} width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden>\n <circle className={styles.ringTrack} cx={size / 2} cy={size / 2} r={radius} strokeWidth={strokeWidth} />\n <circle\n className={classNames(styles.ringArc, shownPercent >= 95 ? styles.ringArcFull : shownPercent >= 80 && styles.ringArcHigh)}\n cx={size / 2}\n cy={size / 2}\n r={radius}\n strokeWidth={strokeWidth}\n strokeDasharray={`${(circumference * shownPercent) / 100} ${circumference}`}\n />\n </svg>\n {showsPercent ? <span aria-hidden>{shownPercent} %</span> : null}\n </>\n );\n if (onClick) {\n return (\n <button\n type=\"button\"\n className={classNames(styles.ring, styles.ringInteractive, className)}\n aria-label={label}\n title={label}\n onClick={onClick}\n data-testid=\"trace-context-ring\"\n >\n {content}\n </button>\n );\n }\n return (\n <span className={classNames(styles.ring, className)} role=\"img\" aria-label={label} title={label} data-testid=\"trace-context-ring\">\n {content}\n </span>\n );\n};\n","import type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { ConversationTraceLevel, ConversationTurnTrace, ConversationTurnTraces } from \"../../contract/conversation-trace\";\n\n/**\n * The loader of one conversation's turn trace: every turn trace a screen shows reads through it, so the turns on screen\n * share their requests. It holds the turns it read (by turn number), reads the newest window first, walks back one\n * window at a time while a wanted turn is older than what it holds, follows a running turn with reads of the changed\n * turns only, and reads again when the conversation changed. One request runs at a time; a failed read is tried again\n * at the next change, never in a loop, and never throws into the component that asked.\n */\n\n/** The part of the conversation client the loader reads through. */\nexport type ConversationTraceClient = Pick<AgentsConversationClient, \"getTurnTraces\">;\n\nexport interface ConversationTraceLoaderOptions {\n /** The level asked for; the server answers at most the level the reader is allowed. Default `STEPS`. */\n level?: ConversationTraceLevel;\n /** Turns of one read. Default 20 (the server's default window). */\n pageSize?: number;\n}\n\n/** What the loader holds of a conversation at one moment; a new object after every change. */\nexport interface ConversationTraceState {\n /** The turns read so far, oldest first; without gaps from the oldest one read to the newest. */\n turns: ConversationTurnTrace[];\n /** `idle` before the first read, `loading` while that read runs, `ready` after it, `failed` when it failed. */\n status: \"idle\" | \"loading\" | \"ready\" | \"failed\";\n /** The level the server answered; null before the first answer. */\n level: ConversationTraceLevel | null;\n /** A turn runs in the conversation, as the newest read saw it. */\n isRunLive: boolean;\n /** Turns older than the oldest one read exist, as the page read that holds the oldest turn said. */\n hasOlderTurns: boolean;\n /** Turns of the whole conversation, as the newest read counted them; null before the first answer. */\n totalTurnCount: number | null;\n}\n\nconst DEFAULT_PAGE_SIZE = 20;\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst EMPTY_STATE: ConversationTraceState = { turns: [], status: \"idle\", level: null, isRunLive: false, hasOlderTurns: false, totalTurnCount: null };\n\ntype TraceRead = { kind: \"newest\" } | { kind: \"follow\"; afterMessageIndex: number } | { kind: \"older\"; fromTurnNumber: number; limit: number };\n\nexport class ConversationTraceLoader {\n protected readonly level: ConversationTraceLevel;\n protected readonly pageSize: number;\n protected readonly turnsByNumber = new Map<number, ConversationTurnTrace>();\n protected readonly listeners = new Set<() => void>();\n /** The turns a component waits for, by the id of the message that started them, with how many wait. */\n protected readonly wantedTurnMessageIds = new Map<number, number>();\n /** The turns that run right now, with how many components follow each. */\n protected readonly liveTurnMessageIds = new Map<number, number>();\n /** Turns that ended since the last follow read: that read returns them whole once more. */\n protected readonly endedTurnMessageIds = new Set<number>();\n /** The revision at which a wanted turn newer than everything held was last looked for. */\n protected readonly lookedForAtRevision = new Map<number, number>();\n protected state: ConversationTraceState = EMPTY_STATE;\n protected newestMessageIndex: number | null = null;\n protected hasReadNewest = false;\n protected wantsNewest = false;\n protected needsFollowRead = false;\n protected isReading = false;\n protected isPumpScheduled = false;\n /** Counts what could have changed the trace: a changed conversation, a poll tick. A failed read waits for the next. */\n protected revision = 0;\n protected failedAtRevision: number | null = null;\n protected conversationRevision: string | number | null = null;\n protected followerCount = 0;\n protected pollTimer: ReturnType<typeof setInterval> | null = null;\n protected pollIntervalMs = DEFAULT_POLL_INTERVAL_MS;\n\n constructor(\n protected readonly client: ConversationTraceClient,\n protected readonly conversationId: number,\n options: ConversationTraceLoaderOptions = {},\n ) {\n this.level = options.level ?? \"STEPS\";\n this.pageSize = Math.max(1, options.pageSize ?? DEFAULT_PAGE_SIZE);\n }\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n getState = (): ConversationTraceState => this.state;\n\n /** The turn a message started, when it was read. */\n findTurn(turnMessageId: number): ConversationTurnTrace | null {\n for (const turn of this.turnsByNumber.values()) {\n if (turn.turnMessageId === turnMessageId) return turn;\n }\n return null;\n }\n\n /**\n * A component shows the turn of this message: the loader reads until it holds the turn or knows the message started\n * none. Returns the release (the component is gone).\n */\n requestTurn(turnMessageId: number): () => void {\n this.wantedTurnMessageIds.set(turnMessageId, (this.wantedTurnMessageIds.get(turnMessageId) ?? 0) + 1);\n this.schedulePump();\n return () => {\n const remaining = (this.wantedTurnMessageIds.get(turnMessageId) ?? 1) - 1;\n if (remaining > 0) this.wantedTurnMessageIds.set(turnMessageId, remaining);\n else {\n this.wantedTurnMessageIds.delete(turnMessageId);\n this.lookedForAtRevision.delete(turnMessageId);\n }\n };\n }\n\n /** A component shows the conversation's newest turns (a pane, a sub-agent's trace): the newest window is read. */\n requestNewestTurns(): void {\n this.wantsNewest = true;\n this.schedulePump();\n }\n\n /**\n * The turn of this message runs: the loader follows it with a read of the changed turns every `pollIntervalMs` until\n * the returned function is called (the turn ended), then reads it once more for its final figures.\n */\n followLiveTurn(turnMessageId: number, pollIntervalMs: number = DEFAULT_POLL_INTERVAL_MS): () => void {\n this.liveTurnMessageIds.set(turnMessageId, (this.liveTurnMessageIds.get(turnMessageId) ?? 0) + 1);\n const stopFollowing = this.followChanges(pollIntervalMs);\n return () => {\n const remaining = (this.liveTurnMessageIds.get(turnMessageId) ?? 1) - 1;\n if (remaining > 0) this.liveTurnMessageIds.set(turnMessageId, remaining);\n else {\n this.liveTurnMessageIds.delete(turnMessageId);\n this.endedTurnMessageIds.add(turnMessageId);\n }\n stopFollowing();\n };\n }\n\n /**\n * Reads the changed turns every `pollIntervalMs` until the returned function is called, then once more: for a\n * component that shows a conversation while it runs without naming a turn (a sub-agent's trace).\n */\n followChanges(pollIntervalMs: number = DEFAULT_POLL_INTERVAL_MS): () => void {\n this.followerCount += 1;\n this.pollIntervalMs = Math.max(250, pollIntervalMs);\n this.startPolling();\n this.noteChange();\n let isReleased = false;\n return () => {\n if (isReleased) return;\n isReleased = true;\n this.followerCount -= 1;\n if (this.followerCount <= 0) this.stopPolling();\n this.noteChange();\n };\n }\n\n /**\n * Tells the loader where the conversation stands (a value that changes with every new message, e.g. its message\n * count and newest id). A changed value makes the loader read the changed turns.\n */\n noteConversationRevision(conversationRevision: string | number): void {\n if (this.conversationRevision === conversationRevision) return;\n const isFirst = this.conversationRevision === null;\n this.conversationRevision = conversationRevision;\n // The first value only names where the conversation stood when its first read started.\n if (!isFirst) this.noteChange();\n }\n\n /** Reads the changed turns now (the stop of a turn was accepted, a diff was stored). */\n refresh(): void {\n this.noteChange();\n }\n\n /** Stops the loader's timer; the turns it holds stay readable. */\n dispose(): void {\n this.stopPolling();\n this.listeners.clear();\n }\n\n protected noteChange(): void {\n this.revision += 1;\n if (this.hasReadNewest) this.needsFollowRead = true;\n this.schedulePump();\n }\n\n protected startPolling(): void {\n this.stopPolling();\n this.pollTimer = setInterval(() => this.noteChange(), this.pollIntervalMs);\n }\n\n protected stopPolling(): void {\n if (this.pollTimer !== null) clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n\n /** Every request of one tick becomes one decision: the components of a thread mount together. */\n protected schedulePump(): void {\n if (this.isPumpScheduled) return;\n this.isPumpScheduled = true;\n queueMicrotask(() => {\n this.isPumpScheduled = false;\n this.pump();\n });\n }\n\n protected pump(): void {\n if (this.isReading) return;\n const read = this.chooseNextRead();\n if (read === null) return;\n this.isReading = true;\n if (!this.hasReadNewest) this.publish({ status: \"loading\" });\n const revisionAtStart = this.revision;\n void this.runRead(read)\n .then(\n (traces) => {\n this.failedAtRevision = null;\n this.acceptRead(read, traces);\n },\n () => {\n // The trace is an addition to the thread: a failed read shows nothing and waits for the next change.\n this.failedAtRevision = revisionAtStart;\n if (read.kind === \"follow\") this.needsFollowRead = false;\n if (!this.hasReadNewest) this.publish({ status: \"failed\" });\n },\n )\n .finally(() => {\n this.isReading = false;\n this.pump();\n });\n }\n\n protected runRead(read: TraceRead): Promise<ConversationTurnTraces> {\n const getTurnTraces = this.client.getTurnTraces;\n if (!getTurnTraces) return Promise.reject(new Error(\"The conversation client reads no turn traces.\"));\n if (read.kind === \"newest\") return getTurnTraces(this.conversationId, { level: this.level, limit: this.pageSize });\n if (read.kind === \"follow\") return getTurnTraces(this.conversationId, { level: this.level, afterMessageIndex: read.afterMessageIndex });\n return getTurnTraces(this.conversationId, { level: this.level, fromTurnNumber: read.fromTurnNumber, limit: read.limit });\n }\n\n /** The one read to run next, or null when the loader holds everything that is wanted. */\n protected chooseNextRead(): TraceRead | null {\n // A failed read is tried again only after something changed.\n if (this.failedAtRevision !== null && this.failedAtRevision === this.revision) return null;\n const hasWishes = this.wantedTurnMessageIds.size > 0 || this.wantsNewest || this.followerCount > 0;\n if (!this.hasReadNewest) return hasWishes ? { kind: \"newest\" } : null;\n\n const sortedTurns = this.state.turns;\n const initiatorIds = sortedTurns.map((turn) => turn.turnMessageId).filter((id): id is number => id !== null);\n const newestInitiatorId = initiatorIds.length > 0 ? initiatorIds[initiatorIds.length - 1] : null;\n const oldestInitiatorId = initiatorIds.length > 0 ? initiatorIds[0] : null;\n const oldestTurnNumber = sortedTurns.length > 0 ? sortedTurns[0].turnNumber : null;\n\n let smallestMissingOlderId: number | null = null;\n for (const turnMessageId of this.wantedTurnMessageIds.keys()) {\n if (this.findTurn(turnMessageId) !== null) continue;\n if (newestInitiatorId === null || turnMessageId > newestInitiatorId) {\n // Newer than everything held: its turn may have started since the last read. Looked for once per change.\n if (this.lookedForAtRevision.get(turnMessageId) !== this.revision) {\n this.lookedForAtRevision.set(turnMessageId, this.revision);\n this.needsFollowRead = true;\n }\n } else if (oldestInitiatorId !== null && turnMessageId < oldestInitiatorId && this.state.hasOlderTurns) {\n smallestMissingOlderId = smallestMissingOlderId === null ? turnMessageId : Math.min(smallestMissingOlderId, turnMessageId);\n }\n // A message between two held turns started none.\n }\n\n if (this.needsFollowRead) {\n const afterMessageIndex = this.readFollowPosition();\n return afterMessageIndex === null ? { kind: \"newest\" } : { kind: \"follow\", afterMessageIndex };\n }\n if (smallestMissingOlderId !== null && oldestTurnNumber !== null && oldestTurnNumber > 1) {\n const fromTurnNumber = Math.max(1, oldestTurnNumber - this.pageSize);\n return { kind: \"older\", fromTurnNumber, limit: oldestTurnNumber - fromTurnNumber };\n }\n return null;\n }\n\n /**\n * The position a follow read asks after: the newest row read, moved back before the first row of every turn that\n * runs or just ended, so those turns come back whole (a step's status changes without a new row).\n */\n protected readFollowPosition(): number | null {\n if (this.newestMessageIndex === null) return null;\n let position = this.newestMessageIndex;\n for (const turn of this.turnsByNumber.values()) {\n const isFollowed =\n turn.isRunning ||\n (turn.turnMessageId !== null && (this.liveTurnMessageIds.has(turn.turnMessageId) || this.endedTurnMessageIds.has(turn.turnMessageId)));\n if (isFollowed && turn.turnMessageIndex !== null) position = Math.min(position, turn.turnMessageIndex - 1);\n }\n return position;\n }\n\n /**\n * Whether turns older than the held ones exist after `traces` was read. Only a page read knows (the newest page, a\n * page of older turns), and only the page that reaches back at least as far as the oldest held turn decides; a\n * follow-up read is no page and leaves the fact as it is.\n */\n protected readHasOlderTurns(read: TraceRead, traces: ConversationTurnTraces): boolean {\n if (read.kind === \"follow\") return this.state.hasOlderTurns;\n const oldestHeldTurnNumber = this.state.turns.length > 0 ? this.state.turns[0].turnNumber : null;\n const firstTurnNumberOfPage = traces.firstTurnNumber ?? (traces.turns.length > 0 ? traces.turns[0].turnNumber : null);\n if (oldestHeldTurnNumber === null) return traces.hasOlderTurns;\n if (firstTurnNumberOfPage === null) return this.state.hasOlderTurns;\n return firstTurnNumberOfPage <= oldestHeldTurnNumber ? traces.hasOlderTurns : this.state.hasOlderTurns;\n }\n\n protected acceptRead(read: TraceRead, traces: ConversationTurnTraces): void {\n let hasChanged = !this.hasReadNewest;\n const hasOlderTurns = this.readHasOlderTurns(read, traces);\n const totalTurnCount = traces.totalTurnCount ?? this.state.totalTurnCount;\n if (read.kind !== \"older\") {\n this.hasReadNewest = true;\n this.needsFollowRead = false;\n this.endedTurnMessageIds.clear();\n if (traces.newestMessageIndex !== null) this.newestMessageIndex = traces.newestMessageIndex;\n }\n for (const turn of traces.turns) {\n const heldTurn = this.turnsByNumber.get(turn.turnNumber);\n // An unchanged turn keeps its object, so its rows do not render again.\n if (heldTurn !== undefined && JSON.stringify(heldTurn) === JSON.stringify(turn)) continue;\n this.turnsByNumber.set(turn.turnNumber, turn);\n hasChanged = true;\n }\n const isRunLive = read.kind === \"older\" ? this.state.isRunLive : traces.isRunLive;\n const level = traces.level;\n if (\n !hasChanged &&\n isRunLive === this.state.isRunLive &&\n level === this.state.level &&\n hasOlderTurns === this.state.hasOlderTurns &&\n totalTurnCount === this.state.totalTurnCount &&\n this.state.status === \"ready\"\n ) {\n return;\n }\n const turns = [...this.turnsByNumber.values()].sort((first, second) => first.turnNumber - second.turnNumber);\n this.publish({ turns, status: \"ready\", level, isRunLive, hasOlderTurns, totalTurnCount });\n }\n\n protected publish(change: Partial<ConversationTraceState>): void {\n this.state = { ...this.state, ...change };\n for (const listener of [...this.listeners]) listener();\n }\n}\n\nconst loadersByClient = new WeakMap<object, Map<string, ConversationTraceLoader>>();\n\n/**\n * The loader of a conversation's trace at one level: one per client, conversation and level, so every component that\n * shows a turn of that conversation shares its reads and what it holds.\n */\nexport const getConversationTraceLoader = (\n client: ConversationTraceClient,\n conversationId: number,\n options: ConversationTraceLoaderOptions = {},\n): ConversationTraceLoader => {\n let loaders = loadersByClient.get(client);\n if (loaders === undefined) {\n loaders = new Map();\n loadersByClient.set(client, loaders);\n }\n const key = `${conversationId}:${options.level ?? \"STEPS\"}:${options.pageSize ?? DEFAULT_PAGE_SIZE}`;\n let loader = loaders.get(key);\n if (loader === undefined) {\n loader = new ConversationTraceLoader(client, conversationId, options);\n loaders.set(key, loader);\n }\n return loader;\n};\n\n/** Drops the loaders of a client (a test, a sign-out): their timers stop and the next read starts over. */\nexport const releaseConversationTraceLoaders = (client: ConversationTraceClient): void => {\n const loaders = loadersByClient.get(client);\n if (loaders === undefined) return;\n for (const loader of loaders.values()) loader.dispose();\n loadersByClient.delete(client);\n};\n","import { useEffect, useMemo, useSyncExternalStore } from \"react\";\nimport type { ConversationTraceLevel, ConversationTurnTrace } from \"../../contract/conversation-trace\";\nimport type { AgentsChatState } from \"../store/agents-chat-state\";\nimport { useAgentsChatSelector, useOptionalAgentsChatStore } from \"../store/use-agents-chat-store\";\nimport { type ConversationTraceClient, type ConversationTraceState, getConversationTraceLoader } from \"./conversation-trace-loader\";\n\n// The hooks over the trace loader: one turn of a conversation, and the turns the loader holds of it.\n\n/** Where the shown conversation stands: its message count and its newest message id, as one value. */\nconst selectConversationRevision = (state: AgentsChatState): string => {\n const messages = state.messages ?? [];\n return `${messages.length}:${messages[messages.length - 1]?.id ?? \"\"}`;\n};\n\n/**\n * Where the conversation of the chat around this component stands, for the loader's reads after a change: the given\n * value, else the message count and newest message id of the chat's own store; null outside a chat.\n */\nexport const useConversationTraceRevision = (conversationRevision?: string | number | null): string | number | null => {\n const chatStore = useOptionalAgentsChatStore();\n const storeRevision = useAgentsChatSelector(chatStore, selectConversationRevision, \"\");\n if (conversationRevision !== undefined && conversationRevision !== null) return conversationRevision;\n return chatStore === null ? null : storeRevision;\n};\n\nexport interface UseConversationTurnTraceOptions {\n client: ConversationTraceClient;\n conversationId: number;\n /** The message that started the turn; null (an optimistic message without an id yet) reads nothing. */\n turnMessageId: number | null;\n level: ConversationTraceLevel;\n /** The turn runs: the loader follows it until this turns false. */\n isLive: boolean;\n pollIntervalMs?: number;\n /** A value that changes with every new message of the conversation; default: read from the chat's store. */\n conversationRevision?: string | number | null;\n}\n\nexport interface ConversationTurnTraceRead {\n /** The trace of the turn; null while it is not read, when the message started none, and after a failed read. */\n turn: ConversationTurnTrace | null;\n /** The loader's state of the conversation. */\n state: ConversationTraceState;\n /** Reads the changed turns now. */\n refresh: () => void;\n}\n\n/**\n * The trace of the turn one message started, read through the conversation's shared loader: every turn on screen\n * shares the loader's reads, a live turn is followed until it ends, and a change of the conversation reads again.\n */\nexport const useConversationTurnTrace = (options: UseConversationTurnTraceOptions): ConversationTurnTraceRead => {\n const { client, conversationId, turnMessageId, level, isLive, pollIntervalMs } = options;\n const loader = useMemo(() => getConversationTraceLoader(client, conversationId, { level }), [client, conversationId, level]);\n const state = useSyncExternalStore(loader.subscribe, loader.getState, loader.getState);\n const conversationRevision = useConversationTraceRevision(options.conversationRevision);\n\n useEffect(() => {\n if (conversationRevision !== null) loader.noteConversationRevision(conversationRevision);\n }, [loader, conversationRevision]);\n useEffect(() => (turnMessageId === null ? undefined : loader.requestTurn(turnMessageId)), [loader, turnMessageId]);\n useEffect(\n () => (turnMessageId === null || !isLive ? undefined : loader.followLiveTurn(turnMessageId, pollIntervalMs)),\n [loader, turnMessageId, isLive, pollIntervalMs],\n );\n\n // `state` is read so the turn is looked up again after every change the loader publishes.\n const turn = useMemo(() => (turnMessageId === null ? null : loader.findTurn(turnMessageId)), [loader, turnMessageId, state]);\n return { turn, state, refresh: () => loader.refresh() };\n};\n\nexport interface UseConversationTracesOptions {\n client: ConversationTraceClient;\n /** The conversation; null reads nothing. */\n conversationId: number | null;\n level: ConversationTraceLevel;\n /** Follows the conversation while a turn runs in it (a sub-agent's trace, which no chat follows). Default false. */\n followsWhileLive?: boolean;\n pollIntervalMs?: number;\n conversationRevision?: string | number | null;\n}\n\nconst NO_TRACE_STATE: ConversationTraceState = { turns: [], status: \"idle\", level: null, isRunLive: false, hasOlderTurns: false, totalTurnCount: null };\nconst subscribeToNothing = () => () => undefined;\nconst readNoTraceState = () => NO_TRACE_STATE;\n\n/**\n * The turns the conversation's shared loader holds, the newest window at least: for a pane beside the chat (its\n * changed files, its sub-agents) and for the trace of a sub-agent's conversation.\n */\nexport const useConversationTraces = (options: UseConversationTracesOptions): ConversationTraceState => {\n const { client, conversationId, level, followsWhileLive = false, pollIntervalMs } = options;\n const loader = useMemo(\n () => (conversationId === null ? null : getConversationTraceLoader(client, conversationId, { level })),\n [client, conversationId, level],\n );\n const state = useSyncExternalStore(loader?.subscribe ?? subscribeToNothing, loader?.getState ?? readNoTraceState, loader?.getState ?? readNoTraceState);\n const conversationRevision = useConversationTraceRevision(options.conversationRevision);\n\n useEffect(() => loader?.requestNewestTurns(), [loader]);\n useEffect(() => {\n if (loader !== null && conversationRevision !== null) loader.noteConversationRevision(conversationRevision);\n }, [loader, conversationRevision]);\n const isFollowing = followsWhileLive && state.isRunLive;\n useEffect(() => (loader !== null && isFollowing ? loader.followChanges(pollIntervalMs) : undefined), [loader, isFollowing, pollIntervalMs]);\n return state;\n};\n","import { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport type { ConversationTraceClient } from \"./conversation-trace-loader\";\nimport { selectVisibleTraceSteps, TraceStepRow } from \"./ToolStepGroup\";\nimport type { TraceHostBindings, TraceViewMode } from \"./trace-types\";\nimport { useConversationTraces } from \"./use-conversation-trace\";\nimport agentStyles from \"./trace-agents.module.scss\";\nimport stepStyles from \"./trace-steps.module.scss\";\n\nexport interface ConversationChildTraceProps {\n /** The conversation client; the server lets a reader of a conversation read the traces of its sub-agents. */\n client: ConversationTraceClient;\n /** The conversation of the sub-agent. */\n conversationId: number;\n /** `verbose` reads the debug level and shows tool names and details. Default `normal`. */\n viewMode?: TraceViewMode;\n host?: TraceHostBindings;\n isCompact?: boolean;\n pollIntervalMs?: number;\n}\n\n/**\n * The steps of a sub-agent's conversation, shown inside its open row: read when the row opens (through the shared\n * loader of that conversation), followed while the sub-agent runs. A failed read shows nothing.\n */\nexport const ConversationChildTrace = (props: ConversationChildTraceProps) => {\n const { client, conversationId, viewMode = \"normal\", host, isCompact = false, pollIntervalMs } = props;\n const state = useConversationTraces({\n client,\n conversationId,\n level: viewMode === \"verbose\" ? \"DEBUG\" : \"STEPS\",\n followsWhileLive: true,\n pollIntervalMs,\n });\n if (state.status === \"idle\" || state.status === \"loading\") {\n return <div className={agentStyles.quiet}>{translateText(\"Loading the steps…\")}</div>;\n }\n if (state.status === \"failed\") return null;\n const rows = state.turns.flatMap((turn) =>\n selectVisibleTraceSteps(turn.steps, viewMode === \"summary\" ? \"normal\" : viewMode).map((step) => ({ key: `${turn.turnNumber}:${step.key}`, step })),\n );\n // A run that has ended without a step to show (a job that only ran one tool) says so; a live one may still get some.\n if (rows.length === 0) {\n return <div className={agentStyles.quiet}>{state.isRunLive ? translateText(\"No steps so far.\") : translateText(\"This run recorded no steps.\")}</div>;\n }\n return (\n <div className={classNames(stepStyles.steps, isCompact && stepStyles.compact)} data-testid=\"trace-child-steps\">\n {rows.map((row) => (\n <TraceStepRow\n key={row.key}\n step={row.step}\n viewMode={viewMode === \"summary\" ? \"normal\" : viewMode}\n host={host}\n conversationId={conversationId}\n isCompact={isCompact}\n />\n ))}\n </div>\n );\n};\n","import { useState } from \"react\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetCallbacksContext\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport styles from \"./trace-steps.module.scss\";\n\n/** A tool call of the turn that waits for the owner's approval. */\nexport interface ConsentRequestCardCall {\n /** The tool in words (\"Create support directive\"); the tool's name when there are none. */\n title: string;\n /** What the call would do, as the step narrated it. */\n line?: string | null;\n}\n\nexport interface ConsentRequestCardProps {\n /** The conversation the turn belongs to: the card acts only inside the live chat of that conversation. */\n conversationId: number;\n /** The message that started the turn: once the owner wrote after it, the request is answered and the card goes. */\n turnMessageId: number;\n calls: ConsentRequestCardCall[];\n isCompact?: boolean;\n}\n\n/**\n * The card of a turn that ended on a tool call held for the owner's approval: what would run, and two buttons that\n * answer the agent's question in the owner's words, as an explicit yes to exactly the described step (the server's\n * consent check accepts nothing less) or a clear no. The agent reads the answer\n * like any reply; the call runs only after a yes. Outside the live chat (the analysis view) and once the owner wrote\n * after the turn, the card is not shown: the step's \"waits for approval\" badge tells the story there.\n */\nexport const ConsentRequestCard = (props: ConsentRequestCardProps) => {\n const { conversationId, turnMessageId, calls, isCompact = false } = props;\n const widgetContext = useConversationWidgetContext();\n const [sentAnswer, setSentAnswer] = useState<\"yes\" | \"no\" | null>(null);\n if (calls.length === 0 || widgetContext.conversationId !== conversationId) return null;\n const messages = widgetContext.messages ?? [];\n const turnPosition = messages.findIndex((message) => message.id === turnMessageId);\n const isAnswered = turnPosition >= 0 && messages.slice(turnPosition + 1).some((message) => message.role === \"USER\" && message.messageType !== \"SIGNAL\");\n if (isAnswered && sentAnswer === null) return null;\n\n const answer = (choice: \"yes\" | \"no\") => {\n if (sentAnswer !== null) return;\n setSentAnswer(choice);\n // The server's consent check takes only an explicit yes to exactly the step the agent described (checked live: this\n // wording in German passes, a bare \"yes, go ahead\" does not).\n void widgetContext.sendMessageToChat(\n choice === \"yes\"\n ? translateText(\"Yes, I explicitly approve this step, exactly as you described it.\")\n : translateText(\"No, please don't run this step.\"),\n );\n };\n const heading =\n calls.length === 1\n ? translateText(\"Approve: %action%?\", { action: calls[0].title })\n : translateText(\"Approve %count% actions?\", { count: calls.length });\n\n return (\n <div className={classNames(styles.consentCard, isCompact && styles.consentCardCompact)} data-testid=\"trace-consent-request\">\n <div className={styles.consentHead}>\n <Icon name=\"stepWaiting\" pixelSize={14} />\n <span className={styles.consentTitle}>{heading}</span>\n <span className={classNames(styles.badge, styles.badgeWarning)}>{translateText(\"waits for you\")}</span>\n </div>\n {calls.some((call) => call.line) ? (\n <ul className={styles.consentCalls}>\n {calls.map((call, position) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: the calls of one turn keep their order\n <li key={position}>{calls.length > 1 ? <b>{call.title}: </b> : null}{call.line}</li>\n ))}\n </ul>\n ) : null}\n <div className={styles.consentActions}>\n <button type=\"button\" className={styles.consentApprove} disabled={sentAnswer !== null} onClick={() => answer(\"yes\")}>\n {translateText(\"Approve\")}\n </button>\n <button type=\"button\" className={styles.consentDecline} disabled={sentAnswer !== null} onClick={() => answer(\"no\")}>\n {translateText(\"Don't run it\")}\n </button>\n <span className={styles.consentNote}>\n {sentAnswer === null ? translateText(\"Runs only after your approval.\") : translateText(\"Your answer was sent.\")}\n </span>\n </div>\n </div>\n );\n};\n","import { useState } from \"react\";\nimport type { ConversationBackgroundJob, ConversationBackgroundJobStop } from \"../../contract/conversation\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { formatTraceClock, readTraceMoment } from \"./trace-format\";\nimport { useTraceNow } from \"./trace-parts\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface RunningBackgroundJobLinesProps {\n /** The jobs whose end is not reported yet, oldest first; nothing is rendered without one. */\n backgroundJobs: ConversationBackgroundJob[];\n /** Stops one job; without it no Stop button. The lines read again through `onStopped` once the call settled. */\n onStop?: (backgroundJobId: number) => Promise<ConversationBackgroundJobStop>;\n /** Called after every stop call, accepted or not: the chat reads the activity again at once. */\n onStopped?: () => void;\n /** The chat is the compact side panel. */\n isCompact?: boolean;\n className?: string;\n}\n\n/** What a job's line says after its label: the clock of its run, or the time until a wake-up rings. */\nconst describeJobTime = (backgroundJob: ConversationBackgroundJob, now: number): string | null => {\n const dueAt = readTraceMoment(backgroundJob.dueAt);\n if (dueAt !== null && dueAt > now) {\n return translateText(\"rings in %time%\", { time: formatTraceClock(dueAt - now) });\n }\n const startedAt = readTraceMoment(backgroundJob.startedAt);\n return startedAt !== null ? formatTraceClock(now - startedAt) : null;\n};\n\n/**\n * The background jobs of the conversation that still run beside the turns (a command after the detach window, a\n * wake-up the agent set): one status line each, as the running turn's own line looks — a spinner, the job's label\n * and its clock (a wake-up: the time until it rings), the hint when the job waits for the host, and a Stop for that\n * job alone. A stopped job's end reaches the agent in its next turn; the turn's Stop stays the stop of everything.\n */\nexport const RunningBackgroundJobLines = (props: RunningBackgroundJobLinesProps) => {\n const { backgroundJobs, onStop, onStopped, isCompact = false, className } = props;\n const now = useTraceNow(backgroundJobs.length > 0);\n const [stoppingJobIds, setStoppingJobIds] = useState<readonly number[]>([]);\n if (backgroundJobs.length === 0) return null;\n\n const handleStop = async (backgroundJobId: number) => {\n if (!onStop) return;\n setStoppingJobIds((jobIds) => [...jobIds, backgroundJobId]);\n try {\n await onStop(backgroundJobId);\n } catch {\n // The stop was not accepted: the button is there again and the job runs on.\n } finally {\n setStoppingJobIds((jobIds) => jobIds.filter((jobId) => jobId !== backgroundJobId));\n onStopped?.();\n }\n };\n\n return (\n <div\n className={classNames(styles.turnTrace, isCompact && styles.turnTraceCompact, className)}\n role=\"group\"\n aria-label={translateText(\"Background jobs\")}\n data-testid=\"running-background-jobs\"\n >\n {backgroundJobs.map((backgroundJob) => {\n const isWaitingForHost = backgroundJob.liveStatus === \"WAITING_FOR_HOST\";\n const isStopping = stoppingJobIds.includes(backgroundJob.id);\n const jobTime = describeJobTime(backgroundJob, now);\n return (\n <div\n key={backgroundJob.id}\n className={styles.statusLine}\n data-testid=\"running-background-job\"\n data-background-job-id={backgroundJob.id}\n data-live-status={backgroundJob.liveStatus ?? undefined}\n >\n <span className={classNames(styles.spinner, isWaitingForHost && styles.spinnerWaiting)} aria-hidden />\n {/* the label gives way on a narrow screen, the job number and its clock stay whole (otherwise at 390 px the clock\n was cut off behind the label); the separator before them is drawn by the style, so it never\n opens a line when they wrap below the label */}\n <span className={styles.jobStatusText} title={backgroundJob.label}>\n <span className={styles.jobStatusParts}>\n <span className={classNames(styles.statusWord, styles.jobLabel)}>{backgroundJob.label || translateText(\"Background job\")}</span>\n {[translateText(\"Background job #%number%\", { number: backgroundJob.id }), isStopping ? translateText(\"Stopping…\") : jobTime]\n .filter((part): part is string => part !== null)\n .map((part) => (\n <span key={part === jobTime ? \"time\" : part} className={styles.jobMeta} data-testid=\"running-background-job-meta\">\n {part}\n </span>\n ))}\n </span>\n </span>\n {isWaitingForHost ? (\n <span className={classNames(styles.badge, styles.badgeWarning)} title={backgroundJob.liveNote ?? undefined} data-testid=\"background-job-waiting-for-host\">\n {translateText(\"waits for the host\")}\n </span>\n ) : null}\n <span className={styles.metaGrow} />\n {onStop ? (\n <button\n type=\"button\"\n className={styles.stopButton}\n disabled={isStopping}\n aria-label={translateText(\"Stop background job #%number%\", { number: backgroundJob.id })}\n onClick={() => void handleStop(backgroundJob.id)}\n >\n <span className={styles.stopSquare} aria-hidden />\n {translateText(\"Stop\")}\n </button>\n ) : null}\n </div>\n );\n })}\n </div>\n );\n};\n","import { type ReactNode, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { formatTraceClock, readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport { useTraceNow } from \"./trace-parts\";\nimport type { TraceViewMode } from \"./trace-types\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface RunStatusLineProps {\n /** When the turn started: a server date-time, an ISO date-time or a moment in ms. The clock ticks from it. */\n startedAt?: string | number | null;\n /** What the agent does right now, in words (\"reads the rides\"). Default: \"Working\". */\n statusText?: string | null;\n /** `verbose` adds the tokens and the cost. Default `normal`. */\n viewMode?: TraceViewMode;\n /** Tokens of the turn so far (verbose). */\n tokens?: number | null;\n /** Cost of the turn so far (verbose). */\n costInUsd?: number | null;\n formatCost?: (costInUsd: number) => string;\n /** Stops the turn; without it no Stop button. A promise keeps the button disabled until it settles. */\n onStop?: () => void | Promise<void>;\n /** The stop was asked for and the turn winds down: the line says so, the button is off. */\n isStopping?: boolean;\n /** Further content on the right of the line. */\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * The status line of a running turn: a spinner, \"Working · 0:42\" ticking from the turn's start, in the verbose view\n * the tokens and the cost so far, and a Stop button.\n */\nexport const RunStatusLine = (props: RunStatusLineProps) => {\n const { startedAt, statusText, viewMode = \"normal\", tokens, costInUsd, formatCost, onStop, isStopping = false, children, className } = props;\n const format = useTraceFormat();\n const now = useTraceNow(true);\n const [isStopPending, setIsStopPending] = useState(false);\n const startedAtMoment = typeof startedAt === \"number\" ? startedAt : readTraceMoment(startedAt);\n const showsStopping = isStopping || isStopPending;\n\n const figures = [\n startedAtMoment !== null ? formatTraceClock(now - startedAtMoment) : null,\n // before the first model call answers there is nothing to count: \"0 tokens · $0.00\" would read as a fault\n viewMode === \"verbose\" && tokens != null && tokens > 0 ? translateText(\"%count% tokens\", { count: format.count(tokens) }) : null,\n viewMode === \"verbose\" && costInUsd != null && costInUsd > 0 ? (formatCost ?? format.cost)(costInUsd) : null,\n ].filter((figure): figure is string => figure !== null);\n\n const handleStop = async () => {\n if (!onStop) return;\n setIsStopPending(true);\n try {\n await onStop();\n } finally {\n setIsStopPending(false);\n }\n };\n\n return (\n <div className={classNames(styles.statusLine, className)} role=\"status\" data-testid=\"trace-run-status\">\n <span className={styles.spinner} aria-hidden />\n <span className={styles.statusText}>\n <span className={styles.statusWord}>{showsStopping ? translateText(\"Stopping…\") : (statusText ?? translateText(\"Working\"))}</span>\n {figures.length > 0 ? ` · ${figures.join(\" · \")}` : null}\n </span>\n <span className={styles.metaGrow} />\n {children}\n {onStop ? (\n <button type=\"button\" className={styles.stopButton} disabled={showsStopping} onClick={() => void handleStop()}>\n <span className={styles.stopSquare} aria-hidden />\n {translateText(\"Stop\")}\n </button>\n ) : null}\n </div>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { ConversationTraceStep, ConversationTurnTrace as ConversationTurnTraceData } from \"../../contract/conversation-trace\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport { ConsentRequestCard } from \"./ConsentRequestCard\";\nimport { ConversationChildTrace } from \"./ConversationChildTrace\";\nimport { FileChangesSummary } from \"./FileChangesSummary\";\nimport { QueuedMessageChip } from \"./QueuedMessageChip\";\nimport { RunningBackgroundJobLines } from \"./RunningBackgroundJobLines\";\nimport { RunStatusLine } from \"./RunStatusLine\";\nimport { useRunningBackgroundJobs } from \"./running-background-jobs-context\";\nimport { buildTaskPlanItems } from \"./StepKindDetails\";\nimport { TaskPlanRow, type TaskPlanItem } from \"./TaskPlanRow\";\nimport { readTaskPlanCountsOfStep } from \"./task-plan-counts\";\nimport { MIN_SHOWN_TURN_DURATION_MS, selectVisibleTraceSteps, ToolStepGroup } from \"./ToolStepGroup\";\nimport { describeStepCount } from \"./trace-counts\";\nimport { useTraceFormat } from \"./trace-format\";\nimport type { TraceFileChange, TraceHostBindings, TraceViewMode } from \"./trace-types\";\nimport { TurnMetaLine } from \"./TurnMetaLine\";\nimport { useConversationTurnTrace } from \"./use-conversation-trace\";\nimport styles from \"./trace-steps.module.scss\";\n\n/** The part of the conversation client the turn trace uses: the trace read, the stop and the stored diffs. */\nexport type ConversationTurnTraceClient = Pick<AgentsConversationClient, \"getTurnTraces\" | \"stopTurn\" | \"getFileChangeDiff\">;\n\n/** A task plan whose items the host knows (the conversation's working state): shown while the turn runs. */\nexport interface ConversationTurnTracePlan {\n title?: string | null;\n items: TaskPlanItem[];\n}\n\nexport interface ConversationTurnTraceProps {\n conversationId: number;\n /** The message that started the turn (`AgentChat`'s `TurnTrace` slot hands it over). */\n turnMessageId: number | string;\n /** live = the turn runs right now; done = it ended, or the message started none. */\n phase: \"live\" | \"done\";\n /** The chat is the compact side panel: narrow blocks, no side-by-side diff. */\n isCompact: boolean;\n /** The conversation client port: `getTurnTraces` feeds the trace, `stopTurn` the Stop button, `getFileChangeDiff` the full diffs. */\n client: ConversationTurnTraceClient;\n /** `summary` (Short), `normal` or `verbose`; verbose needs `isDebugAllowed`, else it reads as normal. */\n viewMode: TraceViewMode;\n /** The host's records, links, mounts and money. `loadFullDiff` and `renderChildTrace` default to the client's reads. */\n host?: TraceHostBindings;\n /** The reader may see the debug level (tool names, arguments, results, tokens, cost). Default false. */\n isDebugAllowed?: boolean;\n /** How often a running turn is read again. Default 1500 ms. */\n pollIntervalMs?: number;\n /** Opens what the model was sent at a call of this turn (verbose): the id of the turn's newest model call message. */\n onOpenContext?: (messageId: number) => void;\n /** The route of the turn in the host's analysis view (verbose); null for none. */\n buildAnalysisHref?: (conversationId: number, turnMessageId: number) => string | null;\n /** The task plan with its items, when the host has it; without it a running turn shows the plan's counts from the trace. */\n taskPlan?: ConversationTurnTracePlan | null;\n /** A value that changes with every new message of the conversation; default: read from the chat's store. */\n conversationRevision?: string | number | null;\n className?: string;\n}\n\n/** The newest model call of a turn that a stored message carries: what \"What the model saw\" opens. */\nconst findNewestModelCallMessageId = (steps: ConversationTraceStep[]): number | null => {\n for (let position = steps.length - 1; position >= 0; position -= 1) {\n const step = steps[position];\n if ((step.kind === \"MODEL_CALL\" || step.modelCall !== null) && step.messageId !== null) return step.messageId;\n }\n return null;\n};\n\n/** The server's words for the turn's model, from its newest model call of that model; null when no step names it. */\nconst findTurnModelLabel = (steps: ConversationTraceStep[], modelName: string | null | undefined): string | null => {\n if (!modelName) return null;\n for (let position = steps.length - 1; position >= 0; position -= 1) {\n const step = steps[position];\n if (step.modelCall?.modelName === modelName && step.modelLabel) return step.modelLabel;\n }\n return null;\n};\n\n/** The newest plan update of a turn. */\nconst findNewestTaskPlanStep = (steps: ConversationTraceStep[]): ConversationTraceStep | null => {\n for (let position = steps.length - 1; position >= 0; position -= 1) {\n if (steps[position].kind === \"TASK_PLAN\" && steps[position].taskPlanItemCount !== null) return steps[position];\n }\n return null;\n};\n\n/** What a running turn spent so far, summed over its model calls (the turn's own totals come with its end). */\nconst sumModelCalls = (turn: ConversationTurnTraceData): { tokens: number | null; costInUsd: number | null } => {\n let tokens: number | null = turn.totals.inputTokens !== null || turn.totals.outputTokens !== null ? (turn.totals.inputTokens ?? 0) + (turn.totals.outputTokens ?? 0) : null;\n let costInUsd = turn.totals.costInUsd;\n if (tokens === null || costInUsd === null) {\n let summedTokens = 0;\n let summedCost = 0;\n let hasTokens = false;\n let hasCost = false;\n for (const step of turn.steps) {\n if (step.kind !== \"MODEL_CALL\" || step.modelCall === null) continue;\n if (step.modelCall.inputTokens !== null || step.modelCall.outputTokens !== null) {\n summedTokens += (step.modelCall.inputTokens ?? 0) + (step.modelCall.outputTokens ?? 0);\n hasTokens = true;\n }\n if (step.modelCall.costInUsd !== null) {\n summedCost += step.modelCall.costInUsd;\n hasCost = true;\n }\n }\n if (tokens === null && hasTokens) tokens = summedTokens;\n if (costInUsd === null && hasCost) costInUsd = summedCost;\n }\n return { tokens, costInUsd };\n};\n\n/**\n * The trace of one turn in the chat, ready for `AgentChat`'s `TurnTrace` slot: it reads the turn through the\n * conversation's shared loader (the turns on screen share their requests), follows it while it runs and shows it by\n * the view mode. Short: one line \"12 steps · 48 s\" that opens the steps. Normal: the steps folded, each with its\n * narrated line, sub-agents with their own steps, commands and file edits. Verbose (debug readers): the steps open,\n * with tool names, thinking, arguments and results, the loaded skills and the turn's figures with the links to what\n * the model saw and to the analysis. While the turn runs: the status line with the clock and Stop, and the task plan.\n * A failed read renders nothing: the thread stays as it is. Under the newest turn of the chat (the context of the chat\n * controller names it) stand the lines of the conversation's background jobs whose end is not reported yet, each with\n * its own Stop — also once that turn has answered.\n */\nexport const ConversationTurnTrace = (props: ConversationTurnTraceProps) => {\n const runningBackgroundJobs = useRunningBackgroundJobs();\n const showsBackgroundJobLines =\n runningBackgroundJobs !== null &&\n runningBackgroundJobs.conversationId === props.conversationId &&\n runningBackgroundJobs.anchorTurnMessageId !== null &&\n String(runningBackgroundJobs.anchorTurnMessageId) === String(props.turnMessageId) &&\n runningBackgroundJobs.backgroundJobs.length > 0;\n return (\n <>\n <ConversationTurnTraceBody {...props} />\n {showsBackgroundJobLines ? (\n <RunningBackgroundJobLines\n backgroundJobs={runningBackgroundJobs.backgroundJobs}\n onStop={runningBackgroundJobs.stopBackgroundJob}\n onStopped={runningBackgroundJobs.refresh}\n isCompact={props.isCompact}\n />\n ) : null}\n </>\n );\n};\n\n/** The trace of one turn itself: its steps, its status line and plan while it runs, its consent card. */\nconst ConversationTurnTraceBody = (props: ConversationTurnTraceProps) => {\n const {\n conversationId,\n turnMessageId,\n phase,\n isCompact,\n client,\n viewMode,\n host,\n isDebugAllowed = false,\n pollIntervalMs,\n onOpenContext,\n buildAnalysisHref,\n taskPlan,\n conversationRevision,\n className,\n } = props;\n const format = useTraceFormat();\n const isLive = phase === \"live\";\n const shownViewMode: TraceViewMode = viewMode === \"verbose\" && !isDebugAllowed ? \"normal\" : viewMode;\n const isVerbose = shownViewMode === \"verbose\";\n const numericTurnMessageId = typeof turnMessageId === \"number\" && Number.isFinite(turnMessageId) ? turnMessageId : null;\n const { turn, refresh } = useConversationTurnTrace({\n client,\n conversationId,\n turnMessageId: numericTurnMessageId,\n level: isVerbose ? \"DEBUG\" : \"STEPS\",\n isLive,\n pollIntervalMs,\n conversationRevision,\n });\n\n // Short opens to the steps on a click; another turn or another mode starts closed again.\n const [isSummaryOpened, setIsSummaryOpened] = useState(false);\n useEffect(() => setIsSummaryOpened(false), [viewMode, numericTurnMessageId]);\n // The clock of a turn whose trace is not read yet ticks from the moment the turn was first seen running.\n const firstSeenLiveAt = useRef<number | null>(null);\n if (isLive && firstSeenLiveAt.current === null) firstSeenLiveAt.current = Date.now();\n if (!isLive) firstSeenLiveAt.current = null;\n // A stop that was accepted keeps the line at \"Stopping…\" until the turn ends.\n const [isStopping, setIsStopping] = useState(false);\n useEffect(() => {\n if (!isLive) setIsStopping(false);\n }, [isLive]);\n\n const { getFileChangeDiff, getTurnTraces, stopTurn } = client;\n const boundHost = useMemo<TraceHostBindings>(() => {\n const loadFullDiffOfClient = getFileChangeDiff\n ? async (fileChange: TraceFileChange): Promise<string> => {\n if (fileChange.id == null) return fileChange.diffPreview ?? \"\";\n return (await getFileChangeDiff(fileChange.id)).diff;\n }\n : undefined;\n return {\n ...host,\n openModelCallContext: host?.openModelCallContext ?? onOpenContext,\n loadFullDiff: host?.loadFullDiff ?? loadFullDiffOfClient,\n renderChildTrace:\n host?.renderChildTrace ??\n ((childConversationId: number) => (\n <ConversationChildTrace\n client={{ getTurnTraces }}\n conversationId={childConversationId}\n viewMode={shownViewMode}\n host={host}\n isCompact={isCompact}\n pollIntervalMs={pollIntervalMs}\n />\n )),\n };\n }, [host, onOpenContext, getFileChangeDiff, getTurnTraces, shownViewMode, isCompact, pollIntervalMs]);\n\n if (turn === null && !isLive) return null;\n\n const steps = turn?.steps ?? [];\n const totals = turn?.totals ?? null;\n const readerSteps = selectVisibleTraceSteps(steps, \"normal\");\n const handleStop = stopTurn\n ? async () => {\n try {\n const turnStop = await stopTurn(conversationId);\n setIsStopping(turnStop.isStopped);\n refresh();\n } catch {\n // The stop was not accepted: the button is there again and the turn runs on.\n setIsStopping(false);\n }\n }\n : undefined;\n\n const spent = turn !== null && isVerbose ? sumModelCalls(turn) : { tokens: null, costInUsd: null };\n const statusLine = isLive ? (\n <RunStatusLine\n startedAt={turn?.startedAt ?? firstSeenLiveAt.current}\n viewMode={shownViewMode}\n tokens={spent.tokens}\n costInUsd={spent.costInUsd}\n formatCost={boundHost.formatCost}\n onStop={handleStop}\n isStopping={isStopping}\n />\n ) : null;\n\n const newestPlanStep = isLive ? findNewestTaskPlanStep(steps) : null;\n const planRow = !isLive ? null : taskPlan && taskPlan.items.length > 0 ? (\n <TaskPlanRow title={taskPlan.title} items={taskPlan.items} defaultOpen={!isCompact} />\n ) : newestPlanStep !== null ? (\n <TaskPlanRow\n title={newestPlanStep.taskPlanTitle}\n // The items of the plan when the trace names them, else the head with its counts.\n items={buildTaskPlanItems(newestPlanStep.taskPlanItems)}\n defaultOpen={!isCompact}\n totalCount={newestPlanStep.taskPlanItemCount}\n doneCount={readTaskPlanCountsOfStep(newestPlanStep).done}\n />\n ) : null;\n\n // The tool calls the finished turn holds for the owner's approval: a card to answer them (the live chat only).\n const consentCalls = !isLive\n ? steps\n .filter((step) => step.isHeldForConsent)\n .map((step) => ({ title: step.toolNameInWords || step.toolName || translateText(\"Action\"), line: step.line ?? null }))\n : [];\n const consentCard =\n consentCalls.length > 0 && numericTurnMessageId !== null ? (\n <ConsentRequestCard conversationId={conversationId} turnMessageId={numericTurnMessageId} calls={consentCalls} isCompact={isCompact} />\n ) : null;\n\n // Short: nothing of a turn without steps; one line that opens the steps of a turn with some.\n if (shownViewMode === \"summary\" && !isSummaryOpened) {\n if (isLive) {\n return (\n <div className={classNames(styles.turnTrace, isCompact && styles.turnTraceCompact, className)} data-testid=\"conversation-turn-trace\" data-view-mode=\"summary\" data-phase={phase}>\n {statusLine}\n </div>\n );\n }\n if (readerSteps.length === 0) return null;\n const summaryParts = [\n describeStepCount(readerSteps.length, format),\n totals?.durationMs != null && totals.durationMs >= MIN_SHOWN_TURN_DURATION_MS ? format.duration(totals.durationMs) : null,\n ].filter((part): part is string => part !== null);\n return (\n <div className={classNames(styles.turnTrace, isCompact && styles.turnTraceCompact, className)} data-testid=\"conversation-turn-trace\" data-view-mode=\"summary\" data-phase={phase}>\n <button\n type=\"button\"\n className={styles.summaryChip}\n aria-expanded={false}\n title={translateText(\"Show the steps\")}\n onClick={() => setIsSummaryOpened(true)}\n data-testid=\"trace-summary-chip\"\n >\n <Icon name=\"steps\" pixelSize={13} />\n {summaryParts.join(\" · \")}\n </button>\n {consentCard}\n </div>\n );\n }\n\n const groupViewMode: TraceViewMode = shownViewMode === \"summary\" ? \"normal\" : shownViewMode;\n const newestModelCallMessageId = isVerbose ? findNewestModelCallMessageId(steps) : null;\n const analysisHref = isVerbose && numericTurnMessageId !== null ? (buildAnalysisHref?.(conversationId, numericTurnMessageId) ?? null) : null;\n const metaLine =\n isVerbose && totals !== null && !isLive ? (\n <TurnMetaLine\n {...totals}\n modelLabel={findTurnModelLabel(steps, totals.modelName)}\n onOpenContext={onOpenContext && newestModelCallMessageId !== null ? () => onOpenContext(newestModelCallMessageId) : undefined}\n analysisHref={analysisHref}\n linkComponent={boundHost.linkComponent}\n formatCost={boundHost.formatCost}\n isCompact={isCompact}\n />\n ) : null;\n // Owner messages that came in while this turn ran and that it took up: a quiet line each once the turn is over (the\n // thread shows them as plain messages; while the turn runs the controller marks them as queued).\n const queuedMessagesTakenUp =\n !isLive && turn !== null && shownViewMode !== \"summary\"\n ? (turn.queuedMessages ?? []).filter((message) => message.handledInTurnNumber == null || message.handledInTurnNumber === turn.turnNumber)\n : [];\n const hasGroup = selectVisibleTraceSteps(steps, groupViewMode).length > 0 || isLive || metaLine !== null;\n if (!hasGroup) return consentCard;\n\n return (\n <div\n className={classNames(styles.turnTrace, styles.anchor, isCompact && styles.turnTraceCompact, className)}\n data-testid=\"conversation-turn-trace\"\n data-view-mode={shownViewMode}\n data-phase={phase}\n data-trace-turn-number={turn?.turnNumber ?? undefined}\n >\n {planRow}\n <ToolStepGroup\n // The fold starts over when the turn ends: open while it runs, then as the mode says (closed in normal).\n key={isLive ? \"live\" : \"done\"}\n steps={steps}\n viewMode={groupViewMode}\n durationMs={isLive ? null : totals?.durationMs}\n // The status line below says that the turn runs: the group's head stays calm and only stands open.\n defaultOpen={isLive || shownViewMode === \"summary\" ? true : undefined}\n summary={\n totals !== null && (totals.commandCount > 0 || totals.fileCount > 0 || totals.linesAdded > 0 || totals.linesRemoved > 0) ? (\n <FileChangesSummary commandCount={totals.commandCount} fileCount={totals.fileCount} linesAdded={totals.linesAdded} linesRemoved={totals.linesRemoved} />\n ) : undefined\n }\n metaLine={metaLine}\n host={boundHost}\n conversationId={conversationId}\n isCompact={isCompact}\n />\n {queuedMessagesTakenUp.map((message) => (\n <QueuedMessageChip key={message.messageId ?? message.text} text={message.text} wasTakenUp isCompact={isCompact} />\n ))}\n {consentCard}\n {statusLine}\n </div>\n );\n};\n","import type { TraceTaskPlanStepItem } from \"./trace-types\";\n\n/**\n * Where an item of the task plan stands, as the work plan draws it: done, does not apply (skipped), blocked, running\n * (the first open leaf: the step the agent works on now) or open.\n */\nexport type TaskPlanNodeState = \"done\" | \"skipped\" | \"blocked\" | \"running\" | \"open\";\n\n/** One item of the plan in its tree: its children, its state and the part of its leaves that is closed. */\nexport interface TaskPlanTreeNode {\n item: TraceTaskPlanStepItem;\n key: string;\n depth: number;\n parent: TaskPlanTreeNode | null;\n children: TaskPlanTreeNode[];\n state: TaskPlanNodeState;\n /** Leaves below the node (the node itself for a leaf) that are done or do not apply, and all of them. */\n closedLeafCount: number;\n leafCount: number;\n}\n\n/** The plan as a tree, with the counts the work plan shows. */\nexport interface TaskPlanTree {\n roots: TaskPlanTreeNode[];\n /** Every node in plan order (depth first). */\n nodes: TaskPlanTreeNode[];\n byKey: ReadonlyMap<string, TaskPlanTreeNode>;\n /** The running leaf (the first open leaf), null when none is open. */\n running: TaskPlanTreeNode | null;\n /** All leaves, the closed ones (done or does not apply), the blocked and the skipped ones. */\n leafCount: number;\n closedLeafCount: number;\n blockedLeafCount: number;\n skippedLeafCount: number;\n /** The position of the top-level item the plan works on (1-based; the count of top-level items when all are closed). */\n currentTopLevelPosition: number;\n}\n\nconst CLOSED_STATES: readonly TaskPlanNodeState[] = [\"done\", \"skipped\"];\n\n/** The status the plan shows for an item: the server's derived status, else the item's own. */\nexport const readShownStatus = (item: Pick<TraceTaskPlanStepItem, \"status\" | \"shownStatus\">): string =>\n (item.shownStatus ?? item.status ?? \"open\").toLowerCase();\n\nconst readBaseState = (status: string): Exclude<TaskPlanNodeState, \"running\"> => {\n if (status === \"done\" || status === \"completed\") return \"done\";\n if (status === \"not_applicable\" || status === \"skipped\" || status === \"cancelled\") return \"skipped\";\n if (status === \"blocked\") return \"blocked\";\n return \"open\";\n};\n\n/**\n * Builds the tree of a plan's items (in plan order, each with its `depth`): a node's parent is the nearest item before\n * it with a smaller depth. A container whose server sends no derived status derives its state from its children\n * (blocked when a child is blocked and none open, done when all are closed). The first open leaf outside a closed\n * container is the running step.\n */\nexport const buildTaskPlanTree = (items: readonly TraceTaskPlanStepItem[]): TaskPlanTree => {\n const roots: TaskPlanTreeNode[] = [];\n const nodes: TaskPlanTreeNode[] = [];\n const byKey = new Map<string, TaskPlanTreeNode>();\n const stack: TaskPlanTreeNode[] = [];\n items.forEach((item, position) => {\n const depth = Math.max(0, item.depth ?? 0);\n while (stack.length > 0 && stack[stack.length - 1].depth >= depth) stack.pop();\n const parent = stack.length > 0 ? stack[stack.length - 1] : null;\n const key = item.key || item.numberPath || String(position);\n const node: TaskPlanTreeNode = {\n item,\n key,\n depth: parent ? parent.depth + 1 : 0,\n parent,\n children: [],\n state: readBaseState(readShownStatus(item)),\n closedLeafCount: 0,\n leafCount: 0,\n };\n (parent ? parent.children : roots).push(node);\n nodes.push(node);\n if (!byKey.has(key)) byKey.set(key, node);\n stack.push(node);\n });\n const settle = (node: TaskPlanTreeNode): void => {\n if (node.children.length === 0) {\n node.leafCount = 1;\n node.closedLeafCount = CLOSED_STATES.includes(node.state) ? 1 : 0;\n return;\n }\n node.children.forEach(settle);\n node.leafCount = node.children.reduce((sum, child) => sum + child.leafCount, 0);\n node.closedLeafCount = node.children.reduce((sum, child) => sum + child.closedLeafCount, 0);\n if (node.item.shownStatus != null || node.state !== \"open\") return;\n // an older server: derive the container from its children\n const childStates = node.children.map((child) => child.state);\n if (childStates.every((state) => CLOSED_STATES.includes(state))) {\n node.state = childStates.includes(\"done\") ? \"done\" : \"skipped\";\n } else if (childStates.includes(\"blocked\") && !childStates.includes(\"open\")) {\n node.state = \"blocked\";\n }\n };\n // an open item below a blocked or not applicable container is covered by that container's verdict\n const cover = (node: TaskPlanTreeNode): void => {\n for (const child of node.children) {\n if ((node.state === \"blocked\" || node.state === \"skipped\") && child.state === \"open\" && child.item.shownStatus == null) child.state = node.state;\n cover(child);\n }\n };\n roots.forEach(cover);\n roots.forEach(settle);\n // the running step: the first open leaf; its open ancestors run too\n const running = nodes.find((node) => node.children.length === 0 && node.state === \"open\") ?? null;\n for (let node: TaskPlanTreeNode | null = running; node !== null; node = node.parent) {\n if (node.state === \"open\") node.state = \"running\";\n }\n const leaves = nodes.filter((node) => node.children.length === 0);\n const openTopLevelPosition = roots.findIndex((root) => !CLOSED_STATES.includes(root.state));\n return {\n roots,\n nodes,\n byKey,\n running,\n leafCount: leaves.length,\n closedLeafCount: leaves.filter((node) => CLOSED_STATES.includes(node.state)).length,\n blockedLeafCount: leaves.filter((node) => node.state === \"blocked\").length,\n skippedLeafCount: leaves.filter((node) => node.state === \"skipped\").length,\n currentTopLevelPosition: openTopLevelPosition === -1 ? roots.length : openTopLevelPosition + 1,\n };\n};\n\n/**\n * The containers the work plan opens at first: every container that is not closed (the path of the running and of a\n * blocked step among them); a done or skipped branch stays folded.\n */\nexport const readDefaultExpandedKeys = (tree: TaskPlanTree): Set<string> =>\n new Set(tree.nodes.filter((node) => node.children.length > 0 && !CLOSED_STATES.includes(node.state)).map((node) => node.key));\n\n/** The nodes a reader sees with the given containers open, in plan order. */\nexport const readVisibleNodes = (tree: TaskPlanTree, expandedKeys: ReadonlySet<string>): TaskPlanTreeNode[] => {\n const visible: TaskPlanTreeNode[] = [];\n const walk = (level: TaskPlanTreeNode[]) => {\n for (const node of level) {\n visible.push(node);\n if (node.children.length > 0 && expandedKeys.has(node.key)) walk(node.children);\n }\n };\n walk(tree.roots);\n return visible;\n};\n\n/** The item before and after a node in plan order (any depth), for the arrows of the detail view. */\nexport const readNeighbours = (tree: TaskPlanTree, key: string): { previous: TaskPlanTreeNode | null; next: TaskPlanTreeNode | null } => {\n const position = tree.nodes.findIndex((node) => node.key === key);\n if (position === -1) return { previous: null, next: null };\n return { previous: tree.nodes[position - 1] ?? null, next: tree.nodes[position + 1] ?? null };\n};\n","import type { CSSProperties, ReactNode } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport type { TaskPlanNodeState, TaskPlanTree, TaskPlanTreeNode } from \"./task-plan-tree\";\nimport { readNeighbours } from \"./task-plan-tree\";\nimport type { TraceTaskPlanItemSource, TraceTaskPlanRejection } from \"./trace-collect\";\nimport { readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport styles from \"./task-plan.module.scss\";\n\n/** What the detail view shows: the plan, or one item by its key. */\nexport type TaskPlanDetailTarget = { kind: \"plan\" } | { kind: \"item\"; key: string };\n\nexport interface TaskPlanDrawerProps {\n target: TaskPlanDetailTarget;\n tree: TaskPlanTree;\n /** The plan's title: the request it was made for. */\n title?: string | null;\n /** Per item key, the plan update that last changed it and the one it first appeared in. */\n itemSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n itemFirstSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n /** Debug level: what refused plan calls told the agent. */\n rejections?: readonly TraceTaskPlanRejection[];\n /** When the plan was last updated (a server date-time). */\n updatedAt?: string | null;\n onNavigate: (target: TaskPlanDetailTarget) => void;\n onClose: () => void;\n /** Leads to the plan update in the trace; without it the times are plain text. */\n onShowSource?: (node: TaskPlanTreeNode, source: TraceTaskPlanItemSource) => void;\n}\n\nconst STATE_LABELS: Readonly<Record<TaskPlanNodeState, () => string>> = {\n done: () => translateText(\"Done\"),\n skipped: () => translateText(\"Does not apply\", undefined, \"plan-item-state\"),\n blocked: () => translateText(\"Blocked\", undefined, \"plan-item-state\"),\n running: () => translateText(\"In progress\"),\n open: () => translateText(\"Not started\"),\n};\n\n/** The state mark of an item: a ring, filled to the closed share for an open container. */\nexport const TaskPlanMark = ({ node }: { node: TaskPlanTreeNode }) => {\n const { state } = node;\n const isPart = node.children.length > 0 && state === \"open\" && node.closedLeafCount > 0;\n const style = isPart ? ({ \"--agents-task-plan-part\": `${Math.round((node.closedLeafCount / node.leafCount) * 100)}%` } as CSSProperties) : undefined;\n return (\n <span\n className={classNames(\n styles.mark,\n state === \"done\" && styles.markDone,\n state === \"skipped\" && styles.markSkipped,\n state === \"blocked\" && styles.markBlocked,\n state === \"running\" && styles.markRunning,\n isPart && styles.markPart,\n )}\n style={style}\n role=\"img\"\n aria-label={STATE_LABELS[state]()}\n >\n {state === \"done\" ? <Icon name=\"stepDone\" pixelSize={11} /> : null}\n {state === \"skipped\" ? <Icon name=\"dash\" pixelSize={11} /> : null}\n {state === \"blocked\" ? <Icon name=\"exclamation\" pixelSize={11} /> : null}\n </span>\n );\n};\n\n/** The leaves of nodes as small segments, one per leaf, coloured by its state. */\nexport const TaskPlanSegments = ({ nodes, isSmall }: { nodes: readonly TaskPlanTreeNode[]; isSmall?: boolean }) => {\n const leaves: TaskPlanTreeNode[] = [];\n const collect = (level: readonly TaskPlanTreeNode[]) => level.forEach((node) => (node.children.length > 0 ? collect(node.children) : leaves.push(node)));\n collect(nodes);\n return (\n <span className={classNames(styles.segments, isSmall && styles.segmentsSmall)} aria-hidden=\"true\">\n {leaves.map((leaf) => (\n <span\n key={leaf.key}\n className={classNames(\n styles.segment,\n leaf.state === \"done\" && styles.segmentDone,\n leaf.state === \"skipped\" && styles.segmentSkipped,\n leaf.state === \"blocked\" && styles.segmentBlocked,\n leaf.state === \"running\" && styles.segmentRunning,\n )}\n />\n ))}\n </span>\n );\n};\n\nconst Section = (props: { icon?: Parameters<typeof Icon>[0][\"name\"]; title: string; isDebug?: boolean; tone?: \"running\" | \"blocked\" | \"done\" | \"criterion\"; extra?: ReactNode; children: ReactNode }) => (\n <section\n className={classNames(\n styles.section,\n props.tone === \"running\" && styles.sectionRunning,\n props.tone === \"blocked\" && styles.sectionBlocked,\n props.tone === \"done\" && styles.sectionDone,\n props.tone === \"criterion\" && styles.sectionCriterion,\n )}\n >\n <h4 className={styles.sectionHead}>\n {props.icon ? <Icon name={props.icon} pixelSize={13} /> : null}\n {props.title}\n {props.isDebug ? <span className={classNames(styles.chip, styles.chipDebug)}>{translateText(\"Debug\")}</span> : null}\n {props.extra}\n </h4>\n {props.children}\n </section>\n);\n\n/** \"Turn 3 · 10:06\" for a plan update. */\nconst useDescribeSource = () => {\n const format = useTraceFormat();\n return (source: TraceTaskPlanItemSource): string => {\n const moment = readTraceMoment(source.startedAt ?? null);\n return moment === null\n ? translateText(\"Turn %number%\", { number: format.number(source.turnNumber) })\n : translateText(\"Turn %number% · %time%\", { number: format.number(source.turnNumber), time: format.time(moment) });\n };\n};\n\n/** The note of an item's state; a container that has none names the step that runs or blocks below it. */\nconst readStateNote = (node: TaskPlanTreeNode): string | null => {\n const note = node.item.statusNote ?? null;\n if (note) return note;\n if (node.children.length > 0) {\n const leaf = findLeafInState(node, \"blocked\") ?? findLeafInState(node, \"running\");\n if (leaf) return `${leaf.item.numberPath ?? leaf.key} ${leaf.item.title}${leaf.item.statusNote ? `: ${leaf.item.statusNote}` : \"\"}`;\n }\n if (node.state === \"running\") return translateText(\"The agent works on this step now.\");\n if (node.state === \"open\") return translateText(\"Not started yet.\");\n return null;\n};\n\nconst findLeafInState = (node: TaskPlanTreeNode, state: TaskPlanNodeState): TaskPlanTreeNode | null => {\n if (node.children.length === 0) return node.state === state ? node : null;\n for (const child of node.children) {\n const leaf = findLeafInState(child, state);\n if (leaf) return leaf;\n }\n return null;\n};\n\nconst STATE_NOTE_TITLES: Readonly<Record<TaskPlanNodeState, () => string>> = {\n done: () => translateText(\"Result\"),\n skipped: () => translateText(\"Why it does not apply\"),\n blocked: () => translateText(\"Reason\"),\n running: () => translateText(\"Now\"),\n open: () => translateText(\"Status\"),\n};\n\nconst ItemDetail = (props: TaskPlanDrawerProps & { node: TaskPlanTreeNode }) => {\n const { node, onNavigate, itemSources, itemFirstSources, rejections, onShowSource } = props;\n const describeSource = useDescribeSource();\n const { item } = node;\n const note = readStateNote(node);\n const tone = node.state === \"running\" ? \"running\" : node.state === \"blocked\" ? \"blocked\" : node.state === \"done\" ? \"done\" : undefined;\n const firstSource = itemFirstSources?.[node.key];\n const lastSource = itemSources?.[node.key];\n const itemRejections = (rejections ?? []).filter((rejection) => rejection.itemKey === node.key || rejection.itemKey === item.numberPath);\n const isDebugShown = item.instruction != null || (item.declarations?.length ?? 0) > 0 || (item.skillNames?.length ?? 0) > 0 || itemRejections.length > 0;\n const subtaskCount = node.children.length;\n return (\n <>\n <div className={styles.detailHead}>\n <span className={styles.eyebrow}>\n {translateText(\"Step %number%\", { number: item.numberPath ?? node.key })}\n {node.parent ? (\n <>\n <span aria-hidden=\"true\">·</span>\n <span>{translateText(\"part of\")}</span>\n <button type=\"button\" className={styles.eyebrowLink} onClick={() => onNavigate({ kind: \"item\", key: node.parent!.key })}>\n {`${node.parent.item.numberPath ?? node.parent.key} ${node.parent.item.title}`}\n </button>\n </>\n ) : null}\n {subtaskCount > 0 ? (\n <>\n <span aria-hidden=\"true\">·</span>\n <span>\n {subtaskCount === 1\n ? translateText(\"%count% subtasks\", { count: subtaskCount }, \"plan-subtasks-one\")\n : translateText(\"%count% subtasks\", { count: subtaskCount }, \"plan-subtasks-other\")}\n </span>\n </>\n ) : null}\n </span>\n <h3 className={styles.detailTitle} data-testid=\"trace-task-plan-detail-title\">\n {item.title}\n </h3>\n </div>\n\n <Section title={`${STATE_LABELS[node.state]()} · ${STATE_NOTE_TITLES[node.state]()}`} tone={tone}>\n {note ? <p className={styles.text}>{note}</p> : null}\n {item.requiresUserAction || item.retryable || item.isPreResolvedAtSeed ? (\n <div className={styles.flags}>\n {item.requiresUserAction ? <span className={classNames(styles.chip, styles.chipOwner)}>{translateText(\"Waits for you\")}</span> : null}\n {item.retryable ? <span className={styles.chip}>{translateText(\"Can be tried again\")}</span> : null}\n {item.isPreResolvedAtSeed ? <span className={styles.chip}>{translateText(\"Already done at the start\")}</span> : null}\n </div>\n ) : null}\n </Section>\n\n {subtaskCount > 0 ? (\n <Section\n icon=\"steps\"\n title={translateText(\"Subtasks\")}\n extra={<span className={styles.chip}>{`${node.closedLeafCount}/${node.leafCount}`}</span>}\n >\n <TaskPlanSegments nodes={node.children} />\n <ul className={styles.miniList}>\n {node.children.map((child) => (\n <li key={child.key}>\n <button type=\"button\" className={styles.miniRow} onClick={() => onNavigate({ kind: \"item\", key: child.key })}>\n <TaskPlanMark node={child} />\n <span className={styles.number}>{child.item.numberPath ?? child.key}</span>\n <span className={styles.miniTitle}>{child.item.title}</span>\n <span className={styles.miniState}>\n {child.children.length > 0 ? `${child.closedLeafCount}/${child.leafCount}` : STATE_LABELS[child.state]()}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </Section>\n ) : null}\n\n <Section\n icon=\"check\"\n title={translateText(\"Done when\")}\n tone=\"criterion\"\n extra={\n node.children.length === 0 && item.closesItself ? (\n <span className={classNames(styles.chip, styles.chipRunning)}>{translateText(\"Closes itself\")}</span>\n ) : null\n }\n >\n <p className={styles.text}>\n {node.children.length > 0\n ? translateText(\"every subtask is done or does not apply. The step then closes itself.\")\n : item.closesItself\n ? translateText(\"the record shows it: a completed call, a widget or a delivered answer. The platform ticks it off, not the agent.\")\n : translateText(\"the agent ticks it off with what it produced.\")}\n </p>\n {item.doneCriterion ? (\n <dl className={styles.facts}>\n <dt>{translateText(\"Criterion\")}</dt>\n <dd className={styles.mono}>{item.doneCriterion}</dd>\n </dl>\n ) : null}\n </Section>\n\n <Section icon=\"clock\" title={translateText(\"Origin and times\")}>\n <dl className={styles.facts}>\n <dt>{translateText(\"Origin\", undefined, \"task-plan-origin\")}</dt>\n <dd>{item.isSeeded ? translateText(\"Seeded from the purpose\") : translateText(\"Added by the agent\")}</dd>\n {item.customerProgressStepKey ? (\n <>\n <dt>{translateText(\"Customer step\")}</dt>\n <dd className={styles.mono}>{item.customerProgressStepKey}</dd>\n </>\n ) : null}\n {firstSource ? (\n <>\n <dt>{translateText(\"Created\")}</dt>\n <dd>{describeSource(firstSource)}</dd>\n </>\n ) : null}\n {lastSource ? (\n <>\n <dt>{translateText(\"Last changed\")}</dt>\n <dd>\n {describeSource(lastSource)}\n {onShowSource ? (\n <>\n {\" · \"}\n <button\n type=\"button\"\n className={styles.link}\n data-testid=\"trace-task-plan-item-link\"\n title={translateText(\"Show the step that last changed this item\")}\n onClick={() => onShowSource(node, lastSource)}\n >\n {translateText(\"in the trace\")}\n </button>\n </>\n ) : null}\n </dd>\n </>\n ) : null}\n {item.wasClosedByPlatform ? (\n <>\n <dt>{translateText(\"Closed by\")}</dt>\n <dd>{translateText(\"the platform\")}</dd>\n </>\n ) : null}\n </dl>\n </Section>\n\n {isDebugShown ? (\n <>\n {item.instruction ? (\n <Section icon=\"ai\" title={translateText(\"Instruction to the agent\")} isDebug>\n <p className={classNames(styles.text, styles.mono)}>{item.instruction}</p>\n </Section>\n ) : null}\n {(item.declarations?.length ?? 0) > 0 || (item.skillNames?.length ?? 0) > 0 || item.evidenceMessageIndex != null || item.platformResolvedAtMessageIndex != null ? (\n <Section icon=\"code\" title={translateText(\"Fields\")} isDebug>\n <dl className={styles.facts}>\n {(item.declarations ?? []).map((declaration) => (\n <FactRow key={declaration.name} name={declaration.name} value={declaration.value} />\n ))}\n {(item.skillNames?.length ?? 0) > 0 ? <FactRow name=\"skillNames\" value={(item.skillNames ?? []).join(\", \")} /> : null}\n {item.evidenceMessageIndex != null ? <FactRow name=\"evidenceMessageIndex\" value={String(item.evidenceMessageIndex)} /> : null}\n {item.platformResolvedAtMessageIndex != null ? (\n <FactRow name=\"platformResolvedAtMessageIndex\" value={String(item.platformResolvedAtMessageIndex)} />\n ) : null}\n </dl>\n </Section>\n ) : null}\n {itemRejections.length > 0 ? <RejectionsSection rejections={itemRejections} /> : null}\n </>\n ) : null}\n </>\n );\n};\n\nconst FactRow = ({ name, value }: { name: string; value: string }) => (\n <>\n <dt className={styles.mono}>{name}</dt>\n <dd className={styles.mono}>{value}</dd>\n </>\n);\n\nconst RejectionsSection = ({ rejections }: { rejections: readonly TraceTaskPlanRejection[] }) => {\n const describeSource = useDescribeSource();\n return (\n <Section icon=\"exclamation\" title={translateText(\"Rejected plan changes\")} isDebug>\n {rejections.map((rejection, position) => (\n <div key={`${rejection.source.stepKey}:${position}`} className={styles.rejection}>\n <span className={styles.quiet}>{[describeSource(rejection.source), rejection.toolName].filter(Boolean).join(\" · \")}</span>\n <span className={classNames(styles.text, styles.mono)}>{rejection.line}</span>\n </div>\n ))}\n </Section>\n );\n};\n\nconst PlanDetail = (props: TaskPlanDrawerProps) => {\n const { tree, title, onNavigate, itemFirstSources, itemSources, rejections } = props;\n const format = useTraceFormat();\n const describeSource = useDescribeSource();\n const isFinished = tree.leafCount > 0 && tree.closedLeafCount + tree.blockedLeafCount === tree.leafCount && tree.blockedLeafCount === 0;\n const openCount = tree.leafCount - tree.closedLeafCount - tree.blockedLeafCount;\n const doneCount = tree.closedLeafCount - tree.skippedLeafCount;\n const sources = Object.values(itemFirstSources ?? {});\n const firstSource = sources.reduce<TraceTaskPlanItemSource | null>(\n (earliest, source) => (earliest === null || source.turnNumber < earliest.turnNumber ? source : earliest),\n null,\n );\n const lastSource = Object.values(itemSources ?? {}).reduce<TraceTaskPlanItemSource | null>(\n (latest, source) => (latest === null || source.turnNumber >= latest.turnNumber ? source : latest),\n null,\n );\n const seededCount = tree.nodes.filter((node) => node.item.isSeeded).length;\n const addedNodes = seededCount > 0 ? tree.nodes.filter((node) => !node.item.isSeeded) : [];\n const leaves = tree.nodes.filter((node) => node.children.length === 0);\n const share = tree.leafCount > 0 ? Math.round((tree.closedLeafCount / tree.leafCount) * 100) : 0;\n return (\n <>\n <div className={styles.detailHead}>\n <span className={styles.eyebrow}>{translateText(\"Work plan\")}</span>\n <h3 className={styles.detailTitle} data-testid=\"trace-task-plan-detail-title\">\n {title || translateText(\"Plan\")}\n </h3>\n </div>\n <section className={styles.section}>\n <div className={styles.head}>\n <span className={styles.ring} style={{ \"--agents-task-plan-part\": `${share}%` } as CSSProperties}>\n <b>{`${tree.closedLeafCount}/${tree.leafCount}`}</b>\n </span>\n <div className={styles.headText} style={{ gap: \"0.375rem\" }}>\n <b>{translateText(\"%done% of %total% steps\", { done: format.number(tree.closedLeafCount), total: format.number(tree.leafCount) })}</b>\n <div className={styles.flags}>\n <span className={classNames(styles.chip, isFinished ? styles.chipDone : tree.blockedLeafCount > 0 ? styles.chipBlocked : styles.chipRunning)}>\n {isFinished ? translateText(\"Finished\") : tree.blockedLeafCount > 0 ? STATE_LABELS.blocked() : STATE_LABELS.running()}\n </span>\n {doneCount > 0 ? <span className={styles.chip}>{translateText(\"%count% done\", { count: format.number(doneCount) })}</span> : null}\n {tree.skippedLeafCount > 0 ? (\n <span className={styles.chip}>{translateText(\"%count% do not apply\", { count: format.number(tree.skippedLeafCount) })}</span>\n ) : null}\n {openCount > 0 ? <span className={styles.chip}>{translateText(\"%count% open\", { count: format.number(openCount) })}</span> : null}\n </div>\n </div>\n </div>\n <TaskPlanSegments nodes={tree.roots} />\n </section>\n {isFinished ? (\n <Section icon=\"check\" title={translateText(\"Result\")}>\n {leaves.map((leaf) => (\n <div key={leaf.key} className={styles.outcome}>\n <TaskPlanMark node={leaf} />\n <span>\n <b>{leaf.item.title}</b>\n {leaf.item.statusNote ? <span className={styles.quiet}>{` · ${leaf.item.statusNote}`}</span> : null}\n </span>\n </div>\n ))}\n </Section>\n ) : (\n <Section icon=\"steps\" title={translateText(\"Steps\")}>\n <ul className={styles.miniList}>\n {tree.roots.map((root) => (\n <li key={root.key}>\n <button type=\"button\" className={styles.miniRow} onClick={() => onNavigate({ kind: \"item\", key: root.key })}>\n <TaskPlanMark node={root} />\n <span className={styles.number}>{root.item.numberPath ?? root.key}</span>\n <span className={styles.miniTitle}>{root.item.title}</span>\n <span className={styles.miniState}>\n {root.children.length > 0 ? `${root.closedLeafCount}/${root.leafCount}` : STATE_LABELS[root.state]()}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </Section>\n )}\n <Section icon=\"clock\" title={translateText(\"Times and origin\")}>\n <dl className={styles.facts}>\n {firstSource ? (\n <>\n <dt>{translateText(\"Created\")}</dt>\n <dd>{describeSource(firstSource)}</dd>\n </>\n ) : null}\n {lastSource ? (\n <>\n <dt>{translateText(\"Last changed\")}</dt>\n <dd>{describeSource(lastSource)}</dd>\n </>\n ) : null}\n <dt>{translateText(\"Origin\", undefined, \"task-plan-origin\")}</dt>\n <dd>\n {seededCount > 0\n ? translateText(\"Seeded from the purpose: %seeded% of %total% items\", { seeded: format.number(seededCount), total: format.number(tree.nodes.length) })\n : translateText(\"Made by the agent\")}\n </dd>\n {addedNodes.length > 0 ? (\n <>\n <dt>{translateText(\"Added by the agent\")}</dt>\n <dd>{addedNodes.map((node) => `${node.item.numberPath ?? node.key} ${node.item.title}`).join(\", \")}</dd>\n </>\n ) : null}\n </dl>\n </Section>\n {(rejections?.length ?? 0) > 0 ? <RejectionsSection rejections={rejections ?? []} /> : null}\n </>\n );\n};\n\n/**\n * The detail view of the work plan, for the plan or for one item. The plan: its goal (the request it was made for),\n * its progress with the counts, its result once finished (every step with its note), when it was made and changed and\n * where its items came from. An item: its state with the note (what was produced, why it is blocked, why it does not\n * apply) and whether it waits for the owner, its subtasks with their part progress, when it is done (by its subtasks,\n * by the record, by the agent's tick), its origin and times; at the debug level the agent's instruction, the seeded\n * declarations and the rejected plan changes that name it. The head leads back to the plan, up to the parent and to the\n * item before and after it in the plan.\n */\nexport const TaskPlanDrawer = (props: TaskPlanDrawerProps) => {\n const { target, tree, onNavigate, onClose } = props;\n const node = target.kind === \"item\" ? tree.byKey.get(target.key) ?? null : null;\n const neighbours = node ? readNeighbours(tree, node.key) : { previous: null, next: null };\n return (\n <aside className={styles.detail} data-testid=\"trace-task-plan-detail\" aria-label={translateText(\"Details\")}>\n <div className={styles.detailNav}>\n {node ? (\n <button type=\"button\" className={styles.pill} onClick={() => onNavigate({ kind: \"plan\" })}>\n <Icon name=\"arrowLeft\" pixelSize={13} />\n {translateText(\"Plan\")}\n </button>\n ) : null}\n <span className={styles.grow} />\n {node?.parent ? (\n <button\n type=\"button\"\n className={styles.pill}\n title={translateText(\"Parent step\")}\n onClick={() => onNavigate({ kind: \"item\", key: node.parent!.key })}\n >\n <Icon name=\"arrowUp\" pixelSize={13} />\n {node.parent.item.numberPath ?? node.parent.key}\n </button>\n ) : null}\n {node ? (\n <>\n <button\n type=\"button\"\n className={classNames(styles.pill, styles.pillSquare)}\n title={translateText(\"Previous step\")}\n aria-label={translateText(\"Previous step\")}\n disabled={neighbours.previous === null}\n onClick={() => neighbours.previous && onNavigate({ kind: \"item\", key: neighbours.previous.key })}\n >\n <Icon name=\"caretUp\" pixelSize={13} />\n </button>\n <button\n type=\"button\"\n className={classNames(styles.pill, styles.pillSquare)}\n title={translateText(\"Next step\")}\n aria-label={translateText(\"Next step\")}\n disabled={neighbours.next === null}\n onClick={() => neighbours.next && onNavigate({ kind: \"item\", key: neighbours.next.key })}\n >\n <Icon name=\"caretDown\" pixelSize={13} />\n </button>\n </>\n ) : null}\n <button\n type=\"button\"\n className={classNames(styles.pill, styles.pillSquare)}\n title={translateText(\"Close\")}\n aria-label={translateText(\"Close\")}\n onClick={onClose}\n >\n <Icon name=\"close\" pixelSize={13} />\n </button>\n </div>\n {node ? <ItemDetail {...props} node={node} /> : <PlanDetail {...props} />}\n </aside>\n );\n};\n","import { type ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport { describeTaskPlanProgress, readTaskPlanCounts } from \"./task-plan-counts\";\nimport { type TaskPlanTreeNode, buildTaskPlanTree, readDefaultExpandedKeys, readVisibleNodes } from \"./task-plan-tree\";\nimport { type TaskPlanDetailTarget, TaskPlanDrawer, TaskPlanMark, TaskPlanSegments } from \"./TaskPlanDrawer\";\nimport { useTraceFormat } from \"./trace-format\";\nimport type { TraceTaskPlanItemSource, TraceTaskPlanRejection } from \"./trace-collect\";\nimport type { TraceTaskPlanStepItem } from \"./trace-types\";\nimport styles from \"./task-plan.module.scss\";\n\nexport interface TaskPlanPaneProps {\n /** The plan's own title (the request it was made for); it heads the pane. */\n title?: string | null;\n /** The items in the plan's order, each with its `depth`; without them the pane shows the counts alone. */\n items: TraceTaskPlanStepItem[];\n /**\n * Top-level items of the plan, how many of them are done or do not apply, and how many are blocked: the counts of a\n * plan whose items the reader does not have. With items the pane counts their leaves.\n */\n itemCount?: number | null;\n doneCount?: number | null;\n blockedCount?: number | null;\n /** A quiet line under the title (the turn that last updated the plan). */\n note?: ReactNode;\n /**\n * Per item key, the plan update that last changed the item (`TraceTaskPlanSnapshot.itemSources`) and the one it first\n * appeared in: the times of the detail view. With `onSelectItem` the detail view leads to that step in the trace.\n */\n itemSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n itemFirstSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n onSelectItem?: (item: TraceTaskPlanStepItem, source: TraceTaskPlanItemSource) => void;\n /** Debug level: what refused plan calls told the agent (`TraceTaskPlanSnapshot.rejections`). */\n rejections?: readonly TraceTaskPlanRejection[];\n /** The detail view a host opens the pane on (a deep link); default none. */\n defaultDetail?: TaskPlanDetailTarget | null;\n className?: string;\n}\n\n/** The state of a row as `data-plan-item-state` names it (the running step is `next`, a skipped one `skipped`). */\nconst ROW_STATE_ATTRIBUTES = { done: \"done\", skipped: \"skipped\", blocked: \"blocked\", running: \"next\", open: \"open\" } as const;\n\nconst TaskPlanRow = (props: {\n node: TaskPlanTreeNode;\n isExpanded: boolean;\n isSelected: boolean;\n waitsForOwner: boolean;\n onToggle: (key: string) => void;\n onOpen: (key: string) => void;\n}) => {\n const { node, isExpanded, isSelected, waitsForOwner, onToggle, onOpen } = props;\n const { item, state } = node;\n const isContainer = node.children.length > 0;\n const indent = node.depth * 22;\n const note = !isContainer && (state === \"running\" || state === \"blocked\") ? item.statusNote : isContainer && !isExpanded ? item.statusNote : null;\n return (\n <li\n className={classNames(\n styles.row,\n !isContainer && state === \"running\" && styles.rowRunning,\n !isContainer && state === \"blocked\" && styles.rowBlocked,\n (state === \"done\" || state === \"skipped\") && styles.rowClosed,\n state === \"skipped\" && styles.rowSkipped,\n isSelected && styles.rowSelected,\n )}\n style={{ paddingLeft: `${indent}px` }}\n data-plan-item-state={ROW_STATE_ATTRIBUTES[state]}\n data-plan-item-key={node.key}\n aria-current={state === \"running\" && !isContainer ? \"step\" : undefined}\n >\n {Array.from({ length: node.depth }, (_, level) => (\n <span key={level} className={styles.guide} style={{ left: `${level * 22 + 11}px` }} aria-hidden=\"true\" />\n ))}\n {isContainer ? (\n <button\n type=\"button\"\n className={styles.toggle}\n aria-expanded={isExpanded}\n aria-label={isExpanded ? translateText(\"Fold the subtasks\") : translateText(\"Show the subtasks\")}\n onClick={() => onToggle(node.key)}\n >\n <Icon name={isExpanded ? \"chevronDown\" : \"chevronRight\"} pixelSize={13} />\n </button>\n ) : (\n <span className={styles.toggleSpacer} />\n )}\n <button type=\"button\" className={styles.rowButton} onClick={() => onOpen(node.key)} data-testid=\"trace-task-plan-row\">\n <TaskPlanMark node={node} />\n {item.numberPath ? <span className={styles.number}>{item.numberPath}</span> : null}\n <span className={styles.rowText}>\n <span className={styles.rowTitle}>{item.title}</span>\n {note ? <span className={styles.rowNote}>{note}</span> : null}\n </span>\n {isContainer ? (\n <>\n <span className={styles.part}>{`${node.closedLeafCount}/${node.leafCount}`}</span>\n <TaskPlanSegments nodes={node.children} isSmall />\n </>\n ) : null}\n {!isContainer && state === \"running\" ? (\n <span className={classNames(styles.chip, styles.chipRunning)}>\n {waitsForOwner ? translateText(\"Up next\", undefined, \"plan-item-state\") : translateText(\"In progress\")}\n </span>\n ) : null}\n {!isContainer && state === \"blocked\" && item.requiresUserAction ? (\n <span className={classNames(styles.chip, styles.chipOwner)}>{translateText(\"Waits for you\")}</span>\n ) : null}\n {!isContainer && state === \"blocked\" && !item.requiresUserAction ? (\n <span className={classNames(styles.chip, styles.chipBlocked)}>{translateText(\"Blocked\", undefined, \"plan-item-state\")}</span>\n ) : null}\n {!isContainer && state === \"skipped\" ? <span className={styles.chip}>{translateText(\"Does not apply\", undefined, \"plan-item-state\")}</span> : null}\n <Icon name=\"chevronRight\" pixelSize={12} className={styles.go} />\n </button>\n </li>\n );\n};\n\n/**\n * The task plan of a conversation as it stands, for a pane beside the chat. Its head names the plan and its progress\n * over all steps (\"6 of 9 done · step 2 of 3\", a segment per step), then the plan as a tree: every container shows its\n * part progress (\"4/5\") and folds; the path of the running step and of a blocked one is open, closed branches are\n * folded. Every item shows its state (done, does not apply, blocked — \"waits for you\" when only the owner can lift it —,\n * in progress or not started) and the note of a running or blocked step. A click on an item opens its detail view,\n * \"Plan details\" the plan's ({@link TaskPlanDrawer}): beside the tree in a wide pane, in its place in a narrow one.\n */\nexport const TaskPlanPane = (props: TaskPlanPaneProps) => {\n const { title, items, note, itemSources, itemFirstSources, onSelectItem, rejections, className } = props;\n const format = useTraceFormat();\n const tree = useMemo(() => buildTaskPlanTree(items), [items]);\n const defaultExpandedKeys = useMemo(() => readDefaultExpandedKeys(tree), [tree]);\n // the reader's own folding wins over the default per container\n const [toggledKeys, setToggledKeys] = useState<ReadonlySet<string>>(() => new Set());\n const [detail, setDetail] = useState<TaskPlanDetailTarget | null>(props.defaultDetail ?? null);\n const expandedKeys = useMemo(() => {\n const keys = new Set(defaultExpandedKeys);\n toggledKeys.forEach((key) => (keys.has(key) ? keys.delete(key) : keys.add(key)));\n return keys;\n }, [defaultExpandedKeys, toggledKeys]);\n // an item shown in the detail view that leaves the plan closes the view\n useEffect(() => {\n if (detail?.kind === \"item\" && !tree.byKey.has(detail.key)) setDetail(null);\n }, [detail, tree]);\n\n const counts =\n items.length > 0\n ? { total: tree.leafCount, done: tree.closedLeafCount, blocked: tree.blockedLeafCount, open: tree.leafCount - tree.closedLeafCount - tree.blockedLeafCount }\n : readTaskPlanCounts({ itemCount: props.itemCount, doneItemCount: props.doneCount, blockedItemCount: props.blockedCount, items });\n const progressText = describeTaskPlanProgress(counts, format);\n const visibleNodes = readVisibleNodes(tree, expandedKeys);\n const waitsForOwner = tree.nodes.some((node) => node.children.length === 0 && node.state === \"blocked\" && node.item.requiresUserAction);\n const selectedKey = detail?.kind === \"item\" ? detail.key : null;\n const isFinished = counts.total > 0 && counts.done === counts.total;\n const toggle = (key: string) =>\n setToggledKeys((previous) => {\n const next = new Set(previous);\n if (next.has(key)) next.delete(key);\n else next.add(key);\n return next;\n });\n const openItem = (key: string) => {\n // the path of an item opened in the detail view is unfolded in the tree\n setDetail({ kind: \"item\", key });\n const node = tree.byKey.get(key);\n const foldedAncestors: string[] = [];\n for (let ancestor = node?.parent ?? null; ancestor !== null; ancestor = ancestor.parent) {\n if (!expandedKeys.has(ancestor.key)) foldedAncestors.push(ancestor.key);\n }\n if (foldedAncestors.length === 0) return;\n setToggledKeys((previous) => {\n const next = new Set(previous);\n // a folded ancestor is either one the reader folded (toggled) or one folded by default: flip it\n foldedAncestors.forEach((ancestorKey) => (next.has(ancestorKey) ? next.delete(ancestorKey) : next.add(ancestorKey)));\n return next;\n });\n };\n\n return (\n <div className={classNames(styles.pane, className)} data-testid=\"trace-task-plan-pane\">\n <div className={classNames(styles.layout, detail !== null && styles.layoutWithDetail)}>\n <div className={styles.main}>\n <div className={styles.head}>\n <div className={styles.headText}>\n {/* A model that names its plan after the whole request gives a long title: two lines, the rest as tooltip. */}\n <span className={styles.title} title={title ?? undefined}>\n {title || translateText(\"Plan\")}\n </span>\n {note ? <span className={styles.sub}>{note}</span> : null}\n </div>\n <button\n type=\"button\"\n className={classNames(styles.pill, detail?.kind === \"plan\" && styles.pillOn)}\n aria-pressed={detail?.kind === \"plan\"}\n onClick={() => setDetail(detail?.kind === \"plan\" ? null : { kind: \"plan\" })}\n data-testid=\"trace-task-plan-details\"\n >\n <Icon name=\"details\" pixelSize={14} />\n {translateText(\"Plan details\")}\n </button>\n </div>\n {counts.total > 0 ? (\n <div className={styles.progress}>\n <div className={styles.progressLine}>\n <span>{progressText}</span>\n {tree.roots.length > 1 ? (\n <span className={styles.quiet}>\n {\"· \"}\n {isFinished\n ? translateText(\"Finished\")\n : translateText(\"step %current% of %total%\", {\n current: format.number(Math.min(tree.currentTopLevelPosition, tree.roots.length)),\n total: format.number(tree.roots.length),\n })}\n </span>\n ) : null}\n <span className={styles.grow} />\n {waitsForOwner ? <span className={classNames(styles.chip, styles.chipOwner)}>{translateText(\"Waits for you\")}</span> : null}\n </div>\n {items.length > 0 ? (\n <div role=\"progressbar\" aria-valuemin={0} aria-valuemax={counts.total} aria-valuenow={counts.done} aria-label={progressText}>\n <TaskPlanSegments nodes={tree.roots} />\n </div>\n ) : null}\n </div>\n ) : null}\n {visibleNodes.length > 0 ? (\n <ol className={styles.tree}>\n {visibleNodes.map((node) => (\n <TaskPlanRow\n key={node.key}\n node={node}\n isExpanded={expandedKeys.has(node.key)}\n isSelected={node.key === selectedKey}\n waitsForOwner={waitsForOwner}\n onToggle={toggle}\n onOpen={openItem}\n />\n ))}\n </ol>\n ) : null}\n </div>\n {detail !== null ? (\n <TaskPlanDrawer\n target={detail}\n tree={tree}\n title={title}\n itemSources={itemSources}\n itemFirstSources={itemFirstSources}\n rejections={rejections}\n onNavigate={(target) => (target.kind === \"item\" ? openItem(target.key) : setDetail(target))}\n onClose={() => setDetail(null)}\n onShowSource={onSelectItem ? (node, source) => onSelectItem(node.item, source) : undefined}\n />\n ) : null}\n </div>\n </div>\n );\n};\n","import type { TraceTaskPlanItemSource } from \"./trace-collect\";\n\n/** The attribute a step row carries with the server's id of its step: the anchor a plan item scrolls to. */\nexport const TRACE_STEP_ANCHOR_ATTRIBUTE = \"data-trace-step-anchor\";\n/** The attribute a turn's trace carries with its turn number: the fallback where the step's row is not drawn. */\nexport const TRACE_TURN_ANCHOR_ATTRIBUTE = \"data-trace-turn-number\";\n/** Set for a moment on the row (or turn) a plan item pointed to. */\nexport const TRACE_HIGHLIGHT_ATTRIBUTE = \"data-trace-highlighted\";\n\nconst HIGHLIGHT_DURATION_MS = 2000;\n\nconst escapeAttributeValue = (value: string): string => value.replace(/[\"\\\\]/g, \"\\\\$&\");\n\n/**\n * Scrolls to the row of the step that last changed a plan item and highlights it for a moment; where the view does not\n * draw the step (the summary view folds it away), to its turn. Answers whether anything was found.\n */\nexport const focusTraceStep = (root: ParentNode, source: TraceTaskPlanItemSource): boolean => {\n const stepElement =\n source.stepId !== null ? root.querySelector<HTMLElement>(`[${TRACE_STEP_ANCHOR_ATTRIBUTE}=\"${escapeAttributeValue(source.stepId)}\"]`) : null;\n const element = stepElement ?? root.querySelector<HTMLElement>(`[${TRACE_TURN_ANCHOR_ATTRIBUTE}=\"${source.turnNumber}\"]`);\n if (element === null) return false;\n element.scrollIntoView?.({ block: \"center\", behavior: \"smooth\" });\n element.setAttribute(TRACE_HIGHLIGHT_ATTRIBUTE, \"true\");\n setTimeout(() => element.removeAttribute(TRACE_HIGHLIGHT_ATTRIBUTE), HIGHLIGHT_DURATION_MS);\n return true;\n};\n","import type {\n ConversationFileChange,\n ConversationTraceEntityReference,\n ConversationTraceRecordChange,\n ConversationTraceTaskPlanItem,\n ConversationTurnTrace,\n} from \"../../contract/conversation-trace\";\nimport { translateText } from \"../../provider/environment\";\nimport type { BackgroundTask } from \"./BackgroundTasksList\";\nimport { readTaskPlanCounts } from \"./task-plan-counts\";\nimport { readTraceMoment, readTraceStepState, readTraceSubAgentState } from \"./trace-format\";\nimport { describeTraceBackgroundJob, isTraceBackgroundJobLabel } from \"./trace-labels\";\nimport type { TraceStepState } from \"./trace-types\";\n\n// What a pane beside the chat reads out of a conversation's turn traces: the files each turn changed, what the\n// conversation has running beside its turns (its sub-agents, its shell commands in the background), its task plan as\n// it stands, and the tool calls that changed or deleted records.\n\n/** The file changes of one turn. */\nexport interface TraceTurnFileChanges {\n turnNumber: number;\n turnMessageId: number | null;\n startedAt: string | null;\n /** The changes in the order the turn made them. */\n fileChanges: ConversationFileChange[];\n /** Distinct paths the turn changed. */\n fileCount: number;\n linesAdded: number;\n linesRemoved: number;\n}\n\n/** The turns that changed files, oldest first, each with its changes and their counts. */\nexport const collectTraceFileChangesByTurn = (turns: ConversationTurnTrace[]): TraceTurnFileChanges[] =>\n turns.flatMap((turn) => {\n const fileChanges = turn.steps.flatMap((step) => step.fileChanges);\n if (fileChanges.length === 0) return [];\n return [\n {\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n startedAt: turn.startedAt,\n fileChanges,\n fileCount: new Set(fileChanges.map((fileChange) => `${fileChange.mountKind ?? \"\"}:${fileChange.mountName ?? \"\"}:${fileChange.path}`)).size,\n linesAdded: fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesAdded ?? 0), 0),\n linesRemoved: fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesRemoved ?? 0), 0),\n },\n ];\n });\n\n/**\n * What the conversation has running beside its turns, newest first: every sub-agent (a sub-agent that ran again shows\n * once, at its newest state) and every shell command that runs in the background or still runs.\n */\nexport const collectTraceBackgroundTasks = (turns: ConversationTurnTrace[]): BackgroundTask[] => {\n const tasksByKey = new Map<string, BackgroundTask>();\n for (const turn of turns) {\n for (const step of turn.steps) {\n if (step.kind === \"SUB_AGENT\" && step.subAgent !== null) {\n const subAgent = step.subAgent;\n const newestRun = subAgent.runs[subAgent.runs.length - 1];\n const startedAt = readTraceMoment(newestRun?.startedAt);\n const finishedAt = readTraceMoment(newestRun?.finishedAt);\n const key = `subAgent:${subAgent.childConversationId ?? `${turn.turnNumber}:${step.key}`}`;\n // A later step of the same sub-agent (a continuation) replaces the earlier one and moves to the end.\n tasksByKey.delete(key);\n // A background job that runs one tool is no agent: it reads as a job and records no run time of its own.\n const isBackgroundJob = subAgent.taskKind === \"toolRun\" || isTraceBackgroundJobLabel(subAgent.taskText);\n const durationMs = startedAt !== null && finishedAt !== null ? Math.max(0, finishedAt - startedAt) : null;\n tasksByKey.set(key, {\n key,\n type: \"subAgent\",\n title: subAgent.number !== null ? `#${subAgent.number} ${subAgent.label}` : subAgent.label,\n detail: isBackgroundJob ? describeTraceBackgroundJob(subAgent.toolName ?? subAgent.taskText) : subAgent.taskText,\n state: readTraceSubAgentState(subAgent),\n startedAt: newestRun?.startedAt ?? step.startedAt,\n durationMs: durationMs === 0 ? null : durationMs,\n typeLabel: isBackgroundJob ? translateText(\"Background job\") : null,\n childConversationId: subAgent.childConversationId,\n });\n continue;\n }\n if (step.terminal === null) continue;\n const state = readTraceStepState(step);\n if (!step.terminal.isBackground && state !== \"running\") continue;\n const key = `command:${turn.turnNumber}:${step.key}`;\n tasksByKey.set(key, {\n key,\n type: \"command\",\n title: step.terminal.command ?? step.line ?? step.toolNameInWords ?? \"\",\n detail: step.terminal.cwd,\n state,\n startedAt: step.startedAt,\n durationMs: step.terminal.durationMs ?? step.durationMs,\n });\n }\n }\n return [...tasksByKey.values()].reverse();\n};\n\n/** The task plan of a conversation as its newest plan update left it. */\nexport interface TraceTaskPlanSnapshot {\n /** The turn of the plan update, and the message that started it. */\n turnNumber: number;\n turnMessageId: number | null;\n /** The key of the plan update's step in its turn. */\n stepKey: string;\n title: string | null;\n /** The items in the plan's order; empty when the trace names only the counts. */\n items: ConversationTraceTaskPlanItem[];\n itemCount: number;\n /** Top-level items that are done or do not apply; a blocked item is never one. */\n doneCount: number;\n /** Top-level items that are blocked. */\n blockedCount: number;\n /** When the plan was last updated (a server date-time). */\n updatedAt: string | null;\n /**\n * Per item key: the plan update that last changed the item (it appeared, or its status or title changed). An item\n * whose change lies before the loaded turns has none.\n */\n itemSources: Readonly<Record<string, TraceTaskPlanItemSource>>;\n /** Per item key: the plan update the item first appeared in (as it stands now: same key and title). */\n itemFirstSources: Readonly<Record<string, TraceTaskPlanItemSource>>;\n /** Debug level: what refused plan calls told the agent, oldest first (empty at the steps level). */\n rejections: readonly TraceTaskPlanRejection[];\n}\n\n/** The plan update (a `TASK_PLAN` step) that last changed an item of the plan: where the trace shows it. */\nexport interface TraceTaskPlanItemSource {\n turnNumber: number;\n turnMessageId: number | null;\n /** The key of the step in its turn. */\n stepKey: string;\n /** The id the server gives the step (the anchor of its row); null when it sends none. */\n stepId: string | null;\n /** When the plan update ran (a server date-time); null when the trace names none. */\n startedAt?: string | null;\n}\n\n/** One line a refused plan call returned to the agent, with the plan update it belongs to. */\nexport interface TraceTaskPlanRejection {\n line: string;\n /** The first item key the line names; null when it names none. */\n itemKey: string | null;\n /** The plan tool of the call (`update_task_plan`, `set_task_status`). */\n toolName: string | null;\n source: TraceTaskPlanItemSource;\n}\n\n/**\n * Per item key, the plan update that last changed the item, read over the `TASK_PLAN` steps of the turns oldest\n * first: an item that appears, or whose status or title differs from the update before, is changed by that update.\n */\nconst collectTaskPlanItemSources = (\n turns: ConversationTurnTrace[],\n): { sources: Record<string, TraceTaskPlanItemSource>; firstSources: Record<string, TraceTaskPlanItemSource>; rejections: TraceTaskPlanRejection[] } => {\n const sources: Record<string, TraceTaskPlanItemSource> = {};\n const firstSources: Record<string, TraceTaskPlanItemSource> = {};\n const rejections: TraceTaskPlanRejection[] = [];\n const previousStateByKey = new Map<string, string>();\n const titleByKey = new Map<string, string>();\n for (const turn of turns) {\n for (const step of turn.steps) {\n if (step.kind !== \"TASK_PLAN\") continue;\n const source: TraceTaskPlanItemSource = {\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n stepKey: step.key,\n stepId: step.stepId ?? null,\n startedAt: step.startedAt ?? null,\n };\n for (const rejection of step.taskPlanRejections ?? []) {\n rejections.push({ line: rejection.line, itemKey: rejection.itemKey, toolName: step.toolName ?? null, source });\n }\n for (const item of step.taskPlanItems) {\n // a key whose title changed names another item (a plan made anew): it appears again\n if (titleByKey.get(item.key) !== item.title) firstSources[item.key] = source;\n titleByKey.set(item.key, item.title);\n const state = `${item.shownStatus ?? item.status ?? \"\"}\\u0000${item.title}\\u0000${item.statusNote ?? \"\"}`;\n if (previousStateByKey.get(item.key) === state) continue;\n previousStateByKey.set(item.key, state);\n sources[item.key] = source;\n }\n }\n }\n return { sources, firstSources, rejections };\n};\n\n/**\n * The conversation's task plan after its newest plan update (the last `TASK_PLAN` step of the turns that names a plan);\n * null for a conversation without a plan among the turns. The counts are the server's where it sends them, else those\n * of the items (`readTaskPlanCounts`).\n */\nexport const collectTraceTaskPlan = (turns: ConversationTurnTrace[]): TraceTaskPlanSnapshot | null => {\n for (let turnPosition = turns.length - 1; turnPosition >= 0; turnPosition -= 1) {\n const turn = turns[turnPosition];\n for (let stepPosition = turn.steps.length - 1; stepPosition >= 0; stepPosition -= 1) {\n const step = turn.steps[stepPosition];\n if (step.kind !== \"TASK_PLAN\") continue;\n const items = step.taskPlanItems;\n if (items.length === 0 && (step.taskPlanItemCount === null || step.taskPlanItemCount <= 0)) continue;\n const itemHistory = collectTaskPlanItemSources(turns);\n const counts = readTaskPlanCounts({\n itemCount: step.taskPlanItemCount,\n openItemCount: step.taskPlanOpenItemCount,\n doneItemCount: step.taskPlanDoneItemCount,\n blockedItemCount: step.taskPlanBlockedItemCount,\n items,\n });\n return {\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n stepKey: step.key,\n title: step.taskPlanTitle,\n items,\n itemCount: counts.total,\n doneCount: counts.done,\n blockedCount: counts.blocked,\n updatedAt: step.startedAt,\n itemSources: itemHistory.sources,\n itemFirstSources: itemHistory.firstSources,\n rejections: itemHistory.rejections,\n };\n }\n }\n return null;\n};\n\n/** A tool call that changed or deleted records. */\nexport interface TraceChangedRecord {\n /** Unique among the records of the turns: the turn's number and the step's key. */\n key: string;\n turnNumber: number;\n turnMessageId: number | null;\n /** The id the server gives the step; null when it sends none. */\n stepId: string | null;\n messageId: number | null;\n toolName: string | null;\n toolNameInWords: string | null;\n /** The narrated line of the step, as the owner read it. */\n line: string | null;\n effect: \"WRITE\" | \"DELETE\";\n /** Where the call stands: `done`, `running`, `failed` (nothing was changed), or `waiting` for the owner's approval. */\n state: TraceStepState;\n startedAt: string | null;\n /** The records the call's arguments name by id. */\n entityReferences: ConversationTraceEntityReference[];\n /** The records the call created, changed or deleted, each field before and after (captured at its writes). */\n recordChanges: ConversationTraceRecordChange[];\n /** Changed records left out beyond the server's cap. */\n omittedRecordChangeCount: number;\n}\n\n/**\n * The tool calls of the turns that changed or deleted records (the effect the tool declares: `WRITE`, `DELETE`),\n * newest first. A call a gate refused never ran and is left out; a call that failed or waits for the owner's approval\n * stays, with its state. What a call changed comes with it: each record with its fields before and after the call,\n * as the server captured them at the call's own write statements (empty for a call stored before the capture).\n */\nexport const collectTraceChangedRecords = (turns: ConversationTurnTrace[]): TraceChangedRecord[] => {\n const records: TraceChangedRecord[] = [];\n for (const turn of turns) {\n for (const step of turn.steps) {\n if (step.kind !== \"TOOL_CALL\" || (step.effect !== \"WRITE\" && step.effect !== \"DELETE\") || step.isRefused) continue;\n records.push({\n key: `${turn.turnNumber}:${step.key}`,\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n stepId: step.stepId,\n messageId: step.messageId,\n toolName: step.toolName,\n toolNameInWords: step.toolNameInWords,\n line: step.line,\n effect: step.effect,\n state: readTraceStepState(step),\n startedAt: step.startedAt,\n entityReferences: step.entityReferences,\n recordChanges: step.recordChanges ?? [],\n omittedRecordChangeCount: step.omittedRecordChangeCount ?? 0,\n });\n }\n }\n return records.reverse();\n};\n","import type { CSSProperties } from \"react\";\nimport { useAgentsTexts } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Text } from \"../../provider/components\";\nimport { AgentChatActivityDots } from \"../AgentChatActivityDots/AgentChatActivityDots\";\nimport { DEFAULT_AGENT_CHAT_ACTIVITY_TIMING } from \"../controller/chat-activity-timing\";\nimport type { AgentChatActivityProps } from \"../controller/AgentChatController\";\nimport styles from \"./AgentChatActivityStack.module.scss\";\n\n/** The lines the stack keeps on screen: the newest one and about three readable ranks above it, the oldest under the mask. */\nexport const ACTIVITY_STACK_VISIBLE_LINES = 4;\n\n/** The shortest and the longest time a line takes to move up one rank; between them a quarter of the line pace. */\nconst MIN_RANK_MOVE_MS = 160;\nconst MAX_RANK_MOVE_MS = 520;\n\n/**\n * The stacked activity feed at the tail of the thread, a drop-in `ThinkingIndicator` of `AgentChat`\n * (`<AgentChat ThinkingIndicator={AgentChatActivityStack} />`): one generated sentence per tool call of the running\n * turn, the newest at the bottom at full size, the older ones drifting up, smaller and fainter under a top mask.\n * Before the first sentence it shows the calm dots and \"Working on it…\"; once a sentence is told, only sentences. It\n * fades out over the success beat when the turn ends, and shows nothing between turns or after a failed turn.\n *\n * The moving layer is decorative (`aria-hidden`); a polite status region carries the newest sentence. The motion\n * follows the chat's timing (`activityTiming`: the line pace and the success beat), stays still under\n * `prefers-reduced-motion`, and every colour comes from the `--agents-*` variables.\n */\nexport const AgentChatActivityStack = (props: AgentChatActivityProps) => {\n const { active, failed, activityTicker, activityTiming = DEFAULT_AGENT_CHAT_ACTIVITY_TIMING } = props;\n const texts = useAgentsTexts();\n const { phase, currentTurn } = activityTicker;\n const lines = currentTurn?.lines ?? [];\n const isWorking = !failed && (active || phase === \"live\");\n const isFadingOut = !failed && phase === \"done\" && lines.length > 0;\n if (!isWorking && !isFadingOut) return null;\n\n const stackedLines = lines.slice(-ACTIVITY_STACK_VISIBLE_LINES);\n const newestSentence = lines.length > 0 ? lines[lines.length - 1].line : null;\n const rankMoveMs = Math.min(MAX_RANK_MOVE_MS, Math.max(MIN_RANK_MOVE_MS, Math.round(activityTiming.linePaceMs / 4)));\n const timingStyle = {\n \"--agents-activity-stack-move-duration\": `${rankMoveMs}ms`,\n \"--agents-activity-stack-fade-duration\": `${activityTiming.successBeatMs}ms`,\n } as CSSProperties;\n\n return (\n <div\n className={classNames(styles.stack, isFadingOut && styles.fadingOut)}\n style={timingStyle}\n data-testid=\"agent-chat-activity-stack\"\n data-phase={isFadingOut ? \"done\" : \"live\"}\n >\n <div className={styles.visual} aria-hidden=\"true\">\n {stackedLines.length === 0 ? (\n <div className={styles.waiting}>\n <AgentChatActivityDots variant=\"pulse\" />\n <Text role=\"help\" color=\"--agents-fg-light\">\n Working on it…\n </Text>\n </div>\n ) : (\n <ol className={styles.lines}>\n {stackedLines.map((line, index) => {\n const rank = stackedLines.length - 1 - index;\n return (\n <li key={line.toolCallMessageId} className={styles.line} data-rank={rank}>\n <Text role=\"help\" color={rank === 0 ? \"--agents-fg\" : \"--agents-fg-light\"} translate={false} ellipsis>\n {line.line}\n </Text>\n </li>\n );\n })}\n </ol>\n )}\n </div>\n <div className={styles.statusRegion} role=\"status\" aria-live=\"polite\" data-testid=\"agent-chat-activity-stack-status\">\n {newestSentence ?? texts.translate(\"Working on it…\")}\n </div>\n </div>\n );\n};\n","import { useCallback, useEffect, useState } from \"react\";\n\n/**\n * Shared semantic-search state with a hard 700ms debounce and a minimum three-character query because every request\n * runs an LLM reranker and consumes AI credits. `enabled` mirrors whether the owning panel is open; the caller runs\n * `clearSearch` in the open handler so it renders clean immediately, while a rising-edge reset effect would flash the\n * previous session's query and results.\n */\nexport const useDebouncedSemanticSearch = <TResult>(\n fetcher: (trimmedQuery: string) => Promise<TResult[]>,\n enabled: boolean,\n) => {\n const [query, setQuery] = useState(\"\");\n const [results, setResults] = useState<TResult[] | null>(null);\n const [searching, setSearching] = useState(false);\n const trimmedQuery = query.trim();\n\n const clearSearch = useCallback(() => {\n setQuery(\"\");\n setResults(null);\n }, []);\n\n useEffect(() => {\n if (!enabled || trimmedQuery.length < 3) {\n setResults(null);\n setSearching(false);\n return;\n }\n let cancelled = false;\n setSearching(true);\n // Drop the previous query's results the moment a new search starts, so the loading skeleton shows again — the\n // same as a first search from an empty input — instead of the stale hits lingering until the new ones arrive.\n setResults(null);\n const timer = setTimeout(() => {\n void (async () => {\n try {\n const fetchedResults = await fetcher(trimmedQuery);\n if (!cancelled) {\n setResults(fetchedResults);\n }\n } catch {\n if (!cancelled) {\n setResults([]);\n }\n } finally {\n if (!cancelled) {\n setSearching(false);\n }\n }\n })();\n }, 700);\n return () => {\n cancelled = true;\n clearTimeout(timer);\n };\n }, [trimmedQuery, enabled, fetcher]);\n\n return {\n query,\n setQuery,\n trimmedQuery,\n results,\n searching,\n isSearchActive: enabled && trimmedQuery.length >= 3,\n clearSearch,\n };\n};\n","import { useCallback } from \"react\";\nimport { useAgentsConversationClient } from \"../../client/AgentsConversationClientContext\";\nimport type {\n ConversationMessageSearchHit,\n ConversationSearchGroup,\n ConversationSearchOptions,\n} from \"../../contract/conversation\";\nimport { useDebouncedSemanticSearch } from \"./use-debounced-semantic-search\";\n\n/** The size of every chat search answer: ten matches, excerpts of 420 characters. */\nconst CHAT_SEARCH_OPTIONS: ConversationSearchOptions = { limit: 10, excerptLength: 420 };\n\nexport interface ConversationMessageSearchState {\n query: string;\n setQuery: (query: string) => void;\n trimmedQuery: string;\n hits: ConversationMessageSearchHit[] | null;\n searching: boolean;\n isSearchActive: boolean;\n /** Wipe query + hits. The caller runs this in the click handler that OPENS the panel (see hook doc). */\n clearSearch: () => void;\n}\n\nexport interface ConversationsSearchState {\n query: string;\n setQuery: (query: string) => void;\n trimmedQuery: string;\n searchGroups: ConversationSearchGroup[] | null;\n searching: boolean;\n isSearchActive: boolean;\n /** Wipe query + results. The caller runs this in the click handler that OPENS the panel (see hook doc). */\n clearSearch: () => void;\n}\n\n/**\n * In-conversation \"find in this chat\" search state: the conversation client's `searchConversationMessages` returns\n * the matched hits of one conversation.\n */\nexport const useConversationMessageSearch = (\n conversationId: number,\n enabled: boolean,\n): ConversationMessageSearchState => {\n const conversationClient = useAgentsConversationClient();\n const fetchConversationMessageHits = useCallback(\n (trimmedQuery: string) =>\n conversationClient.searchConversationMessages(conversationId, trimmedQuery, CHAT_SEARCH_OPTIONS),\n [conversationClient, conversationId],\n );\n const { results: hits, ...searchState } = useDebouncedSemanticSearch<ConversationMessageSearchHit>(\n fetchConversationMessageHits,\n enabled,\n );\n\n return {\n hits,\n ...searchState,\n };\n};\n\n/**\n * Cross-conversation \"search all my chats\" state: the conversation client's `searchConversations` returns the\n * matches grouped by conversation.\n */\nexport const useConversationsSearch = (enabled: boolean): ConversationsSearchState => {\n const conversationClient = useAgentsConversationClient();\n const fetchConversationSearchGroups = useCallback(\n (trimmedQuery: string) => conversationClient.searchConversations(trimmedQuery, CHAT_SEARCH_OPTIONS),\n [conversationClient],\n );\n const { results: searchGroups, ...searchState } = useDebouncedSemanticSearch<ConversationSearchGroup>(\n fetchConversationSearchGroups,\n enabled,\n );\n\n return {\n searchGroups,\n ...searchState,\n };\n};\n","import { Button, Text, type AgentsTextReplacements } from \"../../../provider/components\";\nimport React, { useEffect, useRef } from \"react\";\nimport styles from \"./ConversationMessageInputAttachmentsErrorBox.module.scss\";\n\nexport const ERROR_BOX_AUTO_DISMISS_AFTER_MS = 5000;\n\nexport interface ConversationMessageInputAttachmentsErrorBoxProps {\n /** Validation errors of ONE invalid selection, straight from `MediaItemFile.validationErrors`. */\n errors: { text: string; replacements?: AgentsTextReplacements }[];\n onDismiss: () => void;\n /** Stories pass a short value so play-tests don't wait 5 real seconds. */\n autoDismissAfterMs?: number;\n testId?: string;\n}\n\n/**\n * The single error box above the chat input for an invalid file selection. Auto-dismisses after\n * `autoDismissAfterMs` with a visible countdown bar (CSS animation — the timeout and the bar share\n * the duration and pause/resume together), or immediately via the ✕. Hovering the box pauses the\n * countdown (timer AND bar) so the user can finish reading; leaving resumes with the remaining\n * time. The HOST re-arms it for a new invalid selection by remounting (`key` bump) — mount is the\n * only moment the timer starts.\n */\nexport const ConversationMessageInputAttachmentsErrorBox = (\n props: ConversationMessageInputAttachmentsErrorBoxProps,\n) => {\n const {\n errors,\n onDismiss,\n autoDismissAfterMs = ERROR_BOX_AUTO_DISMISS_AFTER_MS,\n testId = \"chat-input-attachments\",\n } = props;\n\n const remainingDismissMsRef = useRef(autoDismissAfterMs);\n const dismissTimeoutIdRef = useRef<number | undefined>(undefined);\n const dismissTimeoutStartedAtMsRef = useRef(0);\n\n const startDismissTimeout = () => {\n dismissTimeoutStartedAtMsRef.current = Date.now();\n dismissTimeoutIdRef.current = window.setTimeout(onDismiss, remainingDismissMsRef.current);\n };\n\n const pauseDismissTimeout = () => {\n window.clearTimeout(dismissTimeoutIdRef.current);\n remainingDismissMsRef.current -= Date.now() - dismissTimeoutStartedAtMsRef.current;\n };\n\n useEffect(() => {\n startDismissTimeout();\n return () => window.clearTimeout(dismissTimeoutIdRef.current);\n // Mount-only by design: the host re-arms via remount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div\n className={styles.errorBox}\n onMouseEnter={pauseDismissTimeout}\n onMouseLeave={startDismissTimeout}\n data-testid={`${testId}-error-box`}\n >\n <div className={styles.errorLines}>\n {errors.map((error, errorIndex) => (\n <Text key={errorIndex} role=\"caption\" color=\"var(--agents-danger-500)\" replacements={error.replacements}>\n {error.text}\n </Text>\n ))}\n </div>\n <Button\n className={styles.dismissButton}\n variant=\"muted\"\n size=\"small\"\n icon=\"close\"\n onClick={onDismiss}\n testId={`${testId}-error-box-dismiss`}\n rounded\n />\n <div\n className={styles.countdownBar}\n style={{ animationDuration: `${autoDismissAfterMs}ms` }}\n data-testid={`${testId}-error-box-countdown`}\n />\n </div>\n );\n};\n","/** A file size as the attachment card shows it (\"1.5 MB\"); the same wording as the app's file helpers. */\nexport const convertBytesToSizeString = (bytes: number): string => {\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n if (bytes === 0) {\n return \"0 Byte\";\n }\n const sizeIndex = Math.floor(Math.log(bytes) / Math.log(1024));\n return parseFloat((bytes / Math.pow(1024, sizeIndex)).toFixed(2)) + \" \" + sizes[sizeIndex];\n};\n","import { Button, ProgressBar, Text } from \"../../../provider/components\";\nimport React from \"react\";\nimport styles from \"./ConversationMessageInputAttachmentPreviewWidget.module.scss\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { convertBytesToSizeString } from \"./convert-bytes-to-size-string\";\nimport { useAgentsTexts } from \"../../../provider/AgentsProvider\";\n\nexport type ConversationMessageInputAttachmentUploadStatus = \"uploading\" | \"uploaded\" | \"failed\";\n\n/**\n * Presentational shape of one attachment above the chat input. The host's attachment state\n * (e.g. `useAgentChatAttachments`' `AgentChatAttachment`) is a superset of this.\n */\nexport type ConversationMessageInputAttachmentPreview = {\n attachmentId: string;\n /** Data-URI of the image — renders the thumbnail card. Absent → generic file card. */\n previewImageSrc?: string;\n /** Generic-card fields (image cards show the thumbnail instead). */\n fileName?: string;\n fileSizeBytes?: number;\n mimeType?: string;\n uploadStatus: ConversationMessageInputAttachmentUploadStatus;\n /** 0-100; only meaningful while `uploadStatus` is \"uploading\". */\n uploadProgressPercent: number;\n};\n\nexport interface ConversationMessageInputAttachmentPreviewWidgetProps {\n attachment: ConversationMessageInputAttachmentPreview;\n /**\n * The card's bin — the host drops the attachment (and discards its in-flight upload result). Omitted → no bin: a\n * read-only card (e.g. a sent message's echo of a non-image file).\n */\n onRemove?: () => void;\n testId?: string;\n}\n\n/**\n * One attachment card above the chat input: an image thumbnail (or a generic name/type/size card\n * for future non-image types), an upload progress bar while the media-library upload runs, a\n * failed state, and a bin that is always in view to remove it (only when the host passes `onRemove`).\n *\n * While uploading, a white caption with a black shadow sits over the image bottom:\n * \"Uploading (45%)...\" while bytes are still going out, \"Processing...\" once all bytes are sent\n * (progress 100%) but the media-library call hasn't resolved — the bar goes indeterminate for that\n * stretch. Both disappear when the upload settles.\n */\nexport const ConversationMessageInputAttachmentPreviewWidget = (\n props: ConversationMessageInputAttachmentPreviewWidgetProps,\n) => {\n const { attachment, onRemove, testId = \"chat-input-attachment\" } = props;\n const texts = useAgentsTexts();\n\n const isUploading = attachment.uploadStatus === \"uploading\";\n const hasFailed = attachment.uploadStatus === \"failed\";\n // All bytes sent, but the media-library call hasn't resolved yet.\n const isProcessingAfterUpload = isUploading && attachment.uploadProgressPercent >= 100;\n const fileTypeLabel = attachment.mimeType?.split(\"/\").pop()?.toUpperCase();\n\n return (\n <div\n className={classNames(styles.card, {\n [styles.cardFailed]: hasFailed,\n [styles.cardGenericFile]: !attachment.previewImageSrc,\n })}\n data-testid={`${testId}-card`}\n >\n {attachment.previewImageSrc ? (\n <img className={styles.thumbnail} src={attachment.previewImageSrc} alt={attachment.fileName ?? \"\"} />\n ) : (\n <div className={styles.fileFacts}>\n <Text role=\"help\" color=\"var(--agents-fg)\" textWrap=\"nowrap\" translate={false}>\n {attachment.fileName ?? \"\"}\n </Text>\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" textWrap=\"nowrap\" translate={false}>\n {[fileTypeLabel, attachment.fileSizeBytes ? convertBytesToSizeString(attachment.fileSizeBytes) : undefined]\n .filter(Boolean)\n .join(\" • \")}\n </Text>\n </div>\n )}\n {isUploading && (\n <div className={styles.uploadProgress} data-testid={`${testId}-upload-progress`}>\n <Text\n className={styles.uploadStatusCaption}\n role=\"caption\"\n color=\"var(--agents-neutral-000)\"\n replacements={{ uploadProgressPercent: `${attachment.uploadProgressPercent}%` }}\n testId={`${testId}-upload-status`}\n >\n {isProcessingAfterUpload ? \"Processing...\" : \"Uploading (%uploadProgressPercent%)...\"}\n </Text>\n <ProgressBar\n value={attachment.uploadProgressPercent}\n indeterminate={!(attachment.uploadProgressPercent > 0 && !isProcessingAfterUpload)}\n color=\"var(--agents-primary-500)\"\n height=\"4px\"\n />\n </div>\n )}\n {hasFailed && (\n <Text\n className={styles.failedCaption}\n role=\"caption\"\n color=\"var(--agents-danger-500)\"\n testId={`${testId}-failed-caption`}\n >\n Upload failed\n </Text>\n )}\n {/* Own holder because the component library's Button puts `className` on the inner <button>, not on its\n in-flow wrapper span — the holder is what actually positions the bin. */}\n {onRemove !== undefined && (\n <span className={styles.removeButtonHolder}>\n <Button\n className={styles.removeButton}\n variant=\"muted\"\n size=\"small\"\n icon=\"trash\"\n ariaLabel={texts.translate(\"Remove file\")}\n onClick={onRemove}\n testId={`${testId}-remove-button`}\n rounded\n />\n </span>\n )}\n </div>\n );\n};\n","import React from \"react\";\nimport styles from \"./ConversationMessageInputAttachmentsPreviewStrip.module.scss\";\nimport { classNames } from \"../../../provider/class-names\";\nimport {\n ConversationMessageInputAttachmentPreview,\n ConversationMessageInputAttachmentPreviewWidget,\n} from \"./ConversationMessageInputAttachmentPreviewWidget\";\n\nexport interface ConversationMessageInputAttachmentsPreviewStripProps {\n attachments: ConversationMessageInputAttachmentPreview[];\n onRemoveAttachment: (attachmentId: string) => void;\n testId?: string;\n}\n\n/**\n * Horizontal strip of attachment cards above the chat input's text area. Grows in / shrinks out\n * with the grid-rows 0fr→1fr reveal (same trick as the selection chip) instead of popping; scrolls\n * horizontally when the cards outgrow the input's width.\n */\nexport const ConversationMessageInputAttachmentsPreviewStrip = (\n props: ConversationMessageInputAttachmentsPreviewStripProps,\n) => {\n const { attachments, onRemoveAttachment, testId = \"chat-input-attachments\" } = props;\n\n return (\n <div\n className={classNames(styles.stripReveal, { [styles.stripRevealOpen]: attachments.length > 0 })}\n data-testid={`${testId}-strip`}\n >\n <div className={styles.stripRevealInner}>\n <div className={styles.strip}>\n {attachments.map((attachment) => (\n <ConversationMessageInputAttachmentPreviewWidget\n key={attachment.attachmentId}\n attachment={attachment}\n onRemove={() => onRemoveAttachment(attachment.attachmentId)}\n testId={`${testId}-${attachment.attachmentId}`}\n />\n ))}\n </div>\n </div>\n </div>\n );\n};\n"],"names":["styles","line","text","compact","collapsed","collapsedPillSizer","_","clock","title","description","replacements","Fragment","suggestions","visible","backgroundPaintedByHost","confineTopBlurBandToChatPane","messagesBottom","layout","titleSlot","root","handle","min","max","tab","classes","lines","selectConversation","chatMessages","content","note","actions","stepStyles","records","record","chip","row","part","TaskPlanRow","stack","tree","rejection","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AA,UAAA;AAAA,QAAA;AAAA,QAMF,aAAa,UACZ,oBAAC,QAAA,EAAK,WAAW,OAAO,oBACtB,UAAA;AAAA,UAAC;AAAA,UAAA;AAAA,YACC,WAAW,OAAO;AAAA,YAClB,SAAQ;AAAA,YACR,MAAK;AAAA,YACL,MAAK;AAAA,YACL,WAAW,MAAM,UAAU,aAAa;AAAA,YACxC,SAAS;AAAA,YACT,QAAQ,GAAG,MAAM;AAAA,YACjB,SAAO;AAAA,UAAA;AAAA,QAAA,EACT,CACF;AAAA,MAAA;AAAA,IAAA;AAAA,EAAA;AAIR;AC5GO,MAAM,kDAAkD,CAC7D,UACG;AACH,QAAM,EAAE,aAAa,oBAAoB,SAAS,6BAA6B;AAE/E,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAW,WAAWA,SAAO,aAAa,EAAE,CAACA,SAAO,eAAe,GAAG,YAAY,SAAS,GAAG;AAAA,MAC9F,eAAa,GAAG,MAAM;AAAA,MAEtB,UAAA,oBAAC,OAAA,EAAI,WAAWA,SAAO,kBACrB,UAAA,oBAAC,OAAA,EAAI,WAAWA,SAAO,OACpB,UAAA,YAAY,IAAI,CAAC,eAChB;AAAA,QAAC;AAAA,QAAA;AAAA,UAEC;AAAA,UACA,UAAU,MAAM,mBAAmB,WAAW,YAAY;AAAA,UAC1D,QAAQ,GAAG,MAAM,IAAI,WAAW,YAAY;AAAA,QAAA;AAAA,QAHvC,WAAW;AAAA,MAAA,CAKnB,GACH,EAAA,CACF;AAAA,IAAA;AAAA,EAAA;AAGN;"}
|
|
1
|
+
{"version":3,"file":"chat.js","sources":["../src/chat/AgentChatActivityHistory/AgentChatActivityHistory.tsx","../src/chat/AgentChatActivityDots/AgentChatActivityDots.tsx","../src/chat/AgentChatActivityIndicator/AgentChatActivityIndicator.tsx","../src/chat/ConversationClosedBar/ConversationClosedBar.tsx","../src/renderer/canvas/CanvasRestoreOnMount.tsx","../src/renderer/ConversationDeepLinkedWidget.tsx","../src/chat/ConversationMessageInput/ConversationMessageInput.tsx","../src/chat/ConversationLoadingStates.tsx","../src/renderer/markdown-contains-widget.ts","../src/chat/assistant-message-has-renderable-markdown.ts","../src/chat/ConversationMessage/ConversationMessageSystem/ConversationMessageSystemHeader/ConversationMessageSystemHeader.tsx","../src/chat/ConversationMessage/ConversationMessageSystem/ConversationMessageSystem.tsx","../src/chat/controller/turn-initiators.ts","../src/chat/ConversationMessageList/message-times.ts","../src/chat/ConversationMessage/ConversationCallMarkerChip/ConversationCallMarkerChip.tsx","../src/chat/ConversationMessage/ConversationTaskInstructionDisclosure/ConversationTaskInstructionDisclosure.tsx","../src/chat/ConversationMessage/ConversationMessageWidgets/ConversationMessageThinking/ConversationMessageThinking.tsx","../src/chat/ConversationErrorWidget/ConversationErrorWidget.tsx","../src/chat/ConversationMessageList/ConversationMessageList.tsx","../src/chat/ConversationSuggestionWidget/ConversationSuggestionWidget.tsx","../src/chat/ConversationIntroWidget/ConversationIntroWidget.tsx","../src/chat/ConversationScrollToLatestMessageButton/ConversationScrollToLatestMessageButton.tsx","../src/chat/ConversationViewBody/hooks/useIsMessagesBottomOutOfView.ts","../src/chat/ConversationViewBody/hooks/usePinQuestionOnSend.ts","../src/chat/ConversationViewBody/ConversationViewBody.tsx","../src/chat/canvas-layout.ts","../src/chat/CanvasPane/CanvasPane.tsx","../src/chat/CanvasResizeHandle/use-canvas-resize.ts","../src/chat/CanvasResizeHandle/CanvasResizeHandle.tsx","../src/chat/use-canvas-shell-transitions.ts","../src/chat/ConversationView.tsx","../src/chat/controller/merge-activity-elements.ts","../src/chat/controller/activity-ticker.ts","../src/chat/controller/use-activity-ticker.ts","../src/chat/controller/use-conversation-activity.ts","../src/chat/controller/chat-activity-timing.ts","../src/chat/controller/pending-start-request.ts","../src/chat/controller/conversation-change-signal-rules.ts","../src/chat/controller/use-conversation-live-updates.ts","../src/chat/controller/use-conversation-message-pages.ts","../src/chat/trace/running-background-jobs-context.ts","../src/chat/trace/QueuedMessageChip.tsx","../src/chat/controller/use-conversation-scroll-jump.ts","../src/renderer/detect-unrendered-widgets.ts","../src/chat/controller/use-conversation-signals.ts","../src/chat/controller/AgentChatController.tsx","../src/chat/AgentChat/AgentChat.tsx","../src/chat/trace/BackgroundTasksList.tsx","../src/chat/trace/ChangedFilesPane.tsx","../src/chat/trace/ChangeSetCard.tsx","../src/chat/trace/ChangedRecordsList.tsx","../src/chat/trace/ContextRing.tsx","../src/chat/trace/conversation-trace-loader.ts","../src/chat/trace/use-conversation-trace.ts","../src/chat/trace/ConversationChildTrace.tsx","../src/chat/trace/ConsentRequestCard.tsx","../src/chat/trace/RunningBackgroundJobLines.tsx","../src/chat/trace/RunStatusLine.tsx","../src/chat/trace/ConversationTurnTrace.tsx","../src/chat/trace/task-plan-tree.ts","../src/chat/trace/TaskPlanDrawer.tsx","../src/chat/trace/TaskPlanPane.tsx","../src/chat/trace/trace-step-focus.ts","../src/chat/trace/trace-collect.ts","../src/chat/AgentChatActivityStack/AgentChatActivityStack.tsx","../src/chat/controller/use-debounced-semantic-search.ts","../src/chat/controller/use-conversation-search.ts","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/ConversationMessageInputAttachmentsErrorBox.tsx","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/convert-bytes-to-size-string.ts","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/ConversationMessageInputAttachmentPreviewWidget.tsx","../src/chat/ConversationMessageInput/ConversationMessageInputAttachments/ConversationMessageInputAttachmentsPreviewStrip.tsx"],"sourcesContent":["import { Text } from \"../../provider/components\";\nimport type { AgentChatActivityHistoryProps } from \"../controller/AgentChatController\";\nimport styles from \"./AgentChatActivityHistory.module.scss\";\n\n/**\n * The package default of a finished turn's kept activity lines under the message that started the turn (`AgentChat`\n * with `keepActivityHistoryAfterAnswer`): one muted line per step, oldest first.\n */\nexport const AgentChatActivityHistory = (props: AgentChatActivityHistoryProps) => {\n const { turn } = props;\n if (turn === null || turn.lines.length === 0) return null;\n return (\n <div className={styles.history} data-testid=\"agent-chat-activity-history\">\n {turn.lines.map((line) => (\n <Text key={`${line.toolCallMessageId}-${line.state}`} role=\"help\" color=\"--agents-fg-light\" translate={false}>\n {line.line}\n </Text>\n ))}\n </div>\n );\n};\n","import { classNames } from \"../../provider/class-names\";\nimport styles from \"./AgentChatActivityDots.module.scss\";\n\n/** How the three dots move: `bounce` hops them in turn (the indicator's default); `pulse` only fades and grows them, calmly. */\nexport type AgentChatActivityDotsVariant = \"bounce\" | \"pulse\";\n\nexport interface AgentChatActivityDotsProps {\n /** Default `bounce`. */\n variant?: AgentChatActivityDotsVariant;\n}\n\n/**\n * The three working dots of the activity components, decorative (`aria-hidden`). Coloured by `--agents-fg-light`;\n * still under `prefers-reduced-motion`.\n */\nexport const AgentChatActivityDots = ({ variant = \"bounce\" }: AgentChatActivityDotsProps) => (\n <div\n className={classNames(styles.dots, variant === \"pulse\" ? styles.pulse : styles.bounce)}\n aria-hidden=\"true\"\n data-agents-activity-dots={variant}\n >\n <span />\n <span />\n <span />\n </div>\n);\n","import { Text } from \"../../provider/components\";\nimport { AgentChatActivityDots, type AgentChatActivityDotsVariant } from \"../AgentChatActivityDots/AgentChatActivityDots\";\nimport type { AgentChatActivityProps } from \"../controller/AgentChatController\";\nimport styles from \"./AgentChatActivityIndicator.module.scss\";\n\nexport interface AgentChatActivityIndicatorProps extends AgentChatActivityProps {\n /** How the dots move: `bounce` (the default) or the calm `pulse`. */\n dotsVariant?: AgentChatActivityDotsVariant;\n}\n\n/**\n * The package default of the agent's activity at the tail of the thread (`AgentChat`'s `ThinkingIndicator`): three\n * dots and the line the activity ticker shows right now — the step the agent works on — while a turn runs; nothing\n * between turns or after a failed one (the error card speaks then). An app with an agent avatar replaces it\n * (host application: the agent's face beside the same ticker lines). `AgentChatActivityStack` is the stacked feed.\n */\nexport const AgentChatActivityIndicator = (props: AgentChatActivityIndicatorProps) => {\n const { active, failed, activityTicker, dotsVariant = \"bounce\" } = props;\n const isWorking = !failed && (active || activityTicker.phase === \"live\");\n if (!isWorking) return null;\n const currentLines = activityTicker.currentTurn?.lines ?? [];\n const currentLine = currentLines.length > 0 ? currentLines[currentLines.length - 1].line : null;\n return (\n <div className={styles.activity} role=\"status\" aria-live=\"polite\" data-testid=\"agent-chat-activity\">\n <AgentChatActivityDots variant={dotsVariant} />\n {currentLine !== null ? (\n <Text role=\"help\" color=\"--agents-fg-light\" translate={false}>\n {currentLine}\n </Text>\n ) : (\n <Text role=\"help\" color=\"--agents-fg-light\">\n Working on it…\n </Text>\n )}\n </div>\n );\n};\n","import { Icon, Text } from \"../../provider/components\";\nimport styles from \"./ConversationClosedBar.module.scss\";\n\nexport interface ConversationClosedBarProps {\n /** The status line; a text key. Default \"This conversation is closed.\". */\n text?: string;\n}\n\n/**\n * The package default in place of the composer on a closed conversation (its run state ended it: COMPLETED or\n * CANCELLED; the server refuses further input). A status line, no action — an app that offers one replaces the bar\n * through `AgentChat`'s `inputReplacementSlot`.\n */\nexport const ConversationClosedBar = (props: ConversationClosedBarProps) => {\n const { text = \"This conversation is closed.\" } = props;\n return (\n <div className={styles.bar} data-testid=\"agent-chat-closed-bar\">\n <Icon name=\"check\" color=\"--agents-success-500\" />\n <Text>{text}</Text>\n </div>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport type { ChatMessage } from \"../../chat/chat-message\";\nimport { normalizeServerMessageToMarkdown } from \"../../chat/normalize-server-message-to-markdown\";\nimport { useConversationWidgetContext } from \"../ConversationWidgetCallbacksContext\";\nimport { conversationWidgetRegistry } from \"../conversationWidgetRegistry\";\nimport { canvasBehaviourOf, canvasKindOpenerWidgetNamesOf } from \"./canvas-behaviours\";\nimport { payloadHashOfInstanceId } from \"./canvas-state\";\nimport { StoredCanvasPointer, clearStoredCanvas, readStoredCanvas } from \"./canvasStorage\";\nimport { findWidgetFencesInMarkdown } from \"./find-widget-fences-in-markdown\";\n\nexport interface CanvasRestoreOnMountProps {\n /** The conversation the host shows. Undefined for a cold chat — nothing to restore. */\n conversationId?: number;\n /** The host's loaded messages. A message-anchored restore waits for THIS conversation's page to be in. */\n messages: ChatMessage[] | null;\n}\n\n/** Does the anchor message still carry a widget that opens this canvas — the same instance, when the id names one? */\nconst anchorMessageCarriesCanvasWidget = (\n pointer: StoredCanvasPointer,\n anchorMessage: ChatMessage,\n): boolean => {\n // The openers the widget registry declares (`opensCanvases`) and those a registered canvas kind names itself.\n const openers = new Set([\n ...conversationWidgetRegistry.widgets\n .filter((entry) => entry.opensCanvases?.includes(pointer.canvasId))\n .map((entry) => entry.name),\n ...canvasKindOpenerWidgetNamesOf(pointer.canvasId),\n ]);\n if (openers.size === 0) return false;\n const payloadHash = payloadHashOfInstanceId(pointer.instanceId);\n return findWidgetFencesInMarkdown(normalizeServerMessageToMarkdown(anchorMessage.message)).some(\n (fence) => openers.has(fence.name) && (payloadHash === undefined || fence.payloadHash === payloadHash),\n );\n};\n\n/**\n * Restores the canvas that was open in this conversation — on a reload, in a new tab, and when the customer comes\n * back to the conversation (A → B → A alike). Must render INSIDE the provider (it dispatches\n * through the context) and runs once per conversation, after the mount reset. A PAGE-anchored canvas (an app's\n * editor opened from a page) needs no message and restores as soon as the conversation id is known. A MESSAGE-anchored\n * canvas waits for the conversation's own messages and has three limits:\n * - the anchor message must be in the loaded page — otherwise the canvas is that far back and irrelevant: the pointer\n * is dropped, nothing is paged in;\n * - a `turn` canvas whose anchor message is no longer the newest assistant message is not restored — its turn is over;\n * - the anchor message must still carry a widget that opens this canvas (a stale or mangled pointer opens nothing).\n */\nexport const CanvasRestoreOnMount = ({ conversationId, messages }: CanvasRestoreOnMountProps) => {\n const { openCanvas } = useConversationWidgetContext();\n const restoredForConversationIdRef = useRef<number | undefined>(undefined);\n\n useEffect(() => {\n if (conversationId === undefined || restoredForConversationIdRef.current === conversationId) return;\n const pointer = readStoredCanvas(conversationId);\n if (pointer === null) {\n restoredForConversationIdRef.current = conversationId;\n return;\n }\n\n const restore = () =>\n openCanvas({\n canvasId: pointer.canvasId,\n instanceId: pointer.instanceId,\n anchor: pointer.anchor,\n origin: \"restoredAfterReload\",\n justDelivered: false,\n ...(pointer.createdEntityId !== undefined ? { createdEntityId: pointer.createdEntityId } : {}),\n });\n\n if (pointer.anchor.kind === \"page\") {\n restoredForConversationIdRef.current = conversationId;\n restore();\n return;\n }\n\n // Right after a switch the slice still holds the PREVIOUS conversation's messages for a beat — wait until the\n // list belongs to this conversation, or the anchor checks would read the wrong transcript.\n if (messages === null || !messages.some((message) => message.conversationId === conversationId)) return;\n restoredForConversationIdRef.current = conversationId;\n\n const anchorMessageId = pointer.anchor.messageId;\n const anchorMessage = messages.find((message) => message.id === anchorMessageId);\n const newestAssistantMessage = [...messages].reverse().find((message) => message.role === \"ASSISTANT\");\n const turnIsOver =\n canvasBehaviourOf(pointer.canvasId)?.lifetime === \"turn\" && newestAssistantMessage?.id !== anchorMessageId;\n if (anchorMessage === undefined || turnIsOver || !anchorMessageCarriesCanvasWidget(pointer, anchorMessage)) {\n clearStoredCanvas(conversationId);\n return;\n }\n restore();\n }, [conversationId, messages, openCanvas]);\n\n return null;\n};\n","import React, { useMemo } from \"react\";\nimport { resolveDeepLinkableWidget } from \"./resolve-deep-linkable-widget\";\nimport { ConversationWidgetFeatureGate } from \"./_access/ConversationWidgetFeatureGate\";\nimport { ConversationWidgetErrorBoundary } from \"./ConversationWidgetErrorBoundary\";\nimport { buildWidgetAgentSpaceKeyProps } from \"./_agent-space/widget-agent-space-key-attribute\";\n\nexport interface ConversationDeepLinkedWidgetProps {\n /** Canonical registry wire name, from `?agentWidget=` or a restored pinned canvas. Unknown / not deep-linkable → nothing renders. */\n widgetName?: string;\n /** The key of the chat's agent space, forwarded to the widget exactly as a markdown attribute would carry it. */\n agentSpaceKey?: number;\n}\n\n/**\n * Mounts ONE registered widget outside the message list — the customer opened it from a page (`?agentWidget=`). The\n * widget receives `openedByPage` (plus `interactive` / `justDelivered`), so a canvas-opening widget (an app's editor\n * widget, `ExampleWidget`) opens its canvas with origin `openedByPage` and a page anchor; nothing is written to the\n * conversation, no message and no signal. (A canvas that was open before a reload comes back through\n * `CanvasRestoreOnMount`, not through this mount.)\n *\n * Rendered with the entry's feature gate and the shared error boundary, but WITHOUT the viewport windowing of\n * {@link ConversationWidgetHost}: there is no message to scroll past here, and a windowed wrapper would unmount a\n * zero-height widget (these widgets render `null` and live entirely in the canvas), taking its canvas with it.\n */\nexport const ConversationDeepLinkedWidget = ({ widgetName, agentSpaceKey }: ConversationDeepLinkedWidgetProps) => {\n const entry = useMemo(() => resolveDeepLinkableWidget(widgetName), [widgetName]);\n if (!entry) return null;\n\n const { component: Component, featureFlag, upsellTrigger } = entry;\n const widget = <Component fresh interactive justDelivered openedByPage {...buildWidgetAgentSpaceKeyProps(agentSpaceKey)} />;\n\n return (\n <ConversationWidgetErrorBoundary widgetName={entry.name}>\n {featureFlag ? (\n <ConversationWidgetFeatureGate\n featureFlag={featureFlag}\n UpsellTrigger={upsellTrigger}\n agentSpaceKeyAttribute={agentSpaceKey}\n >\n {widget}\n </ConversationWidgetFeatureGate>\n ) : (\n widget\n )}\n </ConversationWidgetErrorBoundary>\n );\n};\n","import { Button, GlowFrame, Text, Tooltip } from \"../../provider/components\";\nimport React, {\n useRef,\n useState,\n KeyboardEvent,\n useEffect,\n useImperativeHandle,\n useLayoutEffect,\n useMemo,\n} from \"react\";\nimport styles from \"./ConversationMessageInput.module.scss\";\nimport type { ConversationAttachmentReference } from \"../../contract/conversation\";\nimport { SendMessageHandler } from \"../conversation-send-message\";\nimport { useAgentsTexts } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport { ConversationComposerWidget } from \"../../renderer/conversation-composer-widget\";\nimport { buildMessageTextWithComposerWidgets } from \"../../renderer/composer-widget-fence\";\nimport { conversationWidgetRegistry } from \"../../renderer/conversationWidgetRegistry\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetContext\";\n\n// Half the one-line compact input (8px padding + the 40px send row + 8px): fully round at rest, and the same corners\n// as it grows with the text. The glow and the input share it through --ai-border-radius.\nconst COMPACT_INPUT_RADIUS_PX = 28;\n\n/**\n * Cap on the message a user can send. Covers the longest legitimate business\n * inputs (pasted homepage copy, article drafts, menus ≈ 8k chars) while blocking\n * accidental huge dumps. Typing and pasting past it stay possible — the text is\n * never trimmed — but sending is blocked until the user edits back under the cap.\n */\nexport const MAX_MESSAGE_LENGTH = 10000;\n\n/** The character counter stays hidden until the message approaches the cap. */\nexport const CHARACTER_COUNTER_SHOWN_FROM_LENGTH = Math.floor(MAX_MESSAGE_LENGTH * 0.9);\n\n/**\n * Imperative handle so a host-owned control (e.g. the agent \"+\" menu's \"Generate image\" entry)\n * can put text into the input without owning the contentEditable itself.\n */\nexport interface ConversationMessageInputHandle {\n /** Replaces the input's text and focuses the caret at the end. */\n insertTextIntoInput: (text: string) => void;\n /** Focuses the input, the caret at the end of its text (e.g. after files were dropped on the chat). */\n focusInput?: () => void;\n}\n\nexport interface ConversationMessageInputProps {\n /**\n * Callback when a message is submitted. The text already carries every outgoing composer widget's fence;\n * `options.composerWidgets` lists the same widgets (`outgoingComposerWidgets`, then `hostComposerWidgets`).\n */\n onSendMessage?: SendMessageHandler;\n\n /**\n * Placeholder text for the input\n */\n placeholder?: string;\n\n /**\n * Whether the input is disabled\n */\n disabled?: boolean;\n\n /**\n * Theme color for the input\n */\n themeColor?: string;\n\n /**\n * One-line form: text and send button on the same row inside a pill, growing with the text. The agent dashboard's\n * input; the chat keeps the full form.\n */\n compact?: boolean;\n\n /**\n * The compact form only: the top slot takes a row of its own above the text and the start cluster stands left of the\n * text instead of in the action row. Default false: the compact layout keeps both where the full form has them.\n */\n compactStackedSlots?: boolean;\n\n /**\n * Compact only: shrunk to a small glowing pill showing one line, the placeholder or the start of a draft, its buttons\n * hidden but kept (the agent dashboard while the page is scrolled). The host expands it again on hover, focus or at the\n * top of the page.\n */\n collapsed?: boolean;\n\n /**\n * Compact only: called with the width in px the collapsed pill needs to show the whole translated placeholder on one\n * line, its side padding included, and again whenever that width changes (a font loading, another language). The\n * host gives the pill this width, so the placeholder fits in every language.\n */\n onCollapsedPillWidthChange?: (collapsedPillWidthPx: number) => void;\n\n /**\n * Whether the AI is currently processing a response\n */\n isProcessing?: boolean;\n\n /**\n * Test ID for the component\n */\n testId?: string;\n\n /**\n * Additional CSS classes to apply to the component\n */\n className?: string;\n\n /**\n * Additional CSS classes on the input's own box (the pill in the compact form), inside its glow. A host's decoration\n * drawn over the input (e.g. a host's file-drop ring) gets the input's exact size this way, and its\n * corners from `var(--ai-border-radius)`.\n */\n inputContainerClassName?: string;\n\n /**\n * Extra action controls rendered inside the input's bottom action row, left of the send button —\n * e.g. the agent model picker pill.\n */\n actionsSlot?: React.ReactNode;\n\n /**\n * Action controls pinned to the LEFT edge of the bottom action row (the `actionsSlot` cluster\n * stays right, next to the send button) — e.g. the agent \"+\" attachments menu. In the compact form with\n * `compactStackedSlots` they stand left of the text, on its row.\n */\n actionsSlotStart?: React.ReactNode;\n\n /**\n * Host-owned content rendered above the editable text area, inside the input container —\n * attachment preview cards, validation error boxes, selection chips. Each injected block owns\n * its reveal/collapse animation. In the compact form with `compactStackedSlots` it takes a row of its own above the\n * text.\n */\n topSlot?: React.ReactNode;\n\n /** Shown in place of the send button while there is nothing to send — e.g. the button that starts a voice chat. */\n sendReplacementWhenEmpty?: React.ReactNode;\n\n /** Painted behind the input, over its whole box — e.g. the voice glow of a running voice chat. */\n glowUnderlay?: React.ReactNode;\n\n /**\n * Hard send gate: blocks the send button AND Enter while true, but keeps the text editable\n * (unlike `disabled`/`isProcessing`). The host sets it e.g. while attachment uploads run.\n */\n sendDisabled?: boolean;\n\n /**\n * Uploaded media-library images that ride along in `onSendMessage`'s options object (`attachments`)\n * on the next send. Owned and cleared by the host; ConversationMessageInput only forwards them.\n */\n outgoingAttachmentImages?: ConversationAttachmentReference[];\n\n /**\n * Composer widgets the HOST holds outside the widget context (e.g. a widget built from the files the host uploaded\n * through its own control), sent exactly like `outgoingComposerWidgets`: their fences follow the\n * context's own in the message text and in `options.composerWidgets`. Owned and cleared by the host; Backspace never\n * touches them.\n */\n hostComposerWidgets?: ConversationComposerWidget[];\n\n /**\n * Composer widgets that ride along on the next send — mirrors `outgoingAttachmentImages`. On send their fences\n * are appended to the typed text (`buildMessageTextWithComposerWidgets`) and they ride along in `onSendMessage`'s\n * options object (`composerWidgets`); a widget-only send (empty typed text) is allowed. Backspace on an empty\n * input removes the last part / widget via the widget context directly (`useConversationWidgetContext`).\n */\n outgoingComposerWidgets?: ConversationComposerWidget[];\n\n /** Called right after a successful send — the host clears the composer widgets it owns. */\n onComposerWidgetsSent?: () => void;\n\n /** Imperative handle for host-owned controls to put text into the input. */\n apiRef?: React.Ref<ConversationMessageInputHandle>;\n}\n\nexport const ConversationMessageInput = (props: ConversationMessageInputProps) => {\n const {\n onSendMessage,\n placeholder = \"Ask anything\",\n disabled = false,\n isProcessing = false,\n testId = \"chat-input\",\n className,\n inputContainerClassName,\n actionsSlot,\n actionsSlotStart,\n topSlot,\n sendReplacementWhenEmpty,\n glowUnderlay,\n sendDisabled = false,\n outgoingAttachmentImages,\n hostComposerWidgets,\n outgoingComposerWidgets,\n onComposerWidgetsSent,\n apiRef,\n compact = false,\n compactStackedSlots = false,\n collapsed = false,\n onCollapsedPillWidthChange,\n } = props;\n\n const { removeComposerWidget, replaceComposerWidgetFields } = useConversationWidgetContext();\n\n const [inputValue, setInputValue] = useState(\"\");\n const inputRef = useRef<HTMLSpanElement>(null);\n const isComposingRef = useRef(false);\n // Through the texts of this subtree (an `AgentsProvider` environment's `texts`, else the app-wide ones).\n const texts = useAgentsTexts();\n const translatedPlaceholder = useMemo(() => texts.translate(placeholder), [texts, placeholder]);\n // The send button shows only an icon: its accessible name comes from the package's texts.\n const sendButtonAccessibleName = texts.translate(\"Send message\");\n const collapsedPillSizerRef = useRef<HTMLSpanElement>(null);\n const measuresCollapsedPillWidth = compact && !!onCollapsedPillWidthChange;\n const isCompactStacked = compact && compactStackedSlots;\n\n const isMessageTooLong = inputValue.length > MAX_MESSAGE_LENGTH;\n // Every composer widget the next send carries: the widget context's own, then the host's.\n const composerWidgetsToSend = [...(outgoingComposerWidgets ?? []), ...(hostComposerWidgets ?? [])];\n // Text OR at least one composer widget is enough to send (a fence-only message is allowed).\n const hasSendableContent = inputValue.trim() !== \"\" || composerWidgetsToSend.length > 0;\n\n const focusInputAtEnd = () => {\n if (!inputRef.current) return;\n inputRef.current.focus();\n const sel = window.getSelection();\n const range = document.createRange();\n range.selectNodeContents(inputRef.current);\n range.collapse(false);\n sel?.removeAllRanges();\n sel?.addRange(range);\n };\n\n const setInputText = (text: string) => {\n setInputValue(text);\n if (inputRef.current) {\n inputRef.current.textContent = text;\n focusInputAtEnd();\n }\n };\n\n useImperativeHandle(apiRef, () => ({ insertTextIntoInput: setInputText, focusInput: focusInputAtEnd }));\n\n const handleSendMessage = () => {\n const messageText = buildMessageTextWithComposerWidgets(inputValue, composerWidgetsToSend);\n if (!messageText || disabled || isProcessing || isMessageTooLong || sendDisabled) return;\n\n const accepted = onSendMessage?.(messageText, {\n attachments: outgoingAttachmentImages?.length ? outgoingAttachmentImages : undefined,\n composerWidgets: composerWidgetsToSend.length ? composerWidgetsToSend : undefined,\n });\n // A refused send (a closed conversation, a start still in flight) keeps the text and every composer widget.\n if (accepted === false) return;\n onComposerWidgetsSent?.();\n setInputValue(\"\");\n if (inputRef.current) {\n inputRef.current.textContent = \"\";\n }\n };\n\n // Backspace on an EMPTY input removes the last removable part of the last composer widget (declared via the\n // registry's `removeLastPartFromComposerWidgetFields`), or the whole widget when the entry omits it / nothing is\n // left. Mutates through the widget context directly — `outgoingComposerWidgets` only supplies the \"which\n // widget is last\" snapshot, mirroring the host-owned value ridden into the send.\n const handleBackspaceOnEmptyInput = () => {\n const widgets = outgoingComposerWidgets ?? [];\n const lastWidget = widgets[widgets.length - 1];\n if (!lastWidget) return;\n\n const entry = conversationWidgetRegistry.widgets.find((candidate) => candidate.name === lastWidget.widgetName);\n const removeLastPart = entry?.removeLastPartFromComposerWidgetFields;\n if (!removeLastPart) {\n removeComposerWidget(lastWidget.composerWidgetId);\n return;\n }\n const nextFields = removeLastPart(lastWidget.fields);\n if (nextFields === null) {\n removeComposerWidget(lastWidget.composerWidgetId);\n } else {\n replaceComposerWidgetFields(lastWidget.composerWidgetId, nextFields);\n }\n };\n\n const handleKeyPress = (e: KeyboardEvent) => {\n if (e.key === \"Enter\" && !e.shiftKey) {\n if (isComposingRef.current) return;\n e.preventDefault();\n handleSendMessage();\n return;\n }\n if (e.key === \"Backspace\" && inputValue === \"\" && (outgoingComposerWidgets?.length ?? 0) > 0) {\n e.preventDefault();\n handleBackspaceOnEmptyInput();\n }\n };\n\n const handleInput = () => {\n if (isComposingRef.current) return;\n if (!inputRef.current) return;\n setInputValue(inputRef.current.textContent || \"\");\n };\n\n const handleCompositionStart = () => {\n isComposingRef.current = true;\n };\n\n const handleCompositionEnd = () => {\n isComposingRef.current = false;\n handleInput();\n };\n\n const handleContainerMouseDown = (e: React.MouseEvent<HTMLDivElement>) => {\n const target = e.target as HTMLElement;\n // Let clicks on the editable span itself fall through — browser positions the caret at the click point.\n if (target === inputRef.current || inputRef.current?.contains(target)) return;\n // Let clicks on buttons (send, any future action buttons) fall through untouched.\n if (target.closest(\"button\")) return;\n // Dead space click: redirect focus to end of input, but only when editing is allowed.\n if (disabled || isProcessing) return;\n e.preventDefault();\n focusInputAtEnd();\n };\n\n // Before the first paint, so the pill never shows at a width that cuts the placeholder off; again when the sizer's\n // text changes width.\n useLayoutEffect(() => {\n const collapsedPillSizer = collapsedPillSizerRef.current;\n if (!collapsedPillSizer || !onCollapsedPillWidthChange) return;\n const reportCollapsedPillWidth = () =>\n onCollapsedPillWidthChange(Math.ceil(collapsedPillSizer.getBoundingClientRect().width));\n reportCollapsedPillWidth();\n const resizeObserver = new ResizeObserver(reportCollapsedPillWidth);\n resizeObserver.observe(collapsedPillSizer);\n return () => resizeObserver.disconnect();\n }, [measuresCollapsedPillWidth, onCollapsedPillWidthChange]);\n\n const wasProcessingRef = useRef(isProcessing);\n useEffect(() => {\n if (wasProcessingRef.current && !isProcessing && !disabled) {\n inputRef.current?.focus();\n }\n wasProcessingRef.current = isProcessing;\n }, [isProcessing, disabled]);\n\n useEffect(() => {\n const handlePasteEvent = (e: ClipboardEvent) => {\n e.preventDefault();\n\n // Plain text (works across modern browsers)\n const text = e.clipboardData?.getData(\"text/plain\");\n\n if (!text) {\n return;\n }\n\n // Insert text at caret position\n if (document.queryCommandSupported?.(\"insertText\")) {\n document.execCommand(\"insertText\", false, text);\n } else {\n // Fallback for newer/stricter environments\n const sel = window.getSelection();\n if (!sel || sel.rangeCount === 0) return;\n sel.deleteFromDocument();\n sel.getRangeAt(0).insertNode(document.createTextNode(text));\n sel.collapseToEnd();\n }\n // The fallback path mutates the DOM directly and fires no input event,\n // so sync state explicitly (harmless duplicate after execCommand).\n setInputValue(inputRef.current?.textContent || \"\");\n };\n const currentInput = inputRef.current;\n currentInput?.addEventListener(\"paste\", handlePasteEvent);\n\n return () => {\n currentInput?.removeEventListener(\"paste\", handlePasteEvent);\n };\n }, []);\n\n return (\n <div className={className}>\n {glowUnderlay}\n {/* Without its own base the glow takes the inherited --ai-base-color: the agent's own base colour on an agent surface, the\n category colour in an AI-extension category conversation (ConversationViewBody), the theme's AI colour\n elsewhere. */}\n <GlowFrame\n className={classNames(styles.aiGlow)}\n color={isMessageTooLong ? \"var(--agents-danger-500)\" : undefined}\n borderRadius={compact ? COMPACT_INPUT_RADIUS_PX : undefined}\n borderWidth={2}\n blurWidth={6}\n >\n <div\n className={classNames(\n styles.inputContainer,\n {\n [styles.compact]: compact,\n [styles.compactStacked]: isCompactStacked,\n [styles.compactWithActionsStart]: isCompactStacked && !!actionsSlotStart,\n [styles.collapsed]: compact && collapsed,\n },\n inputContainerClassName,\n )}\n onMouseDown={handleContainerMouseDown}\n >\n {/* Stacked compact form: one flex row, the top slot wraps onto a row of its own above it, and the start\n cluster stands left of the text instead of in the action row. */}\n {isCompactStacked && !!topSlot && <div className={styles.compactTopSlot}>{topSlot}</div>}\n {!isCompactStacked && topSlot}\n {isCompactStacked && !!actionsSlotStart && (\n <div className={styles.compactActionsStart}>{actionsSlotStart}</div>\n )}\n <span\n ref={inputRef}\n contentEditable={!(disabled || isProcessing)}\n onInput={handleInput}\n onCompositionStart={handleCompositionStart}\n onCompositionEnd={handleCompositionEnd}\n onKeyDown={handleKeyPress}\n // The placeholder shows while the input is empty, focused or not: the chat focuses the input after every\n // turn, and a focused empty input without it read as a field without purpose.\n className={`${styles.editableInput} ${!inputValue ? styles.showPlaceholder : \"\"}`}\n data-placeholder={translatedPlaceholder}\n data-testid={`${testId}-textarea`}\n ></span>\n\n {/* Meta row above the actions: the character counter lives on its own line\n so it never crowds the send/attachment buttons on small screens. */}\n {inputValue.length >= CHARACTER_COUNTER_SHOWN_FROM_LENGTH && (\n <div className={styles.statusRow}>\n <Text\n role=\"caption\"\n translate={false}\n color={isMessageTooLong ? \"var(--agents-danger-500)\" : \"var(--agents-fg-lightest)\"}\n className={styles.characterCounter}\n testId={`${testId}-character-counter`}\n >\n {`${inputValue.length.toLocaleString()} / ${MAX_MESSAGE_LENGTH.toLocaleString()}`}\n </Text>\n </div>\n )}\n\n <div className={styles.actions}>\n {!isCompactStacked && !!actionsSlotStart && <div className={styles.actionsStart}>{actionsSlotStart}</div>}\n {/* <div className={styles.buttons}> */}\n {/* TODO: Implement emoji functionality */}\n {/* <Button\n type={ButtonTypes.muted}\n onClick={() => {\n }}\n testId={`${testId}-voice-button`}\n disabled={disabled || isProcessing}\n icon={IconNames.audioMicrophone}\n rounded\n /> */}\n {/* Over the cap: send is disabled and hovering it shows the popover with the\n reason. The wrapper carries the not-allowed cursor and routes hover past\n the disabled button to the popover (see .sendBlocked in the module scss). */}\n {actionsSlot}\n {sendReplacementWhenEmpty && !hasSendableContent ? (\n sendReplacementWhenEmpty\n ) : (\n <div className={classNames(styles.ownAction, { [styles.sendBlocked]: isMessageTooLong })}>\n <Tooltip\n text={isMessageTooLong ? \"Your message is over the %maxLength% character limit\" : undefined}\n replacements={{ maxLength: MAX_MESSAGE_LENGTH.toLocaleString() }}\n placement=\"top\"\n >\n <Button\n variant={\n hasSendableContent && !isMessageTooLong && !sendDisabled ? \"shimmer\" : \"muted\"\n }\n onClick={handleSendMessage}\n icon=\"arrowUp\"\n testId={`${testId}-send-button`}\n ariaLabel={sendButtonAccessibleName}\n disabled={!hasSendableContent || disabled || isProcessing || isMessageTooLong || sendDisabled}\n size={hasSendableContent && !isMessageTooLong && !sendDisabled ? \"medium\" : undefined}\n rounded\n />\n </Tooltip>\n </div>\n )}\n {/* </div> */}\n </div>\n </div>\n </GlowFrame>\n {measuresCollapsedPillWidth && (\n <span ref={collapsedPillSizerRef} className={styles.collapsedPillSizer} aria-hidden=\"true\">\n {translatedPlaceholder}\n </span>\n )}\n </div>\n );\n};\n","import { Skeleton } from \"../provider/components\";\nimport React from \"react\";\nimport styles from \"./Conversation.module.scss\";\nimport loadingStyles from \"./ConversationLoadingStates.module.scss\";\n\nconst SKEL_RADIUS = \"var(--agents-skeleton-radius)\";\n\nexport const NoConversationLoading = () => {\n return (\n <div className={styles.extensionIntro}>\n <Skeleton className={loadingStyles.avatar} borderRadius={SKEL_RADIUS} />\n <Skeleton className={loadingStyles.title} />\n <Skeleton className={loadingStyles.subtitle} />\n <div className={styles.suggestions}>\n {Array.from({ length: 3 }, (_, index) => (\n <Skeleton key={index} className={loadingStyles.suggestionCard} borderRadius={SKEL_RADIUS} />\n ))}\n </div>\n </div>\n );\n};\n\nexport const ConversationLoading = () => {\n return (\n <div className={styles.chatMessages}>\n <Skeleton className={loadingStyles.userBubble} borderRadius={SKEL_RADIUS} />\n <div className={loadingStyles.messageHeader}>\n <Skeleton className={loadingStyles.messageAvatar} borderRadius={SKEL_RADIUS} />\n <Skeleton className={loadingStyles.messageAuthor} />\n </div>\n <Skeleton className={loadingStyles.messageBody} borderRadius={SKEL_RADIUS} />\n </div>\n );\n};\n","import { conversationWidgetRegistry, getConversationWidgetRegistryRevision } from \"./conversationWidgetRegistry\";\nimport { parseWidgetJsonObject } from \"./widget-fence-json\";\nimport { WIDGET_FENCE_LANG } from \"./widget-fence-syntax\";\nimport { resolveCanonicalWidgetName } from \"./widget-name-resolver\";\n\n/**\n * Does a message's markdown carry a widget? The conversation asks this to reset the drawer when a fresh widget message\n * arrives, and to decide whether a reloaded last message should re-open its canvas (see ConversationMessageWidgets).\n *\n * Lives in its own file rather than in `conversationWidgetRegistry.ts` so the registry stays import-free: a registry →\n * resolver import back would be a cycle whose evaluation order decides whether the app boots. The registry is read\n * lazily for the same reason (a widget can import AgentChat, which imports this file).\n */\n\nlet widgetNames: ReadonlySet<string> | undefined;\nlet widgetNamesRevision = -1;\n\n// Every registered widget name, canonical. Read lazily — see the note above and in widget-name-resolver.ts.\nconst getWidgetNames = (): ReadonlySet<string> => {\n if (widgetNames === undefined || widgetNamesRevision !== getConversationWidgetRegistryRevision()) {\n widgetNames = new Set(conversationWidgetRegistry.widgets.map((widget) => widget.name));\n widgetNamesRevision = getConversationWidgetRegistryRevision();\n }\n return widgetNames;\n};\n\n// Matches the widget name at the start of a line in the stored `::Name` form (and the `:::Name`\n// form old messages may carry); a single-colon inline node doesn't match (min two colons).\nconst WIDGET_NODE_RE = /^[ \\t]*:{2,3}([A-Za-z][\\w]*)/gm;\n\n// Fenced code blocks must not count as widgets — remark-directive never parses\n// its nodes inside them. The open-fence variant drops a still-unterminated\n// fence so streamed partial markdown doesn't match either.\nconst CLOSED_CODE_FENCE_RE = /```[\\s\\S]*?```/g;\nconst OPEN_CODE_FENCE_RE = /```[\\s\\S]*$/;\n\n// A closed ```widget fence — the agent's widget syntax (see remarkWidgetFencePlugin). Only a CLOSED fence counts:\n// a still-streaming open fence has no terminating ``` yet and must not match prematurely. Built from the shared\n// lang constant so \"``` widget\" (a space before the lang — remark accepts it) resolves the same as everywhere else.\nconst CLOSED_WIDGET_FENCE_RE = new RegExp(\"```[ \\\\t]*\" + WIDGET_FENCE_LANG + \"\\\\s*([\\\\s\\\\S]*?)```\", \"g\");\n\n/**\n * True when the markdown contains at least one widget — either a `::Name` / `:::Name` node OR a closed ```widget\n * fence whose `type` resolves to a registered widget. BOTH forms go through `resolveCanonicalWidgetName`, so a stored\n * message written as `::ExampleWidgetDirective{…}` or `{\"type\":\"ExampleWidgetDirective\"}` counts exactly like the\n * canonical `::ExampleWidget` — the drawer resets for old conversations too.\n */\nexport const markdownContainsWidget = (markdown: string): boolean => widgetNamesInMarkdown(markdown).length > 0;\n\n/**\n * The CANONICAL names of every registered widget the markdown carries, in order of appearance, one entry per\n * occurrence (both syntaxes, legacy `…Directive` spellings resolved). The message list reads it to tell a superseded\n * widget from the live one: a later message carrying a widget of the SAME name retires the earlier one's controls.\n */\nexport const widgetNamesInMarkdown = (markdown: string): string[] => {\n if (!markdown) {\n return [];\n }\n const names: string[] = [];\n for (const match of markdown.matchAll(CLOSED_WIDGET_FENCE_RE)) {\n // malformed fence body → not a renderable widget; a surplus trailing `}` / `]` is read as the backend reads it\n const parsed = parseWidgetJsonObject(match[1]);\n const type = parsed?.type;\n const canonicalName = typeof type === \"string\" ? resolveCanonicalWidgetName(type, getWidgetNames()) : null;\n if (canonicalName) {\n names.push(canonicalName);\n }\n }\n const withoutCode = markdown.replace(CLOSED_CODE_FENCE_RE, \"\").replace(OPEN_CODE_FENCE_RE, \"\");\n for (const match of withoutCode.matchAll(WIDGET_NODE_RE)) {\n const canonicalName = resolveCanonicalWidgetName(match[1], getWidgetNames());\n if (canonicalName) {\n names.push(canonicalName);\n }\n }\n return names;\n};\n","import { normalizeServerMessageToMarkdown } from \"./normalize-server-message-to-markdown\";\n\n/**\n * Whether the whole markdown is one bare JSON object with a string `type`. Normalization already fenced every\n * registered widget type, so what is left is a type no widget renders — model noise like `{\"type\":\"no-op\"}`\n * (GPT-6 Luna), never owner-facing text.\n */\nconst isBareUnknownTypeJson = (markdown: string): boolean => {\n if (!markdown.startsWith(\"{\")) return false;\n let parsed: unknown;\n try {\n parsed = JSON.parse(markdown);\n } catch {\n return false;\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n return typeof (parsed as Record<string, unknown>).type === \"string\";\n};\n\n/**\n * True when an assistant message's stored content yields markdown that actually renders something.\n *\n * Not every ASSISTANT row carries text. An agentic run persists one ASSISTANT/TEXT turn per step, and a step\n * that only called a tool stores `message: \"\"` (13 such turns in a 30-message run); a payload whose parts are\n * all blank text likewise normalizes to \"\". Such a row would render an empty markdown container that still\n * consumed a full `$x3` gap in the message list, so ConversationMessageList drops it instead — the per-turn agentic\n * trace those rows carry is the admin console's job (AgentConversationInspector), not the customer chat's.\n *\n * The null/blank short-circuit also keeps normalizeServerMessageToMarkdown's \"unrecognized message shape\"\n * console warning from firing on every one of those rows.\n */\nexport const assistantMessageHasRenderableMarkdown = (message: unknown): boolean => {\n if (message == null) return false;\n if (typeof message === \"string\" && message.trim() === \"\") return false;\n const markdown = normalizeServerMessageToMarkdown(message).trim();\n return markdown !== \"\" && !isBareUnknownTypeJson(markdown);\n};\n","import { Button, Icon, Text } from \"../../../../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity } from \"../../../chat-assistant-identity\";\nimport React, { memo, useMemo } from \"react\";\nimport styles from \"./ConversationMessageSystemHeader.module.scss\";\n\nexport interface ConversationMessageSystemHeaderProps {\n aiPromptExtensionCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantIdentity;\n onExpandContentClick?: () => void;\n isContentExpanded?: boolean;\n}\n\nexport const ConversationMessageSystemHeader = memo((props: ConversationMessageSystemHeaderProps) => {\n const { aiPromptExtensionCategory, aiPromptExtension, isContentExpanded, onExpandContentClick } = props;\n\n return (\n <div className={styles.responseHeaderLayout}>\n <div className={styles.responseHeader}>\n <span className={styles.iconContainer}>\n <Icon color=\"var(--agents-fg-on-accent)\" name=\"wizard\" />\n </span>\n <div>\n <Text role=\"help\" weight=\"bold\">\n {aiPromptExtension?.name ?? \"AI Extensions\"}\n </Text>\n {aiPromptExtensionCategory !== undefined ? (\n <Text role=\"caption\">{aiPromptExtensionCategory?.name} System</Text>\n ) : null}\n {aiPromptExtensionCategory === undefined ? (\n <Text role=\"caption\">System</Text>\n ) : null}\n </div>\n </div>\n <div className={styles.responseHeaderAction}>\n <Button\n variant=\"muted\"\n icon={isContentExpanded ? \"caretUp\" : \"caretDown\"}\n onClick={onExpandContentClick}\n />\n </div>\n </div>\n );\n});\n","import React, { memo, useState } from \"react\";\nimport type { ChatAssistantCategory } from \"../../chat-assistant-identity\";\nimport styles from \"./ConversationMessageSystem.module.scss\";\nimport { Markdown } from \"../../../provider/components\";\nimport { ConversationMessageSystemHeader } from \"./ConversationMessageSystemHeader/ConversationMessageSystemHeader\";\n\nexport interface ConversationMessageSystemProps {\n aiPromptExtensionCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantCategory;\n message: string;\n}\n\nexport const ConversationMessageSystem = memo((props: ConversationMessageSystemProps) => {\n const { aiPromptExtensionCategory, aiPromptExtension, message } = props;\n\n const [isContentExpanded, setIsContentExpanded] = useState(false);\n\n return (\n <div className={styles.responseContainer}>\n <ConversationMessageSystemHeader\n aiPromptExtensionCategory={aiPromptExtensionCategory}\n aiPromptExtension={aiPromptExtension}\n onExpandContentClick={() => setIsContentExpanded((v) => !v)}\n isContentExpanded={isContentExpanded}\n />\n\n <div style={{ display: isContentExpanded ? undefined : \"none\" }}>\n <div className={styles.responseMessage}>\n <Markdown markdown={message} />\n </div>\n </div>\n </div>\n );\n});\n","import { assistantMessageHasRenderableMarkdown } from \"../assistant-message-has-renderable-markdown\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { SIGNAL_SOURCES_THAT_OWE_NO_WORK } from \"../last-wire-message-is-unanswered-user-message\";\n\n/**\n * Whether a message can start a turn of the agent: the owner's own message, or a signal that owes work (a widget\n * click, a nudge). Tool-result reports, bookkeeping rows (ERROR, CHECKPOINT) and the signals that owe no work never\n * start one. Which of these messages did start a turn is the server's word (its trace names the message of each\n * turn); the chat offers the per-turn slot after each of them.\n */\nexport const isTurnInitiatorMessage = (message: ChatMessage): boolean => {\n if (message.messageType === \"ERROR\" || message.messageType === \"CHECKPOINT\" || message.messageType === \"TOOL_MESSAGE\") {\n return false;\n }\n if (message.messageType === \"SIGNAL\") return !SIGNAL_SOURCES_THAT_OWE_NO_WORK.includes(message.signalSource ?? \"\");\n if (message.role !== \"USER\") return false;\n if (message.messageType === \"TOOL_CALL\") return false;\n return !(message.message ?? \"\").startsWith(\"/toolresult \");\n};\n\n/** The agent's answer to the owner: an assistant text the chat shows. */\nconst isAssistantAnswer = (message: ChatMessage): boolean =>\n message.role === \"ASSISTANT\" &&\n (message.messageType === \"TEXT\" || message.messageType == null) &&\n assistantMessageHasRenderableMarkdown(message.message);\n\nexport interface TurnsInFlight {\n /** The message that started the turn in flight; null when none runs or it is not known yet. */\n liveTurnMessageId: number | null;\n /** The owner's messages sent while that turn ran, still unanswered: the agent reads them after the current step. */\n queuedMessages: ChatMessage[];\n}\n\nconst NO_TURN_IN_FLIGHT: TurnsInFlight = { liveTurnMessageId: null, queuedMessages: [] };\n\n/**\n * The turn in flight and the owner's messages queued behind it, from the loaded messages. The messages that can start\n * a turn and stand after the agent's newest answer are the candidates: the one the activity read named\n * (`namedTurnMessageId`), else the oldest of them, started the turn in flight; every owner message after it waits.\n * Nothing is in flight while no turn runs.\n */\nexport const findTurnsInFlight = (\n messages: ChatMessage[] | null,\n isTurnRunning: boolean,\n namedTurnMessageId: number | null,\n): TurnsInFlight => {\n if (!isTurnRunning || !messages?.length) return NO_TURN_IN_FLIGHT;\n let firstIndexAfterNewestAnswer = 0;\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (isAssistantAnswer(messages[index])) {\n firstIndexAfterNewestAnswer = index + 1;\n break;\n }\n }\n const candidates = messages.slice(firstIndexAfterNewestAnswer).filter(isTurnInitiatorMessage);\n if (candidates.length === 0 && namedTurnMessageId === null) {\n // A turn runs, yet every message that can start one stands before the newest answer: an answer in parts (the agent\n // wrote a line and works on, a nudge of the loop follows), or the turn the server started for an owner message\n // that arrived during the previous turn (it stands above that turn's answer). Until the activity read names the\n // turn (one read window), the newest such message holds it, so the run's status line never drops out in between.\n const newestInitiator = messages.slice(0, firstIndexAfterNewestAnswer).filter(isTurnInitiatorMessage).at(-1);\n return { liveTurnMessageId: typeof newestInitiator?.id === \"number\" ? newestInitiator.id : null, queuedMessages: [] };\n }\n const namedPosition =\n namedTurnMessageId === null ? -1 : candidates.findIndex((candidate) => candidate.id === namedTurnMessageId);\n // A turn the activity read named but whose message stands before the newest answer (an answer in parts): every\n // candidate after that answer waits behind it.\n const isNamedBeforeCandidates = namedTurnMessageId !== null && namedPosition === -1;\n const livePosition = isNamedBeforeCandidates ? -1 : Math.max(namedPosition, 0);\n const liveCandidate = isNamedBeforeCandidates ? undefined : candidates[livePosition];\n const liveTurnMessageId = isNamedBeforeCandidates ? namedTurnMessageId : typeof liveCandidate?.id === \"number\" ? liveCandidate.id : null;\n return {\n liveTurnMessageId,\n // Only the owner's own words show as queued; a signal behind the running turn has no bubble.\n queuedMessages: candidates.slice(livePosition + 1).filter((candidate) => candidate.role === \"USER\" && candidate.messageType !== \"SIGNAL\"),\n };\n};\n","import { useMemo } from \"react\";\nimport { useAgentsOwnerSettings } from \"../../provider/AgentsProvider\";\nimport { translateText } from \"../../provider/environment\";\nimport { readTraceMoment } from \"../trace/trace-format\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { isTurnInitiatorMessage } from \"../controller/turn-initiators\";\nimport { PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES } from \"../last-wire-message-is-unanswered-user-message\";\n\n/**\n * When what was written in the chat: the day separators, the time heads after a pause, the \"finished HH:MM\" under a\n * long turn's answer and the exact time of each message.\n *\n * - `turns` (B): a separator before the first message of each day (\"Today · 09:58\"; without the time when a voice chat\n * marker opens the day, it shows its own), a time head (\"10:31\") before a message that starts a turn more than\n * {@link MESSAGE_TIME_PAUSE_MS} after the message before it. The agent's own steps and run time never cause one: the\n * answer stays with its question, and a turn that took longer than the pause ends with \"finished 10:24\" under its\n * answer. The exact time of each message on hover / keyboard focus, on touch by a tap.\n * - `everyMessage` (C): `turns` plus a quiet time under every message.\n */\nexport type MessageTimesMode = \"turns\" | \"everyMessage\";\n\n/** The pause between two messages after which the next turn gets a time head, and the turn length that earns \"finished\". */\nexport const MESSAGE_TIME_PAUSE_MS = 20 * 60 * 1000;\n\n/** What stands at one message of the list (by its index); every field is absent when nothing does. */\nexport interface MessageTimeMarks {\n /** The message's moment (ms); null for a message without one (the owner's message before the server stored it). */\n moment: number | null;\n /** A day separator stands before the message; `withTime` names the time in it (\"Today · 09:58\"). */\n daySeparator?: { withTime: boolean };\n /** A time head stands before the message (a turn after a pause). */\n timeHead?: boolean;\n /** \"finished HH:MM\" stands under the message: the last answer of a turn that ran longer than the pause. */\n finishedAt?: number;\n}\n\n/** A voice chat (phone call) lifecycle marker: the list shows it as a centred chip that carries its own time. */\nexport const isCallMarkerMessage = (message: ChatMessage): boolean =>\n message.messageType === \"SIGNAL\" && PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES.includes(message.signalSource ?? \"\");\n\n/**\n * The time marks of a message list (pure). `isShown` says which messages the list renders as a row; `dayKeyOf` maps a\n * moment to its calendar day in the owner's time zone; `isTurnRunning` keeps the newest turn open (no \"finished\" before\n * it ended).\n */\nexport const buildMessageTimeMarks = (\n messages: readonly ChatMessage[],\n isShown: (message: ChatMessage) => boolean,\n dayKeyOf: (moment: number) => string,\n isTurnRunning: boolean,\n): MessageTimeMarks[] => {\n // `createdAt` is the moment; `createdDate` is a calendar date only and would read as midnight\n const marks: MessageTimeMarks[] = messages.map((message) => ({ moment: readTraceMoment(message.createdAt) }));\n let previousMoment: number | null = null;\n let previousDayKey: string | null = null;\n let turnStartedAt: number | null = null;\n let lastAnswerIndexOfTurn: number | null = null;\n const closeTurn = () => {\n if (turnStartedAt === null || lastAnswerIndexOfTurn === null) return;\n const answeredAt = marks[lastAnswerIndexOfTurn].moment;\n if (answeredAt !== null && answeredAt - turnStartedAt > MESSAGE_TIME_PAUSE_MS) marks[lastAnswerIndexOfTurn].finishedAt = answeredAt;\n };\n messages.forEach((message, index) => {\n const moment = marks[index].moment;\n if (moment === null) return;\n const isCallMarker = isCallMarkerMessage(message);\n const startsTurn = isTurnInitiatorMessage(message);\n const shown = isShown(message);\n // separators stand before a row the owner sees or before the message that started a turn (its trace follows it)\n if (shown || startsTurn || isCallMarker) {\n const dayKey = dayKeyOf(moment);\n if (dayKey !== previousDayKey) {\n marks[index].daySeparator = { withTime: !isCallMarker };\n previousDayKey = dayKey;\n } else if ((startsTurn || isCallMarker) && previousMoment !== null && moment - previousMoment > MESSAGE_TIME_PAUSE_MS) {\n // a voice chat marker is a time head of its own (it shows its time)\n if (!isCallMarker) marks[index].timeHead = true;\n }\n }\n if (startsTurn) {\n closeTurn();\n turnStartedAt = moment;\n lastAnswerIndexOfTurn = null;\n }\n if (shown && message.role === \"ASSISTANT\" && turnStartedAt !== null) lastAnswerIndexOfTurn = index;\n // every message moves the clock, the agent's tool steps too: a pause is a pause of the whole conversation\n previousMoment = moment;\n });\n if (!isTurnRunning) closeTurn();\n return marks;\n};\n\n/** The words and figures of the message times in the owner's locale and time zone. */\nexport interface MessageTimeFormat {\n /** The clock time of a moment: `09:58`. */\n time: (moment: number) => string;\n /** The exact moment with the zone: `Mo., 30. Nov. 2026, 09:58:14 MEZ`. */\n exact: (moment: number) => string;\n /** The day of a moment for a separator: `Today`, `Yesterday`, `Mo., 24. Nov.`, `24. Nov. 2025` (another year). */\n day: (moment: number) => string;\n /** The calendar day of a moment in the owner's time zone, as a key (`2026-11-30`). */\n dayKey: (moment: number) => string;\n /** \"finished 10:24\". */\n finished: (moment: number) => string;\n}\n\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/** Builds the formatters (undefined locale / zone: the runtime's). `now` is injected for tests. */\nexport const createMessageTimeFormat = (locale?: string | null, timeZone?: string | null, now: () => number = Date.now): MessageTimeFormat => {\n const localeOrDefault = locale ?? undefined;\n const zone = timeZone ?? undefined;\n const clock = new Intl.DateTimeFormat(localeOrDefault, { hour: \"2-digit\", minute: \"2-digit\", timeZone: zone });\n const exactFormat = new Intl.DateTimeFormat(localeOrDefault, {\n weekday: \"short\",\n day: \"numeric\",\n month: \"short\",\n year: \"numeric\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n timeZoneName: \"short\",\n timeZone: zone,\n });\n const dayOfThisYear = new Intl.DateTimeFormat(localeOrDefault, { weekday: \"short\", day: \"numeric\", month: \"short\", timeZone: zone });\n const dayOfAnotherYear = new Intl.DateTimeFormat(localeOrDefault, { day: \"numeric\", month: \"short\", year: \"numeric\", timeZone: zone });\n const dayKeyParts = new Intl.DateTimeFormat(\"en-CA\", { year: \"numeric\", month: \"2-digit\", day: \"2-digit\", timeZone: zone });\n const dayKey = (moment: number): string => dayKeyParts.format(moment);\n const yearOf = (moment: number): string => dayKey(moment).slice(0, 4);\n return {\n time: (moment) => clock.format(moment),\n exact: (moment) => exactFormat.format(moment),\n dayKey,\n day: (moment) => {\n const today = now();\n const key = dayKey(moment);\n if (key === dayKey(today)) return translateText(\"Today\");\n if (key === dayKey(today - DAY_MS)) return translateText(\"Yesterday\", undefined, \"chat-day\");\n return yearOf(moment) === yearOf(today) ? dayOfThisYear.format(moment) : dayOfAnotherYear.format(moment);\n },\n finished: (moment) => translateText(\"finished %time%\", { time: clock.format(moment) }, \"chat-turn-end\"),\n };\n};\n\n/** The formatters of the owner's locale and time zone (`AgentsEnvironment.useOwnerSettings`), else the runtime's. */\nexport const useMessageTimeFormat = (): MessageTimeFormat => {\n const { locale, dateLocale, timeZone } = useAgentsOwnerSettings();\n const shownLocale = dateLocale ?? locale;\n return useMemo(() => createMessageTimeFormat(shownLocale, timeZone), [shownLocale, timeZone]);\n};\n\n/** `252` → `4:12 min`: the length of a voice chat, compact as the chat's marker shows it. */\nexport const formatCallLength = (durationSeconds: number): string => {\n const safeSeconds = Math.max(0, Math.round(durationSeconds));\n const clock = `${Math.floor(safeSeconds / 60)}:${String(safeSeconds % 60).padStart(2, \"0\")}`;\n return translateText(\"%clock% min\", { clock }, \"voice-call-length\");\n};\n","import { Icon, Text } from \"../../../provider/components\";\nimport { getAgentDisplayName } from \"../../../provider/environment\";\nimport React, { memo } from \"react\";\nimport { VoiceBarsIcon } from \"./VoiceBarsIcon/VoiceBarsIcon\";\nimport styles from \"./ConversationCallMarkerChip.module.scss\";\nimport { textKey } from \"../../../provider/text-key\";\nimport { formatCallLength, useMessageTimeFormat } from \"../../ConversationMessageList/message-times\";\n\nexport interface ConversationCallMarkerChipProps {\n /** PHONE_CALL_STARTED | PHONE_CALL_ENDED — the lifecycle signal's source. */\n signalSource: string;\n /** The signal's model-visible text — carries the duration as `NNNs` and the end reason as `reason <value>`. */\n signalText: string;\n /**\n * When the signal was written (ms). Given, every marker but \"ended\" names its clock time (\"Voice chat started · 21:05\"):\n * the marker is the time head of what follows. Omitted: no time, as before.\n */\n moment?: number | null;\n}\n\ntype CallMarkerState = \"started\" | \"ended\" | \"declined\" | \"missed\" | \"notConnected\";\n\nconst MARKER_LABELS: Readonly<Record<CallMarkerState, { inApp: string; phoneLine: string }>> = {\n started: { inApp: textKey(\"Voice chat started\"), phoneLine: textKey(\"Phone call started\") },\n ended: { inApp: textKey(\"Voice chat ended\"), phoneLine: textKey(\"Phone call ended\") },\n declined: { inApp: textKey(\"You declined a voice chat with %agentName%\"), phoneLine: textKey(\"Phone call declined\") },\n missed: { inApp: textKey(\"You missed a voice chat with %agentName%\"), phoneLine: textKey(\"Phone call not answered\") },\n notConnected: { inApp: textKey(\"Voice chat did not connect\"), phoneLine: textKey(\"Phone call not answered\") },\n};\n\n/** The agent's ring the owner turned down (DECLINED) or let run out (EXPIRED, NOT_ANSWERED) is its own mark in the chat. */\nconst callMarkerStateOf = (isCallEnd: boolean, endReason: string | undefined): CallMarkerState => {\n if (!isCallEnd) return \"started\";\n if (endReason === \"DECLINED\") return \"declined\";\n if (endReason === \"EXPIRED\" || endReason === \"NOT_ANSWERED\") return \"missed\";\n if (endReason === \"FAILED\") return \"notConnected\";\n return \"ended\";\n};\n\n/**\n * Centered marker for a call's lifecycle inside the chat timeline: started, ended (with its duration), declined, missed\n * or not connected; an in-app call is a voice chat with the agent (its voice bars), a phone call keeps the phone. Rendered\n * from the otherwise user-invisible PHONE_CALL_* SIGNAL messages — the label derives from the signal source + the small text contract of AgentVoiceCall::buildLifecycleSignalText (`In-app call …` vs\n * `Phone call …`, duration `NNNs`, reason `reason <value>`); an unparsable text degrades to the plain label.\n */\nexport const ConversationCallMarkerChip = memo(({ signalSource, signalText, moment = null }: ConversationCallMarkerChipProps) => {\n const timeFormat = useMessageTimeFormat();\n const isCallEnd = signalSource === \"PHONE_CALL_ENDED\";\n const isInAppCall = signalText.startsWith(\"In-app call\");\n const endReason = /reason ([A-Za-z_-]+)/.exec(signalText)?.[1];\n const durationSeconds = /(\\d+)s\\b/.exec(signalText)?.[1];\n const markerState = callMarkerStateOf(isCallEnd, endReason);\n const markerLabel = isInAppCall ? MARKER_LABELS[markerState].inApp : MARKER_LABELS[markerState].phoneLine;\n\n return (\n <div className={styles.markerRow} data-testid=\"conversation-call-marker\">\n <span className={styles.markerChip} data-state={markerState}>\n <span className={styles.markerIcon}>\n {isInAppCall ? <VoiceBarsIcon size={16} /> : <Icon name=\"phone\" />}\n </span>\n <Text role=\"caption\" replacements={{ agentName: getAgentDisplayName() }}>\n {markerLabel}\n </Text>\n {markerState === \"ended\" && durationSeconds != null && (\n <span className={styles.markerDuration}>\n <Text role=\"caption\" translate={false}>\n {formatCallLength(Number(durationSeconds))}\n </Text>\n </span>\n )}\n {markerState !== \"ended\" && moment !== null && (\n <time className={styles.markerDuration} dateTime={new Date(moment).toISOString()} title={timeFormat.exact(moment)}>\n <Text role=\"caption\" translate={false}>\n {timeFormat.time(moment)}\n </Text>\n </time>\n )}\n </span>\n </div>\n );\n});\n","import { Button, Text } from \"../../../provider/components\";\nimport React, { useState } from \"react\";\nimport styles from \"./ConversationTaskInstructionDisclosure.module.scss\";\n\nexport interface ConversationTaskInstructionDisclosureProps {\n /** The machine-composed seed instruction of a schedule-spawned run — the full text revealed on expand. */\n instructionText: string;\n}\n\n/**\n * Replaces the owner bubble for the FIRST user message of a SCHEDULE-spawned run conversation (UX overhaul W4\n * item 19). That message is the machine-composed task instruction (the schedule's task text + the previous run's\n * outcome line, see AIConversationSchedule::composeSeedUserMessageText) — NOT something the owner typed, so an\n * owner bubble would misattribute it as the owner's own words. Collapsed by default to a muted\n * \"Show task instruction\" disclosure; expanding reveals the full instruction text for inspection.\n */\nexport const ConversationTaskInstructionDisclosure = ({\n instructionText,\n}: ConversationTaskInstructionDisclosureProps) => {\n const [expanded, setExpanded] = useState(false);\n\n return (\n <div className={styles.disclosure}>\n {expanded ? (\n <div className={styles.instructionPanel}>\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" allowNewLines translate={false}>\n {instructionText}\n </Text>\n </div>\n ) : null}\n <Button variant=\"muted\" onClick={() => setExpanded((wasExpanded) => !wasExpanded)}>\n {expanded ? \"Hide task instruction\" : \"Show task instruction\"}\n </Button>\n </div>\n );\n};\n","import { Text } from \"../../../../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity } from \"../../../chat-assistant-identity\";\nimport React, { memo, useState, useEffect } from \"react\";\nimport styles from \"./ConversationMessageThinking.module.scss\";\nimport { ConversationMessageHeader } from \"../ConversationMessageHeader/ConversationMessageHeader\";\n\nconst loadingStateMessages = [\n \"Gathering business data…\",\n \"Planning what to do…\",\n \"Working on it…\",\n \"Clarifying response…\",\n \"Almost ready…\",\n \"Something new came up…\",\n];\n\nexport interface ConversationMessageThinkingProps {\n aiPromptExtensionCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantIdentity;\n}\n\nexport const ConversationMessageThinking = memo((props: ConversationMessageThinkingProps) => {\n const { aiPromptExtensionCategory, aiPromptExtension } = props;\n const [currentIndex, setCurrentIndex] = useState(0);\n\n useEffect(() => {\n const interval = setInterval(() => {\n setCurrentIndex((prevIndex) => (prevIndex + 1) % loadingStateMessages.length);\n }, 2500);\n\n return () => clearInterval(interval);\n }, []);\n\n return (\n <div className={styles.responseContainer}>\n <ConversationMessageHeader\n aiPromptExtensionCategory={aiPromptExtensionCategory}\n aiPromptExtension={aiPromptExtension}\n />\n\n <div className={styles.thinkingMessage}>\n <div className={styles.thinkingDots}>\n <span />\n <span />\n <span />\n </div>\n <Text>{loadingStateMessages[currentIndex]}</Text>\n </div>\n </div>\n );\n});\n","import { Button, Icon, Text } from \"../../provider/components\";\nimport React, { useCallback, useMemo, useState } from \"react\";\nimport styles from \"./ConversationErrorWidget.module.scss\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport { useAgentsBudgetLimit } from \"../../provider/AgentsProvider\";\n\n/** The first day of next month as `DD.MM.YYYY` — the day a monthly budget resets. */\nconst formatFirstDayOfNextMonth = (now: Date): string => {\n const firstDayOfNextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);\n const day = String(firstDayOfNextMonth.getDate()).padStart(2, \"0\");\n const month = String(firstDayOfNextMonth.getMonth() + 1).padStart(2, \"0\");\n return `${day}.${month}.${firstDayOfNextMonth.getFullYear()}`;\n};\n\nexport interface ConversationErrorWidgetProps {\n errorType: ConversationErrorType;\n /** Retry-After seconds of the 429 — only meaningful for RATE_LIMIT; picks the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /**\n * Retry action for a generic run failure whose customer message is persisted but unanswered: the HOST decides eligibility and binds the call to ITS chat slice (the AI-extensions chat and the agent\n * widget mount this card on separate Redux partitions), so the card only renders the action when it is given one.\n * Resolves when the retry was accepted; rejects when there is nothing to retry — the card then keeps showing.\n */\n onRetry?: () => Promise<void>;\n}\n\nexport const ConversationErrorWidget = (props: ConversationErrorWidgetProps) => {\n const { errorType, rateLimitRetryAfterSeconds, onRetry } = props;\n const [retrying, setRetrying] = useState(false);\n // The app's budget: whether an upgrade lifts the limit, and the fair-use wording (resellers that present the AI\n // budget as a fair-use allowance).\n const budgetLimit = useAgentsBudgetLimit();\n const isUpSellPossible = budgetLimit.canUpgrade;\n const showFairUsageMessage = budgetLimit.showsFairUseWording;\n\n const canRetry = errorType === ConversationErrorType.AGENT_ERROR && onRetry !== undefined;\n\n const handleRetry = useCallback(async () => {\n if (!onRetry || retrying) {\n return;\n }\n setRetrying(true);\n try {\n await onRetry();\n // Accepted: the host cleared the card / flipped the thinking indicator; nothing left to do here.\n } catch (error) {\n // Rejected (nothing to retry / conversation gone / network): keep the card, re-enable the action.\n console.warn(\"Conversation retry rejected\", error);\n setRetrying(false);\n }\n }, [onRetry, retrying]);\n\n const { icon, title, description, replacements } = useMemo(() => {\n let title = \"Network error\";\n let description = \"We’re sorry, something went wrong. Please refresh the page or try again later.\";\n let replacements: Record<string, string> | undefined = undefined;\n if (errorType === ConversationErrorType.AI_BUDGET) {\n title = \"Limit reached\";\n if (showFairUsageMessage) {\n description = isUpSellPossible\n ? \"You've reached your fair use limit for this month. This limit will reset on %resetDate%, or you can upgrade now to continue without interruption.\"\n : \"You've reached your fair use limit for this month. This limit will reset on %resetDate%.\";\n replacements = { resetDate: formatFirstDayOfNextMonth(new Date()) };\n } else {\n description = isUpSellPossible\n ? \"You've reached your maximum monthly usage. This limit resets on %limitResetDate%, or you can upgrade now to continue without interruption.\"\n : \"You've reached your maximum monthly usage. This limit resets on %limitResetDate%.\";\n replacements = { limitResetDate: formatFirstDayOfNextMonth(new Date()) };\n }\n }\n if (errorType === ConversationErrorType.RATE_LIMIT) {\n title = \"Usage limit reached\";\n if (!rateLimitRetryAfterSeconds || rateLimitRetryAfterSeconds <= 90) {\n description = \"You've sent a lot of AI requests in a short time. Please wait a minute and try again.\";\n } else if (rateLimitRetryAfterSeconds <= 3600) {\n description =\n \"You've reached your AI usage limit for this hour. Please try again in about %retryAfterMinutes% minutes.\";\n replacements = { retryAfterMinutes: `${Math.ceil(rateLimitRetryAfterSeconds / 60)}` };\n } else {\n description = \"You've reached your AI usage limit for today. Please try again later.\";\n }\n }\n if (errorType === ConversationErrorType.AGENT_ERROR) {\n title = \"Something went wrong\";\n if (canRetry) {\n description = \"We’re sorry, something went wrong. Your message is saved — retry to have it answered.\";\n }\n }\n if (errorType === ConversationErrorType.CONVERSATION_CLOSED) {\n title = \"Conversation closed\";\n description = \"This conversation is completed and closed. Please start a new conversation.\";\n }\n return {\n icon: \"warning\" as const,\n title,\n description,\n replacements,\n };\n }, [errorType, isUpSellPossible, rateLimitRetryAfterSeconds, showFairUsageMessage, canRetry]);\n\n return (\n <div className={styles.errorMessageContainer}>\n <div>\n <div className={styles.errorMessageTitle}>\n <Icon name={icon} />\n <Text weight=\"bold\">{title}</Text>\n </div>\n <Text replacements={replacements}>{description}</Text>\n </div>\n {errorType === ConversationErrorType.AI_BUDGET && isUpSellPossible ? (\n <Button size=\"extraLarge\" onClick={budgetLimit.openUpgrade} variant=\"shimmer\">\n Upgrade Plan\n </Button>\n ) : null}\n {canRetry ? (\n <Button size=\"extraLarge\" onClick={handleRetry} variant=\"shimmer\" disabled={retrying}>\n Retry\n </Button>\n ) : null}\n </div>\n );\n};\n","import { classNames } from \"../../provider/class-names\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity } from \"../chat-assistant-identity\";\nimport React, { Fragment, useMemo, useRef, useState } from \"react\";\nimport {\n ConversationMessageUser,\n ConversationMessageUserTheme,\n} from \"../ConversationMessage/ConversationMessageUser/ConversationMessageUser\";\nimport { ConversationMessageWidgets } from \"../ConversationMessage/ConversationMessageWidgets/ConversationMessageWidgets\";\nimport { widgetNamesInMarkdown } from \"../../renderer/markdown-contains-widget\";\nimport { isWidgetClickSignalSource } from \"../../renderer/widget-click-signal-sources\";\nimport { normalizeServerMessageToMarkdown } from \"../normalize-server-message-to-markdown\";\nimport { assistantMessageHasRenderableMarkdown } from \"../assistant-message-has-renderable-markdown\";\nimport { lastWireMessageIsUnansweredUserMessage } from \"../last-wire-message-is-unanswered-user-message\";\nimport { ConversationMessageSystem } from \"../ConversationMessage/ConversationMessageSystem/ConversationMessageSystem\";\nimport { ConversationCallMarkerChip } from \"../ConversationMessage/ConversationCallMarkerChip/ConversationCallMarkerChip\";\nimport { ConversationTaskInstructionDisclosure } from \"../ConversationMessage/ConversationTaskInstructionDisclosure/ConversationTaskInstructionDisclosure\";\nimport { ConversationMessageThinking } from \"../ConversationMessage/ConversationMessageWidgets/ConversationMessageThinking/ConversationMessageThinking\";\nimport { ConversationErrorWidget } from \"../ConversationErrorWidget/ConversationErrorWidget\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES } from \"../last-wire-message-is-unanswered-user-message\";\nimport styles from \"../Conversation.module.scss\";\nimport timeStyles from \"./ConversationMessageTimes.module.scss\";\nimport { buildMessageTimeMarks, type MessageTimeMarks, type MessageTimesMode, useMessageTimeFormat } from \"./message-times\";\nimport { Ref, RefObject } from \"react\";\n\ninterface ConversationMessageListProps {\n className?: string;\n messages: ChatMessage[] | null;\n currentCategory?: ChatAssistantCategory;\n aiPromptExtension?: ChatAssistantIdentity;\n isDebugMode: boolean;\n aiThinking: boolean;\n /**\n * Custom node mounted at the tail of the message list instead of the default\n * (thinking-only) ConversationMessageThinking. Rendered permanently — used by\n * A host to show the animated agent face, which idles between turns.\n */\n thinkingIndicator?: React.ReactNode;\n /**\n * Hide the assistant header (icon + name + \"Assistant\") and the copy button\n * on assistant messages. Used by a host, which renders bare messages.\n */\n hideAssistantMeta?: boolean;\n /**\n * Theme for user-message bubbles. When omitted, falls back to the legacy\n * behavior: \"light\" for generic (no-agent) chat, \"default\" otherwise. A host\n * forces \"dark\".\n */\n userMessageTheme?: ConversationMessageUserTheme;\n error: ConversationErrorType | null;\n /** Retry-After seconds of a 429 quota rejection — forwarded to the error card for the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /**\n * Host-bound retry of a FAILED run. Offered on the error card only while the newest wire\n * message is the customer's own, still unanswered — the persisted message is re-driven server-side.\n */\n onRetryFailedRun?: () => Promise<void>;\n messagesBottomRef: RefObject<HTMLDivElement | null>;\n messagesListRef?: Ref<HTMLDivElement | null>;\n /**\n * Opt-in staggered fade-in of a fresh reply's markdown blocks — see useFreshMessageBlockReveal;\n * forwarded to ConversationMessageWidgets. Default off.\n */\n enableFreshMessageBlockReveal?: boolean;\n /**\n * Id of the ONE user message to render as a collapsed task-instruction disclosure instead of an owner bubble:\n * the machine-composed seed instruction of a SCHEDULE-spawned run (UX overhaul W4 item 19). The host resolves\n * the id (AgentChat: first USER message once the history is loaded to its start); undefined renders every\n * user message normally.\n */\n taskInstructionMessageId?: number;\n /**\n * Host content rendered right after one message of the thread — also after a message the list itself does not show\n * (a work signal that started an agent turn). The agent chat puts each turn's activity card under the message that\n * started the turn. The content is a row of the list's flex column, so the list's gap stands above it; the list\n * publishes that gap as `--chat-messages-gap`. Undefined (every other host) renders the rows exactly as before.\n */\n renderAfterMessage?: (message: ChatMessage) => React.ReactNode;\n /**\n * Host content beside each shown assistant message (an avatar face, 24–28 px): it stands left of the message, at its\n * top. Undefined (every other host) renders the assistant messages exactly as before.\n */\n renderAssistantAvatar?: (message: ChatMessage) => React.ReactNode;\n /** The backend refuses every widget signal of a closed conversation, so no widget renders its controls. */\n isConversationClosed?: boolean;\n /**\n * When what was written (`message-times.ts`): `turns` = day separators, a time head after a pause of 20 minutes,\n * \"finished HH:MM\" under a long turn's answer, the exact time of each message on hover / focus / tap; `everyMessage`\n * adds a quiet time under every message (a verbose view). Undefined / null: no times, as before.\n */\n messageTimes?: MessageTimesMode | null;\n}\n\n/** The interactive parts of a message: a tap on them is theirs, never the time line's. */\nconst INTERACTIVE_SELECTOR = \"a, button, input, textarea, select, summary, label, [role='button'], [contenteditable='true']\";\n\n/**\n * Whether the list renders a row for the message (the rules of `renderMessageRow`): the call markers, the owner's\n * messages (not the tool reports), the assistant's messages with text, system rows in the debug mode.\n */\nconst isMessageShownAsRow = (message: ChatMessage, isDebugMode: boolean): boolean => {\n if (message.messageType === \"SIGNAL\") return PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES.includes(message.signalSource ?? \"\");\n if (message.messageType === \"ERROR\") return false;\n if (message.role === \"USER\") return !(message.message ?? \"\").startsWith(\"/toolresult \");\n if (message.role === \"ASSISTANT\") return assistantMessageHasRenderableMarkdown(message.message);\n return message.role === \"SYSTEM\" && isDebugMode;\n};\n\nconst WIDGET_VISIBILITY_WINDOW = 15;\n\n/** The canonical widget names an assistant-role message carries (empty for every other row). */\nconst widgetNamesOfMessage = (message: ChatMessage): string[] =>\n message.role === \"ASSISTANT\" ? widgetNamesInMarkdown(normalizeServerMessageToMarkdown(message.message)) : [];\n\n/**\n * The id of the newest widget-carrying assistant-role message the owner has not answered yet — null when the newest\n * such message is followed by a USER message or by a widget-click signal (the owner moved on; its controls stay\n * read-only after a reload, as before). Walks from the end so the first widget hit is the newest.\n */\nexport const findUnansweredWidgetMessageId = (messages: ChatMessage[]): string | number | null => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message.role === \"USER\") return null;\n if (message.messageType === \"SIGNAL\" && isWidgetClickSignalSource(message.signalSource)) return null;\n if (widgetNamesOfMessage(message).length > 0) return message.id ?? null;\n }\n return null;\n};\n\n/**\n * The ids of every widget-carrying assistant-role message that a LATER assistant-role message supersedes with a\n * widget of the same name. Pure, order-based: the newest widget of a type is the live one.\n */\nexport const findSupersededWidgetMessageIds = (messages: ChatMessage[]): Set<string | number> => {\n const supersededIds = new Set<string | number>();\n const newestMessageIdByWidgetName = new Map<string, string | number>();\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message.id == null) continue;\n for (const widgetName of widgetNamesOfMessage(message)) {\n const newestMessageId = newestMessageIdByWidgetName.get(widgetName);\n if (newestMessageId === undefined) {\n newestMessageIdByWidgetName.set(widgetName, message.id);\n } else if (newestMessageId !== message.id) {\n // a second fence of the same type INSIDE one message is not a successor of itself\n supersededIds.add(message.id);\n }\n }\n }\n return supersededIds;\n};\n\nexport const ConversationMessageList = ({\n className,\n messages,\n currentCategory,\n aiPromptExtension,\n isDebugMode,\n aiThinking,\n thinkingIndicator,\n hideAssistantMeta,\n userMessageTheme,\n error,\n rateLimitRetryAfterSeconds,\n onRetryFailedRun,\n messagesBottomRef,\n messagesListRef,\n enableFreshMessageBlockReveal,\n taskInstructionMessageId,\n renderAfterMessage,\n renderAssistantAvatar,\n isConversationClosed = false,\n messageTimes = null,\n}: ConversationMessageListProps) => {\n const list = messages ?? [];\n const timeFormat = useMessageTimeFormat();\n const timeMarks = useMemo<MessageTimeMarks[] | null>(\n () =>\n messageTimes === null\n ? null\n : buildMessageTimeMarks(messages ?? [], (message) => isMessageShownAsRow(message, isDebugMode), timeFormat.dayKey, aiThinking),\n [messageTimes, messages, isDebugMode, timeFormat, aiThinking],\n );\n // Touch: the message whose time line a tap opened (one at a time; a second tap closes it).\n const [tappedTimeMessageKey, setTappedTimeMessageKey] = useState<string | number | null>(null);\n const hideWidgetsBeforeIndex = Math.max(0, list.length - WIDGET_VISIBILITY_WINDOW);\n const userTheme: ConversationMessageUserTheme =\n userMessageTheme ?? (aiPromptExtension === undefined ? \"light\" : \"default\");\n\n // Reload promotion: on resume-from-history the slice never tags messages `fresh` (those are history), so the\n // newest reply's widgets would render read-only — a customer who reloads mid-setup would find the question's\n // buttons gone. Evaluated ONCE the first time messages arrive: the newest assistant-role message that carries a\n // widget is rendered INTERACTIVE, provided the owner has not answered it yet (no later USER message, no later\n // widget-click signal). \"Newest widget-carrying\", not \"newest assistant message\": a widget a TOOL writes (e.g. a\n // confirm widget of the app's first-run setup) is indexed before the agent's own line under it, so it is never the last\n // message — and read-only it would tell the owner the match \"was already handled\" while the setup waits for that\n // very click. It is NOT rendered `justDelivered`: that flag is the one-shot side-effect gate (canvas open, draft\n // creation) and must never re-fire on a reload — a canvas that was open comes back through the canvas model's own\n // restore, not through this promotion. (Detection lives here, in the render tree — importing the widget registry\n // into the store-init slice case forms a TDZ cycle.)\n const reloadReopenMessageIdRef = useRef<string | number | null | undefined>(undefined);\n if (reloadReopenMessageIdRef.current === undefined && list.length > 0) {\n reloadReopenMessageIdRef.current = findUnansweredWidgetMessageId(list);\n }\n // A widget the owner already moved past: a LATER assistant-role message carrying a widget of the SAME type retires\n // the earlier one's controls (the newest identify widget is the live one — the owner corrected the seed, a new\n // search wrote a new widget; the superseded one must not accept a confirm for the wrong business). Recomputed as\n // the list grows, so it also applies in-session where the slice keeps the earlier message `fresh`.\n const supersededWidgetMessageIds = useMemo(() => findSupersededWidgetMessageIds(messages ?? []), [messages]);\n const renderMessageRow = (message: ChatMessage, index: number): React.ReactNode => {\n const hideWidgets = index < hideWidgetsBeforeIndex;\n // Phone-call lifecycle signals are the ONE user-visible signal kind: the timeline renders them as a\n // centered call marker chip (started / ended + duration / not reached).\n if (message.messageType === \"SIGNAL\" && PHONE_CALL_LIFECYCLE_SIGNAL_SOURCES.includes(message.signalSource ?? \"\")) {\n return (\n <ConversationCallMarkerChip\n key={message.id ?? index}\n signalSource={message.signalSource ?? \"\"}\n signalText={message.message ?? \"\"}\n moment={timeMarks?.[index]?.moment ?? null}\n />\n );\n }\n // Every OTHER out-of-band SIGNAL message (nudge, memory-conflict, widget events) is model-only —\n // never shown to the customer. Stored role=SYSTEM, so this guard precedes the role branches.\n if (message.messageType === \"SIGNAL\") return null;\n // ERROR messages carry the raw internal failure (e.g. a provider 400 with the full error body) — never shown to\n // the customer. The user-facing \"something went wrong\" is the ConversationErrorWidget below, rendered from runState=FAILED.\n if (message.messageType === \"ERROR\") return null;\n\n let messageNode: React.ReactNode = null;\n if (message.role === \"USER\") {\n // Hide tool-result reports from the chat UI (they are model-internal)\n if (message.message?.startsWith(\"/toolresult \")) return null;\n // The SCHEDULE-run seed instruction is machine-composed — render it as a collapsed disclosure, never as\n // the owner's own words (see taskInstructionMessageId).\n messageNode =\n taskInstructionMessageId != null && message.id === taskInstructionMessageId ? (\n <ConversationTaskInstructionDisclosure instructionText={message.message ?? \"\"} />\n ) : (\n <ConversationMessageUser text={message.message ?? \"\"} theme={userTheme} />\n );\n } else if (message.role === \"ASSISTANT\") {\n // A text-less assistant turn has nothing to show the customer, and rendering it anyway emits an empty\n // markdown container that still consumes a full `$x3` message-list gap. Its agentic trace fields are\n // the admin console's concern (AgentConversationInspector, its own timeline), not this chat's.\n if (!assistantMessageHasRenderableMarkdown(message.message)) return null;\n messageNode = (\n <ConversationMessageWidgets\n key={message.id}\n interactive={\n !isConversationClosed &&\n !(message.id != null && supersededWidgetMessageIds.has(message.id)) &&\n ((message.fresh ?? false) || (message.id != null && message.id === reloadReopenMessageIdRef.current))\n }\n justDelivered={message.fresh ?? false}\n aiPromptExtensionCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n message={message.message}\n messageId={message.id}\n hideWidgets={hideWidgets}\n hideAssistantMeta={hideAssistantMeta}\n enableFreshMessageBlockReveal={enableFreshMessageBlockReveal}\n />\n );\n if (renderAssistantAvatar) {\n messageNode = (\n <div key={message.id} className={styles.assistantMessageWithAvatar}>\n <div className={styles.assistantAvatar}>{renderAssistantAvatar(message)}</div>\n <div className={styles.assistantMessageBesideAvatar}>{messageNode}</div>\n </div>\n );\n }\n } else if (message.role === \"SYSTEM\" && isDebugMode) {\n messageNode = (\n <ConversationMessageSystem\n aiPromptExtensionCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n message={message.message!}\n />\n );\n }\n if (messageNode === null) return null;\n\n const rowKey = message.id ?? `pending-${message.role}-${index}`;\n const marks = timeMarks?.[index];\n const moment = marks?.moment ?? null;\n const isTimed = moment !== null && message.role !== \"SYSTEM\";\n const isTimeTapped = isTimed && tappedTimeMessageKey === rowKey;\n // Touch has no hover: a tap on the message (not on a link or a button in it) opens its time line, a second closes it.\n const handleRowClick = isTimed\n ? (event: React.MouseEvent<HTMLDivElement>) => {\n if (typeof window === \"undefined\" || !window.matchMedia?.(\"(hover: none)\").matches) return;\n if ((event.target as Element).closest?.(INTERACTIVE_SELECTOR)) return;\n if (window.getSelection?.()?.toString()) return;\n setTappedTimeMessageKey((current) => (current === rowKey ? null : rowKey));\n }\n : undefined;\n\n // `display: contents`-free anchor row carrying the message id, so search results (and any other consumer) can\n // locate a message in the DOM and scroll it into view. The row is a flex column so user bubbles keep their\n // `align-self: flex-end` right-alignment and assistant messages keep their full width.\n return (\n <div\n key={rowKey}\n className={classNames(styles.messageRow, isTimed && timeStyles.timedRow)}\n data-message-id={message.id ?? undefined}\n // Role marker so the scroll logic can locate the last USER row (the question) to pin it to the top on send.\n data-message-role={message.role}\n onClick={handleRowClick}\n >\n {messageNode}\n {isTimed && moment !== null ? (\n <>\n {/* the exact time: read by screen readers with the message, seen on hover and keyboard focus */}\n <time className={timeStyles.exactTime} dateTime={new Date(moment).toISOString()}>\n {timeFormat.exact(moment)}\n </time>\n {isTimeTapped ? (\n <span className={timeStyles.tappedTime} aria-hidden>\n {timeFormat.exact(moment)}\n </span>\n ) : messageTimes === \"everyMessage\" ? (\n <span className={timeStyles.quietTime} aria-hidden>\n {timeFormat.time(moment)}\n </span>\n ) : null}\n {marks?.finishedAt !== undefined ? (\n <span className={timeStyles.finished} aria-hidden>\n {timeFormat.finished(marks.finishedAt)}\n </span>\n ) : null}\n </>\n ) : null}\n </div>\n );\n };\n\n /** The day separator or the time head that stands before a message (the time marks), else nothing. */\n const renderTimeBefore = (index: number): React.ReactNode => {\n const marks = timeMarks?.[index];\n if (!marks || marks.moment === null) return null;\n const moment = marks.moment;\n if (marks.daySeparator) {\n return (\n <div className={timeStyles.daySeparator} role=\"separator\" data-testid=\"conversation-day-separator\">\n <span className={timeStyles.daySeparatorLabel}>\n <span className={timeStyles.daySeparatorDay}>{timeFormat.day(moment)}</span>\n {marks.daySeparator.withTime ? (\n <>\n <span className={timeStyles.daySeparatorDot} aria-hidden>\n ·\n </span>\n <span className={timeStyles.clock}>{timeFormat.time(moment)}</span>\n </>\n ) : null}\n </span>\n </div>\n );\n }\n if (marks.timeHead) {\n return (\n <div className={classNames(timeStyles.timeHead, timeStyles.clock)} role=\"separator\" data-testid=\"conversation-time-head\">\n {timeFormat.time(moment)}\n </div>\n );\n }\n return null;\n };\n\n return (\n <div className={classNames(styles.chatMessages, className)} ref={messagesListRef}>\n {list.map((message, index) =>\n renderAfterMessage || timeMarks !== null ? (\n // Keyed like the row itself and present for every row, so a node that appears after a message never\n // changes the row's position in the tree (and never remounts the message and its widgets).\n <Fragment key={message.id ?? `pending-${message.role}-${index}`}>\n {renderTimeBefore(index)}\n {renderMessageRow(message, index)}\n {renderAfterMessage?.(message)}\n </Fragment>\n ) : (\n renderMessageRow(message, index)\n ),\n )}\n {/* A custom indicator is always mounted (it idles between turns); the\n default one only appears while the agent is thinking. */}\n {thinkingIndicator ?? (\n (aiThinking ? (\n <ConversationMessageThinking\n aiPromptExtensionCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n />\n ) : null)\n )}\n\n {error !== null ? (\n <ConversationErrorWidget\n errorType={error!}\n rateLimitRetryAfterSeconds={rateLimitRetryAfterSeconds}\n onRetry={\n error === ConversationErrorType.AGENT_ERROR && lastWireMessageIsUnansweredUserMessage(messages)\n ? onRetryFailedRun\n : undefined\n }\n />\n ) : null}\n <div className={styles.messagesBottom} ref={messagesBottomRef} />\n </div>\n );\n};\n","import { Icon, InteractiveSurface, Text } from \"../../provider/components\";\nimport type { ChatAssistantOpening } from \"../chat-assistant-identity\";\nimport React from \"react\";\nimport styles from \"./ConversationSuggestionWidget.module.scss\";\nimport { classNames } from \"../../provider/class-names\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\n\nexport interface ConversationSuggestionWidgetProps {\n suggestion: ChatAssistantOpening;\n onClick?: () => void;\n testId?: string;\n}\n\nexport const ConversationSuggestionWidget = (props: ConversationSuggestionWidgetProps) => {\n const { suggestion, onClick, testId } = props;\n const { AssistantIconBadge } = useAgentsEnvironment();\n\n return (\n <InteractiveSurface hoverable className={classNames(styles.suggestionCard)} testId={testId}>\n <button type=\"button\" className={styles.suggestionCardButton} onClick={onClick}>\n {AssistantIconBadge ? (\n <AssistantIconBadge\n iconName={suggestion.iconClass ?? \"\"}\n color=\"var(--agents-fg-on-accent)\"\n backgroundColor=\"color-mix(in srgb, var(--agents-neutral-000) 20%, transparent)\"\n />\n ) : null}\n <div>\n <Text role=\"help\" weight=\"bold\" color=\"var(--agents-fg-on-accent)\">\n {suggestion.name}\n </Text>\n <Text role=\"caption\" color=\"var(--agents-fg-on-accent)\">\n {suggestion.description}\n </Text>\n </div>\n <Icon color=\"var(--agents-fg-on-accent)\" className={styles.arrowIcon} name=\"arrowRight\" />\n </button>\n </InteractiveSurface>\n );\n};\n","import { Text } from \"../../provider/components\";\nimport type { ChatAssistantIdentity, ChatAssistantOpening } from \"../chat-assistant-identity\";\nimport React from \"react\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport styles from \"../Conversation.module.scss\";\nimport { ConversationSuggestionWidget } from \"../ConversationSuggestionWidget/ConversationSuggestionWidget\";\n\ninterface ConversationIntroWidgetProps {\n aiPromptExtension: ChatAssistantIdentity;\n /** The icon class of the extension, an icon of the app's icon set. */\n aiPromptExtensionIcon: string;\n suggestions?: ChatAssistantOpening[];\n onSuggestionClick: (text: string) => void;\n}\n\nexport const ConversationIntroWidget = ({\n aiPromptExtension,\n aiPromptExtensionIcon,\n suggestions,\n onSuggestionClick,\n}: ConversationIntroWidgetProps) => {\n const { AssistantIconBadge } = useAgentsEnvironment();\n return (\n <div className={styles.extensionIntro}>\n {AssistantIconBadge ? (\n <AssistantIconBadge\n iconName={aiPromptExtensionIcon}\n color=\"var(--agents-fg-on-accent)\"\n backgroundColor=\"var(--agents-assistant-400)\"\n isLarge\n />\n ) : null}\n <Text\n role=\"intro\"\n weight=\"bold\"\n textAlign={\"center\"}\n className={styles.extensionIntroTitle}\n >\n {aiPromptExtension.name}\n </Text>\n <Text\n role=\"body\"\n textAlign={\"center\"}\n color=\"var(--agents-fg-light)\"\n className={styles.extensionIntroDescription}\n >\n {aiPromptExtension.description}\n </Text>\n <div className={styles.suggestions}>\n {suggestions?.map((suggestion, index) => (\n <ConversationSuggestionWidget\n key={\"suggestion_prop_\" + index}\n suggestion={suggestion}\n onClick={() => onSuggestionClick(suggestion.openingText!)}\n />\n ))}\n </div>\n </div>\n );\n};\n","import { Button } from \"../../provider/components\";\nimport { useAgentsTexts } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport React from \"react\";\nimport styles from \"./ConversationScrollToLatestMessageButton.module.scss\";\n\ntype ConversationScrollToLatestMessageButtonProps = {\n visible: boolean;\n onClick: () => void;\n};\n\nexport const ConversationScrollToLatestMessageButton = (props: ConversationScrollToLatestMessageButtonProps) => {\n const { visible, onClick } = props;\n // The button shows only an icon: its accessible name comes from the package's texts.\n const texts = useAgentsTexts();\n return (\n <div className={classNames(styles.scrollToLatest, visible ? styles.visible : undefined)}>\n <Button\n variant=\"muted\"\n icon=\"arrowDown\"\n rounded\n blurred\n size=\"extraLarge\"\n onClick={onClick}\n ariaLabel={texts.translate(\"Scroll to the latest message\")}\n testId=\"chat-scroll-to-latest-button\"\n />\n </div>\n );\n};\n","import { RefObject, useEffect, useState } from \"react\";\n\n/** The button appears once the messagesBottom sentinel is this far below the visible bottom edge. */\nconst SHOW_BUTTON_BELOW_FOLD_PX = 300;\n\nexport const useIsMessagesBottomOutOfView = (\n scrollContainer: HTMLDivElement | null,\n messagesList: HTMLDivElement | null,\n messagesBottomRef: RefObject<HTMLDivElement | null>,\n): boolean => {\n const [isOutOfView, setIsOutOfView] = useState(false);\n\n useEffect(() => {\n const messagesBottomSentinel = messagesBottomRef.current;\n if (!scrollContainer || !messagesBottomSentinel) {\n setIsOutOfView(false);\n return undefined;\n }\n const observer = new IntersectionObserver(\n (entries) => setIsOutOfView(!entries[entries.length - 1].isIntersecting),\n // Extends the root's bottom edge by 300px: the sentinel counts as \"in view\" until it is\n // more than 300px below the fold, so the button only appears after real scrolling up.\n { root: scrollContainer, rootMargin: `0px 0px ${SHOW_BUTTON_BELOW_FOLD_PX}px 0px` },\n );\n observer.observe(messagesBottomSentinel);\n return () => {\n observer.disconnect();\n setIsOutOfView(false);\n };\n }, [scrollContainer, messagesList, messagesBottomRef]);\n\n return isOutOfView;\n};\n","import { MutableRefObject, RefObject, useCallback, useRef } from \"react\";\n\n/**\n * The pin-question-on-send machinery of the AW-107 long-answer reading flow, extracted out of ConversationViewBody\n * so the addon lives in its own file (mirrors hooks/useIsMessagesBottomOutOfView.ts). On send, the user's\n * question is pinned to the top with empty room reserved below it and bottom-follow is suspended for the turn,\n * so the reply reveals from its beginning instead of chasing the bottom.\n *\n * Every method no-ops when `enabled` is false, so the disabled state can never leak a layout write\n * (padding-bottom) or a scroll call even if a caller forgets a gate.\n */\nexport const usePinQuestionOnSend = (options: {\n enabled: boolean;\n scrollContainer: HTMLDivElement | null;\n getMessagesListEl: () => HTMLElement | null;\n messagesBottomRef: RefObject<HTMLDivElement | null>;\n /** ConversationViewBody's followBottom ref — pinning suspends bottom-follow for the turn. */\n followBottomRef: MutableRefObject<boolean>;\n}) => {\n const { enabled, scrollContainer, getMessagesListEl, messagesBottomRef, followBottomRef } = options;\n\n // While a turn's question is pinned at the top (from send until the next send / a manual scroll / a conversation\n // switch), we reserve empty room below it and stop chasing the bottom, so the reply flows in from its beginning.\n const questionPinnedThisTurn = useRef(false);\n\n const lastUserMessageRow = useCallback((): HTMLElement | null => {\n const list = getMessagesListEl();\n if (!list) return null;\n const rows = list.querySelectorAll<HTMLElement>('[data-message-role=\"USER\"]');\n return rows[rows.length - 1] ?? null;\n }, [getMessagesListEl]);\n\n const userMessageRowCount = useCallback((): number => {\n const list = getMessagesListEl();\n return list ? list.querySelectorAll('[data-message-role=\"USER\"]').length : 0;\n }, [getMessagesListEl]);\n\n // Reserve just enough empty room below the question that it can be scrolled fully to the top; the room shrinks to 0\n // once the reply alone fills the viewport. Pure layout write — no scrolling here.\n const reserveRoomBelowQuestion = useCallback(\n (questionRow: HTMLElement) => {\n const container = scrollContainer;\n const list = getMessagesListEl();\n const bottomMarker = messagesBottomRef.current;\n if (!container || !list || !bottomMarker) return;\n const topClearance = parseFloat(getComputedStyle(questionRow).scrollMarginTop) || 0;\n const realBelow = bottomMarker.offsetTop - questionRow.offsetTop; // question + reply/thinking so far\n const reserved = Math.max(0, container.clientHeight - topClearance - realBelow);\n list.style.paddingBottom = `${reserved}px`;\n },\n [scrollContainer, getMessagesListEl, messagesBottomRef],\n );\n\n // Pin the latest question row to the top and hand the space below to the reply. Returns false (no-op) when the\n // addon is disabled or there is no USER row to pin.\n const pinLatestQuestionToTop = useCallback(\n (behavior: ScrollBehavior): boolean => {\n if (!enabled) return false;\n const questionRow = lastUserMessageRow();\n if (!questionRow) return false;\n reserveRoomBelowQuestion(questionRow); // reserve first, so there's room to lift the question all the way up\n questionRow.scrollIntoView({ behavior, block: \"start\", inline: \"nearest\" });\n followBottomRef.current = false;\n questionPinnedThisTurn.current = true;\n return true;\n },\n [enabled, lastUserMessageRow, reserveRoomBelowQuestion, followBottomRef],\n );\n\n // Re-reserve room below the pinned question; no-op when disabled or not pinned. Used by the positioning layout\n // effect and the ResizeObserver as the reply grows.\n const reserveRoomBelowPinnedQuestion = useCallback(() => {\n if (!enabled || !questionPinnedThisTurn.current) return;\n const questionRow = lastUserMessageRow();\n if (questionRow) reserveRoomBelowQuestion(questionRow);\n }, [enabled, lastUserMessageRow, reserveRoomBelowQuestion]);\n\n const isQuestionPinnedThisTurn = useCallback(() => questionPinnedThisTurn.current, []);\n\n // Clear the pin + remove the reserved padding-bottom (conversation switch, scroll-to-latest).\n const endPinnedTurn = useCallback(() => {\n if (!enabled) return;\n questionPinnedThisTurn.current = false;\n getMessagesListEl()?.style.removeProperty(\"padding-bottom\");\n }, [enabled, getMessagesListEl]);\n\n return {\n pinLatestQuestionToTop,\n reserveRoomBelowPinnedQuestion,\n isQuestionPinnedThisTurn,\n endPinnedTurn,\n userMessageRowCount,\n };\n};\n","import { Text } from \"../../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity, ChatAssistantOpening } from \"../chat-assistant-identity\";\nimport { classNames } from \"../../provider/class-names\";\nimport React, { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport styles from \"./ConversationViewBody.module.scss\";\nimport {\n ConversationMessageInput,\n ConversationMessageInputHandle,\n} from \"../ConversationMessageInput/ConversationMessageInput\";\nimport { ConversationMessageInputComposerWidgets } from \"../ConversationMessageInput/ConversationMessageInputComposerWidgets/ConversationMessageInputComposerWidgets\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetContext\";\nimport type { ConversationAttachmentReference } from \"../../contract/conversation\";\nimport type { ConversationComposerWidget } from \"../../renderer/conversation-composer-widget\";\nimport { SendMessageHandler } from \"../conversation-send-message\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { NoConversationLoading, ConversationLoading } from \"../ConversationLoadingStates\";\nimport { ConversationMessageList } from \"../ConversationMessageList/ConversationMessageList\";\nimport type { MessageTimesMode } from \"../ConversationMessageList/message-times\";\nimport { WidgetWindowRootContext } from \"../../renderer/widget-windowing\";\nimport { ConversationIntroWidget } from \"../ConversationIntroWidget/ConversationIntroWidget\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport { ConversationMessageUserTheme } from \"../ConversationMessage/ConversationMessageUser/ConversationMessageUser\";\nimport { ConversationScrollToLatestMessageButton } from \"../ConversationScrollToLatestMessageButton/ConversationScrollToLatestMessageButton\";\nimport { useIsMessagesBottomOutOfView } from \"./hooks/useIsMessagesBottomOutOfView\";\nimport { usePinQuestionOnSend } from \"./hooks/usePinQuestionOnSend\";\n\nexport interface ConversationViewProps {\n currentCategory?: ChatAssistantCategory; // Type from categories\n aiPromptExtension?: ChatAssistantIdentity; // Type from agents\n suggestions?: ChatAssistantOpening[]; // Type from conversationOpenings\n messages: ChatMessage[] | null; // Type from messages\n aiThinking: boolean;\n error: ConversationErrorType | null;\n /** Retry-After seconds of a 429 quota rejection — forwarded to the error card for the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /** Host-bound retry of a FAILED run — forwarded to the message list / error card. */\n onRetryFailedRun?: () => Promise<void>;\n isDebugMode: boolean;\n categoriesLoaded: boolean;\n conversationId?: number;\n startingNewConversation?: boolean;\n /**\n * Show the message list even when no conversation exists yet. Used by a host,\n * whose fresh (not-yet-created) chat renders its empty message list.\n */\n showMessagesWithoutConversation?: boolean;\n /**\n * Follow the conversation bottom (scroll-on-mount + resize follow). Default true.\n * A host disables it for a fresh chat that has no messages yet, so the view stays\n * anchored at the top.\n */\n autoScroll?: boolean;\n /**\n * Custom node mounted at the tail of the message list instead of the default\n * (thinking-only) ConversationMessageThinking. Rendered permanently — used by\n * A host to show the animated agent face, which idles between turns.\n */\n thinkingIndicator?: React.ReactNode;\n /**\n * Custom background slot rendered absolutely behind the chat content. When\n * provided, the default chat gradient and the AI-Extensions category\n * illustrations are suppressed so the caller owns the entire background\n * (e.g. A host's shader). Pair with a parent that supplies a solid base color\n * if the slot doesn't paint the full canvas itself.\n */\n background?: React.ReactNode;\n /**\n * Opt-in: the host paints the chat's background itself OUTSIDE this component (e.g. the agent's root shader).\n * Keeps the `customBg` visual mode (top blur band) that passing `background` would give, but with\n * no background node here and a transparent pane fill so the host's layer shows through.\n */\n backgroundPaintedByHost?: boolean;\n /**\n * The setup progress stepper (today's only consumer: the agent chat), mounted as a DIRECT CHILD of this\n * view's pane root — a `position: relative` box the size of the chat pane — and outside the scroll container,\n * so it stays put while messages scroll under it. Mounted here rather than in the host's floating top bar for\n * the same reason the top blur band is (see `.contentWrapper::before`): it has to track the chat content\n * column, so it follows the pane when a canvas or a side panel contracts it, which a viewport-positioned\n * overlay cannot — and that pane boundary exists only inside this view's split.\n *\n * The node brings its OWN positioning, stacking and query container (see the stepper's `.progressStepperRow`);\n * this view contributes nothing but the positioned pane root it is mounted in.\n */\n progressStepperSlot?: React.ReactNode;\n /**\n * Host-owned layer shown while files are dragged over the window: this chat takes them. Like `progressStepperSlot`\n * the node positions itself against the pane root; it lies over the messages and under the input.\n */\n fileDropHintSlot?: React.ReactNode;\n /**\n * Optional external ref to the scrollable content wrapper. Forwarded so\n * callers can drive scroll-linked effects (e.g. an animated background\n * that morphs with scroll position) without having to query the DOM.\n */\n scrollRef?: React.Ref<HTMLDivElement>;\n /**\n * Bump to force a scroll to the newest message (via {@link scrollToLatestMessage}, so it clears any pinned turn and\n * re-enables bottom-follow). Each distinct value triggers one scroll; the initial `0`/`undefined` is ignored. Used by\n * the agent to follow the turn a widget/CTA-click signal starts (which posts no visible message of its own).\n */\n scrollToBottomNonce?: number;\n /**\n * Optional external override of the internal bottom-follow flag. Provide it when the host runs its own programmatic\n * scroll away from the bottom (e.g. the agent's search-result jump, which pages older messages in and scrolls to\n * a message far above the bottom): the host sets it `false` for the jump so the resize/message-follow effects stop\n * re-anchoring to the bottom and yanking the view back mid-jump. Left undefined, ConversationViewBody uses its own ref and\n * behaves exactly as before. Shared with the AW-107 pin machinery, so both agree on one flag.\n */\n followBottomRef?: React.MutableRefObject<boolean>;\n /**\n * Optional \"a programmatic jump is in flight\" gate. Set by the host (the agent's search-result jump) for the duration of a\n * jump. While true, the near-bottom onScroll handler does NOT re-enable bottom-follow and the resize ResizeObserver\n * does NOT auto-scroll to the bottom — otherwise, right after the jump the container is still near the bottom, so\n * onScroll would flip follow back on and the follow-up content-resize would yank the view back down. Left undefined,\n * nothing is gated. Distinct from `followBottomRef`: that flag alone is clobbered by onScroll; this gate stops it.\n */\n scrollJumpActiveRef?: React.MutableRefObject<boolean>;\n /**\n * Hide the assistant header (icon + name + \"Assistant\") and the copy button\n * on assistant messages. Used by a host, which renders bare messages.\n */\n hideAssistantMeta?: boolean;\n /**\n * Theme for user-message bubbles, forwarded to ConversationMessageList. A host forces\n * \"dark\"; when omitted the list falls back to its legacy light/default logic.\n */\n userMessageTheme?: ConversationMessageUserTheme;\n /**\n * True when the host (the agent) is minimized to the compact side-panel; forwarded to ConversationViewBody.\n */\n isCompact?: boolean;\n /**\n * Opt-in (agent host only): confine the customBg top blur band to the chat pane instead of the whole viewport —\n * active only while a sibling side panel is docked beside the chat, so the band compresses together with it instead\n * of bleeding across the panel. See `.confineTopBlurBandToChatPane` below.\n */\n confineTopBlurBandToChatPane?: boolean;\n /**\n * Scroll-up older-message pagination (opt-in — mirrors the admin inspector). When `onLoadOlder` is provided, a top\n * sentinel + IntersectionObserver (root = the scroll container) prefetches the next older page ~300px before the\n * top, and the viewport is anchored across the prepend so it doesn't jump. `hasMoreOlder` gates the sentinel;\n * `loadingOlder` shows a small loading row. Left undefined (the default) → no pagination, behaviour unchanged.\n */\n hasMoreOlder?: boolean;\n loadingOlder?: boolean;\n onLoadOlder?: () => void;\n /**\n * Extra action controls rendered inside the chat input's action row, left of the send button —\n * forwarded to ConversationMessageInput (e.g. the agent model picker pill).\n */\n inputActionsSlot?: React.ReactNode;\n /**\n * Action controls pinned to the LEFT edge of the chat input's action row (`inputActionsSlot`\n * stays right) — forwarded to ConversationMessageInput's `actionsSlotStart` (e.g. the agent \"+\" attachments menu).\n */\n inputActionsSlotStart?: React.ReactNode;\n /**\n * Host-owned content rendered inside the chat input above its editable text area — attachment\n * preview cards, validation error boxes. Forwarded to ConversationMessageInput's `topSlot`.\n */\n inputTopSlot?: React.ReactNode;\n /**\n * Hard send gate for the chat input: blocks the send button AND Enter while true, but keeps the\n * text editable. The host sets it e.g. while attachment uploads run.\n */\n inputSendDisabled?: boolean;\n /**\n * Host-owned content rendered IN PLACE of the chat input — the closed-conversation bar of a completed\n * setup conversation (no further input possible). When set, the body renders it instead of ConversationMessageInput,\n * in a wrapper carrying the input's own width, bottom gap and stacking rule — so the node needs no layout of its\n * own, and the background layer cannot paint over it.\n */\n inputReplacementSlot?: React.ReactNode;\n /**\n * Host-owned band right above the chat input, the input overlapping its lower edge — e.g. the running voice chat\n * with its controls. Not rendered while `inputReplacementSlot` replaces the input.\n */\n inputBandSlot?: React.ReactNode;\n /** The chat input's placeholder; the input's own default otherwise. */\n inputPlaceholder?: string;\n /** Forwarded to ConversationMessageInput's `sendReplacementWhenEmpty`. */\n inputSendReplacementWhenEmpty?: React.ReactNode;\n /** Forwarded to ConversationMessageInput's `glowUnderlay`. */\n inputGlowUnderlay?: React.ReactNode;\n /**\n * Host-owned layer over the message column, the same size — e.g. the voice chat's focus mode. The message column\n * stays mounted under it (scroll position and widget state kept); `isContentOverlayShown` switches between them.\n */\n contentOverlaySlot?: React.ReactNode;\n isContentOverlayShown?: boolean;\n /**\n * Uploaded media-library images that ride along in `onSendMessage`'s options object (`attachments`) on the next\n * send. Owned and cleared by the host; forwarded to ConversationMessageInput.\n */\n outgoingAttachmentImages?: ConversationAttachmentReference[];\n /**\n * Composer widgets the host holds outside the widget context (e.g. a widget built from the files the host\n * uploaded), sent like the context's own on the next send. Owned and cleared by the host; forwarded to\n * ConversationMessageInput.\n */\n hostComposerWidgets?: ConversationComposerWidget[];\n /**\n * Imperative handle on the chat input (insertTextIntoInput) so host-owned controls — e.g. the\n * \"+\" menu's \"Generate image\" entry — can put text into it. Forwarded to ConversationMessageInput's `apiRef`.\n */\n conversationMessageInputApiRef?: React.Ref<ConversationMessageInputHandle>;\n /**\n * Keep the chat input editable and sendable while `aiThinking` is true (default false — the input locks for the\n * whole turn); only the first post of a new conversation still locks it, while no conversation id exists yet. Opt\n * in ONLY for a host whose post call stores the message and returns at once, and whose agent checks for unanswered\n * messages when its turn ends, so a message sent mid-turn is answered in the next turn. A host whose post call\n * generates the reply synchronously within the request has no such guard and must leave it off.\n */\n allowSendWhileAiThinking?: boolean;\n /**\n * Opt-in long-answer reading flow (AW-107), default false. When enabled:\n * (1) on send, the question is pinned to the top with room reserved below it so the reply\n * reveals from its beginning instead of chasing the bottom;\n * (2) a scroll-to-latest-message button floats above the input while the bottom is out of view;\n * (3) a fresh static reply's markdown blocks fade in staggered (useFreshMessageBlockReveal).\n * Left off, the chat keeps the classic bottom-follow behavior — AI Extensions stays off;\n * the agent chat opts in.\n */\n enablePinQuestionAndRevealAnswer?: boolean;\n /** New user messages are not sends (a voice chat saves the owner's spoken sentences): keep bottom-follow, no pin. */\n isQuestionPinSuspended?: boolean;\n /**\n * Id of the ONE user message ConversationMessageList renders as a collapsed task-instruction disclosure instead of an\n * owner bubble — the machine-composed seed instruction of a SCHEDULE-spawned run (UX overhaul W4 item 19).\n * Undefined (every host except the agent chat) changes nothing.\n */\n taskInstructionMessageId?: number;\n /**\n * Host content rendered right after one message of the thread, forwarded to ConversationMessageList (the agent chat's\n * activity card under the message that started each turn). Undefined changes nothing.\n */\n renderAfterMessage?: (message: ChatMessage) => React.ReactNode;\n /** Host content beside each shown assistant message (an avatar face), forwarded to ConversationMessageList. */\n renderAssistantAvatar?: (message: ChatMessage) => React.ReactNode;\n /** Forwarded to ConversationMessageList: a closed conversation renders no widget controls. */\n isConversationClosed?: boolean;\n /** Forwarded to ConversationMessageList: when what was written (`MessageTimesMode`). */\n messageTimes?: MessageTimesMode | null;\n onSuggestionClick: (text: string) => void;\n onSendMessage: SendMessageHandler;\n}\n\nexport const ConversationViewBody = (props: ConversationViewProps) => {\n const {\n currentCategory,\n aiPromptExtension,\n suggestions,\n messages,\n aiThinking,\n error,\n rateLimitRetryAfterSeconds,\n onRetryFailedRun,\n isDebugMode,\n categoriesLoaded,\n startingNewConversation,\n conversationId,\n showMessagesWithoutConversation,\n autoScroll = true,\n thinkingIndicator,\n background,\n backgroundPaintedByHost,\n progressStepperSlot,\n fileDropHintSlot,\n scrollRef,\n scrollToBottomNonce,\n followBottomRef,\n scrollJumpActiveRef,\n hideAssistantMeta,\n userMessageTheme,\n isCompact,\n confineTopBlurBandToChatPane,\n hasMoreOlder,\n loadingOlder,\n onLoadOlder,\n inputActionsSlot,\n inputActionsSlotStart,\n inputTopSlot,\n inputSendDisabled,\n inputReplacementSlot,\n inputBandSlot,\n inputPlaceholder,\n inputSendReplacementWhenEmpty,\n inputGlowUnderlay,\n contentOverlaySlot,\n isContentOverlayShown = false,\n outgoingAttachmentImages,\n hostComposerWidgets,\n conversationMessageInputApiRef,\n allowSendWhileAiThinking,\n enablePinQuestionAndRevealAnswer = false,\n isQuestionPinSuspended = false,\n taskInstructionMessageId,\n renderAfterMessage,\n renderAssistantAvatar,\n isConversationClosed,\n messageTimes,\n onSuggestionClick,\n onSendMessage,\n } = props;\n\n // Composer widgets ride the widget context itself (like the deleted selection chip did), so every\n // ConversationView host gets the strip, the outgoing-on-send value and the clear-on-send wiring for free.\n const { composerWidgets, clearComposerWidgets } = useConversationWidgetContext();\n\n const messagesBottom = useRef<HTMLDivElement | null>(null);\n const [scrollContainer, setScrollContainer] = useState<HTMLDivElement | null>(null);\n const [messagesList, setMessagesList] = useState<HTMLDivElement | null>(null);\n // Bottom-follow flag. Uses the host-supplied ref when given (so a host-driven jump can suspend follow, see\n // `followBottomRef` in props), otherwise a local one — identical behaviour when no host overrides it.\n const internalFollowBottom = useRef(true);\n const followBottom = followBottomRef ?? internalFollowBottom;\n // Rendered USER-row count at the last positioning pass — an increase within the same conversation means the user\n // just sent (the pin trigger). Counted from the DOM (not the messages array) so hidden USER messages (/toolresult\n // reports, SIGNAL/ERROR) never miscount and it always matches the row pinLatestQuestionToTop targets.\n const prevUserMessageCount = useRef(0);\n // Last conversationId the positioning effect saw, to tell a real switch / new-chat (re-anchor to bottom) apart from\n // the cold-start id landing mid-turn (undefined → a freshly-created id while pinned → keep the pin).\n const prevConversationId = useRef<number | undefined>(conversationId);\n // Scroll-up pagination (opt-in via onLoadOlder). Capturing the scrollHeight when an older-load starts lets the\n // prepend layout-effect restore the viewport so it doesn't jump when the older page merges in.\n const prependAnchorScrollHeight = useRef<number | null>(null);\n\n // Combined ref callback for the scrollable content wrapper: drives the\n // internal state ref (the auto-scroll / follow-bottom effects depend on it)\n // AND forwards to the caller-supplied `scrollRef` when present. Stable identity\n // so the ref isn't detached/reattached on every render.\n const handleContentWrapperRef = useCallback(\n (el: HTMLDivElement | null) => {\n setScrollContainer(el);\n if (typeof scrollRef === \"function\") scrollRef(el);\n else if (scrollRef) (scrollRef as React.MutableRefObject<HTMLDivElement | null>).current = el;\n },\n [scrollRef],\n );\n\n // The named assistant's theme and background come from the app; the agent chat shows none.\n const { readAssistantThemeClassName, AssistantBackground } = useAgentsEnvironment();\n const colorPalette = useMemo(\n () =>\n currentCategory?.alias\n ? (readAssistantThemeClassName?.(currentCategory.alias) ?? styles.genericChat)\n : styles.genericChat,\n [currentCategory, readAssistantThemeClassName],\n );\n\n const isMessageListVisible =\n (!!messages && (!!conversationId || !!showMessagesWithoutConversation)) ||\n startingNewConversation ||\n (!!error && error !== ConversationErrorType.CONVERSATION_NOT_FOUND);\n\n const isConversationIntroVisible = useMemo(\n () =>\n aiPromptExtension !== undefined &&\n !conversationId &&\n !startingNewConversation &&\n !messages &&\n !(!!error && error !== ConversationErrorType.CONVERSATION_NOT_FOUND),\n [aiPromptExtension, conversationId, startingNewConversation, messages, error],\n );\n\n // The list DOM node. Prefer the state ref (it drives the ResizeObserver effect); fall back to the bottom marker's\n // parent, which is always the .chatMessages list — needed in the layout effect on the render where the list first\n // mounts (setMessagesList hasn't flushed to state yet, but messagesBottom's ref is already committed).\n const getMessagesListEl = useCallback(\n (): HTMLElement | null => messagesList ?? messagesBottom.current?.parentElement ?? null,\n [messagesList],\n );\n\n const {\n pinLatestQuestionToTop,\n reserveRoomBelowPinnedQuestion,\n isQuestionPinnedThisTurn,\n endPinnedTurn,\n userMessageRowCount,\n } = usePinQuestionOnSend({\n enabled: enablePinQuestionAndRevealAnswer,\n scrollContainer,\n getMessagesListEl,\n messagesBottomRef: messagesBottom,\n followBottomRef: followBottom,\n });\n\n // First positioning is instant and pre-paint (layout effect + behavior \"auto\"):\n // opening a conversation lands directly at the bottom with no visible scroll\n // animation. Subsequent message updates scroll smoothly.\n const hasPositionedOnce = useRef(false);\n useLayoutEffect(() => {\n // Older-page prepend (scroll-up pagination): restore the viewport so the freshly-prepended messages don't shift\n // it, and do NOT auto-scroll to the bottom. The anchor is only set when an older-load started, so a conversation\n // switch / live tick never enters this branch.\n if (prependAnchorScrollHeight.current !== null) {\n if (scrollContainer) {\n const delta = scrollContainer.scrollHeight - prependAnchorScrollHeight.current;\n if (delta > 0) scrollContainer.scrollTop += delta;\n }\n prependAnchorScrollHeight.current = null;\n return;\n }\n if (!autoScroll) {\n hasPositionedOnce.current = false;\n return;\n }\n\n // Addon off (default): the classic bottom-follow — re-anchor to the bottom on every message update, exactly the\n // pre-AW-107 behavior (including the old quirk that it scrolls even before the list mounts, no messagesBottom guard).\n if (!enablePinQuestionAndRevealAnswer) {\n followBottom.current = true;\n messagesBottom.current?.scrollIntoView({\n behavior: hasPositionedOnce.current ? \"smooth\" : \"auto\",\n block: \"end\",\n inline: \"nearest\",\n });\n hasPositionedOnce.current = true;\n return;\n }\n\n // A real conversation switch / new-chat / first history load re-anchors to the bottom. The one exception is the\n // cold-start id landing (undefined → a freshly-created id) MID-TURN: the question was already pinned on send, so\n // keep it pinned instead of yanking back to the bottom.\n const conversationChanged = prevConversationId.current !== conversationId;\n const isColdStartIdLanding = prevConversationId.current === undefined && isQuestionPinnedThisTurn();\n prevConversationId.current = conversationId;\n if (conversationChanged && !isColdStartIdLanding) {\n endPinnedTurn();\n followBottom.current = true;\n hasPositionedOnce.current = false;\n }\n\n const userCount = userMessageRowCount();\n\n // First positioning for this conversation. If the list isn't mounted yet (still loading / intro screen), wait for\n // it. A fresh cold-start send (startingNewConversation, nothing positioned yet) pins the first question to the top;\n // opening an existing conversation lands at the bottom, as today.\n if (!hasPositionedOnce.current) {\n if (!messagesBottom.current) return; // list not in the DOM yet — nothing to position\n hasPositionedOnce.current = true;\n prevUserMessageCount.current = userCount;\n if (startingNewConversation && userCount > 0) {\n pinLatestQuestionToTop(\"auto\");\n } else {\n followBottom.current = true;\n messagesBottom.current.scrollIntoView({ behavior: \"auto\", block: \"end\", inline: \"nearest\" });\n }\n return;\n }\n\n // Same conversation, already positioned: a new USER row means the user just sent → pin the new question to the top.\n if (userCount > prevUserMessageCount.current && !isQuestionPinSuspended) {\n prevUserMessageCount.current = userCount;\n pinLatestQuestionToTop(\"smooth\");\n return;\n }\n prevUserMessageCount.current = userCount;\n\n // A later update within the same turn (the reply arriving / growing): keep the question pinned and just re-reserve\n // room — never scroll. Outside a pinned turn (e.g. a background refresh) keep today's bottom-follow.\n if (isQuestionPinnedThisTurn()) {\n reserveRoomBelowPinnedQuestion();\n } else if (followBottom.current) {\n messagesBottom.current?.scrollIntoView({ behavior: \"smooth\", block: \"end\", inline: \"nearest\" });\n }\n }, [\n messages,\n autoScroll,\n scrollContainer,\n conversationId,\n startingNewConversation,\n enablePinQuestionAndRevealAnswer,\n isQuestionPinSuspended,\n userMessageRowCount,\n reserveRoomBelowPinnedQuestion,\n pinLatestQuestionToTop,\n isQuestionPinnedThisTurn,\n endPinnedTurn,\n followBottom,\n ]);\n\n // Capture the scroll height the instant an older-load starts — consumed by the prepend layout-effect above to keep\n // the viewport anchored once the older page merges in.\n useEffect(() => {\n if (loadingOlder && scrollContainer) {\n prependAnchorScrollHeight.current = scrollContainer.scrollHeight;\n }\n }, [loadingOlder, scrollContainer]);\n\n // Scroll-up lazy-load: prefetch the next older page when the user scrolls within ~300px of the top. onLoadOlder is\n // self-guarded (in-flight + hasMoreOlder) by the caller, so repeated scroll ticks near the top don't double-fetch.\n // No-op unless the caller opts in via onLoadOlder.\n useEffect(() => {\n if (!onLoadOlder || !scrollContainer || !hasMoreOlder) return undefined;\n const onScrollNearTop = () => {\n if (scrollContainer.scrollTop <= 300) onLoadOlder();\n };\n scrollContainer.addEventListener(\"scroll\", onScrollNearTop, { passive: true });\n return () => scrollContainer.removeEventListener(\"scroll\", onScrollNearTop);\n }, [onLoadOlder, scrollContainer, hasMoreOlder]);\n\n useEffect(() => {\n if (!autoScroll) return;\n const container = scrollContainer;\n const list = messagesList;\n if (!container || !list) return;\n\n const NEAR_BOTTOM_PX = 80;\n const isNearBottom = () => container.scrollHeight - container.scrollTop - container.clientHeight <= NEAR_BOTTOM_PX;\n\n let animRaf: number | null = null;\n let isProgrammaticScroll = false;\n const cancelAnim = () => {\n if (animRaf !== null) {\n cancelAnimationFrame(animRaf);\n animRaf = null;\n }\n };\n\n // Non-interruptible smooth scroll: if already running, the existing\n // animation just re-reads the target each frame and chases it — no\n // restart, no blink. Only user interaction or unmount cancels it.\n const startSmoothToBottom = (durationMs: number) => {\n if (animRaf !== null) return; // in-flight; target re-read each frame\n const start = container.scrollTop;\n const initialTarget = container.scrollHeight - container.clientHeight;\n if (initialTarget - start <= 0) return;\n const t0 = performance.now();\n const easeOut = (t: number) => 1 - Math.pow(1 - t, 3);\n const tick = (now: number) => {\n const t = Math.min(1, (now - t0) / durationMs);\n const target = container.scrollHeight - container.clientHeight;\n isProgrammaticScroll = true;\n container.scrollTop = start + (target - start) * easeOut(t);\n isProgrammaticScroll = false;\n if (t < 1) {\n animRaf = requestAnimationFrame(tick);\n } else {\n animRaf = null;\n }\n };\n animRaf = requestAnimationFrame(tick);\n };\n\n const disableFollow = () => {\n followBottom.current = false;\n // A pinned turn (AW-107) keeps its pin + reserved room across a manual scroll — we deliberately do NOT clear them\n // here. Dropping the padding on scroll shrank the scroll height and made the viewport jump; and the empty space\n // below a short reply is intentional, so the question holds its place at the top for the whole turn.\n cancelAnim();\n };\n const onScroll = () => {\n if (isProgrammaticScroll) return;\n // A host-driven jump is in flight: don't re-enable follow just because the viewport is still/again near the\n // bottom — that clobbers the jump and lets the resize-follow yank the view back down.\n if (scrollJumpActiveRef?.current) return;\n if (isNearBottom()) followBottom.current = true;\n };\n\n container.addEventListener(\"wheel\", disableFollow, { passive: true });\n container.addEventListener(\"touchmove\", disableFollow, { passive: true });\n container.addEventListener(\"keydown\", disableFollow);\n container.addEventListener(\"scroll\", onScroll, { passive: true });\n\n const observer = new ResizeObserver(() => {\n // A host-driven jump is in flight (search-result jump): the messages settle their heights as they render, which\n // fires this observer — do NOT auto-scroll to the bottom, or the jump gets yanked back down.\n if (scrollJumpActiveRef?.current) return;\n // During a pinned turn the reply grows below the fold: re-reserve room (it shrinks to 0 as the reply fills the\n // viewport) — never scroll, so the question stays put at the top. Inert when the addon is off (pin never set).\n if (isQuestionPinnedThisTurn()) {\n reserveRoomBelowPinnedQuestion();\n return;\n }\n if (!followBottom.current) return;\n startSmoothToBottom(180);\n });\n observer.observe(list);\n // Also react to viewport/pane height changes (window resize, drawer open/close): the list observer won't fire when\n // only the container's height changes, but a pinned turn's reserved room depends on container.clientHeight. Only\n // needed for the addon — leaving it on for the default chat would newly trigger scroll-to-bottom on drawer toggle.\n if (enablePinQuestionAndRevealAnswer) observer.observe(container);\n\n return () => {\n container.removeEventListener(\"wheel\", disableFollow);\n container.removeEventListener(\"touchmove\", disableFollow);\n container.removeEventListener(\"keydown\", disableFollow);\n container.removeEventListener(\"scroll\", onScroll);\n observer.disconnect();\n cancelAnim();\n };\n }, [\n isMessageListVisible,\n scrollContainer,\n messagesList,\n autoScroll,\n enablePinQuestionAndRevealAnswer,\n isQuestionPinnedThisTurn,\n reserveRoomBelowPinnedQuestion,\n followBottom,\n scrollJumpActiveRef,\n ]);\n\n // Only observe the sentinel when the addon is on — a null container makes the hook return false + mount no observer.\n const isMessagesBottomOutOfView = useIsMessagesBottomOutOfView(\n enablePinQuestionAndRevealAnswer ? scrollContainer : null,\n messagesList,\n messagesBottom,\n );\n\n // Jump back to the newest message. Ends a pinned turn: the user is explicitly leaving the pinned\n // question, so bottom-follow takes over again (the ResizeObserver's pinned branch would otherwise\n // keep suppressing it, ConversationViewBody.tsx:396). Dropping the reserved padding here cannot jump the\n // viewport: the button only shows when the viewport is ≥300px ABOVE the sentinel, and the padding\n // lives entirely BELOW it — shrinking scrollHeight below the viewport doesn't move scrollTop.\n const scrollToLatestMessage = useCallback(() => {\n endPinnedTurn();\n followBottom.current = true;\n messagesBottom.current?.scrollIntoView({ behavior: \"smooth\", block: \"end\", inline: \"nearest\" });\n }, [endPinnedTurn, followBottom]);\n\n // Caller-driven scroll-to-bottom (scrollToBottomNonce bumped per widget/CTA-click signal). Goes through\n // scrollToLatestMessage so it clears any pinned turn and re-enables bottom-follow — a raw scrollTo would be\n // suppressed while a turn is pinned. Ignores the initial 0/undefined so it never scrolls on mount.\n useEffect(() => {\n if (!scrollToBottomNonce) return;\n scrollToLatestMessage();\n }, [scrollToBottomNonce, scrollToLatestMessage]);\n\n const messageColumn = (\n <div\n className={styles.contentWrapper}\n // A stable hook for a host's own stylesheet (the default chat drops the top blur band, it has no top bar).\n data-agents-chat-scroll=\"\"\n data-testid=\"chat-messages-scroll\"\n ref={handleContentWrapperRef}\n aria-hidden={isContentOverlayShown || undefined}\n inert={isContentOverlayShown || undefined}\n >\n {!conversationId && !categoriesLoaded && !aiPromptExtension ? (\n <NoConversationLoading />\n ) : null}\n\n {!!conversationId && !messages ? (\n <ConversationLoading />\n ) : null}\n\n {isConversationIntroVisible ? (\n <ConversationIntroWidget\n aiPromptExtension={aiPromptExtension!}\n aiPromptExtensionIcon={aiPromptExtension!.iconClass as string}\n suggestions={suggestions}\n onSuggestionClick={onSuggestionClick}\n />\n ) : null}\n\n {!!loadingOlder ? (\n <span className={styles.olderLoading}>\n <Text>{\"Loading older messages…\"}</Text>\n </span>\n ) : null}\n\n {isMessageListVisible ? (\n <>\n {/* The scroll container (this contentWrapper) is the IntersectionObserver root for widget viewport-windowing. */}\n <WidgetWindowRootContext.Provider value={scrollContainer}>\n <ConversationMessageList\n className={\n enablePinQuestionAndRevealAnswer && (conversationId || startingNewConversation || aiThinking || error)\n ? styles.topAlignedMessages\n : undefined\n }\n messages={messages}\n currentCategory={currentCategory}\n aiPromptExtension={aiPromptExtension}\n isDebugMode={isDebugMode}\n aiThinking={aiThinking}\n thinkingIndicator={thinkingIndicator}\n hideAssistantMeta={hideAssistantMeta}\n userMessageTheme={userMessageTheme}\n error={error}\n rateLimitRetryAfterSeconds={rateLimitRetryAfterSeconds}\n onRetryFailedRun={onRetryFailedRun}\n messagesBottomRef={messagesBottom}\n messagesListRef={setMessagesList}\n enableFreshMessageBlockReveal={enablePinQuestionAndRevealAnswer}\n taskInstructionMessageId={taskInstructionMessageId}\n renderAfterMessage={renderAfterMessage}\n renderAssistantAvatar={renderAssistantAvatar}\n isConversationClosed={isConversationClosed}\n messageTimes={messageTimes}\n />\n </WidgetWindowRootContext.Provider>\n </>\n ) : null}\n </div>\n );\n\n return (\n <div\n className={classNames(\n styles.chat,\n background || backgroundPaintedByHost ? styles.customBg : colorPalette,\n backgroundPaintedByHost ? styles.backgroundPaintedByHost : undefined,\n isCompact ? styles.chatCompact : undefined,\n confineTopBlurBandToChatPane ? styles.confineTopBlurBandToChatPane : undefined,\n )}\n >\n {background ? (\n <div className={styles.backgroundLayer}>{background}</div>\n ) : backgroundPaintedByHost ? null : (\n AssistantBackground ? (\n <AssistantBackground category={currentCategory} categoryAlias={currentCategory?.alias ?? undefined} />\n ) : null\n )}\n\n {/* Positions itself against this .chat root (see the prop's doc) — no wrapper, no class from here. */}\n {progressStepperSlot}\n {fileDropHintSlot}\n\n {contentOverlaySlot !== undefined ? (\n <div className={styles.contentLayers} data-overlay-shown={isContentOverlayShown || undefined}>\n {messageColumn}\n <div\n className={styles.contentOverlay}\n aria-hidden={!isContentOverlayShown || undefined}\n inert={!isContentOverlayShown || undefined}\n >\n {contentOverlaySlot}\n </div>\n </div>\n ) : (\n messageColumn\n )}\n {enablePinQuestionAndRevealAnswer && (\n <div className={styles.scrollToLatestAnchor}>\n <ConversationScrollToLatestMessageButton\n visible={isMessagesBottomOutOfView}\n onClick={scrollToLatestMessage}\n />\n </div>\n )}\n {/* With allowSendWhileAiThinking the input stays open during a turn, EXCEPT while the cold-start\n startWithMessage POST is in flight: no conversation id exists yet, so the host's send handler would drop a\n second message silently — keep the brief lock for exactly that window. */}\n {inputReplacementSlot ? (\n <div className={styles.inputReplacement}>{inputReplacementSlot}</div>\n ) : (\n <>\n {inputBandSlot}\n <ConversationMessageInput\n className={classNames(styles.input, currentCategory?.alias ? styles.inputInCategory : undefined)}\n isProcessing={allowSendWhileAiThinking ? !!startingNewConversation : aiThinking}\n onSendMessage={onSendMessage}\n actionsSlot={inputActionsSlot}\n actionsSlotStart={inputActionsSlotStart}\n // The composer-widgets strip is one topSlot block like any other — above the host's own blocks\n // (attachment previews sit closest to the text). It reads the widget context itself, so every\n // ConversationView host gets it for free.\n topSlot={\n <>\n <ConversationMessageInputComposerWidgets testId=\"chat-input\" />\n {inputTopSlot}\n </>\n }\n sendDisabled={inputSendDisabled}\n outgoingAttachmentImages={outgoingAttachmentImages}\n hostComposerWidgets={hostComposerWidgets}\n outgoingComposerWidgets={composerWidgets}\n onComposerWidgetsSent={clearComposerWidgets}\n apiRef={conversationMessageInputApiRef}\n placeholder={inputPlaceholder}\n sendReplacementWhenEmpty={inputSendReplacementWhenEmpty}\n glowUnderlay={inputGlowUnderlay}\n />\n </>\n )}\n </div>\n );\n};\n","import type { AgentsCanvasLayout } from \"../provider/environment\";\nimport { useAgentsEnvironment } from \"../provider/AgentsProvider\";\nimport { CANVAS_BOXED_INSET_PX, CHAT_COLUMN_MIN_WIDTH_PX } from \"../renderer/canvas/canvas-behaviours\";\n\n/** `AgentsCanvasLayout` with every member set: the host's value, else the package's own chrome. */\nexport interface ResolvedCanvasLayout {\n readonly showsCloseButton: boolean;\n readonly showsDividerToggle: boolean;\n readonly showsNarrowReopenControl: boolean;\n readonly chatColumnMinWidthPx: number;\n readonly boxedInsetPx: number;\n readonly paneSurface: \"card\" | \"none\";\n}\n\nexport const resolveCanvasLayout = (layout: AgentsCanvasLayout | undefined): ResolvedCanvasLayout => ({\n showsCloseButton: layout?.showsCloseButton ?? true,\n showsDividerToggle: layout?.showsDividerToggle ?? true,\n showsNarrowReopenControl: layout?.showsNarrowReopenControl ?? true,\n chatColumnMinWidthPx: Math.max(0, layout?.chatColumnMinWidthPx ?? CHAT_COLUMN_MIN_WIDTH_PX),\n boxedInsetPx: Math.max(0, layout?.boxedInsetPx ?? CANVAS_BOXED_INSET_PX),\n paneSurface: layout?.paneSurface ?? \"card\",\n});\n\n/** The canvas layout of this subtree's environment (`AgentsEnvironment.canvasLayout`). */\nexport const useCanvasLayout = (): ResolvedCanvasLayout => resolveCanvasLayout(useAgentsEnvironment().canvasLayout);\n","import { Button, LoadingSpinner } from \"../../provider/components\";\nimport { classNames } from \"../../provider/class-names\";\nimport React, { Fragment, useEffect, useState } from \"react\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetContext\";\nimport { ConversationWidgetErrorBoundary } from \"../../renderer/ConversationWidgetErrorBoundary\";\nimport { canvasBehaviourOf } from \"../../renderer/canvas/canvas-behaviours\";\nimport {\n canvasBodies,\n canvasFeatureFlagOf,\n} from \"../../renderer/canvas/canvasBodies\";\nimport { CanvasTitleSlotContext } from \"../../renderer/canvas/canvas-title-slot-context\";\nimport { ConversationWidgetFeatureGate } from \"../../renderer/_access/ConversationWidgetFeatureGate\";\nimport { normalizeServerMessageToMarkdown } from \"../normalize-server-message-to-markdown\";\nimport type { ChatMessage } from \"../chat-message\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport { useCanvasLayout } from \"../canvas-layout\";\nimport classes from \"./CanvasPane.module.scss\";\n\ninterface CanvasPaneProps {\n /** The host's loaded messages — a message-anchored canvas body parses its fence out of its anchor message. */\n messages: ChatMessage[] | null;\n /** Render as a rounded surface card (agent side-split — the pane is inset below the floating top bar). */\n boxed?: boolean;\n}\n\n// The canvas slides in via a main-thread react-spring animation. Mounting a heavy body (e.g. an app's full list\n// page) DURING that slide blocks the animation frames and makes opening stagger. So we hold the content for a beat — a\n// light loader fills the pane while it slides in, then the body mounts.\nconst CANVAS_OPEN_SETTLE_MS = 350;\n\nconst OpeningLoader = () => (\n // Cheap, content-agnostic placeholder shown while the canvas slides in, so the open animation isn't blocked by the\n // body's mount. A centered spinner (not a content-shaped skeleton) because the canvas hosts many different bodies.\n <div className={classes.openingLoader} aria-hidden>\n <LoadingSpinner />\n </div>\n);\n\n/**\n * The CANVAS PANE — renders the canvas the chat's slice points at (`canvas`, a pointer to its anchor): the body from\n * `canvasBodies`, keyed on `mountGeneration`, geometry from its behaviour (`canvasBehaviourOf`), the canvas's own feature gate and the\n * shared error boundary. A message-anchored body receives its anchor message's markdown and re-reads its widget's\n * payload from it — nothing but the pointer is stored anywhere.\n */\nexport const CanvasPane = ({ messages, boxed = false }: CanvasPaneProps) => {\n const CanvasBodyContainer = useAgentsEnvironment().CanvasBodyContainer ?? Fragment;\n const { canvas, closeCanvas, chatAgentSpaceKey } = useConversationWidgetContext();\n // A host that frames the canvas itself (`AgentsEnvironment.canvasLayout`) may close it from its own chrome and paint\n // its own card.\n const { showsCloseButton, paneSurface } = useCanvasLayout();\n\n // Re-deferred on every open (the mountGeneration changes each time a canvas mounts).\n const mountGeneration = canvas?.mountGeneration;\n const [contentReady, setContentReady] = useState(false);\n const [titleSlot, setTitleSlot] = useState<HTMLDivElement | null>(null);\n useEffect(() => {\n setContentReady(false);\n const timer = window.setTimeout(() => setContentReady(true), CANVAS_OPEN_SETTLE_MS);\n return () => window.clearTimeout(timer);\n }, [mountGeneration]);\n\n if (!canvas) {\n return null;\n }\n const Body = canvasBodies[canvas.canvasId];\n\n const behaviour = canvasBehaviourOf(canvas.canvasId);\n const featureFlag = canvasFeatureFlagOf(canvas.canvasId);\n const anchor = canvas.anchor;\n const anchorMessage =\n anchor.kind === \"message\" ? (messages ?? []).find((message) => message.id === anchor.messageId) : undefined;\n const anchorMessageMarkdown =\n anchorMessage !== undefined ? normalizeServerMessageToMarkdown(anchorMessage.message) : null;\n const hasTitleSlot = !!behaviour?.titleBesideCloseButton;\n const surfaceByHost = paneSurface === \"none\";\n const body = <Body canvas={canvas} agentSpaceKey={chatAgentSpaceKey} anchorMessageMarkdown={anchorMessageMarkdown} />;\n\n return (\n <div\n className={classNames(\n classes.root,\n surfaceByHost ? classes.rootSurfaceByHost : \"\",\n boxed && !surfaceByHost ? classes.rootBoxed : \"\",\n behaviour?.fullBleed ? classes.rootFullBleedContent : \"\",\n behaviour?.overlayCloseButton ? classes.rootOverlayCloseButton : \"\",\n )}\n data-testid=\"chat-canvas-pane\"\n data-canvas-id={canvas.canvasId}\n >\n {showsCloseButton || hasTitleSlot ? (\n <div className={classes.closeButtonRow}>\n {hasTitleSlot && <div ref={setTitleSlot} className={classes.titleSlot} />}\n {showsCloseButton ? (\n <Button\n variant=\"muted\"\n // Floating over the body's dark hero image: the light trigger for dark surfaces.\n inverted={behaviour?.overlayCloseButton}\n onDark={behaviour?.overlayCloseButton}\n icon=\"closeCanvas\"\n iconPosition={\"right\"}\n rounded\n blurred\n // The customer's OWN close: a live re-delivery of this canvas is vetoed until the next send / click.\n onClick={() => closeCanvas(true)}\n >\n Close canvas\n </Button>\n ) : null}\n </div>\n ) : null}\n <div key={canvas.mountGeneration} className={classes.content}>\n {contentReady ? (\n // The app's wrapper of a canvas body (host application: canvas-hosted list pages must not rewrite the page URL).\n <CanvasBodyContainer>\n <CanvasTitleSlotContext.Provider value={hasTitleSlot ? titleSlot : null}>\n <ConversationWidgetErrorBoundary widgetName={`canvas:${canvas.canvasId}`}>\n {featureFlag ? (\n // The canvas owns its gate (not inherited from an opener): a restored or page-opened canvas has no\n // widget mount to inherit it from. A page anchor's agent space is the gate's agent space.\n <ConversationWidgetFeatureGate\n featureFlag={featureFlag}\n agentSpaceKeyAttribute={anchor.kind === \"page\" ? anchor.agentSpaceKey : undefined}\n >\n {body}\n </ConversationWidgetFeatureGate>\n ) : (\n body\n )}\n </ConversationWidgetErrorBoundary>\n </CanvasTitleSlotContext.Provider>\n </CanvasBodyContainer>\n ) : (\n <OpeningLoader />\n )}\n </div>\n </div>\n );\n};\n","import { KeyboardEvent, PointerEvent as ReactPointerEvent, RefObject, useEffect, useRef, useState } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport {\n CANVAS_MIN_WIDTH_PX,\n CHAT_COLUMN_MIN_WIDTH_PX,\n} from \"../../renderer/canvas/canvas-behaviours\";\n\nconst KEY_STEP_PX = 24;\nconst NEAR_PX = 40;\nconst RUBBER_MAX_PX = 44;\nconst RUBBER_K = 70;\nconst MAGNET_PX = 6;\nconst MAGNET_X = 0.4;\nconst MAGNET_Y = 0.12;\nconst DRAG_TRAVEL_PX = 12;\nconst LEAN_PX = DRAG_TRAVEL_PX;\nconst CLOSE_PULL_PX = 64;\nconst ARM_DELAY_MS = 350;\nconst LEAN_REST_MS = 150;\n\n/** `idle` (hidden until the pointer comes near), `hover`, `drag`, `armed` (pulled past the narrowest and held: release closes). */\nexport type CanvasResizeTab = \"idle\" | \"hover\" | \"drag\" | \"armed\";\n\nexport const rubberBand = (distance: number): number =>\n Math.sign(distance) * RUBBER_MAX_PX * (1 - Math.exp(-Math.abs(distance) / RUBBER_K));\n\nexport const canvasWidthLimits = (\n rootWidth: number,\n inset: number,\n chatColumnMinWidthPx: number = CHAT_COLUMN_MIN_WIDTH_PX,\n): { min: number; max: number } => {\n const min = CANVAS_MIN_WIDTH_PX + inset * 2;\n return { min, max: Math.max(min, rootWidth - chatColumnMinWidthPx) };\n};\n\nexport const clampCanvasWidth = (\n width: number,\n rootWidth: number,\n inset: number,\n chatColumnMinWidthPx: number = CHAT_COLUMN_MIN_WIDTH_PX,\n): number => {\n const { min, max } = canvasWidthLimits(rootWidth, inset, chatColumnMinWidthPx);\n return Math.round(Math.min(max, Math.max(min, width)));\n};\n\ninterface UseCanvasResizeOptions {\n /** The split's root: the canvas pane's right edge is its right edge, and `--agents-canvas-width-drag` is written onto it while dragging. */\n rootRef: RefObject<HTMLElement | null>;\n /** The canvas card's inset from its pane edge — the handle sits on the card's edge. */\n inset: number;\n /** The narrowest the chat column gets beside the canvas; default `CHAT_COLUMN_MIN_WIDTH_PX`. */\n chatColumnMinWidthPx?: number;\n /** The pane width the customer set (px), or `null` for the canvas's default split. */\n width: number | null;\n onWidthChange: (width: number | null) => void;\n onClose: () => void;\n}\n\n/**\n * The canvas's left edge drags. The edge follows the pointer through a CSS variable on the split's root (no render per\n * move); the width is committed once on release. Pulled `CLOSE_PULL_PX` past the narrowest and held, the tab arms and\n * release closes the canvas.\n */\nexport const useCanvasResize = (options: UseCanvasResizeOptions) => {\n const { rootRef, inset, width, onWidthChange, onClose } = options;\n const chatColumnMinWidthPx = options.chatColumnMinWidthPx ?? CHAT_COLUMN_MIN_WIDTH_PX;\n const handleRef = useRef<HTMLDivElement>(null);\n const [isHovered, setIsHovered] = useState(false);\n const [isDragging, setIsDragging] = useState(false);\n const [isArmed, setIsArmed] = useState(false);\n const [tabX, setTabX] = useState(0);\n const isDraggingRef = useRef(false);\n const timers = useRef({ arm: 0, lean: 0 });\n const latest = useRef({ inset, chatColumnMinWidthPx, onWidthChange, onClose });\n latest.current = { inset, chatColumnMinWidthPx, onWidthChange, onClose };\n\n useEffect(() => {\n const root = rootRef.current;\n const pendingTimers = timers.current;\n return () => {\n window.clearTimeout(pendingTimers.arm);\n window.clearTimeout(pendingTimers.lean);\n // Unmounted mid-drag (the canvas closed): the split must not keep following a pointer nobody holds.\n delete root?.dataset.resizing;\n root?.style.removeProperty(\"--agents-canvas-width-drag\");\n };\n }, [rootRef]);\n\n const magnetise = (clientX: number | null, clientY: number | null, reach = MAGNET_PX) => {\n const handle = handleRef.current;\n if (!handle) return;\n const rect = handle.getBoundingClientRect();\n const cap = (value: number) => Math.max(-reach, Math.min(reach, value));\n const x = clientX === null ? 0 : cap((clientX - (rect.left + rect.width / 2)) * MAGNET_X);\n const y = clientY === null ? 0 : cap((clientY - (rect.top + rect.height / 2)) * MAGNET_Y);\n handle.style.setProperty(\"--agents-resize-magnet-x\", `${x.toFixed(2)}px`);\n handle.style.setProperty(\"--agents-resize-magnet-y\", `${y.toFixed(2)}px`);\n };\n\n const setNear = (isNear: boolean) => {\n const handle = handleRef.current;\n if (handle && (handle.dataset.near === \"true\") !== isNear) {\n handle.dataset.near = String(isNear);\n }\n };\n\n useEffect(() => {\n const root = rootRef.current;\n if (!root) return;\n const onPointerMove = (event: PointerEvent) => {\n if (isDraggingRef.current) return;\n const rect = handleRef.current?.getBoundingClientRect();\n const isNear =\n !!rect &&\n event.clientY >= rect.top &&\n event.clientY <= rect.bottom &&\n Math.abs(event.clientX - (rect.left + rect.width / 2)) <= NEAR_PX;\n setNear(isNear);\n if (isNear) magnetise(event.clientX, event.clientY);\n else magnetise(null, null);\n };\n const onPointerLeave = () => {\n if (isDraggingRef.current) return;\n setNear(false);\n magnetise(null, null);\n };\n root.addEventListener(\"pointermove\", onPointerMove);\n root.addEventListener(\"pointerleave\", onPointerLeave);\n return () => {\n root.removeEventListener(\"pointermove\", onPointerMove);\n root.removeEventListener(\"pointerleave\", onPointerLeave);\n };\n }, [rootRef]);\n\n const rootWidth = () => rootRef.current?.clientWidth ?? 0;\n const currentWidth = () => {\n const root = rootRef.current;\n const handle = handleRef.current;\n if (!root || !handle) return CANVAS_MIN_WIDTH_PX;\n const handleCenter = handle.getBoundingClientRect().left + handle.offsetWidth / 2;\n return root.getBoundingClientRect().right - handleCenter + latest.current.inset;\n };\n\n const startDrag = (event: ReactPointerEvent<HTMLElement>) => {\n const root = rootRef.current;\n if (event.button !== 0 || !root) return;\n event.preventDefault();\n const handle = event.currentTarget;\n try {\n handle.setPointerCapture(event.pointerId);\n } catch {\n // A pointer the browser does not know (synthetic): the strip still gets its moves while over it.\n }\n const { min, max } = canvasWidthLimits(rootWidth(), latest.current.inset, latest.current.chatColumnMinWidthPx);\n const grabOffset = event.clientX - handle.getBoundingClientRect().left - handle.offsetWidth / 2;\n let lastX = event.clientX;\n let lean = 0;\n let isArmedNow = false;\n let draggedWidth: number | null = null;\n isDraggingRef.current = true;\n setIsDragging(true);\n // Resize mode reads `--agents-canvas-width-drag`: seed it, or a press without a move leaves the split without a width.\n root.style.setProperty(\"--agents-canvas-width-drag\", `${clampCanvasWidth(currentWidth(), rootWidth(), latest.current.inset, latest.current.chatColumnMinWidthPx)}px`);\n root.dataset.resizing = \"true\";\n\n const disarm = () => {\n window.clearTimeout(timers.current.arm);\n timers.current.arm = 0;\n if (isArmedNow) {\n isArmedNow = false;\n setIsArmed(false);\n }\n };\n\n magnetise(null, event.clientY, DRAG_TRAVEL_PX);\n const move = (moveEvent: PointerEvent) => {\n magnetise(null, moveEvent.clientY, DRAG_TRAVEL_PX);\n const desired = root.getBoundingClientRect().right - (moveEvent.clientX - grabOffset) + latest.current.inset;\n const next = clampCanvasWidth(desired, rootWidth(), latest.current.inset, latest.current.chatColumnMinWidthPx);\n draggedWidth = next;\n root.style.setProperty(\"--agents-canvas-width-drag\", `${next}px`);\n\n // Past the narrowest the edge stops and the tab stretches after the pointer; past the widest it holds its lean.\n const beyond = Math.min(max, Math.max(min, desired)) - desired;\n const moved = moveEvent.clientX - lastX;\n if (moved !== 0) lean = Math.sign(moved) * LEAN_PX;\n lastX = moveEvent.clientX;\n const tabFor = (currentLean: number) =>\n beyond > 0 ? Math.max(LEAN_PX, rubberBand(beyond)) : beyond < 0 ? -LEAN_PX : currentLean;\n setTabX(tabFor(lean));\n window.clearTimeout(timers.current.lean);\n timers.current.lean = window.setTimeout(() => {\n lean = 0;\n setTabX(tabFor(0));\n }, LEAN_REST_MS);\n\n if (next === min && beyond >= CLOSE_PULL_PX) {\n if (!isArmedNow && !timers.current.arm) {\n timers.current.arm = window.setTimeout(() => {\n timers.current.arm = 0;\n isArmedNow = true;\n setIsArmed(true);\n }, ARM_DELAY_MS);\n }\n } else {\n disarm();\n }\n };\n\n const finish = () => {\n handle.removeEventListener(\"pointermove\", move);\n handle.removeEventListener(\"pointerup\", finish);\n handle.removeEventListener(\"pointercancel\", finish);\n window.clearTimeout(timers.current.lean);\n const closes = isArmedNow;\n disarm();\n isDraggingRef.current = false;\n setIsDragging(false);\n setTabX(0);\n magnetise(null, null);\n delete root.dataset.resizing;\n // Committed in the same frame the drag variable goes, so the edge never flashes back to the old width.\n flushSync(() => latest.current.onWidthChange(closes ? null : (draggedWidth ?? width)));\n root.style.removeProperty(\"--agents-canvas-width-drag\");\n if (closes) {\n setNear(false);\n setIsHovered(false);\n latest.current.onClose();\n }\n };\n handle.addEventListener(\"pointermove\", move);\n handle.addEventListener(\"pointerup\", finish);\n handle.addEventListener(\"pointercancel\", finish);\n };\n\n const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {\n const { min, max } = canvasWidthLimits(rootWidth(), inset, chatColumnMinWidthPx);\n const next =\n event.key === \"ArrowLeft\"\n ? currentWidth() + KEY_STEP_PX\n : event.key === \"ArrowRight\"\n ? currentWidth() - KEY_STEP_PX\n : event.key === \"Home\"\n ? max\n : event.key === \"End\"\n ? min\n : null;\n if (next === null) return;\n event.preventDefault();\n onWidthChange(clampCanvasWidth(next, rootWidth(), inset, chatColumnMinWidthPx));\n };\n\n const tab: CanvasResizeTab = isArmed ? \"armed\" : isDragging ? \"drag\" : isHovered ? \"hover\" : \"idle\";\n const { min, max } = canvasWidthLimits(rootWidth(), inset, chatColumnMinWidthPx);\n return {\n tab,\n tabX,\n handleProps: {\n ref: handleRef,\n role: \"separator\",\n \"aria-orientation\": \"vertical\" as const,\n \"aria-valuemin\": min,\n \"aria-valuemax\": Math.round(max),\n \"aria-valuenow\": width ?? undefined,\n tabIndex: 0,\n onPointerDown: startDrag,\n onPointerEnter: () => setIsHovered(true),\n onPointerLeave: () => setIsHovered(false),\n onKeyDown,\n onDoubleClick: () => onWidthChange(null),\n },\n };\n};\n","import { CSSProperties, RefObject } from \"react\";\nimport { translateText } from \"../../provider/environment\";\nimport { useCanvasResize } from \"./use-canvas-resize\";\nimport styles from \"./CanvasResizeHandle.module.scss\";\n\nexport interface CanvasResizeHandleProps {\n rootRef: RefObject<HTMLElement | null>;\n inset: number;\n /** The narrowest the chat column gets (`AgentsCanvasLayout.chatColumnMinWidthPx`); default `CHAT_COLUMN_MIN_WIDTH_PX`. */\n chatColumnMinWidthPx?: number;\n width: number | null;\n onWidthChange: (width: number | null) => void;\n onClose: () => void;\n}\n\n/** The pull tab on the canvas's left edge: drag to resize, pull past the narrowest and hold to close. */\nexport const CanvasResizeHandle = (props: CanvasResizeHandleProps) => {\n const { rootRef, inset, chatColumnMinWidthPx, width, onWidthChange, onClose } = props;\n const { tab, tabX, handleProps } = useCanvasResize({ rootRef, inset, chatColumnMinWidthPx, width, onWidthChange, onClose });\n\n return (\n <div\n {...handleProps}\n className={styles.handle}\n data-tab={tab}\n aria-label={translateText(\"Resize canvas\")}\n >\n <span className={styles.tab} style={{ \"--agents-resize-tab-x\": `${tabX}px` } as CSSProperties} aria-hidden=\"true\">\n <span className={styles.tabCircle} />\n <span className={styles.tabTop} />\n <span className={styles.tabBottom} />\n </span>\n </div>\n );\n};\n","import { useEffect, useRef } from \"react\";\nimport { canvasBehaviourOf } from \"../renderer/canvas/canvas-behaviours\";\nimport { useConversationWidgetContext } from \"../renderer/ConversationWidgetContext\";\n\nexport interface CanvasShellTransitionsInput {\n /** The conversation the view shows; undefined for a cold chat that has none yet. */\n conversationId?: number;\n /** The viewport is wide enough for the side split (`useCanvasViable`). */\n canvasViable: boolean;\n}\n\n/**\n * The two SHELL-driven transitions of the canvas model that `ConversationView` owns (the widget-driven ones go through\n * `openCanvas`; the send boundary is the hosts'):\n *\n * - **A conversation switch** (history select / new chat) makes the previous conversation's canvas stale — it is\n * cleared so the new conversation starts with a closed canvas. History replay never auto-opens a canvas (the\n * opening rule rejects replay), and the LEFT conversation keeps its stored pointer for when the customer comes\n * back. Only a REAL switch between two conversations counts. Not the first mount: a canvas the host opened on open\n * (the `?agentWidget=` deep-link, a restored canvas) mounts its widget BEFORE this parent effect runs, and an\n * unconditional reset would tear it down before the customer ever sees it. And not the id ARRIVING on a chat that\n * had none: that is the same conversation, just persisted now (the first send creates it) — closing the customer's\n * pinned work surface at that moment would be wrong.\n * - **The wide → narrow crossing** closes the side-split canvas as a shell close (re-openable, no customer veto).\n * Keyed on `canvasViable` ONLY (the canvas read through a ref) so it fires on the crossing, NOT when the mobile CTA\n * opens a canvas on an already narrow viewport. Skipped for a canvas whose behaviour says `narrowViewport:\n * \"overlay\"`: its widget renders nothing inline, so closing it on the crossing would leave the chat with no content\n * at all — it stays open as the full-screen overlay.\n */\nexport const useCanvasShellTransitions = ({ conversationId, canvasViable }: CanvasShellTransitionsInput): void => {\n const { canvas, closeCanvas, resetCanvas } = useConversationWidgetContext();\n const canvasBehaviour = canvas ? (canvasBehaviourOf(canvas.canvasId) ?? null) : null;\n\n const previousConversationIdRef = useRef(conversationId);\n useEffect(() => {\n const previousConversationId = previousConversationIdRef.current;\n previousConversationIdRef.current = conversationId;\n if (previousConversationId === undefined || previousConversationId === conversationId) return;\n resetCanvas();\n }, [conversationId, resetCanvas]);\n\n const canvasClosesOnNarrowRef = useRef(false);\n canvasClosesOnNarrowRef.current = canvasBehaviour !== null && canvasBehaviour.narrowViewport === \"none\";\n useEffect(() => {\n if (!canvasViable && canvasClosesOnNarrowRef.current) closeCanvas(false);\n }, [canvasViable, closeCanvas]);\n};\n","import { Button, SplitView } from \"../provider/components\";\nimport type { ChatAssistantCategory, ChatAssistantIdentity, ChatAssistantOpening } from \"./chat-assistant-identity\";\nimport { classNames } from \"../provider/class-names\";\nimport React, { CSSProperties, useRef, useState } from \"react\";\nimport { useCanvasViable } from \"../widgets/CanvasLauncherWidget/use-canvas-viable\";\nimport {\n CANVAS_MIN_WIDTH_PX,\n CHAT_COLUMN_MIN_WIDTH_PX,\n DEFAULT_CANVAS_WIDTH_PERCENT,\n type CanvasId,\n canvasBehaviourOf,\n canvasWidthPercentOf,\n} from \"../renderer/canvas/canvas-behaviours\";\nimport { ConversationViewBody } from \"./ConversationViewBody/ConversationViewBody\";\nimport type { MessageTimesMode } from \"./ConversationMessageList/message-times\";\nimport { ConversationErrorType } from \"./store/conversation-error-type\";\nimport type { ChatMessage } from \"./chat-message\";\nimport { ConversationMessageUserTheme } from \"./ConversationMessage/ConversationMessageUser/ConversationMessageUser\";\nimport { ConversationMessageInputHandle } from \"./ConversationMessageInput/ConversationMessageInput\";\nimport type { ConversationAttachmentReference } from \"../contract/conversation\";\nimport type { ConversationComposerWidget } from \"../renderer/conversation-composer-widget\";\nimport { SendMessageHandler } from \"./conversation-send-message\";\nimport { CanvasPane } from \"./CanvasPane/CanvasPane\";\nimport { CanvasResizeHandle } from \"./CanvasResizeHandle/CanvasResizeHandle\";\nimport { useCanvasShellTransitions } from \"./use-canvas-shell-transitions\";\nimport { useConversationWidgetContext } from \"../renderer/ConversationWidgetContext\";\nimport { CanvasLabelContext } from \"../renderer/canvas/canvas-label-context\";\nimport { useCanvasLayout } from \"./canvas-layout\";\nimport classes from \"./Conversation.module.scss\";\n\nexport interface ConversationViewProps {\n currentCategory?: ChatAssistantCategory; // Type from categories\n aiPromptExtension?: ChatAssistantIdentity; // Type from agents\n suggestions?: ChatAssistantOpening[]; // Type from conversationOpenings\n messages: ChatMessage[] | null; // Type from messages\n aiThinking: boolean;\n error: ConversationErrorType | null;\n /** Retry-After seconds of a 429 quota rejection — forwarded to the error card for the \"try again in …\" wording. */\n rateLimitRetryAfterSeconds?: number | null;\n /**\n * Host-bound retry of a FAILED run: re-drives the persisted, unanswered customer message\n * server-side. Each host binds it to ITS chat slice; forwarded through the body to the message list / error card.\n */\n onRetryFailedRun?: () => Promise<void>;\n /**\n * True when the host (the agent) is minimized to the compact side-panel; forwarded to ConversationViewBody.\n */\n isCompact?: boolean;\n isDebugMode: boolean;\n categoriesLoaded: boolean;\n conversationId?: number;\n startingNewConversation?: boolean;\n /**\n * Show the message list even when no conversation exists yet. Used by a host,\n * whose fresh (not-yet-created) chat renders its empty message list.\n */\n showMessagesWithoutConversation?: boolean;\n /**\n * Follow the conversation bottom (scroll-on-mount + resize follow). Default true.\n * A host disables it for a fresh chat that has no messages yet.\n */\n autoScroll?: boolean;\n /**\n * Custom node mounted at the tail of the message list instead of the default\n * (thinking-only) ConversationMessageThinking. Rendered permanently — used by\n * A host to show the animated agent face, which idles between turns.\n */\n thinkingIndicator?: React.ReactNode;\n /**\n * Hide the assistant header (icon + name + \"Assistant\") and the copy button\n * on assistant messages. Used by a host, which renders bare messages.\n */\n hideAssistantMeta?: boolean;\n /**\n * Theme for user-message bubbles, passed through to ConversationViewBody →\n * ConversationMessageList. A host forces \"dark\"; omitted elsewhere.\n */\n userMessageTheme?: ConversationMessageUserTheme;\n /**\n * Custom background slot passed through to ConversationViewBody. When provided, the\n * default chat gradient and AI-Extensions illustrations are suppressed.\n */\n background?: React.ReactNode;\n /**\n * Opt-in: the host paints the chat's background itself, OUTSIDE this component — passed through to ConversationViewBody,\n * which keeps the same `customBg` visual mode (transparent pane) `background` would give it, minus\n * a background node of its own to render (see ConversationViewBody's `backgroundPaintedByHost`).\n */\n backgroundPaintedByHost?: boolean;\n /**\n * Optional ref forwarded to ConversationViewBody's scrollable content wrapper.\n * Callers use this to drive scroll-linked effects on top of the chat — e.g.\n * `useShaderScrollMorph` for the animated background.\n */\n scrollRef?: React.Ref<HTMLDivElement>;\n /** Bump to force a scroll to the newest message — forwarded to ConversationViewBody (see its `scrollToBottomNonce`). */\n scrollToBottomNonce?: number;\n /**\n * Optional external bottom-follow flag, forwarded to ConversationViewBody (see its `followBottomRef`). A host sets it `false`\n * for a programmatic jump away from the bottom (e.g. the search-result jump) so the follow effects stop yanking the\n * view back. Left undefined, ConversationViewBody uses its own internal flag.\n */\n followBottomRef?: React.MutableRefObject<boolean>;\n /**\n * Optional \"a programmatic jump is in flight\" gate, forwarded to ConversationViewBody (see its `scrollJumpActiveRef`). While\n * true, ConversationViewBody neither re-enables bottom-follow on scroll nor auto-scrolls to the bottom on resize, so the\n * host's jump isn't fought by the near-bottom onScroll handler or the resize-follow. Left undefined → no gating.\n */\n scrollJumpActiveRef?: React.MutableRefObject<boolean>;\n /**\n * Render the chat body alone, without the two-pane ModalSplitView. The split view's\n * second pane is sized for a full-width modal, so in a narrow side panel (e.g. an\n * app's editor drawer) it overlays whatever sits beside the panel — and those hosts\n * don't use widget content-drawers anyway.\n */\n disableSplitView?: boolean;\n /**\n * Opt-in: show the round divider FAB that toggles the canvas (open → close, closed → re-open the last canvas).\n * Off by default — ConversationView is shared (generic AI-extensions chat, a host, agent); only hosts that want the\n * divider toggle (agent) enable it.\n */\n enableCanvasToggle?: boolean;\n /**\n * Opt-in (agent): render the side-split canvas as a rounded surface card (border-radius + surface background)\n * so it sits neatly alongside the left side of the host's floating top bar, instead of a flush full-height pane.\n * Only the card surface is gated here and only while the canvas is a side-split (viewport ≥ 850px); the small\n * inset that keeps the canvas clear of the pane edge applies to every canvas (see CanvasPane `.root`),\n * including the narrow full-screen overlay below 850px (where the host hides its top bar, AW-57).\n */\n boxCanvasBelowTopBar?: boolean;\n /**\n * Opt-in (agent host only): confine the customBg top blur band to the chat pane (position: sticky, sized to\n * the pane) instead of the whole viewport (position: fixed, the default for a custom `background` in full-screen\n * mode). Turn on only while a sibling side panel is docked beside the chat (sideCard mode) — otherwise the band\n * would stay full-viewport-width and bleed over the panel instead of compressing together with the chat. Forwarded\n * straight through to ConversationViewBody, which owns the actual CSS (see its `.confineTopBlurBandToChatPane`).\n */\n confineTopBlurBandToChatPane?: boolean;\n /**\n * The setup progress stepper (today's only consumer: the agent chat), forwarded straight through to\n * ConversationViewBody, which mounts it as a direct child of its positioned pane root — the node brings its own\n * positioning. It lands INSIDE this view's split, so an open canvas contracts it along with the chat; that pane\n * boundary is why the host cannot place the strip itself.\n */\n progressStepperSlot?: React.ReactNode;\n /** See ConversationViewBody: the host's layer while files are dragged over the window. */\n fileDropHintSlot?: React.ReactNode;\n /**\n * Scroll-up older-message pagination (opt-in — forwarded to ConversationViewBody). When `onLoadOlder` is provided, a top\n * sentinel prefetches the next older page and the viewport is anchored across the prepend. Default off.\n */\n hasMoreOlder?: boolean;\n loadingOlder?: boolean;\n onLoadOlder?: () => void;\n /**\n * Extra action controls rendered inside the chat input's action row, left of the send button —\n * spread through to ConversationViewBody → ConversationMessageInput (e.g. the agent model picker pill).\n */\n inputActionsSlot?: React.ReactNode;\n /**\n * Action controls pinned to the LEFT edge of the chat input's action row (`inputActionsSlot`\n * stays right) — spread through to ConversationViewBody → ConversationMessageInput (e.g. the agent \"+\" attachments menu).\n */\n inputActionsSlotStart?: React.ReactNode;\n /**\n * Host-owned content rendered inside the chat input above its editable text area — attachment\n * preview cards, validation error boxes. Spread through to ConversationViewBody → ConversationMessageInput's `topSlot`.\n */\n inputTopSlot?: React.ReactNode;\n /**\n * Hard send gate for the chat input: blocks the send button AND Enter while true, but keeps the\n * text editable. The host sets it e.g. while attachment uploads run.\n */\n inputSendDisabled?: boolean;\n /**\n * Host-owned content rendered IN PLACE of the chat input — the closed-conversation bar of a completed\n * setup conversation (no further input possible). When set, ConversationViewBody renders it instead of ConversationMessageInput.\n */\n inputReplacementSlot?: React.ReactNode;\n /**\n * Host-owned band right above the chat input, the input overlapping its lower edge — e.g. the running voice chat\n * with its controls. Not rendered while `inputReplacementSlot` replaces the input.\n */\n inputBandSlot?: React.ReactNode;\n /** The chat input's placeholder; the input's own default otherwise. */\n inputPlaceholder?: string;\n /** Forwarded to ConversationMessageInput's `sendReplacementWhenEmpty`. */\n inputSendReplacementWhenEmpty?: React.ReactNode;\n /** Forwarded to ConversationMessageInput's `glowUnderlay`. */\n inputGlowUnderlay?: React.ReactNode;\n /**\n * Host-owned layer over the message column, the same size — e.g. the voice chat's focus mode. The message column\n * stays mounted under it (scroll position and widget state kept); `isContentOverlayShown` switches between them.\n */\n contentOverlaySlot?: React.ReactNode;\n isContentOverlayShown?: boolean;\n /**\n * Uploaded media-library images that ride along in `onSendMessage`'s options object (`attachments`) on the next\n * send. Owned and cleared by the host; ConversationView/ConversationMessageInput only forward them.\n */\n outgoingAttachmentImages?: ConversationAttachmentReference[];\n /**\n * Composer widgets the host holds outside the widget context (e.g. a widget built from the files the host\n * uploaded), sent like the context's own on the next send. Owned and cleared by the host;\n * ConversationView/ConversationMessageInput only forward them.\n */\n hostComposerWidgets?: ConversationComposerWidget[];\n /**\n * Imperative handle on the chat input (insertTextIntoInput) so host-owned controls — e.g. the\n * \"+\" menu's \"Generate image\" entry — can put text into it.\n */\n conversationMessageInputApiRef?: React.Ref<ConversationMessageInputHandle>;\n /**\n * Keep the chat input editable and sendable while `aiThinking` is true (default false — the input locks for the\n * whole turn); only the first post of a new conversation still locks it, while no conversation id exists yet. Opt\n * in ONLY for a host whose post call stores the message and returns at once, and whose agent checks for unanswered\n * messages when its turn ends, so a message sent mid-turn is answered in the next turn. A host whose post call\n * generates the reply synchronously within the request has no such guard and must leave it off.\n */\n allowSendWhileAiThinking?: boolean;\n /**\n * Opt-in long-answer reading flow (AW-107), default false — spread through to ConversationViewBody. When enabled:\n * (1) on send, the question is pinned to the top with room reserved below it; (2) a scroll-to-latest-message\n * button floats above the input while the bottom is out of view; (3) a fresh static reply's markdown blocks\n * fade in staggered. AI Extensions stays off; the agent chat opts in.\n */\n enablePinQuestionAndRevealAnswer?: boolean;\n /** Forwarded to ConversationViewBody's `isQuestionPinSuspended`. */\n isQuestionPinSuspended?: boolean;\n /**\n * Id of the ONE user message ConversationMessageList renders as a collapsed task-instruction disclosure instead of an\n * owner bubble — the machine-composed seed instruction of a SCHEDULE-spawned run (UX overhaul W4 item 19).\n * Forwarded through ConversationViewBody. Undefined (every host except the agent chat) changes nothing.\n */\n taskInstructionMessageId?: number;\n /**\n * Host content rendered right after one message of the thread — the agent chat's activity card under the message that\n * started each turn. Forwarded through ConversationViewBody to ConversationMessageList. Undefined changes nothing.\n */\n renderAfterMessage?: (message: ChatMessage) => React.ReactNode;\n /** Host content beside each shown assistant message (an avatar face), forwarded through ConversationViewBody. */\n renderAssistantAvatar?: (message: ChatMessage) => React.ReactNode;\n /** Forwarded through ConversationViewBody to ConversationMessageList: a closed conversation renders no widget controls. */\n isConversationClosed?: boolean;\n /** Forwarded through ConversationViewBody to ConversationMessageList: when what was written (`MessageTimesMode`). */\n messageTimes?: MessageTimesMode | null;\n onSuggestionClick: (text: string) => void;\n onSendMessage: SendMessageHandler;\n}\n\nexport const ConversationView = (props: ConversationViewProps) => {\n const { enableCanvasToggle, boxCanvasBelowTopBar, onSendMessage, conversationId, messages } = props;\n const { canvas, lastClosedCanvas, closeCanvas, reopenLastClosedCanvas, resetCanvasForNewTurn } =\n useConversationWidgetContext();\n const canvasViable = useCanvasViable();\n // The host's frame of the canvas (`AgentsEnvironment.canvasLayout`): its own chrome replaces the package's controls.\n const canvasLayout = useCanvasLayout();\n const chatColumnMinWidthPx = canvasLayout.chatColumnMinWidthPx;\n // The short name the open body reports (`useCanvasLabel`), handed to the SplitView for a host's tab or head.\n const [canvasLabel, setCanvasLabel] = useState<string | null>(null);\n // The canvas is a pointer in the chat's slice; its geometry comes from its behaviour (`canvas-behaviours.ts`).\n const canvasBehaviour = canvas ? (canvasBehaviourOf(canvas.canvasId) ?? null) : null;\n const isCanvasOpen = canvas !== null;\n // The conversation switch clears the canvas; the wide → narrow crossing closes a `narrowViewport: \"none\"` canvas.\n useCanvasShellTransitions({ conversationId, canvasViable });\n\n // A new user message starts a new turn — the previous turn's canvas is now stale, so tear it down AND drop the\n // divider FAB (the reset clears `canReopenDrawer`). Runs before the reply arrives, so a fresh canvas opened by the\n // new reply is unaffected. A PINNED canvas (a work surface for the whole conversation, not one\n // turn's result) survives — that is the only difference to `resetCanvas`.\n const handleSendMessage: SendMessageHandler = (message, options) => {\n resetCanvasForNewTurn();\n onSendMessage(message, options);\n };\n\n // The canvas pane starts at the width its behaviour declares; the customer can pull its left edge (`CanvasResizeHandle`).\n // The split reads the width from `--agents-canvas-width-set` (a percentage, or the clamped pull in px), so a drag moves the edge without a\n // render. The width of the last shown canvas is kept while the pane slides out. The divider toggle + slide derive from it.\n const lastCanvasWidthPercentRef = useRef(DEFAULT_CANVAS_WIDTH_PERCENT);\n if (canvasBehaviour) lastCanvasWidthPercentRef.current = canvasWidthPercentOf(canvasBehaviour);\n const canvasWidthPercent = lastCanvasWidthPercentRef.current;\n const boxCanvas = !!boxCanvasBelowTopBar && canvasViable;\n const canvasInset = boxCanvas ? canvasLayout.boxedInsetPx : 0;\n const splitViewRootRef = useRef<HTMLDivElement>(null);\n // The pull belongs to the canvas it was made on: another canvas starts at its own default split.\n const lastCanvasIdRef = useRef<CanvasId | null>(null);\n if (canvas) lastCanvasIdRef.current = canvas.canvasId;\n const [pulledCanvas, setPulledCanvas] = useState<{ canvasId: CanvasId; width: number } | null>(null);\n const pulledCanvasWidth = pulledCanvas?.canvasId === lastCanvasIdRef.current ? pulledCanvas.width : null;\n const setPulledCanvasWidth = (width: number | null) =>\n setPulledCanvas(width !== null && lastCanvasIdRef.current ? { canvasId: lastCanvasIdRef.current, width } : null);\n const canvasResizable = canvasBehaviour?.layout === \"split\" && canvasViable && !props.isCompact;\n const splitViewRootStyle = {\n \"--agents-canvas-width-set\":\n pulledCanvasWidth === null\n ? canvasLayout.chatColumnMinWidthPx === CHAT_COLUMN_MIN_WIDTH_PX\n ? `${canvasWidthPercent}%`\n : // a host's own chat minimum also caps the default split (the package's minimum is met by every viable split)\n `min(${canvasWidthPercent}%, calc(100% - ${chatColumnMinWidthPx}px))`\n : `clamp(${CANVAS_MIN_WIDTH_PX + canvasInset * 2}px, ${pulledCanvasWidth}px, calc(100% - ${chatColumnMinWidthPx}px))`,\n \"--agents-canvas-inset\": `${canvasInset}px`,\n } as CSSProperties;\n\n // The canvas toggle button on the divider: closes the open canvas (the customer's own close), re-opens the last\n // closed one.\n const toggleCanvas = () => {\n if (canvas) closeCanvas(true);\n else reopenLastClosedCanvas();\n };\n // On a narrow viewport the divider (and its toggle) does not exist: the canvas is a full-screen overlay. The canvases\n // whose widgets render nothing inline would have no way back after a close, so the shell offers its own re-open\n // control over the chat, fed by `lastClosedCanvas`, independent of transcript windowing.\n const showsNarrowReopenControl =\n !!enableCanvasToggle &&\n canvasLayout.showsNarrowReopenControl &&\n !canvasViable &&\n !isCanvasOpen &&\n lastClosedCanvas !== null;\n\n if (props.disableSplitView) {\n return <ConversationViewBody {...props} />;\n }\n\n return (\n <div ref={splitViewRootRef} className={classes.splitViewRoot} style={splitViewRootStyle}>\n {showsNarrowReopenControl ? (\n <div className={classes.canvasReopenControl}>\n <Button\n variant=\"muted\"\n icon=\"maximize\"\n iconPosition={\"left\"}\n rounded\n blurred\n size=\"small\"\n onClick={reopenLastClosedCanvas}\n >\n Re-open canvas\n </Button>\n </div>\n ) : null}\n <SplitView\n isSideOpen={isCanvasOpen}\n coversBelowWidth={850}\n // The canvas toggle button on the divider: closes the open canvas, or re-opens the last closed one. Shown only\n // while a canvas is open or one was closed — otherwise there's nothing to toggle.\n sideToggle={\n enableCanvasToggle &&\n canvasLayout.showsDividerToggle &&\n !canvasResizable &&\n (isCanvasOpen || lastClosedCanvas !== null)\n ? {\n onToggle: toggleCanvas,\n // Centered vertically on the divider.\n verticalPositionPercent: 50,\n // The chat's own re-open control is shown: the split view adds no second one while it covers.\n mainPaneShowsReopen: showsNarrowReopenControl,\n // The canvas pane carries its own close button: no floating toggle over it while it covers the chat.\n sidePaneShowsClose: canvasLayout.showsCloseButton,\n }\n : undefined\n }\n sideLabel={isCanvasOpen && canvasLabel !== null ? canvasLabel : undefined}\n main={{\n width: \"100%\",\n narrowedWidth: \"calc(100% - var(--agents-canvas-width))\",\n // The pane's default inline background (var(--agents-neutral-000)) would occlude a host-painted background layer.\n background: props.backgroundPaintedByHost ? \"transparent\" : undefined,\n content: <ConversationViewBody {...props} onSendMessage={handleSendMessage} />,\n }}\n side={{\n width: \"var(--agents-canvas-width)\",\n narrowedWidth: \"var(--agents-canvas-width)\",\n content: (\n // Boxed only while side-split: below 850px the canvas is a full-screen overlay and stays full-bleed.\n <div\n className={classNames(\n classes.splitViewPane,\n boxCanvas && canvasLayout.paneSurface === \"card\" ? classes.splitViewPaneBoxed : \"\",\n )}\n >\n <CanvasLabelContext.Provider value={setCanvasLabel}>\n <CanvasPane messages={messages} boxed={boxCanvas} />\n </CanvasLabelContext.Provider>\n </div>\n ),\n }}\n />\n {canvasResizable ? (\n <CanvasResizeHandle\n rootRef={splitViewRootRef}\n inset={canvasInset}\n chatColumnMinWidthPx={chatColumnMinWidthPx}\n width={pulledCanvasWidth}\n onWidthChange={setPulledCanvasWidth}\n onClose={() => closeCanvas(true)}\n />\n ) : null}\n </div>\n );\n};\n","import type { ConversationActivityElement } from \"../../contract/conversation\";\n\n/**\n * What the activity read sends per element and the stack reads (`ConversationActivityElement`); every field may be\n * missing on an element a caller builds by hand (stories, specs).\n */\nexport type ActivityLineInput = Partial<ConversationActivityElement>;\n\n/** One row of the stack: the element as the endpoint sent it last, keyed by its tool-call message id. */\nexport type ActivityElement = ActivityLineInput & { toolCallMessageId: number };\n\nconst STATE_RANK: Record<string, number> = { queued: 0, running: 1, finished: 2, failed: 2, skipped: 2 };\n\n/**\n * Merge a response into the stack: a later state replaces an earlier one, a line never disappears once told (an\n * element answered without a line, because the narrator was late, keeps the sentence it already had), and an element\n * the response no longer carries stays (the turn snapshot is complete, so this only happens on a pinned turn that a\n * later turn pushed out of the window). Row order is the endpoint's: the order of the persisted rows.\n */\nexport const mergeActivityElements = (\n previous: ActivityElement[],\n incoming: ActivityLineInput[] | null | undefined,\n): ActivityElement[] => {\n const byId = new Map<number, ActivityElement>(previous.map((element) => [element.toolCallMessageId, element]));\n const ordered: number[] = [];\n (incoming ?? []).forEach((element) => {\n const id = element.toolCallMessageId;\n if (id == null || id <= 0) return;\n ordered.push(id);\n const known = byId.get(id);\n if (!known) {\n byId.set(id, { ...element, toolCallMessageId: id });\n return;\n }\n const knownRank = STATE_RANK[known.state ?? \"queued\"] ?? 0;\n const incomingRank = STATE_RANK[element.state ?? \"queued\"] ?? 0;\n // A state never moves backwards (a stale response after a fresher one).\n if (incomingRank < knownRank) return;\n const stateAdvanced = incomingRank > knownRank || known.state !== element.state;\n byId.set(id, {\n ...known,\n ...element,\n toolCallMessageId: id,\n // The finished line replaces the started one; a missing line keeps what was told, unless the state advanced\n // (then the started sentence would misdescribe a finished step, so the row shows its state alone).\n line: element.line ?? (stateAdvanced ? null : (known.line ?? null)),\n });\n });\n // Rows the response carried, in its order, then rows it no longer carries, in their previous order.\n const carried = new Set(ordered);\n const kept = previous\n .filter((element) => !carried.has(element.toolCallMessageId))\n .map((element) => element.toolCallMessageId);\n return [...kept, ...ordered].map((id) => byId.get(id)!);\n};\n\n/** The rows the customer reads: skipped elements carry nothing. */\nexport const visibleActivityElements = (elements: ActivityElement[]): ActivityElement[] =>\n elements.filter((element) => element.state !== \"skipped\");\n\n/**\n * Whether a response names a turn different from the one pinned locally — the stack must start clean instead of\n * merging the new turn's rows into the previous (already folded) one. False until a turn is pinned, and false while\n * the response has not named a turn yet (a request still in flight for the newly pinned, not-yet-answered turn).\n */\nexport const isDifferentTurn = (pinnedTurnMessageId: number | null, answeredTurnMessageId: number | null): boolean =>\n pinnedTurnMessageId !== null && answeredTurnMessageId !== null && answeredTurnMessageId !== pinnedTurnMessageId;\n","import { ActivityElement, visibleActivityElements } from \"./merge-activity-elements\";\n\n/**\n * The least time a line stands beside the face before the next one takes its place — the concept's rhythm (the agent\n * prototype's ThinkingIndicator swaps its line every 2.2 s), so every sentence can be read between two swaps.\n */\nexport const LINE_PACE_MS = 2200;\n/** The shorter wait while more than {@link BACKLOG_THRESHOLD} lines are queued, so a burst catches up. */\nexport const BACKLOG_LINE_PACE_MS = 1400;\nconst BACKLOG_THRESHOLD = 2;\n/**\n * More queued lines than this are shown at once, oldest first: one narrator answer carries up to 8 lines, and the\n * ticker must never trail the turn by more than a few seconds.\n */\nexport const MAX_WAITING_LINES = 4;\n/** Finished turns kept in the thread at most (keepActivityHistoryAfterAnswer); the oldest one falls away beyond. */\nexport const MAX_KEPT_TURNS = 30;\n\n/** One sentence the ticker shows: the started or the finished line of one step. */\nexport interface ActivityTickerLine {\n toolCallMessageId: number;\n /** The step's state when this line was told: queued / running / finished / failed. */\n state: string;\n line: string;\n kind: string | null;\n /** The delegation helper that ran the step (1-based); null for the assistant's own steps. */\n helperIndex: number | null;\n}\n\n/** Whether the line's step was still at work (queued or running) when the line was told, not finished or failed. */\nexport const isStepStillRunning = (line: ActivityTickerLine): boolean =>\n line.state === \"queued\" || line.state === \"running\";\n\n/**\n * What the ticker shows and what still waits to be shown. The endpoint delivers lines in bursts (one request per 3 s,\n * up to 8 lines per narrator answer); this queue hands them to the screen one at a time.\n */\nexport interface ActivityTickerQueue {\n /** The line each step shows right now, keyed by its tool-call message id. */\n shownLines: Record<number, ActivityTickerLine>;\n /** The steps shown before the newest one, oldest first; never contains {@link currentId}. */\n trailIds: number[];\n /** The step whose line was shown last: the one beside the face. */\n currentId: number | null;\n /** Lines not shown yet, oldest first, at most one per step (a newer line of the same step replaces the waiting one). */\n waitingLines: ActivityTickerLine[];\n /** When the newest line last changed (ms since epoch); the pace counts from here. */\n lastShownAt: number;\n}\n\nexport const EMPTY_ACTIVITY_TICKER_QUEUE: ActivityTickerQueue = {\n shownLines: {},\n trailIds: [],\n currentId: null,\n waitingLines: [],\n lastShownAt: Number.NEGATIVE_INFINITY,\n};\n\n/**\n * The element as a ticker line. An element without a sentence keeps the sentence already told for its step and takes\n * its new state: mergeActivityElements drops the started sentence when a step finishes before the narrator described\n * the finish, and the row must then show its check (or its failure) instead of running on. A step never told has\n * nothing to show.\n */\nconst toTickerLine = (\n element: ActivityElement,\n toldLine: ActivityTickerLine | undefined,\n): ActivityTickerLine | null => {\n const sentence = element.line ?? toldLine?.line;\n if (!sentence) return null;\n return {\n toolCallMessageId: element.toolCallMessageId,\n state: element.state ?? \"queued\",\n line: sentence,\n kind: element.kind ?? null,\n helperIndex: element.helperIndex ?? null,\n };\n};\n\nconst isSameLine = (shown: ActivityTickerLine | undefined, incoming: ActivityTickerLine) =>\n !!shown && shown.state === incoming.state && shown.line === incoming.line;\n\nconst LINE_STATE_RANK: Record<string, number> = { queued: 0, running: 1, finished: 2, failed: 2, skipped: 2 };\n\n/** Whether the incoming line is of an earlier state than the one already told for its step (a stale read). */\nconst isOlderStateThan = (told: ActivityTickerLine | undefined, incoming: ActivityTickerLine) =>\n !!told && (LINE_STATE_RANK[incoming.state] ?? 0) < (LINE_STATE_RANK[told.state] ?? 0);\n\n/** Every shown line in the order it was told, oldest first. */\nexport const shownLinesInOrder = (queue: ActivityTickerQueue): ActivityTickerLine[] =>\n [...queue.trailIds, ...(queue.currentId !== null ? [queue.currentId] : [])]\n .map((stepId) => queue.shownLines[stepId])\n .filter(Boolean);\n\n/**\n * Put one line on screen. A line of a step already told replaces that step's line in place (the history keeps every\n * step once); any other line becomes the newest one, beside the face, and the previous newest one moves up into the\n * trail.\n */\nexport const showActivityLine = (\n queue: ActivityTickerQueue,\n line: ActivityTickerLine,\n now: number,\n): ActivityTickerQueue => {\n const stepId = line.toolCallMessageId;\n const shownLines = { ...queue.shownLines, [stepId]: line };\n if (queue.currentId === stepId) {\n return { ...queue, shownLines, lastShownAt: now };\n }\n if (queue.trailIds.includes(stepId)) {\n return { ...queue, shownLines };\n }\n const trailIds = queue.currentId !== null ? [...queue.trailIds, queue.currentId] : queue.trailIds;\n return { ...queue, shownLines, trailIds, currentId: stepId, lastShownAt: now };\n};\n\n/**\n * Take the endpoint's elements in: every line not shown yet waits in the queue, except the finished line of a step\n * already in the trail, which replaces that row in place at once. Skipped elements and elements of a step never told\n * a sentence never show (only generated sentences appear).\n */\nexport const receiveActivityElements = (\n queue: ActivityTickerQueue,\n elements: ActivityElement[],\n now: number,\n): ActivityTickerQueue => {\n let nextQueue = queue;\n visibleActivityElements(elements).forEach((element) => {\n const stepId = element.toolCallMessageId;\n const waitingLine = nextQueue.waitingLines.find((line) => line.toolCallMessageId === stepId);\n const incomingLine = toTickerLine(element, waitingLine ?? nextQueue.shownLines[stepId]);\n if (!incomingLine) return;\n const toldLine = waitingLine ?? nextQueue.shownLines[stepId];\n // per step the later state wins: a read that arrives out of order never moves a told step back\n if (isSameLine(toldLine, incomingLine) || isOlderStateThan(toldLine, incomingLine)) {\n return;\n }\n if (nextQueue.trailIds.includes(stepId)) {\n nextQueue = {\n ...nextQueue,\n shownLines: { ...nextQueue.shownLines, [stepId]: incomingLine },\n waitingLines: nextQueue.waitingLines.filter((line) => line.toolCallMessageId !== stepId),\n };\n return;\n }\n nextQueue = {\n ...nextQueue,\n waitingLines: waitingLine\n ? nextQueue.waitingLines.map((line) => (line.toolCallMessageId === stepId ? incomingLine : line))\n : [...nextQueue.waitingLines, incomingLine],\n };\n });\n while (nextQueue.waitingLines.length > MAX_WAITING_LINES) {\n const [oldestWaitingLine, ...laterWaitingLines] = nextQueue.waitingLines;\n nextQueue = showActivityLine({ ...nextQueue, waitingLines: laterWaitingLines }, oldestWaitingLine, now);\n }\n return nextQueue;\n};\n\n/**\n * Milliseconds until the next waiting line may be shown; null when nothing waits. The paces default to\n * {@link LINE_PACE_MS} and {@link BACKLOG_LINE_PACE_MS} (a host sets its own through the chat's `activityTiming`).\n */\nexport const msUntilNextActivityLine = (\n queue: ActivityTickerQueue,\n now: number,\n linePaceMs: number = LINE_PACE_MS,\n backlogLinePaceMs: number = BACKLOG_LINE_PACE_MS,\n): number | null => {\n if (queue.waitingLines.length === 0) return null;\n const pace = queue.waitingLines.length > BACKLOG_THRESHOLD ? backlogLinePaceMs : linePaceMs;\n return Math.max(0, queue.lastShownAt + pace - now);\n};\n\n/** Show the oldest waiting line. The caller's timer decides when (see {@link msUntilNextActivityLine}). */\nexport const releaseNextActivityLine = (queue: ActivityTickerQueue, now: number): ActivityTickerQueue => {\n if (queue.waitingLines.length === 0) return queue;\n const [oldestWaitingLine, ...laterWaitingLines] = queue.waitingLines;\n return showActivityLine({ ...queue, waitingLines: laterWaitingLines }, oldestWaitingLine, now);\n};\n\n/** Show every waiting line at once, oldest first — the turn has ended and the answer is on screen. */\nexport const releaseAllActivityLines = (queue: ActivityTickerQueue, now: number): ActivityTickerQueue => {\n const queueWithoutWaitingLines: ActivityTickerQueue = { ...queue, waitingLines: [] };\n return queue.waitingLines.reduce(\n (nextQueue, waitingLine) => showActivityLine(nextQueue, waitingLine, now),\n queueWithoutWaitingLines,\n );\n};\n\n/** Steps the turn has finished or failed, the count the ticker reports. */\nexport const countFinishedSteps = (elements: ActivityElement[]): number =>\n visibleActivityElements(elements).filter((element) => element.state === \"finished\" || element.state === \"failed\")\n .length;\n\n/**\n * Delegation helpers with a step queued or running right now; a helper running several tool calls counts once. The\n * helper number restarts at 1 for every delegate call, so a helper is told apart by the delegate call its steps follow\n * (the endpoint lists each delegate call's helper steps right after it).\n */\nexport const countWorkingHelpers = (elements: ActivityElement[]): number => {\n const workingHelperKeys = new Set<string>();\n let delegateCallId: number | null = null;\n elements.forEach((element) => {\n if (element.helperIndex == null) {\n if (element.kind === \"delegation\" || element.kind === \"background\") delegateCallId = element.toolCallMessageId;\n return;\n }\n if (element.state === \"queued\" || element.state === \"running\") {\n workingHelperKeys.add(`${delegateCallId}:${element.helperIndex}`);\n }\n });\n return workingHelperKeys.size;\n};\n\n/** \"0:42\" / \"2:04\" — elapsed time as a clock, no unit to translate. */\nexport const formatElapsedClock = (elapsedMs: number): string => {\n const elapsedSeconds = Math.max(0, Math.floor(elapsedMs / 1000));\n return `${Math.floor(elapsedSeconds / 60)}:${String(elapsedSeconds % 60).padStart(2, \"0\")}`;\n};\n\n/** Nothing on screen · lines beside the face while the turn runs · the face's success beat after it ended. */\nexport type ActivityTickerPhase = \"idle\" | \"live\" | \"done\";\n\n/** A finished turn whose lines stay in the thread, above its answer, under the message that started it. */\nexport interface KeptActivityTurn {\n turnMessageId: number;\n /** Every line the turn told, oldest first. */\n lines: ActivityTickerLine[];\n}\n\nexport interface ActivityTickerState {\n queue: ActivityTickerQueue;\n phase: ActivityTickerPhase;\n /** The message that started the turn on screen, as the endpoint named it; null until it did. */\n turnMessageId: number | null;\n /** When the running turn started on this screen (ms since epoch), for the elapsed clock; null before any turn. */\n liveSince: number | null;\n /** Finished turns that stay in the thread, oldest first; filled only while the history is kept. */\n keptTurns: KeptActivityTurn[];\n /** The `running` of the previous input, to see where a turn starts and ends. */\n wasRunning: boolean;\n}\n\nexport const INITIAL_ACTIVITY_TICKER_STATE: ActivityTickerState = {\n queue: EMPTY_ACTIVITY_TICKER_QUEUE,\n phase: \"idle\",\n turnMessageId: null,\n liveSince: null,\n keptTurns: [],\n wasRunning: false,\n};\n\nexport type ActivityTickerAction =\n | {\n type: \"elementsReceived\";\n elements: ActivityElement[];\n running: boolean;\n failed: boolean;\n turnMessageId: number | null;\n /** A turn in its success beat that the next turn replaces goes into {@link ActivityTickerState.keptTurns} first. */\n keepHistory: boolean;\n now: number;\n }\n | { type: \"nextLineDue\"; now: number }\n | { type: \"doneBeatOver\"; keepHistory: boolean };\n\n/**\n * Whether a read belongs to another turn than the one on screen: the endpoint names a different turn message, or a\n * turn starts after the previous one left the live phase and its message is not named yet (the read hook unpins the\n * turn on a new start, so a new turn arrives unnamed) or named differently. A read that merely misses a step already\n * shown — a read of fewer rows, an answer that overtook a later one — is the same turn: its lines stay.\n */\nconst isReadOfAnotherTurn = (\n state: ActivityTickerState,\n turnMessageId: number | null,\n turnStarted: boolean,\n): boolean => {\n if (state.turnMessageId !== null && turnMessageId !== null && turnMessageId !== state.turnMessageId) return true;\n return turnStarted && state.phase !== \"live\" && (turnMessageId === null || turnMessageId !== state.turnMessageId);\n};\n\n/**\n * The kept turns plus the turn in its success beat, if it can be placed in the thread (the endpoint named the message\n * that started it). A turn kept before under the same message is replaced: its helpers ended and it ended again.\n */\nconst keptTurnsWithFinishedTurn = (state: ActivityTickerState): KeptActivityTurn[] => {\n const { phase, turnMessageId, queue, keptTurns } = state;\n if (phase !== \"done\" || turnMessageId === null) return keptTurns;\n const finishedTurn: KeptActivityTurn = { turnMessageId, lines: shownLinesInOrder(queue) };\n return [...keptTurns.filter((keptTurn) => keptTurn.turnMessageId !== turnMessageId), finishedTurn].slice(\n -MAX_KEPT_TURNS,\n );\n};\n\n/**\n * The ticker's life across turns. A turn starts when `running` rises: the queue starts clean and the phase goes live.\n * Within a turn the endpoint's snapshot only grows (mergeActivityElements keeps every row it has seen), so a shown step\n * missing from the elements means another turn or another conversation: the queue starts clean. When `running` falls,\n * the waiting lines are shown at once and the face's success beat follows — unless the turn failed or never told a\n * line. After the beat the turn's lines either stay in the thread ({@link KeptActivityTurn}) or are gone, as\n * `keepHistory` says.\n */\nexport const activityTickerReducer = (\n state: ActivityTickerState,\n action: ActivityTickerAction,\n): ActivityTickerState => {\n switch (action.type) {\n case \"elementsReceived\": {\n const { elements, running, failed, keepHistory, now } = action;\n const turnStarted = running && !state.wasRunning;\n const turnEnded = !running && state.wasRunning;\n // Lines already shown in a turn are never dropped: the stack resets only for another turn.\n const startsClean = isReadOfAnotherTurn(state, action.turnMessageId, turnStarted);\n const queue = receiveActivityElements(startsClean ? EMPTY_ACTIVITY_TICKER_QUEUE : state.queue, elements, now);\n let nextState: ActivityTickerState = {\n ...state,\n queue,\n turnMessageId: action.turnMessageId ?? (startsClean ? null : state.turnMessageId),\n wasRunning: running,\n };\n // The turn in its success beat leaves the screen before the next one starts clean: kept in the thread or gone.\n if (startsClean && state.phase === \"done\") {\n nextState = {\n ...nextState,\n phase: \"idle\",\n keptTurns: keepHistory ? keptTurnsWithFinishedTurn(state) : state.keptTurns,\n };\n }\n if (running && startsClean) {\n nextState = { ...nextState, phase: \"live\", liveSince: now };\n }\n if (turnEnded && state.phase === \"live\") {\n const finalQueue = releaseAllActivityLines(queue, now);\n const toldALine = finalQueue.currentId !== null;\n nextState = { ...nextState, queue: finalQueue, phase: toldALine && !failed ? \"done\" : \"idle\" };\n }\n if (failed && nextState.phase === \"done\") {\n nextState = { ...nextState, phase: \"idle\" };\n }\n return nextState;\n }\n case \"nextLineDue\":\n return state.phase === \"live\" ? { ...state, queue: releaseNextActivityLine(state.queue, action.now) } : state;\n case \"doneBeatOver\":\n return state.phase === \"done\"\n ? {\n ...state,\n phase: \"idle\",\n keptTurns: action.keepHistory ? keptTurnsWithFinishedTurn(state) : state.keptTurns,\n }\n : state;\n default:\n return state;\n }\n};\n","import { useEffect, useMemo, useReducer } from \"react\";\n\nimport {\n activityTickerReducer,\n ActivityTickerLine,\n countFinishedSteps,\n countWorkingHelpers,\n ActivityTickerPhase,\n BACKLOG_LINE_PACE_MS,\n INITIAL_ACTIVITY_TICKER_STATE,\n KeptActivityTurn,\n LINE_PACE_MS,\n msUntilNextActivityLine,\n shownLinesInOrder,\n} from \"./activity-ticker\";\nimport { ActivityElement } from \"./merge-activity-elements\";\n\n/**\n * How long the face's success beat rests before the face turns back to idle — counted from the start of the success\n * roll. The ticker keeps or drops the turn's lines once it is over; an app's face times its success roll by it.\n */\nexport const SUCCESS_BEAT_MS = 1400;\n\ninterface UseActivityTickerParams {\n /** The rows of the running turn from {@link useConversationActivity}, in row order. */\n elements: ActivityElement[];\n /** Whether the endpoint says the turn is still in flight. */\n running: boolean;\n /** The message that started the turn, as the endpoint named it; null until it did. */\n turnMessageId?: number | null;\n /** The turn ended in an error: no success beat, nothing kept. */\n failed?: boolean;\n /**\n * After the answer, each finished turn's lines stay in the thread above its answer, under the message that started\n * it; false = they fade out with the line beside the face and nothing remains.\n */\n keepActivityHistoryAfterAnswer?: boolean;\n /** The least time a line stands beside the face. Default `LINE_PACE_MS` (2200). */\n linePaceMs?: number;\n /** The shorter wait while more than two lines are queued. Default `BACKLOG_LINE_PACE_MS` (1400). */\n backlogLinePaceMs?: number;\n /** The success beat's rest. Default {@link SUCCESS_BEAT_MS}. */\n successBeatMs?: number;\n}\n\n/** One turn's lines — the turn running now, in the face's success beat, or kept in the thread. */\nexport interface ActivityTickerTurn {\n /** The message that started the turn: its kept history stands right after it. Null until the endpoint named it. */\n turnMessageId: number | null;\n /** live = the turn runs; done = it ended. */\n phase: \"live\" | \"done\";\n /** Every line told in the turn, oldest first; while live, the last one stands beside the face. */\n lines: ActivityTickerLine[];\n /** Steps finished or failed so far. */\n stepCount: number;\n /** Steps delegation helpers are running right now. */\n helperCount: number;\n /** When the running turn started on this screen (ms since epoch), for the elapsed clock; null once it ended. */\n liveSince: number | null;\n}\n\n/** What the ticker shows right now — read by AgentActivity (the face and its lines) and the history in the thread. */\nexport interface ActivityTicker {\n /** The phase of the turn on screen; the face keeps working while it is live. */\n phase: ActivityTickerPhase;\n /** The turn running now or in the face's success beat; null when idle and before the turn's first line. */\n currentTurn: ActivityTickerTurn | null;\n /**\n * The finished turns whose lines stand in the thread, under the message that started each, oldest first: every kept\n * turn plus the turn in the face's success beat. Empty unless the history is kept; a turn the endpoint never named\n * is never among them (it has no message to stand under).\n */\n historyTurns: ActivityTickerTurn[];\n}\n\nconst toKeptTurn = (keptTurn: KeptActivityTurn): ActivityTickerTurn => ({\n turnMessageId: keptTurn.turnMessageId,\n phase: \"done\",\n lines: keptTurn.lines,\n stepCount: keptTurn.lines.length,\n helperCount: 0,\n liveSince: null,\n});\n\n/**\n * Paces the activity lines of a running turn at the prototype's ThinkingIndicator rhythm. The\n * endpoint delivers lines in bursts; the ticker puts them beside the face one at a time — each stays at least 2.2 s,\n * or 1.4 s while more than two wait — and never falls more than a few lines behind. When the turn ends, the rest is\n * shown at once and the face plays its success beat ({@link SUCCESS_BEAT_MS}); the turn's lines then stay in the\n * thread or are gone, as `keepActivityHistoryAfterAnswer` says. The state machine lives in\n * {@link activityTickerReducer}; this hook only owns the timers.\n */\nexport const useActivityTicker = (params: UseActivityTickerParams): ActivityTicker => {\n const {\n elements,\n running,\n turnMessageId = null,\n failed = false,\n keepActivityHistoryAfterAnswer = false,\n linePaceMs = LINE_PACE_MS,\n backlogLinePaceMs = BACKLOG_LINE_PACE_MS,\n successBeatMs = SUCCESS_BEAT_MS,\n } = params;\n const [state, dispatch] = useReducer(activityTickerReducer, INITIAL_ACTIVITY_TICKER_STATE);\n\n useEffect(() => {\n dispatch({\n type: \"elementsReceived\",\n elements,\n running,\n failed,\n turnMessageId,\n keepHistory: keepActivityHistoryAfterAnswer,\n now: Date.now(),\n });\n // keepActivityHistoryAfterAnswer is read when a turn leaves the screen, it never triggers a receive of its own.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [elements, running, failed, turnMessageId]);\n\n // One timer for the next waiting line; every queue change re-plans it.\n useEffect(() => {\n if (state.phase !== \"live\") return undefined;\n const waitMs = msUntilNextActivityLine(state.queue, Date.now(), linePaceMs, backlogLinePaceMs);\n if (waitMs === null) return undefined;\n const timer = setTimeout(() => dispatch({ type: \"nextLineDue\", now: Date.now() }), waitMs);\n return () => clearTimeout(timer);\n }, [state.phase, state.queue, linePaceMs, backlogLinePaceMs]);\n\n useEffect(() => {\n if (state.phase !== \"done\") return undefined;\n const timer = setTimeout(\n () => dispatch({ type: \"doneBeatOver\", keepHistory: keepActivityHistoryAfterAnswer }),\n successBeatMs,\n );\n return () => clearTimeout(timer);\n }, [state.phase, keepActivityHistoryAfterAnswer, successBeatMs]);\n\n return useMemo(() => {\n const { queue, phase } = state;\n const lines = shownLinesInOrder(queue);\n const currentTurn: ActivityTickerTurn | null =\n phase !== \"idle\" && lines.length > 0\n ? {\n turnMessageId: state.turnMessageId,\n phase,\n lines,\n stepCount: countFinishedSteps(elements),\n helperCount: phase === \"live\" ? countWorkingHelpers(elements) : 0,\n liveSince: phase === \"live\" ? state.liveSince : null,\n }\n : null;\n // Switching the history off takes the kept lines away at once; a turn on screen is never shown twice. The turn in\n // its success beat already stands in the thread, so its lines grow in there as they leave the face.\n const keptTurns = state.keptTurns\n .filter((keptTurn) => currentTurn === null || keptTurn.turnMessageId !== currentTurn.turnMessageId)\n .map(toKeptTurn);\n const finishedTurnOnScreen =\n currentTurn?.phase === \"done\" && currentTurn.turnMessageId !== null ? currentTurn : null;\n const historyTurns = !keepActivityHistoryAfterAnswer\n ? []\n : finishedTurnOnScreen\n ? [...keptTurns, finishedTurnOnScreen]\n : keptTurns;\n return { phase, currentTurn, historyTurns };\n }, [state, elements, keepActivityHistoryAfterAnswer]);\n};\n","import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { useAgentsConversationClient } from \"../../client/AgentsConversationClientContext\";\nimport type { ConversationBackgroundJob } from \"../../contract/conversation\";\nimport { ActivityElement, isDifferentTurn, mergeActivityElements } from \"./merge-activity-elements\";\n\n/** At most one activity request per this many milliseconds per conversation, whatever the tick rate. */\nexport const ACTIVITY_REQUEST_WINDOW_MS = 3000;\n/** While a turn runs, a request also fires on this cadence: the floor for a dead signal. */\nexport const RUNNING_FLOOR_MS = 4000;\n/**\n * Once the signal no longer says \"running\", this many failed requests in a row end the turn on screen: an endpoint that\n * keeps failing must not keep the face working and ask again every {@link RUNNING_FLOOR_MS} while the chat is open.\n */\nexport const MAX_FAILED_REQUESTS_AFTER_SIGNAL_ENDED = 3;\n\ntype Params = {\n conversationId: number;\n /** The signal's run status: \"running\" while a turn drives, \"idle\" / \"failed\" when it ended, null before the first read. */\n runStatus: string | null;\n /** Advances on every signal tick the host acts on (its message refetch); each advance asks for the activity too. */\n signalVersion: number;\n enabled?: boolean;\n /** At most one request per this many milliseconds. Default {@link ACTIVITY_REQUEST_WINDOW_MS}. */\n activityRequestWindowMs?: number;\n /** The request cadence while a turn runs. Default {@link RUNNING_FLOOR_MS}. */\n runningFloorMs?: number;\n};\n\ntype Result = {\n /** The rows of the stack in row order; empty before the first turn of this mount. */\n elements: ActivityElement[];\n /** Whether the narrated turn is still in flight. */\n running: boolean;\n /** The message that started the narrated turn, as the endpoint named it; null before its first answer. */\n turnMessageId: number | null;\n /** The background jobs of the conversation whose end is not reported yet, as the newest answer named them. */\n runningBackgroundJobs: ConversationBackgroundJob[];\n /** Asks for the activity at once (after the owner stopped a job), past the throttle. */\n refresh: () => void;\n};\n\n/**\n * What the agent is doing for the customer right now: pulls the conversation client's\n * `getConversationActivity` (`AgentsConversationClientProvider`) while the customer watches a running turn and merges the answer into the stack. Frontend-driven on purpose: nothing is\n * generated for a hidden tab or a closed chat. The turn is pinned when it starts (`turnMessageId` from the first\n * answer), so a message the customer sends mid-turn does not move the window. Debounced to one request per\n * {@link ACTIVITY_REQUEST_WINDOW_MS} (or the host's `activityRequestWindowMs`) with one trailing request after a burst; a terminal status fires one request for\n * the finished lines, and the requests go on until the endpoint answers that the turn ended — then the stack rests\n * until the next turn. A failed run ends the turn with that last request, whatever it answers, and so do\n * {@link MAX_FAILED_REQUESTS_AFTER_SIGNAL_ENDED} failed requests in a row once the signal stopped saying \"running\"\n * (those also drop the background jobs of the last answer, so the floor rests).\n * The answer also names the conversation's background jobs whose end is not reported yet: while it names any, the\n * requests go on at the floor's cadence and on every signal tick, whatever the turn does (a job runs on after the turn\n * that started it answered).\n * Opening a conversation (a new `conversationId`, or `enabled` turning on) reads once at once — on tab return when the\n * tab is hidden — so a job that runs while the conversation rests shows its line without waiting for a signal; with no\n * job and no turn in flight that read is the only one until the next trigger.\n */\nexport const useConversationActivity = ({\n conversationId,\n runStatus,\n signalVersion,\n enabled = true,\n activityRequestWindowMs = ACTIVITY_REQUEST_WINDOW_MS,\n runningFloorMs = RUNNING_FLOOR_MS,\n}: Params): Result => {\n const conversationClient = useAgentsConversationClient();\n const [elements, setElements] = useState<ActivityElement[]>([]);\n const [running, setRunning] = useState(false);\n const [turnMessageId, setTurnMessageId] = useState<number | null>(null);\n const [runningBackgroundJobs, setRunningBackgroundJobs] = useState<ConversationBackgroundJob[]>([]);\n // Whether the newest answer named a background job: the requests go on while one runs, without a turn.\n const hasRunningBackgroundJobsRef = useRef(false);\n const turnMessageIdRef = useRef<number | null>(null);\n const elementsRef = useRef<ActivityElement[]>([]);\n const inFlightRef = useRef(false);\n // The conversation the request in flight reads, and the one shown: an answer for another conversation is dropped.\n const inFlightConversationIdRef = useRef<number | null>(null);\n const conversationIdRef = useRef(conversationId);\n // The conversation the read on opening was made for; null while disabled, so turning on reads again.\n const openedConversationIdRef = useRef<number | null>(null);\n const trailingRef = useRef(false);\n const lastRequestAtRef = useRef(0);\n const trailingTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const runningRef = useRef(false);\n // What the endpoint said last about the pinned turn: still running or ended. The signal reports the parent\n // conversation IDLE while its helpers run, so a signal \"running\" after \"idle\" is not by itself a new turn.\n const answeredRunningRef = useRef(false);\n // The signal's run status as the answers read it: they land after the status may have changed.\n const runStatusRef = useRef<string | null>(runStatus);\n const consecutiveFailedRequestsRef = useRef(0);\n // The throttled entry, reachable from the request's own trailing call without a dependency cycle.\n const requestActivityRef = useRef<((immediate?: boolean) => void) | null>(null);\n\n useEffect(() => {\n elementsRef.current = elements;\n }, [elements]);\n\n const performRequest = useCallback(async () => {\n if (!enabled || !Number.isFinite(conversationId) || conversationId <= 0) return;\n if (inFlightRef.current) {\n trailingRef.current = true;\n return;\n }\n inFlightRef.current = true;\n inFlightConversationIdRef.current = conversationId;\n lastRequestAtRef.current = Date.now();\n try {\n const response = await conversationClient.getConversationActivity(conversationId, turnMessageIdRef.current);\n // The viewer switched conversations while this read was out: its answer belongs to the old one.\n if (conversationIdRef.current !== conversationId) return;\n const answeredTurn = response.turnMessageId;\n // A new turn started since the stack was pinned: the rows of the old turn fall away, the new turn starts clean.\n const newTurn = isDifferentTurn(turnMessageIdRef.current, answeredTurn);\n turnMessageIdRef.current = answeredTurn;\n setTurnMessageId(answeredTurn);\n const merged = mergeActivityElements(newTurn ? [] : elementsRef.current, response.elements);\n elementsRef.current = merged;\n setElements(merged);\n const answeredBackgroundJobs = response.runningBackgroundJobs ?? [];\n hasRunningBackgroundJobsRef.current = answeredBackgroundJobs.length > 0;\n setRunningBackgroundJobs(answeredBackgroundJobs);\n consecutiveFailedRequestsRef.current = 0;\n // A failed run has ended, whatever its steps say: a tool call the failure left open answers \"running\" forever.\n answeredRunningRef.current = response.turnRunning && runStatusRef.current !== \"failed\";\n setRunning(answeredRunningRef.current);\n } catch {\n if (conversationIdRef.current !== conversationId) return;\n // best-effort: the states of the next answer replace whatever is missing now — unless the turn is known to have\n // ended (the run failed) or the endpoint keeps failing after the signal stopped saying \"running\".\n consecutiveFailedRequestsRef.current += 1;\n const keepsFailingAfterSignalEnded =\n runStatusRef.current !== \"running\" && consecutiveFailedRequestsRef.current >= MAX_FAILED_REQUESTS_AFTER_SIGNAL_ENDED;\n if (runStatusRef.current === \"failed\" || keepsFailingAfterSignalEnded) {\n answeredRunningRef.current = false;\n setRunning(false);\n }\n if (keepsFailingAfterSignalEnded) {\n // the jobs of the last answer would keep the floor asking and their lines with clock and stop button standing:\n // they go too; the next signal tick or opening reads them again\n hasRunningBackgroundJobsRef.current = false;\n setRunningBackgroundJobs([]);\n }\n } finally {\n inFlightRef.current = false;\n inFlightConversationIdRef.current = null;\n if (trailingRef.current) {\n trailingRef.current = false;\n // held back behind a read of the previous conversation: the opened one reads at once, not after the window\n requestActivityRef.current?.(conversationIdRef.current !== conversationId);\n }\n }\n }, [conversationId, conversationClient, enabled]);\n\n // The one throttle every trigger goes through: at most one request per window, one trailing call for a burst.\n const requestActivity = useCallback(\n (immediate = false) => {\n if (typeof document !== \"undefined\" && document.hidden) return;\n if (immediate) {\n if (trailingTimerRef.current !== null) {\n clearTimeout(trailingTimerRef.current);\n trailingTimerRef.current = null;\n }\n void performRequest();\n return;\n }\n const sinceLast = Date.now() - lastRequestAtRef.current;\n if (sinceLast >= activityRequestWindowMs) {\n void performRequest();\n return;\n }\n if (trailingTimerRef.current === null) {\n trailingTimerRef.current = setTimeout(() => {\n trailingTimerRef.current = null;\n void performRequest();\n }, activityRequestWindowMs - sinceLast);\n }\n },\n [performRequest, activityRequestWindowMs],\n );\n useEffect(() => {\n requestActivityRef.current = requestActivity;\n }, [requestActivity]);\n\n // Turn start: drop whatever the previous (already rested) turn left on screen BEFORE asking again — otherwise the\n // first response for the new turn would merge its rows into the old ones still sitting in state (the bug: sending\n // a new message while the previous turn's stack is still shown left the old rows in place with the new ones\n // appended). Unpin, clear the stack, mark it running so the UI switches to the live ticker at once, then request.\n // Turn end: one last request for the finished lines (the response's own `turnRunning` flips `running` false once\n // that lands, not this effect — so the ticker keeps whatever it has until the terminal answer is in).\n useEffect(() => {\n runStatusRef.current = runStatus;\n const isRunning = runStatus === \"running\";\n const wasRunning = runningRef.current;\n runningRef.current = isRunning;\n if (isRunning && !wasRunning) {\n consecutiveFailedRequestsRef.current = 0;\n // A fresh turn only when the endpoint said the pinned one had ended; while helpers run the parent's signal\n // flips idle and back, and the ticker must keep its rows (a different answered turn resets it anyway).\n if (!answeredRunningRef.current) {\n turnMessageIdRef.current = null;\n setTurnMessageId(null);\n elementsRef.current = [];\n setElements([]);\n }\n setRunning(true);\n requestActivity(true);\n } else if (!isRunning && wasRunning) {\n requestActivity(true);\n }\n }, [runStatus, requestActivity]);\n\n // Every signal tick the host acts on asks for the activity too (throttled above).\n useEffect(() => {\n if (signalVersion > 0 && (runningRef.current || hasRunningBackgroundJobsRef.current)) {\n requestActivity();\n }\n }, [signalVersion, requestActivity]);\n\n // The floor while the turn is in flight (a dead signal, a long tool) and the catch-up on tab return. In flight until\n // the endpoint itself answers that the turn ended, not only while the signal says \"running\": the signal reports the\n // parent idle while its helpers work, a turn can end while the tab is hidden (the terminal request above is then\n // skipped), and that request can fail. Stopping at the signal would leave `running` true until the next turn. The\n // catch in performRequest bounds it: a failed run, or failed requests in a row, set `running` false.\n useEffect(() => {\n if (!enabled || (runStatus !== \"running\" && !running && runningBackgroundJobs.length === 0)) return;\n const interval = setInterval(() => requestActivity(), runningFloorMs);\n const onVisibilityChange = () => {\n if (!document.hidden) requestActivity(true);\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n return () => {\n clearInterval(interval);\n document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n };\n }, [enabled, runStatus, running, runningBackgroundJobs.length, requestActivity, runningFloorMs]);\n\n // A different conversation: nothing of the old one is shown.\n useEffect(() => {\n conversationIdRef.current = conversationId;\n turnMessageIdRef.current = null;\n setTurnMessageId(null);\n elementsRef.current = [];\n setElements([]);\n setRunning(false);\n hasRunningBackgroundJobsRef.current = false;\n setRunningBackgroundJobs([]);\n consecutiveFailedRequestsRef.current = 0;\n return () => {\n if (trailingTimerRef.current !== null) {\n clearTimeout(trailingTimerRef.current);\n trailingTimerRef.current = null;\n }\n };\n }, [conversationId]);\n\n // Opening a conversation reads once: the route names the running background jobs on every read, also while the\n // conversation rests, so a job that does not wake the agent shows its line at once instead of after the next signal.\n // A hidden tab reads when it shows again. A read already out for this conversation (a turn that runs on opening)\n // counts as this read.\n useEffect(() => {\n if (!enabled || !Number.isFinite(conversationId) || conversationId <= 0) {\n openedConversationIdRef.current = null;\n return;\n }\n if (openedConversationIdRef.current === conversationId) return;\n const readOnOpening = () => {\n openedConversationIdRef.current = conversationId;\n if (inFlightRef.current && inFlightConversationIdRef.current === conversationId) return;\n requestActivity(true);\n };\n if (typeof document === \"undefined\" || !document.hidden) {\n readOnOpening();\n return;\n }\n const onVisibilityChange = () => {\n if (!document.hidden && openedConversationIdRef.current !== conversationId) readOnOpening();\n };\n document.addEventListener(\"visibilitychange\", onVisibilityChange);\n return () => document.removeEventListener(\"visibilitychange\", onVisibilityChange);\n }, [conversationId, enabled, requestActivity]);\n\n const refresh = useCallback(() => requestActivity(true), [requestActivity]);\n\n return { elements, running, turnMessageId, runningBackgroundJobs, refresh };\n};\n","import { BACKLOG_LINE_PACE_MS, LINE_PACE_MS } from \"./activity-ticker\";\nimport { SUCCESS_BEAT_MS } from \"./use-activity-ticker\";\nimport { ACTIVITY_REQUEST_WINDOW_MS, RUNNING_FLOOR_MS } from \"./use-conversation-activity\";\n\n/**\n * The timing of the chat's activity lines and of its working indicator, for a host whose delivery differs from the\n * package's polling default. Every field is optional and defaults to the package's value; a value that is no finite\n * number at or above 0 counts as unset.\n *\n * A host with a realtime push that writes `activityUpdatedAt` when the narrator finishes lowers\n * `activityRequestWindowMs` (and the paces), so a narrated line shows as soon as the push arrives instead of after the\n * next 3 s window.\n */\nexport interface AgentChatActivityTiming {\n /** At most one activity read per this many milliseconds per conversation. Default 3000 (`ACTIVITY_REQUEST_WINDOW_MS`). */\n activityRequestWindowMs?: number;\n /** While a turn runs, an activity read also fires on this cadence (the floor for a dead signal). Default 4000 (`RUNNING_FLOOR_MS`). */\n runningFloorMs?: number;\n /** The least time a line stands beside the working face before the next one replaces it. Default 2200 (`LINE_PACE_MS`). */\n linePaceMs?: number;\n /** The shorter wait while more than two lines are queued. Default 1400 (`BACKLOG_LINE_PACE_MS`). */\n backlogLinePaceMs?: number;\n /** How long the face's success beat rests after the turn before it turns idle. Default 1400 (`SUCCESS_BEAT_MS`). */\n successBeatMs?: number;\n}\n\n/** Every timing value set: the resolved form the chat's hooks read. */\nexport type ResolvedAgentChatActivityTiming = Required<AgentChatActivityTiming>;\n\n/** The package's timing: what a chat uses when neither the chat nor the environment names a value. */\nexport const DEFAULT_AGENT_CHAT_ACTIVITY_TIMING: ResolvedAgentChatActivityTiming = {\n activityRequestWindowMs: ACTIVITY_REQUEST_WINDOW_MS,\n runningFloorMs: RUNNING_FLOOR_MS,\n linePaceMs: LINE_PACE_MS,\n backlogLinePaceMs: BACKLOG_LINE_PACE_MS,\n successBeatMs: SUCCESS_BEAT_MS,\n};\n\nconst isUsableMilliseconds = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\n/**\n * The timing of one chat: each field from the first source that sets a usable value — the chat's own\n * (`AgentChat activityTiming`), then the environment's (`AgentsEnvironment.chatActivityTiming`), then the package's.\n */\nexport const resolveAgentChatActivityTiming = (\n ...sources: (AgentChatActivityTiming | null | undefined)[]\n): ResolvedAgentChatActivityTiming => {\n const resolved = { ...DEFAULT_AGENT_CHAT_ACTIVITY_TIMING };\n (Object.keys(resolved) as (keyof ResolvedAgentChatActivityTiming)[]).forEach((key) => {\n const source = sources.find((candidate) => isUsableMilliseconds(candidate?.[key]));\n if (source) resolved[key] = source[key] as number;\n });\n return resolved;\n};\n","/**\n * A start an agent entry point outside the widget handed over: a visible USER message (`message`), or the invisible\n * START signal behind an EMPTY visible message (`signal`), which makes the agent speak first.\n */\nexport interface PendingStartRequest {\n kind: \"message\" | \"signal\";\n text: string;\n}\n\n/**\n * The one start the chat should send from the two hand-over fields (the opening request's `userMessage` and\n * `startSignalText`). The app's openers keep at most one of the two set — each clears the\n * other's leftover on the way in — but the message still wins here if both somehow are, since the customer's own words\n * are the stronger request.\n */\nexport const pickPendingStartRequest = (\n pendingStartUserMessage: string | null,\n pendingStartSignalText: string | null,\n): PendingStartRequest | null => {\n if (pendingStartUserMessage) {\n return { kind: \"message\", text: pendingStartUserMessage };\n }\n if (pendingStartSignalText) {\n return { kind: \"signal\", text: pendingStartSignalText };\n }\n return null;\n};\n\nexport interface ChatStateForPendingStartRequest {\n /** The start an agent entry point outside the widget handed over (`pickPendingStartRequest`). */\n pendingStartRequest: PendingStartRequest | null;\n /** The conversation the widget currently wants open (the chat's `conversationId` prop). */\n activeConversationId: number | null | undefined;\n /** The conversation the chat slice currently holds — set until a new-chat reset clears it. */\n loadedConversationId: number | null | undefined;\n /** A start-with-message POST is already in flight (the chat store's `startingNewConversation`). */\n startingNewConversation: boolean;\n /** The start this chat has already sent, so the same one is never posted twice. */\n alreadySentStartRequest: PendingStartRequest | null;\n}\n\n/**\n * Whether the chat should send `pendingStartRequest` as the start of a NEW conversation right now. Called on every\n * relevant state change — NOT once on mount: the widget is often already open (and mounted) when an entry point\n * outside it hands over a request, which is what BUF-4009 was.\n *\n * \"Not yet\" (false) and \"never\" (false) deliberately look the same to the caller: the request stays in the slice, and\n * this is asked again on the next change. A conversation still being open is the \"not yet\" case — Agent drops to a new\n * chat when a request arrives, because every incentive CTA promises a fresh chat for its job, and this then says yes\n * on the cold chat that follows.\n */\nexport const isChatReadyToSendPendingStartRequest = ({\n pendingStartRequest,\n activeConversationId,\n loadedConversationId,\n startingNewConversation,\n alreadySentStartRequest,\n}: ChatStateForPendingStartRequest): boolean => {\n if (!pendingStartRequest) {\n return false;\n }\n // A conversation is open (or still loaded while the new chat is being set up) — the request must never be appended\n // to it. A start already in flight would be dropped by the send handler's own in-flight guard, losing the request.\n if (activeConversationId || loadedConversationId || startingNewConversation) {\n return false;\n }\n return (\n alreadySentStartRequest?.kind !== pendingStartRequest.kind ||\n alreadySentStartRequest.text !== pendingStartRequest.text\n );\n};\n","import type {\n ConversationChangeSignal,\n ConversationRunStatus,\n ConversationSubscriptionEndReason,\n} from \"../../contract/conversation\";\n\n/** While a turn streams, per-message signals arrive in bursts — the re-read is coalesced to one per this window. */\nexport const LIVE_READ_THROTTLE_MS = 1200;\n/** Grace before the first convergence re-read (lets the terminal status' own immediate read land first). */\nexport const CONVERGENCE_BASE_DELAY_MS = 700;\n/** Backoff ceiling between convergence re-reads. */\nexport const CONVERGENCE_MAX_DELAY_MS = 2500;\n/** Stop re-reading for a missing terminal `lastMessageId` after this many attempts (the next action recovers). */\nexport const CONVERGENCE_MAX_ATTEMPTS = 6;\n\n/** What the live-update rules make the chat do. */\nexport interface ConversationLiveUpdateReads {\n /** Read the rows that changed (the chat's changed-tail read). */\n readChangedMessages: () => void;\n /** Read the conversation's metadata again (title, run state). */\n readConversationMetadata: () => void;\n /** Whether a message is loaded — the convergence check of a terminal signal's `lastMessageId`. */\n hasLoadedMessage: (messageId: number) => boolean;\n /** The run status the chat shows; null once the subscription ended. */\n showRunStatus: (runStatus: ConversationRunStatus | null) => void;\n}\n\nconst isTerminalRunStatus = (runStatus: ConversationRunStatus | null): boolean =>\n runStatus === \"idle\" || runStatus === \"failed\";\n\n/**\n * The package's rules over a conversation's live updates — one instance per subscription:\n * - the first pushed signal reads once (a turn may have moved between the chat's open and the subscription), and is\n * the baseline of the counter and of `summaryUpdatedAt`;\n * - a counter advance reads again, throttled to one read per `LIVE_READ_THROTTLE_MS` with one trailing read;\n * - a terminal status reads at once, re-reads the metadata (on the baseline and on every terminal signal that\n * advances the counter: the server closes a conversation after the turn and publishes one more idle signal), and\n * keeps reading with backoff until the signal's `lastMessageId` is loaded (a reply that beat its own commit);\n * - a changed `summaryUpdatedAt` after the baseline re-reads the metadata only;\n * - a status-check emission (`isStatusCheck`) sets the status, and reads again — at once on a terminal status — only\n * while the push path is not alive (the binding's `isPushPathAlive`; without it: no pushed signal arrived yet) and\n * its status differs from the previous check's;\n * - an ended subscription clears the status.\n * The transport's health (reconnect, a dead path, token refresh) is the binding's.\n */\nexport class ConversationChangeSignalRules {\n protected lastChangeCounter: number | null = null;\n protected hasSummaryBaseline = false;\n protected lastSummaryUpdatedAt: number | null = null;\n protected hasPushedSignalArrived = false;\n protected lastStatusCheckRunStatus: ConversationRunStatus | null = null;\n protected lastReadAt = 0;\n protected trailingReadTimer: ReturnType<typeof setTimeout> | null = null;\n protected convergenceTimer: ReturnType<typeof setTimeout> | null = null;\n protected convergenceAttempt = 0;\n protected convergenceMessageId: number | null = null;\n protected disposed = false;\n\n constructor(protected readonly reads: ConversationLiveUpdateReads) {}\n\n receiveSignal = (signal: ConversationChangeSignal): void => {\n if (this.disposed) return;\n if (signal.isStatusCheck) {\n this.receiveStatusCheck(signal.runStatus, signal.isPushPathAlive ?? this.hasPushedSignalArrived);\n return;\n }\n this.hasPushedSignalArrived = true;\n if (signal.runStatus !== null) {\n this.reads.showRunStatus(signal.runStatus);\n }\n if (!this.hasSummaryBaseline) {\n this.hasSummaryBaseline = true;\n this.lastSummaryUpdatedAt = signal.summaryUpdatedAt;\n } else if (signal.summaryUpdatedAt !== null && signal.summaryUpdatedAt !== this.lastSummaryUpdatedAt) {\n this.lastSummaryUpdatedAt = signal.summaryUpdatedAt;\n this.reads.readConversationMetadata();\n }\n const isTerminal = isTerminalRunStatus(signal.runStatus);\n if (this.lastChangeCounter === null) {\n this.lastChangeCounter = signal.changeCounter;\n this.requestRead(isTerminal);\n if (isTerminal) {\n this.convergeOnMessage(signal.lastMessageId);\n this.reads.readConversationMetadata();\n }\n return;\n }\n const hasCounterAdvanced = signal.changeCounter !== this.lastChangeCounter;\n if (!hasCounterAdvanced && !isTerminal) return;\n this.lastChangeCounter = signal.changeCounter;\n this.requestRead(isTerminal);\n if (isTerminal) {\n this.convergeOnMessage(signal.lastMessageId);\n if (hasCounterAdvanced) this.reads.readConversationMetadata();\n }\n };\n\n receiveEnd = (_reason: ConversationSubscriptionEndReason): void => {\n if (this.disposed) return;\n this.reads.showRunStatus(null);\n };\n\n /** Reads now, bypassing the throttle (the chat's safety poll). */\n readNow = (): void => {\n if (this.disposed) return;\n this.reads.readChangedMessages();\n };\n\n dispose = (): void => {\n this.disposed = true;\n this.clearTrailingRead();\n this.clearConvergence();\n };\n\n protected receiveStatusCheck(runStatus: ConversationRunStatus | null, isPushPathAlive: boolean): void {\n if (runStatus === null) return;\n this.reads.showRunStatus(runStatus);\n if (!isPushPathAlive && runStatus !== this.lastStatusCheckRunStatus) {\n this.requestRead(isTerminalRunStatus(runStatus));\n }\n this.lastStatusCheckRunStatus = runStatus;\n }\n\n /** One coordinated read path: `immediate` (a terminal status) cancels a pending trailing read and reads now. */\n protected requestRead(immediate: boolean): void {\n if (immediate) {\n this.clearTrailingRead();\n this.readThrottled();\n return;\n }\n const sinceLastRead = Date.now() - this.lastReadAt;\n if (sinceLastRead >= LIVE_READ_THROTTLE_MS) {\n this.readThrottled();\n return;\n }\n if (this.trailingReadTimer === null) {\n this.trailingReadTimer = setTimeout(this.readTrailing, LIVE_READ_THROTTLE_MS - sinceLastRead);\n }\n }\n\n protected readThrottled(): void {\n this.lastReadAt = Date.now();\n this.reads.readChangedMessages();\n }\n\n protected readTrailing = (): void => {\n this.trailingReadTimer = null;\n if (this.disposed) return;\n this.readThrottled();\n };\n\n protected clearTrailingRead(): void {\n if (this.trailingReadTimer !== null) {\n clearTimeout(this.trailingReadTimer);\n this.trailingReadTimer = null;\n }\n }\n\n protected convergeOnMessage(messageId: number | null): void {\n this.clearConvergence();\n if (messageId === null) return;\n this.convergenceMessageId = messageId;\n this.convergenceAttempt = 0;\n this.convergenceTimer = setTimeout(this.checkConvergence, CONVERGENCE_BASE_DELAY_MS);\n }\n\n protected checkConvergence = (): void => {\n this.convergenceTimer = null;\n const messageId = this.convergenceMessageId;\n if (this.disposed || messageId === null) return;\n if (this.reads.hasLoadedMessage(messageId)) return;\n if (this.convergenceAttempt >= CONVERGENCE_MAX_ATTEMPTS) return;\n this.convergenceAttempt += 1;\n this.reads.readChangedMessages();\n this.convergenceTimer = setTimeout(\n this.checkConvergence,\n Math.min(CONVERGENCE_BASE_DELAY_MS * this.convergenceAttempt, CONVERGENCE_MAX_DELAY_MS),\n );\n };\n\n protected clearConvergence(): void {\n if (this.convergenceTimer !== null) {\n clearTimeout(this.convergenceTimer);\n this.convergenceTimer = null;\n }\n }\n}\n","import { type Dispatch, type RefObject, type SetStateAction, useCallback, useEffect, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { ConversationRunStatus } from \"../../contract/conversation\";\nimport type { AgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { ConversationChangeSignalRules, type ConversationLiveUpdateReads } from \"./conversation-change-signal-rules\";\nimport type { ConversationMessagePages } from \"./use-conversation-message-pages\";\n\n/** The chat's reads behind the live-update rules: the changed tail and the metadata of the chat store's conversation. */\nclass ChatStoreLiveUpdateReads implements ConversationLiveUpdateReads {\n constructor(\n protected readonly chatStore: AgentsChatStore,\n /** The latest reads of the chat (a ref: their object changes with the older-page load state, the subscription does not). */\n protected readonly messagePagesRef: RefObject<ConversationMessagePages>,\n protected readonly conversationId: number,\n protected readonly setLiveReadCount: Dispatch<SetStateAction<number>>,\n readonly showRunStatus: Dispatch<SetStateAction<ConversationRunStatus | null>>,\n ) {}\n\n readChangedMessages = (): void => {\n this.setLiveReadCount((count) => count + 1);\n this.messagePagesRef.current.refetchChangedTail(this.conversationId);\n };\n\n readConversationMetadata = (): void => {\n void this.messagePagesRef.current.readConversationMetadata(this.conversationId);\n };\n\n hasLoadedMessage = (messageId: number): boolean =>\n (this.chatStore.getState().messages ?? []).some((message) => message.id === messageId);\n}\n\n/** The run status alone, for code outside the chat: no reads behind the rules. */\nclass RunStatusOnlyLiveUpdateReads implements ConversationLiveUpdateReads {\n constructor(readonly showRunStatus: Dispatch<SetStateAction<ConversationRunStatus | null>>) {}\n\n readChangedMessages = (): void => undefined;\n\n readConversationMetadata = (): void => undefined;\n\n hasLoadedMessage = (): boolean => true;\n}\n\nexport interface ConversationLiveUpdatesInputs {\n client: AgentsConversationClient;\n chatStore: AgentsChatStore;\n /** The reads the rules trigger (`useConversationMessagePages`). */\n messagePages: ConversationMessagePages;\n /** The conversation to follow; undefined for a cold chat (no subscription). */\n conversationId: number | undefined;\n}\n\nexport interface ConversationLiveUpdates {\n /** The run status the signal (or the binding's run-state check) reported last; null before the first and once ended. */\n runStatus: ConversationRunStatus | null;\n /** Counts the live reads the rules triggered — the activity read follows it (one activity read per signal tick). */\n liveReadCount: number;\n /** Reads the changed tail now, bypassing the throttle, and counts it (the chat's safety poll). */\n readChangedTailNow: () => void;\n}\n\n/**\n * The chat's live updates over `subscribeToConversationChanges`: one subscription per conversation,\n * the rules of `ConversationChangeSignalRules`, the reads written into the chat store.\n */\nexport const useConversationLiveUpdates = (inputs: ConversationLiveUpdatesInputs): ConversationLiveUpdates => {\n const { client, chatStore, messagePages, conversationId } = inputs;\n const [runStatus, setRunStatus] = useState<ConversationRunStatus | null>(null);\n const [liveReadCount, setLiveReadCount] = useState(0);\n const messagePagesRef = useRef(messagePages);\n messagePagesRef.current = messagePages;\n\n useEffect(() => {\n // A client without a subscription follows nothing here; `AgentChat` fills in the polling default before.\n if (!conversationId || !client.subscribeToConversationChanges) return;\n const rules = new ConversationChangeSignalRules(\n new ChatStoreLiveUpdateReads(chatStore, messagePagesRef, conversationId, setLiveReadCount, setRunStatus),\n );\n const unsubscribe = client.subscribeToConversationChanges(conversationId, rules.receiveSignal, rules.receiveEnd);\n return () => {\n rules.dispose();\n unsubscribe();\n };\n }, [client, chatStore, conversationId]);\n\n const readChangedTailNow = useCallback(() => {\n if (!conversationId) return;\n setLiveReadCount((count) => count + 1);\n messagePagesRef.current.refetchChangedTail(conversationId);\n }, [conversationId]);\n\n return { runStatus, liveReadCount, readChangedTailNow };\n};\n\n/**\n * The run status of a conversation for code outside the chat (the launcher button, the end of a voice call), over the\n * same port function and the same status rules as the chat — without reading any message.\n */\nexport const useAgentsConversationRunStatus = (\n client: AgentsConversationClient,\n conversationId: number | undefined,\n): ConversationRunStatus | null => {\n const [runStatus, setRunStatus] = useState<ConversationRunStatus | null>(null);\n useEffect(() => {\n // A client without a subscription reports nothing; wrap it in `withPollingChangeSubscription` first.\n if (!conversationId || !client.subscribeToConversationChanges) return;\n const rules = new ConversationChangeSignalRules(new RunStatusOnlyLiveUpdateReads(setRunStatus));\n const unsubscribe = client.subscribeToConversationChanges(conversationId, rules.receiveSignal, rules.receiveEnd);\n return () => {\n rules.dispose();\n unsubscribe();\n };\n }, [client, conversationId]);\n return runStatus;\n};\n","import { useCallback, useMemo, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { AgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { buildChangedMessagesRequest } from \"./changed-messages-request\";\n\n/** The page size of every message read of the chat: the newest page, the changed tail and an older page. */\nexport const CONVERSATION_MESSAGE_PAGE_SIZE = 50;\n\nexport interface ConversationMessagePages {\n /** Reads the conversation without messages into the store; resolves false when the read was refused. */\n readConversationMetadata: (conversationId: number) => Promise<boolean>;\n /** The newest page an open reads; a changed-tail read asked meanwhile waits for it. */\n fetchOpeningPage: (conversationId: number) => void;\n /** The rows written since the newest loaded one and the rows that can still change (a live update). */\n refetchChangedTail: (conversationId: number) => void;\n /** The page before the oldest loaded message (scroll-up); guarded against a second load and an exhausted history. */\n loadOlder: (conversationId: number | undefined) => Promise<void>;\n /** An older page is on its way. */\n loadingOlder: boolean;\n}\n\n/**\n * The chat's message reads over the conversation client port, written into the chat store: the newest page of an\n * open, the changed tail every live update asks for, an older page on scroll-up, and the metadata read. A changed-tail\n * read asked while the open's newest page is still on its way would read that same page again (nothing is loaded yet,\n * so it has no filter): it is held instead and sent once the page is in, reading past what the page brought, so a\n * reply stored in between still arrives. A failed page read changes nothing (the next live update reads again).\n */\nexport const useConversationMessagePages = (\n chatStore: AgentsChatStore,\n client: AgentsConversationClient,\n pageSize: number = CONVERSATION_MESSAGE_PAGE_SIZE,\n): ConversationMessagePages => {\n const openingPageRef = useRef<{ conversationId: number; refetchOwed: boolean } | null>(null);\n const [loadingOlder, setLoadingOlder] = useState(false);\n const loadingOlderRef = useRef(false);\n\n const readConversationMetadata = useCallback(\n async (conversationId: number): Promise<boolean> => {\n chatStore.dispatch({ type: \"conversationMetadataRequested\", conversationId });\n try {\n const conversation = await client.getConversationMetadata(conversationId);\n chatStore.dispatch({ type: \"conversationMetadataReceived\", conversationId, conversation });\n return true;\n } catch {\n chatStore.dispatch({ type: \"conversationMetadataFailed\", conversationId });\n return false;\n }\n },\n [chatStore, client],\n );\n\n // Reads the store, not the rendered messages: the held read runs before the opened page has re-rendered.\n const fetchChangedTail = useCallback(\n async (conversationId: number): Promise<void> => {\n const changedMessagesRequest = buildChangedMessagesRequest(chatStore.getState().messages, pageSize);\n chatStore.dispatch({ type: \"messagesPageRequested\", conversationId });\n try {\n if (changedMessagesRequest === null) {\n // Nothing loaded yet: the newest page, as on open.\n const page = await client.getNewestMessagesPage(conversationId, pageSize);\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: page.messages,\n hasMoreOlder: page.hasMoreOlder,\n });\n return;\n }\n const changedMessages = await client.getChangedMessages(conversationId, changedMessagesRequest);\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: changedMessages.messages,\n hasMoreOlder: null,\n });\n } catch {\n // A failed live read changes nothing; the next signal reads again.\n }\n },\n [chatStore, client, pageSize],\n );\n\n const fetchOpeningPage = useCallback(\n (conversationId: number) => {\n const openingPage = { conversationId, refetchOwed: false };\n openingPageRef.current = openingPage;\n chatStore.dispatch({ type: \"messagesPageRequested\", conversationId });\n const settleOpeningPage = () => {\n if (openingPageRef.current !== openingPage) return;\n openingPageRef.current = null;\n // A reset since (empty chat, closed window) has nothing left to read into.\n const isStillShown = chatStore.getState().requestedConversationId === conversationId;\n if (openingPage.refetchOwed && isStillShown) {\n void fetchChangedTail(conversationId);\n }\n };\n client\n .getNewestMessagesPage(conversationId, pageSize)\n .then((page) => {\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: page.messages,\n hasMoreOlder: page.hasMoreOlder,\n });\n })\n .catch(() => undefined)\n .then(settleOpeningPage);\n },\n [chatStore, client, pageSize, fetchChangedTail],\n );\n\n const refetchChangedTail = useCallback(\n (conversationId: number) => {\n const openingPage = openingPageRef.current;\n if (openingPage?.conversationId === conversationId) {\n openingPage.refetchOwed = true;\n return;\n }\n void fetchChangedTail(conversationId);\n },\n [fetchChangedTail],\n );\n\n const loadOlder = useCallback(\n async (conversationId: number | undefined): Promise<void> => {\n const { hasMoreOlder, messages } = chatStore.getState();\n if (loadingOlderRef.current || !hasMoreOlder || !conversationId) return;\n const lowestLoadedIndex = (messages ?? [])[0]?.indexInConversation;\n if (lowestLoadedIndex == null) return;\n loadingOlderRef.current = true;\n setLoadingOlder(true);\n chatStore.dispatch({ type: \"messagesPageRequested\", conversationId });\n try {\n const page = await client.getOlderMessagesPage(conversationId, lowestLoadedIndex, pageSize);\n chatStore.dispatch({\n type: \"messagesPageReceived\",\n conversationId,\n messages: page.messages,\n hasMoreOlder: page.hasMoreOlder,\n });\n } catch {\n // The scroll-up load stays armed; the next sentinel hit tries again.\n } finally {\n loadingOlderRef.current = false;\n setLoadingOlder(false);\n }\n },\n [chatStore, client, pageSize],\n );\n\n return useMemo(\n () => ({ readConversationMetadata, fetchOpeningPage, refetchChangedTail, loadOlder, loadingOlder }),\n [readConversationMetadata, fetchOpeningPage, refetchChangedTail, loadOlder, loadingOlder],\n );\n};\n","import { createContext, useContext } from \"react\";\nimport type { ConversationBackgroundJob, ConversationBackgroundJobStop } from \"../../contract/conversation\";\n\n/**\n * What the chat knows about the conversation's background jobs, for the trace of a turn: the jobs whose end is not\n * reported yet (from the activity read) and where their lines stand. The chat controller provides it; the turn trace\n * shows the lines under the turn the context names. Without a provider no line is shown.\n */\nexport interface RunningBackgroundJobsContextValue {\n conversationId: number;\n /** The message that started the newest turn of the thread: the lines stand under the trace of that turn. */\n anchorTurnMessageId: number | string | null;\n /** The jobs whose end is not reported yet, oldest first. */\n backgroundJobs: ConversationBackgroundJob[];\n /** Stops one job (`stopBackgroundJob` of the client); without it the lines offer no Stop. */\n stopBackgroundJob?: (backgroundJobId: number) => Promise<ConversationBackgroundJobStop>;\n /** Reads the activity again at once (after a stop). */\n refresh: () => void;\n}\n\nexport const RunningBackgroundJobsContext = createContext<RunningBackgroundJobsContextValue | null>(null);\n\n/** The background jobs of the chat around, or null outside a chat that provides them. */\nexport const useRunningBackgroundJobs = (): RunningBackgroundJobsContextValue | null => useContext(RunningBackgroundJobsContext);\n","import { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface QueuedMessageChipProps {\n /** The queued message, quoted in the chip (above a composer). Without it the chip only says that the message waits. */\n text?: string | null;\n /** The chip stands in a narrow thread (a floating panel). */\n isCompact?: boolean;\n /**\n * The turn is over and took the message up: a quiet label above the message's bubble (\"Sent during the run · taken\n * up in this turn\") instead of the wait; `text` is only its tooltip.\n */\n wasTakenUp?: boolean;\n className?: string;\n}\n\n/**\n * The mark of an owner message sent while a turn runs: the agent reads it at its next step. Under the message in the\n * thread it is one quiet line; with `text` it quotes the message (above a composer).\n */\nexport const QueuedMessageChip = (props: QueuedMessageChipProps) => {\n const { text, isCompact = false, wasTakenUp = false, className } = props;\n if (wasTakenUp) {\n return (\n <div className={classNames(styles.queued, styles.queuedTakenUp, className)} data-testid=\"trace-queued-message-taken-up\" data-compact={isCompact || undefined} title={text ?? undefined}>\n <Icon name=\"stepDone\" pixelSize={12} />\n <span className={styles.queuedText}>\n {translateText(\"Sent during the run\")}\n {isCompact ? null : <> · {translateText(\"taken up in this turn\")}</>}\n </span>\n </div>\n );\n }\n return (\n <div\n className={classNames(styles.queued, !text && styles.queuedInThread, className)}\n role=\"status\"\n data-testid=\"trace-queued-message\"\n data-compact={isCompact || undefined}\n >\n <Icon name=\"stepWaiting\" pixelSize={13} />\n <span className={styles.queuedText}>\n {text ? (\n <>\n {translateText(\"Queued:\")} <span className={styles.queuedQuote}>{text}</span>\n {isCompact ? null : <> · {translateText(\"read at the next step\")}</>}\n </>\n ) : (\n translateText(\"Queued · read at the next step\")\n )}\n </span>\n </div>\n );\n};\n","import { RefObject, useCallback, useEffect, useRef } from \"react\";\nimport type { ChatMessage } from \"../chat-message\";\nimport type { ChatScrollTarget } from \"./chat-scroll-target\";\n\n/** What the scroll follow reads of the activity ticker: its phase and the lines of the turn on screen. */\nexport interface ConversationScrollActivityTicker {\n phase: string;\n currentTurn: { lines: { toolCallMessageId: number; state: string | null }[] } | null;\n}\n\nexport interface ConversationScrollJumpInputs {\n /** The top-bar search's request to scroll a message into view and flash it; re-applied whenever its nonce changes. */\n scrollTarget: ChatScrollTarget | undefined;\n /** The conversation the host asked for (the chat's `conversationId` prop) — the one a request is armed for. */\n conversationId: number | undefined;\n /** The conversation the chat store holds right now; differs from `conversationId` for a beat after a switch. */\n conversation: { id?: number | null } | null;\n /** The loaded messages: every change retries a pending request. */\n messages: ChatMessage[] | null;\n /** The loaded messages as of the last render, read where the retry runs. */\n messagesRef: RefObject<ChatMessage[] | null>;\n /** Whether an older page exists, as of the last render. */\n hasMoreOlderRef: RefObject<boolean>;\n /** Pages the next older page in (self-guarded against concurrent and exhausted loads). */\n loadOlder: () => Promise<void>;\n /** The chat's scroll container (the host may own it, e.g. for a scroll-linked background). */\n chatScrollRef: RefObject<HTMLDivElement | null>;\n /** What the activity ticker shows; a new line scrolls it into view while the chat follows the bottom. */\n activityTicker: ConversationScrollActivityTicker;\n}\n\nexport interface ConversationScrollJump {\n /** Bottom-follow flag shared with ConversationViewBody; false while a jump is armed and after it. */\n followBottomRef: RefObject<boolean>;\n /** \"A programmatic jump is in flight\" gate shared with ConversationViewBody. */\n scrollJumpActiveRef: RefObject<boolean>;\n}\n\n/**\n * The chat's programmatic scrolling: the jump to a requested message (paging older pages in until it is rendered, then\n * the flash once the smooth scroll settled) and keeping the activity ticker in view as it grows. Owns the two refs it\n * shares with ConversationViewBody, which suspend the bottom-follow while a jump is armed.\n */\nexport const useConversationScrollJump = (inputs: ConversationScrollJumpInputs): ConversationScrollJump => {\n const {\n scrollTarget,\n conversationId,\n conversation,\n messages,\n messagesRef,\n hasMoreOlderRef,\n loadOlder,\n chatScrollRef,\n activityTicker,\n } = inputs;\n\n // Scroll-to-message (top-bar search → Agent → here). The requested hit is held in a ref until its message is\n // actually in the DOM: if it sits on an older page that hasn't loaded yet, page older in and retry on each\n // `messages` change. `data-message-id` is stamped on every rendered message by ConversationMessageList; the flash is a\n // transient `data-flash` attribute styled in ConversationMessageList's stylesheet.\n // `armedForConversationId` stamps which conversation the request targeted, so a request that outlives its\n // conversation (e.g. the selected search hit's conversation 404s) can't page through an unrelated one later.\n const pendingScrollRef = useRef<(ChatScrollTarget & { armedForConversationId?: number }) | null>(null);\n // Bottom-follow flag shared with ConversationViewBody. A search-result jump scrolls to a message ABOVE the bottom, then the\n // messages settle their heights (images/markdown) which fires ConversationViewBody's resize bottom-follow. While a jump is\n // armed we hold this false so follow stays suspended for the whole jump (and afterwards — the user is now reading up\n // there, exactly as a manual scroll-up).\n const followBottomRef = useRef(true);\n // \"A programmatic jump is in flight\" gate, shared with ConversationViewBody. Distinct from followBottomRef because the jump\n // must ALSO stop ConversationViewBody's near-bottom onScroll handler from flipping followBottom back to true: right after the\n // click the container is still near the bottom (the smooth scrollIntoView hasn't physically moved yet), so onScroll\n // would re-enable follow and the resize-follow would then yank the view back down. While this is true ConversationViewBody\n // neither re-enables follow on scroll nor auto-scrolls to the bottom on resize. Cleared once the jump settles/disarms.\n const scrollJumpActiveRef = useRef(false);\n\n // Keep the activity ticker in view as it grows — a new line beside the face or a new row above it scrolls it\n // into view with the exact guarded pattern the search-result jump above uses (chatScrollRef query +\n // scrollIntoView), not a second scroller. Keyed on what the ticker SHOWS, not on the endpoint's elements: the ticker\n // releases lines one at a time after they arrive. Skipped while the user has scrolled away (followBottomRef false)\n // or a host jump is already in flight (scrollJumpActiveRef) — the scroll-to-latest button already covers that case,\n // exactly as it does for a growing final answer under the pinned-question addon.\n // `block: \"nearest\"`, never \"end\": during a pinned turn (enablePinQuestionAndRevealAnswer) the room reserved below\n // the question makes the pinned position the scroll bottom, so ConversationViewBody's near-bottom onScroll turns\n // followBottomRef back on. \"end\" then aligned the ticker with the viewport bottom — scrolling UP by the reserved room\n // and dropping the question off the top. \"nearest\" only scrolls once the ticker actually runs below the fold.\n const activitySignatureRef = useRef(\"\");\n useEffect(() => {\n const { phase, currentTurn } = activityTicker;\n const newestLine = currentTurn?.lines[currentTurn.lines.length - 1];\n const signature = `${phase}|${currentTurn?.lines.length}|${newestLine?.toolCallMessageId}:${newestLine?.state}`;\n if (signature === activitySignatureRef.current) return;\n activitySignatureRef.current = signature;\n if (phase !== \"live\" || !followBottomRef.current || scrollJumpActiveRef.current) return;\n const tickerElement = chatScrollRef.current?.querySelector<HTMLElement>('[data-testid=\"agent-activity-ticker\"]');\n tickerElement?.scrollIntoView({ behavior: \"smooth\", block: \"nearest\", inline: \"nearest\" });\n }, [activityTicker, chatScrollRef, followBottomRef, scrollJumpActiveRef]);\n\n // Tracks the in-flight \"remove the flash highlight\" timer so it can be cancelled if a new scroll lands first or the\n // widget unmounts mid-flash (otherwise the callback fires on a detached node).\n const flashTimerRef = useRef<number | null>(null);\n // Tracks the requestAnimationFrame loop that waits for the smooth scroll to settle before the flash starts, so a new\n // scroll request or an unmount can cancel a still-pending wait.\n const scrollSettleRafRef = useRef<number | null>(null);\n const tryScrollToPendingMessage = useCallback(() => {\n const target = pendingScrollRef.current;\n if (!target?.messageId) return;\n // The conversation the request was armed for is gone (load failed / user navigated elsewhere) — disarm rather\n // than hunting a foreign message id through whatever conversation is shown now.\n if (target.armedForConversationId !== conversationId) {\n pendingScrollRef.current = null;\n scrollJumpActiveRef.current = false;\n return;\n }\n // A jump is armed for the current conversation → suspend bottom-follow AND gate ConversationViewBody's follow-re-enable /\n // resize-follow for the whole jump. Re-asserted on every retry (each older-page merge), so even a conversation\n // switch that briefly re-enabled follow can't yank us down.\n followBottomRef.current = false;\n scrollJumpActiveRef.current = true;\n const messageElement = chatScrollRef.current?.querySelector<HTMLElement>(`[data-message-id=\"${target.messageId}\"]`);\n if (messageElement) {\n pendingScrollRef.current = null;\n // Cancel any flash still in flight from a previous jump (its removal timer + settle watcher) and clear the\n // attribute so the animation can restart cleanly on this message.\n if (flashTimerRef.current !== null) window.clearTimeout(flashTimerRef.current);\n if (scrollSettleRafRef.current !== null) window.cancelAnimationFrame(scrollSettleRafRef.current);\n messageElement.removeAttribute(\"data-flash\");\n\n messageElement.scrollIntoView({ behavior: \"smooth\", block: \"center\" });\n\n // Start the flash only AFTER the smooth scroll settles, so the highlight plays on the at-rest message rather\n // than during the travel. Watch the element's viewport position each frame: once it holds still for 3\n // consecutive frames (covers both \"scrolled then stopped\" and \"already in view\"), or a 1.2s safety cap elapses,\n // the scroll has ended → toggle `data-flash` and arm its ~2s removal.\n let lastTop = messageElement.getBoundingClientRect().top;\n let stillFrames = 0;\n const startedAt = performance.now();\n const waitForScrollEnd = () => {\n if (!messageElement.isConnected) {\n scrollSettleRafRef.current = null;\n scrollJumpActiveRef.current = false;\n return;\n }\n const top = messageElement.getBoundingClientRect().top;\n stillFrames = Math.abs(top - lastTop) < 0.5 ? stillFrames + 1 : 0;\n lastTop = top;\n if (stillFrames >= 3 || performance.now() - startedAt > 1200) {\n scrollSettleRafRef.current = null;\n // The jump has come to rest → lift the gate. followBottomRef stays false, so a later content-resize won't\n // yank to the bottom; the user is parked at the target, exactly as after a manual scroll-up.\n scrollJumpActiveRef.current = false;\n messageElement.setAttribute(\"data-flash\", \"true\");\n flashTimerRef.current = window.setTimeout(() => {\n flashTimerRef.current = null;\n if (messageElement.isConnected) messageElement.removeAttribute(\"data-flash\");\n }, 2000);\n return;\n }\n scrollSettleRafRef.current = window.requestAnimationFrame(waitForScrollEnd);\n };\n scrollSettleRafRef.current = window.requestAnimationFrame(waitForScrollEnd);\n return;\n }\n // Conversation just switched (e.g. a cross-conversation search hit selected in the current tab): the slice still\n // holds the PREVIOUS conversation's messages/hasMoreOlder for a beat before the new fetch resolves. Evaluating\n // against that stale data below would misjudge \"exhausted\" and disarm the request too early — wait instead for the\n // messages-change effect to retry once the new conversation's own data actually lands.\n if (String(conversation?.id) !== String(conversationId) || messagesRef.current === null) return;\n // Not rendered yet — if the target is older than the oldest loaded message, page older in; the messages-change\n // effect below retries once that page merges. loadOlder self-guards against concurrent / exhausted loads.\n const lowestLoadedIndex = messagesRef.current[0]?.indexInConversation;\n const targetIsOlderThanLoaded =\n target.indexInConversation == null || lowestLoadedIndex == null || target.indexInConversation < lowestLoadedIndex;\n if (hasMoreOlderRef.current && targetIsOlderThanLoaded) {\n void loadOlder();\n return;\n }\n // Exhausted every older page and still no match (e.g. a deleted/stale message id) — disarm so we don't keep\n // re-querying on every future message change and can't later jump to an unrelated message that reuses the id.\n pendingScrollRef.current = null;\n scrollJumpActiveRef.current = false;\n }, [chatScrollRef, loadOlder, conversation, conversationId]);\n\n // A new scroll request (nonce changed) → arm it and attempt immediately.\n useEffect(() => {\n if (!scrollTarget?.messageId) return;\n // conversationId is read from this render's closure: Agent sets the target conversation and the scroll\n // request in the same state update, so at arm time the prop already names the conversation the hit belongs to.\n pendingScrollRef.current = { ...scrollTarget, armedForConversationId: conversationId };\n tryScrollToPendingMessage();\n // This effect closes over the nonce-triggering render's current conversation and pending message. The nonce bump\n // is deliberately the sole re-run trigger; it reads those current values when it fires.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [scrollTarget?.nonce]);\n\n // Cancel a pending flash-removal timer and scroll-settle watcher on unmount so neither fires after the widget closes.\n useEffect(\n () => () => {\n if (flashTimerRef.current !== null) window.clearTimeout(flashTimerRef.current);\n if (scrollSettleRafRef.current !== null) window.cancelAnimationFrame(scrollSettleRafRef.current);\n },\n [],\n );\n\n // Retry the pending scroll after each message-list change (an older page merged in, or the live reply landed).\n useEffect(() => {\n if (pendingScrollRef.current) tryScrollToPendingMessage();\n }, [messages, tryScrollToPendingMessage]);\n\n return { followBottomRef, scrollJumpActiveRef };\n};\n","import { findBalancedJsonObjectEnd } from \"./balanced-json-object\";\nimport { parseWidgetJsonObject } from \"./widget-fence-json\";\nimport { BARE_WIDGET_LINE_GLOBAL, WIDGET_FENCE_LANG } from \"./widget-fence-syntax\";\nimport { closestWidgetNames, resolveWidgetName } from \"./widget-name-resolver\";\n\n/**\n * The signal provenance for the widget-render-failure corrective signal — distinct from a widget CLICK. Mirrors the\n * backend {@link AIConversationMessage::SIGNAL_SOURCE_FRONTEND_WIDGET_INVALID}; the admin inspector shows it as the\n * signal source and the agent loop treats it as model-visible feedback.\n */\nexport const WIDGET_INVALID_SIGNAL_SOURCE = \"FRONTEND_WIDGET_INVALID\";\n\nexport interface UnrenderedWidget {\n /** The `type` the model wrote. */\n type: string;\n /**\n * What went wrong:\n * - `unknownType`: a widget block (fenced or bare `widget { … }` line) whose type is not a registered widget →\n * dropped, the customer sees NOTHING.\n * - `missingFence`: widget JSON emitted as PLAIN TEXT (no ```widget fence, no `widget` prefix) → the customer sees\n * raw JSON prose.\n */\n kind: \"unknownType\" | \"missingFence\";\n /** The closest valid widget names (deterministic similarity) for a \"did you mean\" — may be empty. */\n suggestions: string[];\n}\n\n// A ```widget fenced block: ```widget <optional trailing> \\n <json> \\n ``` . Non-greedy body; the `m`-less dotall\n// via [\\s\\S] so a multi-line JSON body is captured. Built from the shared lang constant so \"``` widget\" (a space\n// before the lang — remark accepts it) is recognized the same way as the render plugin and the repairer.\nconst WIDGET_FENCE = new RegExp(\"```[ \\\\t]*\" + WIDGET_FENCE_LANG + \"[^\\\\n]*\\\\n([\\\\s\\\\S]*?)```\", \"g\");\n\n// ANY fenced block — stripped before the naked-JSON scan so fenced content (handled widgets, legit code samples)\n// is never re-reported as fence-less.\nconst ANY_FENCE = /```[\\s\\S]*?```/g;\n\n/**\n * Parse a candidate JSON snippet into its `type` string, or null when it isn't an object with a string `type` — read\n * like the render plugin reads a block (`parseWidgetJsonObject`: a surplus trailing `}` / `]` is tolerated).\n */\nconst parseWidgetType = (jsonCandidate: string): string | null => {\n const type = parseWidgetJsonObject(jsonCandidate)?.type;\n return typeof type === \"string\" && type !== \"\" ? type : null;\n};\n\n/**\n * Extract balanced `{…}` JSON candidates that start at a line beginning (after whitespace) in PLAIN text — the shape\n * a model emits when it writes a widget payload without the fence (observed live: the final answer carried\n * `{ \"type\": \"ExampleWidget\", … }` as its own paragraph). A simple brace-balance walk (strings respected) keeps this\n * dependency-free; nested objects are fine. Bare `widget { … }` lines are NOT captured here (they start with the\n * `widget` prefix, not `{`) — remarkWidgetFencePlugin renders those, and the bare-line scan below covers their\n * unknown types.\n */\nconst extractNakedJsonCandidates = (plainText: string): string[] => {\n const candidates: string[] = [];\n const lines = plainText.split(\"\\n\");\n let offset = 0;\n for (const line of lines) {\n const lineStart = offset;\n offset += line.length + 1;\n if (!line.trimStart().startsWith(\"{\")) continue;\n const openIndex = lineStart + line.indexOf(\"{\");\n const jsonObjectEnd = findBalancedJsonObjectEnd(plainText, openIndex);\n if (jsonObjectEnd !== null) {\n candidates.push(plainText.slice(openIndex, jsonObjectEnd + 1));\n }\n }\n return candidates;\n};\n\n/**\n * Find widget-emission failures in an assistant message — the cases where the customer does NOT get the intended\n * widget. Uses the SAME resolveWidgetName as the render plugin, so \"valid\" means exactly \"would have rendered\".\n * Three scan surfaces, two failure classes:\n *\n * 1. `unknownType` — a ```widget fence OR a bare `widget { … }` line (both forms remarkWidgetFencePlugin renders)\n * whose `type` is not a registered widget: the plugin silently DROPS it, the customer sees nothing and the model\n * gets no feedback (a model wrote `type: \"example\"` instead of `ExampleWidget`). A malformed-JSON\n * block is skipped (the plugin drops it too).\n * 2. `missingFence` — widget JSON emitted as PLAIN prose (no fence, no `widget` prefix): nothing intercepts it, so\n * the customer sees raw JSON text (found live: `{ \"type\": \"ExampleWidget\", … }` as a paragraph of the final answer).\n * Reported when the naked JSON's `type` resolves to a VALID widget (the model clearly meant a widget) or is CLOSE\n * to one (similarity shortlist non-empty) — arbitrary JSON without a widget-like `type` is never flagged (no false\n * positives on legitimate JSON content).\n */\nexport const detectUnrenderedWidgets = (messageText: string): UnrenderedWidget[] => {\n const unrendered: UnrenderedWidget[] = [];\n const seenTypes = new Set<string>();\n const report = (type: string, kind: UnrenderedWidget[\"kind\"], suggestions: string[]) => {\n if (seenTypes.has(type)) return;\n seenTypes.add(type);\n unrendered.push({ type, kind, suggestions });\n };\n\n // 1) Rendered-form blocks (```widget fence + bare `widget { … }` line) with an unknown type.\n if (messageText.includes(\"widget\")) {\n for (const renderedFormRegex of [WIDGET_FENCE, BARE_WIDGET_LINE_GLOBAL]) {\n renderedFormRegex.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = renderedFormRegex.exec(messageText)) !== null) {\n const type = parseWidgetType(match[1]);\n if (type === null) continue;\n if (resolveWidgetName(type)) continue; // resolves → it rendered; nothing to report\n report(type, \"unknownType\", closestWidgetNames(type));\n }\n }\n }\n\n // 2) Naked widget JSON outside any fence.\n const plainText = messageText.replace(ANY_FENCE, \"\");\n if (plainText.includes('\"type\"')) {\n for (const jsonCandidate of extractNakedJsonCandidates(plainText)) {\n const type = parseWidgetType(jsonCandidate);\n if (type === null) continue;\n if (resolveWidgetName(type)) {\n report(type, \"missingFence\", []);\n continue;\n }\n const suggestions = closestWidgetNames(type);\n if (suggestions.length > 0) {\n report(type, \"unknownType\", suggestions);\n }\n // No resolution AND nothing close → arbitrary JSON, not a widget attempt — never flagged.\n }\n }\n\n return unrendered;\n};\n\n/**\n * The user-INVISIBLE corrective SIGNAL text for one or more widget-emission failures — tells the model exactly what\n * the customer experienced (nothing rendered / raw JSON prose) and how to fix it. Kept terse; the model already holds\n * the full widget catalog in its instructions.\n */\nexport const buildUnrenderedWidgetSignal = (widgets: UnrenderedWidget[]): string => {\n const parts = widgets.map((widget) => {\n if (widget.kind === \"missingFence\") {\n return `You emitted the \"${widget.type}\" widget as PLAIN JSON text — without the \\`\\`\\`widget code fence it does not render and the customer sees raw JSON prose.`;\n }\n const suggestion =\n widget.suggestions.length > 0 ? ` Closest valid widget names: ${widget.suggestions.join(\", \")}.` : \"\";\n return `\"${widget.type}\" is not a valid widget type, so it did not render and the customer sees nothing.${suggestion}`;\n });\n return (\n `A widget you emitted did not reach the customer. ${parts.join(\" \")} ` +\n \"Re-emit it as a ```widget code block (fence on its own lines) using the EXACT valid widget name that matches your intent.\"\n );\n};\n","import { Dispatch, SetStateAction, useCallback, useEffect, useMemo, useRef } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport { isAgentsClientError } from \"../../contract/conversation\";\nimport type { ChatMessage } from \"../chat-message\";\nimport type { SendMessageHandler } from \"../conversation-send-message\";\nimport { normalizeServerMessageToMarkdown } from \"../normalize-server-message-to-markdown\";\nimport type { InjectSignalOptions } from \"../../renderer/ConversationWidgetCallbacksContext\";\nimport {\n buildUnrenderedWidgetSignal,\n detectUnrenderedWidgets,\n WIDGET_INVALID_SIGNAL_SOURCE,\n} from \"../../renderer/detect-unrendered-widgets\";\nimport {\n buildWidgetRenderReportSignal,\n createWidgetRenderReportCollector,\n WIDGET_RENDER_REPORT_SIGNAL_SOURCE,\n type WidgetRenderBlockReport,\n} from \"../../renderer/render-report/widget-render-report-collector\";\n\n/** Max invalid-widget corrective signals per conversation — a too-weak model that keeps emitting bad widgets stops here. */\nconst WIDGET_CORRECTION_CAP = 2;\n\nexport interface ConversationSignalsInputs {\n /** The conversation client the signals go through (`injectSignal`). */\n client: AgentsConversationClient;\n /** The conversation the host asked for (the chat's `conversationId` prop); a signal targets it while none is loaded. */\n conversationId: number | undefined;\n /** The conversation the chat store holds right now. */\n conversation: { id?: number | null } | null;\n /** The loaded messages; the newest settled assistant message is checked for a dropped widget block. */\n messages: ChatMessage[] | null;\n /** The signal's run status (\"running\" | \"idle\" | \"failed\" | null). */\n runStatus: string | null;\n /** A start is in flight; a signal is not sent into a conversation that does not exist yet then. */\n startingNewConversation: boolean;\n /** The run is over; the backend refuses further input. */\n isConversationRunEnded: boolean;\n /** The chat's send — a signal without a conversation starts one through it. */\n handleSendMessage: SendMessageHandler;\n /** Shows the closed-conversation refusal on the error card. */\n rejectAsConversationClosed: () => void;\n /** Re-reads the conversation's metadata (the closed run state locks the widget controls). */\n refetchConversationSummary: () => void;\n /** The chat's jump-to-bottom request counter; a customer's click follows the turn it starts. */\n setScrollToBottomNonce: Dispatch<SetStateAction<number>>;\n}\n\nexport interface ConversationSignals {\n /** Injects a model-visible, customer-invisible signal into the current conversation (the widget context's `injectSignal`). */\n handleInjectSignal: (signalText: string, options?: InjectSignalOptions) => Promise<boolean>;\n /** The widget render report collector of the current conversation (one per conversation). */\n renderReportCollector: ReturnType<typeof createWidgetRenderReportCollector>;\n}\n\n/**\n * The signals the chat sends besides the customer's messages: a widget's injected signal (with the closed-conversation\n * guard and the cold start through a START signal), a context-only signal parked until a turn is observed running,\n * the corrective signal for a widget block the renderer dropped, and the widget render report.\n */\nexport const useConversationSignals = (inputs: ConversationSignalsInputs): ConversationSignals => {\n const {\n client,\n conversationId,\n conversation,\n messages,\n runStatus,\n startingNewConversation,\n isConversationRunEnded,\n handleSendMessage,\n rejectAsConversationClosed,\n refetchConversationSummary,\n setScrollToBottomNonce,\n } = inputs;\n // The conversation actually shown right now, kept in sync every render — read from an `injectSignal` `.catch`\n // so a late-landing rejection for a conversation the customer already left doesn't dispatch onto whatever is\n // open now (see the id check inside `handleInjectSignal`).\n const currentConversationIdRef = useRef<number | null>(null);\n currentConversationIdRef.current = conversation?.id ?? null;\n\n // A `withoutOwnAgentTurn` signal (context riding along a just-posted user message, e.g. advisor-extension\n // instructions) waiting for a turn to be OBSERVED running. Delivered mid-turn it lands in the conversation history\n // without re-driving the agent — the backend only re-drives when the LAST message is an unanswered inbound, and a\n // signal appended before the live turn's reply is no longer last (see the flush effect's strand explanation below;\n // here that strand behavior is exactly what we want: in context from the next turn on, never its own reply).\n // `conversationId` pins the signal to the conversation open at park time: null = parked on a cold start (the\n // paired message creates the conversation, deliver into whichever id lands); a non-null mismatch at flush time\n // means the user switched conversations first — the signal is dropped, never leaked into the other conversation.\n const signalAwaitingRunningTurnRef = useRef<{ signalText: string; conversationId: number | null } | null>(null);\n // Inject a model-visible / user-invisible SIGNAL into the CURRENT conversation and drive one agent turn — the\n // data-back path for a picker widget (\"User selected image A\"). Resilient (swallows errors, never throws\n // into render). The reply lands via the existing realtime signal, exactly like a posted message — no extra handling\n // needed here.\n //\n // NOTE: unlike the message-post path this carries NO admin overrides. The endpoint\n // (AIConversationsController::injectSignal) reads only `signalText` + `signalSource` — it has no `budgetBypass` /\n // `aiModelName` parameter, so the earlier hand-wired call was sending two query params the backend discarded. An\n // impersonating admin's model pick therefore does not apply to a widget-click-driven turn; the conversation's\n // stored model does.\n const handleInjectSignal = useCallback(\n async (signalText: string, options?: InjectSignalOptions): Promise<boolean> => {\n if (!signalText.trim()) return false;\n // CUSTOMER_CLICK (the default when options is omitted, e.g. the briefing widgets' plain signal text) is the\n // customer pressing a widget button; PROGRAMMATIC (park-then-flush ride-alongs, the widget-invalid corrective)\n // never came from a click — it must never surface a refusal or move the scroll position.\n const isCustomerClick = options?.signalOrigin !== \"PROGRAMMATIC\";\n // Same guard as the message path: a closed conversation rejects signals too, so no widget click posts one. A\n // genuine click gets the reason on the error card; a programmatic ride-along is simply dropped, as on any\n // other failure.\n if (isConversationRunEnded) {\n if (isCustomerClick) {\n rejectAsConversationClosed();\n }\n return false;\n }\n // On a real click, scroll the chat to the bottom to follow the turn this signal drives.\n if (isCustomerClick) {\n setScrollToBottomNonce((nonce) => nonce + 1);\n }\n // Context-only signal: deliver it ONLY while a turn is running, so it never drives its own turn / reply. Not\n // running yet (the paired user message's POST is still in flight, or the conversation is still being created on\n // a cold start) — park it until the flush effect below sees \"running\". Dropped if no turn ever starts.\n if (options?.withoutOwnAgentTurn && runStatus !== \"running\") {\n signalAwaitingRunningTurnRef.current = {\n signalText,\n conversationId: conversation?.id ?? conversationId ?? null,\n };\n return false;\n }\n const targetConversationId = conversation?.id ?? conversationId;\n // No conversation yet (e.g. a briefing CTA clicked on the cold dashboard greeting): start one via the\n // start-with-signal path — an EMPTY visible message carrying the click as the invisible START signal, so the\n // agent's first turn already has it and it speaks first (no visible bubble, no deferred re-inject). Once a\n // conversation exists we keep the silent injectSignal behavior below.\n if (!targetConversationId) {\n if (startingNewConversation) return false;\n handleSendMessage(\"\", { startSignalText: signalText });\n return false;\n }\n // No admin-debug overrides here on purpose — see the NOTE on this callback: the endpoint takes neither\n // `budgetBypass` nor `aiModelName`.\n // signalSource defaults server-side to FRONTEND_WIDGET_CLICK; the widget-failover passes FRONTEND_WIDGET_INVALID.\n return client\n .injectSignal(targetConversationId, { text: signalText, source: options?.signalSource })\n .then(() => true)\n .catch((signalRequestError: unknown) => {\n // Best-effort: a failed signal must not break the widget render. The turn simply doesn't advance. A\n // GENUINE widget click is the exception, and only for the one refusal reason the customer can act on\n // (the conversation closed meanwhile) — every other failure stays silent, exactly as before.\n const isConversationClosedRefusal =\n isAgentsClientError(signalRequestError) && signalRequestError.kind === \"closed\";\n // The request targeted a conversation the customer has since left (switched conversations before this\n // late-landing rejection arrived) — don't dispatch onto whatever conversation is open now.\n if (\n isCustomerClick &&\n isConversationClosedRefusal &&\n currentConversationIdRef.current === targetConversationId\n ) {\n rejectAsConversationClosed();\n // The closed runState locks the remaining widget controls.\n refetchConversationSummary();\n }\n return false;\n });\n },\n [\n client,\n conversation,\n conversationId,\n startingNewConversation,\n handleSendMessage,\n runStatus,\n isConversationRunEnded,\n rejectAsConversationClosed,\n refetchConversationSummary,\n setScrollToBottomNonce,\n ],\n );\n\n // Deliver a parked context-only signal the moment its paired turn is observed running (see\n // `signalAwaitingRunningTurnRef`). Re-entering handleInjectSignal with `withoutOwnAgentTurn` while \"running\"\n // passes its park-guard and POSTs. Tiny race stays open: if the turn settles between this observation and the\n // POST landing, the signal becomes the last message and drives one extra turn — rare and harmless (the agent\n // acknowledges the instructions), accepted for an FE-only build.\n useEffect(() => {\n if (runStatus !== \"running\" || !signalAwaitingRunningTurnRef.current) return;\n const parkedSignal = signalAwaitingRunningTurnRef.current;\n signalAwaitingRunningTurnRef.current = null;\n // Parked for a DIFFERENT conversation (the user switched before its turn ran) — drop, don't leak it here.\n if (parkedSignal.conversationId !== null && parkedSignal.conversationId !== conversation?.id) return;\n handleInjectSignal(parkedSignal.signalText, { withoutOwnAgentTurn: true, signalOrigin: \"PROGRAMMATIC\" });\n }, [runStatus, handleInjectSignal, conversation?.id]);\n\n // ── Widget failover ─────────────────────────────────────────────────────────────────────────────────────────────\n // A weaker model can emit a ```widget block whose `type` is not a real widget (a model wrote\n // `type: \"example\"`, not `ExampleWidget`). remarkWidgetFencePlugin silently DROPS it → the customer sees no\n // widget and the model gets no feedback, so it insists \"it should be visible\". Detect the dropped block on the newest\n // SETTLED assistant message and inject a silent corrective SIGNAL (with a similarity \"did you mean\" shortlist) so the\n // model re-emits with a valid name. Guards: (1) only after a live turn we OBSERVED running — never retroactively\n // \"correct\" widgets already in history when a conversation opens; (2) report each message id at most once; (3) cap\n // corrections per conversation so a too-weak model can't loop forever.\n const sawRunningForWidgetCheckRef = useRef(false);\n const reportedWidgetErrorMessageIdsRef = useRef<Set<number>>(new Set());\n const widgetCorrectionCountRef = useRef(0);\n\n useEffect(() => {\n if (runStatus === \"running\") sawRunningForWidgetCheckRef.current = true;\n }, [runStatus]);\n\n useEffect(() => {\n // A new conversation resets the live-turn sighting and the per-conversation correction budget. (The parked\n // context-only signal is NOT cleared here: a cold start legitimately transitions id null→new while the signal\n // waits; cross-conversation leaking is prevented by the id check in its flush effect instead.)\n sawRunningForWidgetCheckRef.current = false;\n reportedWidgetErrorMessageIdsRef.current = new Set();\n widgetCorrectionCountRef.current = 0;\n }, [conversation?.id]);\n\n useEffect(() => {\n if (runStatus !== \"idle\" || !sawRunningForWidgetCheckRef.current) return;\n if (widgetCorrectionCountRef.current >= WIDGET_CORRECTION_CAP || !messages) return;\n const latestAssistantMessage = [...messages]\n .reverse()\n .find(\n (message) => message.role === \"ASSISTANT\" && message.messageType === \"TEXT\",\n );\n const messageId = latestAssistantMessage?.id;\n if (!messageId || !latestAssistantMessage?.message) return;\n if (reportedWidgetErrorMessageIdsRef.current.has(messageId)) return;\n // Feed the SAME normalized text ConversationMarkdown renders (it repairs a fence the model broke mid-text) —\n // scanning the raw stored text here would report a fence the renderer already fixed as unrendered.\n const unrenderedWidgets = detectUnrenderedWidgets(normalizeServerMessageToMarkdown(latestAssistantMessage.message));\n if (unrenderedWidgets.length === 0) return;\n reportedWidgetErrorMessageIdsRef.current.add(messageId);\n widgetCorrectionCountRef.current += 1;\n handleInjectSignal(buildUnrenderedWidgetSignal(unrenderedWidgets), {\n signalSource: WIDGET_INVALID_SIGNAL_SOURCE,\n signalOrigin: \"PROGRAMMATIC\",\n });\n }, [messages, runStatus, handleInjectSignal]);\n\n // ── Widget render report ─────────────────────────────────────────────────────────────────────────\n // Every block of a live-delivered message reports mounted / empty / failed / pending; once a message's blocks settle,\n // ONE context signal tells the model which ones the owner did not see as intended. A clean render sends nothing; the\n // source owes no work, so the signal never drives a turn of its own (the next turn reads it). One collector per\n // conversation, so a switch never reports into the other one.\n const sendWidgetRenderReportRef = useRef<(messageId: string, blocks: WidgetRenderBlockReport[]) => void>(() => {});\n sendWidgetRenderReportRef.current = (messageId: string, blocks: WidgetRenderBlockReport[]) => {\n const renderReportSignalText = buildWidgetRenderReportSignal(messageId, blocks);\n if (renderReportSignalText === null) return;\n handleInjectSignal(renderReportSignalText, {\n signalSource: WIDGET_RENDER_REPORT_SIGNAL_SOURCE,\n signalOrigin: \"PROGRAMMATIC\",\n });\n };\n const renderReportCollector = useMemo(\n () =>\n createWidgetRenderReportCollector({\n onSettled: (messageId, blocks) => sendWidgetRenderReportRef.current(messageId, blocks),\n }),\n // eslint-disable-next-line react-hooks/exhaustive-deps -- one collector per conversation\n [conversation?.id],\n );\n useEffect(() => () => renderReportCollector.dispose(), [renderReportCollector]);\n\n return { handleInjectSignal, renderReportCollector };\n};\n","import {\n type ComponentType,\n type HTMLAttributes,\n type ReactNode,\n type Ref,\n type RefObject,\n useCallback,\n useEffect,\n useImperativeHandle,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport {\n AgentsClientError,\n type ConversationAttachmentReference,\n isAgentsClientError,\n} from \"../../contract/conversation\";\nimport { useAgentsEnvironment } from \"../../provider/AgentsProvider\";\nimport { reportRunningTurn } from \"../../provider/environment\";\nimport { CanvasRestoreOnMount } from \"../../renderer/canvas/CanvasRestoreOnMount\";\nimport { ConversationDeepLinkedWidget } from \"../../renderer/ConversationDeepLinkedWidget\";\nimport { ConversationWidgetProvider } from \"../../renderer/ConversationWidgetContext\";\nimport { WidgetRenderReportCollectorContext } from \"../../renderer/render-report/widget-render-report-collector\";\nimport { resolveDeepLinkableWidget } from \"../../renderer/resolve-deep-linkable-widget\";\nimport type { ChatMessage } from \"../chat-message\";\nimport type { SendMessageHandler } from \"../conversation-send-message\";\nimport type { ConversationMessageInputHandle } from \"../ConversationMessageInput/ConversationMessageInput\";\nimport type { ConversationComposerWidget } from \"../../renderer/conversation-composer-widget\";\nimport type { ComposerLibraryFile } from \"../../renderer/composer-library-file\";\nimport { ConversationView } from \"../ConversationView\";\nimport { findUnansweredWidgetMessageId } from \"../ConversationMessageList/ConversationMessageList\";\nimport type { MessageTimesMode } from \"../ConversationMessageList/message-times\";\nimport type { AgentsChatState } from \"../store/agents-chat-state\";\nimport { ConversationErrorType } from \"../store/conversation-error-type\";\nimport type { AgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { useAgentsChatSelector } from \"../store/use-agents-chat-store\";\nimport {\n type AgentChatActivityTiming,\n type ResolvedAgentChatActivityTiming,\n resolveAgentChatActivityTiming,\n} from \"./chat-activity-timing\";\nimport type { ChatScrollTarget } from \"./chat-scroll-target\";\nimport { deriveAgentActivity } from \"./derive-agent-activity\";\nimport { isChatReadyToSendPendingStartRequest, type PendingStartRequest, pickPendingStartRequest } from \"./pending-start-request\";\nimport { type ActivityTicker, type ActivityTickerTurn, useActivityTicker } from \"./use-activity-ticker\";\nimport { useConversationActivity } from \"./use-conversation-activity\";\nimport { useConversationLiveUpdates } from \"./use-conversation-live-updates\";\nimport { CONVERSATION_MESSAGE_PAGE_SIZE, useConversationMessagePages } from \"./use-conversation-message-pages\";\nimport { findTurnsInFlight, isTurnInitiatorMessage } from \"./turn-initiators\";\nimport { RunningBackgroundJobsContext, type RunningBackgroundJobsContextValue } from \"../trace/running-background-jobs-context\";\nimport { QueuedMessageChip } from \"../trace/QueuedMessageChip\";\nimport { useConversationScrollJump } from \"./use-conversation-scroll-jump\";\nimport { useConversationSignals } from \"./use-conversation-signals\";\nimport {\n CanvasViabilityContext,\n ElementWidthCanvasViability,\n} from \"../../widgets/CanvasLauncherWidget/use-canvas-viable\";\n\n/** What the host's activity components get: the turn's state and the paced lines of the activity ticker. */\nexport interface AgentChatActivityProps {\n /** A turn is in flight (derived from the messages and the run status). */\n active: boolean;\n /** The chat shows an error card. */\n failed: boolean;\n activityTicker: ActivityTicker;\n /** The agent works on a task: a turn is in flight or the ticker still shows its lines. */\n isAgentWorkingOnTask: boolean;\n /** The key of the agent space the chat is open on. */\n agentSpaceKey: number;\n /** The chat's resolved activity timing (`activityTiming`, the environment's, the package's), for the component's motion. */\n activityTiming?: ResolvedAgentChatActivityTiming;\n /** The chat's store, for a component that reads more of the chat's state (`useAgentsChatSelector`). */\n chatStore: AgentsChatStore;\n /**\n * The newest widget-carrying assistant message the owner has not answered yet (no later owner message, no later\n * widget click) — null when there is none ({@link findUnansweredWidgetMessageId}). Whether that widget waits for an\n * answer is the widget class's `AWAITS_OWNER_INPUT` on the server; the wire does not carry it, so a host that tells\n * questions from other widgets checks the widget names of that message itself.\n */\n unansweredWidgetMessageId: string | number | null;\n}\n\n/** What the host's avatar beside an assistant message gets (`AssistantAvatar`). */\nexport interface AgentChatAssistantAvatarProps {\n message: ChatMessage;\n}\n\n/** What the host's activity history under a message gets: the finished turn that message started, if any. */\nexport interface AgentChatActivityHistoryProps {\n turn: ActivityTickerTurn | null;\n}\n\n/** What the host's trace of one turn gets (`TurnTrace`): the message that started the turn and where the turn stands. */\nexport interface AgentChatTurnTraceProps {\n conversationId: number;\n /** The message that may have started a turn: the owner's message or a signal that owes work. */\n turnMessageId: number | string;\n /** live = the turn this message started runs right now; done = it ended (or the message started none). */\n phase: \"live\" | \"done\";\n /** The chat is the compact side panel: the trace takes its narrow form. */\n isCompact: boolean;\n}\n\n/** What a host does with the composer of a mounted chat (`AgentChat`'s `composerRef`). */\nexport interface AgentChatComposerHandle {\n /**\n * Replaces the composer's draft with `text` (empty clears it) and puts the caret at its end — never sends. Does\n * nothing while the composer is not shown (a closed conversation).\n */\n setComposerDraft: (text: string) => void;\n /** Focuses the composer, the caret at the end of its draft (e.g. after files were dropped on the chat). */\n focusComposer?: () => void;\n}\n\n/** Where the model of the next send comes from — read at send time (an admin's pick can change between renders). */\nexport interface AgentChatSendModelSource {\n readModelForNextSend: () => string | undefined;\n}\n\nexport interface AgentChatControllerProps {\n /** The state handle of this chat instance (created and released by the app). */\n chatStore: AgentsChatStore;\n /** The conversation client this chat reads and sends through. */\n client: AgentsConversationClient;\n /** The key of the agent space new conversations start in. */\n agentSpaceKey: number;\n /** When set, load + resume this existing conversation. Absent = empty chat, lazy-starts on first send. */\n conversationId?: number;\n onNewConversation?: (conversationId: number) => void;\n /** The conversation could not be loaded (missing, deleted, not readable): the host drops to the empty chat. */\n onConversationNotFound?: () => void;\n /** Switch the active conversation — the ConversationSearchResults widget's open-arrow target. */\n onOpenConversation?: (conversationId: number, messageId?: number) => void;\n /** Switch this chat to another conversation of the same agent space in place (a widget linking to related work). */\n onSwitchConversation?: (conversationId: number) => void;\n /** Text inserted into the composer once on mount — never sent automatically. */\n initialComposerPrompt?: string;\n /** A request to scroll a message into view and flash it; re-applied whenever its `nonce` changes. */\n scrollTarget?: ChatScrollTarget;\n /** Each finished turn's activity lines stay in the thread above its answer (rendered by `ActivityHistory`). */\n keepActivityHistoryAfterAnswer?: boolean;\n /**\n * The timing of the activity reads and of the working indicator's lines (the 3 s read window, the line paces, the\n * success beat). Each field the chat leaves out comes from `AgentsEnvironment.chatActivityTiming`, else the package's\n * value. A host whose realtime push writes `activityUpdatedAt` when the narrator finishes lowers the read window, so a\n * narrated line shows at once.\n */\n activityTiming?: AgentChatActivityTiming;\n /** The host shows one conversation the owner may not leave: no starting ideas (the agent speaks first). */\n isPinnedToSingleConversation?: boolean;\n /** App extension of the widget context: the chat is the app's guided first-run setup. */\n isOnboardingSetupConversation?: boolean;\n /** The model of the next send; without it the conversation's own model drives. */\n sendModelSource?: AgentChatSendModelSource;\n /** Called after a send that carried attachments, so the host clears them from the composer. */\n onAttachmentsSent?: () => void;\n /**\n * Called once for every send the chat accepted (typed, a widget's send, the opening request's message), with the\n * text as sent, right when it goes out — e.g. for a host's send animation. A refused send (a closed conversation, a\n * start still in flight) reports nothing.\n */\n onMessageSent?: (messageText: string) => void;\n /**\n * Called after an accepted send that carried composer widgets (the widget context's and `hostComposerWidgets`), with\n * those widgets — the host clears the ones it owns.\n */\n onComposerWidgetsSent?: (composerWidgets: ConversationComposerWidget[]) => void;\n /** Widget callback: put media-library files into the composer (a file library canvas's \"Use in chat\"). */\n attachLibraryFilesToComposer?: (libraryFiles: ComposerLibraryFile[]) => void;\n /** The empty state of a new chat: a synthetic first assistant message (client state only), as markdown. */\n startingIdeasMarkdown?: string;\n /** While true the chat follows the bottom; a rising edge jumps to the newest message (a voice chat). */\n followBottom?: boolean;\n /** The chat's scroll container (the host may own it, e.g. for a scroll-linked background). */\n chatScrollRef: RefObject<HTMLDivElement | null>;\n isCompact?: boolean;\n confineTopBlurBandToChatPane?: boolean;\n /** Class names of the two wrappers around the conversation view (the host's layout). */\n chatAreaClassName?: string;\n chatWrapClassName?: string;\n /** Further props of the chat area element (e.g. a host's file drop zone handlers). */\n chatAreaProps?: Omit<HTMLAttributes<HTMLDivElement>, \"className\" | \"ref\">;\n /** Slots of the conversation view. */\n progressStepperSlot?: ReactNode;\n /** The host's layer while files are dragged over the window (see `ConversationViewBody`'s `fileDropHintSlot`). */\n fileDropHintSlot?: ReactNode;\n inputActionsSlot?: ReactNode;\n inputActionsSlotStart?: ReactNode;\n inputTopSlot?: ReactNode;\n inputSendDisabled?: boolean;\n inputReplacementSlot?: ReactNode;\n inputBandSlot?: ReactNode;\n inputPlaceholder?: string;\n inputSendReplacementWhenEmpty?: ReactNode;\n inputGlowUnderlay?: ReactNode;\n isContentOverlayShown?: boolean;\n isQuestionPinSuspended?: boolean;\n /** The attachments that ride along on the next send. */\n outgoingAttachments?: ConversationAttachmentReference[];\n /** Composer widgets the host holds outside the widget context, sent with the next send (see `ConversationMessageInput`). */\n hostComposerWidgets?: ConversationComposerWidget[];\n /**\n * The agent's activity at the tail of the thread (the agent avatar slot). Always mounted, also between turns: it is\n * the resting avatar under the last message while `active` and `isAgentWorkingOnTask` are false, and the working one\n * during a turn — one instance, never remounted by a turn's start or end.\n */\n ThinkingIndicator: ComponentType<AgentChatActivityProps>;\n /** Shown left of each assistant message, at its top (an avatar face, 24–28 px). Undefined: no avatar. */\n AssistantAvatar?: ComponentType<AgentChatAssistantAvatarProps>;\n /** A layer over the message column (a voice chat's focus mode); shown while `isContentOverlayShown`. */\n ContentOverlay?: ComponentType<AgentChatActivityProps>;\n /** The kept activity lines under the message that started a turn (with `keepActivityHistoryAfterAnswer`). */\n ActivityHistory?: ComponentType<AgentChatActivityHistoryProps>;\n /**\n * The trace of a turn (its step rows), between the message that started the turn and the answer. Mounted once after\n * every message that can start a turn (the owner's messages and the signals that owe work), for turns read from the\n * history as for turns watched live; the component reads the turn's trace by `turnMessageId` and renders nothing for\n * a message that started none. When given it stands in place of `ActivityHistory`. Default: none.\n */\n TurnTrace?: ComponentType<AgentChatTurnTraceProps>;\n /**\n * Marks the owner's messages sent while a turn runs as queued (`QueuedMessageChip` under the message) until the turn\n * ends: the agent reads them after its current step. Default false.\n */\n showsQueuedMessages?: boolean;\n /**\n * When what was written in the thread (`MessageTimesMode`): `turns` = day separators, a time head after a pause,\n * \"finished HH:MM\" under a long turn's answer, the exact time on hover / focus / tap; `everyMessage` adds a quiet time\n * under every message (e.g. the host's verbose view). Default: none.\n */\n messageTimes?: MessageTimesMode | null;\n /** Rendered inside the chat's widget provider (the host's canvas syncs). */\n children?: ReactNode;\n /**\n * The chat renders without the canvas split: no side pane, the message column alone. Default false. Without a canvas\n * surface of the host's own (`hostHasCanvasSurface`), every canvas open is then ignored.\n */\n disableSplitView?: boolean;\n /**\n * Whether a canvas may open in this chat: false ignores every open request (reason `noSurface`), true lets the canvas\n * state open while the host draws it (with `disableSplitView`: in a surface of its own, e.g. `CanvasPane`). Default:\n * true with the split view, false without it.\n */\n hostHasCanvasSurface?: boolean;\n /**\n * The host paints the chat's background behind it (the pane stays transparent, the frosted top band of a floating\n * top bar keeps its look). Default true; false gives the chat the package's own background\n * (`--agents-chat-background`).\n */\n backgroundPaintedByHost?: boolean;\n /** The handle of the composer: put a draft into the mounted chat without a remount (`setComposerDraft`). */\n composerRef?: Ref<AgentChatComposerHandle>;\n}\n\n/** Returns true when the messages contain an ERROR message whose signalSource is AI_BUDGET_REACHED. */\nconst hasBudgetReachedError = (messages: ChatMessage[] | null): boolean =>\n (messages ?? []).some((message) => message.messageType === \"ERROR\" && message.signalSource === \"AI_BUDGET_REACHED\");\n\n/** Every port function rejects with `AgentsClientError`; anything else (a bug) reads as an `other` refusal. */\nconst toAgentsClientErrorOfPort = (failure: unknown): AgentsClientError =>\n isAgentsClientError(failure) ? failure : new AgentsClientError(\"other\");\n\nconst selectMessages = (state: AgentsChatState) => state.messages;\nconst selectError = (state: AgentsChatState) => state.error;\nconst selectRateLimitRetryAfterSeconds = (state: AgentsChatState) => state.rateLimitRetryAfterSeconds;\nconst selectConversation = (state: AgentsChatState) => state.conversation;\nconst selectStartingNewConversation = (state: AgentsChatState) => state.startingNewConversation;\nconst selectCanvas = (state: AgentsChatState) => state.canvas;\nconst selectHasMoreOlder = (state: AgentsChatState) => state.hasMoreOlder;\nconst selectOpeningRequest = (state: AgentsChatState) => state.openingRequest;\n\n/**\n * The agent chat: the controller over the conversation client port and the chat store — open, pages,\n * live updates, sends, signals, the error card and retry, the opening request, the deep-linked widget, the scroll jump\n * and the activity — rendering the conversation view with the host's slots. The drive is async: a reply never comes\n * in the start/post answer, it arrives through the live updates.\n */\nexport const AgentChatController = (props: AgentChatControllerProps) => {\n const {\n chatStore,\n client,\n agentSpaceKey,\n conversationId,\n onNewConversation,\n onConversationNotFound,\n onOpenConversation,\n onSwitchConversation,\n initialComposerPrompt,\n scrollTarget,\n keepActivityHistoryAfterAnswer = false,\n activityTiming,\n isPinnedToSingleConversation = false,\n isOnboardingSetupConversation = false,\n sendModelSource,\n onAttachmentsSent,\n onMessageSent,\n onComposerWidgetsSent,\n attachLibraryFilesToComposer,\n startingIdeasMarkdown,\n followBottom = false,\n chatScrollRef,\n isCompact = false,\n confineTopBlurBandToChatPane = false,\n chatAreaClassName,\n chatWrapClassName,\n chatAreaProps,\n progressStepperSlot,\n fileDropHintSlot,\n inputActionsSlot,\n inputActionsSlotStart,\n inputTopSlot,\n inputSendDisabled,\n inputReplacementSlot,\n inputBandSlot,\n inputPlaceholder,\n inputSendReplacementWhenEmpty,\n inputGlowUnderlay,\n isContentOverlayShown,\n isQuestionPinSuspended,\n outgoingAttachments,\n hostComposerWidgets,\n ThinkingIndicator,\n AssistantAvatar,\n ContentOverlay,\n ActivityHistory,\n TurnTrace,\n showsQueuedMessages = false,\n messageTimes = null,\n children,\n disableSplitView = false,\n hostHasCanvasSurface = !disableSplitView,\n backgroundPaintedByHost = true,\n composerRef,\n } = props;\n\n // The canvas split fits by the width of this chat's own area, not the viewport's (a narrow chat column in a wide\n // window covers the chat with the canvas instead of squeezing a split into it).\n const [canvasViability] = useState(() => new ElementWidthCanvasViability());\n\n // The composer's handle: the initial prompt and a widget's `prefillComposer` put text into it without sending.\n const conversationMessageInputApiRef = useRef<ConversationMessageInputHandle>(null);\n useImperativeHandle(\n composerRef,\n () => ({\n setComposerDraft: (text: string) => conversationMessageInputApiRef.current?.insertTextIntoInput(text),\n focusComposer: () => conversationMessageInputApiRef.current?.focusInput?.(),\n }),\n [],\n );\n useEffect(() => {\n if (!initialComposerPrompt) return;\n conversationMessageInputApiRef.current?.insertTextIntoInput(initialComposerPrompt);\n // Mount-only: a one-shot initial value, not a live prop to keep re-applying.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const messages = useAgentsChatSelector(chatStore, selectMessages);\n const error = useAgentsChatSelector(chatStore, selectError);\n const rateLimitRetryAfterSeconds = useAgentsChatSelector(chatStore, selectRateLimitRetryAfterSeconds);\n const conversation = useAgentsChatSelector(chatStore, selectConversation);\n const startingNewConversation = useAgentsChatSelector(chatStore, selectStartingNewConversation);\n const canvas = useAgentsChatSelector(chatStore, selectCanvas);\n const hasMoreOlder = useAgentsChatSelector(chatStore, selectHasMoreOlder);\n const openingRequest = useAgentsChatSelector(chatStore, selectOpeningRequest);\n const pendingStartUserMessage = openingRequest.userMessage;\n const pendingStartSignalText = openingRequest.startSignalText;\n const pendingStartEntryPointKey = openingRequest.entryPointKey;\n const pendingDeepLinkedWidgetName = openingRequest.deepLinkedWidgetName;\n\n // A terminal runState: the run is over, the server rejects further owner input (the closed bar replaces the input).\n const isConversationRunEnded = conversation?.runState === \"COMPLETED\" || conversation?.runState === \"CANCELLED\";\n\n // The message reads (newest page, changed tail, older page, metadata) over the client, written into the store.\n const messagePages = useConversationMessagePages(chatStore, client, CONVERSATION_MESSAGE_PAGE_SIZE);\n const { readConversationMetadata, fetchOpeningPage, loadOlder, loadingOlder } = messagePages;\n\n // Load an existing conversation: the metadata (no messages, non-destructive) apart from the newest page (merged,\n // never clears — no skeleton flash). A refused metadata read drops the host to the empty chat.\n useEffect(() => {\n if (!conversationId) {\n // Empty chat: reset so a stale conversation can't linger; the first owner message lazy-starts a new one.\n chatStore.dispatch({ type: \"reset\" });\n return;\n }\n if (String(conversation?.id) === String(conversationId)) return;\n chatStore.dispatch({ type: \"reset\" });\n void readConversationMetadata(conversationId).then((wasRead) => {\n if (!wasRead) onConversationNotFound?.();\n });\n fetchOpeningPage(conversationId);\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [conversationId]);\n\n // Reset the chat state on unmount so reopening the chat starts clean.\n useEffect(() => {\n return () => {\n chatStore.dispatch({ type: \"reset\" });\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n const liveConversationId = conversation?.id ?? conversationId;\n\n // The deep-linked widget hand-over (the opening request's `deepLinkedWidgetName`): mounted ONCE per hand-over under\n // a fresh mount key, released once the canvas it declares (`opensCanvases`) is open — never just \"some canvas\" — or\n // after 15 s for a widget that opens none. A cold chat that remounts meanwhile keeps the request.\n const [deepLinkedWidget, setDeepLinkedWidget] = useState<{ name: string; mountKey: number } | undefined>(undefined);\n const mountedHandOverRef = useRef<string | null>(null);\n useEffect(() => {\n if (!pendingDeepLinkedWidgetName) {\n mountedHandOverRef.current = null;\n return;\n }\n if (mountedHandOverRef.current === pendingDeepLinkedWidgetName) return;\n mountedHandOverRef.current = pendingDeepLinkedWidgetName;\n setDeepLinkedWidget((previous) => ({ name: pendingDeepLinkedWidgetName, mountKey: (previous?.mountKey ?? 0) + 1 }));\n }, [pendingDeepLinkedWidgetName]);\n const handedOverOpensCanvas =\n canvas !== null &&\n (resolveDeepLinkableWidget(pendingDeepLinkedWidgetName)?.opensCanvases?.includes(canvas.canvasId) ?? false);\n useEffect(() => {\n if (!pendingDeepLinkedWidgetName) return;\n const releaseHandOver = () =>\n chatStore.dispatch({ type: \"openingRequestSet\", openingRequest: { deepLinkedWidgetName: null } });\n if (handedOverOpensCanvas) {\n releaseHandOver();\n return;\n }\n const release = window.setTimeout(releaseHandOver, 15000);\n return () => window.clearTimeout(release);\n }, [pendingDeepLinkedWidgetName, handedOverOpensCanvas, chatStore]);\n\n const hasMoreOlderRef = useRef(hasMoreOlder);\n hasMoreOlderRef.current = hasMoreOlder;\n const messagesRef = useRef(messages);\n messagesRef.current = messages;\n // Scroll-up pagination: reads the store, so its identity changes only with the conversation (the sentinel's\n // IntersectionObserver is not torn down on every message change).\n const loadOlderOfLiveConversation = useCallback(() => loadOlder(liveConversationId), [loadOlder, liveConversationId]);\n\n // The title lands asynchronously after the first turn: re-read the metadata only (the messages stay as they are).\n const refetchConversationSummary = useCallback(() => {\n if (!liveConversationId) return;\n void readConversationMetadata(liveConversationId);\n }, [readConversationMetadata, liveConversationId]);\n\n // Live updates: the package rules over the client's subscription; the binding owns the transport.\n const { runStatus, liveReadCount, readChangedTailNow } = useConversationLiveUpdates({\n client,\n chatStore,\n messagePages,\n conversationId: liveConversationId,\n });\n\n // What the agent is doing right now, one generated line per step, paced by the ticker.\n const { chatActivityTiming: environmentActivityTiming } = useAgentsEnvironment();\n const resolvedActivityTiming = useMemo(\n () => resolveAgentChatActivityTiming(activityTiming, environmentActivityTiming),\n [activityTiming, environmentActivityTiming],\n );\n const {\n elements: activityElements,\n running: activityRunning,\n turnMessageId: activityTurnMessageId,\n runningBackgroundJobs,\n refresh: refreshActivity,\n } = useConversationActivity({\n conversationId: liveConversationId ?? 0,\n runStatus,\n // Every live read also asks for the activity lines; the hook throttles to one request per read window (3 s default).\n signalVersion: liveReadCount,\n enabled: Boolean(liveConversationId),\n activityRequestWindowMs: resolvedActivityTiming.activityRequestWindowMs,\n runningFloorMs: resolvedActivityTiming.runningFloorMs,\n });\n const activityTicker = useActivityTicker({\n elements: activityElements,\n running: activityRunning,\n turnMessageId: activityTurnMessageId,\n failed: !!error,\n keepActivityHistoryAfterAnswer,\n linePaceMs: resolvedActivityTiming.linePaceMs,\n backlogLinePaceMs: resolvedActivityTiming.backlogLinePaceMs,\n successBeatMs: resolvedActivityTiming.successBeatMs,\n });\n\n // The run status → the error card only (aiThinking follows the derived activity below). messages is a dependency:\n // the ERROR message with signalSource=AI_BUDGET_REACHED lands slightly after the status flips to \"failed\".\n useEffect(() => {\n if (runStatus === \"failed\") {\n chatStore.dispatch({\n type: \"errorSet\",\n error: hasBudgetReachedError(messages) ? ConversationErrorType.AI_BUDGET : ConversationErrorType.AGENT_ERROR,\n });\n } else if (runStatus === \"running\") {\n chatStore.dispatch({ type: \"errorSet\", error: null });\n }\n }, [runStatus, chatStore, messages]);\n\n // Retry of a FAILED run: re-drives the stored, unanswered owner message; accepted → the card goes.\n const handleRetryFailedRun = useCallback(async () => {\n const retryConversationId = conversationId ?? conversation?.id;\n if (!retryConversationId) {\n return;\n }\n await client.retryConversation(retryConversationId);\n chatStore.dispatch({ type: \"errorSet\", error: null });\n }, [conversationId, conversation?.id, client, chatStore]);\n\n // Bumped whenever the chat must jump to the newest content: a widget click that injects a signal, the closed refusal.\n const [scrollToBottomNonce, setScrollToBottomNonce] = useState(0);\n\n // While the host asks to follow the bottom (a voice chat), a question pinned by an earlier send must not keep the\n // new lines below the fold.\n useEffect(() => {\n if (followBottom) setScrollToBottomNonce((nonce) => nonce + 1);\n }, [followBottom]);\n\n /** The closed refusal on the error card, without any request — and the jump, so the card is in view. */\n const rejectAsConversationClosed = useCallback(() => {\n chatStore.dispatch({ type: \"errorSet\", error: ConversationErrorType.CONVERSATION_CLOSED });\n setScrollToBottomNonce((nonce) => nonce + 1);\n }, [chatStore]);\n\n const handleSendMessage = useCallback<SendMessageHandler>(\n (message, { startSignalText, attachments, composerWidgets, entryPointKey }) => {\n // A closed conversation takes no further input — the typed input and every widget send.\n if (isConversationRunEnded) {\n rejectAsConversationClosed();\n return false;\n }\n // The canvas model's SEND boundary: a turn canvas ends, a pinned one stays.\n chatStore.dispatch({ type: \"canvasResetForNewTurn\" });\n const model = sendModelSource?.readModelForNextSend();\n // The optimistic bubble shows the text the server stores (attachments as the binding writes them).\n const sentMessageText = client.composeSentMessageText\n ? client.composeSentMessageText(message, attachments)\n : message;\n // Reported for an accepted send only. Only a send that carried attachments clears them: a widget send and the cold-start greeting carry none and\n // must never wipe what the owner is still composing.\n const reportAcceptedSend = () => {\n if (attachments?.length) onAttachmentsSent?.();\n if (composerWidgets?.length) onComposerWidgetsSent?.(composerWidgets);\n onMessageSent?.(message);\n };\n if (conversation?.id) {\n const postConversationId = conversation.id;\n chatStore.dispatch({ type: \"messagePostRequested\", message: { message: sentMessageText, role: \"USER\" } });\n client\n .postMessage(postConversationId, { text: message, model, attachments })\n .then((posted) =>\n chatStore.dispatch({ type: \"messagePostReceived\", conversationId: postConversationId, posted }),\n )\n .catch((failure: unknown) =>\n chatStore.dispatch({ type: \"messagePostFailed\", error: toAgentsClientErrorOfPort(failure) }),\n );\n reportAcceptedSend();\n return true;\n }\n // No conversation yet — lazy start; `startSignalText` rides along as the invisible start context.\n if (startingNewConversation) return false;\n // The store hands out the start's token (it outlives a remount): its answer applies only while it is pending.\n chatStore.dispatch({ type: \"startRequested\", message: { message: sentMessageText, role: \"USER\" } });\n const startToken = chatStore.getState().pendingStartToken as number;\n client\n .startConversation({ agentSpaceKey, text: message, startSignalText, entryPointKey, model, attachments })\n .then((started) => {\n const isAnswerOfPendingStart = chatStore.getState().pendingStartToken === startToken;\n chatStore.dispatch({ type: \"startReceived\", startToken, started });\n if (!isAnswerOfPendingStart) return;\n // A start that reopened its entry point's recent conversation brings no messages: read its newest page.\n if (started.reopenedExisting) {\n fetchOpeningPage(started.conversation.id);\n }\n onNewConversation?.(started.conversation.id);\n })\n .catch((failure: unknown) => {\n chatStore.dispatch({ type: \"startFailed\", error: toAgentsClientErrorOfPort(failure) });\n });\n reportAcceptedSend();\n return true;\n },\n [\n conversation,\n startingNewConversation,\n chatStore,\n client,\n agentSpaceKey,\n sendModelSource,\n onAttachmentsSent,\n onComposerWidgetsSent,\n onMessageSent,\n isConversationRunEnded,\n rejectAsConversationClosed,\n fetchOpeningPage,\n onNewConversation,\n ],\n );\n\n // The opening request's message or start signal (an entry point outside the chat): posted as the first owner\n // message of a cold chat — keyed on the request, not on mount (the chat may already be open), never into an existing\n // conversation and never while a start is in flight. The send is read through a ref so it can't re-fire.\n const handleSendMessageRef = useRef(handleSendMessage);\n handleSendMessageRef.current = handleSendMessage;\n const sentStartRequestRef = useRef<PendingStartRequest | null>(null);\n const loadedConversationId = conversation?.id;\n useEffect(() => {\n const pendingStartRequest = pickPendingStartRequest(pendingStartUserMessage, pendingStartSignalText);\n if (!pendingStartRequest) {\n // Nothing pending — re-arm, so the SAME entry point can be clicked again.\n sentStartRequestRef.current = null;\n return;\n }\n const isReadyToSend = isChatReadyToSendPendingStartRequest({\n pendingStartRequest,\n activeConversationId: conversationId,\n loadedConversationId,\n startingNewConversation,\n alreadySentStartRequest: sentStartRequestRef.current,\n });\n if (!isReadyToSend) {\n return;\n }\n sentStartRequestRef.current = pendingStartRequest;\n // All cleared: a losing signal left behind would make the host drop the conversation this start just opened.\n chatStore.dispatch({\n type: \"openingRequestSet\",\n openingRequest: { userMessage: null, startSignalText: null, entryPointKey: null },\n });\n const entryPointKey = pendingStartEntryPointKey ?? undefined;\n if (pendingStartRequest.kind === \"signal\") {\n handleSendMessageRef.current(\"\", { startSignalText: pendingStartRequest.text, entryPointKey });\n } else {\n handleSendMessageRef.current(pendingStartRequest.text, { entryPointKey });\n }\n }, [\n pendingStartUserMessage,\n pendingStartSignalText,\n pendingStartEntryPointKey,\n conversationId,\n loadedConversationId,\n startingNewConversation,\n chatStore,\n ]);\n\n // The signals besides the owner's messages: a widget's signal, a parked context-only signal, the corrective signal\n // for a dropped widget block, the widget render report (one collector per conversation).\n const { handleInjectSignal, renderReportCollector } = useConversationSignals({\n client,\n conversationId,\n conversation,\n messages,\n runStatus,\n startingNewConversation,\n isConversationRunEnded,\n handleSendMessage,\n rejectAsConversationClosed,\n refetchConversationSummary,\n setScrollToBottomNonce,\n });\n\n // Scroll-to-message and keeping the activity ticker in view; owns the bottom-follow refs of the view body.\n const { followBottomRef, scrollJumpActiveRef } = useConversationScrollJump({\n scrollTarget,\n conversationId,\n conversation,\n messages,\n messagesRef,\n hasMoreOlderRef,\n loadOlder: loadOlderOfLiveConversation,\n chatScrollRef,\n activityTicker,\n });\n\n const widgetCallbacks = useMemo(\n () => ({\n // Message-only for widgets; resolves true only once the send was accepted (a widget locks on it).\n sendMessageToChat: (message: string) => Promise.resolve(handleSendMessage(message, {}) === true),\n injectSignal: handleInjectSignal,\n prefillComposer: (text: string) => conversationMessageInputApiRef.current?.insertTextIntoInput(text),\n attachLibraryFilesToComposer,\n chatAgentSpaceKey: agentSpaceKey,\n conversationId: liveConversationId,\n onOpenConversation,\n onSwitchConversation,\n isOnboardingSetupConversation,\n }),\n [\n handleSendMessage,\n handleInjectSignal,\n attachLibraryFilesToComposer,\n agentSpaceKey,\n liveConversationId,\n onOpenConversation,\n onSwitchConversation,\n isOnboardingSetupConversation,\n ],\n );\n\n // \"What is the agent doing right now\" — from the live messages and the run status.\n const agentActivity = useMemo(() => deriveAgentActivity(messages, runStatus), [messages, runStatus]);\n\n // The store's aiThinking (the launcher reads it) follows the activity the open chat shows.\n useEffect(() => {\n chatStore.dispatch({ type: \"aiThinkingSet\", aiThinking: agentActivity.active });\n }, [agentActivity.active, chatStore]);\n const isTurnRunning = agentActivity.active || runStatus === \"running\";\n useEffect(() => (isTurnRunning ? reportRunningTurn() : undefined), [isTurnRunning]);\n\n // Changes ONLY when a new message arrives (the merge re-allocates the list with identical content) — the clock of\n // the safety poll below.\n const latestMessageSignature = useMemo(() => {\n const list = messages ?? [];\n const last = list[list.length - 1];\n return `${list.length}:${last?.id ?? \"\"}`;\n }, [messages]);\n\n // The safety poll: one read after a full minute without a new message while a turn is in flight — the floor for a\n // dead live path, never the live path itself.\n useEffect(() => {\n if (!liveConversationId || !agentActivity.active) return;\n const intervalId = setInterval(readChangedTailNow, 60_000);\n return () => clearInterval(intervalId);\n }, [liveConversationId, agentActivity.active, readChangedTailNow, latestMessageSignature]);\n\n // A conversation of a scheduled run: its first owner message is the task's seed, shown collapsed — only when the\n // history is loaded down to its start.\n const isScheduleRunConversation = conversation?.initiatorType === \"SCHEDULE\";\n const taskInstructionMessageId = useMemo(() => {\n if (!isScheduleRunConversation || hasMoreOlder || !messages?.length) return undefined;\n return messages.find((message) => message.role === \"USER\")?.id ?? undefined;\n }, [isScheduleRunConversation, hasMoreOlder, messages]);\n\n // With keepActivityHistoryAfterAnswer, each finished turn's lines stand under the message that started the turn.\n const activityHistoryByTurnMessageId = useMemo(() => {\n const historyTurnsByTurnMessageId = new Map<number, ActivityTickerTurn>();\n activityTicker.historyTurns.forEach((historyTurn) => {\n if (historyTurn.turnMessageId !== null) historyTurnsByTurnMessageId.set(historyTurn.turnMessageId, historyTurn);\n });\n return historyTurnsByTurnMessageId;\n }, [activityTicker.historyTurns]);\n\n // The starting ideas: not on a host pinned to one conversation, not beside an open canvas.\n const showsStartingIdeas =\n startingIdeasMarkdown !== undefined &&\n !conversationId &&\n !messages?.length &&\n !isPinnedToSingleConversation &&\n canvas === null;\n const chatMessages = useMemo(() => {\n if (!showsStartingIdeas) return messages;\n const startingIdeasMessage: ChatMessage = { id: -1, role: \"ASSISTANT\", message: startingIdeasMarkdown, fresh: true };\n return [startingIdeasMessage];\n }, [showsStartingIdeas, startingIdeasMarkdown, messages]);\n\n // The turn in flight and the owner's messages queued behind it (the trace's phase, the queued chips).\n // The activity read's turn counts only while that read says its turn runs: after the turn ended it still names the\n // old turn until the next one is known, and the owner's next message would read as queued behind it.\n const namedLiveTurnMessageId = activityRunning ? (activityTurnMessageId ?? null) : null;\n const turnsInFlight = useMemo(\n () => findTurnsInFlight(messages, isTurnRunning, namedLiveTurnMessageId),\n [messages, isTurnRunning, namedLiveTurnMessageId],\n );\n const hasTurnTraceSlot = TurnTrace !== undefined && liveConversationId !== undefined;\n\n // The background jobs of the conversation stand under the trace of the newest turn of the thread, with a Stop each.\n const backgroundJobsAnchorTurnMessageId = useMemo(() => {\n const threadMessages = messages ?? [];\n for (let position = threadMessages.length - 1; position >= 0; position -= 1) {\n const message = threadMessages[position];\n if (message.id != null && isTurnInitiatorMessage(message) && !turnsInFlight.queuedMessages.includes(message)) return message.id;\n }\n return null;\n }, [messages, turnsInFlight]);\n const { stopBackgroundJob: stopBackgroundJobOfClient } = client;\n const runningBackgroundJobsContextValue = useMemo<RunningBackgroundJobsContextValue | null>(() => {\n if (liveConversationId === undefined) return null;\n return {\n conversationId: liveConversationId,\n anchorTurnMessageId: backgroundJobsAnchorTurnMessageId,\n backgroundJobs: runningBackgroundJobs,\n stopBackgroundJob: stopBackgroundJobOfClient\n ? (backgroundJobId: number) => stopBackgroundJobOfClient(liveConversationId, backgroundJobId)\n : undefined,\n refresh: refreshActivity,\n };\n }, [liveConversationId, backgroundJobsAnchorTurnMessageId, runningBackgroundJobs, stopBackgroundJobOfClient, refreshActivity]);\n const showsKeptActivityHistory = keepActivityHistoryAfterAnswer && ActivityHistory !== undefined && TurnTrace === undefined;\n\n // What stands right after a message: the trace of the turn it started (or the kept activity lines of a host without\n // a trace), and the queued mark of an owner message the running turn has not read yet.\n const renderAfterMessage = useCallback(\n (message: ChatMessage) => {\n // A message queued behind the running turn has started no turn yet: no trace, and the queued mark when asked for.\n const isQueued = turnsInFlight.queuedMessages.includes(message);\n const turnTrace =\n TurnTrace && liveConversationId !== undefined && message.id != null && !isQueued && isTurnInitiatorMessage(message) ? (\n <TurnTrace\n conversationId={liveConversationId}\n turnMessageId={message.id}\n phase={message.id === turnsInFlight.liveTurnMessageId ? \"live\" : \"done\"}\n isCompact={isCompact}\n />\n ) : null;\n const activityHistory =\n showsKeptActivityHistory && ActivityHistory ? (\n <ActivityHistory\n turn={typeof message.id === \"number\" ? (activityHistoryByTurnMessageId.get(message.id) ?? null) : null}\n />\n ) : null;\n if (!isQueued) return turnTrace ?? activityHistory;\n return showsQueuedMessages ? <QueuedMessageChip isCompact={isCompact} /> : null;\n },\n [\n ActivityHistory,\n TurnTrace,\n activityHistoryByTurnMessageId,\n isCompact,\n liveConversationId,\n showsKeptActivityHistory,\n showsQueuedMessages,\n turnsInFlight,\n ],\n );\n const rendersAfterMessages = hasTurnTraceSlot || showsKeptActivityHistory || showsQueuedMessages;\n\n const unansweredWidgetMessageId = useMemo(() => findUnansweredWidgetMessageId(messages ?? []), [messages]);\n const renderAssistantAvatar = useCallback(\n (message: ChatMessage) => (AssistantAvatar ? <AssistantAvatar message={message} /> : null),\n [AssistantAvatar],\n );\n\n const activityProps: AgentChatActivityProps = {\n active: agentActivity.active,\n failed: !!error,\n activityTicker,\n isAgentWorkingOnTask: agentActivity.active || activityTicker.phase === \"live\",\n agentSpaceKey,\n activityTiming: resolvedActivityTiming,\n chatStore,\n unansweredWidgetMessageId,\n };\n\n return (\n <RunningBackgroundJobsContext.Provider value={runningBackgroundJobsContextValue}>\n <CanvasViabilityContext.Provider value={canvasViability}>\n <WidgetRenderReportCollectorContext.Provider value={renderReportCollector}>\n <ConversationWidgetProvider\n callbacks={widgetCallbacks}\n chatStore={chatStore}\n hostHasCanvasSurface={hostHasCanvasSurface}\n >\n {/* The tool a page handed over: renders nothing in the chat itself — such a widget lives in the canvas. */}\n <ConversationDeepLinkedWidget\n key={deepLinkedWidget?.mountKey ?? 0}\n widgetName={deepLinkedWidget?.name}\n agentSpaceKey={agentSpaceKey}\n />\n {/* The canvas that was open in this conversation comes back once ITS messages are in. */}\n <CanvasRestoreOnMount conversationId={liveConversationId} messages={messages} />\n {children}\n <div {...chatAreaProps} className={chatAreaClassName} ref={canvasViability.observe}>\n <div className={chatWrapClassName}>\n <ConversationView\n enableCanvasToggle\n boxCanvasBelowTopBar\n disableSplitView={disableSplitView}\n confineTopBlurBandToChatPane={confineTopBlurBandToChatPane}\n progressStepperSlot={progressStepperSlot}\n fileDropHintSlot={fileDropHintSlot}\n enablePinQuestionAndRevealAnswer\n isQuestionPinSuspended={isQuestionPinSuspended}\n scrollRef={chatScrollRef}\n scrollToBottomNonce={scrollToBottomNonce}\n followBottomRef={followBottomRef}\n scrollJumpActiveRef={scrollJumpActiveRef}\n // The host paints the background at its own root; this pane keeps the transparent custom-background mode.\n backgroundPaintedByHost={backgroundPaintedByHost}\n currentCategory={undefined}\n aiPromptExtension={undefined}\n suggestions={undefined}\n messages={chatMessages}\n aiThinking={agentActivity.active}\n // The input never locks while the agent works: a message posted mid-turn is answered in the next turn.\n allowSendWhileAiThinking\n thinkingIndicator={<ThinkingIndicator {...activityProps} />}\n // Only with something to stand there: otherwise every row would carry an empty slot.\n renderAfterMessage={rendersAfterMessages ? renderAfterMessage : undefined}\n renderAssistantAvatar={AssistantAvatar ? renderAssistantAvatar : undefined}\n hideAssistantMeta\n userMessageTheme=\"dark\"\n error={error}\n rateLimitRetryAfterSeconds={rateLimitRetryAfterSeconds}\n onRetryFailedRun={handleRetryFailedRun}\n isDebugMode={false}\n categoriesLoaded={true}\n conversationId={conversationId ?? conversation?.id ?? undefined}\n startingNewConversation={startingNewConversation}\n showMessagesWithoutConversation\n hasMoreOlder={hasMoreOlder}\n loadingOlder={loadingOlder}\n onLoadOlder={loadOlderOfLiveConversation}\n autoScroll={!!conversationId || (messages?.length ?? 0) > 0}\n isCompact={isCompact}\n inputActionsSlot={inputActionsSlot}\n inputActionsSlotStart={inputActionsSlotStart}\n inputTopSlot={inputTopSlot}\n inputSendDisabled={inputSendDisabled}\n inputReplacementSlot={inputReplacementSlot}\n inputBandSlot={inputBandSlot}\n inputPlaceholder={inputPlaceholder}\n inputSendReplacementWhenEmpty={inputSendReplacementWhenEmpty}\n inputGlowUnderlay={inputGlowUnderlay}\n contentOverlaySlot={ContentOverlay ? <ContentOverlay {...activityProps} /> : undefined}\n isContentOverlayShown={isContentOverlayShown}\n outgoingAttachmentImages={outgoingAttachments}\n hostComposerWidgets={hostComposerWidgets}\n taskInstructionMessageId={taskInstructionMessageId}\n isConversationClosed={isConversationRunEnded}\n messageTimes={messageTimes}\n conversationMessageInputApiRef={conversationMessageInputApiRef}\n onSuggestionClick={() => {}}\n onSendMessage={handleSendMessage}\n />\n </div>\n </div>\n </ConversationWidgetProvider>\n </WidgetRenderReportCollectorContext.Provider>\n </CanvasViabilityContext.Provider>\n </RunningBackgroundJobsContext.Provider>\n );\n};\n","import { type ComponentType, type RefObject, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport {\n AgentsConversationClientProvider,\n useOptionalAgentsConversationClient,\n} from \"../../client/AgentsConversationClientContext\";\nimport type { PollingConversationChangeSubscriptionOptions } from \"../../client/polling/createPollingConversationChangeSubscription\";\nimport { withPollingChangeSubscription } from \"../../client/polling/withPollingChangeSubscription\";\nimport { useAgentsActiveAgentSpaceKey } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport { AgentChatActivityHistory } from \"../AgentChatActivityHistory/AgentChatActivityHistory\";\nimport { AgentChatActivityIndicator } from \"../AgentChatActivityIndicator/AgentChatActivityIndicator\";\nimport { ConversationClosedBar } from \"../ConversationClosedBar/ConversationClosedBar\";\nimport {\n type AgentChatActivityHistoryProps,\n type AgentChatActivityProps,\n AgentChatController,\n type AgentChatControllerProps,\n} from \"../controller/AgentChatController\";\nimport type { AgentsChatState } from \"../store/agents-chat-state\";\nimport { type AgentsChatStore, createAgentsChatStore } from \"../store/create-agents-chat-store\";\nimport { useAgentsChatSelector } from \"../store/use-agents-chat-store\";\nimport styles from \"./AgentChat.module.scss\";\n\n/** The controller's inputs that `AgentChat` fills itself when the app leaves them out. */\ntype DefaultedControllerProps = \"chatStore\" | \"client\" | \"agentSpaceKey\" | \"chatScrollRef\" | \"ThinkingIndicator\";\n\nexport interface AgentChatProps extends Omit<AgentChatControllerProps, DefaultedControllerProps> {\n /** This chat instance's state handle. Default: a store of its own, created on mount and dropped on unmount. */\n chatStore?: AgentsChatStore;\n /**\n * The conversation client. Default: the one `AgentsProvider` (or `AgentsConversationClientProvider`) mounted. A client\n * without `subscribeToConversationChanges` gets the polling default (`withPollingChangeSubscription`).\n */\n client?: AgentsConversationClient;\n /**\n * The intervals of the polling default, for a client without a subscription of its own. Read once per client (when\n * the chat wraps it); ignored for a client that brings its own subscription.\n */\n pollingOptions?: PollingConversationChangeSubscriptionOptions;\n /** The key of the agent space new conversations start in. Default: `AgentsEnvironment.useActiveAgentSpaceKey()`, else 0 (no agent space). */\n agentSpaceKey?: number;\n /** The scroll container of the message list, when the app needs it (a scroll-linked background). Default: internal. */\n chatScrollRef?: RefObject<HTMLDivElement | null>;\n /** The agent's activity at the tail of the thread. Default: `AgentChatActivityIndicator` (dots and the ticker line). */\n ThinkingIndicator?: ComponentType<AgentChatActivityProps>;\n /**\n * The frosted band at the top of the message column that blurs what scrolls under a top bar floating over the chat.\n * Shown, it follows the chat pane (`confineTopBlurBandToChatPane` defaults to true then). Default false: the default\n * chat has no floating top bar.\n */\n showsTopBlurBand?: boolean;\n}\n\nconst selectConversation = (state: AgentsChatState) => state.conversation;\n\n/**\n * The agent chat with the package defaults (`./chat`): `<AgentsProvider client={client}><AgentChat\n * /></AgentsProvider>` is a working chat — message list, composer, activity indicator, error card with retry, canvas\n * pane, quick replies, older pages on scroll-up, the closed bar, live updates over the client's own subscription or,\n * without one, the polling default. Every slot and input of `AgentChatController` can still\n * be passed; what is left out gets its default here. Without `conversationId` the chat starts empty, lazy-starts a\n * conversation on the first send and then follows that conversation by itself (`onNewConversation` reports it).\n */\nexport const AgentChat = (props: AgentChatProps) => {\n const {\n chatStore: appChatStore,\n client: appClient,\n pollingOptions,\n agentSpaceKey: appAgentSpaceKey,\n chatScrollRef: appChatScrollRef,\n ThinkingIndicator = AgentChatActivityIndicator,\n ActivityHistory = AgentChatActivityHistory,\n conversationId: appConversationId,\n onNewConversation,\n inputReplacementSlot,\n chatAreaClassName,\n chatWrapClassName = styles.chatWrap,\n showsTopBlurBand = false,\n confineTopBlurBandToChatPane = showsTopBlurBand,\n ...controllerProps\n } = props;\n\n const mountedClient = useOptionalAgentsConversationClient();\n const givenClient = appClient ?? mountedClient;\n // Live updates for a client without push: the polling default, one wrapper per given client. A client with its\n // own subscription is passed through unchanged.\n const client = useMemo(\n () => (givenClient === null ? null : withPollingChangeSubscription(givenClient, pollingOptions)),\n // The options are read once per client: an inline object must not re-create the subscription on every render.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [givenClient],\n );\n const [ownChatStore] = useState(createAgentsChatStore);\n const chatStore = appChatStore ?? ownChatStore;\n const environmentAgentSpaceKey = useAgentsActiveAgentSpaceKey();\n const agentSpaceKey = appAgentSpaceKey ?? environmentAgentSpaceKey ?? 0;\n const ownChatScrollRef = useRef<HTMLDivElement | null>(null);\n const chatScrollRef = appChatScrollRef ?? ownChatScrollRef;\n\n // The conversation a lazy start opened, followed until the app names another one.\n const [startedConversationId, setStartedConversationId] = useState<number | undefined>(undefined);\n useEffect(() => {\n setStartedConversationId(undefined);\n }, [appConversationId]);\n const conversationId = appConversationId ?? startedConversationId;\n const handleNewConversation = useCallback(\n (newConversationId: number) => {\n setStartedConversationId(newConversationId);\n onNewConversation?.(newConversationId);\n },\n [onNewConversation],\n );\n\n // A terminal run state: the server takes no further input, the closed bar stands in the composer's place.\n const conversation = useAgentsChatSelector(chatStore, selectConversation);\n const isConversationRunEnded = conversation?.runState === \"COMPLETED\" || conversation?.runState === \"CANCELLED\";\n\n if (client === null) {\n throw new Error(\"AgentChat has no conversation client: pass `client`, or mount it in <AgentsProvider client={…}>.\");\n }\n // The chat's client (with its live updates) reaches every hook below — the package's and the host's slots\n // (`useAgentsConversationClient`), also when it came as the `client` prop and not from a provider.\n return (\n <AgentsConversationClientProvider client={client}>\n <AgentChatController\n {...controllerProps}\n confineTopBlurBandToChatPane={confineTopBlurBandToChatPane}\n chatStore={chatStore}\n client={client}\n agentSpaceKey={agentSpaceKey}\n conversationId={conversationId}\n onNewConversation={handleNewConversation}\n chatScrollRef={chatScrollRef}\n ThinkingIndicator={ThinkingIndicator}\n ActivityHistory={ActivityHistory}\n inputReplacementSlot={inputReplacementSlot ?? (isConversationRunEnded ? <ConversationClosedBar /> : undefined)}\n chatAreaClassName={\n chatAreaClassName ?? classNames(styles.chatArea, showsTopBlurBand ? styles.chatAreaWithTopBlurBand : undefined)\n }\n chatWrapClassName={chatWrapClassName}\n />\n </AgentsConversationClientProvider>\n );\n};\n\nexport type { AgentChatActivityHistoryProps, AgentChatActivityProps };\n","import type { ReactNode } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { formatTraceClock, readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport { readTraceStateLabel, TraceStateIcon, useTraceNow } from \"./trace-parts\";\nimport type { TraceStepState } from \"./trace-types\";\nimport styles from \"./trace-agents.module.scss\";\n\nexport type BackgroundTaskType = \"subAgent\" | \"schedule\" | \"command\" | \"call\";\n\nexport interface BackgroundTask {\n key: string;\n type: BackgroundTaskType;\n /** What runs (\"#2 Check the BARMER price list\", a command, a schedule's name); data, never translated. */\n title: string;\n /** A quiet second line (\"every Monday 08:00\", a working directory). */\n detail?: string | null;\n state: TraceStepState;\n /** When the task started (a server date-time); a running task's clock ticks from it. */\n startedAt?: string | null;\n /** How long a finished task ran. */\n durationMs?: number | null;\n /** The badge's words when the host names the type itself. */\n typeLabel?: string | null;\n /** The conversation of a sub-agent, for a host that opens it. */\n childConversationId?: number | null;\n}\n\nexport interface BackgroundTasksListProps {\n tasks: BackgroundTask[];\n /** The list's title. Default: \"Background tasks\". */\n title?: string | null;\n /** Opens a task (its conversation, its output); with it every row is a button. */\n onOpenTask?: (task: BackgroundTask) => void;\n /** Controls on the right of the head. */\n headerActions?: ReactNode;\n className?: string;\n}\n\nconst TYPE_LABELS: Readonly<Record<BackgroundTaskType, () => string>> = {\n subAgent: () => translateText(\"Sub-agent\"),\n // The noun; the bare key is the verb of a host's button.\n schedule: () => translateText(\"Schedule\", undefined, \"task-type\"),\n command: () => translateText(\"Command\"),\n call: () => translateText(\"Call\"),\n};\n\n/**\n * What a conversation has running beside its turn: sub-agents, schedules, shell commands in the background and calls,\n * one row each with its state, its duration (a clock while it runs) and a badge for its type.\n */\nexport const BackgroundTasksList = (props: BackgroundTasksListProps) => {\n const { tasks, title, onOpenTask, headerActions, className } = props;\n const format = useTraceFormat();\n const runningCount = tasks.filter((task) => task.state === \"running\").length;\n const now = useTraceNow(runningCount > 0);\n\n const describeTime = (task: BackgroundTask): string => {\n const startedAt = readTraceMoment(task.startedAt);\n if (task.state === \"running\" && startedAt !== null) return formatTraceClock(now - startedAt);\n if (task.durationMs != null) return format.duration(task.durationMs);\n return readTraceStateLabel(task.state);\n };\n\n return (\n <div className={classNames(styles.tasks, className)} data-testid=\"trace-background-tasks\">\n <div className={styles.tasksHead}>\n <span className={styles.tasksTitle}>{title || translateText(\"Background tasks\")}</span>\n {runningCount > 0 ? <span className={styles.quiet}>{translateText(\"%count% running\", { count: format.number(runningCount) })}</span> : null}\n {headerActions}\n </div>\n {tasks.length === 0 ? (\n <div className={styles.tasksEmpty}>{translateText(\"Nothing runs in the background.\")}</div>\n ) : (\n <ul className={styles.tasksList}>\n {tasks.map((task) => {\n const content = (\n <>\n <span className={styles.taskState}>\n <TraceStateIcon state={task.state} />\n </span>\n <span className={styles.taskTexts}>\n <span className={styles.taskTitle} title={task.title}>\n {task.title}\n </span>\n {task.detail ? (\n <span className={styles.taskDetail} title={task.detail}>\n {task.detail}\n </span>\n ) : null}\n </span>\n <span className={styles.weight}>{describeTime(task)}</span>\n <span className={styles.taskType}>{task.typeLabel || TYPE_LABELS[task.type]()}</span>\n </>\n );\n return (\n <li key={task.key} data-task-state={task.state} data-task-type={task.type}>\n {onOpenTask ? (\n <button type=\"button\" className={classNames(styles.task, styles.taskInteractive)} onClick={() => onOpenTask(task)}>\n {content}\n </button>\n ) : (\n <div className={styles.task}>{content}</div>\n )}\n </li>\n );\n })}\n </ul>\n )}\n </div>\n );\n};\n","import { type ReactNode, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { FileChangesSummary } from \"./FileChangesSummary\";\nimport { FileEditBlock, type FileEditBlockProps } from \"./FileEditBlock\";\nimport { readTraceFileChangeLetter, readTraceFileChangeWord, useTraceFormat } from \"./trace-format\";\nimport { Icon } from \"../../provider/components\";\nimport { TraceLink, TraceMountChip, TracePath } from \"./trace-parts\";\nimport type { TraceFileChange, TraceLinkComponent } from \"./trace-types\";\nimport styles from \"./trace-files.module.scss\";\n\nexport interface ChangedFilesPaneProps\n extends Pick<\n FileEditBlockProps,\n \"describeMount\" | \"maxLines\" | \"isNarrow\" | \"diffModesBelowHead\" | \"defaultDiffMode\" | \"onLoadFullDiff\" | \"onOpenInViewer\" | \"describeFileType\"\n > {\n /** The changed files, in the order they are listed. */\n fileChanges: TraceFileChange[];\n /**\n * Controls the selected file (its position in `fileChanges`); without it the pane keeps its own, starting at\n * `defaultSelectedIndex`.\n */\n selectedIndex?: number;\n onSelectedIndexChange?: (selectedIndex: number) => void;\n /** The file selected at first when the pane keeps the selection itself. Default 0. */\n defaultSelectedIndex?: number;\n /** A title before the summary in the pane's head (\"Turn 3\"). */\n title?: ReactNode;\n /** Controls on the right of the pane's head (a link to the drive). */\n headerActions?: ReactNode;\n /** A small picture of a changed file, for the preview card of a binary file. */\n renderThumbnail?: (fileChange: TraceFileChange) => ReactNode;\n /** Whether the viewer of `onOpenInViewer` can show this file; \"open\" is offered only then. Default: every file. */\n canOpenInViewer?: (fileChange: TraceFileChange) => boolean;\n /** The route of the screen that shows a changed file in the conversation's sandbox; each row and the file's block link to it. Null: no link. */\n buildSandboxHref?: (fileChange: TraceFileChange) => string | null;\n /** The host's link (an in-app route); a plain anchor otherwise. */\n linkComponent?: TraceLinkComponent;\n className?: string;\n}\n\nconst OPERATION_CLASS_NAMES: Readonly<Record<string, string | undefined>> = {\n ADDED: styles.operationAdded,\n MODIFIED: styles.operationModified,\n DELETED: styles.operationDeleted,\n RENAMED: styles.operationRenamed,\n};\n\n/**\n * The files a turn or a conversation changed: a list with the letter of each operation (A, M, D, R), the path, the\n * mount and the size of the change, and below it the file edit block of the selected file.\n */\nexport const ChangedFilesPane = (props: ChangedFilesPaneProps) => {\n const {\n fileChanges,\n selectedIndex,\n onSelectedIndexChange,\n defaultSelectedIndex = 0,\n title,\n headerActions,\n renderThumbnail,\n canOpenInViewer,\n buildSandboxHref,\n linkComponent,\n className,\n describeMount,\n onOpenInViewer,\n ...fileEditProps\n } = props;\n const format = useTraceFormat();\n const [ownSelectedIndex, setOwnSelectedIndex] = useState(defaultSelectedIndex);\n // A file changed twice is one file of the summary, as in the figures of a turn.\n const fileCount = new Set(fileChanges.map((fileChange) => `${fileChange.mountKind ?? \"\"}:${fileChange.mountName ?? \"\"}:${fileChange.path}`)).size;\n const shownSelectedIndex = Math.min(Math.max(selectedIndex ?? ownSelectedIndex, 0), Math.max(fileChanges.length - 1, 0));\n const selectedFileChange = fileChanges[shownSelectedIndex];\n const linesAdded = fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesAdded ?? 0), 0);\n const linesRemoved = fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesRemoved ?? 0), 0);\n\n const select = (index: number) => {\n setOwnSelectedIndex(index);\n onSelectedIndexChange?.(index);\n };\n const describeExtra = (fileChange: TraceFileChange): ReactNode => {\n if (fileChange.linesAdded != null || fileChange.linesRemoved != null) {\n return (\n <>\n <span className={styles.added}>+{format.number(fileChange.linesAdded ?? 0)}</span>{\" \"}\n <span className={styles.removed}>−{format.number(fileChange.linesRemoved ?? 0)}</span>\n </>\n );\n }\n if (fileChange.changeType === \"RENAMED\" && fileChange.previousPath) return `← ${fileChange.previousPath.split(\"/\").pop() ?? \"\"}`;\n if (fileChange.sizeAfter != null) return format.bytes(fileChange.sizeAfter);\n return null;\n };\n\n return (\n <div className={classNames(styles.pane, className)} data-testid=\"trace-changed-files\">\n <div className={styles.paneHead}>\n {title !== undefined && title !== null ? <span className={styles.paneTitle}>{title}</span> : null}\n <FileChangesSummary fileCount={fileCount} linesAdded={linesAdded} linesRemoved={linesRemoved} />\n <span className={styles.grow} />\n {headerActions}\n </div>\n {fileChanges.length === 0 ? (\n <div className={styles.paneEmpty}>{translateText(\"No files were changed.\")}</div>\n ) : (\n <ul className={styles.paneList}>\n {fileChanges.map((fileChange, index) => {\n const changeType = fileChange.changeType ?? \"MODIFIED\";\n const extra = describeExtra(fileChange);\n const sandboxHref = buildSandboxHref?.(fileChange) ?? null;\n return (\n <li key={`${fileChange.id ?? index}:${fileChange.path}`} className={sandboxHref !== null ? styles.paneFileRow : undefined}>\n <button\n type=\"button\"\n className={classNames(styles.paneFile, index === shownSelectedIndex && styles.paneFileOn)}\n aria-current={index === shownSelectedIndex ? \"true\" : undefined}\n onClick={() => select(index)}\n >\n <span\n className={classNames(styles.operation, styles.operationLetter, OPERATION_CLASS_NAMES[changeType])}\n title={readTraceFileChangeWord(changeType)}\n aria-label={readTraceFileChangeWord(changeType)}\n >\n {readTraceFileChangeLetter(changeType)}\n </span>\n <TracePath path={fileChange.path} isMonospaced isRemoved={changeType === \"DELETED\"} />\n <span className={styles.grow} />\n <TraceMountChip\n mountKind={fileChange.mountKind}\n mountName={fileChange.mountName}\n driveSpaceId={fileChange.driveSpaceId}\n describeMount={describeMount}\n />\n {extra !== null ? <span className={styles.paneFileExtra}>{extra}</span> : null}\n </button>\n {sandboxHref !== null ? (\n // Beside the row's button, never inside it: a link in a button is no valid markup.\n <TraceLink href={sandboxHref} linkComponent={linkComponent} className={styles.paneFileLink} title={translateText(\"Show this file in the sandbox\")}>\n <Icon name=\"terminal\" pixelSize={13} />\n </TraceLink>\n ) : null}\n </li>\n );\n })}\n </ul>\n )}\n {selectedFileChange ? (\n <div className={styles.paneDetail}>\n <FileEditBlock\n {...fileEditProps}\n fileChange={selectedFileChange}\n describeMount={describeMount}\n onOpenInViewer={(canOpenInViewer?.(selectedFileChange) ?? true) ? onOpenInViewer : undefined}\n sandboxHref={buildSandboxHref?.(selectedFileChange) ?? null}\n linkComponent={linkComponent}\n thumbnail={renderThumbnail?.(selectedFileChange)}\n />\n </div>\n ) : null}\n </div>\n );\n};\n","import { type ReactNode, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon, type AgentsIconName } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport stepStyles from \"./trace-steps.module.scss\";\nimport styles from \"./trace-agents.module.scss\";\n\nexport interface ChangeSetChange {\n /** A stable key; default: the row's position. */\n key?: string;\n /** The field's name, in the reader's language. */\n label: string;\n /** The value before; null or absent for a field that had none. */\n before?: string | null;\n /** The value after; null or absent for a field that was cleared. */\n after?: string | null;\n}\n\nexport interface ChangeSetCardProps {\n /** What was changed (\"Ride changed\"), in the reader's language. */\n title: string;\n icon?: AgentsIconName;\n /** The chip of the changed record (`EntityChip`). */\n entity?: ReactNode;\n changes: ChangeSetChange[];\n /** A quiet line under the rows (who changed it, when). */\n note?: ReactNode;\n /** Takes the change back; without it no Undo button. A promise keeps the button disabled until it settles. */\n onUndo?: () => void | Promise<void>;\n /** The change was taken back: the card says so and offers no Undo. */\n isUndone?: boolean;\n /** Further controls beside Undo (a link to the record's history). */\n actions?: ReactNode;\n className?: string;\n}\n\n/**\n * What a turn changed on one record: a row per field with the old value struck through and the new one highlighted,\n * and an Undo button when the host can take the change back.\n */\nexport const ChangeSetCard = (props: ChangeSetCardProps) => {\n const { title, icon = \"toolWrite\", entity, changes, note, onUndo, isUndone = false, actions, className } = props;\n const [isUndoPending, setIsUndoPending] = useState(false);\n const handleUndo = async () => {\n if (!onUndo) return;\n setIsUndoPending(true);\n try {\n await onUndo();\n } finally {\n setIsUndoPending(false);\n }\n };\n return (\n <div className={classNames(styles.changeSet, isUndone && styles.changeSetPending, className)} data-testid=\"trace-change-set\" data-undone={isUndone || undefined}>\n <div className={styles.changeSetHead}>\n <Icon name={icon} pixelSize={15} className={stepStyles.rowIcon} />\n <span className={styles.changeSetTitle}>{title}</span>\n {entity}\n <span className={styles.changeSetGrow} />\n {isUndone ? <span className={stepStyles.badge}>{translateText(\"Undone\")}</span> : null}\n </div>\n <dl className={styles.changes}>\n {changes.map((change, index) => {\n const hasBefore = change.before != null && change.before !== \"\";\n const hasAfter = change.after != null && change.after !== \"\";\n return (\n <div key={change.key ?? index} style={{ display: \"contents\" }} data-testid=\"trace-change\">\n <dt className={styles.changeName}>{change.label}</dt>\n <dd className={classNames(styles.changeValue, hasBefore ? styles.changeOld : styles.changeUnchanged)}>\n {hasBefore ? (\n <>\n <span className={stepStyles.visuallyHidden}>{translateText(\"Before:\")} </span>\n {change.before}\n </>\n ) : (\n \"—\"\n )}\n </dd>\n <dd className={classNames(styles.changeValue, styles.changeArrow)} aria-hidden>\n →\n </dd>\n <dd className={classNames(styles.changeValue, hasAfter ? styles.changeNew : styles.changeUnchanged)}>\n {hasAfter ? (\n <>\n <span className={stepStyles.visuallyHidden}>{translateText(\"After:\")} </span>\n {change.after}\n </>\n ) : (\n \"—\"\n )}\n </dd>\n </div>\n );\n })}\n </dl>\n {note || onUndo || actions ? (\n <div className={styles.changeSetFoot}>\n {note ? <span className={styles.changeSetNote}>{note}</span> : null}\n <span className={styles.changeSetGrow} />\n {actions}\n {onUndo && !isUndone ? (\n <button type=\"button\" className={stepStyles.stopButton} disabled={isUndoPending} onClick={() => void handleUndo()}>\n <Icon name=\"undo\" pixelSize={13} />\n {translateText(\"Undo\")}\n </button>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n};\n","import type { ReactNode } from \"react\";\nimport type { ConversationTraceRecordChangeOperation } from \"../../contract/conversation-trace\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport { ChangeSetCard } from \"./ChangeSetCard\";\nimport { EntityChip } from \"./EntityChip\";\nimport type { TraceChangedRecord } from \"./trace-collect\";\nimport { readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport { readTraceStateLabel, TraceLink } from \"./trace-parts\";\nimport type { TraceEntityDescription, TraceEntityReference, TraceLinkComponent } from \"./trace-types\";\nimport styles from \"./trace-pane.module.scss\";\n\nexport interface ChangedRecordsListProps {\n /** The tool calls that changed or deleted records, in the order they are listed (`collectTraceChangedRecords`). */\n records: TraceChangedRecord[];\n /** The list's title. Default: \"Records changed\". */\n title?: string | null;\n /** The chip of a record a call names; null leaves the reference out. Default: no chips. */\n describeEntity?: (reference: TraceEntityReference) => TraceEntityDescription | null;\n /** The route of a record, for a host that only links (`describeEntity` wins when it names an `href`). */\n buildEntityHref?: (argumentName: string, id: number) => string | null;\n /** The route of the call's step in the host's analysis view; null for none. With it a row offers \"Open in analysis\". */\n buildStepHref?: (record: TraceChangedRecord) => string | null;\n /** The host's link (an in-app route); a plain anchor otherwise. */\n linkComponent?: TraceLinkComponent;\n /** A quiet line under the list. */\n note?: ReactNode;\n /** A changed record in words (`Support directive 41`) for the before → after card; null keeps table and id. */\n describeRecord?: (tableName: string, recordId: number | null) => string | null;\n className?: string;\n}\n\n/** `validUntil` reads \"valid until\", `isActive` \"is active\": a stored column name in words. */\nexport const describeChangedFieldName = (fieldName: string): string =>\n fieldName\n .replace(/_/g, \" \")\n .replace(/([a-z0-9])([A-Z])/g, \"$1 $2\")\n .replace(/([A-Z]+)([A-Z][a-z])/g, \"$1 $2\")\n .toLowerCase()\n .trim();\n\n/** `SupportDirectives` and 41 read \"Support directives 41\": a changed record without the host's words. */\nexport const describeChangedRecord = (tableName: string, recordId: number | null): string => {\n const words = describeChangedFieldName(tableName);\n const label = words.charAt(0).toUpperCase() + words.slice(1);\n return recordId === null ? label : `${label} ${recordId}`;\n};\n\nconst readRecordOperationLabel = (operation: ConversationTraceRecordChangeOperation): string => {\n if (operation === \"CREATED\") return translateText(\"created\", undefined, \"record-change\");\n if (operation === \"DELETED\") return translateText(\"deleted\", undefined, \"record-change\");\n return translateText(\"changed\", undefined, \"record-change\");\n};\n\n/**\n * The records a conversation changed, as far as its trace knows them: one row per tool call that changes or deletes\n * data, with the tool in words, when it ran, the chips of the records its arguments name and a link to its step. A\n * call that failed or still waits for the owner's approval is marked, since it changed nothing (yet). Under a call\n * the server captured writes for, its change set lists every record with each field before → after\n * ({@link ChangeSetCard}); a call stored before the capture shows the row only. No undo is offered.\n */\nexport const ChangedRecordsList = (props: ChangedRecordsListProps) => {\n const { records, title, describeEntity, buildEntityHref, buildStepHref, linkComponent, note, describeRecord, className } = props;\n const format = useTraceFormat();\n if (records.length === 0) return null;\n return (\n <div className={classNames(styles.records, className)} data-testid=\"trace-changed-records\">\n <div className={styles.head}>\n <span className={styles.title}>{title || translateText(\"Records changed\")}</span>\n <span className={styles.grow} />\n <span className={styles.quiet}>{format.number(records.length)}</span>\n </div>\n <ul className={styles.recordsList}>\n {records.map((record) => {\n const startedAt = readTraceMoment(record.startedAt);\n const words = record.toolNameInWords || record.toolName || translateText(\"Used a tool\");\n const stepHref = buildStepHref?.(record) ?? null;\n const chips = record.entityReferences\n .map((reference) => {\n const description = describeEntity?.(reference) ?? null;\n if (description === null) return null;\n return (\n <EntityChip\n key={`${reference.argumentName}:${reference.id}`}\n label={description.label}\n icon={description.icon}\n href={description.href}\n argumentName={reference.argumentName}\n id={reference.id}\n buildEntityHref={buildEntityHref}\n linkComponent={linkComponent}\n />\n );\n })\n .filter((chip) => chip !== null);\n const isQuiet = record.state === \"failed\" || record.state === \"waiting\" || record.state === \"cancelled\";\n return (\n <li\n key={record.key}\n className={classNames(styles.record, isQuiet && styles.recordQuiet)}\n data-record-effect={record.effect}\n data-record-state={record.state}\n >\n <div className={styles.recordHead}>\n <Icon name={record.effect === \"DELETE\" ? \"trash\" : \"toolWrite\"} pixelSize={14} className={styles.recordIcon} />\n <span className={styles.recordTitle} title={record.toolName ?? undefined}>\n {words}\n </span>\n {record.effect === \"DELETE\" ? (\n <span className={classNames(styles.mark, styles.markDelete)}>{translateText(\"deletes data\", undefined, \"tool-effect\")}</span>\n ) : null}\n {record.state === \"waiting\" ? (\n <span className={classNames(styles.mark, styles.markWarning)}>{translateText(\"waits for approval\")}</span>\n ) : null}\n {record.state === \"failed\" ? <span className={classNames(styles.mark, styles.markDanger)}>{readTraceStateLabel(\"failed\")}</span> : null}\n {record.state === \"running\" || record.state === \"cancelled\" ? <span className={styles.mark}>{readTraceStateLabel(record.state)}</span> : null}\n <span className={styles.grow} />\n {startedAt !== null ? <span className={styles.recordTime}>{format.time(startedAt)}</span> : null}\n </div>\n {record.line && record.line !== words ? <div className={styles.recordLine}>{record.line}</div> : null}\n {record.recordChanges.length > 0 || record.omittedRecordChangeCount > 0 ? (\n <div className={styles.recordChangeSets}>\n {record.recordChanges.map((recordChange, recordIndex) => (\n <ChangeSetCard\n key={`${recordChange.tableName}:${recordChange.recordId ?? `new-${recordIndex}`}`}\n title={describeRecord?.(recordChange.tableName, recordChange.recordId) ?? describeChangedRecord(recordChange.tableName, recordChange.recordId)}\n icon={recordChange.operation === \"DELETED\" ? \"trash\" : \"toolWrite\"}\n entity={\n <span\n className={classNames(\n styles.mark,\n recordChange.operation === \"CREATED\" && styles.markCreated,\n recordChange.operation === \"DELETED\" && styles.markDelete,\n )}\n >\n {readRecordOperationLabel(recordChange.operation)}\n </span>\n }\n changes={recordChange.fieldChanges.map((fieldChange) => ({\n key: fieldChange.fieldName,\n label: describeChangedFieldName(fieldChange.fieldName),\n before: fieldChange.before,\n after: fieldChange.after,\n }))}\n note={\n recordChange.omittedFieldCount > 0\n ? translateText(\"%count% more fields\", { count: format.number(recordChange.omittedFieldCount) })\n : undefined\n }\n />\n ))}\n {record.omittedRecordChangeCount > 0 ? (\n <span className={styles.recordLine}>\n {translateText(\"%count% more records\", { count: format.number(record.omittedRecordChangeCount) })}\n </span>\n ) : null}\n </div>\n ) : null}\n {chips.length > 0 || stepHref !== null ? (\n <div className={styles.recordFoot}>\n {chips}\n {stepHref !== null ? (\n <TraceLink href={stepHref} linkComponent={linkComponent} className={styles.recordLink} title={translateText(\"Open this step in the analysis\")}>\n <Icon name=\"external\" pixelSize={12} />\n {translateText(\"Open in analysis\")}\n </TraceLink>\n ) : null}\n </div>\n ) : null}\n </li>\n );\n })}\n </ul>\n {note ? <p className={styles.note}>{note}</p> : null}\n </div>\n );\n};\n","import { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { useTraceFormat } from \"./trace-format\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface ContextRingProps {\n /** The share of the context window in use, 0–100. */\n percent: number;\n /** Tokens in the context and the window's size, named in the label when given. */\n usedTokens?: number | null;\n contextWindowTokens?: number | null;\n /** The figure beside the ring (\"71 %\"). Default true. */\n showsPercent?: boolean;\n /** Edge length of the ring in px. Default 26. */\n size?: number;\n /** Opens what fills the context; with it the ring is a button. */\n onClick?: () => void;\n className?: string;\n}\n\n/**\n * How full the model's context window is, as a ring with its percentage. It names itself to assistive technology\n * (\"Context 71 % full\"), turns amber from 80 % and red from 95 %, and is a button when a click handler is given.\n */\nexport const ContextRing = (props: ContextRingProps) => {\n const { percent, usedTokens, contextWindowTokens, showsPercent = true, size = 26, onClick, className } = props;\n const format = useTraceFormat();\n const shownPercent = Math.round(Math.min(100, Math.max(0, Number.isFinite(percent) ? percent : 0)));\n const strokeWidth = Math.max(3, Math.round(size / 7));\n const radius = (size - strokeWidth) / 2;\n const circumference = 2 * Math.PI * radius;\n const label =\n usedTokens != null && contextWindowTokens != null\n ? translateText(\"Context %percent% % full (%used% of %total% tokens)\", {\n percent: shownPercent,\n used: format.count(usedTokens),\n total: format.count(contextWindowTokens),\n })\n : translateText(\"Context %percent% % full\", { percent: shownPercent });\n const content = (\n <>\n <svg className={styles.ringSvg} width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden>\n <circle className={styles.ringTrack} cx={size / 2} cy={size / 2} r={radius} strokeWidth={strokeWidth} />\n <circle\n className={classNames(styles.ringArc, shownPercent >= 95 ? styles.ringArcFull : shownPercent >= 80 && styles.ringArcHigh)}\n cx={size / 2}\n cy={size / 2}\n r={radius}\n strokeWidth={strokeWidth}\n strokeDasharray={`${(circumference * shownPercent) / 100} ${circumference}`}\n />\n </svg>\n {showsPercent ? <span aria-hidden>{shownPercent} %</span> : null}\n </>\n );\n if (onClick) {\n return (\n <button\n type=\"button\"\n className={classNames(styles.ring, styles.ringInteractive, className)}\n aria-label={label}\n title={label}\n onClick={onClick}\n data-testid=\"trace-context-ring\"\n >\n {content}\n </button>\n );\n }\n return (\n <span className={classNames(styles.ring, className)} role=\"img\" aria-label={label} title={label} data-testid=\"trace-context-ring\">\n {content}\n </span>\n );\n};\n","import type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { ConversationTraceLevel, ConversationTurnTrace, ConversationTurnTraces } from \"../../contract/conversation-trace\";\n\n/**\n * The loader of one conversation's turn trace: every turn trace a screen shows reads through it, so the turns on screen\n * share their requests. It holds the turns it read (by turn number), reads the newest window first, walks back one\n * window at a time while a wanted turn is older than what it holds, follows a running turn with reads of the changed\n * turns only, and reads again when the conversation changed. One request runs at a time; a failed read is tried again\n * at the next change, never in a loop, and never throws into the component that asked.\n */\n\n/** The part of the conversation client the loader reads through. */\nexport type ConversationTraceClient = Pick<AgentsConversationClient, \"getTurnTraces\">;\n\nexport interface ConversationTraceLoaderOptions {\n /** The level asked for; the server answers at most the level the reader is allowed. Default `STEPS`. */\n level?: ConversationTraceLevel;\n /** Turns of one read. Default 20 (the server's default window). */\n pageSize?: number;\n}\n\n/** What the loader holds of a conversation at one moment; a new object after every change. */\nexport interface ConversationTraceState {\n /** The turns read so far, oldest first; without gaps from the oldest one read to the newest. */\n turns: ConversationTurnTrace[];\n /** `idle` before the first read, `loading` while that read runs, `ready` after it, `failed` when it failed. */\n status: \"idle\" | \"loading\" | \"ready\" | \"failed\";\n /** The level the server answered; null before the first answer. */\n level: ConversationTraceLevel | null;\n /** A turn runs in the conversation, as the newest read saw it. */\n isRunLive: boolean;\n /** Turns older than the oldest one read exist, as the page read that holds the oldest turn said. */\n hasOlderTurns: boolean;\n /** Turns of the whole conversation, as the newest read counted them; null before the first answer. */\n totalTurnCount: number | null;\n}\n\nconst DEFAULT_PAGE_SIZE = 20;\nconst DEFAULT_POLL_INTERVAL_MS = 1500;\nconst EMPTY_STATE: ConversationTraceState = { turns: [], status: \"idle\", level: null, isRunLive: false, hasOlderTurns: false, totalTurnCount: null };\n\ntype TraceRead = { kind: \"newest\" } | { kind: \"follow\"; afterMessageIndex: number } | { kind: \"older\"; fromTurnNumber: number; limit: number };\n\nexport class ConversationTraceLoader {\n protected readonly level: ConversationTraceLevel;\n protected readonly pageSize: number;\n protected readonly turnsByNumber = new Map<number, ConversationTurnTrace>();\n protected readonly listeners = new Set<() => void>();\n /** The turns a component waits for, by the id of the message that started them, with how many wait. */\n protected readonly wantedTurnMessageIds = new Map<number, number>();\n /** The turns that run right now, with how many components follow each. */\n protected readonly liveTurnMessageIds = new Map<number, number>();\n /** Turns that ended since the last follow read: that read returns them whole once more. */\n protected readonly endedTurnMessageIds = new Set<number>();\n /** The revision at which a wanted turn newer than everything held was last looked for. */\n protected readonly lookedForAtRevision = new Map<number, number>();\n protected state: ConversationTraceState = EMPTY_STATE;\n protected newestMessageIndex: number | null = null;\n protected hasReadNewest = false;\n protected wantsNewest = false;\n protected needsFollowRead = false;\n protected isReading = false;\n protected isPumpScheduled = false;\n /** Counts what could have changed the trace: a changed conversation, a poll tick. A failed read waits for the next. */\n protected revision = 0;\n protected failedAtRevision: number | null = null;\n protected conversationRevision: string | number | null = null;\n protected followerCount = 0;\n protected pollTimer: ReturnType<typeof setInterval> | null = null;\n protected pollIntervalMs = DEFAULT_POLL_INTERVAL_MS;\n\n constructor(\n protected readonly client: ConversationTraceClient,\n protected readonly conversationId: number,\n options: ConversationTraceLoaderOptions = {},\n ) {\n this.level = options.level ?? \"STEPS\";\n this.pageSize = Math.max(1, options.pageSize ?? DEFAULT_PAGE_SIZE);\n }\n\n subscribe = (listener: () => void): (() => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n getState = (): ConversationTraceState => this.state;\n\n /** The turn a message started, when it was read. */\n findTurn(turnMessageId: number): ConversationTurnTrace | null {\n for (const turn of this.turnsByNumber.values()) {\n if (turn.turnMessageId === turnMessageId) return turn;\n }\n return null;\n }\n\n /**\n * A component shows the turn of this message: the loader reads until it holds the turn or knows the message started\n * none. Returns the release (the component is gone).\n */\n requestTurn(turnMessageId: number): () => void {\n this.wantedTurnMessageIds.set(turnMessageId, (this.wantedTurnMessageIds.get(turnMessageId) ?? 0) + 1);\n this.schedulePump();\n return () => {\n const remaining = (this.wantedTurnMessageIds.get(turnMessageId) ?? 1) - 1;\n if (remaining > 0) this.wantedTurnMessageIds.set(turnMessageId, remaining);\n else {\n this.wantedTurnMessageIds.delete(turnMessageId);\n this.lookedForAtRevision.delete(turnMessageId);\n }\n };\n }\n\n /** A component shows the conversation's newest turns (a pane, a sub-agent's trace): the newest window is read. */\n requestNewestTurns(): void {\n this.wantsNewest = true;\n this.schedulePump();\n }\n\n /**\n * The turn of this message runs: the loader follows it with a read of the changed turns every `pollIntervalMs` until\n * the returned function is called (the turn ended), then reads it once more for its final figures.\n */\n followLiveTurn(turnMessageId: number, pollIntervalMs: number = DEFAULT_POLL_INTERVAL_MS): () => void {\n this.liveTurnMessageIds.set(turnMessageId, (this.liveTurnMessageIds.get(turnMessageId) ?? 0) + 1);\n const stopFollowing = this.followChanges(pollIntervalMs);\n return () => {\n const remaining = (this.liveTurnMessageIds.get(turnMessageId) ?? 1) - 1;\n if (remaining > 0) this.liveTurnMessageIds.set(turnMessageId, remaining);\n else {\n this.liveTurnMessageIds.delete(turnMessageId);\n this.endedTurnMessageIds.add(turnMessageId);\n }\n stopFollowing();\n };\n }\n\n /**\n * Reads the changed turns every `pollIntervalMs` until the returned function is called, then once more: for a\n * component that shows a conversation while it runs without naming a turn (a sub-agent's trace).\n */\n followChanges(pollIntervalMs: number = DEFAULT_POLL_INTERVAL_MS): () => void {\n this.followerCount += 1;\n this.pollIntervalMs = Math.max(250, pollIntervalMs);\n this.startPolling();\n this.noteChange();\n let isReleased = false;\n return () => {\n if (isReleased) return;\n isReleased = true;\n this.followerCount -= 1;\n if (this.followerCount <= 0) this.stopPolling();\n this.noteChange();\n };\n }\n\n /**\n * Tells the loader where the conversation stands (a value that changes with every new message, e.g. its message\n * count and newest id). A changed value makes the loader read the changed turns.\n */\n noteConversationRevision(conversationRevision: string | number): void {\n if (this.conversationRevision === conversationRevision) return;\n const isFirst = this.conversationRevision === null;\n this.conversationRevision = conversationRevision;\n // The first value only names where the conversation stood when its first read started.\n if (!isFirst) this.noteChange();\n }\n\n /** Reads the changed turns now (the stop of a turn was accepted, a diff was stored). */\n refresh(): void {\n this.noteChange();\n }\n\n /** Stops the loader's timer; the turns it holds stay readable. */\n dispose(): void {\n this.stopPolling();\n this.listeners.clear();\n }\n\n protected noteChange(): void {\n this.revision += 1;\n if (this.hasReadNewest) this.needsFollowRead = true;\n this.schedulePump();\n }\n\n protected startPolling(): void {\n this.stopPolling();\n this.pollTimer = setInterval(() => this.noteChange(), this.pollIntervalMs);\n }\n\n protected stopPolling(): void {\n if (this.pollTimer !== null) clearInterval(this.pollTimer);\n this.pollTimer = null;\n }\n\n /** Every request of one tick becomes one decision: the components of a thread mount together. */\n protected schedulePump(): void {\n if (this.isPumpScheduled) return;\n this.isPumpScheduled = true;\n queueMicrotask(() => {\n this.isPumpScheduled = false;\n this.pump();\n });\n }\n\n protected pump(): void {\n if (this.isReading) return;\n const read = this.chooseNextRead();\n if (read === null) return;\n this.isReading = true;\n if (!this.hasReadNewest) this.publish({ status: \"loading\" });\n const revisionAtStart = this.revision;\n void this.runRead(read)\n .then(\n (traces) => {\n this.failedAtRevision = null;\n this.acceptRead(read, traces);\n },\n () => {\n // The trace is an addition to the thread: a failed read shows nothing and waits for the next change.\n this.failedAtRevision = revisionAtStart;\n if (read.kind === \"follow\") this.needsFollowRead = false;\n if (!this.hasReadNewest) this.publish({ status: \"failed\" });\n },\n )\n .finally(() => {\n this.isReading = false;\n this.pump();\n });\n }\n\n protected runRead(read: TraceRead): Promise<ConversationTurnTraces> {\n const getTurnTraces = this.client.getTurnTraces;\n if (!getTurnTraces) return Promise.reject(new Error(\"The conversation client reads no turn traces.\"));\n if (read.kind === \"newest\") return getTurnTraces(this.conversationId, { level: this.level, limit: this.pageSize });\n if (read.kind === \"follow\") return getTurnTraces(this.conversationId, { level: this.level, afterMessageIndex: read.afterMessageIndex });\n return getTurnTraces(this.conversationId, { level: this.level, fromTurnNumber: read.fromTurnNumber, limit: read.limit });\n }\n\n /** The one read to run next, or null when the loader holds everything that is wanted. */\n protected chooseNextRead(): TraceRead | null {\n // A failed read is tried again only after something changed.\n if (this.failedAtRevision !== null && this.failedAtRevision === this.revision) return null;\n const hasWishes = this.wantedTurnMessageIds.size > 0 || this.wantsNewest || this.followerCount > 0;\n if (!this.hasReadNewest) return hasWishes ? { kind: \"newest\" } : null;\n\n const sortedTurns = this.state.turns;\n const initiatorIds = sortedTurns.map((turn) => turn.turnMessageId).filter((id): id is number => id !== null);\n const newestInitiatorId = initiatorIds.length > 0 ? initiatorIds[initiatorIds.length - 1] : null;\n const oldestInitiatorId = initiatorIds.length > 0 ? initiatorIds[0] : null;\n const oldestTurnNumber = sortedTurns.length > 0 ? sortedTurns[0].turnNumber : null;\n\n let smallestMissingOlderId: number | null = null;\n for (const turnMessageId of this.wantedTurnMessageIds.keys()) {\n if (this.findTurn(turnMessageId) !== null) continue;\n if (newestInitiatorId === null || turnMessageId > newestInitiatorId) {\n // Newer than everything held: its turn may have started since the last read. Looked for once per change.\n if (this.lookedForAtRevision.get(turnMessageId) !== this.revision) {\n this.lookedForAtRevision.set(turnMessageId, this.revision);\n this.needsFollowRead = true;\n }\n } else if (oldestInitiatorId !== null && turnMessageId < oldestInitiatorId && this.state.hasOlderTurns) {\n smallestMissingOlderId = smallestMissingOlderId === null ? turnMessageId : Math.min(smallestMissingOlderId, turnMessageId);\n }\n // A message between two held turns started none.\n }\n\n if (this.needsFollowRead) {\n const afterMessageIndex = this.readFollowPosition();\n return afterMessageIndex === null ? { kind: \"newest\" } : { kind: \"follow\", afterMessageIndex };\n }\n if (smallestMissingOlderId !== null && oldestTurnNumber !== null && oldestTurnNumber > 1) {\n const fromTurnNumber = Math.max(1, oldestTurnNumber - this.pageSize);\n return { kind: \"older\", fromTurnNumber, limit: oldestTurnNumber - fromTurnNumber };\n }\n return null;\n }\n\n /**\n * The position a follow read asks after: the newest row read, moved back before the first row of every turn that\n * runs or just ended, so those turns come back whole (a step's status changes without a new row).\n */\n protected readFollowPosition(): number | null {\n if (this.newestMessageIndex === null) return null;\n let position = this.newestMessageIndex;\n for (const turn of this.turnsByNumber.values()) {\n const isFollowed =\n turn.isRunning ||\n (turn.turnMessageId !== null && (this.liveTurnMessageIds.has(turn.turnMessageId) || this.endedTurnMessageIds.has(turn.turnMessageId)));\n if (isFollowed && turn.turnMessageIndex !== null) position = Math.min(position, turn.turnMessageIndex - 1);\n }\n return position;\n }\n\n /**\n * Whether turns older than the held ones exist after `traces` was read. Only a page read knows (the newest page, a\n * page of older turns), and only the page that reaches back at least as far as the oldest held turn decides; a\n * follow-up read is no page and leaves the fact as it is.\n */\n protected readHasOlderTurns(read: TraceRead, traces: ConversationTurnTraces): boolean {\n if (read.kind === \"follow\") return this.state.hasOlderTurns;\n const oldestHeldTurnNumber = this.state.turns.length > 0 ? this.state.turns[0].turnNumber : null;\n const firstTurnNumberOfPage = traces.firstTurnNumber ?? (traces.turns.length > 0 ? traces.turns[0].turnNumber : null);\n if (oldestHeldTurnNumber === null) return traces.hasOlderTurns;\n if (firstTurnNumberOfPage === null) return this.state.hasOlderTurns;\n return firstTurnNumberOfPage <= oldestHeldTurnNumber ? traces.hasOlderTurns : this.state.hasOlderTurns;\n }\n\n protected acceptRead(read: TraceRead, traces: ConversationTurnTraces): void {\n let hasChanged = !this.hasReadNewest;\n const hasOlderTurns = this.readHasOlderTurns(read, traces);\n const totalTurnCount = traces.totalTurnCount ?? this.state.totalTurnCount;\n if (read.kind !== \"older\") {\n this.hasReadNewest = true;\n this.needsFollowRead = false;\n this.endedTurnMessageIds.clear();\n if (traces.newestMessageIndex !== null) this.newestMessageIndex = traces.newestMessageIndex;\n }\n for (const turn of traces.turns) {\n const heldTurn = this.turnsByNumber.get(turn.turnNumber);\n // An unchanged turn keeps its object, so its rows do not render again.\n if (heldTurn !== undefined && JSON.stringify(heldTurn) === JSON.stringify(turn)) continue;\n this.turnsByNumber.set(turn.turnNumber, turn);\n hasChanged = true;\n }\n const isRunLive = read.kind === \"older\" ? this.state.isRunLive : traces.isRunLive;\n const level = traces.level;\n if (\n !hasChanged &&\n isRunLive === this.state.isRunLive &&\n level === this.state.level &&\n hasOlderTurns === this.state.hasOlderTurns &&\n totalTurnCount === this.state.totalTurnCount &&\n this.state.status === \"ready\"\n ) {\n return;\n }\n const turns = [...this.turnsByNumber.values()].sort((first, second) => first.turnNumber - second.turnNumber);\n this.publish({ turns, status: \"ready\", level, isRunLive, hasOlderTurns, totalTurnCount });\n }\n\n protected publish(change: Partial<ConversationTraceState>): void {\n this.state = { ...this.state, ...change };\n for (const listener of [...this.listeners]) listener();\n }\n}\n\nconst loadersByClient = new WeakMap<object, Map<string, ConversationTraceLoader>>();\n\n/**\n * The loader of a conversation's trace at one level: one per client, conversation and level, so every component that\n * shows a turn of that conversation shares its reads and what it holds.\n */\nexport const getConversationTraceLoader = (\n client: ConversationTraceClient,\n conversationId: number,\n options: ConversationTraceLoaderOptions = {},\n): ConversationTraceLoader => {\n let loaders = loadersByClient.get(client);\n if (loaders === undefined) {\n loaders = new Map();\n loadersByClient.set(client, loaders);\n }\n const key = `${conversationId}:${options.level ?? \"STEPS\"}:${options.pageSize ?? DEFAULT_PAGE_SIZE}`;\n let loader = loaders.get(key);\n if (loader === undefined) {\n loader = new ConversationTraceLoader(client, conversationId, options);\n loaders.set(key, loader);\n }\n return loader;\n};\n\n/** Drops the loaders of a client (a test, a sign-out): their timers stop and the next read starts over. */\nexport const releaseConversationTraceLoaders = (client: ConversationTraceClient): void => {\n const loaders = loadersByClient.get(client);\n if (loaders === undefined) return;\n for (const loader of loaders.values()) loader.dispose();\n loadersByClient.delete(client);\n};\n","import { useEffect, useMemo, useSyncExternalStore } from \"react\";\nimport type { ConversationTraceLevel, ConversationTurnTrace } from \"../../contract/conversation-trace\";\nimport type { AgentsChatState } from \"../store/agents-chat-state\";\nimport { useAgentsChatSelector, useOptionalAgentsChatStore } from \"../store/use-agents-chat-store\";\nimport { type ConversationTraceClient, type ConversationTraceState, getConversationTraceLoader } from \"./conversation-trace-loader\";\n\n// The hooks over the trace loader: one turn of a conversation, and the turns the loader holds of it.\n\n/** Where the shown conversation stands: its message count and its newest message id, as one value. */\nconst selectConversationRevision = (state: AgentsChatState): string => {\n const messages = state.messages ?? [];\n return `${messages.length}:${messages[messages.length - 1]?.id ?? \"\"}`;\n};\n\n/**\n * Where the conversation of the chat around this component stands, for the loader's reads after a change: the given\n * value, else the message count and newest message id of the chat's own store; null outside a chat.\n */\nexport const useConversationTraceRevision = (conversationRevision?: string | number | null): string | number | null => {\n const chatStore = useOptionalAgentsChatStore();\n const storeRevision = useAgentsChatSelector(chatStore, selectConversationRevision, \"\");\n if (conversationRevision !== undefined && conversationRevision !== null) return conversationRevision;\n return chatStore === null ? null : storeRevision;\n};\n\nexport interface UseConversationTurnTraceOptions {\n client: ConversationTraceClient;\n conversationId: number;\n /** The message that started the turn; null (an optimistic message without an id yet) reads nothing. */\n turnMessageId: number | null;\n level: ConversationTraceLevel;\n /** The turn runs: the loader follows it until this turns false. */\n isLive: boolean;\n pollIntervalMs?: number;\n /** A value that changes with every new message of the conversation; default: read from the chat's store. */\n conversationRevision?: string | number | null;\n}\n\nexport interface ConversationTurnTraceRead {\n /** The trace of the turn; null while it is not read, when the message started none, and after a failed read. */\n turn: ConversationTurnTrace | null;\n /** The loader's state of the conversation. */\n state: ConversationTraceState;\n /** Reads the changed turns now. */\n refresh: () => void;\n}\n\n/**\n * The trace of the turn one message started, read through the conversation's shared loader: every turn on screen\n * shares the loader's reads, a live turn is followed until it ends, and a change of the conversation reads again.\n */\nexport const useConversationTurnTrace = (options: UseConversationTurnTraceOptions): ConversationTurnTraceRead => {\n const { client, conversationId, turnMessageId, level, isLive, pollIntervalMs } = options;\n const loader = useMemo(() => getConversationTraceLoader(client, conversationId, { level }), [client, conversationId, level]);\n const state = useSyncExternalStore(loader.subscribe, loader.getState, loader.getState);\n const conversationRevision = useConversationTraceRevision(options.conversationRevision);\n\n useEffect(() => {\n if (conversationRevision !== null) loader.noteConversationRevision(conversationRevision);\n }, [loader, conversationRevision]);\n useEffect(() => (turnMessageId === null ? undefined : loader.requestTurn(turnMessageId)), [loader, turnMessageId]);\n useEffect(\n () => (turnMessageId === null || !isLive ? undefined : loader.followLiveTurn(turnMessageId, pollIntervalMs)),\n [loader, turnMessageId, isLive, pollIntervalMs],\n );\n\n // `state` is read so the turn is looked up again after every change the loader publishes.\n const turn = useMemo(() => (turnMessageId === null ? null : loader.findTurn(turnMessageId)), [loader, turnMessageId, state]);\n return { turn, state, refresh: () => loader.refresh() };\n};\n\nexport interface UseConversationTracesOptions {\n client: ConversationTraceClient;\n /** The conversation; null reads nothing. */\n conversationId: number | null;\n level: ConversationTraceLevel;\n /** Follows the conversation while a turn runs in it (a sub-agent's trace, which no chat follows). Default false. */\n followsWhileLive?: boolean;\n pollIntervalMs?: number;\n conversationRevision?: string | number | null;\n}\n\nconst NO_TRACE_STATE: ConversationTraceState = { turns: [], status: \"idle\", level: null, isRunLive: false, hasOlderTurns: false, totalTurnCount: null };\nconst subscribeToNothing = () => () => undefined;\nconst readNoTraceState = () => NO_TRACE_STATE;\n\n/**\n * The turns the conversation's shared loader holds, the newest window at least: for a pane beside the chat (its\n * changed files, its sub-agents) and for the trace of a sub-agent's conversation.\n */\nexport const useConversationTraces = (options: UseConversationTracesOptions): ConversationTraceState => {\n const { client, conversationId, level, followsWhileLive = false, pollIntervalMs } = options;\n const loader = useMemo(\n () => (conversationId === null ? null : getConversationTraceLoader(client, conversationId, { level })),\n [client, conversationId, level],\n );\n const state = useSyncExternalStore(loader?.subscribe ?? subscribeToNothing, loader?.getState ?? readNoTraceState, loader?.getState ?? readNoTraceState);\n const conversationRevision = useConversationTraceRevision(options.conversationRevision);\n\n useEffect(() => loader?.requestNewestTurns(), [loader]);\n useEffect(() => {\n if (loader !== null && conversationRevision !== null) loader.noteConversationRevision(conversationRevision);\n }, [loader, conversationRevision]);\n const isFollowing = followsWhileLive && state.isRunLive;\n useEffect(() => (loader !== null && isFollowing ? loader.followChanges(pollIntervalMs) : undefined), [loader, isFollowing, pollIntervalMs]);\n return state;\n};\n","import { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport type { ConversationTraceClient } from \"./conversation-trace-loader\";\nimport { selectVisibleTraceSteps, TraceStepRow } from \"./ToolStepGroup\";\nimport type { TraceHostBindings, TraceViewMode } from \"./trace-types\";\nimport { useConversationTraces } from \"./use-conversation-trace\";\nimport agentStyles from \"./trace-agents.module.scss\";\nimport stepStyles from \"./trace-steps.module.scss\";\n\nexport interface ConversationChildTraceProps {\n /** The conversation client; the server lets a reader of a conversation read the traces of its sub-agents. */\n client: ConversationTraceClient;\n /** The conversation of the sub-agent. */\n conversationId: number;\n /** `verbose` reads the debug level and shows tool names and details. Default `normal`. */\n viewMode?: TraceViewMode;\n host?: TraceHostBindings;\n isCompact?: boolean;\n pollIntervalMs?: number;\n}\n\n/**\n * The steps of a sub-agent's conversation, shown inside its open row: read when the row opens (through the shared\n * loader of that conversation), followed while the sub-agent runs. A failed read shows nothing.\n */\nexport const ConversationChildTrace = (props: ConversationChildTraceProps) => {\n const { client, conversationId, viewMode = \"normal\", host, isCompact = false, pollIntervalMs } = props;\n const state = useConversationTraces({\n client,\n conversationId,\n level: viewMode === \"verbose\" ? \"DEBUG\" : \"STEPS\",\n followsWhileLive: true,\n pollIntervalMs,\n });\n if (state.status === \"idle\" || state.status === \"loading\") {\n return <div className={agentStyles.quiet}>{translateText(\"Loading the steps…\")}</div>;\n }\n if (state.status === \"failed\") return null;\n const rows = state.turns.flatMap((turn) =>\n selectVisibleTraceSteps(turn.steps, viewMode === \"summary\" ? \"normal\" : viewMode).map((step) => ({ key: `${turn.turnNumber}:${step.key}`, step })),\n );\n // A run that has ended without a step to show (a job that only ran one tool) says so; a live one may still get some.\n if (rows.length === 0) {\n return <div className={agentStyles.quiet}>{state.isRunLive ? translateText(\"No steps so far.\") : translateText(\"This run recorded no steps.\")}</div>;\n }\n return (\n <div className={classNames(stepStyles.steps, isCompact && stepStyles.compact)} data-testid=\"trace-child-steps\">\n {rows.map((row) => (\n <TraceStepRow\n key={row.key}\n step={row.step}\n viewMode={viewMode === \"summary\" ? \"normal\" : viewMode}\n host={host}\n conversationId={conversationId}\n isCompact={isCompact}\n />\n ))}\n </div>\n );\n};\n","import { useState } from \"react\";\nimport { useConversationWidgetContext } from \"../../renderer/ConversationWidgetCallbacksContext\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport styles from \"./trace-steps.module.scss\";\n\n/** A tool call of the turn that waits for the owner's approval. */\nexport interface ConsentRequestCardCall {\n /** The tool in words (\"Create support directive\"); the tool's name when there are none. */\n title: string;\n /** What the call would do, as the step narrated it. */\n line?: string | null;\n}\n\nexport interface ConsentRequestCardProps {\n /** The conversation the turn belongs to: the card acts only inside the live chat of that conversation. */\n conversationId: number;\n /** The message that started the turn: once the owner wrote after it, the request is answered and the card goes. */\n turnMessageId: number;\n calls: ConsentRequestCardCall[];\n isCompact?: boolean;\n}\n\n/**\n * The card of a turn that ended on a tool call held for the owner's approval: what would run, and two buttons that\n * answer the agent's question in the owner's words, as an explicit yes to exactly the described step (the server's\n * consent check accepts nothing less) or a clear no. The agent reads the answer\n * like any reply; the call runs only after a yes. Outside the live chat (the analysis view) and once the owner wrote\n * after the turn, the card is not shown: the step's \"waits for approval\" badge tells the story there.\n */\nexport const ConsentRequestCard = (props: ConsentRequestCardProps) => {\n const { conversationId, turnMessageId, calls, isCompact = false } = props;\n const widgetContext = useConversationWidgetContext();\n const [sentAnswer, setSentAnswer] = useState<\"yes\" | \"no\" | null>(null);\n if (calls.length === 0 || widgetContext.conversationId !== conversationId) return null;\n const messages = widgetContext.messages ?? [];\n const turnPosition = messages.findIndex((message) => message.id === turnMessageId);\n const isAnswered = turnPosition >= 0 && messages.slice(turnPosition + 1).some((message) => message.role === \"USER\" && message.messageType !== \"SIGNAL\");\n if (isAnswered && sentAnswer === null) return null;\n\n const answer = (choice: \"yes\" | \"no\") => {\n if (sentAnswer !== null) return;\n setSentAnswer(choice);\n // The server's consent check takes only an explicit yes to exactly the step the agent described (checked live: this\n // wording in German passes, a bare \"yes, go ahead\" does not).\n void widgetContext.sendMessageToChat(\n choice === \"yes\"\n ? translateText(\"Yes, I explicitly approve this step, exactly as you described it.\")\n : translateText(\"No, please don't run this step.\"),\n );\n };\n const heading =\n calls.length === 1\n ? translateText(\"Approve: %action%?\", { action: calls[0].title })\n : translateText(\"Approve %count% actions?\", { count: calls.length });\n\n return (\n <div className={classNames(styles.consentCard, isCompact && styles.consentCardCompact)} data-testid=\"trace-consent-request\">\n <div className={styles.consentHead}>\n <Icon name=\"stepWaiting\" pixelSize={14} />\n <span className={styles.consentTitle}>{heading}</span>\n <span className={classNames(styles.badge, styles.badgeWarning)}>{translateText(\"waits for you\")}</span>\n </div>\n {calls.some((call) => call.line) ? (\n <ul className={styles.consentCalls}>\n {calls.map((call, position) => (\n // biome-ignore lint/suspicious/noArrayIndexKey: the calls of one turn keep their order\n <li key={position}>{calls.length > 1 ? <b>{call.title}: </b> : null}{call.line}</li>\n ))}\n </ul>\n ) : null}\n <div className={styles.consentActions}>\n <button type=\"button\" className={styles.consentApprove} disabled={sentAnswer !== null} onClick={() => answer(\"yes\")}>\n {translateText(\"Approve\")}\n </button>\n <button type=\"button\" className={styles.consentDecline} disabled={sentAnswer !== null} onClick={() => answer(\"no\")}>\n {translateText(\"Don't run it\")}\n </button>\n <span className={styles.consentNote}>\n {sentAnswer === null ? translateText(\"Runs only after your approval.\") : translateText(\"Your answer was sent.\")}\n </span>\n </div>\n </div>\n );\n};\n","import { useState } from \"react\";\nimport type { ConversationBackgroundJob, ConversationBackgroundJobStop } from \"../../contract/conversation\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { formatTraceClock, readTraceMoment } from \"./trace-format\";\nimport { useTraceNow } from \"./trace-parts\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface RunningBackgroundJobLinesProps {\n /** The jobs whose end is not reported yet, oldest first; nothing is rendered without one. */\n backgroundJobs: ConversationBackgroundJob[];\n /** Stops one job; without it no Stop button. The lines read again through `onStopped` once the call settled. */\n onStop?: (backgroundJobId: number) => Promise<ConversationBackgroundJobStop>;\n /** Called after every stop call, accepted or not: the chat reads the activity again at once. */\n onStopped?: () => void;\n /** The chat is the compact side panel. */\n isCompact?: boolean;\n className?: string;\n}\n\n/** What a job's line says after its label: the clock of its run, or the time until a wake-up rings. */\nconst describeJobTime = (backgroundJob: ConversationBackgroundJob, now: number): string | null => {\n const dueAt = readTraceMoment(backgroundJob.dueAt);\n if (dueAt !== null && dueAt > now) {\n return translateText(\"rings in %time%\", { time: formatTraceClock(dueAt - now) });\n }\n const startedAt = readTraceMoment(backgroundJob.startedAt);\n return startedAt !== null ? formatTraceClock(now - startedAt) : null;\n};\n\n/**\n * The background jobs of the conversation that still run beside the turns (a command after the detach window, a\n * wake-up the agent set): one status line each, as the running turn's own line looks — a spinner, the job's label\n * and its clock (a wake-up: the time until it rings), the hint when the job waits for the host, and a Stop for that\n * job alone. A stopped job's end reaches the agent in its next turn; the turn's Stop stays the stop of everything.\n */\nexport const RunningBackgroundJobLines = (props: RunningBackgroundJobLinesProps) => {\n const { backgroundJobs, onStop, onStopped, isCompact = false, className } = props;\n const now = useTraceNow(backgroundJobs.length > 0);\n const [stoppingJobIds, setStoppingJobIds] = useState<readonly number[]>([]);\n if (backgroundJobs.length === 0) return null;\n\n const handleStop = async (backgroundJobId: number) => {\n if (!onStop) return;\n setStoppingJobIds((jobIds) => [...jobIds, backgroundJobId]);\n try {\n await onStop(backgroundJobId);\n } catch {\n // The stop was not accepted: the button is there again and the job runs on.\n } finally {\n setStoppingJobIds((jobIds) => jobIds.filter((jobId) => jobId !== backgroundJobId));\n onStopped?.();\n }\n };\n\n return (\n <div\n className={classNames(styles.turnTrace, isCompact && styles.turnTraceCompact, className)}\n role=\"group\"\n aria-label={translateText(\"Background jobs\")}\n data-testid=\"running-background-jobs\"\n >\n {backgroundJobs.map((backgroundJob) => {\n const isWaitingForHost = backgroundJob.liveStatus === \"WAITING_FOR_HOST\";\n const isStopping = stoppingJobIds.includes(backgroundJob.id);\n const jobTime = describeJobTime(backgroundJob, now);\n return (\n <div\n key={backgroundJob.id}\n className={styles.statusLine}\n data-testid=\"running-background-job\"\n data-background-job-id={backgroundJob.id}\n data-live-status={backgroundJob.liveStatus ?? undefined}\n >\n <span className={classNames(styles.spinner, isWaitingForHost && styles.spinnerWaiting)} aria-hidden />\n {/* the label gives way on a narrow screen, the job number and its clock stay whole (otherwise at 390 px the clock\n was cut off behind the label); the separator before them is drawn by the style, so it never\n opens a line when they wrap below the label */}\n <span className={styles.jobStatusText} title={backgroundJob.label}>\n <span className={styles.jobStatusParts}>\n <span className={classNames(styles.statusWord, styles.jobLabel)}>{backgroundJob.label || translateText(\"Background job\")}</span>\n {[translateText(\"Background job #%number%\", { number: backgroundJob.id }), isStopping ? translateText(\"Stopping…\") : jobTime]\n .filter((part): part is string => part !== null)\n .map((part) => (\n <span key={part === jobTime ? \"time\" : part} className={styles.jobMeta} data-testid=\"running-background-job-meta\">\n {part}\n </span>\n ))}\n </span>\n </span>\n {isWaitingForHost ? (\n <span className={classNames(styles.badge, styles.badgeWarning)} title={backgroundJob.liveNote ?? undefined} data-testid=\"background-job-waiting-for-host\">\n {translateText(\"waits for the host\")}\n </span>\n ) : null}\n <span className={styles.metaGrow} />\n {onStop ? (\n <button\n type=\"button\"\n className={styles.stopButton}\n disabled={isStopping}\n aria-label={translateText(\"Stop background job #%number%\", { number: backgroundJob.id })}\n onClick={() => void handleStop(backgroundJob.id)}\n >\n <span className={styles.stopSquare} aria-hidden />\n {translateText(\"Stop\")}\n </button>\n ) : null}\n </div>\n );\n })}\n </div>\n );\n};\n","import { type ReactNode, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { translateText } from \"../../provider/environment\";\nimport { formatTraceClock, readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport { useTraceNow } from \"./trace-parts\";\nimport type { TraceViewMode } from \"./trace-types\";\nimport styles from \"./trace-steps.module.scss\";\n\nexport interface RunStatusLineProps {\n /** When the turn started: a server date-time, an ISO date-time or a moment in ms. The clock ticks from it. */\n startedAt?: string | number | null;\n /** What the agent does right now, in words (\"reads the rides\"). Default: \"Working\". */\n statusText?: string | null;\n /** `verbose` adds the tokens and the cost. Default `normal`. */\n viewMode?: TraceViewMode;\n /** Tokens of the turn so far (verbose). */\n tokens?: number | null;\n /** Cost of the turn so far (verbose). */\n costInUsd?: number | null;\n formatCost?: (costInUsd: number) => string;\n /** Stops the turn; without it no Stop button. A promise keeps the button disabled until it settles. */\n onStop?: () => void | Promise<void>;\n /** The stop was asked for and the turn winds down: the line says so, the button is off. */\n isStopping?: boolean;\n /** Further content on the right of the line. */\n children?: ReactNode;\n className?: string;\n}\n\n/**\n * The status line of a running turn: a spinner, \"Working · 0:42\" ticking from the turn's start, in the verbose view\n * the tokens and the cost so far, and a Stop button.\n */\nexport const RunStatusLine = (props: RunStatusLineProps) => {\n const { startedAt, statusText, viewMode = \"normal\", tokens, costInUsd, formatCost, onStop, isStopping = false, children, className } = props;\n const format = useTraceFormat();\n const now = useTraceNow(true);\n const [isStopPending, setIsStopPending] = useState(false);\n const startedAtMoment = typeof startedAt === \"number\" ? startedAt : readTraceMoment(startedAt);\n const showsStopping = isStopping || isStopPending;\n\n const figures = [\n startedAtMoment !== null ? formatTraceClock(now - startedAtMoment) : null,\n // before the first model call answers there is nothing to count: \"0 tokens · $0.00\" would read as a fault\n viewMode === \"verbose\" && tokens != null && tokens > 0 ? translateText(\"%count% tokens in total\", { count: format.count(tokens) }) : null,\n viewMode === \"verbose\" && costInUsd != null && costInUsd > 0 ? (formatCost ?? format.cost)(costInUsd) : null,\n ].filter((figure): figure is string => figure !== null);\n\n const handleStop = async () => {\n if (!onStop) return;\n setIsStopPending(true);\n try {\n await onStop();\n } finally {\n setIsStopPending(false);\n }\n };\n\n return (\n <div className={classNames(styles.statusLine, className)} role=\"status\" data-testid=\"trace-run-status\">\n <span className={styles.spinner} aria-hidden />\n <span className={styles.statusText}>\n <span className={styles.statusWord}>{showsStopping ? translateText(\"Stopping…\") : (statusText ?? translateText(\"Working\"))}</span>\n {figures.length > 0 ? ` · ${figures.join(\" · \")}` : null}\n </span>\n <span className={styles.metaGrow} />\n {children}\n {onStop ? (\n <button type=\"button\" className={styles.stopButton} disabled={showsStopping} onClick={() => void handleStop()}>\n <span className={styles.stopSquare} aria-hidden />\n {translateText(\"Stop\")}\n </button>\n ) : null}\n </div>\n );\n};\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport type { AgentsConversationClient } from \"../../client/AgentsConversationClient\";\nimport type { ConversationTraceStep, ConversationTurnTrace as ConversationTurnTraceData } from \"../../contract/conversation-trace\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport { ConsentRequestCard } from \"./ConsentRequestCard\";\nimport { ConversationChildTrace } from \"./ConversationChildTrace\";\nimport { FileChangesSummary } from \"./FileChangesSummary\";\nimport { QueuedMessageChip } from \"./QueuedMessageChip\";\nimport { RunningBackgroundJobLines } from \"./RunningBackgroundJobLines\";\nimport { RunStatusLine } from \"./RunStatusLine\";\nimport { useRunningBackgroundJobs } from \"./running-background-jobs-context\";\nimport { buildTaskPlanItems } from \"./StepKindDetails\";\nimport { TaskPlanRow, type TaskPlanItem } from \"./TaskPlanRow\";\nimport { readTaskPlanCountsOfStep } from \"./task-plan-counts\";\nimport { MIN_SHOWN_TURN_DURATION_MS, selectVisibleTraceSteps, ToolStepGroup } from \"./ToolStepGroup\";\nimport { describeStepCount } from \"./trace-counts\";\nimport { useTraceFormat } from \"./trace-format\";\nimport type { TraceFileChange, TraceHostBindings, TraceViewMode } from \"./trace-types\";\nimport { TurnMetaLine } from \"./TurnMetaLine\";\nimport { useConversationTurnTrace } from \"./use-conversation-trace\";\nimport styles from \"./trace-steps.module.scss\";\n\n/** The part of the conversation client the turn trace uses: the trace read, the stop and the stored diffs. */\nexport type ConversationTurnTraceClient = Pick<AgentsConversationClient, \"getTurnTraces\" | \"stopTurn\" | \"getFileChangeDiff\">;\n\n/** A task plan whose items the host knows (the conversation's working state): shown while the turn runs. */\nexport interface ConversationTurnTracePlan {\n title?: string | null;\n items: TaskPlanItem[];\n}\n\nexport interface ConversationTurnTraceProps {\n conversationId: number;\n /** The message that started the turn (`AgentChat`'s `TurnTrace` slot hands it over). */\n turnMessageId: number | string;\n /** live = the turn runs right now; done = it ended, or the message started none. */\n phase: \"live\" | \"done\";\n /** The chat is the compact side panel: narrow blocks, no side-by-side diff. */\n isCompact: boolean;\n /** The conversation client port: `getTurnTraces` feeds the trace, `stopTurn` the Stop button, `getFileChangeDiff` the full diffs. */\n client: ConversationTurnTraceClient;\n /** `summary` (Short), `normal` or `verbose`; verbose needs `isDebugAllowed`, else it reads as normal. */\n viewMode: TraceViewMode;\n /** The host's records, links, mounts and money. `loadFullDiff` and `renderChildTrace` default to the client's reads. */\n host?: TraceHostBindings;\n /** The reader may see the debug level (tool names, arguments, results, tokens, cost). Default false. */\n isDebugAllowed?: boolean;\n /** How often a running turn is read again. Default 1500 ms. */\n pollIntervalMs?: number;\n /** Opens what the model was sent at a call of this turn (verbose): the id of the turn's newest model call message. */\n onOpenContext?: (messageId: number) => void;\n /** The route of the turn in the host's analysis view (verbose); null for none. */\n buildAnalysisHref?: (conversationId: number, turnMessageId: number) => string | null;\n /** The task plan with its items, when the host has it; without it a running turn shows the plan's counts from the trace. */\n taskPlan?: ConversationTurnTracePlan | null;\n /** A value that changes with every new message of the conversation; default: read from the chat's store. */\n conversationRevision?: string | number | null;\n className?: string;\n}\n\n/** The newest model call of a turn that a stored message carries: what \"What the model saw\" opens. */\nconst findNewestModelCallMessageId = (steps: ConversationTraceStep[]): number | null => {\n for (let position = steps.length - 1; position >= 0; position -= 1) {\n const step = steps[position];\n if ((step.kind === \"MODEL_CALL\" || step.modelCall !== null) && step.messageId !== null) return step.messageId;\n }\n return null;\n};\n\n/** The server's words for the turn's model, from its newest model call of that model; null when no step names it. */\nconst findTurnModelLabel = (steps: ConversationTraceStep[], modelName: string | null | undefined): string | null => {\n if (!modelName) return null;\n for (let position = steps.length - 1; position >= 0; position -= 1) {\n const step = steps[position];\n if (step.modelCall?.modelName === modelName && step.modelLabel) return step.modelLabel;\n }\n return null;\n};\n\n/** The newest plan update of a turn. */\nconst findNewestTaskPlanStep = (steps: ConversationTraceStep[]): ConversationTraceStep | null => {\n for (let position = steps.length - 1; position >= 0; position -= 1) {\n if (steps[position].kind === \"TASK_PLAN\" && steps[position].taskPlanItemCount !== null) return steps[position];\n }\n return null;\n};\n\n/** What a running turn spent so far, summed over its model calls (the turn's own totals come with its end). */\nconst sumModelCalls = (turn: ConversationTurnTraceData): { tokens: number | null; costInUsd: number | null } => {\n let tokens: number | null = turn.totals.inputTokens !== null || turn.totals.outputTokens !== null ? (turn.totals.inputTokens ?? 0) + (turn.totals.outputTokens ?? 0) : null;\n let costInUsd = turn.totals.costInUsd;\n if (tokens === null || costInUsd === null) {\n let summedTokens = 0;\n let summedCost = 0;\n let hasTokens = false;\n let hasCost = false;\n for (const step of turn.steps) {\n if (step.kind !== \"MODEL_CALL\" || step.modelCall === null) continue;\n if (step.modelCall.inputTokens !== null || step.modelCall.outputTokens !== null) {\n summedTokens += (step.modelCall.inputTokens ?? 0) + (step.modelCall.outputTokens ?? 0);\n hasTokens = true;\n }\n if (step.modelCall.costInUsd !== null) {\n summedCost += step.modelCall.costInUsd;\n hasCost = true;\n }\n }\n if (tokens === null && hasTokens) tokens = summedTokens;\n if (costInUsd === null && hasCost) costInUsd = summedCost;\n }\n return { tokens, costInUsd };\n};\n\n/**\n * The trace of one turn in the chat, ready for `AgentChat`'s `TurnTrace` slot: it reads the turn through the\n * conversation's shared loader (the turns on screen share their requests), follows it while it runs and shows it by\n * the view mode. Short: one line \"12 steps · 48 s\" that opens the steps. Normal: the steps folded, each with its\n * narrated line, sub-agents with their own steps, commands and file edits. Verbose (debug readers): the steps open,\n * with tool names, thinking, arguments and results, the loaded skills and the turn's figures with the links to what\n * the model saw and to the analysis. While the turn runs: the status line with the clock and Stop, and the task plan.\n * A failed read renders nothing: the thread stays as it is. Under the newest turn of the chat (the context of the chat\n * controller names it) stand the lines of the conversation's background jobs whose end is not reported yet, each with\n * its own Stop — also once that turn has answered.\n */\nexport const ConversationTurnTrace = (props: ConversationTurnTraceProps) => {\n const runningBackgroundJobs = useRunningBackgroundJobs();\n const showsBackgroundJobLines =\n runningBackgroundJobs !== null &&\n runningBackgroundJobs.conversationId === props.conversationId &&\n runningBackgroundJobs.anchorTurnMessageId !== null &&\n String(runningBackgroundJobs.anchorTurnMessageId) === String(props.turnMessageId) &&\n runningBackgroundJobs.backgroundJobs.length > 0;\n return (\n <>\n <ConversationTurnTraceBody {...props} />\n {showsBackgroundJobLines ? (\n <RunningBackgroundJobLines\n backgroundJobs={runningBackgroundJobs.backgroundJobs}\n onStop={runningBackgroundJobs.stopBackgroundJob}\n onStopped={runningBackgroundJobs.refresh}\n isCompact={props.isCompact}\n />\n ) : null}\n </>\n );\n};\n\n/** The trace of one turn itself: its steps, its status line and plan while it runs, its consent card. */\nconst ConversationTurnTraceBody = (props: ConversationTurnTraceProps) => {\n const {\n conversationId,\n turnMessageId,\n phase,\n isCompact,\n client,\n viewMode,\n host,\n isDebugAllowed = false,\n pollIntervalMs,\n onOpenContext,\n buildAnalysisHref,\n taskPlan,\n conversationRevision,\n className,\n } = props;\n const format = useTraceFormat();\n const isLive = phase === \"live\";\n const shownViewMode: TraceViewMode = viewMode === \"verbose\" && !isDebugAllowed ? \"normal\" : viewMode;\n const isVerbose = shownViewMode === \"verbose\";\n const numericTurnMessageId = typeof turnMessageId === \"number\" && Number.isFinite(turnMessageId) ? turnMessageId : null;\n const { turn, refresh } = useConversationTurnTrace({\n client,\n conversationId,\n turnMessageId: numericTurnMessageId,\n level: isVerbose ? \"DEBUG\" : \"STEPS\",\n isLive,\n pollIntervalMs,\n conversationRevision,\n });\n\n // Short opens to the steps on a click; another turn or another mode starts closed again.\n const [isSummaryOpened, setIsSummaryOpened] = useState(false);\n useEffect(() => setIsSummaryOpened(false), [viewMode, numericTurnMessageId]);\n // The clock of a turn whose trace is not read yet ticks from the moment the turn was first seen running.\n const firstSeenLiveAt = useRef<number | null>(null);\n if (isLive && firstSeenLiveAt.current === null) firstSeenLiveAt.current = Date.now();\n if (!isLive) firstSeenLiveAt.current = null;\n // A stop that was accepted keeps the line at \"Stopping…\" until the turn ends.\n const [isStopping, setIsStopping] = useState(false);\n useEffect(() => {\n if (!isLive) setIsStopping(false);\n }, [isLive]);\n\n const { getFileChangeDiff, getTurnTraces, stopTurn } = client;\n const boundHost = useMemo<TraceHostBindings>(() => {\n const loadFullDiffOfClient = getFileChangeDiff\n ? async (fileChange: TraceFileChange): Promise<string> => {\n if (fileChange.id == null) return fileChange.diffPreview ?? \"\";\n return (await getFileChangeDiff(fileChange.id)).diff;\n }\n : undefined;\n return {\n ...host,\n openModelCallContext: host?.openModelCallContext ?? onOpenContext,\n loadFullDiff: host?.loadFullDiff ?? loadFullDiffOfClient,\n renderChildTrace:\n host?.renderChildTrace ??\n ((childConversationId: number) => (\n <ConversationChildTrace\n client={{ getTurnTraces }}\n conversationId={childConversationId}\n viewMode={shownViewMode}\n host={host}\n isCompact={isCompact}\n pollIntervalMs={pollIntervalMs}\n />\n )),\n };\n }, [host, onOpenContext, getFileChangeDiff, getTurnTraces, shownViewMode, isCompact, pollIntervalMs]);\n\n if (turn === null && !isLive) return null;\n\n const steps = turn?.steps ?? [];\n const totals = turn?.totals ?? null;\n const readerSteps = selectVisibleTraceSteps(steps, \"normal\");\n const handleStop = stopTurn\n ? async () => {\n try {\n const turnStop = await stopTurn(conversationId);\n setIsStopping(turnStop.isStopped);\n refresh();\n } catch {\n // The stop was not accepted: the button is there again and the turn runs on.\n setIsStopping(false);\n }\n }\n : undefined;\n\n const spent = turn !== null && isVerbose ? sumModelCalls(turn) : { tokens: null, costInUsd: null };\n const statusLine = isLive ? (\n <RunStatusLine\n startedAt={turn?.startedAt ?? firstSeenLiveAt.current}\n viewMode={shownViewMode}\n tokens={spent.tokens}\n costInUsd={spent.costInUsd}\n formatCost={boundHost.formatCost}\n onStop={handleStop}\n isStopping={isStopping}\n />\n ) : null;\n\n const newestPlanStep = isLive ? findNewestTaskPlanStep(steps) : null;\n const planRow = !isLive ? null : taskPlan && taskPlan.items.length > 0 ? (\n <TaskPlanRow title={taskPlan.title} items={taskPlan.items} defaultOpen={!isCompact} />\n ) : newestPlanStep !== null ? (\n <TaskPlanRow\n title={newestPlanStep.taskPlanTitle}\n // The items of the plan when the trace names them, else the head with its counts.\n items={buildTaskPlanItems(newestPlanStep.taskPlanItems)}\n defaultOpen={!isCompact}\n totalCount={newestPlanStep.taskPlanItemCount}\n doneCount={readTaskPlanCountsOfStep(newestPlanStep).done}\n />\n ) : null;\n\n // The tool calls the finished turn holds for the owner's approval: a card to answer them (the live chat only).\n const consentCalls = !isLive\n ? steps\n .filter((step) => step.isHeldForConsent)\n .map((step) => ({ title: step.toolNameInWords || step.toolName || translateText(\"Action\"), line: step.line ?? null }))\n : [];\n const consentCard =\n consentCalls.length > 0 && numericTurnMessageId !== null ? (\n <ConsentRequestCard conversationId={conversationId} turnMessageId={numericTurnMessageId} calls={consentCalls} isCompact={isCompact} />\n ) : null;\n\n // Short: nothing of a turn without steps; one line that opens the steps of a turn with some.\n if (shownViewMode === \"summary\" && !isSummaryOpened) {\n if (isLive) {\n return (\n <div className={classNames(styles.turnTrace, isCompact && styles.turnTraceCompact, className)} data-testid=\"conversation-turn-trace\" data-view-mode=\"summary\" data-phase={phase}>\n {statusLine}\n </div>\n );\n }\n if (readerSteps.length === 0) return null;\n const summaryParts = [\n describeStepCount(readerSteps.length, format),\n totals?.durationMs != null && totals.durationMs >= MIN_SHOWN_TURN_DURATION_MS ? format.duration(totals.durationMs) : null,\n ].filter((part): part is string => part !== null);\n return (\n <div className={classNames(styles.turnTrace, isCompact && styles.turnTraceCompact, className)} data-testid=\"conversation-turn-trace\" data-view-mode=\"summary\" data-phase={phase}>\n <button\n type=\"button\"\n className={styles.summaryChip}\n aria-expanded={false}\n title={translateText(\"Show the steps\")}\n onClick={() => setIsSummaryOpened(true)}\n data-testid=\"trace-summary-chip\"\n >\n <Icon name=\"steps\" pixelSize={13} />\n {summaryParts.join(\" · \")}\n </button>\n {consentCard}\n </div>\n );\n }\n\n const groupViewMode: TraceViewMode = shownViewMode === \"summary\" ? \"normal\" : shownViewMode;\n const newestModelCallMessageId = isVerbose ? findNewestModelCallMessageId(steps) : null;\n const analysisHref = isVerbose && numericTurnMessageId !== null ? (buildAnalysisHref?.(conversationId, numericTurnMessageId) ?? null) : null;\n const metaLine =\n isVerbose && totals !== null && !isLive ? (\n <TurnMetaLine\n {...totals}\n modelLabel={findTurnModelLabel(steps, totals.modelName)}\n onOpenContext={onOpenContext && newestModelCallMessageId !== null ? () => onOpenContext(newestModelCallMessageId) : undefined}\n analysisHref={analysisHref}\n linkComponent={boundHost.linkComponent}\n formatCost={boundHost.formatCost}\n isCompact={isCompact}\n />\n ) : null;\n // Owner messages that came in while this turn ran and that it took up: a quiet line each once the turn is over (the\n // thread shows them as plain messages; while the turn runs the controller marks them as queued).\n const queuedMessagesTakenUp =\n !isLive && turn !== null && shownViewMode !== \"summary\"\n ? (turn.queuedMessages ?? []).filter((message) => message.handledInTurnNumber == null || message.handledInTurnNumber === turn.turnNumber)\n : [];\n const hasGroup = selectVisibleTraceSteps(steps, groupViewMode).length > 0 || isLive || metaLine !== null;\n if (!hasGroup) return consentCard;\n\n return (\n <div\n className={classNames(styles.turnTrace, styles.anchor, isCompact && styles.turnTraceCompact, className)}\n data-testid=\"conversation-turn-trace\"\n data-view-mode={shownViewMode}\n data-phase={phase}\n data-trace-turn-number={turn?.turnNumber ?? undefined}\n >\n {planRow}\n <ToolStepGroup\n // The fold starts over when the turn ends: open while it runs, then as the mode says (closed in normal).\n key={isLive ? \"live\" : \"done\"}\n steps={steps}\n viewMode={groupViewMode}\n durationMs={isLive ? null : totals?.durationMs}\n // The status line below says that the turn runs: the group's head stays calm and only stands open.\n defaultOpen={isLive || shownViewMode === \"summary\" ? true : undefined}\n summary={\n totals !== null && (totals.commandCount > 0 || totals.fileCount > 0 || totals.linesAdded > 0 || totals.linesRemoved > 0) ? (\n <FileChangesSummary commandCount={totals.commandCount} fileCount={totals.fileCount} linesAdded={totals.linesAdded} linesRemoved={totals.linesRemoved} />\n ) : undefined\n }\n metaLine={metaLine}\n host={boundHost}\n conversationId={conversationId}\n isCompact={isCompact}\n />\n {queuedMessagesTakenUp.map((message) => (\n <QueuedMessageChip key={message.messageId ?? message.text} text={message.text} wasTakenUp isCompact={isCompact} />\n ))}\n {consentCard}\n {statusLine}\n </div>\n );\n};\n","import type { TraceTaskPlanStepItem } from \"./trace-types\";\n\n/**\n * Where an item of the task plan stands, as the work plan draws it: done, does not apply (skipped), blocked, running\n * (the first open leaf: the step the agent works on now) or open.\n */\nexport type TaskPlanNodeState = \"done\" | \"skipped\" | \"blocked\" | \"running\" | \"open\";\n\n/** One item of the plan in its tree: its children, its state and the part of its leaves that is closed. */\nexport interface TaskPlanTreeNode {\n item: TraceTaskPlanStepItem;\n key: string;\n depth: number;\n parent: TaskPlanTreeNode | null;\n children: TaskPlanTreeNode[];\n state: TaskPlanNodeState;\n /** Leaves below the node (the node itself for a leaf) that are done or do not apply, and all of them. */\n closedLeafCount: number;\n leafCount: number;\n}\n\n/** The plan as a tree, with the counts the work plan shows. */\nexport interface TaskPlanTree {\n roots: TaskPlanTreeNode[];\n /** Every node in plan order (depth first). */\n nodes: TaskPlanTreeNode[];\n byKey: ReadonlyMap<string, TaskPlanTreeNode>;\n /** The running leaf (the first open leaf), null when none is open. */\n running: TaskPlanTreeNode | null;\n /** All leaves, the closed ones (done or does not apply), the blocked and the skipped ones. */\n leafCount: number;\n closedLeafCount: number;\n blockedLeafCount: number;\n skippedLeafCount: number;\n /** The position of the top-level item the plan works on (1-based; the count of top-level items when all are closed). */\n currentTopLevelPosition: number;\n}\n\nconst CLOSED_STATES: readonly TaskPlanNodeState[] = [\"done\", \"skipped\"];\n\n/** The status the plan shows for an item: the server's derived status, else the item's own. */\nexport const readShownStatus = (item: Pick<TraceTaskPlanStepItem, \"status\" | \"shownStatus\">): string =>\n (item.shownStatus ?? item.status ?? \"open\").toLowerCase();\n\nconst readBaseState = (status: string): Exclude<TaskPlanNodeState, \"running\"> => {\n if (status === \"done\" || status === \"completed\") return \"done\";\n if (status === \"not_applicable\" || status === \"skipped\" || status === \"cancelled\") return \"skipped\";\n if (status === \"blocked\") return \"blocked\";\n return \"open\";\n};\n\n/**\n * Builds the tree of a plan's items (in plan order, each with its `depth`): a node's parent is the nearest item before\n * it with a smaller depth. A container whose server sends no derived status derives its state from its children\n * (blocked when a child is blocked and none open, done when all are closed). The first open leaf outside a closed\n * container is the running step.\n */\nexport const buildTaskPlanTree = (items: readonly TraceTaskPlanStepItem[]): TaskPlanTree => {\n const roots: TaskPlanTreeNode[] = [];\n const nodes: TaskPlanTreeNode[] = [];\n const byKey = new Map<string, TaskPlanTreeNode>();\n const stack: TaskPlanTreeNode[] = [];\n items.forEach((item, position) => {\n const depth = Math.max(0, item.depth ?? 0);\n while (stack.length > 0 && stack[stack.length - 1].depth >= depth) stack.pop();\n const parent = stack.length > 0 ? stack[stack.length - 1] : null;\n const key = item.key || item.numberPath || String(position);\n const node: TaskPlanTreeNode = {\n item,\n key,\n depth: parent ? parent.depth + 1 : 0,\n parent,\n children: [],\n state: readBaseState(readShownStatus(item)),\n closedLeafCount: 0,\n leafCount: 0,\n };\n (parent ? parent.children : roots).push(node);\n nodes.push(node);\n if (!byKey.has(key)) byKey.set(key, node);\n stack.push(node);\n });\n const settle = (node: TaskPlanTreeNode): void => {\n if (node.children.length === 0) {\n node.leafCount = 1;\n node.closedLeafCount = CLOSED_STATES.includes(node.state) ? 1 : 0;\n return;\n }\n node.children.forEach(settle);\n node.leafCount = node.children.reduce((sum, child) => sum + child.leafCount, 0);\n node.closedLeafCount = node.children.reduce((sum, child) => sum + child.closedLeafCount, 0);\n if (node.item.shownStatus != null || node.state !== \"open\") return;\n // an older server: derive the container from its children\n const childStates = node.children.map((child) => child.state);\n if (childStates.every((state) => CLOSED_STATES.includes(state))) {\n node.state = childStates.includes(\"done\") ? \"done\" : \"skipped\";\n } else if (childStates.includes(\"blocked\") && !childStates.includes(\"open\")) {\n node.state = \"blocked\";\n }\n };\n // an open item below a blocked or not applicable container is covered by that container's verdict\n const cover = (node: TaskPlanTreeNode): void => {\n for (const child of node.children) {\n if ((node.state === \"blocked\" || node.state === \"skipped\") && child.state === \"open\" && child.item.shownStatus == null) child.state = node.state;\n cover(child);\n }\n };\n roots.forEach(cover);\n roots.forEach(settle);\n // the running step: the first open leaf; its open ancestors run too\n const running = nodes.find((node) => node.children.length === 0 && node.state === \"open\") ?? null;\n for (let node: TaskPlanTreeNode | null = running; node !== null; node = node.parent) {\n if (node.state === \"open\") node.state = \"running\";\n }\n const leaves = nodes.filter((node) => node.children.length === 0);\n const openTopLevelPosition = roots.findIndex((root) => !CLOSED_STATES.includes(root.state));\n return {\n roots,\n nodes,\n byKey,\n running,\n leafCount: leaves.length,\n closedLeafCount: leaves.filter((node) => CLOSED_STATES.includes(node.state)).length,\n blockedLeafCount: leaves.filter((node) => node.state === \"blocked\").length,\n skippedLeafCount: leaves.filter((node) => node.state === \"skipped\").length,\n currentTopLevelPosition: openTopLevelPosition === -1 ? roots.length : openTopLevelPosition + 1,\n };\n};\n\n/**\n * The containers the work plan opens at first: every container that is not closed (the path of the running and of a\n * blocked step among them); a done or skipped branch stays folded.\n */\nexport const readDefaultExpandedKeys = (tree: TaskPlanTree): Set<string> =>\n new Set(tree.nodes.filter((node) => node.children.length > 0 && !CLOSED_STATES.includes(node.state)).map((node) => node.key));\n\n/** The nodes a reader sees with the given containers open, in plan order. */\nexport const readVisibleNodes = (tree: TaskPlanTree, expandedKeys: ReadonlySet<string>): TaskPlanTreeNode[] => {\n const visible: TaskPlanTreeNode[] = [];\n const walk = (level: TaskPlanTreeNode[]) => {\n for (const node of level) {\n visible.push(node);\n if (node.children.length > 0 && expandedKeys.has(node.key)) walk(node.children);\n }\n };\n walk(tree.roots);\n return visible;\n};\n\n/** The item before and after a node in plan order (any depth), for the arrows of the detail view. */\nexport const readNeighbours = (tree: TaskPlanTree, key: string): { previous: TaskPlanTreeNode | null; next: TaskPlanTreeNode | null } => {\n const position = tree.nodes.findIndex((node) => node.key === key);\n if (position === -1) return { previous: null, next: null };\n return { previous: tree.nodes[position - 1] ?? null, next: tree.nodes[position + 1] ?? null };\n};\n","import type { CSSProperties, ReactNode } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport type { TaskPlanNodeState, TaskPlanTree, TaskPlanTreeNode } from \"./task-plan-tree\";\nimport { readNeighbours } from \"./task-plan-tree\";\nimport type { TraceTaskPlanItemSource, TraceTaskPlanRejection } from \"./trace-collect\";\nimport { readTraceMoment, useTraceFormat } from \"./trace-format\";\nimport styles from \"./task-plan.module.scss\";\n\n/** What the detail view shows: the plan, or one item by its key. */\nexport type TaskPlanDetailTarget = { kind: \"plan\" } | { kind: \"item\"; key: string };\n\nexport interface TaskPlanDrawerProps {\n target: TaskPlanDetailTarget;\n tree: TaskPlanTree;\n /** The plan's title: the request it was made for. */\n title?: string | null;\n /** Per item key, the plan update that last changed it and the one it first appeared in. */\n itemSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n itemFirstSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n /** Debug level: what refused plan calls told the agent. */\n rejections?: readonly TraceTaskPlanRejection[];\n /** When the plan was last updated (a server date-time). */\n updatedAt?: string | null;\n onNavigate: (target: TaskPlanDetailTarget) => void;\n onClose: () => void;\n /** Leads to the plan update in the trace; without it the times are plain text. */\n onShowSource?: (node: TaskPlanTreeNode, source: TraceTaskPlanItemSource) => void;\n}\n\nconst STATE_LABELS: Readonly<Record<TaskPlanNodeState, () => string>> = {\n done: () => translateText(\"Done\"),\n skipped: () => translateText(\"Does not apply\", undefined, \"plan-item-state\"),\n blocked: () => translateText(\"Blocked\", undefined, \"plan-item-state\"),\n running: () => translateText(\"In progress\"),\n open: () => translateText(\"Not started\"),\n};\n\n/** The state mark of an item: a ring, filled to the closed share for an open container. */\nexport const TaskPlanMark = ({ node }: { node: TaskPlanTreeNode }) => {\n const { state } = node;\n const isPart = node.children.length > 0 && state === \"open\" && node.closedLeafCount > 0;\n const style = isPart ? ({ \"--agents-task-plan-part\": `${Math.round((node.closedLeafCount / node.leafCount) * 100)}%` } as CSSProperties) : undefined;\n return (\n <span\n className={classNames(\n styles.mark,\n state === \"done\" && styles.markDone,\n state === \"skipped\" && styles.markSkipped,\n state === \"blocked\" && styles.markBlocked,\n state === \"running\" && styles.markRunning,\n isPart && styles.markPart,\n )}\n style={style}\n role=\"img\"\n aria-label={STATE_LABELS[state]()}\n >\n {state === \"done\" ? <Icon name=\"stepDone\" pixelSize={11} /> : null}\n {state === \"skipped\" ? <Icon name=\"dash\" pixelSize={11} /> : null}\n {state === \"blocked\" ? <Icon name=\"exclamation\" pixelSize={11} /> : null}\n </span>\n );\n};\n\n/** The leaves of nodes as small segments, one per leaf, coloured by its state. */\nexport const TaskPlanSegments = ({ nodes, isSmall }: { nodes: readonly TaskPlanTreeNode[]; isSmall?: boolean }) => {\n const leaves: TaskPlanTreeNode[] = [];\n const collect = (level: readonly TaskPlanTreeNode[]) => level.forEach((node) => (node.children.length > 0 ? collect(node.children) : leaves.push(node)));\n collect(nodes);\n return (\n <span className={classNames(styles.segments, isSmall && styles.segmentsSmall)} aria-hidden=\"true\">\n {leaves.map((leaf) => (\n <span\n key={leaf.key}\n className={classNames(\n styles.segment,\n leaf.state === \"done\" && styles.segmentDone,\n leaf.state === \"skipped\" && styles.segmentSkipped,\n leaf.state === \"blocked\" && styles.segmentBlocked,\n leaf.state === \"running\" && styles.segmentRunning,\n )}\n />\n ))}\n </span>\n );\n};\n\nconst Section = (props: { icon?: Parameters<typeof Icon>[0][\"name\"]; title: string; isDebug?: boolean; tone?: \"running\" | \"blocked\" | \"done\" | \"criterion\"; extra?: ReactNode; children: ReactNode }) => (\n <section\n className={classNames(\n styles.section,\n props.tone === \"running\" && styles.sectionRunning,\n props.tone === \"blocked\" && styles.sectionBlocked,\n props.tone === \"done\" && styles.sectionDone,\n props.tone === \"criterion\" && styles.sectionCriterion,\n )}\n >\n <h4 className={styles.sectionHead}>\n {props.icon ? <Icon name={props.icon} pixelSize={13} /> : null}\n {props.title}\n {props.isDebug ? <span className={classNames(styles.chip, styles.chipDebug)}>{translateText(\"Debug\")}</span> : null}\n {props.extra}\n </h4>\n {props.children}\n </section>\n);\n\n/** \"Turn 3 · 10:06\" for a plan update. */\nconst useDescribeSource = () => {\n const format = useTraceFormat();\n return (source: TraceTaskPlanItemSource): string => {\n const moment = readTraceMoment(source.startedAt ?? null);\n return moment === null\n ? translateText(\"Turn %number%\", { number: format.number(source.turnNumber) })\n : translateText(\"Turn %number% · %time%\", { number: format.number(source.turnNumber), time: format.time(moment) });\n };\n};\n\n/** The note of an item's state; a container that has none names the step that runs or blocks below it. */\nconst readStateNote = (node: TaskPlanTreeNode): string | null => {\n const note = node.item.statusNote ?? null;\n if (note) return note;\n if (node.children.length > 0) {\n const leaf = findLeafInState(node, \"blocked\") ?? findLeafInState(node, \"running\");\n if (leaf) return `${leaf.item.numberPath ?? leaf.key} ${leaf.item.title}${leaf.item.statusNote ? `: ${leaf.item.statusNote}` : \"\"}`;\n }\n if (node.state === \"running\") return translateText(\"The agent works on this step now.\");\n if (node.state === \"open\") return translateText(\"Not started yet.\");\n return null;\n};\n\nconst findLeafInState = (node: TaskPlanTreeNode, state: TaskPlanNodeState): TaskPlanTreeNode | null => {\n if (node.children.length === 0) return node.state === state ? node : null;\n for (const child of node.children) {\n const leaf = findLeafInState(child, state);\n if (leaf) return leaf;\n }\n return null;\n};\n\nconst STATE_NOTE_TITLES: Readonly<Record<TaskPlanNodeState, () => string>> = {\n done: () => translateText(\"Result\"),\n skipped: () => translateText(\"Why it does not apply\"),\n blocked: () => translateText(\"Reason\"),\n running: () => translateText(\"Now\"),\n open: () => translateText(\"Status\"),\n};\n\nconst ItemDetail = (props: TaskPlanDrawerProps & { node: TaskPlanTreeNode }) => {\n const { node, onNavigate, itemSources, itemFirstSources, rejections, onShowSource } = props;\n const describeSource = useDescribeSource();\n const { item } = node;\n const note = readStateNote(node);\n const tone = node.state === \"running\" ? \"running\" : node.state === \"blocked\" ? \"blocked\" : node.state === \"done\" ? \"done\" : undefined;\n const firstSource = itemFirstSources?.[node.key];\n const lastSource = itemSources?.[node.key];\n const itemRejections = (rejections ?? []).filter((rejection) => rejection.itemKey === node.key || rejection.itemKey === item.numberPath);\n const isDebugShown = item.instruction != null || (item.declarations?.length ?? 0) > 0 || (item.skillNames?.length ?? 0) > 0 || itemRejections.length > 0;\n const subtaskCount = node.children.length;\n return (\n <>\n <div className={styles.detailHead}>\n <span className={styles.eyebrow}>\n {translateText(\"Step %number%\", { number: item.numberPath ?? node.key })}\n {node.parent ? (\n <>\n <span aria-hidden=\"true\">·</span>\n <span>{translateText(\"part of\")}</span>\n <button type=\"button\" className={styles.eyebrowLink} onClick={() => onNavigate({ kind: \"item\", key: node.parent!.key })}>\n {`${node.parent.item.numberPath ?? node.parent.key} ${node.parent.item.title}`}\n </button>\n </>\n ) : null}\n {subtaskCount > 0 ? (\n <>\n <span aria-hidden=\"true\">·</span>\n <span>\n {subtaskCount === 1\n ? translateText(\"%count% subtasks\", { count: subtaskCount }, \"plan-subtasks-one\")\n : translateText(\"%count% subtasks\", { count: subtaskCount }, \"plan-subtasks-other\")}\n </span>\n </>\n ) : null}\n </span>\n <h3 className={styles.detailTitle} data-testid=\"trace-task-plan-detail-title\">\n {item.title}\n </h3>\n </div>\n\n <Section title={`${STATE_LABELS[node.state]()} · ${STATE_NOTE_TITLES[node.state]()}`} tone={tone}>\n {note ? <p className={styles.text}>{note}</p> : null}\n {item.requiresUserAction || item.retryable || item.isPreResolvedAtSeed ? (\n <div className={styles.flags}>\n {item.requiresUserAction ? <span className={classNames(styles.chip, styles.chipOwner)}>{translateText(\"Waits for you\")}</span> : null}\n {item.retryable ? <span className={styles.chip}>{translateText(\"Can be tried again\")}</span> : null}\n {item.isPreResolvedAtSeed ? <span className={styles.chip}>{translateText(\"Already done at the start\")}</span> : null}\n </div>\n ) : null}\n </Section>\n\n {subtaskCount > 0 ? (\n <Section\n icon=\"steps\"\n title={translateText(\"Subtasks\")}\n extra={<span className={styles.chip}>{`${node.closedLeafCount}/${node.leafCount}`}</span>}\n >\n <TaskPlanSegments nodes={node.children} />\n <ul className={styles.miniList}>\n {node.children.map((child) => (\n <li key={child.key}>\n <button type=\"button\" className={styles.miniRow} onClick={() => onNavigate({ kind: \"item\", key: child.key })}>\n <TaskPlanMark node={child} />\n <span className={styles.number}>{child.item.numberPath ?? child.key}</span>\n <span className={styles.miniTitle}>{child.item.title}</span>\n <span className={styles.miniState}>\n {child.children.length > 0 ? `${child.closedLeafCount}/${child.leafCount}` : STATE_LABELS[child.state]()}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </Section>\n ) : null}\n\n <Section\n icon=\"check\"\n title={translateText(\"Done when\")}\n tone=\"criterion\"\n extra={\n node.children.length === 0 && item.closesItself ? (\n <span className={classNames(styles.chip, styles.chipRunning)}>{translateText(\"Closes itself\")}</span>\n ) : null\n }\n >\n <p className={styles.text}>\n {node.children.length > 0\n ? translateText(\"every subtask is done or does not apply. The step then closes itself.\")\n : item.closesItself\n ? translateText(\"the record shows it: a completed call, a widget or a delivered answer. The platform ticks it off, not the agent.\")\n : translateText(\"the agent ticks it off with what it produced.\")}\n </p>\n {item.doneCriterion ? (\n <dl className={styles.facts}>\n <dt>{translateText(\"Criterion\")}</dt>\n <dd className={styles.mono}>{item.doneCriterion}</dd>\n </dl>\n ) : null}\n </Section>\n\n <Section icon=\"clock\" title={translateText(\"Origin and times\")}>\n <dl className={styles.facts}>\n <dt>{translateText(\"Origin\", undefined, \"task-plan-origin\")}</dt>\n <dd>{item.isSeeded ? translateText(\"Seeded from the purpose\") : translateText(\"Added by the agent\")}</dd>\n {item.customerProgressStepKey ? (\n <>\n <dt>{translateText(\"Customer step\")}</dt>\n <dd className={styles.mono}>{item.customerProgressStepKey}</dd>\n </>\n ) : null}\n {firstSource ? (\n <>\n <dt>{translateText(\"Created\")}</dt>\n <dd>{describeSource(firstSource)}</dd>\n </>\n ) : null}\n {lastSource ? (\n <>\n <dt>{translateText(\"Last changed\")}</dt>\n <dd>\n {describeSource(lastSource)}\n {onShowSource ? (\n <>\n {\" · \"}\n <button\n type=\"button\"\n className={styles.link}\n data-testid=\"trace-task-plan-item-link\"\n title={translateText(\"Show the step that last changed this item\")}\n onClick={() => onShowSource(node, lastSource)}\n >\n {translateText(\"in the trace\")}\n </button>\n </>\n ) : null}\n </dd>\n </>\n ) : null}\n {item.wasClosedByPlatform ? (\n <>\n <dt>{translateText(\"Closed by\")}</dt>\n <dd>{translateText(\"the platform\")}</dd>\n </>\n ) : null}\n </dl>\n </Section>\n\n {isDebugShown ? (\n <>\n {item.instruction ? (\n <Section icon=\"ai\" title={translateText(\"Instruction to the agent\")} isDebug>\n <p className={classNames(styles.text, styles.mono)}>{item.instruction}</p>\n </Section>\n ) : null}\n {(item.declarations?.length ?? 0) > 0 || (item.skillNames?.length ?? 0) > 0 || item.evidenceMessageIndex != null || item.platformResolvedAtMessageIndex != null ? (\n <Section icon=\"code\" title={translateText(\"Fields\")} isDebug>\n <dl className={styles.facts}>\n {(item.declarations ?? []).map((declaration) => (\n <FactRow key={declaration.name} name={declaration.name} value={declaration.value} />\n ))}\n {(item.skillNames?.length ?? 0) > 0 ? <FactRow name=\"skillNames\" value={(item.skillNames ?? []).join(\", \")} /> : null}\n {item.evidenceMessageIndex != null ? <FactRow name=\"evidenceMessageIndex\" value={String(item.evidenceMessageIndex)} /> : null}\n {item.platformResolvedAtMessageIndex != null ? (\n <FactRow name=\"platformResolvedAtMessageIndex\" value={String(item.platformResolvedAtMessageIndex)} />\n ) : null}\n </dl>\n </Section>\n ) : null}\n {itemRejections.length > 0 ? <RejectionsSection rejections={itemRejections} /> : null}\n </>\n ) : null}\n </>\n );\n};\n\nconst FactRow = ({ name, value }: { name: string; value: string }) => (\n <>\n <dt className={styles.mono}>{name}</dt>\n <dd className={styles.mono}>{value}</dd>\n </>\n);\n\nconst RejectionsSection = ({ rejections }: { rejections: readonly TraceTaskPlanRejection[] }) => {\n const describeSource = useDescribeSource();\n return (\n <Section icon=\"exclamation\" title={translateText(\"Rejected plan changes\")} isDebug>\n {rejections.map((rejection, position) => (\n <div key={`${rejection.source.stepKey}:${position}`} className={styles.rejection}>\n <span className={styles.quiet}>{[describeSource(rejection.source), rejection.toolName].filter(Boolean).join(\" · \")}</span>\n <span className={classNames(styles.text, styles.mono)}>{rejection.line}</span>\n </div>\n ))}\n </Section>\n );\n};\n\nconst PlanDetail = (props: TaskPlanDrawerProps) => {\n const { tree, title, onNavigate, itemFirstSources, itemSources, rejections } = props;\n const format = useTraceFormat();\n const describeSource = useDescribeSource();\n const isFinished = tree.leafCount > 0 && tree.closedLeafCount + tree.blockedLeafCount === tree.leafCount && tree.blockedLeafCount === 0;\n const openCount = tree.leafCount - tree.closedLeafCount - tree.blockedLeafCount;\n const doneCount = tree.closedLeafCount - tree.skippedLeafCount;\n const sources = Object.values(itemFirstSources ?? {});\n const firstSource = sources.reduce<TraceTaskPlanItemSource | null>(\n (earliest, source) => (earliest === null || source.turnNumber < earliest.turnNumber ? source : earliest),\n null,\n );\n const lastSource = Object.values(itemSources ?? {}).reduce<TraceTaskPlanItemSource | null>(\n (latest, source) => (latest === null || source.turnNumber >= latest.turnNumber ? source : latest),\n null,\n );\n const seededCount = tree.nodes.filter((node) => node.item.isSeeded).length;\n const addedNodes = seededCount > 0 ? tree.nodes.filter((node) => !node.item.isSeeded) : [];\n const leaves = tree.nodes.filter((node) => node.children.length === 0);\n const share = tree.leafCount > 0 ? Math.round((tree.closedLeafCount / tree.leafCount) * 100) : 0;\n return (\n <>\n <div className={styles.detailHead}>\n <span className={styles.eyebrow}>{translateText(\"Work plan\")}</span>\n <h3 className={styles.detailTitle} data-testid=\"trace-task-plan-detail-title\">\n {title || translateText(\"Plan\")}\n </h3>\n </div>\n <section className={styles.section}>\n <div className={styles.head}>\n <span className={styles.ring} style={{ \"--agents-task-plan-part\": `${share}%` } as CSSProperties}>\n <b>{`${tree.closedLeafCount}/${tree.leafCount}`}</b>\n </span>\n <div className={styles.headText} style={{ gap: \"0.375rem\" }}>\n <b>{translateText(\"%done% of %total% steps\", { done: format.number(tree.closedLeafCount), total: format.number(tree.leafCount) })}</b>\n <div className={styles.flags}>\n <span className={classNames(styles.chip, isFinished ? styles.chipDone : tree.blockedLeafCount > 0 ? styles.chipBlocked : styles.chipRunning)}>\n {isFinished ? translateText(\"Finished\") : tree.blockedLeafCount > 0 ? STATE_LABELS.blocked() : STATE_LABELS.running()}\n </span>\n {doneCount > 0 ? <span className={styles.chip}>{translateText(\"%count% done\", { count: format.number(doneCount) })}</span> : null}\n {tree.skippedLeafCount > 0 ? (\n <span className={styles.chip}>{translateText(\"%count% do not apply\", { count: format.number(tree.skippedLeafCount) })}</span>\n ) : null}\n {openCount > 0 ? <span className={styles.chip}>{translateText(\"%count% open\", { count: format.number(openCount) })}</span> : null}\n </div>\n </div>\n </div>\n <TaskPlanSegments nodes={tree.roots} />\n </section>\n {isFinished ? (\n <Section icon=\"check\" title={translateText(\"Result\")}>\n {leaves.map((leaf) => (\n <div key={leaf.key} className={styles.outcome}>\n <TaskPlanMark node={leaf} />\n <span>\n <b>{leaf.item.title}</b>\n {leaf.item.statusNote ? <span className={styles.quiet}>{` · ${leaf.item.statusNote}`}</span> : null}\n </span>\n </div>\n ))}\n </Section>\n ) : (\n <Section icon=\"steps\" title={translateText(\"Steps\")}>\n <ul className={styles.miniList}>\n {tree.roots.map((root) => (\n <li key={root.key}>\n <button type=\"button\" className={styles.miniRow} onClick={() => onNavigate({ kind: \"item\", key: root.key })}>\n <TaskPlanMark node={root} />\n <span className={styles.number}>{root.item.numberPath ?? root.key}</span>\n <span className={styles.miniTitle}>{root.item.title}</span>\n <span className={styles.miniState}>\n {root.children.length > 0 ? `${root.closedLeafCount}/${root.leafCount}` : STATE_LABELS[root.state]()}\n </span>\n </button>\n </li>\n ))}\n </ul>\n </Section>\n )}\n <Section icon=\"clock\" title={translateText(\"Times and origin\")}>\n <dl className={styles.facts}>\n {firstSource ? (\n <>\n <dt>{translateText(\"Created\")}</dt>\n <dd>{describeSource(firstSource)}</dd>\n </>\n ) : null}\n {lastSource ? (\n <>\n <dt>{translateText(\"Last changed\")}</dt>\n <dd>{describeSource(lastSource)}</dd>\n </>\n ) : null}\n <dt>{translateText(\"Origin\", undefined, \"task-plan-origin\")}</dt>\n <dd>\n {seededCount > 0\n ? translateText(\"Seeded from the purpose: %seeded% of %total% items\", { seeded: format.number(seededCount), total: format.number(tree.nodes.length) })\n : translateText(\"Made by the agent\")}\n </dd>\n {addedNodes.length > 0 ? (\n <>\n <dt>{translateText(\"Added by the agent\")}</dt>\n <dd>{addedNodes.map((node) => `${node.item.numberPath ?? node.key} ${node.item.title}`).join(\", \")}</dd>\n </>\n ) : null}\n </dl>\n </Section>\n {(rejections?.length ?? 0) > 0 ? <RejectionsSection rejections={rejections ?? []} /> : null}\n </>\n );\n};\n\n/**\n * The detail view of the work plan, for the plan or for one item. The plan: its goal (the request it was made for),\n * its progress with the counts, its result once finished (every step with its note), when it was made and changed and\n * where its items came from. An item: its state with the note (what was produced, why it is blocked, why it does not\n * apply) and whether it waits for the owner, its subtasks with their part progress, when it is done (by its subtasks,\n * by the record, by the agent's tick), its origin and times; at the debug level the agent's instruction, the seeded\n * declarations and the rejected plan changes that name it. The head leads back to the plan, up to the parent and to the\n * item before and after it in the plan.\n */\nexport const TaskPlanDrawer = (props: TaskPlanDrawerProps) => {\n const { target, tree, onNavigate, onClose } = props;\n const node = target.kind === \"item\" ? tree.byKey.get(target.key) ?? null : null;\n const neighbours = node ? readNeighbours(tree, node.key) : { previous: null, next: null };\n return (\n <aside className={styles.detail} data-testid=\"trace-task-plan-detail\" aria-label={translateText(\"Details\")}>\n <div className={styles.detailNav}>\n {node ? (\n <button type=\"button\" className={styles.pill} onClick={() => onNavigate({ kind: \"plan\" })}>\n <Icon name=\"arrowLeft\" pixelSize={13} />\n {translateText(\"Plan\")}\n </button>\n ) : null}\n <span className={styles.grow} />\n {node?.parent ? (\n <button\n type=\"button\"\n className={styles.pill}\n title={translateText(\"Parent step\")}\n onClick={() => onNavigate({ kind: \"item\", key: node.parent!.key })}\n >\n <Icon name=\"arrowUp\" pixelSize={13} />\n {node.parent.item.numberPath ?? node.parent.key}\n </button>\n ) : null}\n {node ? (\n <>\n <button\n type=\"button\"\n className={classNames(styles.pill, styles.pillSquare)}\n title={translateText(\"Previous step\")}\n aria-label={translateText(\"Previous step\")}\n disabled={neighbours.previous === null}\n onClick={() => neighbours.previous && onNavigate({ kind: \"item\", key: neighbours.previous.key })}\n >\n <Icon name=\"caretUp\" pixelSize={13} />\n </button>\n <button\n type=\"button\"\n className={classNames(styles.pill, styles.pillSquare)}\n title={translateText(\"Next step\")}\n aria-label={translateText(\"Next step\")}\n disabled={neighbours.next === null}\n onClick={() => neighbours.next && onNavigate({ kind: \"item\", key: neighbours.next.key })}\n >\n <Icon name=\"caretDown\" pixelSize={13} />\n </button>\n </>\n ) : null}\n <button\n type=\"button\"\n className={classNames(styles.pill, styles.pillSquare)}\n title={translateText(\"Close\")}\n aria-label={translateText(\"Close\")}\n onClick={onClose}\n >\n <Icon name=\"close\" pixelSize={13} />\n </button>\n </div>\n {node ? <ItemDetail {...props} node={node} /> : <PlanDetail {...props} />}\n </aside>\n );\n};\n","import { type ReactNode, useEffect, useMemo, useState } from \"react\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Icon } from \"../../provider/components\";\nimport { translateText } from \"../../provider/environment\";\nimport { describeTaskPlanProgress, readTaskPlanCounts } from \"./task-plan-counts\";\nimport { type TaskPlanTreeNode, buildTaskPlanTree, readDefaultExpandedKeys, readVisibleNodes } from \"./task-plan-tree\";\nimport { type TaskPlanDetailTarget, TaskPlanDrawer, TaskPlanMark, TaskPlanSegments } from \"./TaskPlanDrawer\";\nimport { useTraceFormat } from \"./trace-format\";\nimport type { TraceTaskPlanItemSource, TraceTaskPlanRejection } from \"./trace-collect\";\nimport type { TraceTaskPlanStepItem } from \"./trace-types\";\nimport styles from \"./task-plan.module.scss\";\n\nexport interface TaskPlanPaneProps {\n /** The plan's own title (the request it was made for); it heads the pane. */\n title?: string | null;\n /** The items in the plan's order, each with its `depth`; without them the pane shows the counts alone. */\n items: TraceTaskPlanStepItem[];\n /**\n * Top-level items of the plan, how many of them are done or do not apply, and how many are blocked: the counts of a\n * plan whose items the reader does not have. With items the pane counts their leaves.\n */\n itemCount?: number | null;\n doneCount?: number | null;\n blockedCount?: number | null;\n /** A quiet line under the title (the turn that last updated the plan). */\n note?: ReactNode;\n /**\n * Per item key, the plan update that last changed the item (`TraceTaskPlanSnapshot.itemSources`) and the one it first\n * appeared in: the times of the detail view. With `onSelectItem` the detail view leads to that step in the trace.\n */\n itemSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n itemFirstSources?: Readonly<Record<string, TraceTaskPlanItemSource>>;\n onSelectItem?: (item: TraceTaskPlanStepItem, source: TraceTaskPlanItemSource) => void;\n /** Debug level: what refused plan calls told the agent (`TraceTaskPlanSnapshot.rejections`). */\n rejections?: readonly TraceTaskPlanRejection[];\n /** The detail view a host opens the pane on (a deep link); default none. */\n defaultDetail?: TaskPlanDetailTarget | null;\n className?: string;\n}\n\n/** The state of a row as `data-plan-item-state` names it (the running step is `next`, a skipped one `skipped`). */\nconst ROW_STATE_ATTRIBUTES = { done: \"done\", skipped: \"skipped\", blocked: \"blocked\", running: \"next\", open: \"open\" } as const;\n\nconst TaskPlanRow = (props: {\n node: TaskPlanTreeNode;\n isExpanded: boolean;\n isSelected: boolean;\n waitsForOwner: boolean;\n onToggle: (key: string) => void;\n onOpen: (key: string) => void;\n}) => {\n const { node, isExpanded, isSelected, waitsForOwner, onToggle, onOpen } = props;\n const { item, state } = node;\n const isContainer = node.children.length > 0;\n const indent = node.depth * 22;\n const note = !isContainer && (state === \"running\" || state === \"blocked\") ? item.statusNote : isContainer && !isExpanded ? item.statusNote : null;\n return (\n <li\n className={classNames(\n styles.row,\n !isContainer && state === \"running\" && styles.rowRunning,\n !isContainer && state === \"blocked\" && styles.rowBlocked,\n (state === \"done\" || state === \"skipped\") && styles.rowClosed,\n state === \"skipped\" && styles.rowSkipped,\n isSelected && styles.rowSelected,\n )}\n style={{ paddingLeft: `${indent}px` }}\n data-plan-item-state={ROW_STATE_ATTRIBUTES[state]}\n data-plan-item-key={node.key}\n aria-current={state === \"running\" && !isContainer ? \"step\" : undefined}\n >\n {Array.from({ length: node.depth }, (_, level) => (\n <span key={level} className={styles.guide} style={{ left: `${level * 22 + 11}px` }} aria-hidden=\"true\" />\n ))}\n {isContainer ? (\n <button\n type=\"button\"\n className={styles.toggle}\n aria-expanded={isExpanded}\n aria-label={isExpanded ? translateText(\"Fold the subtasks\") : translateText(\"Show the subtasks\")}\n onClick={() => onToggle(node.key)}\n >\n <Icon name={isExpanded ? \"chevronDown\" : \"chevronRight\"} pixelSize={13} />\n </button>\n ) : (\n <span className={styles.toggleSpacer} />\n )}\n <button type=\"button\" className={styles.rowButton} onClick={() => onOpen(node.key)} data-testid=\"trace-task-plan-row\">\n <TaskPlanMark node={node} />\n {item.numberPath ? <span className={styles.number}>{item.numberPath}</span> : null}\n <span className={styles.rowText}>\n <span className={styles.rowTitle}>{item.title}</span>\n {note ? <span className={styles.rowNote}>{note}</span> : null}\n </span>\n {isContainer ? (\n <>\n <span className={styles.part}>{`${node.closedLeafCount}/${node.leafCount}`}</span>\n <TaskPlanSegments nodes={node.children} isSmall />\n </>\n ) : null}\n {!isContainer && state === \"running\" ? (\n <span className={classNames(styles.chip, styles.chipRunning)}>\n {waitsForOwner ? translateText(\"Up next\", undefined, \"plan-item-state\") : translateText(\"In progress\")}\n </span>\n ) : null}\n {!isContainer && state === \"blocked\" && item.requiresUserAction ? (\n <span className={classNames(styles.chip, styles.chipOwner)}>{translateText(\"Waits for you\")}</span>\n ) : null}\n {!isContainer && state === \"blocked\" && !item.requiresUserAction ? (\n <span className={classNames(styles.chip, styles.chipBlocked)}>{translateText(\"Blocked\", undefined, \"plan-item-state\")}</span>\n ) : null}\n {!isContainer && state === \"skipped\" ? <span className={styles.chip}>{translateText(\"Does not apply\", undefined, \"plan-item-state\")}</span> : null}\n <Icon name=\"chevronRight\" pixelSize={12} className={styles.go} />\n </button>\n </li>\n );\n};\n\n/**\n * The task plan of a conversation as it stands, for a pane beside the chat. Its head names the plan and its progress\n * over all steps (\"6 of 9 done · step 2 of 3\", a segment per step), then the plan as a tree: every container shows its\n * part progress (\"4/5\") and folds; the path of the running step and of a blocked one is open, closed branches are\n * folded. Every item shows its state (done, does not apply, blocked — \"waits for you\" when only the owner can lift it —,\n * in progress or not started) and the note of a running or blocked step. A click on an item opens its detail view,\n * \"Plan details\" the plan's ({@link TaskPlanDrawer}): beside the tree in a wide pane, in its place in a narrow one.\n */\nexport const TaskPlanPane = (props: TaskPlanPaneProps) => {\n const { title, items, note, itemSources, itemFirstSources, onSelectItem, rejections, className } = props;\n const format = useTraceFormat();\n const tree = useMemo(() => buildTaskPlanTree(items), [items]);\n const defaultExpandedKeys = useMemo(() => readDefaultExpandedKeys(tree), [tree]);\n // the reader's own folding wins over the default per container\n const [toggledKeys, setToggledKeys] = useState<ReadonlySet<string>>(() => new Set());\n const [detail, setDetail] = useState<TaskPlanDetailTarget | null>(props.defaultDetail ?? null);\n const expandedKeys = useMemo(() => {\n const keys = new Set(defaultExpandedKeys);\n toggledKeys.forEach((key) => (keys.has(key) ? keys.delete(key) : keys.add(key)));\n return keys;\n }, [defaultExpandedKeys, toggledKeys]);\n // an item shown in the detail view that leaves the plan closes the view\n useEffect(() => {\n if (detail?.kind === \"item\" && !tree.byKey.has(detail.key)) setDetail(null);\n }, [detail, tree]);\n\n const counts =\n items.length > 0\n ? { total: tree.leafCount, done: tree.closedLeafCount, blocked: tree.blockedLeafCount, open: tree.leafCount - tree.closedLeafCount - tree.blockedLeafCount }\n : readTaskPlanCounts({ itemCount: props.itemCount, doneItemCount: props.doneCount, blockedItemCount: props.blockedCount, items });\n const progressText = describeTaskPlanProgress(counts, format);\n const visibleNodes = readVisibleNodes(tree, expandedKeys);\n const waitsForOwner = tree.nodes.some((node) => node.children.length === 0 && node.state === \"blocked\" && node.item.requiresUserAction);\n const selectedKey = detail?.kind === \"item\" ? detail.key : null;\n const isFinished = counts.total > 0 && counts.done === counts.total;\n const toggle = (key: string) =>\n setToggledKeys((previous) => {\n const next = new Set(previous);\n if (next.has(key)) next.delete(key);\n else next.add(key);\n return next;\n });\n const openItem = (key: string) => {\n // the path of an item opened in the detail view is unfolded in the tree\n setDetail({ kind: \"item\", key });\n const node = tree.byKey.get(key);\n const foldedAncestors: string[] = [];\n for (let ancestor = node?.parent ?? null; ancestor !== null; ancestor = ancestor.parent) {\n if (!expandedKeys.has(ancestor.key)) foldedAncestors.push(ancestor.key);\n }\n if (foldedAncestors.length === 0) return;\n setToggledKeys((previous) => {\n const next = new Set(previous);\n // a folded ancestor is either one the reader folded (toggled) or one folded by default: flip it\n foldedAncestors.forEach((ancestorKey) => (next.has(ancestorKey) ? next.delete(ancestorKey) : next.add(ancestorKey)));\n return next;\n });\n };\n\n return (\n <div className={classNames(styles.pane, className)} data-testid=\"trace-task-plan-pane\">\n <div className={classNames(styles.layout, detail !== null && styles.layoutWithDetail)}>\n <div className={styles.main}>\n <div className={styles.head}>\n <div className={styles.headText}>\n {/* A model that names its plan after the whole request gives a long title: two lines, the rest as tooltip. */}\n <span className={styles.title} title={title ?? undefined}>\n {title || translateText(\"Plan\")}\n </span>\n {note ? <span className={styles.sub}>{note}</span> : null}\n </div>\n <button\n type=\"button\"\n className={classNames(styles.pill, detail?.kind === \"plan\" && styles.pillOn)}\n aria-pressed={detail?.kind === \"plan\"}\n onClick={() => setDetail(detail?.kind === \"plan\" ? null : { kind: \"plan\" })}\n data-testid=\"trace-task-plan-details\"\n >\n <Icon name=\"details\" pixelSize={14} />\n {translateText(\"Plan details\")}\n </button>\n </div>\n {counts.total > 0 ? (\n <div className={styles.progress}>\n <div className={styles.progressLine}>\n <span>{progressText}</span>\n {tree.roots.length > 1 ? (\n <span className={styles.quiet}>\n {\"· \"}\n {isFinished\n ? translateText(\"Finished\")\n : translateText(\"step %current% of %total%\", {\n current: format.number(Math.min(tree.currentTopLevelPosition, tree.roots.length)),\n total: format.number(tree.roots.length),\n })}\n </span>\n ) : null}\n <span className={styles.grow} />\n {waitsForOwner ? <span className={classNames(styles.chip, styles.chipOwner)}>{translateText(\"Waits for you\")}</span> : null}\n </div>\n {items.length > 0 ? (\n <div role=\"progressbar\" aria-valuemin={0} aria-valuemax={counts.total} aria-valuenow={counts.done} aria-label={progressText}>\n <TaskPlanSegments nodes={tree.roots} />\n </div>\n ) : null}\n </div>\n ) : null}\n {visibleNodes.length > 0 ? (\n <ol className={styles.tree}>\n {visibleNodes.map((node) => (\n <TaskPlanRow\n key={node.key}\n node={node}\n isExpanded={expandedKeys.has(node.key)}\n isSelected={node.key === selectedKey}\n waitsForOwner={waitsForOwner}\n onToggle={toggle}\n onOpen={openItem}\n />\n ))}\n </ol>\n ) : null}\n </div>\n {detail !== null ? (\n <TaskPlanDrawer\n target={detail}\n tree={tree}\n title={title}\n itemSources={itemSources}\n itemFirstSources={itemFirstSources}\n rejections={rejections}\n onNavigate={(target) => (target.kind === \"item\" ? openItem(target.key) : setDetail(target))}\n onClose={() => setDetail(null)}\n onShowSource={onSelectItem ? (node, source) => onSelectItem(node.item, source) : undefined}\n />\n ) : null}\n </div>\n </div>\n );\n};\n","import type { TraceTaskPlanItemSource } from \"./trace-collect\";\n\n/** The attribute a step row carries with the server's id of its step: the anchor a plan item scrolls to. */\nexport const TRACE_STEP_ANCHOR_ATTRIBUTE = \"data-trace-step-anchor\";\n/** The attribute a turn's trace carries with its turn number: the fallback where the step's row is not drawn. */\nexport const TRACE_TURN_ANCHOR_ATTRIBUTE = \"data-trace-turn-number\";\n/** Set for a moment on the row (or turn) a plan item pointed to. */\nexport const TRACE_HIGHLIGHT_ATTRIBUTE = \"data-trace-highlighted\";\n\nconst HIGHLIGHT_DURATION_MS = 2000;\n\nconst escapeAttributeValue = (value: string): string => value.replace(/[\"\\\\]/g, \"\\\\$&\");\n\n/**\n * Scrolls to the row of the step that last changed a plan item and highlights it for a moment; where the view does not\n * draw the step (the summary view folds it away), to its turn. Answers whether anything was found.\n */\nexport const focusTraceStep = (root: ParentNode, source: TraceTaskPlanItemSource): boolean => {\n const stepElement =\n source.stepId !== null ? root.querySelector<HTMLElement>(`[${TRACE_STEP_ANCHOR_ATTRIBUTE}=\"${escapeAttributeValue(source.stepId)}\"]`) : null;\n const element = stepElement ?? root.querySelector<HTMLElement>(`[${TRACE_TURN_ANCHOR_ATTRIBUTE}=\"${source.turnNumber}\"]`);\n if (element === null) return false;\n element.scrollIntoView?.({ block: \"center\", behavior: \"smooth\" });\n element.setAttribute(TRACE_HIGHLIGHT_ATTRIBUTE, \"true\");\n setTimeout(() => element.removeAttribute(TRACE_HIGHLIGHT_ATTRIBUTE), HIGHLIGHT_DURATION_MS);\n return true;\n};\n","import type {\n ConversationFileChange,\n ConversationTraceEntityReference,\n ConversationTraceRecordChange,\n ConversationTraceTaskPlanItem,\n ConversationTurnTrace,\n} from \"../../contract/conversation-trace\";\nimport { translateText } from \"../../provider/environment\";\nimport type { BackgroundTask } from \"./BackgroundTasksList\";\nimport { readTaskPlanCounts } from \"./task-plan-counts\";\nimport { readTraceMoment, readTraceStepState, readTraceSubAgentState } from \"./trace-format\";\nimport { describeTraceBackgroundJob, isTraceBackgroundJobLabel } from \"./trace-labels\";\nimport type { TraceStepState } from \"./trace-types\";\n\n// What a pane beside the chat reads out of a conversation's turn traces: the files each turn changed, what the\n// conversation has running beside its turns (its sub-agents, its shell commands in the background), its task plan as\n// it stands, and the tool calls that changed or deleted records.\n\n/** The file changes of one turn. */\nexport interface TraceTurnFileChanges {\n turnNumber: number;\n turnMessageId: number | null;\n startedAt: string | null;\n /** The changes in the order the turn made them. */\n fileChanges: ConversationFileChange[];\n /** Distinct paths the turn changed. */\n fileCount: number;\n linesAdded: number;\n linesRemoved: number;\n}\n\n/** The turns that changed files, oldest first, each with its changes and their counts. */\nexport const collectTraceFileChangesByTurn = (turns: ConversationTurnTrace[]): TraceTurnFileChanges[] =>\n turns.flatMap((turn) => {\n const fileChanges = turn.steps.flatMap((step) => step.fileChanges);\n if (fileChanges.length === 0) return [];\n return [\n {\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n startedAt: turn.startedAt,\n fileChanges,\n fileCount: new Set(fileChanges.map((fileChange) => `${fileChange.mountKind ?? \"\"}:${fileChange.mountName ?? \"\"}:${fileChange.path}`)).size,\n linesAdded: fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesAdded ?? 0), 0),\n linesRemoved: fileChanges.reduce((sum, fileChange) => sum + (fileChange.linesRemoved ?? 0), 0),\n },\n ];\n });\n\n/**\n * What the conversation has running beside its turns, newest first: every sub-agent (a sub-agent that ran again shows\n * once, at its newest state) and every shell command that runs in the background or still runs.\n */\nexport const collectTraceBackgroundTasks = (turns: ConversationTurnTrace[]): BackgroundTask[] => {\n const tasksByKey = new Map<string, BackgroundTask>();\n for (const turn of turns) {\n for (const step of turn.steps) {\n if (step.kind === \"SUB_AGENT\" && step.subAgent !== null) {\n const subAgent = step.subAgent;\n const newestRun = subAgent.runs[subAgent.runs.length - 1];\n const startedAt = readTraceMoment(newestRun?.startedAt);\n const finishedAt = readTraceMoment(newestRun?.finishedAt);\n const key = `subAgent:${subAgent.childConversationId ?? `${turn.turnNumber}:${step.key}`}`;\n // A later step of the same sub-agent (a continuation) replaces the earlier one and moves to the end.\n tasksByKey.delete(key);\n // A background job that runs one tool is no agent: it reads as a job and records no run time of its own.\n const isBackgroundJob = subAgent.taskKind === \"toolRun\" || isTraceBackgroundJobLabel(subAgent.taskText);\n const durationMs = startedAt !== null && finishedAt !== null ? Math.max(0, finishedAt - startedAt) : null;\n tasksByKey.set(key, {\n key,\n type: \"subAgent\",\n title: subAgent.number !== null ? `#${subAgent.number} ${subAgent.label}` : subAgent.label,\n detail: isBackgroundJob ? describeTraceBackgroundJob(subAgent.toolName ?? subAgent.taskText) : subAgent.taskText,\n state: readTraceSubAgentState(subAgent),\n startedAt: newestRun?.startedAt ?? step.startedAt,\n durationMs: durationMs === 0 ? null : durationMs,\n typeLabel: isBackgroundJob ? translateText(\"Background job\") : null,\n childConversationId: subAgent.childConversationId,\n });\n continue;\n }\n if (step.terminal === null) continue;\n const state = readTraceStepState(step);\n if (!step.terminal.isBackground && state !== \"running\") continue;\n const key = `command:${turn.turnNumber}:${step.key}`;\n tasksByKey.set(key, {\n key,\n type: \"command\",\n title: step.terminal.command ?? step.line ?? step.toolNameInWords ?? \"\",\n detail: step.terminal.cwd,\n state,\n startedAt: step.startedAt,\n durationMs: step.terminal.durationMs ?? step.durationMs,\n });\n }\n }\n return [...tasksByKey.values()].reverse();\n};\n\n/** The task plan of a conversation as its newest plan update left it. */\nexport interface TraceTaskPlanSnapshot {\n /** The turn of the plan update, and the message that started it. */\n turnNumber: number;\n turnMessageId: number | null;\n /** The key of the plan update's step in its turn. */\n stepKey: string;\n title: string | null;\n /** The items in the plan's order; empty when the trace names only the counts. */\n items: ConversationTraceTaskPlanItem[];\n itemCount: number;\n /** Top-level items that are done or do not apply; a blocked item is never one. */\n doneCount: number;\n /** Top-level items that are blocked. */\n blockedCount: number;\n /** When the plan was last updated (a server date-time). */\n updatedAt: string | null;\n /**\n * Per item key: the plan update that last changed the item (it appeared, or its status or title changed). An item\n * whose change lies before the loaded turns has none.\n */\n itemSources: Readonly<Record<string, TraceTaskPlanItemSource>>;\n /** Per item key: the plan update the item first appeared in (as it stands now: same key and title). */\n itemFirstSources: Readonly<Record<string, TraceTaskPlanItemSource>>;\n /** Debug level: what refused plan calls told the agent, oldest first (empty at the steps level). */\n rejections: readonly TraceTaskPlanRejection[];\n}\n\n/** The plan update (a `TASK_PLAN` step) that last changed an item of the plan: where the trace shows it. */\nexport interface TraceTaskPlanItemSource {\n turnNumber: number;\n turnMessageId: number | null;\n /** The key of the step in its turn. */\n stepKey: string;\n /** The id the server gives the step (the anchor of its row); null when it sends none. */\n stepId: string | null;\n /** When the plan update ran (a server date-time); null when the trace names none. */\n startedAt?: string | null;\n}\n\n/** One line a refused plan call returned to the agent, with the plan update it belongs to. */\nexport interface TraceTaskPlanRejection {\n line: string;\n /** The first item key the line names; null when it names none. */\n itemKey: string | null;\n /** The plan tool of the call (`update_task_plan`, `set_task_status`). */\n toolName: string | null;\n source: TraceTaskPlanItemSource;\n}\n\n/**\n * Per item key, the plan update that last changed the item, read over the `TASK_PLAN` steps of the turns oldest\n * first: an item that appears, or whose status or title differs from the update before, is changed by that update.\n */\nconst collectTaskPlanItemSources = (\n turns: ConversationTurnTrace[],\n): { sources: Record<string, TraceTaskPlanItemSource>; firstSources: Record<string, TraceTaskPlanItemSource>; rejections: TraceTaskPlanRejection[] } => {\n const sources: Record<string, TraceTaskPlanItemSource> = {};\n const firstSources: Record<string, TraceTaskPlanItemSource> = {};\n const rejections: TraceTaskPlanRejection[] = [];\n const previousStateByKey = new Map<string, string>();\n const titleByKey = new Map<string, string>();\n for (const turn of turns) {\n for (const step of turn.steps) {\n if (step.kind !== \"TASK_PLAN\") continue;\n const source: TraceTaskPlanItemSource = {\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n stepKey: step.key,\n stepId: step.stepId ?? null,\n startedAt: step.startedAt ?? null,\n };\n for (const rejection of step.taskPlanRejections ?? []) {\n rejections.push({ line: rejection.line, itemKey: rejection.itemKey, toolName: step.toolName ?? null, source });\n }\n for (const item of step.taskPlanItems) {\n // a key whose title changed names another item (a plan made anew): it appears again\n if (titleByKey.get(item.key) !== item.title) firstSources[item.key] = source;\n titleByKey.set(item.key, item.title);\n const state = `${item.shownStatus ?? item.status ?? \"\"}\\u0000${item.title}\\u0000${item.statusNote ?? \"\"}`;\n if (previousStateByKey.get(item.key) === state) continue;\n previousStateByKey.set(item.key, state);\n sources[item.key] = source;\n }\n }\n }\n return { sources, firstSources, rejections };\n};\n\n/**\n * The conversation's task plan after its newest plan update (the last `TASK_PLAN` step of the turns that names a plan);\n * null for a conversation without a plan among the turns. The counts are the server's where it sends them, else those\n * of the items (`readTaskPlanCounts`).\n */\nexport const collectTraceTaskPlan = (turns: ConversationTurnTrace[]): TraceTaskPlanSnapshot | null => {\n for (let turnPosition = turns.length - 1; turnPosition >= 0; turnPosition -= 1) {\n const turn = turns[turnPosition];\n for (let stepPosition = turn.steps.length - 1; stepPosition >= 0; stepPosition -= 1) {\n const step = turn.steps[stepPosition];\n if (step.kind !== \"TASK_PLAN\") continue;\n const items = step.taskPlanItems;\n if (items.length === 0 && (step.taskPlanItemCount === null || step.taskPlanItemCount <= 0)) continue;\n const itemHistory = collectTaskPlanItemSources(turns);\n const counts = readTaskPlanCounts({\n itemCount: step.taskPlanItemCount,\n openItemCount: step.taskPlanOpenItemCount,\n doneItemCount: step.taskPlanDoneItemCount,\n blockedItemCount: step.taskPlanBlockedItemCount,\n items,\n });\n return {\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n stepKey: step.key,\n title: step.taskPlanTitle,\n items,\n itemCount: counts.total,\n doneCount: counts.done,\n blockedCount: counts.blocked,\n updatedAt: step.startedAt,\n itemSources: itemHistory.sources,\n itemFirstSources: itemHistory.firstSources,\n rejections: itemHistory.rejections,\n };\n }\n }\n return null;\n};\n\n/** A tool call that changed or deleted records. */\nexport interface TraceChangedRecord {\n /** Unique among the records of the turns: the turn's number and the step's key. */\n key: string;\n turnNumber: number;\n turnMessageId: number | null;\n /** The id the server gives the step; null when it sends none. */\n stepId: string | null;\n messageId: number | null;\n toolName: string | null;\n toolNameInWords: string | null;\n /** The narrated line of the step, as the owner read it. */\n line: string | null;\n effect: \"WRITE\" | \"DELETE\";\n /** Where the call stands: `done`, `running`, `failed` (nothing was changed), or `waiting` for the owner's approval. */\n state: TraceStepState;\n startedAt: string | null;\n /** The records the call's arguments name by id. */\n entityReferences: ConversationTraceEntityReference[];\n /** The records the call created, changed or deleted, each field before and after (captured at its writes). */\n recordChanges: ConversationTraceRecordChange[];\n /** Changed records left out beyond the server's cap. */\n omittedRecordChangeCount: number;\n}\n\n/**\n * The tool calls of the turns that changed or deleted records (the effect the tool declares: `WRITE`, `DELETE`),\n * newest first. A call a gate refused never ran and is left out; a call that failed or waits for the owner's approval\n * stays, with its state. What a call changed comes with it: each record with its fields before and after the call,\n * as the server captured them at the call's own write statements (empty for a call stored before the capture).\n */\nexport const collectTraceChangedRecords = (turns: ConversationTurnTrace[]): TraceChangedRecord[] => {\n const records: TraceChangedRecord[] = [];\n for (const turn of turns) {\n for (const step of turn.steps) {\n if (step.kind !== \"TOOL_CALL\" || (step.effect !== \"WRITE\" && step.effect !== \"DELETE\") || step.isRefused) continue;\n records.push({\n key: `${turn.turnNumber}:${step.key}`,\n turnNumber: turn.turnNumber,\n turnMessageId: turn.turnMessageId,\n stepId: step.stepId,\n messageId: step.messageId,\n toolName: step.toolName,\n toolNameInWords: step.toolNameInWords,\n line: step.line,\n effect: step.effect,\n state: readTraceStepState(step),\n startedAt: step.startedAt,\n entityReferences: step.entityReferences,\n recordChanges: step.recordChanges ?? [],\n omittedRecordChangeCount: step.omittedRecordChangeCount ?? 0,\n });\n }\n }\n return records.reverse();\n};\n","import type { CSSProperties } from \"react\";\nimport { useAgentsTexts } from \"../../provider/AgentsProvider\";\nimport { classNames } from \"../../provider/class-names\";\nimport { Text } from \"../../provider/components\";\nimport { AgentChatActivityDots } from \"../AgentChatActivityDots/AgentChatActivityDots\";\nimport { DEFAULT_AGENT_CHAT_ACTIVITY_TIMING } from \"../controller/chat-activity-timing\";\nimport type { AgentChatActivityProps } from \"../controller/AgentChatController\";\nimport styles from \"./AgentChatActivityStack.module.scss\";\n\n/** The lines the stack keeps on screen: the newest one and about three readable ranks above it, the oldest under the mask. */\nexport const ACTIVITY_STACK_VISIBLE_LINES = 4;\n\n/** The shortest and the longest time a line takes to move up one rank; between them a quarter of the line pace. */\nconst MIN_RANK_MOVE_MS = 160;\nconst MAX_RANK_MOVE_MS = 520;\n\n/**\n * The stacked activity feed at the tail of the thread, a drop-in `ThinkingIndicator` of `AgentChat`\n * (`<AgentChat ThinkingIndicator={AgentChatActivityStack} />`): one generated sentence per tool call of the running\n * turn, the newest at the bottom at full size, the older ones drifting up, smaller and fainter under a top mask.\n * Before the first sentence it shows the calm dots and \"Working on it…\"; once a sentence is told, only sentences. It\n * fades out over the success beat when the turn ends, and shows nothing between turns or after a failed turn.\n *\n * The moving layer is decorative (`aria-hidden`); a polite status region carries the newest sentence. The motion\n * follows the chat's timing (`activityTiming`: the line pace and the success beat), stays still under\n * `prefers-reduced-motion`, and every colour comes from the `--agents-*` variables.\n */\nexport const AgentChatActivityStack = (props: AgentChatActivityProps) => {\n const { active, failed, activityTicker, activityTiming = DEFAULT_AGENT_CHAT_ACTIVITY_TIMING } = props;\n const texts = useAgentsTexts();\n const { phase, currentTurn } = activityTicker;\n const lines = currentTurn?.lines ?? [];\n const isWorking = !failed && (active || phase === \"live\");\n const isFadingOut = !failed && phase === \"done\" && lines.length > 0;\n if (!isWorking && !isFadingOut) return null;\n\n const stackedLines = lines.slice(-ACTIVITY_STACK_VISIBLE_LINES);\n const newestSentence = lines.length > 0 ? lines[lines.length - 1].line : null;\n const rankMoveMs = Math.min(MAX_RANK_MOVE_MS, Math.max(MIN_RANK_MOVE_MS, Math.round(activityTiming.linePaceMs / 4)));\n const timingStyle = {\n \"--agents-activity-stack-move-duration\": `${rankMoveMs}ms`,\n \"--agents-activity-stack-fade-duration\": `${activityTiming.successBeatMs}ms`,\n } as CSSProperties;\n\n return (\n <div\n className={classNames(styles.stack, isFadingOut && styles.fadingOut)}\n style={timingStyle}\n data-testid=\"agent-chat-activity-stack\"\n data-phase={isFadingOut ? \"done\" : \"live\"}\n >\n <div className={styles.visual} aria-hidden=\"true\">\n {stackedLines.length === 0 ? (\n <div className={styles.waiting}>\n <AgentChatActivityDots variant=\"pulse\" />\n <Text role=\"help\" color=\"--agents-fg-light\">\n Working on it…\n </Text>\n </div>\n ) : (\n <ol className={styles.lines}>\n {stackedLines.map((line, index) => {\n const rank = stackedLines.length - 1 - index;\n return (\n <li key={line.toolCallMessageId} className={styles.line} data-rank={rank}>\n <Text role=\"help\" color={rank === 0 ? \"--agents-fg\" : \"--agents-fg-light\"} translate={false} ellipsis>\n {line.line}\n </Text>\n </li>\n );\n })}\n </ol>\n )}\n </div>\n <div className={styles.statusRegion} role=\"status\" aria-live=\"polite\" data-testid=\"agent-chat-activity-stack-status\">\n {newestSentence ?? texts.translate(\"Working on it…\")}\n </div>\n </div>\n );\n};\n","import { useCallback, useEffect, useState } from \"react\";\n\n/**\n * Shared semantic-search state with a hard 700ms debounce and a minimum three-character query because every request\n * runs an LLM reranker and consumes AI credits. `enabled` mirrors whether the owning panel is open; the caller runs\n * `clearSearch` in the open handler so it renders clean immediately, while a rising-edge reset effect would flash the\n * previous session's query and results.\n */\nexport const useDebouncedSemanticSearch = <TResult>(\n fetcher: (trimmedQuery: string) => Promise<TResult[]>,\n enabled: boolean,\n) => {\n const [query, setQuery] = useState(\"\");\n const [results, setResults] = useState<TResult[] | null>(null);\n const [searching, setSearching] = useState(false);\n const trimmedQuery = query.trim();\n\n const clearSearch = useCallback(() => {\n setQuery(\"\");\n setResults(null);\n }, []);\n\n useEffect(() => {\n if (!enabled || trimmedQuery.length < 3) {\n setResults(null);\n setSearching(false);\n return;\n }\n let cancelled = false;\n setSearching(true);\n // Drop the previous query's results the moment a new search starts, so the loading skeleton shows again — the\n // same as a first search from an empty input — instead of the stale hits lingering until the new ones arrive.\n setResults(null);\n const timer = setTimeout(() => {\n void (async () => {\n try {\n const fetchedResults = await fetcher(trimmedQuery);\n if (!cancelled) {\n setResults(fetchedResults);\n }\n } catch {\n if (!cancelled) {\n setResults([]);\n }\n } finally {\n if (!cancelled) {\n setSearching(false);\n }\n }\n })();\n }, 700);\n return () => {\n cancelled = true;\n clearTimeout(timer);\n };\n }, [trimmedQuery, enabled, fetcher]);\n\n return {\n query,\n setQuery,\n trimmedQuery,\n results,\n searching,\n isSearchActive: enabled && trimmedQuery.length >= 3,\n clearSearch,\n };\n};\n","import { useCallback } from \"react\";\nimport { useAgentsConversationClient } from \"../../client/AgentsConversationClientContext\";\nimport type {\n ConversationMessageSearchHit,\n ConversationSearchGroup,\n ConversationSearchOptions,\n} from \"../../contract/conversation\";\nimport { useDebouncedSemanticSearch } from \"./use-debounced-semantic-search\";\n\n/** The size of every chat search answer: ten matches, excerpts of 420 characters. */\nconst CHAT_SEARCH_OPTIONS: ConversationSearchOptions = { limit: 10, excerptLength: 420 };\n\nexport interface ConversationMessageSearchState {\n query: string;\n setQuery: (query: string) => void;\n trimmedQuery: string;\n hits: ConversationMessageSearchHit[] | null;\n searching: boolean;\n isSearchActive: boolean;\n /** Wipe query + hits. The caller runs this in the click handler that OPENS the panel (see hook doc). */\n clearSearch: () => void;\n}\n\nexport interface ConversationsSearchState {\n query: string;\n setQuery: (query: string) => void;\n trimmedQuery: string;\n searchGroups: ConversationSearchGroup[] | null;\n searching: boolean;\n isSearchActive: boolean;\n /** Wipe query + results. The caller runs this in the click handler that OPENS the panel (see hook doc). */\n clearSearch: () => void;\n}\n\n/**\n * In-conversation \"find in this chat\" search state: the conversation client's `searchConversationMessages` returns\n * the matched hits of one conversation.\n */\nexport const useConversationMessageSearch = (\n conversationId: number,\n enabled: boolean,\n): ConversationMessageSearchState => {\n const conversationClient = useAgentsConversationClient();\n const fetchConversationMessageHits = useCallback(\n (trimmedQuery: string) =>\n conversationClient.searchConversationMessages(conversationId, trimmedQuery, CHAT_SEARCH_OPTIONS),\n [conversationClient, conversationId],\n );\n const { results: hits, ...searchState } = useDebouncedSemanticSearch<ConversationMessageSearchHit>(\n fetchConversationMessageHits,\n enabled,\n );\n\n return {\n hits,\n ...searchState,\n };\n};\n\n/**\n * Cross-conversation \"search all my chats\" state: the conversation client's `searchConversations` returns the\n * matches grouped by conversation.\n */\nexport const useConversationsSearch = (enabled: boolean): ConversationsSearchState => {\n const conversationClient = useAgentsConversationClient();\n const fetchConversationSearchGroups = useCallback(\n (trimmedQuery: string) => conversationClient.searchConversations(trimmedQuery, CHAT_SEARCH_OPTIONS),\n [conversationClient],\n );\n const { results: searchGroups, ...searchState } = useDebouncedSemanticSearch<ConversationSearchGroup>(\n fetchConversationSearchGroups,\n enabled,\n );\n\n return {\n searchGroups,\n ...searchState,\n };\n};\n","import { Button, Text, type AgentsTextReplacements } from \"../../../provider/components\";\nimport React, { useEffect, useRef } from \"react\";\nimport styles from \"./ConversationMessageInputAttachmentsErrorBox.module.scss\";\n\nexport const ERROR_BOX_AUTO_DISMISS_AFTER_MS = 5000;\n\nexport interface ConversationMessageInputAttachmentsErrorBoxProps {\n /** Validation errors of ONE invalid selection, straight from `MediaItemFile.validationErrors`. */\n errors: { text: string; replacements?: AgentsTextReplacements }[];\n onDismiss: () => void;\n /** Stories pass a short value so play-tests don't wait 5 real seconds. */\n autoDismissAfterMs?: number;\n testId?: string;\n}\n\n/**\n * The single error box above the chat input for an invalid file selection. Auto-dismisses after\n * `autoDismissAfterMs` with a visible countdown bar (CSS animation — the timeout and the bar share\n * the duration and pause/resume together), or immediately via the ✕. Hovering the box pauses the\n * countdown (timer AND bar) so the user can finish reading; leaving resumes with the remaining\n * time. The HOST re-arms it for a new invalid selection by remounting (`key` bump) — mount is the\n * only moment the timer starts.\n */\nexport const ConversationMessageInputAttachmentsErrorBox = (\n props: ConversationMessageInputAttachmentsErrorBoxProps,\n) => {\n const {\n errors,\n onDismiss,\n autoDismissAfterMs = ERROR_BOX_AUTO_DISMISS_AFTER_MS,\n testId = \"chat-input-attachments\",\n } = props;\n\n const remainingDismissMsRef = useRef(autoDismissAfterMs);\n const dismissTimeoutIdRef = useRef<number | undefined>(undefined);\n const dismissTimeoutStartedAtMsRef = useRef(0);\n\n const startDismissTimeout = () => {\n dismissTimeoutStartedAtMsRef.current = Date.now();\n dismissTimeoutIdRef.current = window.setTimeout(onDismiss, remainingDismissMsRef.current);\n };\n\n const pauseDismissTimeout = () => {\n window.clearTimeout(dismissTimeoutIdRef.current);\n remainingDismissMsRef.current -= Date.now() - dismissTimeoutStartedAtMsRef.current;\n };\n\n useEffect(() => {\n startDismissTimeout();\n return () => window.clearTimeout(dismissTimeoutIdRef.current);\n // Mount-only by design: the host re-arms via remount.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return (\n <div\n className={styles.errorBox}\n onMouseEnter={pauseDismissTimeout}\n onMouseLeave={startDismissTimeout}\n data-testid={`${testId}-error-box`}\n >\n <div className={styles.errorLines}>\n {errors.map((error, errorIndex) => (\n <Text key={errorIndex} role=\"caption\" color=\"var(--agents-danger-500)\" replacements={error.replacements}>\n {error.text}\n </Text>\n ))}\n </div>\n <Button\n className={styles.dismissButton}\n variant=\"muted\"\n size=\"small\"\n icon=\"close\"\n onClick={onDismiss}\n testId={`${testId}-error-box-dismiss`}\n rounded\n />\n <div\n className={styles.countdownBar}\n style={{ animationDuration: `${autoDismissAfterMs}ms` }}\n data-testid={`${testId}-error-box-countdown`}\n />\n </div>\n );\n};\n","/** A file size as the attachment card shows it (\"1.5 MB\"); the same wording as the app's file helpers. */\nexport const convertBytesToSizeString = (bytes: number): string => {\n const sizes = [\"Bytes\", \"KB\", \"MB\", \"GB\", \"TB\"];\n if (bytes === 0) {\n return \"0 Byte\";\n }\n const sizeIndex = Math.floor(Math.log(bytes) / Math.log(1024));\n return parseFloat((bytes / Math.pow(1024, sizeIndex)).toFixed(2)) + \" \" + sizes[sizeIndex];\n};\n","import { Button, ProgressBar, Text } from \"../../../provider/components\";\nimport React from \"react\";\nimport styles from \"./ConversationMessageInputAttachmentPreviewWidget.module.scss\";\nimport { classNames } from \"../../../provider/class-names\";\nimport { convertBytesToSizeString } from \"./convert-bytes-to-size-string\";\nimport { useAgentsTexts } from \"../../../provider/AgentsProvider\";\n\nexport type ConversationMessageInputAttachmentUploadStatus = \"uploading\" | \"uploaded\" | \"failed\";\n\n/**\n * Presentational shape of one attachment above the chat input. The host's attachment state\n * (e.g. `useAgentChatAttachments`' `AgentChatAttachment`) is a superset of this.\n */\nexport type ConversationMessageInputAttachmentPreview = {\n attachmentId: string;\n /** Data-URI of the image — renders the thumbnail card. Absent → generic file card. */\n previewImageSrc?: string;\n /** Generic-card fields (image cards show the thumbnail instead). */\n fileName?: string;\n fileSizeBytes?: number;\n mimeType?: string;\n uploadStatus: ConversationMessageInputAttachmentUploadStatus;\n /** 0-100; only meaningful while `uploadStatus` is \"uploading\". */\n uploadProgressPercent: number;\n};\n\nexport interface ConversationMessageInputAttachmentPreviewWidgetProps {\n attachment: ConversationMessageInputAttachmentPreview;\n /**\n * The card's bin — the host drops the attachment (and discards its in-flight upload result). Omitted → no bin: a\n * read-only card (e.g. a sent message's echo of a non-image file).\n */\n onRemove?: () => void;\n testId?: string;\n}\n\n/**\n * One attachment card above the chat input: an image thumbnail (or a generic name/type/size card\n * for future non-image types), an upload progress bar while the media-library upload runs, a\n * failed state, and a bin that is always in view to remove it (only when the host passes `onRemove`).\n *\n * While uploading, a white caption with a black shadow sits over the image bottom:\n * \"Uploading (45%)...\" while bytes are still going out, \"Processing...\" once all bytes are sent\n * (progress 100%) but the media-library call hasn't resolved — the bar goes indeterminate for that\n * stretch. Both disappear when the upload settles.\n */\nexport const ConversationMessageInputAttachmentPreviewWidget = (\n props: ConversationMessageInputAttachmentPreviewWidgetProps,\n) => {\n const { attachment, onRemove, testId = \"chat-input-attachment\" } = props;\n const texts = useAgentsTexts();\n\n const isUploading = attachment.uploadStatus === \"uploading\";\n const hasFailed = attachment.uploadStatus === \"failed\";\n // All bytes sent, but the media-library call hasn't resolved yet.\n const isProcessingAfterUpload = isUploading && attachment.uploadProgressPercent >= 100;\n const fileTypeLabel = attachment.mimeType?.split(\"/\").pop()?.toUpperCase();\n\n return (\n <div\n className={classNames(styles.card, {\n [styles.cardFailed]: hasFailed,\n [styles.cardGenericFile]: !attachment.previewImageSrc,\n })}\n data-testid={`${testId}-card`}\n >\n {attachment.previewImageSrc ? (\n <img className={styles.thumbnail} src={attachment.previewImageSrc} alt={attachment.fileName ?? \"\"} />\n ) : (\n <div className={styles.fileFacts}>\n <Text role=\"help\" color=\"var(--agents-fg)\" textWrap=\"nowrap\" translate={false}>\n {attachment.fileName ?? \"\"}\n </Text>\n <Text role=\"caption\" color=\"var(--agents-fg-light)\" textWrap=\"nowrap\" translate={false}>\n {[fileTypeLabel, attachment.fileSizeBytes ? convertBytesToSizeString(attachment.fileSizeBytes) : undefined]\n .filter(Boolean)\n .join(\" • \")}\n </Text>\n </div>\n )}\n {isUploading && (\n <div className={styles.uploadProgress} data-testid={`${testId}-upload-progress`}>\n <Text\n className={styles.uploadStatusCaption}\n role=\"caption\"\n color=\"var(--agents-neutral-000)\"\n replacements={{ uploadProgressPercent: `${attachment.uploadProgressPercent}%` }}\n testId={`${testId}-upload-status`}\n >\n {isProcessingAfterUpload ? \"Processing...\" : \"Uploading (%uploadProgressPercent%)...\"}\n </Text>\n <ProgressBar\n value={attachment.uploadProgressPercent}\n indeterminate={!(attachment.uploadProgressPercent > 0 && !isProcessingAfterUpload)}\n color=\"var(--agents-primary-500)\"\n height=\"4px\"\n />\n </div>\n )}\n {hasFailed && (\n <Text\n className={styles.failedCaption}\n role=\"caption\"\n color=\"var(--agents-danger-500)\"\n testId={`${testId}-failed-caption`}\n >\n Upload failed\n </Text>\n )}\n {/* Own holder because the component library's Button puts `className` on the inner <button>, not on its\n in-flow wrapper span — the holder is what actually positions the bin. */}\n {onRemove !== undefined && (\n <span className={styles.removeButtonHolder}>\n <Button\n className={styles.removeButton}\n variant=\"muted\"\n size=\"small\"\n icon=\"trash\"\n ariaLabel={texts.translate(\"Remove file\")}\n onClick={onRemove}\n testId={`${testId}-remove-button`}\n rounded\n />\n </span>\n )}\n </div>\n );\n};\n","import React from \"react\";\nimport styles from \"./ConversationMessageInputAttachmentsPreviewStrip.module.scss\";\nimport { classNames } from \"../../../provider/class-names\";\nimport {\n ConversationMessageInputAttachmentPreview,\n ConversationMessageInputAttachmentPreviewWidget,\n} from \"./ConversationMessageInputAttachmentPreviewWidget\";\n\nexport interface ConversationMessageInputAttachmentsPreviewStripProps {\n attachments: ConversationMessageInputAttachmentPreview[];\n onRemoveAttachment: (attachmentId: string) => void;\n testId?: string;\n}\n\n/**\n * Horizontal strip of attachment cards above the chat input's text area. Grows in / shrinks out\n * with the grid-rows 0fr→1fr reveal (same trick as the selection chip) instead of popping; scrolls\n * horizontally when the cards outgrow the input's width.\n */\nexport const ConversationMessageInputAttachmentsPreviewStrip = (\n props: ConversationMessageInputAttachmentsPreviewStripProps,\n) => {\n const { attachments, onRemoveAttachment, testId = \"chat-input-attachments\" } = props;\n\n return (\n <div\n className={classNames(styles.stripReveal, { [styles.stripRevealOpen]: attachments.length > 0 })}\n data-testid={`${testId}-strip`}\n >\n <div className={styles.stripRevealInner}>\n <div className={styles.strip}>\n {attachments.map((attachment) => (\n <ConversationMessageInputAttachmentPreviewWidget\n key={attachment.attachmentId}\n attachment={attachment}\n onRemove={() => onRemoveAttachment(attachment.attachmentId)}\n testId={`${testId}-${attachment.attachmentId}`}\n />\n ))}\n </div>\n </div>\n </div>\n );\n};\n"],"names":["styles","line","text","compact","collapsed","collapsedPillSizer","_","clock","title","description","replacements","Fragment","suggestions","visible","backgroundPaintedByHost","confineTopBlurBandToChatPane","messagesBottom","layout","titleSlot","root","handle","min","max","tab","classes","lines","selectConversation","chatMessages","content","note","actions","stepStyles","records","record","chip","row","part","TaskPlanRow","stack","tree","rejection","detail","toggle","key"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,MAAM,2BAA2B,CAAC,UAAyC;AAChF,QAAM,EAAE,SAAS;AACjB,MAAI,SAAS,QAAQ,KAAK,MAAM,WAAW,EAAG,QAAO;AACrD,SACE,oBAAC,OAAA,EAAI,WAAWA,SAAO,SAAS,eAAY,+BACzC,UAAA,KAAK,MAAM,IAAI,CAACC,8BACd,MAAA,EAAqD,MAAK,QAAO,OAAM,qBAAoB,WAAW,OACpG,UAAAA,MAAK,KAAA,GADG,GAAGA,MAAK,iBAAiB,IAAIA,MAAK,KAAK,EAElD,CACD,GACH;AAEJ;;;;;;;;;ACLO,MAAM,wBAAwB,CAAC,EAAE,UAAU,eAChD;AAAA,EAAC;AAAA,EAAA;AAAA,IACC,WAAW,WAAWD,SAAO,MAAM,YAAY,UAAUA,SAAO,QAAQA,SAAO,MAAM;AAAA,IACrF,eAAY;AAAA,IACZ,6BAA2B;AAAA,IAE3B,UAAA;AAAA,MAAA,oBAAC,QAAA,EAAK;AAAA,0BACL,QAAA,EAAK;AAAA,0BACL,QAAA,CAAA,CAAK;AAAA,IAAA;AAAA,EAAA;AACR;;;;;ACRK,MAAM,6BAA6B,CAAC,UAA2C;AACpF,QAAM,EAAE,QAAQ,QAAQ,gBAAgB,cAAc,aAAa;AACnE,QAAM,YAAY,CAAC,WAAW,UAAU,eAAe,UAAU;AACjE,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,eAAe,eAAe,aAAa,SAAS,CAAA;AAC1D,QAAM,cAAc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