@opengeni/react 3.5.1-canary.0 → 3.7.0-canary.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.
Files changed (52) hide show
  1. package/dist/artifacts.d.ts +1 -1
  2. package/dist/artifacts.js +229 -6
  3. package/dist/artifacts.js.map +1 -1
  4. package/dist/{chunk-IB27C53Y.js → chunk-C6WDLHBA.js} +31 -23
  5. package/dist/chunk-C6WDLHBA.js.map +1 -0
  6. package/dist/{chunk-WY3MELVJ.js → chunk-DOK4KZF2.js} +119 -8
  7. package/dist/chunk-DOK4KZF2.js.map +1 -0
  8. package/dist/{chunk-TJFMMDQU.js → chunk-FJBOU2TH.js} +112 -6
  9. package/dist/chunk-FJBOU2TH.js.map +1 -0
  10. package/dist/{chunk-UNCXXIQR.js → chunk-R55HFTT3.js} +66 -24
  11. package/dist/chunk-R55HFTT3.js.map +1 -0
  12. package/dist/client.d.ts +1 -1
  13. package/dist/components/artifacts/index.d.ts +1 -1
  14. package/dist/components/artifacts/published-html-artifact-frame.d.ts +45 -3
  15. package/dist/components/composer.d.ts +2 -0
  16. package/dist/components/session-chrome.d.ts +1 -1
  17. package/dist/composer.js +1 -1
  18. package/dist/{fleet-decision-row-GGCAT4E4.js → fleet-decision-row-YZ3ZKWMM.js} +2 -1
  19. package/dist/fleet-decision-row-YZ3ZKWMM.js.map +1 -0
  20. package/dist/hooks/use-file-attachments.d.ts +6 -0
  21. package/dist/hooks/use-sandbox-files.d.ts +4 -1
  22. package/dist/hooks/use-workspace-edit.d.ts +4 -0
  23. package/dist/index.js +114 -58
  24. package/dist/index.js.map +1 -1
  25. package/dist/session-ui.js +2 -2
  26. package/dist/session.js +2 -2
  27. package/dist/timeline/registry.d.ts +2 -0
  28. package/dist/timeline/types.d.ts +1 -1
  29. package/package.json +2 -2
  30. package/src/artifacts.ts +3 -0
  31. package/src/client.ts +2 -1
  32. package/src/components/artifacts/index.ts +3 -0
  33. package/src/components/artifacts/published-html-artifact-frame.tsx +284 -4
  34. package/src/components/composer.tsx +89 -25
  35. package/src/components/message-timeline.tsx +32 -8
  36. package/src/components/sandbox-workspace.tsx +11 -1
  37. package/src/components/session-chrome.tsx +3 -3
  38. package/src/hooks/use-file-attachments.ts +34 -0
  39. package/src/hooks/use-sandbox-files.ts +68 -20
  40. package/src/hooks/use-session-events.ts +21 -26
  41. package/src/hooks/use-workspace-edit.ts +23 -5
  42. package/src/timeline/fleet-decision-projection.ts +2 -1
  43. package/src/timeline/fleet-decision-row.tsx +1 -0
  44. package/src/timeline/projection.ts +151 -7
  45. package/src/timeline/registry.ts +15 -3
  46. package/src/timeline/tool-renderers.tsx +117 -1
  47. package/src/timeline/types.ts +8 -1
  48. package/dist/chunk-IB27C53Y.js.map +0 -1
  49. package/dist/chunk-TJFMMDQU.js.map +0 -1
  50. package/dist/chunk-UNCXXIQR.js.map +0 -1
  51. package/dist/chunk-WY3MELVJ.js.map +0 -1
  52. package/dist/fleet-decision-row-GGCAT4E4.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/components/human-input-form.tsx","../src/components/human-input-surface.tsx","../src/components/copy-button.tsx","../src/components/markdown.tsx","../src/lib/motion.ts","../src/lib/motion-inspect.ts","../src/components/soften-streaming-markdown.ts","../src/components/stream-reveal.ts","../src/components/user-message-body.tsx","../src/timeline/registry.ts","../src/timeline/parsers.ts","../src/timeline/disclosure-context.tsx","../src/timeline/shared.tsx","../src/lib/git-patch.ts","../src/components/pierre-diff.tsx","../src/timeline/tool-renderers.tsx","../src/timeline/compute-label.tsx","../src/timeline/tool-diff.tsx","../src/lib/use-theme-type.ts","../src/timeline/activity-rail.tsx","../src/timeline/entrance.tsx","../src/timeline/seen-activity-ids.ts","../src/timeline/turn-summary.tsx","../src/timeline/fold-memory.ts","../src/components/generated-video-player.tsx","../src/components/session-status.tsx","../src/components/message-timeline.tsx","../src/components/tip-follow.ts","../src/components/machine-input-display.ts","../src/components/queue-surface.tsx","../src/components/session-chrome.tsx"],"sourcesContent":["import type {\n HumanInputAnswer,\n HumanInputQuestion,\n SessionHumanInputRequest,\n SubmitHumanInputResponseRequest,\n} from \"@opengeni/sdk\";\nimport { ChevronDownIcon, ChevronUpIcon, MessageCircleQuestionIcon } from \"lucide-react\";\nimport { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\n\nexport type HumanInputAnswerDraft = {\n values: string[];\n other: string;\n otherSelected: boolean;\n};\n\nexport type HumanInputFormMessages = {\n title: string;\n description: string;\n submit: string;\n skip: string;\n submitting: string;\n other: string;\n deadlineLabel: string;\n formatDeadline: (value: string) => string;\n required: string;\n otherRequired: string;\n minSelections: (count: number) => string;\n maxSelections: (count: number) => string;\n optional: string;\n /** Shown when the question list overflows the card and more content is below. */\n moreBelow: string;\n questionCount: (count: number) => string;\n collapse: string;\n expand: string;\n selectionHint: (min: number | null | undefined, max: number | null | undefined) => string | null;\n};\n\nexport const defaultHumanInputFormMessages: HumanInputFormMessages = {\n title: \"Input required\",\n /** Multi-question chrome has no default subtitle; hosts may still override. */\n description: \"\",\n submit: \"Send answers\",\n skip: \"Skip\",\n submitting: \"Submitting…\",\n other: \"Other\",\n deadlineLabel: \"Expires\",\n formatDeadline,\n required: \"This question is required.\",\n otherRequired: \"Enter a value for Other.\",\n minSelections: (count) => `Choose at least ${count} option${count === 1 ? \"\" : \"s\"}.`,\n maxSelections: (count) => `Choose no more than ${count} option${count === 1 ? \"\" : \"s\"}.`,\n optional: \"Optional\",\n moreBelow: \"More below\",\n questionCount: (count) => `${count} questions`,\n collapse: \"Collapse\",\n expand: \"Expand\",\n selectionHint: (min, max) => {\n if (min != null && max != null) return `Choose ${min}–${max}.`;\n if (min != null) return `Choose at least ${min}.`;\n if (max != null) return `Choose up to ${max}.`;\n return null;\n },\n};\n\nexport type HumanInputFormProps = {\n request: Pick<SessionHumanInputRequest, \"id\" | \"questions\" | \"allowSkip\" | \"expiresAt\">;\n onSubmit: (response: SubmitHumanInputResponseRequest) => void | Promise<void>;\n submitting?: boolean | undefined;\n error?: string | null | undefined;\n title?: ReactNode;\n description?: ReactNode;\n /** e.g. \"1 of 2\" when a host is stepping through parallel requests. */\n progressLabel?: ReactNode;\n submitLabel?: string | undefined;\n skipLabel?: string | undefined;\n messages?: Partial<HumanInputFormMessages> | undefined;\n autoFocus?: boolean | undefined;\n /** Start collapsed to a compact bar (drafts still retained). */\n defaultCollapsed?: boolean | undefined;\n className?: string | undefined;\n};\n\n/**\n * Styled but host-neutral renderer for one structured request. Matches the\n * waiting-tone decision language of ApprovalSurface: question-first, compact\n * options, sticky ask/submit chrome. Hosts can replace title/description or\n * use `useHumanInputRequests` headlessly.\n */\nexport function HumanInputForm(props: HumanInputFormProps) {\n // The pending-request read model is refreshed after session events and\n // returns newly allocated question arrays for the same durable request.\n // Key the state owner by that request's lifecycle identity so reconciliation\n // cannot erase an answer that the operator is still typing.\n return <HumanInputRequestForm key={props.request.id} {...props} />;\n}\n\nfunction HumanInputRequestForm({\n request,\n onSubmit,\n submitting = false,\n error,\n title,\n description,\n progressLabel,\n submitLabel,\n skipLabel,\n messages: messageOverrides,\n autoFocus = true,\n defaultCollapsed = false,\n className,\n}: HumanInputFormProps) {\n const messages = { ...defaultHumanInputFormMessages, ...messageOverrides };\n const singleQuestion = request.questions.length === 1 ? request.questions[0]! : null;\n const resolvedTitle =\n title === undefined\n ? singleQuestion\n ? (singleQuestion.label ?? singleQuestion.prompt)\n : messages.title\n : title;\n const resolvedDescription =\n description === undefined\n ? singleQuestion\n ? singleQuestion.label\n ? singleQuestion.prompt\n : (singleQuestion.helpText ?? null)\n : messages.description || null\n : description;\n const resolvedSubmitLabel = submitLabel ?? messages.submit;\n const resolvedSkipLabel = skipLabel ?? messages.skip;\n const formId = useId();\n const titleId = useId();\n const scrollRef = useRef<HTMLDivElement>(null);\n const [drafts, setDrafts] = useState<Record<string, HumanInputAnswerDraft>>(() =>\n initialDrafts(request.questions),\n );\n const [validationErrors, setValidationErrors] = useState<Record<string, string>>({});\n const [submissionError, setSubmissionError] = useState<string | null>(null);\n const [submittingInternally, setSubmittingInternally] = useState(false);\n const [overflowBelow, setOverflowBelow] = useState(false);\n const [collapsed, setCollapsed] = useState(defaultCollapsed);\n const submissionInFlight = useRef(false);\n const submissionGeneration = useRef(0);\n const busy = submitting || submittingInternally;\n\n useEffect(() => {\n if (collapsed) {\n setOverflowBelow(false);\n return;\n }\n const node = scrollRef.current;\n if (!node) return;\n const sync = () => {\n const { scrollTop, scrollHeight, clientHeight } = node;\n setOverflowBelow(\n scrollHeight > clientHeight + 2 && scrollTop + clientHeight < scrollHeight - 4,\n );\n };\n // Layout after paint: first sync can run before the max-height flex\n // constraint resolves, which falsely reports no overflow.\n const frame = requestAnimationFrame(sync);\n node.addEventListener(\"scroll\", sync, { passive: true });\n const observer = typeof ResizeObserver !== \"undefined\" ? new ResizeObserver(sync) : null;\n observer?.observe(node);\n const content = node.firstElementChild;\n if (content) observer?.observe(content);\n return () => {\n cancelAnimationFrame(frame);\n node.removeEventListener(\"scroll\", sync);\n observer?.disconnect();\n };\n }, [request.id, request.questions, collapsed]);\n\n const update = (\n questionId: string,\n apply: (draft: HumanInputAnswerDraft) => HumanInputAnswerDraft,\n ): void => {\n setDrafts((current) => ({\n ...current,\n [questionId]: apply(current[questionId] ?? emptyDraft()),\n }));\n setValidationErrors((current) => {\n if (!(questionId in current)) return current;\n const next = { ...current };\n delete next[questionId];\n return next;\n });\n };\n\n const submitResponse = async (response: SubmitHumanInputResponseRequest): Promise<void> => {\n if (busy || submissionInFlight.current) return;\n const generation = submissionGeneration.current;\n submissionInFlight.current = true;\n setSubmissionError(null);\n setSubmittingInternally(true);\n try {\n await onSubmit(response);\n } catch (cause) {\n if (generation === submissionGeneration.current) {\n setSubmissionError(cause instanceof Error ? cause.message : String(cause));\n }\n } finally {\n if (generation === submissionGeneration.current) {\n submissionInFlight.current = false;\n setSubmittingInternally(false);\n }\n }\n };\n\n const focusQuestion = (questionId: string): void => {\n const root = scrollRef.current;\n if (!root) return;\n const block = Array.from(\n root.querySelectorAll<HTMLElement>(\"[data-human-input-question]\"),\n ).find((node) => node.getAttribute(\"data-human-input-question\") === questionId);\n block?.scrollIntoView({ block: \"nearest\", behavior: \"smooth\" });\n const focusable = block?.querySelector<HTMLElement>(\n \"input:not([type='hidden']):not([disabled]), textarea:not([disabled])\",\n );\n focusable?.focus({ preventScroll: true });\n };\n\n const submit = async (event: FormEvent<HTMLFormElement>): Promise<void> => {\n event.preventDefault();\n const result = answersFromDrafts(request.questions, drafts, messages);\n if (Object.keys(result.errors).length > 0) {\n setValidationErrors(result.errors);\n const firstInvalid = request.questions.find((question) => question.id in result.errors);\n if (firstInvalid) {\n // After paint so aria-invalid / error text exist under the question.\n requestAnimationFrame(() => focusQuestion(firstInvalid.id));\n }\n return;\n }\n await submitResponse({ outcome: \"answered\", answers: result.answers });\n };\n\n const metaBits = [\n progressLabel,\n !singleQuestion ? messages.questionCount(request.questions.length) : null,\n request.expiresAt ? (\n <>\n {messages.deadlineLabel}{\" \"}\n <time dateTime={request.expiresAt} title={new Date(request.expiresAt).toLocaleString()}>\n {messages.formatDeadline(request.expiresAt)}\n </time>\n </>\n ) : null,\n ].filter(Boolean);\n\n if (collapsed) {\n return (\n <div\n data-human-input-request={request.id}\n data-human-input-collapsed=\"\"\n aria-labelledby={titleId}\n className={cn(\n \"og-root flex w-full items-center gap-3 rounded-og-lg border border-og-status-waiting/35 bg-og-status-waiting/5 px-3 py-2.5 shadow-og-sm\",\n className,\n )}\n >\n <span className=\"inline-flex size-8 shrink-0 items-center justify-center rounded-og-md bg-og-status-waiting/12 text-og-status-waiting\">\n <MessageCircleQuestionIcon aria-hidden=\"true\" className=\"size-4\" />\n </span>\n <div className=\"min-w-0 flex-1\">\n <h2 id={titleId} className=\"truncate text-og-sm font-semibold text-og-fg\">\n {resolvedTitle}\n </h2>\n {metaBits.length > 0 ? (\n <p className=\"mt-0.5 truncate text-og-xs text-og-fg-subtle\">{metaBits.join(\" · \")}</p>\n ) : null}\n </div>\n <button\n type=\"button\"\n onClick={() => setCollapsed(false)}\n className=\"inline-flex min-h-8 shrink-0 items-center gap-1 rounded-og-md border border-og-border px-2.5 py-1 text-og-xs font-medium text-og-fg-muted transition-colors hover:bg-og-surface-1 hover:text-og-fg\"\n >\n {messages.expand}\n <ChevronDownIcon aria-hidden=\"true\" className=\"size-3.5\" />\n </button>\n </div>\n );\n }\n\n return (\n <form\n data-human-input-request={request.id}\n onSubmit={(event) => void submit(event)}\n aria-labelledby={titleId}\n className={cn(\n // Multi-question: pin height at the cap so the flex body gets a real\n // box and overflow-y engages. max-height alone + percentage/`h-full`\n // children often sizes to content and clips with no scroll.\n \"og-root flex min-h-0 w-full flex-col overflow-hidden rounded-og-lg border border-og-status-waiting/35 bg-og-status-waiting/5 shadow-og-sm\",\n singleQuestion\n ? \"max-h-[min(28rem,50dvh)]\"\n : \"h-[min(28rem,50dvh)] max-h-[min(28rem,50dvh)]\",\n className,\n )}\n >\n <header className=\"shrink-0 border-b border-og-status-waiting/20 px-4 py-3\">\n <div className=\"flex items-start gap-3\">\n <span className=\"mt-0.5 inline-flex size-8 shrink-0 items-center justify-center rounded-og-md bg-og-status-waiting/12 text-og-status-waiting\">\n <MessageCircleQuestionIcon aria-hidden=\"true\" className=\"size-4\" />\n </span>\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-baseline gap-x-2 gap-y-0.5\">\n <h2 id={titleId} className=\"text-og-md font-semibold text-og-fg\">\n {resolvedTitle}\n {singleQuestion?.required && !request.allowSkip ? (\n <span aria-hidden className=\"ml-1 text-og-status-failed\">\n *\n </span>\n ) : null}\n </h2>\n {progressLabel ? (\n <span className=\"text-og-xs font-medium text-og-status-waiting\">\n {progressLabel}\n </span>\n ) : null}\n {!singleQuestion ? (\n <span className=\"text-og-xs font-medium text-og-fg-subtle\">\n {messages.questionCount(request.questions.length)}\n </span>\n ) : null}\n </div>\n {resolvedDescription ? (\n <div className=\"mt-0.5 text-og-sm text-og-fg-muted\">{resolvedDescription}</div>\n ) : null}\n {request.expiresAt ? (\n <p className=\"mt-1 text-og-xs text-og-fg-subtle\">\n {messages.deadlineLabel}{\" \"}\n <time\n dateTime={request.expiresAt}\n title={new Date(request.expiresAt).toLocaleString()}\n >\n {messages.formatDeadline(request.expiresAt)}\n </time>\n </p>\n ) : null}\n {request.allowSkip && singleQuestion ? (\n <p className=\"mt-1 text-og-xs text-og-fg-subtle\">Or skip and let the agent decide.</p>\n ) : null}\n </div>\n <button\n type=\"button\"\n onClick={() => setCollapsed(true)}\n aria-label={messages.collapse}\n title={messages.collapse}\n className=\"inline-flex size-8 shrink-0 items-center justify-center rounded-og-md text-og-fg-muted transition-colors hover:bg-og-surface-1 hover:text-og-fg\"\n >\n <ChevronUpIcon aria-hidden=\"true\" className=\"size-4\" />\n </button>\n </div>\n </header>\n\n <div className=\"relative flex min-h-0 flex-1 flex-col overflow-hidden\">\n <div\n ref={scrollRef}\n className=\"min-h-0 flex-1 overflow-y-auto overscroll-contain [scrollbar-gutter:stable]\"\n >\n <fieldset disabled={busy} className=\"min-w-0 space-y-4 px-4 py-3\">\n {request.questions.map((question, index) => {\n if (singleQuestion) {\n // Title already carries the question; only render the control + help extras.\n return (\n <div key={question.id} data-human-input-question={question.id}>\n <QuestionControls\n question={question}\n questionNumber={null}\n labelledBy={titleId}\n draft={drafts[question.id] ?? emptyDraft()}\n fieldId={`${formId}-${index}`}\n error={validationErrors[question.id]}\n messages={messages}\n autoFocus={autoFocus}\n firstOption\n showPromptChrome={false}\n allowSkip={request.allowSkip}\n busy={busy}\n onUpdate={(apply) => update(question.id, apply)}\n />\n </div>\n );\n }\n return (\n <div\n key={question.id}\n data-human-input-question={question.id}\n className=\"flex flex-col gap-1.5\"\n >\n <QuestionControls\n question={question}\n questionNumber={index + 1}\n labelledBy={undefined}\n draft={drafts[question.id] ?? emptyDraft()}\n fieldId={`${formId}-${index}`}\n error={validationErrors[question.id]}\n messages={messages}\n autoFocus={autoFocus && index === 0}\n firstOption={index === 0}\n showPromptChrome\n allowSkip={request.allowSkip}\n busy={busy}\n onUpdate={(apply) => update(question.id, apply)}\n />\n </div>\n );\n })}\n </fieldset>\n </div>\n {overflowBelow ? (\n <div\n className=\"pointer-events-none absolute inset-x-0 bottom-0 z-[1] flex flex-col items-center\"\n aria-hidden=\"true\"\n >\n <div className=\"h-10 w-full bg-gradient-to-t from-og-surface-1 via-og-surface-1/85 to-transparent\" />\n <span className=\"-mt-5 mb-1 rounded-og-full bg-og-surface-1 px-2.5 py-0.5 text-og-xs font-medium text-og-fg-muted shadow-og-sm ring-1 ring-og-border/60\">\n {messages.moreBelow}\n </span>\n </div>\n ) : null}\n </div>\n\n {(error ?? submissionError) ? (\n <p\n role=\"alert\"\n className=\"relative z-10 shrink-0 px-4 pb-1 text-og-sm text-og-status-failed\"\n >\n {error ?? submissionError}\n </p>\n ) : null}\n\n <footer className=\"relative z-10 flex shrink-0 items-center justify-end gap-2 border-t border-og-status-waiting/20 bg-og-surface-1/95 px-4 py-3 backdrop-blur-[2px]\">\n {request.allowSkip ? (\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => void submitResponse({ outcome: \"skipped\" })}\n className=\"inline-flex min-h-9 items-center rounded-og-md border border-og-border px-3 py-1.5 text-og-sm font-medium text-og-fg-muted transition-colors hover:bg-og-surface-1 hover:text-og-fg disabled:opacity-50\"\n >\n {resolvedSkipLabel}\n </button>\n ) : null}\n <button\n type=\"submit\"\n disabled={busy}\n className=\"inline-flex min-h-9 items-center rounded-og-md bg-og-accent-deep px-3 py-1.5 text-og-sm font-medium text-og-accent-fg transition hover:brightness-110 disabled:opacity-50\"\n >\n {busy ? messages.submitting : resolvedSubmitLabel}\n </button>\n </footer>\n </form>\n );\n}\n\nfunction QuestionControls({\n question,\n questionNumber,\n labelledBy,\n draft,\n fieldId,\n error,\n messages,\n autoFocus,\n firstOption,\n showPromptChrome,\n allowSkip,\n busy,\n onUpdate,\n}: {\n question: HumanInputQuestion;\n questionNumber: number | null;\n labelledBy: string | undefined;\n draft: HumanInputAnswerDraft;\n fieldId: string;\n error: string | undefined;\n messages: HumanInputFormMessages;\n autoFocus: boolean;\n firstOption: boolean;\n showPromptChrome: boolean;\n allowSkip: boolean;\n busy: boolean;\n onUpdate: (apply: (draft: HumanInputAnswerDraft) => HumanInputAnswerDraft) => void;\n}) {\n const errorId = `${fieldId}-error`;\n const helpId = `${fieldId}-help`;\n const labelId = `${fieldId}-label`;\n const promptId = `${fieldId}-prompt`;\n const otherChoiceId = `${fieldId}-other-choice`;\n const otherLabelId = `${fieldId}-other-label`;\n const otherTextId = `${fieldId}-other-text`;\n const visibleLabel = question.label ?? question.prompt;\n const controlLabelId = showPromptChrome ? labelId : labelledBy;\n const hint =\n question.kind === \"multi_select\"\n ? messages.selectionHint(\n question.validation?.minSelections,\n question.validation?.maxSelections,\n )\n : null;\n const describedBy =\n [\n question.label && showPromptChrome ? promptId : null,\n question.helpText && showPromptChrome ? helpId : null,\n hint ? `${fieldId}-hint` : null,\n error ? errorId : null,\n ]\n .filter(Boolean)\n .join(\" \") || undefined;\n const selectOtherDraft = (current: HumanInputAnswerDraft): HumanInputAnswerDraft => ({\n ...current,\n otherSelected: true,\n ...(question.kind === \"single_select\" ? { values: [] } : {}),\n });\n return (\n <>\n {showPromptChrome ? (\n <>\n <div className=\"flex flex-wrap items-baseline gap-x-2\">\n <label\n id={labelId}\n htmlFor={question.kind === \"text\" ? fieldId : undefined}\n className=\"text-og-sm font-medium text-og-fg\"\n >\n {questionNumber === null ? null : (\n <span className=\"mr-1.5 tabular-nums text-og-fg-muted\">{questionNumber}.</span>\n )}\n {questionNumber === null ? null : \" \"}\n {visibleLabel}\n {question.required && !allowSkip ? (\n <span aria-hidden className=\"ml-1 text-og-status-failed\">\n *\n </span>\n ) : !question.required ? (\n <span className=\"ml-1.5 text-og-xs font-normal text-og-fg-subtle\">\n {messages.optional}\n </span>\n ) : null}\n </label>\n </div>\n {question.label ? (\n <p id={promptId} className=\"text-og-sm text-og-fg-muted\">\n {question.prompt}\n </p>\n ) : null}\n {question.helpText ? (\n <p id={helpId} className=\"text-og-xs text-og-fg-subtle\">\n {question.helpText}\n </p>\n ) : null}\n {hint ? (\n <p id={`${fieldId}-hint`} className=\"text-og-xs text-og-fg-subtle\">\n {hint}\n </p>\n ) : null}\n </>\n ) : (\n <>\n {!question.required && allowSkip === false ? (\n <p className=\"text-og-xs text-og-fg-subtle\">{messages.optional}</p>\n ) : null}\n {question.helpText && question.label ? (\n <p id={helpId} className=\"mb-1.5 text-og-xs text-og-fg-subtle\">\n {question.helpText}\n </p>\n ) : null}\n {hint ? (\n <p id={`${fieldId}-hint`} className=\"mb-1.5 text-og-xs text-og-fg-subtle\">\n {hint}\n </p>\n ) : null}\n </>\n )}\n\n {question.kind === \"text\" ? (\n <textarea\n id={fieldId}\n value={draft.values[0] ?? \"\"}\n onChange={(event) =>\n onUpdate((current) => ({\n ...current,\n values: event.target.value ? [event.target.value] : [],\n }))\n }\n aria-invalid={Boolean(error)}\n aria-labelledby={controlLabelId}\n aria-describedby={describedBy}\n autoFocus={autoFocus}\n rows={2}\n className=\"min-h-14 w-full resize-y rounded-og-md border border-og-border bg-og-surface-1 px-3 py-2 text-og-sm text-og-fg outline-hidden placeholder:text-og-fg-subtle focus:border-og-accent\"\n />\n ) : (\n <div\n role={question.kind === \"single_select\" ? \"radiogroup\" : \"group\"}\n aria-labelledby={controlLabelId}\n aria-describedby={describedBy}\n className=\"flex flex-col gap-0.5\"\n >\n {question.options.map((option, optionIndex) => {\n const checked = draft.values.includes(option.id);\n return (\n <label\n key={option.id}\n className={cn(\n \"flex cursor-pointer items-start gap-2.5 rounded-og-md px-2.5 py-2 transition-colors\",\n checked\n ? \"bg-og-status-waiting/12 text-og-fg\"\n : \"text-og-fg hover:bg-og-surface-1/80\",\n )}\n >\n <input\n type={question.kind === \"single_select\" ? \"radio\" : \"checkbox\"}\n name={question.kind === \"single_select\" ? fieldId : undefined}\n autoFocus={autoFocus && firstOption && optionIndex === 0}\n checked={checked}\n onChange={(event) =>\n onUpdate((current) => ({\n ...current,\n values:\n question.kind === \"single_select\"\n ? event.target.checked\n ? [option.id]\n : []\n : event.target.checked\n ? [...current.values, option.id]\n : current.values.filter((value) => value !== option.id),\n ...(question.kind === \"single_select\" && event.target.checked\n ? { otherSelected: false }\n : {}),\n }))\n }\n className=\"mt-0.5 accent-og-accent\"\n />\n <span className=\"min-w-0\">\n <span className=\"block text-og-sm font-medium\">{option.label}</span>\n {option.description ? (\n <span className=\"mt-0.5 block text-og-xs text-og-fg-muted\">\n {option.description}\n </span>\n ) : null}\n </span>\n </label>\n );\n })}\n <div\n className={cn(\n \"flex items-start gap-2.5 rounded-og-md px-2.5 py-2 transition-colors\",\n draft.otherSelected\n ? \"bg-og-status-waiting/12 text-og-fg\"\n : \"text-og-fg hover:bg-og-surface-1/80\",\n )}\n >\n <input\n id={otherChoiceId}\n type={question.kind === \"single_select\" ? \"radio\" : \"checkbox\"}\n name={question.kind === \"single_select\" ? fieldId : undefined}\n aria-labelledby={otherLabelId}\n checked={draft.otherSelected}\n autoFocus={autoFocus && firstOption && question.options.length === 0}\n onChange={(event) =>\n onUpdate((current) => ({\n ...current,\n otherSelected: event.target.checked,\n ...(question.kind === \"single_select\" && event.target.checked\n ? { values: [] }\n : {}),\n }))\n }\n className=\"mt-2 accent-og-accent\"\n />\n <span className=\"min-w-0 flex-1\">\n <label\n id={otherLabelId}\n htmlFor={otherChoiceId}\n className=\"block text-og-sm font-medium\"\n >\n {messages.other}\n </label>\n <label htmlFor={otherTextId} className=\"sr-only\">\n {messages.other} answer for {visibleLabel}\n </label>\n <input\n id={otherTextId}\n type=\"text\"\n value={draft.other}\n disabled={busy}\n placeholder=\"Type a value…\"\n onClick={() => onUpdate(selectOtherDraft)}\n onFocus={() => onUpdate(selectOtherDraft)}\n onChange={(event) => {\n const other = event.target.value;\n onUpdate((current) => ({\n ...selectOtherDraft(current),\n other,\n }));\n }}\n className=\"mt-1.5 w-full rounded-og-sm border border-og-border bg-og-surface-1 px-2 py-1.5 text-og-sm text-og-fg outline-hidden focus:border-og-accent disabled:opacity-50\"\n />\n </span>\n </div>\n </div>\n )}\n {error ? (\n <p id={errorId} role=\"alert\" className=\"text-og-xs text-og-status-failed\">\n {error}\n </p>\n ) : null}\n </>\n );\n}\n\nexport function answersFromDrafts(\n questions: HumanInputQuestion[],\n drafts: Record<string, HumanInputAnswerDraft>,\n messageOverrides: Partial<HumanInputFormMessages> = {},\n): { answers: HumanInputAnswer[]; errors: Record<string, string> } {\n const messages = { ...defaultHumanInputFormMessages, ...messageOverrides };\n const answers: HumanInputAnswer[] = [];\n const errors: Record<string, string> = {};\n for (const question of questions) {\n const draft = drafts[question.id] ?? emptyDraft();\n const values = question.kind === \"text\" ? draft.values.filter(Boolean) : draft.values;\n const other = draft.otherSelected ? draft.other : \"\";\n const hasOther = Boolean(other.trim());\n const supplied = values.length + (hasOther ? 1 : 0);\n\n // Other-selected-but-empty must win over generic \"required\" — otherwise the\n // user sees the wrong diagnosis next to a clearly selected control.\n if (question.kind !== \"text\" && draft.otherSelected && !hasOther) {\n errors[question.id] = messages.otherRequired;\n continue;\n }\n\n if (question.required && supplied === 0) {\n errors[question.id] = messages.required;\n continue;\n }\n if (question.kind !== \"text\") {\n const min = question.validation?.minSelections;\n const max = question.kind === \"single_select\" ? 1 : question.validation?.maxSelections;\n if (min != null && supplied < min) {\n errors[question.id] = messages.minSelections(min);\n continue;\n }\n if (max != null && supplied > max) {\n errors[question.id] = messages.maxSelections(max);\n continue;\n }\n }\n if (supplied > 0) {\n answers.push({\n questionId: question.id,\n values,\n ...(hasOther ? { other } : {}),\n });\n }\n }\n return { answers, errors };\n}\n\nfunction initialDrafts(questions: HumanInputQuestion[]): Record<string, HumanInputAnswerDraft> {\n return Object.fromEntries(questions.map((question) => [question.id, emptyDraft()]));\n}\n\nfunction emptyDraft(): HumanInputAnswerDraft {\n return { values: [], other: \"\", otherSelected: false };\n}\n\nfunction formatDeadline(value: string): string {\n const date = new Date(value);\n if (Number.isNaN(date.getTime())) return value;\n const ms = date.getTime() - Date.now();\n if (ms <= 0) return \"deadline passed\";\n const minutes = Math.round(ms / 60_000);\n if (minutes < 1) return \"in under a minute\";\n if (minutes < 60) return `in ${minutes}m`;\n const hours = Math.round(minutes / 60);\n if (hours < 48) return `in ${hours}h`;\n return date.toLocaleString();\n}\n","import type { SessionHumanInputRequest, SubmitHumanInputResponseRequest } from \"@opengeni/sdk\";\nimport { useEffect, useMemo, useRef } from \"react\";\nimport { isActionableHumanInputRequest } from \"../human-input\";\nimport { cn } from \"../lib/cn\";\nimport {\n HumanInputForm,\n type HumanInputFormMessages,\n type HumanInputFormProps,\n} from \"./human-input-form\";\n\nexport type HumanInputSurfaceProps = {\n requests: SessionHumanInputRequest[];\n onSubmit: (requestId: string, response: SubmitHumanInputResponseRequest) => void | Promise<void>;\n respondingRequestId?: string | null | undefined;\n error?: string | null | undefined;\n messages?: Partial<HumanInputFormMessages> | undefined;\n className?: string | undefined;\n /** Forwarded to the active form. Defaults true. */\n autoFocus?: boolean | undefined;\n};\n\n/**\n * One decision shell for pending structured human-input requests. Parallel\n * freezes are shown one at a time (oldest first) as “N of M”; Send answers/Skip\n * settles the active request and the next remaining set advances automatically\n * when the authoritative pending list updates.\n */\nexport function HumanInputSurface({\n requests,\n onSubmit,\n respondingRequestId = null,\n error,\n messages,\n className,\n autoFocus = true,\n}: HumanInputSurfaceProps) {\n const batchTotalRef = useRef(0);\n\n const ordered = useMemo(() => {\n const now = Date.now();\n return requests\n .filter((request) => isActionableHumanInputRequest(request, now))\n .sort((a, b) => {\n const aAt = a.createdAt ? Date.parse(a.createdAt) : 0;\n const bAt = b.createdAt ? Date.parse(b.createdAt) : 0;\n if (aAt !== bAt) return aAt - bAt;\n return a.id.localeCompare(b.id);\n });\n }, [requests]);\n\n useEffect(() => {\n if (ordered.length === 0) {\n batchTotalRef.current = 0;\n return;\n }\n batchTotalRef.current =\n batchTotalRef.current === 0\n ? ordered.length\n : Math.max(batchTotalRef.current, ordered.length);\n }, [ordered]);\n\n if (ordered.length === 0) return null;\n\n const active = ordered[0]!;\n const batchTotal = Math.max(batchTotalRef.current, ordered.length);\n const position = batchTotal - ordered.length + 1;\n const progressLabel = batchTotal > 1 ? `${position} of ${batchTotal}` : null;\n\n const formProps: HumanInputFormProps = {\n request: active,\n submitting: respondingRequestId !== null,\n error: error ?? null,\n progressLabel,\n autoFocus,\n ...(messages ? { messages } : {}),\n onSubmit: (response) => onSubmit(active.id, response),\n };\n\n return (\n <div className={cn(\"w-full\", className)} data-human-input-surface=\"\">\n <HumanInputForm {...formProps} />\n </div>\n );\n}\n","import { CheckIcon, CopyIcon } from \"lucide-react\";\nimport { useEffect, useRef, useState, type MouseEvent, type ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { copyTextToClipboard } from \"../lib/clipboard\";\nimport { Tooltip, TooltipContent, TooltipTrigger } from \"./tooltip\";\n\nconst COPIED_MS = 1600;\n\nexport type CopyButtonProps = {\n /** Plain text to copy, or a lazy getter (tables / late DOM). */\n text: string | (() => string);\n /** Accessible name + tooltip while idle. */\n label?: string | undefined;\n className?: string | undefined;\n /**\n * `always` — visible control.\n * `group-hover` — parent must use `group/copy`; fades in on hover/focus-visible.\n */\n reveal?: \"always\" | \"group-hover\" | undefined;\n};\n\n/**\n * Ghost icon copy control — no chrome box, no \"Copy code\" label.\n * Copy → check flash. Hover-reveal via `group/copy` on a parent.\n */\nexport function CopyButton({\n text,\n label = \"Copy\",\n className,\n reveal = \"group-hover\",\n}: CopyButtonProps) {\n const [copied, setCopied] = useState(false);\n const [tipOpen, setTipOpen] = useState(false);\n const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n useEffect(() => {\n return () => {\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n }\n };\n }, []);\n\n const onClick = async (event: MouseEvent<HTMLButtonElement>) => {\n event.preventDefault();\n event.stopPropagation();\n // Capture before any await: React nulls `currentTarget` after the\n // synchronous handler turn. Blurring via the stale target throws and used\n // to skip the copied-reset timer, leaving the tip stuck on \"Copied\".\n const button = event.currentTarget;\n const pointerActivated = event.detail > 0;\n const value = typeof text === \"function\" ? text() : text;\n const ok = await copyTextToClipboard(value);\n if (!ok) {\n return;\n }\n setCopied(true);\n setTipOpen(true);\n if (timerRef.current !== null) {\n clearTimeout(timerRef.current);\n }\n // Always arm the reset before blur — a throw here must not leave the\n // forced \"Copied\" tip open forever.\n timerRef.current = setTimeout(() => {\n timerRef.current = null;\n setCopied(false);\n setTipOpen(false);\n }, COPIED_MS);\n // Pointer activation focuses the button and leaves `group-focus-within`\n // stuck after the cursor leaves — chrome never \"unhovers\". Keyboard\n // activation (`detail === 0`) keeps focus for a11y.\n if (pointerActivated) {\n button.blur();\n }\n };\n\n const tip = copied ? \"Copied\" : label;\n\n return (\n <Tooltip\n open={copied ? true : tipOpen}\n onOpenChange={(next) => {\n if (!copied) {\n setTipOpen(next);\n }\n }}\n >\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n data-og-copy=\"\"\n data-state={copied ? \"copied\" : \"idle\"}\n aria-label={tip}\n onClick={onClick}\n className={cn(\n \"inline-flex size-7 shrink-0 items-center justify-center rounded-og-sm pointer-coarse:size-11\",\n \"text-og-fg-subtle transition-[opacity,color,background-color] duration-150\",\n \"hover:bg-og-surface-2/80 hover:text-og-fg\",\n \"focus-visible:opacity-100 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-og-accent/40\",\n reveal === \"group-hover\" &&\n \"opacity-0 group-hover/copy:opacity-100 group-focus-within/copy:opacity-100 pointer-coarse:opacity-70\",\n copied && \"opacity-100 text-og-accent\",\n className,\n )}\n >\n {copied ? (\n <CheckIcon className=\"size-3.5\" aria-hidden />\n ) : (\n <CopyIcon className=\"size-3.5\" aria-hidden />\n )}\n </button>\n </TooltipTrigger>\n <TooltipContent side=\"top\">{tip}</TooltipContent>\n </Tooltip>\n );\n}\n\n/** Hover-reveal chrome around a message / turn so {@link CopyButton} can fade in. */\nexport function CopyHoverFrame({\n children,\n className,\n copyText,\n label,\n align = \"end\",\n trailing,\n}: {\n children: ReactNode;\n className?: string | undefined;\n copyText: string;\n label: string;\n align?: \"start\" | \"end\" | undefined;\n /** Optional footer meta (e.g. sent/finished clock) — immediately after the copy control. */\n trailing?: ReactNode | undefined;\n}) {\n if (copyText.trim().length === 0) {\n return <div className={className}>{children}</div>;\n }\n return (\n <div className={cn(\"group/copy\", className)}>\n {children}\n {/* Sit under the body — top-right overlay collided with the first line. */}\n <div\n className={cn(\n \"mt-1 flex h-7 items-center gap-1.5\",\n align === \"end\" ? \"justify-end\" : \"justify-start\",\n )}\n >\n <CopyButton text={copyText} label={label} reveal=\"group-hover\" />\n {trailing}\n </div>\n </div>\n );\n}\n","import {\n Children,\n isValidElement,\n memo,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type ComponentPropsWithoutRef,\n type ReactNode,\n} from \"react\";\nimport ReactMarkdown, {\n defaultUrlTransform,\n type Components,\n type UrlTransform,\n} from \"react-markdown\";\nimport remarkGfm from \"remark-gfm\";\nimport { cn } from \"../lib/cn\";\nimport { tableElementToTsv } from \"../lib/clipboard\";\nimport { prefersReducedMotion } from \"../lib/motion\";\nimport { MOTION_INSPECT_SCALE } from \"../lib/motion-inspect\";\nimport { CopyButton } from \"./copy-button\";\nimport { softenStreamingMarkdown } from \"./soften-streaming-markdown\";\nimport { createStreamReveal, rehypeStreamReveal, type StreamReveal } from \"./stream-reveal\";\nimport { TooltipProvider } from \"./tooltip\";\n\n/**\n * The default renderer for chat message bodies in {@link MessageTimeline}.\n *\n * Agent (and user) messages arrive as GitHub-flavored markdown. This turns the\n * raw text into styled HTML using `react-markdown` + `remark-gfm`, themed to the\n * package's `og-*` design tokens so it reads as one cohesive dark surface — no\n * stock Tailwind colors leak in.\n *\n * It re-parses on every render, which is exactly right for streaming: a body\n * that is still arriving (an unterminated `**`, a half-open code fence, a table\n * mid-row) renders as best-effort markdown and resolves cleanly as the rest of\n * the tokens land. Consumers who want a different renderer can still pass\n * `renderMessageText` to `MessageTimeline` to override this entirely.\n */\nexport type MarkdownProps = {\n children: string;\n className?: string | undefined;\n /**\n * While true, newly arrived source fades in through tip ink (`.og-stream-ink`):\n * an age window over each append batch — fast streams keep a large soft band,\n * slow streams a tight tip. Paint-only: the DOM always holds the full truthful\n * text. Once streaming ends and trailing ink settles, the body re-renders as\n * plain markdown with a short local settle breath (no page-wide view\n * transition — that blinked the whole document).\n */\n streaming?: boolean | undefined;\n /**\n * Open a session-local file link in the host's Files surface. The path is the\n * exact decoded `sandbox:` payload; `line`, when present, is 1-based.\n */\n onSandboxFile?: ((path: string, line?: number) => void | Promise<void>) | undefined;\n};\n\n/** Exact target path plus optional 1-based line from a markdown href. */\nexport type SandboxFileLocation = {\n path: string;\n line: number | null;\n};\n\n/* --- element renderers (themed to og-* tokens) ------------------------------ */\n\nconst baseComponents: Components = {\n h1: ({ children, ...props }) => (\n <h1\n className=\"mt-5 mb-2.5 text-xl font-semibold tracking-tight text-og-fg first:mt-0\"\n {...props}\n >\n {children}\n </h1>\n ),\n h2: ({ children, ...props }) => (\n <h2 className=\"mt-5 mb-2 text-lg font-semibold tracking-tight text-og-fg first:mt-0\" {...props}>\n {children}\n </h2>\n ),\n h3: ({ children, ...props }) => (\n <h3\n className=\"mt-4 mb-1.5 text-og-md font-semibold tracking-tight text-og-fg first:mt-0\"\n {...props}\n >\n {children}\n </h3>\n ),\n h4: ({ children, ...props }) => (\n <h4\n className=\"mt-4 mb-1.5 text-og-sm font-semibold uppercase tracking-[0.04em] text-og-fg-muted first:mt-0\"\n {...props}\n >\n {children}\n </h4>\n ),\n p: ({ children, ...props }) => (\n <p className=\"my-2.5 leading-7 first:mt-0 last:mb-0\" {...props}>\n {children}\n </p>\n ),\n strong: ({ children, ...props }) => (\n <strong className=\"font-semibold text-og-fg\" {...props}>\n {children}\n </strong>\n ),\n em: ({ children, ...props }) => (\n <em className=\"italic\" {...props}>\n {children}\n </em>\n ),\n ul: ({ children, ...props }) => (\n <ul\n className=\"my-2.5 ml-5 flex list-disc flex-col gap-1 marker:text-og-fg-subtle first:mt-0 last:mb-0\"\n {...props}\n >\n {children}\n </ul>\n ),\n ol: ({ children, ...props }) => (\n <ol\n className=\"my-2.5 ml-5 flex list-decimal flex-col gap-1 marker:text-og-fg-subtle first:mt-0 last:mb-0\"\n {...props}\n >\n {children}\n </ol>\n ),\n // GFM task-list items carry a leading checkbox <input>; `list-none` + a\n // negative margin pull the checkbox back to the bullet column so it aligns\n // with the text.\n li: ({ children, ...props }) => (\n <li\n className=\"leading-7 marker:text-og-fg-subtle [&>ul]:my-1 [&>ol]:my-1 [&:has(>input)]:list-none [&:has(>input)]:-ml-5\"\n {...props}\n >\n {children}\n </li>\n ),\n input: ({ type, ...props }) =>\n type === \"checkbox\" ? (\n <input\n {...props}\n type=\"checkbox\"\n disabled\n className=\"mr-2 size-3.5 translate-y-[2px] cursor-default accent-og-accent align-baseline\"\n />\n ) : (\n <input type={type} {...props} />\n ),\n blockquote: ({ children, ...props }) => (\n <blockquote\n className=\"my-3 border-l-2 border-og-border-strong pl-3.5 text-og-fg-muted [&>p]:my-1.5 first:mt-0 last:mb-0\"\n {...props}\n >\n {children}\n </blockquote>\n ),\n hr: (props) => <hr className=\"my-4 border-0 border-t border-og-border\" {...props} />,\n // Inline `code` vs fenced code blocks. react-markdown v10 no longer passes an\n // `inline` flag; a fenced block is a <code> whose parent is <pre> (styled by\n // the `pre` renderer), so a `code` reaching here is treated as inline.\n code: ({ children, className: _className, ...props }) => (\n <code\n className=\"rounded-og-xs bg-og-surface-1 px-1 py-0.5 font-og-mono text-og-sm text-og-fg\"\n {...props}\n >\n {children}\n </code>\n ),\n // Fenced code — quiet mono block (no card / no nested vertical scroll).\n pre: ({ children }) => <MarkdownCodeBlock>{children}</MarkdownCodeBlock>,\n // Tables stay unboxed (hairline rules); hover reveals a TSV copy control.\n table: ({ children, ...props }) => <MarkdownTable {...props}>{children}</MarkdownTable>,\n thead: ({ children, ...props }) => <thead {...props}>{children}</thead>,\n th: ({ children, ...props }) => (\n <th\n className=\"border-b border-og-border px-0 py-1.5 pr-4 text-left font-medium text-og-fg first:pl-0\"\n {...props}\n >\n {children}\n </th>\n ),\n td: ({ children, ...props }) => (\n <td\n className=\"border-b border-og-border/70 px-0 py-1.5 pr-4 align-top text-og-fg-muted [tr:last-child>&]:border-b-0\"\n {...props}\n >\n {children}\n </td>\n ),\n img: ({ alt, src, ...props }) =>\n src ? (\n <img\n alt={alt ?? \"\"}\n src={src}\n className=\"my-3 max-w-full rounded-og-md border border-og-border\"\n {...props}\n />\n ) : alt ? (\n <span className=\"text-og-fg-subtle\" aria-disabled=\"true\">\n {alt}\n </span>\n ) : null,\n};\n\nconst MARKDOWN_LINK_CLASS =\n \"break-words font-medium text-og-accent-strong underline-offset-2 hover:underline\";\n\nfunction markdownComponents(onSandboxFile: MarkdownProps[\"onSandboxFile\"]): Components {\n return {\n ...baseComponents,\n a: ({ children, href, ...props }) => {\n const location = sandboxFileLocationFromHref(href);\n if (location !== null) {\n return (\n <SandboxMarkdownLink location={location} onSandboxFile={onSandboxFile}>\n {children}\n </SandboxMarkdownLink>\n );\n }\n if (isSandboxHref(href) || !href) {\n return (\n <span\n className=\"break-words font-medium text-og-fg-subtle underline decoration-dotted underline-offset-2\"\n aria-disabled=\"true\"\n title={\n isSandboxHref(href)\n ? \"This sandbox file reference is invalid\"\n : \"This link is unavailable\"\n }\n >\n {children}\n </span>\n );\n }\n return (\n <a\n className={MARKDOWN_LINK_CLASS}\n target=\"_blank\"\n rel=\"noreferrer noopener\"\n href={href}\n {...props}\n >\n {children}\n </a>\n );\n },\n };\n}\n\nfunction SandboxMarkdownLink({\n location,\n onSandboxFile,\n children,\n}: {\n location: SandboxFileLocation;\n onSandboxFile: MarkdownProps[\"onSandboxFile\"];\n children: ReactNode;\n}) {\n const [state, setState] = useState<\"idle\" | \"loading\" | \"error\">(\"idle\");\n const { path, line } = location;\n if (!onSandboxFile) {\n return (\n <span\n className=\"break-words font-medium text-og-fg-subtle underline decoration-dotted underline-offset-2\"\n aria-disabled=\"true\"\n title=\"This sandbox file requires a session-aware handler\"\n >\n {children}\n </span>\n );\n }\n const idleTitle = line !== null ? `Open ${path} at line ${line}` : `Open ${path}`;\n return (\n <button\n type=\"button\"\n className={cn(\n MARKDOWN_LINK_CLASS,\n \"inline-flex min-h-7 cursor-pointer items-center disabled:cursor-wait disabled:opacity-70 pointer-coarse:min-h-11\",\n )}\n disabled={state === \"loading\"}\n aria-busy={state === \"loading\"}\n title={state === \"error\" ? \"Couldn't open this file. Select to retry.\" : idleTitle}\n onClick={() => {\n setState(\"loading\");\n void Promise.resolve(onSandboxFile(path, line ?? undefined)).then(\n () => setState(\"idle\"),\n () => setState(\"error\"),\n );\n }}\n >\n {children}\n {state === \"loading\" ? \" (opening…)\" : state === \"error\" ? \" (retry)\" : null}\n </button>\n );\n}\n\nconst SANDBOX_SCHEME = \"sandbox:\";\nconst LEGACY_WORKSPACE_PREFIX = \"/workspace/\";\nconst TRAILING_LINE = /:([0-9]+)$/u;\nconst TRAILING_INVALID_LINE = /:-(?:[0-9]+)$|:[0-9]+-[0-9]+$/u;\nconst CONTROL_CHARACTER = /[\\u0000-\\u001f\\u007f]/u;\n\nfunction isSandboxHref(href: string | undefined): boolean {\n return href?.startsWith(SANDBOX_SCHEME) ?? false;\n}\n\n/**\n * Parse an OpenGeni `sandbox:` application href (plus the historical bare\n * `/workspace/...` form). The decoded path is intentionally opaque here:\n * target selection, path policy, and filesystem authority belong to the\n * session-aware host and its FileSystem boundary.\n */\nexport function sandboxFileLocationFromHref(href: string | undefined): SandboxFileLocation | null {\n if (!href) return null;\n const encodedLocation = isSandboxHref(href)\n ? href.slice(SANDBOX_SCHEME.length)\n : href.startsWith(LEGACY_WORKSPACE_PREFIX)\n ? href\n : null;\n if (!encodedLocation || encodedLocation.includes(\"?\") || encodedLocation.includes(\"#\")) {\n return null;\n }\n if (TRAILING_INVALID_LINE.test(encodedLocation)) return null;\n const lineMatch = TRAILING_LINE.exec(encodedLocation);\n const encodedPath = lineMatch ? encodedLocation.slice(0, -lineMatch[0].length) : encodedLocation;\n const line = lineMatch?.[1] ? Number(lineMatch[1]) : null;\n if (line !== null && (!Number.isSafeInteger(line) || line < 1)) return null;\n if (!encodedPath) return null;\n try {\n const path = decodeURIComponent(encodedPath);\n return path && !CONTROL_CHARACTER.test(path) ? { path, line } : null;\n } catch {\n return null;\n }\n}\n\n/** Return the exact decoded path for a supported sandbox-link href. */\nexport function sandboxFilePathFromHref(href: string | undefined): string | null {\n return sandboxFileLocationFromHref(href)?.path ?? null;\n}\n\nconst markdownUrlTransform: UrlTransform = (url, key, node) =>\n key === \"href\" && node.tagName === \"a\" && isSandboxHref(url) ? url : defaultUrlTransform(url);\n\n/** How long after the stream ends the reveal pipeline stays for trailing animations. */\n/** Trailing ink window after stream end — keep ≥ {@link INK_FADE_MS}. */\nconst REVEAL_LINGER_MS = 480 * MOTION_INSPECT_SCALE;\n/** Keep in sync with `--og-duration-markdown-crystallize` / view-transition CSS. */\nconst MARKDOWN_SETTLE_MS = 480 * MOTION_INSPECT_SCALE;\n\nfunction nodeText(node: ReactNode): string {\n if (node == null || typeof node === \"boolean\") {\n return \"\";\n }\n if (typeof node === \"string\" || typeof node === \"number\") {\n return String(node);\n }\n if (Array.isArray(node)) {\n return node.map(nodeText).join(\"\");\n }\n if (isValidElement<{ children?: ReactNode }>(node)) {\n return nodeText(node.props.children);\n }\n return \"\";\n}\n\nfunction fenceLanguage(children: ReactNode): string | null {\n let found: string | null = null;\n Children.forEach(children, (child) => {\n if (found || !isValidElement<{ className?: string }>(child)) {\n return;\n }\n const match = /language-([a-zA-Z0-9_+-]+)/.exec(child.props.className ?? \"\");\n if (match?.[1]) {\n found = match[1];\n }\n });\n return found;\n}\n\nfunction MarkdownCodeBlock({ children }: { children?: ReactNode }) {\n const code = nodeText(children).replace(/\\n$/, \"\");\n const language = fenceLanguage(children);\n // mt-only (no mb / last:mb-0): next sibling streaming in used to flip a\n // previous block's bottom margin on and yank tip-follow. Copy is overlay-only.\n // Fixed leading + overflow-x:auto with stable block chrome so wide ASCII lines\n // don't pop a scrollbar gutters mid-stream (another tip bob).\n return (\n <div className=\"group/copy relative mt-3 first:mt-0\">\n <div className=\"pointer-events-none absolute top-1.5 right-1.5 z-10 flex items-center gap-1\">\n {language ? (\n <span className=\"rounded px-1 py-0.5 font-og-mono text-[10px] uppercase tracking-wide text-og-fg-subtle/80 opacity-0 transition-opacity group-hover/copy:opacity-100 pointer-coarse:opacity-70\">\n {language}\n </span>\n ) : null}\n <div className=\"pointer-events-auto\">\n <CopyButton text={code} label=\"Copy code\" reveal=\"group-hover\" />\n </div>\n </div>\n <pre\n tabIndex={0}\n className=\"overflow-x-auto overflow-y-hidden rounded-og-md bg-og-surface-1/70 px-3 py-2.5 font-og-mono text-og-sm leading-5 text-og-fg-muted [scrollbar-gutter:stable] [&>code]:block [&>code]:border-0 [&>code]:bg-transparent [&>code]:p-0 [&>code]:leading-5 [&>code]:text-inherit\"\n >\n {children}\n </pre>\n </div>\n );\n}\n\nfunction MarkdownTable({ children, className, ...props }: ComponentPropsWithoutRef<\"table\">) {\n const tableRef = useRef<HTMLTableElement | null>(null);\n return (\n <div className=\"group/copy relative mt-3 max-w-full first:mt-0\">\n <div className=\"pointer-events-none absolute top-0 right-0 z-10\">\n <div className=\"pointer-events-auto\">\n <CopyButton\n text={() => tableElementToTsv(tableRef.current)}\n label=\"Copy table\"\n reveal=\"group-hover\"\n />\n </div>\n </div>\n <div className=\"overflow-x-auto\" tabIndex={0}>\n <table\n ref={tableRef}\n className={cn(\"w-full min-w-0 border-collapse text-og-base\", className)}\n {...props}\n >\n {children}\n </table>\n </div>\n </div>\n );\n}\n\nfunction MarkdownImpl({ children, className, streaming = false, onSandboxFile }: MarkdownProps) {\n // Tip-ink engine for THIS body: created on the first streaming render, kept\n // through a short linger after the stream ends (so the last age window can\n // finish), then dropped so settled bodies pay zero cost. Observing during\n // render is idempotent per text length — StrictMode double-renders are safe.\n const revealRef = useRef<StreamReveal | null>(null);\n const bodyRef = useRef<HTMLDivElement | null>(null);\n const [, bump] = useReducer((n: number) => n + 1, 0);\n const [settling, setSettling] = useState(false);\n const hadRevealRef = useRef(false);\n const now = typeof performance !== \"undefined\" ? performance.now() : Date.now();\n\n // Local settle breath only — View Transitions with `::view-transition-*(*)`\n // were fading the document root and felt like a full-page blink / focus loss\n // right as a turn ended (just before the next user message in the seed loop).\n const crystallize = (mutate: () => void) => {\n mutate();\n setSettling(true);\n bump();\n return setTimeout(() => setSettling(false), MARKDOWN_SETTLE_MS);\n };\n if (streaming && revealRef.current === null && !prefersReducedMotion()) {\n revealRef.current = createStreamReveal();\n }\n const reveal = revealRef.current;\n if (reveal !== null && streaming) {\n reveal.observe(children, now);\n }\n if (reveal !== null) {\n hadRevealRef.current = true;\n }\n const revealActive = reveal !== null && (streaming || reveal.hasActive(now));\n // The plugin walks the standard hast tree; a structural local type keeps the\n // module dependency-free, at the cost of this narrowing cast at the seam.\n const rehypePlugins =\n revealActive && reveal !== null\n ? ([[rehypeStreamReveal, { reveal, now }]] as unknown as NonNullable<\n Parameters<typeof ReactMarkdown>[0][\"rehypePlugins\"]\n >)\n : undefined;\n\n // Drop tip ink after trailing age windows finish. Same commit crystallizes:\n // ink spans → final plain markdown (soften off) + a short local settle breath.\n useEffect(() => {\n if (streaming || revealRef.current === null) {\n return;\n }\n let clearSettle: ReturnType<typeof setTimeout> | undefined;\n const timer = setTimeout(() => {\n const shouldSettle = hadRevealRef.current && !prefersReducedMotion();\n if (shouldSettle) {\n hadRevealRef.current = false;\n }\n if (shouldSettle) {\n clearSettle = crystallize(() => {\n revealRef.current = null;\n });\n } else {\n revealRef.current = null;\n bump();\n }\n }, REVEAL_LINGER_MS);\n return () => {\n clearTimeout(timer);\n if (clearSettle !== undefined) {\n clearTimeout(clearSettle);\n }\n };\n }, [streaming]);\n\n // No-reveal path (stream ended before any ink batch): soften already dropped\n // with `streaming`; keep the same local settle breath.\n const wasStreamingRef = useRef(streaming);\n useEffect(() => {\n const ended = wasStreamingRef.current && !streaming;\n wasStreamingRef.current = streaming;\n if (!ended || revealRef.current !== null || prefersReducedMotion()) {\n return;\n }\n setSettling(true);\n const timer = setTimeout(() => setSettling(false), MARKDOWN_SETTLE_MS);\n return () => clearTimeout(timer);\n }, [streaming]);\n\n // Soften unfinished markers for DISPLAY while the reveal pipeline is alive\n // (stream + linger) — not only while `streaming` — so task lists / tables /\n // fences don't snap to final GFM one commit before the crystallize morph.\n // Reveal identity still tracks the true source (`children`).\n const parseText = streaming || revealActive ? softenStreamingMarkdown(children) : children;\n const components = useMemo(() => markdownComponents(onSandboxFile), [onSandboxFile]);\n\n // `min-w-0` lets the prose shrink inside flex parents (message bubbles) so\n // long links and code blocks wrap/scroll instead of forcing overflow.\n return (\n <TooltipProvider delayDuration={400}>\n <div\n ref={bodyRef}\n className={cn(\n \"og-markdown-body min-w-0 break-words\",\n settling && \"og-markdown-settle\",\n className,\n )}\n >\n <ReactMarkdown\n remarkPlugins={[remarkGfm]}\n rehypePlugins={rehypePlugins}\n components={components}\n urlTransform={markdownUrlTransform}\n >\n {parseText}\n </ReactMarkdown>\n </div>\n </TooltipProvider>\n );\n}\n\n/** Memoized so streaming re-renders of the parent don't re-parse settled bodies. */\nexport const Markdown = memo(MarkdownImpl);\n","import { flushSync } from \"react-dom\";\n\n/**\n * Live `prefers-reduced-motion` check for JS-driven motion (scroll glides,\n * streaming word reveals). CSS animations are already neutralized globally in\n * styles/index.css; this lets the imperative paths skip their work entirely.\n */\nlet query: MediaQueryList | null | undefined;\n\nexport function prefersReducedMotion(): boolean {\n if (query === undefined) {\n query =\n typeof window !== \"undefined\" && typeof window.matchMedia === \"function\"\n ? window.matchMedia(\"(prefers-reduced-motion: reduce)\")\n : null;\n }\n return query?.matches ?? false;\n}\n\n/** Test seam: forget the cached MediaQueryList so a stubbed matchMedia applies. */\nexport function resetReducedMotionCache(): void {\n query = undefined;\n}\n\ntype ViewTransitionResult = { finished: Promise<void> };\ntype ViewTransitionCallback = () => void;\ntype ViewTransitionOptions = {\n update: ViewTransitionCallback;\n types?: string[];\n};\ntype ViewTransitionStarter = {\n (callback: ViewTransitionCallback): ViewTransitionResult;\n (options: ViewTransitionOptions): ViewTransitionResult;\n};\n\n/** Active VT type for markdown crystallize — scoped CSS, not a full-page blink. */\nexport const MARKDOWN_CRYSTALLIZE_VT_TYPE = \"og-md-crystallize\";\n\n/**\n * Run a DOM update inside the browser View Transition API when available.\n * Snapshots the before/after paint and cross-fades (or custom CSS morphs)\n * between them — the platform \"morph\" primitive React's experimental\n * `<ViewTransition>` wraps. Falls back to a synchronous update.\n */\nexport function runViewTransition(update: () => void, options?: { types?: string[] }): void {\n if (prefersReducedMotion()) {\n update();\n return;\n }\n const doc = typeof document !== \"undefined\" ? document : null;\n const start = doc\n ? ((doc as Document & { startViewTransition?: ViewTransitionStarter }).startViewTransition ??\n null)\n : null;\n if (typeof start !== \"function\") {\n update();\n return;\n }\n const types = options?.types;\n if (types && types.length > 0) {\n try {\n Reflect.apply(start, doc, [\n {\n update: () => {\n flushSync(update);\n },\n types,\n },\n ]);\n return;\n } catch {\n // Older engines only accept the callback form.\n }\n }\n Reflect.apply(start, doc, [\n () => {\n flushSync(update);\n },\n ]);\n}\n","/**\n * TEMP eyeball scale for vertical motion (tip-follow, settle fold, CSS).\n * Set back to `1` before landing — not a product knob.\n */\nexport const MOTION_INSPECT_SCALE = 1;\n","/**\n * Display-only softener for mid-stream markdown.\n *\n * While tokens are still arriving, incomplete markers (`**bold`, an open\n * fence, a half-finished link) would otherwise render as raw punctuation —\n * the hard \"breaking\" flash. This closes a small set of common unfinished\n * constructs so the parse looks settled; the SOURCE string is never mutated\n * (callers pass the softened copy only into the markdown parser).\n *\n * When the real closers land, the softened and true parses converge and the\n * crystallize breath covers the remount.\n */\n\nexport function softenStreamingMarkdown(source: string): string {\n if (source.length === 0) {\n return source;\n }\n let text = source;\n\n // Unclosed fenced code block: an odd count of ``` line-openers means the\n // trailing fence is still in flight. Always soft-close — including an empty\n // opener — so code chrome (padding/tint) appears once at ``` and lines only\n // grow the body. Stripping empty openers deferred chrome until the first\n // body line, which landed as one fat height spike (yank around fences).\n //\n // If the body already ends with `\\n`, append only ``` — a second `\\n``` would\n // invent a blank line that vanishes when the real closer lands (height shrink\n // → tip-follow compensate + mid soft-rise cancel = up/down flicker).\n if (countFences(text) % 2 === 1) {\n text += text.endsWith(\"\\n\") ? \"```\" : \"\\n```\";\n }\n\n // Work outside fenced blocks so we don't \"fix\" markers that are literal\n // code content.\n const segments = splitByFences(text);\n for (const segment of segments) {\n if (segment.kind === \"fence\") {\n continue;\n }\n segment.value = closeInlineMarkers(segment.value);\n }\n let result = segments.map((segment) => segment.value).join(\"\");\n // split(\"\\n\") drops a trailing newline into an empty final line; restore it\n // so balanced finished fences round-trip byte-identical.\n if (text.endsWith(\"\\n\") && !result.endsWith(\"\\n\")) {\n result += \"\\n\";\n }\n return result;\n}\n\nfunction countFences(text: string): number {\n let count = 0;\n for (const line of text.split(\"\\n\")) {\n if (/^ {0,3}```/.test(line)) {\n count += 1;\n }\n }\n return count;\n}\n\ntype Segment = { kind: \"prose\" | \"fence\"; value: string };\n\nfunction splitByFences(text: string): Segment[] {\n const segments: Segment[] = [];\n const lines = text.split(\"\\n\");\n let buf: string[] = [];\n let inFence = false;\n /**\n * `boundary`: prose → fence. `join` alone drops a blank line before ```\n * (`[\"a\",\"\"].join` → `\"a\\n\"`, need `\"a\\n\\n\"`), so append an extra `\\n`.\n * `end`: final segment. Trailing `\"\"` from `split(\"\\n\")` already encodes a\n * terminating newline — do NOT append another (that was inventing `\\n\\n`\n * on every streamed line and shrinking it away at crystallize).\n */\n const flush = (kind: Segment[\"kind\"], mode: \"boundary\" | \"end\") => {\n if (buf.length === 0) {\n return;\n }\n let value = buf.join(\"\\n\");\n if (mode === \"boundary\") {\n value += \"\\n\";\n }\n segments.push({ kind, value });\n buf = [];\n };\n for (const line of lines) {\n const isFence = /^ {0,3}```/.test(line);\n if (isFence) {\n if (inFence) {\n buf.push(line);\n flush(\"fence\", \"end\");\n inFence = false;\n } else {\n flush(\"prose\", \"boundary\");\n buf.push(line);\n inFence = true;\n }\n continue;\n }\n buf.push(line);\n }\n flush(inFence ? \"fence\" : \"prose\", \"end\");\n return segments;\n}\n\n/**\n * Close unmatched **, *, ~~, and ` in prose. Order matters: handle the\n * longer bold/strike markers before single `*` so we don't steal from `**`.\n */\nfunction closeInlineMarkers(prose: string): string {\n let text = prose;\n text = closeDelimiter(text, \"~~\");\n text = closeDelimiter(text, \"**\");\n text = closeDelimiter(text, \"__\");\n text = closeSingleBackticks(text);\n text = closeSingleAsterisks(text);\n text = closeUnfinishedLink(text);\n return text;\n}\n\nfunction closeDelimiter(text: string, delimiter: string): string {\n // Count occurrences that aren't escaped. Odd → append a closer.\n let count = 0;\n let i = 0;\n while (i < text.length) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i += 2;\n continue;\n }\n if (text.startsWith(delimiter, i)) {\n count += 1;\n i += delimiter.length;\n continue;\n }\n i += 1;\n }\n return count % 2 === 1 ? insertBeforeTrailingNewlines(text, delimiter) : text;\n}\n\n/** Soft closers belong before trailing `\\n`s so restore/round-trip stay stable. */\nfunction insertBeforeTrailingNewlines(text: string, suffix: string): string {\n let end = text.length;\n while (end > 0 && text[end - 1] === \"\\n\") {\n end -= 1;\n }\n return text.slice(0, end) + suffix + text.slice(end);\n}\n\nfunction closeSingleBackticks(text: string): string {\n // Ignore ``` (fences already stripped) and even pairs. A trailing unmatched\n // ` is the common \"inline code still typing\" case.\n let count = 0;\n for (let i = 0; i < text.length; i += 1) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i += 1;\n continue;\n }\n if (text[i] === \"`\") {\n // Skip triple backticks if any leaked into prose.\n if (text.startsWith(\"```\", i)) {\n i += 2;\n continue;\n }\n count += 1;\n }\n }\n return count % 2 === 1 ? insertBeforeTrailingNewlines(text, \"`\") : text;\n}\n\nfunction closeSingleAsterisks(text: string): string {\n // Count `*` that are NOT part of `**` (already handled). Odd → close italic.\n let count = 0;\n for (let i = 0; i < text.length; i += 1) {\n if (text[i] === \"\\\\\" && i + 1 < text.length) {\n i += 1;\n continue;\n }\n if (text[i] === \"*\" && text[i + 1] === \"*\") {\n i += 1;\n continue;\n }\n if (text[i] === \"*\") {\n count += 1;\n }\n }\n return count % 2 === 1 ? insertBeforeTrailingNewlines(text, \"*\") : text;\n}\n\nfunction closeUnfinishedLink(text: string): string {\n // `[label](url` without the trailing `)` — close it. Bare `[label` without\n // `](` is left alone (too ambiguous with footnotes / prose brackets).\n const open = text.lastIndexOf(\"](\");\n if (open === -1) {\n return text;\n }\n const after = text.slice(open + 2);\n if (after.includes(\")\")) {\n return text;\n }\n // Don't close if a later `[` started something else after.\n if (after.includes(\"[\")) {\n return text;\n }\n return insertBeforeTrailingNewlines(text, \")\");\n}\n","/* ----------------------------------------------------------------------------\n Streaming tip ink (age-window fade)\n\n Append-only markdown grows at the tip. Rather than staggering per-word\n onsets (glitter under fast models), each append batch is born at wall time\n and fades in over a fixed age window:\n\n opacity progress = clamp((now − birth) / INK_FADE_MS, 0, 1)\n\n Fast arrival → many recent characters still young → a large soft band.\n Slow arrival → only the tip is young → a tight tip wash.\n Same rule both ways; time does the work. No per-word stagger, no artificial\n content lag — layout always holds the truthful text; paint only.\n\n Identity is the character offset into the source. CSS animation-delay =\n birth − now (often negative) so mid-fade re-renders resume, never restart.\n Runs settle back to plain text once age ≥ INK_FADE_MS (zero span cost).\n -------------------------------------------------------------------------- */\n\nimport { MOTION_INSPECT_SCALE } from \"../lib/motion-inspect\";\n\n/** Keep in sync with `--og-duration-stream` / `.og-stream-ink` in styles. */\nexport const INK_FADE_MS = 420 * MOTION_INSPECT_SCALE;\n/** @deprecated Use {@link INK_FADE_MS}. */\nexport const WORD_ANIMATION_MS = INK_FADE_MS;\n\n/**\n * A first observation larger than this is pre-existing history (timeline\n * opened mid-stream), not live tip — it renders instantly.\n */\nconst INITIAL_ANIMATED_LIMIT = 400;\n\ntype InkBatch = {\n start: number;\n end: number;\n birth: number;\n};\n\nexport type StreamReveal = {\n /** Register the full current source text; new suffix becomes an ink batch. */\n observe(text: string, now: number): void;\n /**\n * CSS animation-delay (ms) for the run covering `offset`, or null when that\n * ink has settled and should render as plain text. Negative = resume mid-fade.\n */\n delayFor(offset: number, now: number): number | null;\n /** True while any batch is still inside its fade window. */\n hasActive(now: number): boolean;\n};\n\nexport function createStreamReveal(): StreamReveal {\n let batches: InkBatch[] = [];\n let revealedChars = -1;\n\n return {\n observe(text, now) {\n if (revealedChars === -1) {\n revealedChars = text.length > INITIAL_ANIMATED_LIMIT ? text.length : 0;\n }\n if (text.length <= revealedChars) {\n // Idempotent re-observation (StrictMode) or defensive no-op on shrink.\n revealedChars = Math.max(revealedChars, text.length);\n return;\n }\n batches.push({ start: revealedChars, end: text.length, birth: now });\n revealedChars = text.length;\n batches = batches.filter((batch) => batch.birth + INK_FADE_MS > now);\n },\n\n delayFor(offset, now) {\n const batch = findBatch(batches, offset);\n if (!batch) {\n return null;\n }\n const delay = batch.birth - now;\n return delay + INK_FADE_MS <= 0 ? null : delay;\n },\n\n hasActive(now) {\n const last = batches[batches.length - 1];\n return last !== undefined && last.birth + INK_FADE_MS > now;\n },\n };\n}\n\nfunction findBatch(batches: readonly InkBatch[], offset: number): InkBatch | null {\n let low = 0;\n let high = batches.length - 1;\n while (low <= high) {\n const mid = (low + high) >> 1;\n const batch = batches[mid]!;\n if (offset < batch.start) {\n high = mid - 1;\n } else if (offset >= batch.end) {\n low = mid + 1;\n } else {\n return batch;\n }\n }\n return null;\n}\n\n/* ----------------------------------------------------------------------------\n rehype: wrap still-fading source runs in `.og-stream-ink` spans.\n\n Contiguous offsets that share one birth (one append batch) become ONE span —\n a continuous ink surface, not per-word glitter. Code/pre stay plain. Nodes\n without source positions (syntax rewritten around them) render plain too.\n -------------------------------------------------------------------------- */\n\ntype HastText = {\n type: \"text\";\n value: string;\n position?: { start?: { offset?: number | undefined } | undefined } | undefined;\n};\n\ntype HastParent = {\n type: string;\n tagName?: string;\n value?: string;\n children?: HastChild[];\n};\n\ntype HastChild = (HastText | HastParent) & Record<string, unknown>;\n\nexport function rehypeStreamReveal(options: { reveal: StreamReveal; now: number }) {\n const { reveal, now } = options;\n return (tree: HastParent) => {\n walk(tree, false);\n };\n\n function walk(node: HastParent, insideVerbatim: boolean): void {\n if (!node.children) {\n return;\n }\n const verbatim = insideVerbatim || node.tagName === \"code\" || node.tagName === \"pre\";\n const next: HastChild[] = [];\n for (const child of node.children) {\n if (child.type === \"text\" && !verbatim) {\n next.push(...splitTextNode(child as HastText));\n continue;\n }\n walk(child as HastParent, verbatim);\n next.push(child);\n }\n node.children = next;\n }\n\n function splitTextNode(node: HastText): HastChild[] {\n const sourceOffset = node.position?.start?.offset;\n if (sourceOffset === undefined) {\n return [node as HastChild];\n }\n const value = node.value;\n const out: HastChild[] = [];\n let plain = \"\";\n const flushPlain = () => {\n if (plain.length > 0) {\n out.push({ type: \"text\", value: plain } as HastChild);\n plain = \"\";\n }\n };\n\n let i = 0;\n while (i < value.length) {\n const delay = reveal.delayFor(sourceOffset + i, now);\n let j = i + 1;\n while (j < value.length) {\n const nextDelay = reveal.delayFor(sourceOffset + j, now);\n if (nextDelay !== delay) {\n break;\n }\n j += 1;\n }\n const slice = value.slice(i, j);\n if (delay === null) {\n plain += slice;\n } else {\n flushPlain();\n out.push({\n type: \"element\",\n tagName: \"span\",\n properties: {\n className: [\"og-stream-ink\"],\n style: `animation-delay:${Math.round(delay)}ms`,\n },\n children: [{ type: \"text\", value: slice }],\n } as unknown as HastChild);\n }\n i = j;\n }\n flushPlain();\n return out.length > 0 ? out : [node as HastChild];\n }\n}\n","import {\n createContext,\n useCallback,\n useContext,\n useId,\n useLayoutEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { cn } from \"../lib/cn\";\n\nconst FALLBACK_LINE_THRESHOLD = 12;\nconst FALLBACK_TEXT_THRESHOLD = 900;\nconst FALLBACK_UNBROKEN_THRESHOLD = 260;\nconst INTERACTIVE_DESCENDANT_SELECTOR = [\n \"a[href]\",\n \"area[href]\",\n \"button\",\n \"input:not([type='hidden'])\",\n \"select\",\n \"textarea\",\n \"iframe\",\n \"object\",\n \"embed\",\n \"audio[controls]\",\n \"video[controls]\",\n \"summary\",\n \"[contenteditable]:not([contenteditable='false'])\",\n \"[tabindex]\",\n \"[role='button']\",\n \"[role='link']\",\n \"[role='checkbox']\",\n \"[role='radio']\",\n \"[role='switch']\",\n \"[role='slider']\",\n \"[role='spinbutton']\",\n \"[role='textbox']\",\n \"[role='combobox']\",\n \"[role='listbox']\",\n \"[role='menuitem']\",\n \"[role='option']\",\n \"[role='tab']\",\n \"[role='treeitem']\",\n].join(\",\");\n\nfunction composedParentElement(element: Element): Element | null {\n if (element.assignedSlot) {\n return element.assignedSlot;\n }\n if (element.parentElement) {\n return element.parentElement;\n }\n const root = element.getRootNode();\n return typeof ShadowRoot !== \"undefined\" && root instanceof ShadowRoot ? root.host : null;\n}\n\nfunction hasComposedInertAncestor(element: Element, boundary: Element): boolean {\n let current: Element | null = element;\n while (current) {\n if (current.hasAttribute(\"inert\")) {\n return true;\n }\n if (current === boundary) {\n return false;\n }\n current = composedParentElement(current);\n }\n return false;\n}\n\n/**\n * Native inert crosses shadow boundaries, but ordinary selectors do not.\n * Recursively inspect open roots control-by-control so visible shadow content\n * stays interactive. An opaque custom-element host is the conservative focus\n * boundary for a closed root that cannot be inspected.\n */\nfunction collectInteractionBoundaries(root: ParentNode): HTMLElement[] {\n const boundaries: HTMLElement[] = [];\n const scopes: ParentNode[] = [root];\n for (let scopeIndex = 0; scopeIndex < scopes.length; scopeIndex += 1) {\n for (const element of scopes[scopeIndex]!.querySelectorAll(\"*\")) {\n if (!(element instanceof HTMLElement)) {\n continue;\n }\n const shadowRoot = element.shadowRoot;\n const opaqueCustomElement = element.localName.includes(\"-\") && !shadowRoot;\n if (element.matches(INTERACTIVE_DESCENDANT_SELECTOR) || opaqueCustomElement) {\n boundaries.push(element);\n }\n if (shadowRoot) {\n scopes.push(shadowRoot);\n }\n }\n }\n return boundaries;\n}\n\nfunction isFullyInsideVisiblePreview(rect: DOMRect, clipRect: DOMRect): boolean {\n return (\n rect.width > 0 &&\n rect.height > 0 &&\n rect.top >= clipRect.top - 1 &&\n rect.bottom <= clipRect.bottom + 1 &&\n rect.left >= clipRect.left - 1 &&\n rect.right <= clipRect.right + 1\n );\n}\n\ntype RestoreDisclosureAnchor = (() => void) | null;\n\ntype SharedResizeObserverState = {\n callbacks: Map<Element, () => void>;\n observer: ResizeObserver;\n handleWindowResize: () => void;\n};\n\ntype DisclosureMeasurementJob = {\n read: () => boolean;\n write: (collapsible: boolean) => void;\n};\n\nconst sharedResizeObservers = new WeakMap<Window, SharedResizeObserverState>();\nconst disclosureMeasurementJobs = new Map<object, DisclosureMeasurementJob>();\nlet disclosureMeasurementQueued = false;\n\n/**\n * Coalesce a commit's disclosure reads before applying any presentation writes.\n * Reading and writing one message at a time forced a fresh layout for every\n * newly mounted row in large history prepends.\n */\nfunction scheduleDisclosureMeasurement(\n view: Window,\n key: object,\n job: DisclosureMeasurementJob,\n): () => void {\n disclosureMeasurementJobs.set(key, job);\n if (!disclosureMeasurementQueued) {\n disclosureMeasurementQueued = true;\n view.queueMicrotask(() => {\n disclosureMeasurementQueued = false;\n const pending = [...disclosureMeasurementJobs.values()];\n disclosureMeasurementJobs.clear();\n const decisions = pending.map(({ read }) => read());\n for (let index = 0; index < pending.length; index += 1) {\n pending[index]!.write(decisions[index]!);\n }\n });\n }\n return () => disclosureMeasurementJobs.delete(key);\n}\n\nfunction observeSharedResize(element: Element, callback: () => void): (() => void) | null {\n const view = element.ownerDocument.defaultView;\n if (!view || typeof ResizeObserver === \"undefined\") {\n return null;\n }\n let state = sharedResizeObservers.get(view);\n if (!state) {\n const callbacks = new Map<Element, () => void>();\n const handleWindowResize = () => {\n for (const registered of new Set(callbacks.values())) registered();\n };\n const observer = new ResizeObserver((entries) => {\n if (entries.length === 0) {\n handleWindowResize();\n } else {\n for (const entry of entries) {\n callbacks.get(entry.target)?.();\n }\n }\n });\n view.addEventListener(\"resize\", handleWindowResize);\n state = { callbacks, observer, handleWindowResize };\n sharedResizeObservers.set(view, state);\n }\n state.callbacks.set(element, callback);\n state.observer.observe(element);\n return () => {\n if (state.callbacks.get(element) !== callback) {\n return;\n }\n state.callbacks.delete(element);\n state.observer.unobserve(element);\n if (state.callbacks.size === 0) {\n state.observer.disconnect();\n view.removeEventListener(\"resize\", state.handleWindowResize);\n sharedResizeObservers.delete(view);\n }\n };\n}\n\nexport type UserMessageDisclosureContextValue = {\n expandedByMessageId: Map<string, boolean>;\n beginChange: (\n messageBody: HTMLElement,\n disclosureControl: HTMLElement,\n ) => RestoreDisclosureAnchor;\n};\n\nconst UserMessageDisclosureContext = createContext<UserMessageDisclosureContextValue | null>(null);\n\nexport function UserMessageDisclosureProvider({\n value,\n children,\n}: {\n value: UserMessageDisclosureContextValue;\n children: ReactNode;\n}) {\n return (\n <UserMessageDisclosureContext.Provider value={value}>\n {children}\n </UserMessageDisclosureContext.Provider>\n );\n}\n\n/**\n * Deterministic first-paint fallback for runtimes without layout measurement.\n * Real browsers replace this estimate with the rendered-height decision in the\n * first layout effect. The complete text always remains mounted either way.\n */\nexport function userMessageLikelyNeedsDisclosure(text: string): boolean {\n const lines = text.split(/\\r?\\n/);\n return (\n lines.length > FALLBACK_LINE_THRESHOLD ||\n text.length > FALLBACK_TEXT_THRESHOLD ||\n lines.some((line) => line.length > FALLBACK_UNBROKEN_THRESHOLD)\n );\n}\n\nexport type UserMessageBodyProps = {\n /** Durable timeline item id. Expansion memory is keyed by this value. */\n messageId: string;\n /** Complete source text. Used only for the deterministic measurement fallback. */\n text: string;\n children: ReactNode;\n className?: string | undefined;\n};\n\n/**\n * Lossless disclosure boundary for already-sent user-message text.\n *\n * The full rendered subtree always remains in the DOM. A real browser decides\n * whether disclosure is needed from rendered height (including Markdown\n * structure and wrapping); the source-text heuristic is only a deterministic\n * fallback for SSR/test environments without layout. Timeline-owned context\n * remembers expansion per durable message id and preserves the reader's scroll\n * anchor when height changes.\n */\nexport function UserMessageBody({ messageId, text, children, className }: UserMessageBodyProps) {\n const disclosure = useContext(UserMessageDisclosureContext);\n const [expanded, setExpanded] = useState(\n () => disclosure?.expandedByMessageId.get(messageId) ?? false,\n );\n const collapsibleRef = useRef(userMessageLikelyNeedsDisclosure(text));\n const expandedRef = useRef(expanded);\n expandedRef.current = expanded;\n const rootRef = useRef<HTMLDivElement | null>(null);\n const clipRef = useRef<HTMLDivElement | null>(null);\n const contentRef = useRef<HTMLDivElement | null>(null);\n const thresholdRef = useRef<HTMLSpanElement | null>(null);\n const fadeRef = useRef<HTMLSpanElement | null>(null);\n const disclosureControlRef = useRef<HTMLButtonElement | null>(null);\n const pendingRestoreRef = useRef<RestoreDisclosureAnchor>(null);\n const managedInertDescendantsRef = useRef(new Set<HTMLElement>());\n const measurementKeyRef = useRef({});\n const contentId = `og-user-message-${useId().replace(/:/g, \"\")}`;\n const collapsible = collapsibleRef.current;\n const collapsed = collapsible && !expanded;\n\n const syncDisclosurePresentation = useCallback((nextCollapsible: boolean) => {\n collapsibleRef.current = nextCollapsible;\n const nextCollapsed = nextCollapsible && !expandedRef.current;\n const clip = clipRef.current;\n clip?.classList.toggle(\"max-h-56\", nextCollapsed);\n clip?.classList.toggle(\"overflow-hidden\", nextCollapsed);\n clip?.classList.toggle(\"sm:max-h-72\", nextCollapsed);\n if (fadeRef.current) fadeRef.current.hidden = !nextCollapsed;\n if (disclosureControlRef.current) disclosureControlRef.current.hidden = !nextCollapsible;\n }, []);\n\n const restoreManagedInertDescendants = useCallback(() => {\n for (const descendant of managedInertDescendantsRef.current) {\n if (descendant.hasAttribute(\"data-og-user-message-managed-inert\")) {\n descendant.removeAttribute(\"inert\");\n descendant.removeAttribute(\"data-og-user-message-managed-inert\");\n }\n }\n managedInertDescendantsRef.current.clear();\n }, []);\n\n const syncCollapsedInteractivity = useCallback(() => {\n restoreManagedInertDescendants();\n if (!collapsibleRef.current || expandedRef.current) {\n return;\n }\n\n const clip = clipRef.current;\n const content = contentRef.current;\n if (!clip || !content) {\n return;\n }\n\n const clipRect = clip.getBoundingClientRect();\n if (clipRect.height <= 0) {\n return;\n }\n\n for (const descendant of collectInteractionBoundaries(content)) {\n if (hasComposedInertAncestor(descendant, content)) {\n continue;\n }\n const rect = descendant.getBoundingClientRect();\n if (isFullyInsideVisiblePreview(rect, clipRect)) {\n continue;\n }\n descendant.setAttribute(\"inert\", \"\");\n descendant.setAttribute(\"data-og-user-message-managed-inert\", \"\");\n managedInertDescendantsRef.current.add(descendant);\n }\n }, [restoreManagedInertDescendants]);\n\n const readCollapsible = useCallback(() => {\n const content = contentRef.current;\n const threshold = thresholdRef.current;\n if (!content || !threshold) {\n return userMessageLikelyNeedsDisclosure(text);\n }\n const renderedHeight = Math.max(content.scrollHeight, content.getBoundingClientRect().height);\n const collapseHeight = Math.max(\n threshold.offsetHeight,\n threshold.getBoundingClientRect().height,\n );\n return renderedHeight > 0 && collapseHeight > 0\n ? renderedHeight > collapseHeight + 1\n : userMessageLikelyNeedsDisclosure(text);\n }, [text]);\n\n const measure = useCallback(() => {\n const view = rootRef.current?.ownerDocument.defaultView;\n if (!view) {\n syncDisclosurePresentation(readCollapsible());\n syncCollapsedInteractivity();\n return () => undefined;\n }\n return scheduleDisclosureMeasurement(view, measurementKeyRef.current, {\n read: readCollapsible,\n write: (nextCollapsible) => {\n syncDisclosurePresentation(nextCollapsible);\n syncCollapsedInteractivity();\n },\n });\n }, [readCollapsible, syncCollapsedInteractivity, syncDisclosurePresentation]);\n\n useLayoutEffect(() => {\n const cancelPendingMeasurement = measure();\n const content = contentRef.current;\n const threshold = thresholdRef.current;\n const onResize = () => {\n measure();\n };\n const stopObservingContent = content ? observeSharedResize(content, onResize) : null;\n const stopObservingThreshold = threshold ? observeSharedResize(threshold, onResize) : null;\n const observerAvailable = stopObservingContent !== null || stopObservingThreshold !== null;\n const handleResize = () => {\n measure();\n };\n // ResizeObserver already reports viewport-driven wrapping/height changes\n // for both measured elements. The window listener is only the fallback for\n // runtimes without ResizeObserver; installing both created one redundant\n // global listener per durable user message in large timelines.\n if (!observerAvailable) {\n window.addEventListener(\"resize\", handleResize);\n }\n return () => {\n cancelPendingMeasurement();\n stopObservingContent?.();\n stopObservingThreshold?.();\n if (!observerAvailable) {\n window.removeEventListener(\"resize\", handleResize);\n }\n };\n }, [measure, syncCollapsedInteractivity]);\n\n useLayoutEffect(() => {\n syncDisclosurePresentation(collapsibleRef.current);\n syncCollapsedInteractivity();\n return restoreManagedInertDescendants;\n }, [\n expanded,\n restoreManagedInertDescendants,\n syncCollapsedInteractivity,\n syncDisclosurePresentation,\n ]);\n\n useLayoutEffect(() => {\n const restore = pendingRestoreRef.current;\n pendingRestoreRef.current = null;\n restore?.();\n }, [expanded]);\n\n const toggle = (control: HTMLButtonElement) => {\n const root = rootRef.current;\n pendingRestoreRef.current = root && disclosure ? disclosure.beginChange(root, control) : null;\n const next = !expanded;\n if (!next && contentRef.current?.contains(document.activeElement)) {\n control.focus({ preventScroll: true });\n }\n disclosure?.expandedByMessageId.set(messageId, next);\n setExpanded(next);\n };\n\n return (\n <div\n ref={rootRef}\n data-og-user-message-body=\"\"\n data-og-message-id={messageId}\n data-og-expanded={expanded ? \"true\" : \"false\"}\n className={cn(\"relative min-w-0\", className)}\n >\n <span\n ref={thresholdRef}\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute h-56 w-0 invisible sm:h-72\"\n />\n <div\n ref={clipRef}\n id={contentId}\n data-og-user-message-clip=\"\"\n className={cn(\"relative min-w-0\", collapsed && \"max-h-56 overflow-hidden sm:max-h-72\")}\n >\n <div\n ref={contentRef}\n data-og-user-message-content=\"\"\n className=\"min-w-0 [overflow-wrap:anywhere]\"\n >\n {children}\n </div>\n <span\n ref={fadeRef}\n aria-hidden=\"true\"\n hidden={!collapsed}\n data-og-user-message-fade=\"\"\n className=\"pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-t from-og-surface-2 via-og-surface-2/90 to-transparent\"\n />\n </div>\n <button\n ref={disclosureControlRef}\n type=\"button\"\n hidden={!collapsible}\n aria-controls={contentId}\n aria-expanded={expanded}\n data-og-user-message-disclosure=\"\"\n className=\"mt-1.5 inline-flex min-h-7 items-center rounded-og-sm px-1.5 text-og-xs font-medium text-og-fg-muted outline-hidden transition-colors hover:bg-og-surface-3/60 hover:text-og-fg focus-visible:ring-2 focus-visible:ring-og-accent/45 pointer-coarse:min-h-11\"\n onClick={(event) => toggle(event.currentTarget)}\n >\n {expanded ? \"Show less\" : \"Show more\"}\n </button>\n </div>\n );\n}\n","import type { RetainedArtifactReference, VideoArtifactPlaybackSource } from \"@opengeni/sdk\";\nimport type { ComponentType } from \"react\";\nimport { mcpToolLeaf } from \"./tool-display-name\";\nimport type { ToolCallItem } from \"./types\";\n\n/* ----------------------------------------------------------------------------\n Tool renderer registry\n\n The extension point. A `ToolRenderer` is a React component fed one projected\n `ToolCallItem`; the registry resolves which renderer handles a given call,\n keyed on the tool `name` and (secondarily) its provider-native `raw.type`.\n\n Resolution order (most → least specific):\n 1. exact match on `raw.type` (e.g. \"apply_patch_call\", \"computer_call\")\n 2. exact match on the tool `name` (e.g. \"exec_command\", \"web_search_call\")\n 3. leaf match after MCP `__` prefix (e.g. opengeni__environment_set_variable)\n 4. the registry's generic fallback\n\n A consumer extends the defaults without forking by passing overrides to\n `createToolRegistry` — e.g. a custom renderer for their own MCP tool, or a\n replacement for a built-in one. The registry is immutable and fully typed.\n -------------------------------------------------------------------------- */\n\nexport type ToolRendererProps = {\n item: ToolCallItem;\n loadRetainedScreenshot?: RetainedScreenshotLoader | undefined;\n loadRetainedArtifact?: RetainedArtifactLoader | undefined;\n};\n\nexport type RetainedScreenshotLoader = (\n artifact: RetainedArtifactReference,\n signal: AbortSignal,\n) => Promise<Uint8Array | null>;\n\nexport type RetainedArtifactLoader = (\n artifact: RetainedArtifactReference,\n signal: AbortSignal,\n) => Promise<Uint8Array | { url: string } | null>;\n\n/** Mint an expiring source for native browser playback without loading video bytes in JS. */\nexport type VideoArtifactPlaybackLoader = (\n artifactId: string,\n signal: AbortSignal,\n) => Promise<VideoArtifactPlaybackSource>;\n\nexport type ToolRenderer = ComponentType<ToolRendererProps>;\n\n/** A registry entry: which key it matches and the component that renders it. */\nexport type ToolRegistryEntry =\n | { match: \"rawType\"; type: string; render: ToolRenderer }\n | { match: \"name\"; name: string; render: ToolRenderer };\n\nexport type ToolRegistry = {\n /** Resolve the renderer for a call (never null — falls back to generic). */\n resolve: (item: ToolCallItem) => ToolRenderer;\n /** The generic fallback renderer. */\n fallback: ToolRenderer;\n};\n\nexport type CreateToolRegistryOptions = {\n /**\n * Entries that take precedence over the built-ins. Earlier entries win, so a\n * consumer can shadow a default renderer for the same key.\n */\n entries?: ToolRegistryEntry[] | undefined;\n /** Replace the generic fallback used for unmatched tools. */\n fallback?: ToolRenderer | undefined;\n};\n\n/** The `raw.type` of a projected tool call, when the provider item carries one. */\nexport function rawTypeOf(item: ToolCallItem): string | null {\n const raw = item.raw;\n if (raw && typeof raw === \"object\" && typeof (raw as { type?: unknown }).type === \"string\") {\n return (raw as { type: string }).type;\n }\n return null;\n}\n\n/**\n * Build a tool registry from a set of entries and a fallback. The returned\n * registry resolves in priority order: `raw.type` entries first, then `name`\n * entries, then the fallback. Consumer `entries` are consulted before the\n * built-in `baseEntries`, so they shadow defaults cleanly.\n */\nexport function createToolRegistry(\n baseEntries: ToolRegistryEntry[],\n baseFallback: ToolRenderer,\n options: CreateToolRegistryOptions = {},\n): ToolRegistry {\n const entries = [...(options.entries ?? []), ...baseEntries];\n const fallback = options.fallback ?? baseFallback;\n\n const byRawType = new Map<string, ToolRenderer>();\n const byName = new Map<string, ToolRenderer>();\n for (const entry of entries) {\n if (entry.match === \"rawType\") {\n if (!byRawType.has(entry.type)) {\n byRawType.set(entry.type, entry.render);\n }\n } else if (!byName.has(entry.name)) {\n byName.set(entry.name, entry.render);\n }\n }\n\n const resolve = (item: ToolCallItem): ToolRenderer => {\n const rawType = rawTypeOf(item);\n if (rawType) {\n const byType = byRawType.get(rawType);\n if (byType) {\n return byType;\n }\n }\n const exact = byName.get(item.name);\n if (exact) {\n return exact;\n }\n const leaf = mcpToolLeaf(item.name);\n if (leaf !== item.name) {\n const byLeaf = byName.get(leaf);\n if (byLeaf) {\n return byLeaf;\n }\n }\n return fallback;\n };\n\n return { resolve, fallback };\n}\n","import {\n normalizeMcpOutput,\n parseGeneratedImageReceipt,\n type GeneratedImageReceipt,\n type GitFileDiff,\n type RetainedArtifactMetadata,\n} from \"@opengeni/sdk\";\nimport { tryParseJson } from \"../lib/format\";\n\nexport type { GeneratedImageReceipt };\n\n/* ----------------------------------------------------------------------------\n Pure parsers for the provider-native tool shapes that the timeline renders.\n\n These are intentionally browser-safe, dependency-free mirrors of the\n server-side helpers in `@opengeni/runtime` (`sandboxCommandExitCode`,\n `parseExecBannerSessionId`, `stripExecBanner`) plus the V4A diff parser the\n apply-patch renderer needs. The SDK does not depend on `@opengeni/runtime` by\n design (runtime is a heavy server package); these few regexes are cheap to\n own here and keep the React surface free of a server dependency.\n\n Every function is pure -- same input, same output -- so it can be\n unit-tested and memoized.\n -------------------------------------------------------------------------- */\n\n/** Recover the exit code from a sandbox exec banner (`Process exited with code N`). */\nexport function sandboxCommandExitCode(out: unknown): number | null {\n const match = String(out ?? \"\").match(/Process exited with code (-?\\d+)/);\n return match ? Number(match[1]) : null;\n}\n\n/**\n * Recover the numeric exec-session id the sandbox embeds for a STILL-RUNNING\n * (backgrounded) process (`Process running with session ID N`). A finished\n * command emits `Process exited with code N` instead, which yields `null`.\n */\nexport function parseExecBannerSessionId(out: unknown): number | null {\n const text = String(out ?? \"\");\n const outputIdx = text.indexOf(\"\\nOutput:\\n\");\n const banner =\n outputIdx >= 0 ? text.slice(0, outputIdx) : text.startsWith(\"Output:\\n\") ? \"\" : text;\n const match = banner.match(/Process running with session ID (\\d+)/);\n if (!match) {\n return null;\n }\n const n = Number.parseInt(match[1]!, 10);\n return Number.isFinite(n) ? n : null;\n}\n\n/** Strip the exec banner (`Chunk ID ...\\n...\\nOutput:\\n`) down to the command's stdout. */\nexport function stripExecBanner(out: unknown): string {\n const text = String(out ?? \"\");\n const marker = text.indexOf(\"\\nOutput:\\n\");\n if (marker >= 0) {\n return text.slice(marker + \"\\nOutput:\\n\".length);\n }\n if (text.startsWith(\"Output:\\n\")) {\n return text.slice(\"Output:\\n\".length);\n }\n return text;\n}\n\n/** The sandbox clamped the output (token/line truncation markers in the banner). */\nexport function execTruncated(out: unknown): boolean {\n return /Total output lines:|\\.{3}\\d+ tokens truncated\\.{3}|\\[\\.{3}\\d+ characters truncated/.test(\n String(out ?? \"\"),\n );\n}\n\n/** A `write_stdin` whose target PTY vanished (`write_stdin failed: session not found: N`). */\nexport function isExecSessionLostBanner(out: unknown): boolean {\n return /write_stdin failed: session not found: \\d+/.test(String(out ?? \"\"));\n}\n\n/** True when the exec stdout looks binary/garbled (a NUL byte or ELF magic). */\nexport function looksBinary(text: string): boolean {\n return text.includes(\"\\u0000\") || text.startsWith(\"\\u007fELF\");\n}\n\n/**\n * Render unprintable control characters as caret notation (0x03 -> `^C`) so a\n * `write_stdin` keystroke payload reads cleanly in the row title.\n */\nexport function controlCaret(printable: string): string {\n return String(printable).replace(\n /[\\u0000-\\u001f]/g,\n (c) => `^${String.fromCharCode(c.charCodeAt(0) + 64)}`,\n );\n}\n\n/* --- V4A apply_patch diff -> GitFileDiff ------------------------------------ */\n\n/** One operation inside an `apply_patch_call` (a V4A file edit). */\nexport type ApplyPatchOperation = {\n /**\n * The V4A op kind. The three canonical values are `create_file`,\n * `update_file`, and `delete_file`; the open `string` tail tolerates a\n * forward-compatible/unknown op kind from the provider without a type error\n * (it falls through to the \"Edited\" treatment).\n */\n type: \"create_file\" | \"update_file\" | \"delete_file\" | (string & {});\n path: string;\n /** Rename target -- when present the op is a move/rename. */\n moveTo?: string | null | undefined;\n /** The V4A hunk string (`@@ ...` lines with `+`/`-`/context prefixes). */\n diff?: string | undefined;\n};\n\n/**\n * Parse a single V4A `apply_patch` operation into the SDK's `GitFileDiff` shape\n * so it can flow into the SAME `DiffView` / `PierreDiff` the Files tab uses.\n * Throws on a hunk string it cannot structure (no `@@` anchor on an update); the\n * renderer catches and falls back to a raw-patch view.\n */\nexport function v4aToGitFileDiff(op: ApplyPatchOperation): GitFileDiff {\n const status: GitFileDiff[\"status\"] =\n op.type === \"create_file\"\n ? \"added\"\n : op.type === \"delete_file\"\n ? \"deleted\"\n : op.moveTo\n ? \"renamed\"\n : \"modified\";\n const oldPath = op.moveTo ? op.path : null;\n const path = op.moveTo || op.path;\n\n const hunks: GitFileDiff[\"hunks\"] = [];\n let additions = 0;\n let deletions = 0;\n let sawHunkAnchor = false;\n\n if (op.type !== \"delete_file\") {\n const lines = (op.diff ?? \"\").split(\"\\n\");\n let cur: GitFileDiff[\"hunks\"][number] | null = null;\n let oldNo = 1;\n let newNo = 1;\n for (const raw of lines) {\n if (raw.startsWith(\"@@\")) {\n sawHunkAnchor = true;\n const match = raw.match(/-(\\d+)(?:,\\d+)?\\s+\\+(\\d+)/);\n oldNo = match ? Number(match[1]) : 1;\n newNo = match ? Number(match[2]) : 1;\n cur = {\n oldStart: oldNo,\n oldLines: 0,\n newStart: newNo,\n newLines: 0,\n header: raw,\n lines: [{ type: \"meta\", oldNo: null, newNo: null, text: raw }],\n };\n hunks.push(cur);\n } else if (cur || op.type === \"create_file\") {\n if (!cur) {\n // No `@@` anchor on a create_file body: synthesize an add-only hunk.\n // Leave `header` empty so `gitFileDiffToPatch` regenerates a valid\n // `@@ -0,0 +1,N @@` from the range fields once newLines is counted — a\n // pre-baked partial header (e.g. `@@ +1 @@`) renders zero lines in a\n // generic unified-diff parser.\n cur = {\n oldStart: 0,\n oldLines: 0,\n newStart: 1,\n newLines: 0,\n header: \"\",\n lines: [],\n };\n hunks.push(cur);\n oldNo = 0;\n newNo = 1;\n }\n if (raw.startsWith(\"+\")) {\n cur.lines.push({\n type: \"add\",\n oldNo: null,\n newNo: newNo++,\n text: raw.slice(1),\n });\n cur.newLines += 1;\n additions += 1;\n } else if (raw.startsWith(\"-\")) {\n cur.lines.push({\n type: \"del\",\n oldNo: oldNo++,\n newNo: null,\n text: raw.slice(1),\n });\n cur.oldLines += 1;\n deletions += 1;\n } else {\n cur.lines.push({\n type: \"context\",\n oldNo: oldNo++,\n newNo: newNo++,\n text: raw.replace(/^ /, \"\"),\n });\n cur.oldLines += 1;\n cur.newLines += 1;\n }\n }\n }\n // An update with content but no recognizable hunk anchor is malformed V4A;\n // the caller falls back to the raw-patch view instead of a structured diff.\n if (op.type === \"update_file\" && !sawHunkAnchor && lines.some((l) => l.trim().length > 0)) {\n throw new Error(\"malformed V4A: no @@ hunk anchor\");\n }\n }\n\n return {\n path,\n oldPath,\n status,\n isBinary: false,\n isImage: false,\n additions,\n deletions,\n hunks,\n truncated: false,\n };\n}\n\nconst BEGIN_PATCH = \"*** Begin Patch\";\nconst END_PATCH = \"*** End Patch\";\nconst ADD_FILE = \"*** Add File: \";\nconst DELETE_FILE = \"*** Delete File: \";\nconst UPDATE_FILE = \"*** Update File: \";\nconst MOVE_TO = \"*** Move to: \";\n\nconst APPLY_PATCH_OP_TYPES = new Set([\"create_file\", \"update_file\", \"delete_file\"]);\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\n/** Freeform / `{ patch }` / command payloads — tolerate leading whitespace. */\nfunction freeformApplyPatchOps(rawPatch: string): ApplyPatchOperation[] {\n return parseFreeformApplyPatch(rawPatch.trimStart());\n}\n\nfunction asApplyPatchOperation(value: unknown): ApplyPatchOperation | null {\n if (!isRecord(value)) return null;\n if (typeof value.type !== \"string\" || !APPLY_PATCH_OP_TYPES.has(value.type)) {\n return null;\n }\n if (typeof value.path !== \"string\" || !value.path) {\n return null;\n }\n const op: ApplyPatchOperation = {\n type: value.type as ApplyPatchOperation[\"type\"],\n path: value.path,\n };\n if (typeof value.diff === \"string\") op.diff = value.diff;\n if (typeof value.moveTo === \"string\" && value.moveTo.length > 0) op.moveTo = value.moveTo;\n return op;\n}\n\nfunction parseStructuredOperations(payloads: unknown[]): ApplyPatchOperation[] {\n if (payloads.length === 0) return [];\n const operations: ApplyPatchOperation[] = [];\n for (const payload of payloads) {\n const op = asApplyPatchOperation(payload);\n if (!op) return [];\n operations.push(op);\n }\n return operations;\n}\n\n/**\n * Mirror of `@openai/agents-core` freeform `*** Begin Patch` → ops. Kept here so\n * the timeline can render Codex function-tool apply_patch without importing the\n * server SDK package.\n */\nexport function parseFreeformApplyPatch(rawPatch: string): ApplyPatchOperation[] {\n const lines = rawPatch.split(/\\r?\\n/);\n if (lines.at(-1) === \"\") lines.pop();\n if (lines[0] !== BEGIN_PATCH) return [];\n if (lines.length < 2 || lines.at(-1) !== END_PATCH) return [];\n\n const operations: ApplyPatchOperation[] = [];\n let index = 1;\n while (index < lines.length - 1) {\n const line = lines[index]!;\n let parsed: { operation: ApplyPatchOperation; nextIndex: number } | { error: true } | null =\n null;\n if (line.startsWith(ADD_FILE)) parsed = parseAddFilePatch(lines, index);\n else if (line.startsWith(DELETE_FILE)) parsed = parseDeleteFilePatch(lines, index);\n else if (line.startsWith(UPDATE_FILE)) parsed = parseUpdateFilePatch(lines, index);\n else return [];\n if (!parsed || \"error\" in parsed) return [];\n operations.push(parsed.operation);\n index = parsed.nextIndex;\n }\n // Match the SDK: Begin/End with no file ops is not a valid patch.\n return operations.length > 0 ? operations : [];\n}\n\nfunction parsePatchHeader(line: string, prefix: string): string | null {\n const path = line.slice(prefix.length).trim();\n return path || null;\n}\n\nfunction isFileOperationHeader(line: string): boolean {\n return line.startsWith(ADD_FILE) || line.startsWith(DELETE_FILE) || line.startsWith(UPDATE_FILE);\n}\n\nfunction joinDiff(lines: string[]): string {\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction parseAddFilePatch(\n lines: string[],\n index: number,\n): { operation: ApplyPatchOperation; nextIndex: number } | { error: true } {\n const path = parsePatchHeader(lines[index]!, ADD_FILE);\n if (!path) return { error: true };\n index += 1;\n const diffLines: string[] = [];\n while (index < lines.length - 1 && !isFileOperationHeader(lines[index]!)) {\n const line = lines[index]!;\n if (!line.startsWith(\"+\")) return { error: true };\n diffLines.push(line);\n index += 1;\n }\n if (diffLines.length === 0) return { error: true };\n return {\n operation: { type: \"create_file\", path, diff: joinDiff(diffLines) },\n nextIndex: index,\n };\n}\n\nfunction parseDeleteFilePatch(\n lines: string[],\n index: number,\n): { operation: ApplyPatchOperation; nextIndex: number } | { error: true } {\n const path = parsePatchHeader(lines[index]!, DELETE_FILE);\n if (!path) return { error: true };\n index += 1;\n if (index < lines.length - 1 && !isFileOperationHeader(lines[index]!)) {\n return { error: true };\n }\n return { operation: { type: \"delete_file\", path }, nextIndex: index };\n}\n\nfunction parseUpdateFilePatch(\n lines: string[],\n index: number,\n): { operation: ApplyPatchOperation; nextIndex: number } | { error: true } {\n const path = parsePatchHeader(lines[index]!, UPDATE_FILE);\n if (!path) return { error: true };\n index += 1;\n let moveTo: string | undefined;\n if (index < lines.length - 1 && lines[index]!.startsWith(MOVE_TO)) {\n const parsedMoveTo = parsePatchHeader(lines[index]!, MOVE_TO);\n if (!parsedMoveTo) return { error: true };\n moveTo = parsedMoveTo;\n index += 1;\n }\n const diffLines: string[] = [];\n while (index < lines.length - 1 && !isFileOperationHeader(lines[index]!)) {\n diffLines.push(lines[index]!);\n index += 1;\n }\n if (diffLines.length === 0 && !moveTo) return { error: true };\n return {\n operation: {\n type: \"update_file\",\n path,\n diff: diffLines.length > 0 ? joinDiff(diffLines) : \"\",\n ...(moveTo ? { moveTo } : {}),\n },\n nextIndex: index,\n };\n}\n\n/**\n * Normalize every apply_patch payload the Agents SDK accepts into structured\n * ops — hosted `{ operation }` / `{ operations }`, function-tool `{ patch }`,\n * `command` tuple, flat op, freeform string, or op array.\n */\nexport function applyPatchOps(raw: unknown): ApplyPatchOperation[] {\n if (raw == null) return [];\n if (typeof raw === \"string\") {\n const trimmed = raw.trimStart();\n if (trimmed.startsWith(BEGIN_PATCH)) return freeformApplyPatchOps(trimmed);\n const parsed = tryParseJson(trimmed);\n return parsed === undefined ? [] : applyPatchOps(parsed);\n }\n if (Array.isArray(raw)) return parseStructuredOperations(raw);\n if (!isRecord(raw)) return [];\n\n if (typeof raw.patch === \"string\") return freeformApplyPatchOps(raw.patch);\n if (Array.isArray(raw.command)) {\n const [commandName, patch] = raw.command;\n if (commandName === \"apply_patch\" && typeof patch === \"string\") {\n return freeformApplyPatchOps(patch);\n }\n }\n // Empty `operations: []` is not authoritative — fall through to operation/flat.\n if (Array.isArray(raw.operations) && raw.operations.length > 0) {\n return parseStructuredOperations(raw.operations);\n }\n if (raw.operation !== undefined) {\n const op = asApplyPatchOperation(raw.operation);\n return op ? [op] : [];\n }\n // Flat single op: `{ type, path, diff?, moveTo? }`.\n const flat = asApplyPatchOperation(raw);\n return flat ? [flat] : [];\n}\n\n/** Ops from provider `raw` and/or function-tool arguments (Codex path). */\nexport function applyPatchOpsFromToolItem(item: {\n raw: unknown;\n arguments: unknown;\n}): ApplyPatchOperation[] {\n const fromRaw = applyPatchOps(item.raw);\n if (fromRaw.length > 0) return fromRaw;\n\n // function_call envelopes sometimes keep the payload only under raw.arguments.\n if (isRecord(item.raw)) {\n const nested = item.raw.arguments ?? item.raw.input;\n if (nested !== undefined && nested !== item.arguments) {\n const fromNested = applyPatchOps(nested);\n if (fromNested.length > 0) return fromNested;\n }\n }\n\n if (item.arguments !== undefined && item.arguments !== null) {\n return applyPatchOps(item.arguments);\n }\n return [];\n}\n\n/**\n * True when a tool item is apply_patch — hosted `raw.type === \"apply_patch_call\"`,\n * function-tool `name` `apply_patch` / `apply_patch_call`, or an MCP-prefixed\n * `…__apply_patch` leaf. Centralizes the rawType-or-name check.\n */\nexport function isApplyPatch(item: { name: string; raw: unknown }): boolean {\n const type =\n item.raw && typeof item.raw === \"object\" ? (item.raw as { type?: unknown }).type : undefined;\n if (type === \"apply_patch_call\") {\n return true;\n }\n const name = item.name;\n return name === \"apply_patch_call\" || name === \"apply_patch\" || name.endsWith(\"__apply_patch\");\n}\n\n/** Parse tool arguments that may arrive as a JSON string or an object. */\nexport function parseToolArgs(args: unknown): Record<string, unknown> {\n if (args == null) {\n return {};\n }\n if (typeof args === \"string\") {\n const parsed = tryParseJson(args);\n return parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : {};\n }\n return typeof args === \"object\" ? (args as Record<string, unknown>) : {};\n}\n\n/** The last non-empty line of a string -- the compact \"what happened\" peek. */\nexport function tailPeek(text: string): string {\n const trimmed = text.trim();\n if (!trimmed) {\n return \"\";\n }\n const lines = trimmed.split(\"\\n\");\n return lines[lines.length - 1] ?? \"\";\n}\n\n/**\n * Unwrap an MCP tool result (`{ content: [{ type: \"text\", text }], isError? }`)\n * into a flat `{ text, isError }`. Non-MCP outputs pass through as their string\n * form.\n */\nexport function unwrapMcpOutput(output: unknown): {\n text: string;\n isError: boolean;\n} {\n const normalized = normalizeMcpOutput(output);\n return { text: normalized.text, isError: normalized.isError };\n}\n\n/* --- computer-use screenshot extraction ------------------------------------- */\n\n/**\n * Extract a renderable `data:` URL from a computer-use screenshot output,\n * whatever transport produced it. The hosted `computer_call` and the\n * function-text mode persist a plain `data:image/...` string; the\n * function-image mode (codex-backed sessions) persists the STRUCTURED image\n * output — `{type:\"image\", image:{data, mediaType}}` with `data` arriving as a\n * number array / index map / Buffer-JSON / base64 string after event\n * serialization — or the agents-core normalized `input_image` content item.\n * Returns null when the output carries no image (so callers fall back to their\n * text/empty presentation).\n */\nexport function screenshotDataUrl(out: unknown): string | null {\n if (typeof out === \"string\") {\n if (out.startsWith(\"data:image\")) {\n return out;\n }\n // A JSON-encoded structured output (some transports stringify tool results).\n if (out.startsWith(\"{\") || out.startsWith(\"[\")) {\n const parsed = tryParseJson(out);\n if (parsed !== undefined && parsed !== out) {\n return screenshotDataUrl(parsed);\n }\n }\n return null;\n }\n if (Array.isArray(out)) {\n for (const entry of out) {\n const url = screenshotDataUrl(entry);\n if (url) {\n return url;\n }\n }\n return null;\n }\n if (out === null || typeof out !== \"object\") {\n return null;\n }\n const record = out as Record<string, unknown>;\n // agents-core normalized content item: {type:\"input_image\", image_url: \"data:…\" | {url}}\n const imageUrl = record.image_url ?? record.imageUrl;\n if (typeof imageUrl === \"string\" && imageUrl.startsWith(\"data:image\")) {\n return imageUrl;\n }\n if (imageUrl && typeof imageUrl === \"object\") {\n const url = (imageUrl as Record<string, unknown>).url;\n if (typeof url === \"string\" && url.startsWith(\"data:image\")) {\n return url;\n }\n }\n // Structured tool output: {type:\"image\", image:{data, mediaType}}\n const image = record.image as Record<string, unknown> | undefined;\n if (image && typeof image === \"object\") {\n const mediaType = typeof image.mediaType === \"string\" ? image.mediaType : \"image/png\";\n const base64 = bytesToBase64(image.data);\n if (base64) {\n return `data:${mediaType};base64,${base64}`;\n }\n if (typeof image.data === \"string\" && image.data.length > 0) {\n // Already base64 text.\n return `data:${mediaType};base64,${image.data}`;\n }\n }\n return null;\n}\n\n/** Parse the closed retained-screenshot receipt carried by new tool events. */\nexport function retainedScreenshotMetadata(out: unknown): RetainedArtifactMetadata | null {\n if (typeof out === \"string\" && (out.startsWith(\"{\") || out.startsWith(\"[\"))) {\n const parsed = tryParseJson(out);\n if (parsed !== undefined && parsed !== out) return retainedScreenshotMetadata(parsed);\n }\n if (Array.isArray(out)) {\n for (const entry of out) {\n const metadata = retainedScreenshotMetadata(entry);\n if (metadata) return metadata;\n }\n return null;\n }\n if (!out || typeof out !== \"object\") return null;\n const value = out as Record<string, unknown>;\n if (typeof value.artifactId !== \"string\" || typeof value.available !== \"boolean\") return null;\n if (!value.available) {\n return typeof value.reason === \"string\" ? (value as unknown as RetainedArtifactMetadata) : null;\n }\n return value.kind === \"computer_screenshot\" &&\n value.contentType === \"image/png\" &&\n typeof value.originalBytes === \"number\" &&\n typeof value.sha256 === \"string\" &&\n value.dimensions !== null &&\n typeof value.dimensions === \"object\" &&\n value.retention !== null &&\n typeof value.retention === \"object\" &&\n (value.retention as Record<string, unknown>).policy === \"session_screenshot\"\n ? (value as unknown as RetainedArtifactMetadata)\n : null;\n}\n\n/** Parse the closed permanent generated-image receipt from native/function tools. */\nexport function generatedImageReceipt(out: unknown): GeneratedImageReceipt | null {\n return parseGeneratedImageReceipt(out);\n}\n\nexport type TimelineMediaPreview = {\n type: \"media_preview\";\n mediaType: string;\n inlineBytes: number | null;\n fullOutputAvailable: false;\n preview: string;\n};\n\n/** Find the explicit non-retained inline-media fact in a tool output. */\nexport function mediaPreviewFact(out: unknown): TimelineMediaPreview | null {\n if (typeof out === \"string\" && (out.startsWith(\"{\") || out.startsWith(\"[\"))) {\n const parsed = tryParseJson(out);\n if (parsed !== undefined && parsed !== out) return mediaPreviewFact(parsed);\n }\n if (Array.isArray(out)) {\n for (const entry of out) {\n const preview = mediaPreviewFact(entry);\n if (preview) return preview;\n }\n return null;\n }\n if (!out || typeof out !== \"object\") return null;\n const record = out as Record<string, unknown>;\n if (\n record.type !== \"media_preview\" ||\n typeof record.mediaType !== \"string\" ||\n record.fullOutputAvailable !== false ||\n typeof record.preview !== \"string\" ||\n (record.inlineBytes !== null && typeof record.inlineBytes !== \"number\")\n ) {\n return null;\n }\n return record as TimelineMediaPreview;\n}\n\n/** Serialize whatever a Uint8Array became in JSON (number[], {\"0\":n,…} index\n * map, or Buffer-JSON {type:\"Buffer\",data:[…]}) back into base64. */\nfunction bytesToBase64(data: unknown): string | null {\n const isByte = (n: unknown): n is number =>\n typeof n === \"number\" && Number.isInteger(n) && n >= 0 && n <= 255;\n let bytes: number[] | null = null;\n if (Array.isArray(data) && data.every(isByte)) {\n bytes = data;\n } else if (data && typeof data === \"object\") {\n const record = data as Record<string, unknown>;\n if (record.type === \"Buffer\" && Array.isArray(record.data) && record.data.every(isByte)) {\n bytes = record.data;\n } else {\n const keys = Object.keys(record);\n if (keys.length > 0 && keys.every((key) => /^\\d+$/.test(key))) {\n const values = keys.sort((a, b) => Number(a) - Number(b)).map((key) => record[key]);\n if (values.every(isByte)) {\n bytes = values;\n }\n }\n }\n }\n if (!bytes || bytes.length === 0) {\n return null;\n }\n try {\n let binary = \"\";\n const CHUNK = 0x8000;\n for (let i = 0; i < bytes.length; i += CHUNK) {\n binary += String.fromCharCode(...bytes.slice(i, i + CHUNK));\n }\n return typeof btoa === \"function\"\n ? btoa(binary)\n : Buffer.from(binary, \"binary\").toString(\"base64\");\n } catch {\n // A hostile/absurd payload must degrade to \"no image\", never crash a render.\n return null;\n }\n}\n","import { createContext, useContext, type ReactNode } from \"react\";\n\n/* ----------------------------------------------------------------------------\n Disclosure defaults context\n\n A tiny, opt-in context that lets an ancestor seed the INITIAL open state of\n every collapsible in the timeline (ActivityDisclosure rows and TurnSummary\n chips). Its sole intended use is deterministic screenshot capture: a tool can\n force every card open so a headless render shows expanded bodies.\n\n It is fully inert in normal app usage. With no provider, the hook returns\n `undefined`, every collapsible keeps its own author-chosen default, and there\n is zero change to how the components look or animate. Mounting the provider\n only changes the SEED of the initial `open` state — Radix still owns the\n open/close transition, so animations are untouched.\n -------------------------------------------------------------------------- */\n\nconst DisclosureDefaultsContext = createContext<boolean | undefined>(undefined);\n\n/**\n * Seed the initial open state of every timeline collapsible below this node.\n * Intended for screenshot/test instrumentation only; absent by default.\n */\nexport function DisclosureDefaultsProvider({\n defaultOpen,\n children,\n}: {\n defaultOpen: boolean;\n children: ReactNode;\n}) {\n return (\n <DisclosureDefaultsContext.Provider value={defaultOpen}>\n {children}\n </DisclosureDefaultsContext.Provider>\n );\n}\n\n/**\n * The forced initial-open seed from an ancestor {@link DisclosureDefaultsProvider},\n * or `undefined` when none is mounted (the inert, app-default case).\n */\nexport function useForcedDefaultOpen(): boolean | undefined {\n return useContext(DisclosureDefaultsContext);\n}\n","import { CameraIcon, CameraOffIcon, ChevronRightIcon } from \"lucide-react\";\nimport { createContext, useContext, useState, type ReactNode } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { stringifyPayload } from \"../lib/format\";\nimport { useForcedDefaultOpen } from \"./disclosure-context\";\nimport { useLightboxOptional } from \"./screenshot-lightbox\";\nimport type { ToolCallTruncation } from \"./types\";\n\n/* ----------------------------------------------------------------------------\n Shared timeline primitives\n\n The restraint layer. One disclosure shape every tool renderer reuses, so the\n rail reads as a calm, aligned column: a chevron, a tinted icon, a title, an\n optional muted preview, and — at most — ONE quiet right-aligned signal\n (a settle chip). Compact by default; the body only mounts when expanded.\n\n CHIP DOCTRINE (closed set — do not extend):\n The right gutter carries at most ONE terse status token per row, and COLOR is\n spent only on the exception. Success is the default, so it never earns a hue:\n a settled-ok chip is bare muted text (or nothing). The colored dot is reserved\n for failure alone. In-flight state is NOT a gutter chip — the shimmering title\n carries it, so a running row has a clean right edge (no detached pulse badge).\n There is no bordered/filled pill. Anything narrative (a session id, \"approval\n rejected\", \"malformed V4A\") belongs in the muted preview line, never the gutter.\n\n ok a settled success quiet muted text (\"0\", \"done\") — no dot\n bad a settled failure red dot + red text (\"exit 6\") — the one hue\n muted quiet metadata subtle text (\"session 3\")\n -------------------------------------------------------------------------- */\n\n/**\n * A subtle settle signal — see the CHIP DOCTRINE above. The closed tone set.\n * `\"interrupted\"` is a calm neutral tone for cancelled items — no dot, same\n * quiet weight as `\"muted\"`, but semantically distinct from metadata.\n */\nexport type DisclosureChip = {\n tone: \"ok\" | \"bad\" | \"muted\" | \"interrupted\";\n text: string;\n};\n\nconst ToolCallTruncationContext = createContext<ToolCallTruncation | null>(null);\n\nexport function ToolCallTruncationProvider({\n value,\n children,\n}: {\n value: ToolCallTruncation | null;\n children: ReactNode;\n}) {\n return (\n <ToolCallTruncationContext.Provider value={value}>\n {children}\n </ToolCallTruncationContext.Provider>\n );\n}\n\nexport type ActivityDisclosureProps = {\n icon: ReactNode;\n /** Icon tint. Defaults to the muted foreground; renderers pass accent/failed. */\n iconTone?: \"accent\" | \"failed\" | \"running\" | \"muted\" | undefined;\n title: ReactNode;\n /** Render the title in the mono face (commands, paths). */\n titleMono?: boolean | undefined;\n /** Shimmer the title while the tool is in-flight. */\n running?: boolean | undefined;\n /**\n * Quiet single-line secondary text (truncated). It is detail-on-demand: hidden\n * when a media preview is set, AND hidden once the row is expanded (the body\n * then owns the detail), so a stat/path never appears twice at once.\n */\n preview?: ReactNode | undefined;\n /** A small inline media preview (a screenshot thumbnail) shown in place of `preview`. */\n media?: ReactNode | undefined;\n /** At most one quiet settle chip, right-aligned to the gutter. */\n chip?: DisclosureChip | undefined;\n /**\n * When true the row carries the standard failure affordance: the icon is tinted\n * red and a \"failed\" bad-chip appears in the right gutter (unless an explicit\n * `chip` is already supplied — the caller's chip wins). Output is still visible\n * on expand; this is a quiet status signal, not a blocking banner.\n *\n * Renderers should pass `failed={item.status === \"failed\"}` on their settled\n * (non-running) paths so any tool with a failed status shows a consistent\n * affordance without each renderer having to duplicate the logic.\n */\n failed?: boolean | undefined;\n /**\n * When true the row carries a calm \"interrupted\" affordance: the icon stays\n * muted (no red) and a quiet \"interrupted\" chip appears in the right gutter\n * (unless an explicit `chip` is already supplied — the caller's chip wins).\n * This is the cancelled-status analogue of `failed`, but deliberately calm\n * and neutral — it is NOT an error; the user chose to stop.\n *\n * Renderers should pass `cancelled={item.status === \"cancelled\"}` so any\n * in-flight item that was interrupted on turn.cancelled reads consistently.\n * `cancelled` is ignored when `failed` is also true (failure takes precedence).\n */\n cancelled?: boolean | undefined;\n /** When false the row is a static line (no expand affordance). */\n expandable?: boolean | undefined;\n /** Seed this individual disclosure open; user interaction still owns it afterwards. */\n defaultOpen?: boolean | undefined;\n children?: ReactNode | undefined;\n};\n\nconst ICON_TONE: Record<NonNullable<ActivityDisclosureProps[\"iconTone\"]>, string> = {\n accent: \"text-og-accent\",\n failed: \"text-og-status-failed\",\n running: \"text-og-status-running\",\n muted: \"text-og-fg-subtle\",\n};\n\n/**\n * The one disclosure row shape every activity row reuses (tool calls, reasoning,\n * sandbox ops): a chevron, a tinted icon, a title, an optional muted preview or\n * inline media, and at most one right-gutter settle chip. Compact by default;\n * the body mounts only when expanded.\n */\nexport function ActivityDisclosure({\n icon,\n iconTone: iconToneProp = \"muted\",\n title,\n titleMono,\n running,\n preview,\n media,\n chip: chipProp,\n failed,\n cancelled,\n expandable = true,\n defaultOpen,\n children,\n}: ActivityDisclosureProps) {\n // `failed` takes precedence over `cancelled` when both are set (shouldn't happen, but be safe).\n // When `failed` is set the icon goes red and a \"failed\" chip appears in the\n // gutter — unless the caller already supplied an explicit chip (their chip wins,\n // e.g. an exit-code chip that is more informative than a bare \"failed\" label).\n // When `cancelled` is set (and not failed) the icon stays muted and a calm\n // \"interrupted\" chip appears — no red, just a quiet neutral signal.\n const iconTone = failed && iconToneProp === \"muted\" ? \"failed\" : iconToneProp;\n const chip =\n chipProp ??\n (failed\n ? ({ tone: \"bad\", text: \"failed\" } satisfies DisclosureChip)\n : cancelled\n ? ({ tone: \"interrupted\", text: \"interrupted\" } satisfies DisclosureChip)\n : undefined);\n // An ancestor may seed the initial open state (screenshot instrumentation);\n // absent in normal app usage, where the row starts collapsed.\n const forcedDefaultOpen = useForcedDefaultOpen();\n const [open, setOpen] = useState(defaultOpen ?? forcedDefaultOpen ?? false);\n const truncation = useContext(ToolCallTruncationContext);\n const hasBody = expandable && (children != null || truncation != null);\n\n // The preview is detail-on-demand: it is suppressed once the row is open so a\n // path/stat shown in the body never also sits in the collapsed row.\n const previewVisible = preview != null && !open;\n\n // ONE full-row layout for EVERY tool — media or not — so the hit target always\n // equals the visible row. The chevron → icon → title lead; a flex spacer (or\n // the preview) fills the middle; the right gutter (ml-auto) carries the chip OR\n // the media thumbnail. There is no media-vs-non-media fork: the screenshot card\n // toggles from anywhere on the row, exactly like every other row.\n //\n // The row is the single Collapsible.Trigger (via `asChild` onto a div), so it\n // is the toggle surface. A div — not a native <button> — so the interactive\n // media thumbnail (itself a <button>) is valid nested DOM; that thumbnail calls\n // stopPropagation so activating it never toggles the row.\n //\n // Radix forwards aria-expanded / aria-controls / data-state and a click handler\n // onto the asChild child, but it does NOT synthesize the button role, tab stop,\n // or Enter/Space activation for a non-button element. We add those ourselves\n // (role/tabIndex/onKeyDown) so the row is a fully keyboard-operable button to\n // AT and the keyboard, matching its native-<button> siblings (TurnSummary).\n const rowClass = cn(\n \"group/disclosure flex w-full min-w-0 items-center gap-2 rounded-og-sm px-1.5 py-1.5 text-left text-og-base\",\n \"text-og-fg-muted transition-colors duration-150\",\n // A tool row is a touch target on coarse pointers: grow its hit area to the\n // 44px mobile minimum without loosening the dense desktop rail.\n \"pointer-coarse:min-h-11 pointer-coarse:py-2.5\",\n );\n // The chevron rotates to point down when open; it tracks `data-state` on this\n // same row (the Trigger), so the affordance never freezes.\n const inner = (\n <>\n {hasBody ? (\n <ChevronRightIcon className=\"size-3.5 shrink-0 text-og-fg-subtle transition-transform duration-[var(--_og-duration-disclose)] ease-og-in-out group-data-[state=open]/disclosure:rotate-90\" />\n ) : (\n <span className=\"size-3.5 shrink-0\" />\n )}\n <span className={cn(\"shrink-0\", ICON_TONE[iconTone])}>{icon}</span>\n <span\n className={cn(\n \"min-w-0 shrink truncate text-og-base font-medium\",\n titleMono && \"font-og-mono text-og-sm font-normal\",\n running && \"og-shimmer-text\",\n )}\n >\n {title}\n </span>\n {previewVisible && !media ? (\n <span className=\"min-w-0 flex-1 truncate text-og-sm text-og-fg-subtle\">{preview}</span>\n ) : (\n <span className=\"flex-1\" />\n )}\n {/* The right gutter carries at most ONE signal: the media thumbnail, else a\n terse settle chip (hidden once expanded — the body owns the detail). */}\n {media && !open ? (\n <span className=\"ml-auto flex shrink-0 items-center gap-2 pl-2\">{media}</span>\n ) : chip && !open ? (\n <span className=\"ml-auto shrink-0 pl-2\">\n <Chip chip={chip} />\n </span>\n ) : null}\n </>\n );\n\n // A `data-status` attribute on the root lets tests (and AT) detect the item's\n // settled state regardless of whether the chip slot is occupied by media.\n const dataStatus = cancelled ? \"cancelled\" : failed ? \"failed\" : undefined;\n\n if (!hasBody) {\n return (\n <div className={cn(rowClass, \"cursor-default\")} data-status={dataStatus}>\n {inner}\n </div>\n );\n }\n\n // Native disclosure (not radix-ui Collapsible): importing `radix-ui` from the\n // timeline registry pulls Popper into the session share-graph and crashes\n // lazy workspace settings (`createPopperScope is not a function`).\n return (\n <div>\n <div\n role=\"button\"\n tabIndex={0}\n aria-expanded={open}\n data-state={open ? \"open\" : \"closed\"}\n onClick={() => setOpen((prev) => !prev)}\n onKeyDown={(event) => {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.preventDefault();\n setOpen((prev) => !prev);\n }\n }}\n data-status={dataStatus}\n className={cn(\n rowClass,\n \"cursor-pointer outline-hidden hover:bg-og-surface-1 hover:text-og-fg\",\n \"focus-visible:ring-2 focus-visible:ring-og-accent focus-visible:ring-offset-0\",\n )}\n >\n {inner}\n </div>\n {open ? (\n <div className=\"mb-2 ml-7 mt-1.5 flex flex-col gap-2 overflow-hidden animate-og-expand\">\n {children}\n {truncation ? <ToolCallTruncationNotice truncation={truncation} /> : null}\n </div>\n ) : null}\n </div>\n );\n}\n\nfunction ToolCallTruncationNotice({ truncation }: { truncation: ToolCallTruncation }) {\n const fullEvidence = truncation.fullEvidence.available\n ? \"retained\"\n : (truncation.fullEvidence.reason ?? \"unavailable\");\n return (\n <div data-og-tool-output-truncation=\"\" className=\"text-og-sm leading-5 text-og-fg-subtle\">\n Output bounded at <code className=\"font-og-mono\">{truncation.surface}</code>\n {truncation.omittedBytes != null && truncation.omittedBytes > 0\n ? ` · ${truncation.omittedBytes.toLocaleString()} bytes omitted`\n : null}\n {\" · reason \"}\n <code className=\"font-og-mono\">{truncation.reason}</code>\n {\" · full evidence \"}\n <code className=\"font-og-mono\">{fullEvidence}</code>\n </div>\n );\n}\n\n/**\n * The right-gutter settle chip. Color is spent only on the exception: a failure\n * is a red dot + red text (the one colored token in a healthy run); success and\n * metadata are bare muted text with no dot. No box, no fill (see the CHIP\n * DOCTRINE above). A `bad` chip with empty text is a lone dot (no trailing void).\n */\nfunction Chip({ chip }: { chip: DisclosureChip }) {\n const base = \"inline-flex items-center font-og-mono text-og-xs leading-none\";\n const withText = chip.text ? \"gap-1.5\" : \"gap-0\";\n if (chip.tone === \"bad\") {\n return (\n <span className={cn(base, withText, \"text-og-status-failed\")}>\n <span className=\"size-1.5 rounded-full bg-og-status-failed\" />\n {chip.text}\n </span>\n );\n }\n // \"interrupted\" is a calm cancelled signal: same quiet weight as muted, no\n // dot, no red — just a slightly more prominent subtle text so \"interrupted\"\n // reads at a glance without demanding attention the way a failure does.\n if (chip.tone === \"interrupted\") {\n return <span className={cn(base, \"text-og-fg-subtle og-cancelled-chip\")}>{chip.text}</span>;\n }\n // ok and muted are the same quiet weight — success never earns a hue.\n return <span className={cn(base, \"text-og-fg-subtle\")}>{chip.text}</span>;\n}\n\n/* --- terminal output block (exec / write_stdin) ---------------------------- */\n\nexport function TermBlock({\n command,\n workdir,\n output,\n live,\n tailLines = 12,\n failed,\n}: {\n /**\n * The command shown in the prompt header. Pass `null` when the row title\n * already carries it (e.g. an exec row titled `$ cmd`): the header then drops\n * the command — and the whole prompt line if there is no workdir either — so\n * the command never reads twice, stacked, above the output.\n */\n command: string | null;\n workdir?: string | null | undefined;\n /** The FULL output. TermBlock owns the tail/full slicing internally. */\n output: string;\n live?: boolean | undefined;\n /** A non-zero exit / failed call — tints the left accent red (the one hue). */\n failed?: boolean | undefined;\n /**\n * When the output exceeds the tail window, only the last `tailLines` are shown\n * with a \"show full output\" toggle. The component holds the full text, so the\n * toggle reveals the rest (never a dead affordance). Defaults to 12.\n */\n tailLines?: number | undefined;\n}) {\n const [full, setFull] = useState(false);\n const empty = output.trim() === \"\";\n const lines = output.split(\"\\n\");\n const big = lines.length > tailLines + 4;\n const shown = full || !big ? output : lines.slice(-tailLines).join(\"\\n\");\n const showMore = big && !full;\n const showHeader = command != null || workdir != null;\n\n // No frame, no fill: a quiet monospace run flush on the page, marked only by a\n // 2px left accent so it reads as terminal output at a glance without becoming\n // yet another nested box. Color is spent only on the exception — a settled run\n // gets a calm neutral rule, a live one the running hue, a failed one the red.\n return (\n <div\n className={cn(\n \"min-w-0 border-l-2 pl-3\",\n failed\n ? \"border-og-status-failed/50\"\n : live\n ? \"border-og-status-running/50\"\n : \"border-og-border\",\n )}\n >\n {showHeader ? (\n <div className=\"flex items-center gap-2 pb-1\">\n <span className=\"select-none text-og-status-idle\">$</span>\n {command != null ? (\n <span className=\"min-w-0 flex-1 truncate font-og-mono text-og-sm text-og-fg-muted\">\n {command}\n </span>\n ) : (\n <span className=\"flex-1\" />\n )}\n {workdir ? (\n <span className=\"shrink-0 font-og-mono text-og-xs text-og-fg-subtle\">{workdir}</span>\n ) : null}\n </div>\n ) : null}\n {empty ? (\n <p className=\"font-og-mono text-og-xs italic text-og-fg-subtle\">(no output)</p>\n ) : (\n <pre className=\"max-h-72 overflow-auto whitespace-pre-wrap break-all font-og-mono text-og-xs leading-5 text-og-fg-muted\">\n {shown}\n {live ? (\n <span className=\"ml-px inline-block h-[1em] w-[2px] translate-y-[2px] animate-og-blink bg-og-accent align-middle\" />\n ) : null}\n </pre>\n )}\n {showMore ? (\n <button\n type=\"button\"\n onClick={() => setFull(true)}\n className=\"mt-1 text-left text-og-xs text-og-fg-subtle transition-colors hover:text-og-fg\"\n >\n show full output ({lines.length} lines)\n </button>\n ) : null}\n </div>\n );\n}\n\n/* --- generic payload block -------------------------------------------------- */\n\nexport function PayloadBlock({\n label,\n value,\n failed,\n}: {\n label: string;\n value: unknown;\n failed?: boolean | undefined;\n}) {\n const text = typeof value === \"string\" ? value : stringifyPayload(value);\n if (!text || text.trim() === \"\") {\n return null;\n }\n // Flush on the page, no frame — a labelled monospace run marked only by a 2px\n // left accent (red when the call failed, otherwise a calm neutral rule), so a\n // payload reads as detail hanging off the row, never a nested card.\n return (\n <div\n className={cn(\n \"min-w-0 border-l-2 pl-3\",\n failed ? \"border-og-status-failed/50\" : \"border-og-border\",\n )}\n >\n <p className=\"mb-1 text-og-xs font-medium uppercase tracking-[0.08em] text-og-fg-subtle\">\n {label}\n </p>\n <pre\n className={cn(\n \"max-h-64 overflow-auto whitespace-pre-wrap break-all font-og-mono text-og-xs leading-5\",\n failed ? \"text-og-status-failed\" : \"text-og-fg-muted\",\n )}\n >\n {text}\n </pre>\n </div>\n );\n}\n\n/** A quiet inline note inside an expanded body (lost output, empty frame, …). */\nexport function BodyNote({\n children,\n tone,\n}: {\n children: ReactNode;\n tone?: \"error\" | \"muted\" | undefined;\n}) {\n if (tone === \"error\") {\n // A quiet error run marked by a 2px red accent — the same flush, frameless\n // language as the payload/output blocks, not a filled callout box.\n return (\n <div className=\"border-l-2 border-og-status-failed/50 pl-3 font-og-mono text-og-xs leading-5 text-og-status-failed\">\n {children}\n </div>\n );\n }\n return <p className=\"px-0.5 text-og-sm italic leading-5 text-og-fg-subtle\">{children}</p>;\n}\n\n/* --- screenshot thumbnail + media states ------------------------------------ */\n\n/**\n * The shared inline-media footprint, so thumb / skeleton / empty align. Sized to\n * the row's line height (~28px) so a media row never out-weighs a text row and\n * the single-column rhythm holds.\n */\nconst MEDIA_BOX = \"h-7 w-[52px] shrink-0 rounded-og-xs border border-og-border\";\n\n/**\n * A loading screenshot placeholder. A faint camera glyph over a shimmering box,\n * so a still frame of the running state reads unambiguously as \"capturing\" — not\n * a broken thumbnail.\n */\nexport function MediaSkeleton() {\n return (\n <span\n className={cn(\n MEDIA_BOX,\n \"relative inline-flex items-center justify-center overflow-hidden bg-og-surface-2\",\n )}\n >\n <span className=\"absolute inset-0 animate-og-pulse bg-og-surface-3/50\" />\n <CameraIcon className=\"relative size-3.5 text-og-fg-subtle\" />\n </span>\n );\n}\n\n/** A standardized \"tool ran, produced no image\" placeholder in the media slot. */\nexport function MediaEmpty() {\n return (\n <span className={cn(MEDIA_BOX, \"inline-flex items-center justify-center bg-og-bg\")}>\n <CameraOffIcon className=\"size-3.5 text-og-fg-subtle\" />\n </span>\n );\n}\n\n/**\n * A small inline screenshot thumbnail that opens the app lightbox on click.\n *\n * Requires a `LightboxProvider` ancestor for the click-to-expand affordance.\n * Outside one it degrades to a plain, non-interactive image — never a dead\n * \"Expand\" button that announces an action it cannot perform.\n */\nexport function Thumbnail({\n src,\n caption,\n alt = \"screenshot\",\n expandLabel = \"Expand screenshot\",\n lightboxLabel = \"Screenshot\",\n downloadFilename,\n}: {\n src: string;\n caption?: string | undefined;\n alt?: string;\n expandLabel?: string | undefined;\n lightboxLabel?: string | undefined;\n downloadFilename?: string | undefined;\n}) {\n const lightbox = useLightboxOptional();\n const [failed, setFailed] = useState(false);\n if (failed) {\n return <MediaEmpty />;\n }\n // A plain <img> (not a framework Image): this is a framework-agnostic SDK, so\n // the host's image component is unavailable and unwanted here.\n const img = (\n <img\n src={src}\n alt={alt}\n onError={() => setFailed(true)}\n className=\"h-full w-full object-cover transition-opacity group-hover/thumb:opacity-80\"\n />\n );\n if (!lightbox) {\n return <span className={cn(MEDIA_BOX, \"inline-flex overflow-hidden bg-og-bg\")}>{img}</span>;\n }\n // The thumbnail is a real, independently-focusable button nested inside the\n // row's disclosure trigger. It stops both pointer AND keyboard activation from\n // bubbling, so opening the lightbox never also toggles the row.\n return (\n <button\n type=\"button\"\n onClick={(event) => {\n event.stopPropagation();\n lightbox.open(src, caption, event.currentTarget, lightboxLabel, downloadFilename);\n }}\n onKeyDown={(event) => {\n if (event.key === \"Enter\" || event.key === \" \") {\n event.stopPropagation();\n }\n }}\n className={cn(\n MEDIA_BOX,\n \"group/thumb relative inline-flex overflow-hidden bg-og-bg outline-hidden\",\n \"focus-visible:ring-2 focus-visible:ring-og-accent\",\n )}\n aria-label={expandLabel}\n >\n {img}\n </button>\n );\n}\n\n/**\n * The expanded screenshot inside a tool body: a contained, clickable preview\n * (opens the lightbox) with a quiet caption. Constrained height + object-contain\n * so it never breaks the row layout. Like {@link Thumbnail}, it degrades to a\n * plain image outside a `LightboxProvider`.\n */\nexport function ScreenshotFigure({\n src,\n caption,\n alt = \"screenshot\",\n expandLabel = \"Expand screenshot\",\n lightboxLabel = \"Screenshot\",\n downloadFilename,\n}: {\n src: string;\n caption?: string | undefined;\n alt?: string;\n expandLabel?: string | undefined;\n lightboxLabel?: string | undefined;\n downloadFilename?: string | undefined;\n}) {\n const lightbox = useLightboxOptional();\n const [failed, setFailed] = useState(false);\n const surface = \"block w-full overflow-hidden rounded-og-md border border-og-border bg-og-bg\";\n // A plain <img>, like {@link Thumbnail} — a framework-agnostic SDK has no host\n // Image component to defer to.\n const img = (\n <img\n src={src}\n alt={alt}\n onError={() => setFailed(true)}\n className=\"max-h-80 w-full object-contain\"\n />\n );\n return (\n <figure className=\"m-0 min-w-0\">\n {failed ? (\n <div className=\"rounded-og-md border border-og-border bg-og-bg px-3 py-6 text-center font-og-mono text-og-xs text-og-fg-subtle\">\n image unavailable\n </div>\n ) : lightbox ? (\n <button\n type=\"button\"\n onClick={(event) =>\n lightbox.open(src, caption, event.currentTarget, lightboxLabel, downloadFilename)\n }\n className={surface}\n aria-label={expandLabel}\n >\n {img}\n </button>\n ) : (\n <div className={surface}>{img}</div>\n )}\n {caption ? (\n <figcaption className=\"mt-1.5 font-og-mono text-og-xs text-og-fg-subtle\">\n {caption}\n </figcaption>\n ) : null}\n </figure>\n );\n}\n","import type { GitFileDiff } from \"@opengeni/sdk\";\n\n/**\n * Reconstruct a unified-diff patch string for a single `GitFileDiff` so it can\n * be fed to a generic patch renderer (e.g. Pierre's `PatchDiff`). The hook\n * already carries per-line old/new numbers and a hunk header, so we emit a\n * conventional `--- / +++ / @@` patch the parser understands.\n */\nexport function gitFileDiffToPatch(file: GitFileDiff): string {\n const oldPath = file.oldPath ?? file.path;\n const newPath = file.path;\n const lines: string[] = [];\n lines.push(`diff --git a/${oldPath} b/${newPath}`);\n if (file.status === \"deleted\") {\n lines.push(`--- a/${oldPath}`);\n lines.push(`+++ /dev/null`);\n } else if (file.status === \"added\" || file.status === \"untracked\") {\n lines.push(`--- /dev/null`);\n lines.push(`+++ b/${newPath}`);\n } else {\n lines.push(`--- a/${oldPath}`);\n lines.push(`+++ b/${newPath}`);\n }\n for (const hunk of file.hunks) {\n // Only trust a pre-parsed header if it carries the full unified range form\n // `@@ -<o>[,<n>] +<o>[,<n>] @@`. A synthesized create_file hunk (parsers.ts)\n // can carry a degenerate `@@ +1 @@` with no `-`/`+` ranges; a generic patch\n // parser (Pierre) renders zero lines from it, so the expanded diff comes up\n // empty while the collapsed chip still shows the (correct) addition count.\n // In that case regenerate a valid header from the hunk's range fields.\n const headerIsValid = /^@@ -\\d+(?:,\\d+)? \\+\\d+(?:,\\d+)? @@/.test(hunk.header ?? \"\");\n const header = headerIsValid\n ? hunk.header\n : `@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`;\n lines.push(header);\n for (const line of hunk.lines) {\n if (line.type === \"meta\") continue;\n const prefix = line.type === \"add\" ? \"+\" : line.type === \"del\" ? \"-\" : \" \";\n lines.push(`${prefix}${line.text}`);\n }\n }\n return lines.join(\"\\n\") + \"\\n\";\n}\n","import type { GitFileDiff } from \"@opengeni/sdk\";\nimport {\n type ComponentType,\n type CSSProperties,\n type ReactNode,\n lazy,\n Suspense,\n useEffect,\n useState,\n} from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { gitFileDiffToPatch } from \"../lib/git-patch\";\n\n/** Pierre `PatchDiff` props subset we drive. */\ntype PatchDiffComponent = ComponentType<{\n patch: string;\n options?: {\n theme?: string | { dark: string; light: string };\n themeType?: \"dark\" | \"light\";\n diffStyle?: \"unified\" | \"split\";\n overflow?: \"scroll\" | \"wrap\";\n stickyHeader?: boolean;\n };\n disableWorkerPool?: boolean;\n className?: string;\n}>;\n\nexport type PierreDiffProps = {\n diff: GitFileDiff[];\n layout?: \"unified\" | \"split\" | undefined;\n themeType?: \"dark\" | \"light\" | undefined;\n /** Shiki bundled theme names (dark/light) — derived from the host palette. */\n theme?: { dark: string; light: string } | undefined;\n /** Disable Pierre's worker pool if its worker bundling fights the host bundler. */\n disableWorkerPool?: boolean | undefined;\n /** Rendered while the (lazy) Pierre bundle loads. */\n loading?: ReactNode | undefined;\n /** Rendered if `@pierre/diffs/react` is not installed / fails to import. */\n fallback?: ReactNode | undefined;\n /** Skip the Shiki renderer entirely and show the plain-text degrade (the old\n * `usePierre={false}` path — one renderer, opted out of highlighting). */\n plain?: boolean | undefined;\n /** Long-line handling: `\"wrap\"` soft-wraps (the default — a diff in a narrow\n * dock pane should be readable without a horizontal-scroll tax), `\"scroll\"`\n * keeps lines on one row behind a horizontal scrollbar (better for a wide\n * viewport or pathological minified lines). */\n overflow?: \"wrap\" | \"scroll\" | undefined;\n className?: string | undefined;\n};\n\n// Lazy-load `@pierre/diffs/react` so Shiki + the worker pool stay off the\n// critical path (and out of an SSR bundle) until a diff is actually shown. The\n// dynamic specifier is static so the bundler can resolve + chunk it. If the\n// optional peer is absent the import rejects and we render `fallback`.\nconst LazyPatchDiff = lazy(async () => {\n const mod = (await import(\"@pierre/diffs/react\")) as unknown as {\n PatchDiff: PatchDiffComponent;\n };\n return { default: mod.PatchDiff };\n});\n\n/**\n * The Pierre-backed diff: Shiki-highlighted, virtualized, unified/split. Renders\n * one `PatchDiff` per changed file (a reconstructed unified patch from the\n * `GitFileDiff` hunks). The ONE workbench diff renderer; a host without\n * `@pierre/diffs` gets the built-in plain-text degrade (`PlainPatch`).\n */\nexport function PierreDiff({\n diff,\n layout = \"unified\",\n themeType,\n theme,\n disableWorkerPool,\n loading,\n fallback,\n plain,\n overflow = \"wrap\",\n className,\n}: PierreDiffProps) {\n const [failed, setFailed] = useState(false);\n const [forcedColors, setForcedColors] = useState(false);\n\n // Pierre's rich renderer distinguishes additions/deletions primarily through\n // foreground and background colors inside a shadow root. In Windows forced-\n // colors mode those paints intentionally collapse, so expose the literal\n // unified patch (+/- markers) instead of leaving changed lines ambiguous.\n useEffect(() => {\n if (typeof window === \"undefined\" || typeof window.matchMedia !== \"function\") return;\n const query = window.matchMedia(\"(forced-colors: active)\");\n const update = () => setForcedColors(query.matches);\n update();\n query.addEventListener?.(\"change\", update);\n return () => query.removeEventListener?.(\"change\", update);\n }, []);\n\n // Probe the import once so a hard failure (peer missing) shows `fallback`\n // rather than a Suspense boundary that never resolves. Skipped when `plain`.\n useEffect(() => {\n if (plain) return;\n let cancelled = false;\n void import(\"@pierre/diffs/react\").catch(() => {\n if (!cancelled) setFailed(true);\n });\n return () => {\n cancelled = true;\n };\n }, [plain]);\n\n if (plain || failed || forcedColors) {\n // `plain` opts out of highlighting; `failed` = `@pierre/diffs` not installed.\n // Render the caller's fallback, or a plain (unhighlighted) patch dump — NOT a\n // second hunk renderer. One highlighted renderer (Pierre) + a text degrade.\n return (\n <div\n className={className}\n data-opengeni-plain-diff={forcedColors ? \"forced-colors\" : \"fallback\"}\n >\n {fallback ?? <PlainPatch diff={diff} />}\n </div>\n );\n }\n\n // Default to the dark theme: the host UI is dark-first, and Pierre's own\n // auto-detection otherwise lands on the light Shiki theme (a white diff pane\n // inside a dark dock). Callers pass `themeType=\"light\"` to opt into light.\n const options = {\n diffStyle: layout,\n overflow,\n stickyHeader: true,\n ...(theme\n ? { theme }\n : {\n theme: {\n dark: \"github-dark-high-contrast\",\n light: \"github-light-high-contrast\",\n },\n }),\n themeType: themeType ?? \"dark\",\n };\n\n // Pierre renders inside a shadow DOM, so host CSS can't reach it — but it reads\n // a set of `--diffs-*-override` custom properties through the shadow boundary.\n // Pin the diff's own base background to the dock surface and quiet the hunk\n // separator slab so collapsed context rows do not become heavy bars.\n const pierreVars = {\n \"--diffs-dark-bg\": \"var(--og-color-bg)\",\n \"--diffs-light-bg\": \"var(--og-color-bg)\",\n \"--diffs-bg-buffer-override\": \"var(--og-color-surface-1)\",\n \"--diffs-bg-separator-override\": \"var(--og-color-surface-1)\",\n \"--diffs-addition-color-override\": \"var(--og-color-status-idle)\",\n \"--diffs-deletion-color-override\": \"var(--og-color-status-failed)\",\n \"--diffs-fg-number-addition-override\": \"var(--og-color-status-idle)\",\n \"--diffs-fg-number-deletion-override\": \"var(--og-color-status-failed)\",\n \"--diffs-bg-addition-override\":\n \"color-mix(in oklab, var(--og-color-status-idle) 12%, var(--og-color-bg))\",\n \"--diffs-bg-deletion-override\":\n \"color-mix(in oklab, var(--og-color-status-failed) 12%, var(--og-color-bg))\",\n \"--diffs-bg-addition-emphasis-override\":\n \"color-mix(in oklab, var(--og-color-status-idle) 22%, var(--og-color-bg))\",\n \"--diffs-bg-deletion-emphasis-override\":\n \"color-mix(in oklab, var(--og-color-status-failed) 22%, var(--og-color-bg))\",\n \"--diffs-header-font-family\": \"var(--og-font-sans)\",\n \"--diffs-font-family\": \"var(--og-font-mono)\",\n \"--diffs-font-size\": \"var(--og-code-font-size)\",\n \"--diffs-line-height\": \"var(--og-code-line-height)\",\n } as CSSProperties;\n\n return (\n <div className={cn(\"min-w-0\", className)} data-opengeni-pierre-diff style={pierreVars}>\n <Suspense fallback={loading ?? <DiffSkeleton />}>\n {diff.map((file) => (\n <div key={file.path} className=\"mb-2\">\n <LazyPatchDiff\n patch={gitFileDiffToPatch(file)}\n options={options}\n {...(disableWorkerPool !== undefined ? { disableWorkerPool } : {})}\n />\n </div>\n ))}\n </Suspense>\n </div>\n );\n}\n\nfunction DiffSkeleton() {\n return <div className=\"p-3 text-og-sm text-og-fg-subtle\">Loading diff…</div>;\n}\n\n/**\n * The unhighlighted degrade for a host without `@pierre/diffs`: the reconstructed\n * unified patch as monospace text with +/−/@@ tinting. Deliberately NOT a\n * structured hunk renderer — the workbench keeps exactly one of those (Pierre).\n */\nfunction PlainPatch({ diff }: { diff: GitFileDiff[] }) {\n if (diff.length === 0) {\n return <div className=\"p-3 text-og-sm text-og-fg-subtle\">No changes</div>;\n }\n return (\n <div className=\"min-w-0\">\n {diff.map((file) => (\n <pre\n key={file.path}\n aria-label={`Diff for ${file.path}`}\n className=\"mb-2 overflow-auto whitespace-pre rounded-og-sm border border-og-border bg-og-bg/60 p-2.5 font-og-mono text-og-xs leading-5\"\n role=\"region\"\n tabIndex={0}\n >\n {gitFileDiffToPatch(file)\n .split(\"\\n\")\n .map((line, index) => (\n <span\n // Patch line position is the stable identity in this immutable plain-text fallback.\n // oxlint-disable-next-line react/no-array-index-key\n key={index}\n className={cn(\n \"block\",\n line.startsWith(\"@@\")\n ? \"text-og-accent\"\n : line.startsWith(\"+\")\n ? \"text-og-status-idle\"\n : line.startsWith(\"-\")\n ? \"text-og-status-failed\"\n : \"text-og-fg-muted\",\n )}\n >\n {line || \" \"}\n </span>\n ))}\n </pre>\n ))}\n </div>\n );\n}\n","import {\n parseSandboxFileArtifactReceipt,\n type GitFileDiff,\n type RetainedArtifactReference,\n} from \"@opengeni/sdk\";\nimport {\n BoxIcon,\n BrainCircuitIcon,\n CalendarClockIcon,\n CameraIcon,\n CameraOffIcon,\n DownloadIcon,\n FileDiffIcon,\n FileSearchIcon,\n FolderGitIcon,\n GlobeIcon,\n ImageIcon,\n KeyboardIcon,\n KeyRoundIcon,\n LockIcon,\n MessageCircleQuestionIcon,\n MessagesSquareIcon,\n MessageSquareIcon,\n MousePointer2Icon,\n PackageSearchIcon,\n PanelsTopLeftIcon,\n PlugIcon,\n SearchIcon,\n ServerCogIcon,\n ServerIcon,\n Share2Icon,\n TargetIcon,\n TerminalIcon,\n VideoIcon,\n WrenchIcon,\n} from \"lucide-react\";\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { formatBytes, stringifyPayload, tryParseJson } from \"../lib/format\";\nimport { useTimelineComputeLabel } from \"./compute-label\";\nimport {\n applyPatchOpsFromToolItem,\n controlCaret,\n execTruncated,\n generatedImageReceipt,\n isExecSessionLostBanner,\n looksBinary,\n mediaPreviewFact,\n parseExecBannerSessionId,\n parseToolArgs,\n retainedScreenshotMetadata,\n sandboxCommandExitCode,\n stripExecBanner,\n tailPeek,\n unwrapMcpOutput,\n v4aToGitFileDiff,\n screenshotDataUrl,\n type ApplyPatchOperation,\n} from \"./parsers\";\nimport {\n createToolRegistry,\n type ToolRegistry,\n type ToolRegistryEntry,\n type ToolRendererProps,\n} from \"./registry\";\nimport {\n BodyNote,\n MediaEmpty,\n MediaSkeleton,\n PayloadBlock,\n ScreenshotFigure,\n TermBlock,\n Thumbnail,\n ActivityDisclosure,\n type DisclosureChip,\n} from \"./shared\";\nimport { RawPatch, ToolDiff } from \"./tool-diff\";\nimport { mcpToolLeaf, toolDisplayName } from \"./tool-display-name\";\n\n/* ----------------------------------------------------------------------------\n Per-tool renderers\n\n Each renderer takes one projected `ToolCallItem` and returns an `ActivityDisclosure`\n tuned for that tool's real wire shape. The defaults below populate the\n registry; the mapping is registered at the bottom of the file.\n\n Restraint is the rule: compact title + one quiet preview, secondary detail\n only on expand. No loud right-side badges — at most a single settle chip.\n -------------------------------------------------------------------------- */\n\nconst ICON_SIZE = \"size-3.5\";\n\n/**\n * The single in-flight locus for a running row: a pulse dot immediately left of\n * the status word, riding the preview line — NOT a detached gutter badge. The\n * title already shimmers; this keeps the live signal in one place the eye reads\n * left-to-right.\n */\nfunction RunningPreview({ children }: { children: ReactNode }) {\n return (\n <span className=\"inline-flex items-center gap-1.5\">\n <span className=\"size-1.5 shrink-0 animate-og-pulse rounded-full bg-og-status-running\" />\n <span className=\"min-w-0 truncate\">{children}</span>\n </span>\n );\n}\n\n/** Prefix a collapsed preview with the host-supplied active compute label. */\nfunction withComputePreview(label: string | null, preview: string): string {\n if (!label) {\n return preview;\n }\n return `on ${label} · ${preview}`;\n}\n\n/* ---- exec_command ---------------------------------------------------------- */\n\nfunction ExecRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const cmd = typeof args.cmd === \"string\" ? args.cmd : \"\";\n const workdir = typeof args.workdir === \"string\" ? args.workdir : null;\n const running = item.status === \"running\";\n const out = item.output;\n const title = `$ ${cmd}`;\n const computeLabel = useTimelineComputeLabel();\n\n // No output event ever arrived (item.output stays undefined from creation):\n // the turn failed before the output insert — most likely a NUL byte in the\n // command output prevented storage. Surface the specific explanation.\n // (Cancelled items bypass this: a cancellation is not a NUL-storage failure.)\n if (item.status === \"failed\" && out === undefined) {\n return (\n <ActivityDisclosure\n icon={<TerminalIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={title}\n titleMono\n chip={{ tone: \"bad\", text: \"failed\" }}\n preview={withComputePreview(computeLabel, \"output lost — NUL byte could not be stored\")}\n >\n <BodyNote tone=\"error\">\n output contained a NUL byte and could not be stored; the turn failed on this tool&apos;s\n output insert — no output event ever arrived.\n </BodyNote>\n </ActivityDisclosure>\n );\n }\n\n // An output event arrived but the tool still failed (error:true / MCP isError)\n // and the output is empty — show a generic failure rather than claiming NUL.\n // (Cancelled items bypass this: a cancellation is not a tool-call failure.)\n if (item.status === \"failed\" && (out == null || out === \"\")) {\n return (\n <ActivityDisclosure\n icon={<TerminalIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={title}\n titleMono\n chip={{ tone: \"bad\", text: \"failed\" }}\n preview={withComputePreview(computeLabel, \"tool call failed\")}\n >\n <BodyNote tone=\"error\">the tool call failed with no output.</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n if (running) {\n const streamed = typeof out === \"string\" ? stripExecBanner(out) : \"\";\n const runningPreview = streamed ? `${streamed.split(\"\\n\").length} lines` : \"running…\";\n return (\n <ActivityDisclosure\n icon={<TerminalIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={title}\n titleMono\n running\n preview={\n <RunningPreview>{withComputePreview(computeLabel, runningPreview)}</RunningPreview>\n }\n >\n {/* The row title is already `$ ${cmd}`; the TermBlock header drops the\n command (command={null}) so it never repeats above the output. */}\n <TermBlock command={null} workdir={workdir} output={streamed} live />\n </ActivityDisclosure>\n );\n }\n\n const text = typeof out === \"string\" ? out : stringifyPayload(out);\n const stripped = stripExecBanner(text);\n const bgSession = parseExecBannerSessionId(text);\n const exitCode = sandboxCommandExitCode(text);\n const binary = looksBinary(stripped);\n\n // Color is spent on the exception only: a clean exit (0) earns NO chip — the\n // absence of a red token is the success signal. Background sessions surface a\n // muted id; a non-zero exit is the one red token.\n let chip: DisclosureChip | undefined;\n let iconTone: \"accent\" | \"failed\" | \"muted\" = \"muted\";\n if (bgSession != null) {\n chip = { tone: \"muted\", text: `session ${bgSession}` };\n } else if (exitCode != null && exitCode !== 0) {\n chip = { tone: \"bad\", text: `exit ${exitCode}` };\n iconTone = \"failed\";\n }\n\n const peek = binary ? \"binary output\" : tailPeek(stripped) || \"(no output)\";\n const truncated = execTruncated(text);\n const preview = withComputePreview(computeLabel, truncated ? `⋯ truncated · ${peek}` : peek);\n // Hand TermBlock the FULL stripped output; it owns the tail/show-more slicing.\n const body = binary ? \"(binary output suppressed)\" : stripped;\n\n return (\n <ActivityDisclosure\n icon={<TerminalIcon className={ICON_SIZE} />}\n iconTone={iconTone}\n title={title}\n titleMono\n {...(chip ? { chip } : {})}\n failed={item.status === \"failed\"}\n cancelled={item.status === \"cancelled\"}\n preview={preview}\n >\n <TermBlock\n command={null}\n workdir={workdir}\n output={body}\n failed={item.status === \"failed\" || (exitCode != null && exitCode !== 0)}\n />\n {bgSession != null ? (\n <BodyNote>↳ session {bgSession} — a later write_stdin can target this PTY.</BodyNote>\n ) : null}\n </ActivityDisclosure>\n );\n}\n\n/* ---- write_stdin ----------------------------------------------------------- */\n\nfunction WriteStdinRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const sessionId =\n typeof args.session_id === \"string\" || typeof args.session_id === \"number\"\n ? args.session_id\n : undefined;\n const running = item.status === \"running\";\n const text = typeof item.output === \"string\" ? item.output : stringifyPayload(item.output);\n const lost = isExecSessionLostBanner(text);\n const keys = controlCaret(typeof args.chars === \"string\" ? args.chars : \"\");\n const exitCode = sandboxCommandExitCode(text);\n const stripped = stripExecBanner(text);\n\n if (running) {\n return (\n <ActivityDisclosure\n icon={<KeyboardIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={`session ${sessionId} ← ${keys || \"∅\"}`}\n titleMono\n running\n preview={<RunningPreview>sending…</RunningPreview>}\n >\n <BodyNote>sending input to session {sessionId}…</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n // Success (exit 0 or a quiet ack) earns no chip; only a lost PTY / non-zero\n // exit gets the one red token.\n let chip: DisclosureChip | undefined;\n if (lost) {\n chip = { tone: \"bad\", text: \"lost\" };\n } else if (exitCode != null && exitCode !== 0) {\n chip = { tone: \"bad\", text: `exit ${exitCode}` };\n }\n\n return (\n <ActivityDisclosure\n icon={<KeyboardIcon className={ICON_SIZE} />}\n iconTone={lost ? \"failed\" : \"muted\"}\n title={`session ${sessionId} ← ${keys || \"∅\"}`}\n titleMono\n {...(chip ? { chip } : {})}\n failed={item.status === \"failed\"}\n cancelled={item.status === \"cancelled\"}\n preview={lost ? `session ${sessionId} PTY vanished` : tailPeek(stripped) || \"sent\"}\n >\n {lost ? (\n <BodyNote tone=\"error\">{stripped || text}</BodyNote>\n ) : (\n <TermBlock command={`write_stdin → session ${sessionId}`} output={stripped} />\n )}\n </ActivityDisclosure>\n );\n}\n\n/* ---- apply_patch ----------------------------------------------------------- */\n\nfunction verbForOp(op: ApplyPatchOperation | undefined): string {\n if (!op) {\n return \"Edited\";\n }\n return op.type === \"create_file\"\n ? \"Created\"\n : op.type === \"delete_file\"\n ? \"Deleted\"\n : op.moveTo\n ? \"Renamed\"\n : \"Edited\";\n}\n\nfunction basename(path: string): string {\n const parts = path.split(\"/\").filter(Boolean);\n return parts.length ? parts[parts.length - 1]! : path;\n}\n\nfunction dirname(path: string): string {\n const idx = path.lastIndexOf(\"/\");\n return idx >= 0 ? path.slice(0, idx + 1) : \"\";\n}\n\n/**\n * The collapsed-row path preview. Diff magnitude is rendered as a SINGLE muted\n * \"+N −M\" glyph pair — the saturated add/del green/red is reserved exclusively\n * for the expanded DiffView gutter, so the one-line rail stays a calm, single\n * hue (the file path) with no competing colored numerics.\n */\nfunction PathPreview({\n path,\n add,\n del,\n}: {\n path: string;\n add?: number | undefined;\n del?: number | undefined;\n}) {\n return (\n <span className=\"inline-flex items-center gap-2 truncate font-og-mono\">\n <span className=\"truncate\">\n <span className=\"text-og-fg-subtle\">{dirname(path)}</span>\n <span className=\"text-og-fg-muted\">{basename(path)}</span>\n </span>\n {add != null || del != null ? (\n <span className=\"shrink-0 text-og-fg-subtle\">\n {add != null ? `+${add}` : \"\"}\n {add != null && del != null ? \" \" : \"\"}\n {del != null ? `−${del}` : \"\"}\n </span>\n ) : null}\n </span>\n );\n}\n\nfunction ApplyPatchRenderer({ item }: ToolRendererProps) {\n const ops = applyPatchOpsFromToolItem(item);\n const failed = item.status === \"failed\";\n const cancelled = item.status === \"cancelled\";\n const running = item.status === \"running\";\n const firstOp = ops[0];\n\n if (running) {\n // Show the patch structure from the arguments (available immediately on\n // creation), but mark the row clearly as in-progress — not applied yet.\n const fileCount = ops.length;\n const titleVerb = firstOp ? `Applying ${basename(firstOp.path)}` : \"Applying patch\";\n return (\n <ActivityDisclosure\n icon={<FileDiffIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={fileCount > 1 ? `Applying ${fileCount} files` : titleVerb}\n running\n preview={\n <RunningPreview>\n {fileCount > 1 ? `${fileCount} files` : firstOp ? firstOp.path : \"applying…\"}\n </RunningPreview>\n }\n >\n {ops.map((op, index) => {\n const file = safeParseOp(op);\n const key = `${op.type}:${op.path}:${index}`;\n return file ? (\n <ToolDiff key={key} files={[file]} />\n ) : (\n <div key={key}>\n <p className=\"mb-1 font-og-mono text-og-xs text-og-fg-muted\">{op.path}</p>\n <RawPatch diff={op.diff ?? \"\"} />\n </div>\n );\n })}\n </ActivityDisclosure>\n );\n }\n\n if (failed) {\n return (\n <ActivityDisclosure\n icon={<FileDiffIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={firstOp ? `${verbForOp(firstOp)} ${basename(firstOp.path)}` : \"apply_patch\"}\n chip={{ tone: \"bad\", text: \"failed\" }}\n preview={typeof item.output === \"string\" ? item.output : \"patch failed\"}\n >\n <PayloadBlock label=\"Error\" value={item.output} failed />\n </ActivityDisclosure>\n );\n }\n\n // multi-file edit — magnitude stays a single muted glyph; the per-file\n // green/red lives only inside the expanded DiffView gutter.\n if (ops.length > 1) {\n // Parse every op: successfully parsed ones go into ToolDiff; malformed ops\n // fall back to a RawPatch display (mirroring the single-op fallback path).\n // The count in the title/preview equals ops.length so it is always truthful\n // regardless of how many ops parsed successfully.\n const parsed = ops.map((op) => safeParseOp(op));\n const goodFiles = parsed.filter((f): f is GitFileDiff => f !== null);\n const add = goodFiles.reduce((n, f) => n + f.additions, 0);\n const del = goodFiles.reduce((n, f) => n + f.deletions, 0);\n return (\n <ActivityDisclosure\n icon={<FileDiffIcon className={ICON_SIZE} />}\n iconTone=\"accent\"\n title={`Edited ${ops.length} files`}\n cancelled={cancelled}\n preview={\n <span className=\"inline-flex items-center gap-2 font-og-mono\">\n <span className=\"text-og-fg-muted\">{ops.length} files</span>\n <span className=\"text-og-fg-subtle\">\n +{add} −{del}\n </span>\n </span>\n }\n >\n {ops.map((op, index) => {\n const file = parsed[index];\n const key = `${op.type}:${op.path}:${index}`;\n return file ? (\n <ToolDiff key={key} files={[file]} />\n ) : (\n <div key={key}>\n <p className=\"mb-1 font-og-mono text-og-xs text-og-fg-muted\">{op.path}</p>\n <RawPatch diff={op.diff ?? \"\"} />\n </div>\n );\n })}\n </ActivityDisclosure>\n );\n }\n\n // single op\n if (!firstOp) {\n return <GenericRenderer item={item} />;\n }\n if (firstOp.type === \"delete_file\") {\n return (\n <ActivityDisclosure\n icon={<FileDiffIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={`Deleted ${basename(firstOp.path)}`}\n cancelled={cancelled}\n preview={<PathPreview path={firstOp.path} />}\n >\n <BodyNote>File deleted — no diff to show.</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n const file = safeParseOp(firstOp);\n if (!file) {\n return (\n <ActivityDisclosure\n icon={<FileDiffIcon className={ICON_SIZE} />}\n iconTone=\"accent\"\n title={`${verbForOp(firstOp)} ${basename(firstOp.path)}`}\n cancelled={cancelled}\n preview={\n <span className=\"inline-flex items-center gap-2 font-og-mono\">\n <span className=\"text-og-fg-muted\">{basename(firstOp.path)}</span>\n <span className=\"text-og-fg-subtle\">malformed V4A</span>\n </span>\n }\n >\n <RawPatch diff={firstOp.diff ?? \"\"} />\n </ActivityDisclosure>\n );\n }\n\n // The collapsed row shows verb + basename (title) and a muted \"+N −M\"\n // (preview); on expand the preview is hidden and the DiffView header carries\n // the path + churn — so the filename/stat never appears twice at once.\n return (\n <ActivityDisclosure\n icon={<FileDiffIcon className={ICON_SIZE} />}\n iconTone=\"accent\"\n title={`${verbForOp(firstOp)} ${basename(file.path)}`}\n cancelled={cancelled}\n preview={<PathPreview path={file.path} add={file.additions} del={file.deletions} />}\n >\n <ToolDiff files={[file]} />\n </ActivityDisclosure>\n );\n}\n\nfunction safeParseOp(op: ApplyPatchOperation): GitFileDiff | null {\n try {\n return v4aToGitFileDiff(op);\n } catch {\n return null;\n }\n}\n\n/* ---- computer_call --------------------------------------------------------- */\n\ntype ComputerAction = {\n type?: string;\n x?: number;\n y?: number;\n text?: string;\n keys?: string[];\n button?: string;\n};\n\nfunction computerVerb(action: ComputerAction | undefined): string {\n if (!action || !action.type) {\n return \"Acted\";\n }\n switch (action.type) {\n case \"screenshot\":\n return \"Screenshot\";\n case \"click\":\n return `Clicked (${action.x}, ${action.y})`;\n case \"double_click\":\n return `Double-clicked (${action.x}, ${action.y})`;\n case \"move\":\n return `Moved (${action.x}, ${action.y})`;\n case \"scroll\":\n return \"Scrolled\";\n case \"type\": {\n const t = action.text ?? \"\";\n return `Typed “${t.slice(0, 28)}${t.length > 28 ? \"…\" : \"\"}”`;\n }\n case \"keypress\":\n return `Pressed ${(action.keys ?? []).join(\"+\")}`;\n case \"drag\":\n return \"Dragged\";\n case \"wait\":\n return \"Waited\";\n default:\n return action.type;\n }\n}\n\n/** Coerce a function-tool arguments payload into the ComputerAction fields. */\nfunction asComputerArgs(args: unknown): Partial<ComputerAction> {\n if (!args) {\n return {};\n }\n const parsed = typeof args === \"string\" ? tryParseJson(args) : args;\n if (!parsed || typeof parsed !== \"object\") {\n return {};\n }\n const record = parsed as Record<string, unknown>;\n return {\n ...(typeof record.x === \"number\" ? { x: record.x } : {}),\n ...(typeof record.y === \"number\" ? { y: record.y } : {}),\n ...(typeof record.text === \"string\" ? { text: record.text } : {}),\n ...(Array.isArray(record.keys) ? { keys: record.keys as string[] } : {}),\n ...(typeof record.button === \"string\" ? { button: record.button } : {}),\n };\n}\n\nfunction ComputerCallRenderer({ item, loadRetainedScreenshot }: ToolRendererProps) {\n const raw = (item.raw ?? {}) as {\n action?: ComputerAction;\n actions?: ComputerAction[];\n providerData?: { approvalStatus?: string };\n };\n // Function-mode computer tools (computer_screenshot / computer_click / …,\n // used on codex + chat-wire providers since the explicit tool-transport\n // change) carry the action in the tool NAME + arguments instead of raw.action.\n // Normalize them into the same ComputerAction shape so one renderer serves\n // every transport.\n const functionAction: ComputerAction | undefined =\n !raw.action && item.name.startsWith(\"computer_\") && item.name !== \"computer_call\"\n ? { type: item.name.slice(\"computer_\".length), ...asComputerArgs(item.arguments) }\n : undefined;\n const action = raw.action ?? functionAction;\n const actions = raw.actions ?? (action ? [action] : []);\n const verb = computerVerb(action);\n const out = item.output;\n const running = item.status === \"running\";\n const rejected = raw.providerData?.approvalStatus === \"rejected\";\n const readOnly = typeof out === \"string\" && out.includes(\"read-only\");\n const shotUrl = screenshotDataUrl(out);\n const retained = retainedScreenshotMetadata(out);\n const omittedMedia = mediaPreviewFact(out);\n const empty = out === \"\" || out == null;\n const batched = actions.length > 1 ? actions.map((a) => computerVerb(a)).join(\" · \") : null;\n // Fold the batched-action count into the title (one media affordance per row),\n // rather than a separate \"+N more\" mono label competing beside the thumbnail.\n const countSuffix = actions.length > 1 ? ` ·${actions.length}` : \"\";\n const isShot = action?.type === \"screenshot\";\n\n if (running) {\n return (\n <ActivityDisclosure\n icon={\n isShot ? (\n <CameraIcon className={ICON_SIZE} />\n ) : (\n <MousePointer2Icon className={ICON_SIZE} />\n )\n }\n iconTone=\"running\"\n title={verb}\n running\n media={<MediaSkeleton />}\n >\n <BodyNote>capturing frame…</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n if (readOnly) {\n return (\n <ActivityDisclosure\n icon={<MousePointer2Icon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={verb}\n chip={{ tone: \"bad\", text: \"read-only\" }}\n preview=\"write actions disabled\"\n >\n <BodyNote tone=\"error\">computer-use is read-only — write actions are disabled.</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n if (rejected) {\n return (\n <ActivityDisclosure\n icon={<LockIcon className={ICON_SIZE} />}\n iconTone=\"muted\"\n title={verb}\n preview=\"approval rejected — this action did not run\"\n >\n <BodyNote>approval rejected — this action did not run.</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n const isFailed = item.status === \"failed\";\n const isCancelled = item.status === \"cancelled\";\n\n if (retained) {\n if (!retained.available) {\n const state =\n retained.reason === \"expired\" || retained.reason === \"deleted\"\n ? retained.reason\n : \"unavailable\";\n return (\n <ActivityDisclosure\n icon={<CameraOffIcon className={ICON_SIZE} />}\n iconTone={isFailed ? \"failed\" : \"muted\"}\n title={`${verb}${countSuffix} · ${state}`}\n failed={isFailed}\n cancelled={isCancelled}\n preview={`screenshot ${state}`}\n media={<MediaEmpty />}\n >\n <BodyNote tone={isFailed ? \"error\" : undefined}>\n Screenshot {state}: {retained.reason.replaceAll(\"_\", \" \")}.\n </BodyNote>\n </ActivityDisclosure>\n );\n }\n return (\n <RetainedSessionImageDisclosure\n artifact={retained}\n load={loadRetainedScreenshot}\n title={`${verb}${countSuffix}`}\n caption={`${verb}${countSuffix}`}\n noun=\"screenshot\"\n icon={<CameraIcon className={ICON_SIZE} />}\n lightboxLabel=\"Screenshot\"\n batched={batched}\n failed={isFailed}\n cancelled={isCancelled}\n />\n );\n }\n\n if (shotUrl) {\n const caption = `${verb}${actions.length > 1 ? ` (+${actions.length - 1} more)` : \"\"}`;\n return (\n <ActivityDisclosure\n icon={\n isShot ? (\n <CameraIcon className={ICON_SIZE} />\n ) : (\n <MousePointer2Icon className={ICON_SIZE} />\n )\n }\n iconTone={isFailed ? \"failed\" : \"accent\"}\n title={`${verb}${countSuffix}`}\n failed={isFailed}\n cancelled={isCancelled}\n media={<Thumbnail src={shotUrl} caption={caption} />}\n >\n <ScreenshotFigure src={shotUrl} caption={caption} />\n {batched ? <BodyNote>batched: {batched}</BodyNote> : null}\n </ActivityDisclosure>\n );\n }\n\n if (omittedMedia) {\n return (\n <ActivityDisclosure\n icon={<CameraOffIcon className={ICON_SIZE} />}\n iconTone={isFailed ? \"failed\" : \"muted\"}\n title={`${verb}${countSuffix} · image omitted · not retained`}\n failed={isFailed}\n cancelled={isCancelled}\n preview=\"inline image omitted · not retained\"\n media={<MediaEmpty />}\n >\n <BodyNote>\n The inline {omittedMedia.mediaType} output was omitted from the audit timeline and its\n source bytes were not retained.\n </BodyNote>\n {batched ? <BodyNote>batched: {batched}</BodyNote> : null}\n </ActivityDisclosure>\n );\n }\n\n if (empty) {\n return (\n <ActivityDisclosure\n icon={<CameraOffIcon className={ICON_SIZE} />}\n iconTone={isFailed ? \"failed\" : \"muted\"}\n title={verb}\n failed={isFailed}\n cancelled={isCancelled}\n media={<MediaEmpty />}\n >\n <BodyNote>\n {isFailed\n ? \"computer_call failed — no image returned.\"\n : isCancelled\n ? \"computer_call interrupted — no image returned.\"\n : \"(no image) — the session returned an empty screenshot.\"}\n </BodyNote>\n </ActivityDisclosure>\n );\n }\n\n // a non-screenshot action whose output is not an image (click/keypress)\n return (\n <ActivityDisclosure\n icon={<MousePointer2Icon className={ICON_SIZE} />}\n iconTone={isFailed ? \"failed\" : \"accent\"}\n title={verb}\n failed={isFailed}\n cancelled={isCancelled}\n preview={batched ?? undefined}\n expandable={batched != null}\n >\n {batched ? <BodyNote>{batched}</BodyNote> : null}\n </ActivityDisclosure>\n );\n}\n\ntype RetainedImageState =\n | { kind: \"loading\" }\n | { kind: \"ready\"; url: string }\n | { kind: \"unavailable\"; label: string }\n | { kind: \"error\"; message: string };\n\nfunction useRetainedImageObjectUrl(\n artifact: RetainedArtifactReference,\n load: ToolRendererProps[\"loadRetainedArtifact\"],\n): RetainedImageState {\n const [state, setState] = useState<RetainedImageState>({ kind: \"loading\" });\n // Function outputs are commonly serialized JSON. Parsing them creates a new\n // object on every render, so depend on the immutable wire value rather than\n // object identity; otherwise the loader can refetch after its own setState.\n const artifactValue = retainedArtifactValue(artifact);\n const stableArtifactRef = useRef({ value: artifactValue, artifact });\n if (stableArtifactRef.current.value !== artifactValue) {\n stableArtifactRef.current = { value: artifactValue, artifact };\n }\n const stableArtifact = stableArtifactRef.current.artifact;\n useEffect(() => {\n if (!load) {\n setState({ kind: \"unavailable\", label: \"retrieval is not configured\" });\n return;\n }\n const controller = new AbortController();\n let objectUrl: string | null = null;\n setState({ kind: \"loading\" });\n void load(stableArtifact, controller.signal)\n .then((source) => {\n if (controller.signal.aborted) return;\n if (!source) {\n setState({ kind: \"unavailable\", label: \"bytes are unavailable\" });\n return;\n }\n if (!(source instanceof Uint8Array)) {\n if (!source.url.trim()) {\n setState({ kind: \"unavailable\", label: \"URL is unavailable\" });\n return;\n }\n setState({ kind: \"ready\", url: source.url });\n return;\n }\n objectUrl = URL.createObjectURL(\n new Blob([source as unknown as BlobPart], { type: stableArtifact.contentType }),\n );\n setState({ kind: \"ready\", url: objectUrl });\n })\n .catch((error: unknown) => {\n if (controller.signal.aborted) return;\n const status =\n error && typeof error === \"object\" && \"status\" in error\n ? Number((error as { status?: unknown }).status)\n : null;\n setState(\n status === 404\n ? { kind: \"unavailable\", label: \"deleted\" }\n : status === 410\n ? { kind: \"unavailable\", label: \"expired or unavailable\" }\n : { kind: \"error\", message: \"retrieval failed\" },\n );\n });\n return () => {\n controller.abort();\n if (objectUrl) URL.revokeObjectURL(objectUrl);\n };\n }, [stableArtifact, load]);\n return state;\n}\n\nfunction retainedArtifactValue(artifact: RetainedArtifactReference): string {\n return [\n artifact.artifactId,\n artifact.kind,\n artifact.contentType,\n artifact.originalBytes,\n artifact.sha256,\n artifact.retainedAt,\n artifact.dimensions?.width ?? \"\",\n artifact.dimensions?.height ?? \"\",\n artifact.retention.policy,\n artifact.retention.expiresAt ?? \"\",\n artifact.retrieval.method,\n artifact.retrieval.path,\n artifact.retrieval.acceptRanges,\n artifact.retrieval.maxRangeBytes,\n ].join(\"\\0\");\n}\n\nfunction RetainedSessionImageDisclosure({\n artifact,\n load,\n title,\n caption,\n noun,\n icon,\n lightboxLabel,\n batched,\n failed,\n cancelled,\n}: {\n artifact: RetainedArtifactReference;\n load: ToolRendererProps[\"loadRetainedScreenshot\"];\n title: string;\n caption: string;\n noun: \"image\" | \"screenshot\";\n icon: ReactNode;\n lightboxLabel: string;\n batched: string | null;\n failed: boolean;\n cancelled: boolean;\n}) {\n const state = useRetainedImageObjectUrl(artifact, load);\n const downloadFilename = retainedImageFilename(artifact);\n\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone={failed ? \"failed\" : state.kind === \"ready\" ? \"accent\" : \"muted\"}\n title={title}\n failed={failed}\n cancelled={cancelled}\n preview={\n state.kind === \"loading\"\n ? `loading retained ${noun}…`\n : state.kind === \"error\"\n ? `${noun} retrieval failed`\n : state.kind === \"unavailable\"\n ? `${noun} ${state.label}`\n : undefined\n }\n media={\n state.kind === \"ready\" ? (\n <Thumbnail\n src={state.url}\n caption={caption}\n alt={caption}\n expandLabel={`Expand ${noun}`}\n lightboxLabel={lightboxLabel}\n downloadFilename={downloadFilename}\n />\n ) : state.kind === \"loading\" ? (\n <MediaSkeleton />\n ) : (\n <MediaEmpty />\n )\n }\n >\n {state.kind === \"ready\" ? (\n <ScreenshotFigure\n src={state.url}\n caption={caption}\n alt={caption}\n expandLabel={`Expand ${noun}`}\n lightboxLabel={lightboxLabel}\n downloadFilename={downloadFilename}\n />\n ) : state.kind === \"loading\" ? (\n <BodyNote>Loading the retained {noun}…</BodyNote>\n ) : state.kind === \"unavailable\" ? (\n <BodyNote>\n {noun === \"screenshot\" ? \"Screenshot\" : \"Image\"} {state.label}.\n </BodyNote>\n ) : (\n <BodyNote tone=\"error\">\n {noun === \"screenshot\" ? \"Screenshot\" : \"Image\"} retrieval failed: {state.message}\n </BodyNote>\n )}\n {batched ? <BodyNote>batched: {batched}</BodyNote> : null}\n </ActivityDisclosure>\n );\n}\n\nfunction GeneratedImageRenderer({ item, loadRetainedArtifact }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const prompt = typeof args.prompt === \"string\" ? args.prompt : \"\";\n const raw =\n item.raw && typeof item.raw === \"object\" && !Array.isArray(item.raw)\n ? (item.raw as Record<string, unknown>)\n : null;\n // Function tools settle through agent.toolCall.output; OpenAI's hosted image\n // call is already complete on agent.toolCall.created and carries the compact\n // receipt in raw.output. Both paths deliberately converge on one renderer.\n const receipt = generatedImageReceipt(item.output) ?? generatedImageReceipt(raw?.output);\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title=\"Generating image\"\n running\n preview={<RunningPreview>{truncatePreview(prompt, 72) || \"creating…\"}</RunningPreview>}\n media={<MediaSkeleton />}\n >\n {prompt ? <BodyNote>{prompt}</BodyNote> : null}\n </ActivityDisclosure>\n );\n }\n if (!receipt) return <GenericRenderer item={item} />;\n return (\n <GeneratedImageDisclosure\n receipt={receipt}\n load={loadRetainedArtifact}\n prompt={prompt}\n failed={item.status === \"failed\"}\n cancelled={item.status === \"cancelled\"}\n />\n );\n}\n\nfunction GeneratedVideoRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const prompt = typeof args.prompt === \"string\" ? args.prompt : \"\";\n const parsedOutput = typeof item.output === \"string\" ? tryParseJson(item.output) : item.output;\n const accepted =\n parsedOutput &&\n typeof parsedOutput === \"object\" &&\n !Array.isArray(parsedOutput) &&\n (parsedOutput as Record<string, unknown>).status === \"accepted\";\n const failed = item.status === \"failed\";\n const cancelled = item.status === \"cancelled\";\n const running = item.status === \"running\";\n return (\n <ActivityDisclosure\n icon={<VideoIcon className={ICON_SIZE} />}\n iconTone={failed ? \"failed\" : running ? \"running\" : accepted ? \"accent\" : \"muted\"}\n title={\n running ? \"Starting video generation\" : accepted ? \"Generating video\" : \"Generate video\"\n }\n running={running}\n failed={failed}\n cancelled={cancelled}\n preview={truncatePreview(prompt, 88) || (accepted ? \"request accepted\" : undefined)}\n >\n {prompt ? <BodyNote>{prompt}</BodyNote> : null}\n {accepted ? (\n <BodyNote>The video will appear here when it is ready.</BodyNote>\n ) : item.output !== undefined ? (\n <PayloadBlock label=\"Output\" value={item.output} />\n ) : null}\n </ActivityDisclosure>\n );\n}\nfunction SandboxFilePublishRenderer({ item, loadRetainedArtifact }: ToolRendererProps) {\n const { text: output, isError } = unwrapMcpOutput(item.output);\n const receipt = parseSandboxFileArtifactReceipt(output);\n const [downloadState, setDownloadState] = useState<\"idle\" | \"loading\" | \"error\">(\"idle\");\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={<DownloadIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title=\"Publishing file\"\n running\n preview={<RunningPreview>retaining workspace bytes…</RunningPreview>}\n />\n );\n }\n if (!receipt || isError || item.status === \"failed\") {\n return <GenericRenderer item={item} />;\n }\n\n const download = async () => {\n if (!loadRetainedArtifact) {\n setDownloadState(\"error\");\n return;\n }\n setDownloadState(\"loading\");\n let objectUrl: string | null = null;\n try {\n const source = await loadRetainedArtifact(receipt.artifact, new AbortController().signal);\n if (!source) throw new Error(\"artifact unavailable\");\n const url =\n source instanceof Uint8Array\n ? (objectUrl = URL.createObjectURL(\n new Blob([source as unknown as BlobPart], {\n type: receipt.artifact.contentType,\n }),\n ))\n : source.url;\n const anchor = document.createElement(\"a\");\n anchor.href = url;\n anchor.download = receipt.filename;\n anchor.rel = \"noopener\";\n anchor.click();\n setDownloadState(\"idle\");\n } catch {\n setDownloadState(\"error\");\n } finally {\n const urlToRevoke = objectUrl;\n if (urlToRevoke) setTimeout(() => URL.revokeObjectURL(urlToRevoke), 0);\n }\n };\n\n return (\n <ActivityDisclosure\n icon={<DownloadIcon className={ICON_SIZE} />}\n iconTone=\"accent\"\n title={`Published ${receipt.filename}`}\n defaultOpen\n preview={formatBytes(receipt.artifact.originalBytes)}\n >\n <button\n type=\"button\"\n onClick={() => void download()}\n disabled={downloadState === \"loading\"}\n className=\"inline-flex items-center gap-1.5 rounded-og-sm border border-og-border px-2.5 py-1.5 text-og-sm font-medium text-og-fg transition-colors hover:border-og-border-strong hover:bg-og-surface-2 disabled:cursor-wait disabled:opacity-60\"\n >\n <DownloadIcon className=\"size-3.5\" />\n {downloadState === \"loading\"\n ? \"Preparing…\"\n : downloadState === \"error\"\n ? \"Retry download\"\n : \"Download\"}\n </button>\n </ActivityDisclosure>\n );\n}\n\nfunction GeneratedImageDisclosure({\n receipt,\n load,\n prompt,\n failed,\n cancelled,\n}: {\n receipt: NonNullable<ReturnType<typeof generatedImageReceipt>>;\n load: ToolRendererProps[\"loadRetainedArtifact\"];\n prompt: string;\n failed: boolean;\n cancelled: boolean;\n}) {\n const state = useRetainedImageObjectUrl(receipt.artifact, load);\n const dimensions = receipt.artifact.dimensions!;\n const title = failed ? \"Image generation failed\" : \"Generated image\";\n const caption = prompt || `Generated image · ${dimensions.width}×${dimensions.height}`;\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone={failed ? \"failed\" : state.kind === \"ready\" ? \"accent\" : \"muted\"}\n title={title}\n defaultOpen={!failed && !cancelled}\n failed={failed}\n cancelled={cancelled}\n preview={\n state.kind === \"loading\"\n ? \"loading image…\"\n : state.kind === \"error\"\n ? \"image retrieval failed\"\n : state.kind === \"unavailable\"\n ? `image ${state.label}`\n : truncatePreview(prompt, 88) || `${dimensions.width}×${dimensions.height}`\n }\n media={\n state.kind === \"ready\" ? (\n <Thumbnail\n src={state.url}\n caption={caption}\n alt={caption}\n expandLabel=\"Expand generated image\"\n lightboxLabel=\"Generated image\"\n />\n ) : state.kind === \"loading\" ? (\n <MediaSkeleton />\n ) : (\n <MediaEmpty />\n )\n }\n >\n {state.kind === \"ready\" ? (\n <ScreenshotFigure\n src={state.url}\n caption={caption}\n alt={caption}\n expandLabel=\"Expand generated image\"\n lightboxLabel=\"Generated image\"\n />\n ) : state.kind === \"loading\" ? (\n <BodyNote>Loading the generated image…</BodyNote>\n ) : state.kind === \"unavailable\" ? (\n <BodyNote>Image {state.label}.</BodyNote>\n ) : (\n <BodyNote tone=\"error\">Image retrieval failed.</BodyNote>\n )}\n <BodyNote>\n {dimensions.width}×{dimensions.height} · {receipt.sandboxPath}\n </BodyNote>\n </ActivityDisclosure>\n );\n}\n\nfunction retainedImageFilename(artifact: RetainedArtifactReference): string {\n const extension =\n artifact.contentType === \"image/jpeg\"\n ? \"jpg\"\n : artifact.contentType === \"image/webp\"\n ? \"webp\"\n : \"png\";\n return `${artifact.kind}-${artifact.artifactId}.${extension}`;\n}\n\n/* ---- web_search ------------------------------------------------------------ */\n\ntype WebSearchResult = { title: string; domain: string; snippet: string };\n\n/** Pull a search string from tool-call arguments when providerData.action is sparse. */\nfunction webSearchQueryFromArguments(args: unknown): string | null {\n if (typeof args === \"string\") {\n const trimmed = args.trim();\n if (!trimmed) {\n return null;\n }\n try {\n return webSearchQueryFromArguments(JSON.parse(trimmed));\n } catch {\n return trimmed;\n }\n }\n if (!args || typeof args !== \"object\") {\n return null;\n }\n const record = args as Record<string, unknown>;\n if (typeof record.query === \"string\" && record.query.trim().length > 0) {\n return record.query;\n }\n if (Array.isArray(record.queries)) {\n const first = record.queries.find(\n (value): value is string => typeof value === \"string\" && value.trim().length > 0,\n );\n if (first) {\n return first;\n }\n }\n return null;\n}\n\nfunction WebSearchRenderer({ item }: ToolRendererProps) {\n const raw = (item.raw ?? {}) as {\n providerData?: {\n action?: {\n type?: string;\n query?: string;\n queries?: string[];\n url?: string;\n pattern?: string;\n };\n };\n };\n const action = raw.providerData?.action ?? {};\n const actionType = action.type ?? \"search\";\n // Responses API deprecated singular `query` in favor of `queries[]`.\n // Codex/current OpenAI often only populate the array.\n const queries = (action.queries ?? []).filter(\n (value): value is string => typeof value === \"string\" && value.trim().length > 0,\n );\n const searchQuery =\n (typeof action.query === \"string\" && action.query.trim().length > 0 ? action.query : null) ??\n queries[0] ??\n webSearchQueryFromArguments(item.arguments);\n const running = item.status === \"running\";\n const query =\n actionType === \"open_page\"\n ? (action.url ?? \"(page unavailable)\")\n : actionType === \"find_in_page\"\n ? action.pattern && action.url\n ? `\"${action.pattern}\" in ${action.url}`\n : (action.pattern ?? action.url ?? \"(page unavailable)\")\n : // Codex often emits the live card before action.query/queries land;\n // don't flash the scary unavailable copy while still searching.\n (searchQuery ?? (running ? \"…\" : \"(query unavailable)\"));\n const variants = queries.length > 1 ? ` +${queries.length - 1} variants` : \"\";\n const runningTitle =\n actionType === \"open_page\"\n ? \"Opening web page\"\n : actionType === \"find_in_page\"\n ? \"Searching within page\"\n : \"Searching the web\";\n const completedTitle =\n actionType === \"open_page\"\n ? \"Opened web page\"\n : actionType === \"find_in_page\"\n ? \"Searched within page\"\n : \"Searched the web\";\n // web_search may surface a results array on the output when the host enriches it.\n // Filter out null/undefined/non-object entries before casting: host-provided\n // data is untrusted and a null element would throw on result.title access.\n const rawResults = (item.output as { results?: unknown } | undefined)?.results;\n const results = Array.isArray(rawResults)\n ? (rawResults as unknown[]).filter((r): r is WebSearchResult => !!r && typeof r === \"object\")\n : undefined;\n const resultOccurrences = new Map<string, number>();\n const keyedResults = results?.map((result) => {\n const contentKey = `${result.domain}\\u0000${result.title}\\u0000${result.snippet}`;\n const occurrence = (resultOccurrences.get(contentKey) ?? 0) + 1;\n resultOccurrences.set(contentKey, occurrence);\n return { key: `${contentKey}\\u0000${occurrence}`, result };\n });\n\n if (running) {\n return (\n <ActivityDisclosure\n icon={<SearchIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={runningTitle}\n running\n preview={<RunningPreview>{`${query}${variants}`}</RunningPreview>}\n >\n <BodyNote>searching… results fold into the model context (no output event).</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n return (\n <ActivityDisclosure\n icon={<SearchIcon className={ICON_SIZE} />}\n iconTone=\"muted\"\n title={completedTitle}\n preview={`${query}${variants}`}\n failed={item.status === \"failed\"}\n cancelled={item.status === \"cancelled\"}\n >\n {keyedResults && keyedResults.length ? (\n <ul className=\"flex flex-col gap-2\">\n {keyedResults.map(({ key, result }) => (\n <li key={key} className=\"flex gap-2.5\">\n <GlobeIcon className=\"mt-0.5 size-3.5 shrink-0 text-og-fg-subtle\" />\n <div className=\"min-w-0\">\n <p className=\"truncate text-og-base text-og-fg\">\n {result.title} <span className=\"text-og-fg-subtle\">{result.domain}</span>\n </p>\n <p className=\"text-og-sm leading-5 text-og-fg-muted\">{result.snippet}</p>\n </div>\n </li>\n ))}\n </ul>\n ) : (\n <BodyNote>results folded into model context — no list available.</BodyNote>\n )}\n </ActivityDisclosure>\n );\n}\n\n/* ---- view_image ------------------------------------------------------------ */\n\nconst VIEW_IMAGE_ERRORS = [\n \"was not found\",\n \"is not a file\",\n \"exceeded the allowed size\",\n \"is not a supported image\",\n \"unable to read image\",\n];\n\nfunction ViewImageRenderer({ item, loadRetainedScreenshot }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const path = typeof args.path === \"string\" ? args.path : \"\";\n const out = item.output;\n const text = typeof out === \"string\" ? out : \"\";\n const retained = retainedScreenshotMetadata(out);\n const omittedMedia = mediaPreviewFact(out);\n\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={`View ${basename(path)}`}\n running\n preview={<RunningPreview>reading…</RunningPreview>}\n media={<MediaSkeleton />}\n >\n <BodyNote>reading image…</BodyNote>\n </ActivityDisclosure>\n );\n }\n\n const viewFailed = item.status === \"failed\";\n const viewCancelled = item.status === \"cancelled\";\n\n if (retained) {\n const title = `Viewed ${basename(path)}`;\n if (!retained.available) {\n const state =\n retained.reason === \"expired\" || retained.reason === \"deleted\"\n ? retained.reason\n : \"unavailable\";\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone={viewFailed ? \"failed\" : \"muted\"}\n title={`${title} · ${state}`}\n failed={viewFailed}\n cancelled={viewCancelled}\n preview={`image ${state}`}\n media={<MediaEmpty />}\n >\n <BodyNote tone={viewFailed ? \"error\" : undefined}>\n Image {state}: {retained.reason.replaceAll(\"_\", \" \")}.\n </BodyNote>\n </ActivityDisclosure>\n );\n }\n return (\n <RetainedSessionImageDisclosure\n artifact={retained}\n load={loadRetainedScreenshot}\n title={title}\n caption={path || title}\n noun=\"image\"\n icon={<ImageIcon className={ICON_SIZE} />}\n lightboxLabel=\"Image\"\n batched={null}\n failed={viewFailed}\n cancelled={viewCancelled}\n />\n );\n }\n\n const errMatch = VIEW_IMAGE_ERRORS.find((p) => text.includes(p));\n if (errMatch) {\n const tooBig = text.includes(\"exceeded the allowed size\");\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={`View ${basename(path)}`}\n chip={{ tone: \"bad\", text: tooBig ? \"too large\" : \"error\" }}\n preview={text}\n >\n <BodyNote tone=\"error\">{text}</BodyNote>\n </ActivityDisclosure>\n );\n }\n if (text.startsWith(\"OpenAI file reference:\")) {\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone={viewFailed ? \"failed\" : \"muted\"}\n title={`Viewed ${basename(path)}`}\n failed={viewFailed}\n cancelled={viewCancelled}\n preview={path}\n >\n <BodyNote>{text}</BodyNote>\n </ActivityDisclosure>\n );\n }\n if (omittedMedia) {\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone={viewFailed ? \"failed\" : \"muted\"}\n title={`Viewed ${basename(path)} · image omitted · not retained`}\n failed={viewFailed}\n cancelled={viewCancelled}\n preview=\"inline image omitted · not retained\"\n media={<MediaEmpty />}\n >\n <BodyNote>\n The inline {omittedMedia.mediaType} output was omitted from the audit timeline and its\n source bytes were not retained.\n </BodyNote>\n </ActivityDisclosure>\n );\n }\n if (text.includes(\"No image data\")) {\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone={viewFailed ? \"failed\" : \"muted\"}\n title={`Viewed ${basename(path)}`}\n failed={viewFailed}\n cancelled={viewCancelled}\n preview=\"(no image)\"\n >\n <BodyNote>\n {viewFailed\n ? \"view_image failed — no image data returned.\"\n : viewCancelled\n ? \"view_image interrupted.\"\n : \"(no image) — the sandbox session returned no image data.\"}\n </BodyNote>\n </ActivityDisclosure>\n );\n }\n if (text.startsWith(\"data:\")) {\n return (\n <ActivityDisclosure\n icon={<ImageIcon className={ICON_SIZE} />}\n iconTone={viewFailed ? \"failed\" : \"accent\"}\n title={`Viewed ${basename(path)}`}\n failed={viewFailed}\n cancelled={viewCancelled}\n media={<Thumbnail src={text} caption={path} alt={path} />}\n >\n <ScreenshotFigure src={text} caption={path} alt={path} />\n </ActivityDisclosure>\n );\n }\n return <GenericRenderer item={item} />;\n}\n\n/* ---- environment_set_variable (secret-safe, write-only) -------------------- */\n\nfunction SecretSetRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const name = typeof args.name === \"string\" ? args.name : \"variable\";\n\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={<KeyRoundIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={`Set ${name}`}\n running\n preview={<RunningPreview>setting…</RunningPreview>}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n </ActivityDisclosure>\n );\n }\n\n if (item.status === \"failed\") {\n const errorText = typeof item.output === \"string\" ? item.output : null;\n return (\n <ActivityDisclosure\n icon={<KeyRoundIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={`Set ${name}`}\n failed\n preview={errorText ?? \"variable write failed\"}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n {errorText ? (\n <PayloadBlock label=\"Error\" value={errorText} failed />\n ) : (\n <BodyNote tone=\"error\">the tool call failed with no output.</BodyNote>\n )}\n </ActivityDisclosure>\n );\n }\n\n return (\n <ActivityDisclosure\n icon={<KeyRoundIcon className={ICON_SIZE} />}\n iconTone=\"muted\"\n title={`Set ${name}`}\n cancelled={item.status === \"cancelled\"}\n preview=\"exact value preserved\"\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n <BodyNote>\n The configured value is preserved exactly and available through authorized secret reads.\n </BodyNote>\n </ActivityDisclosure>\n );\n}\n\n/* ---- tool_search (progressive MCP disclosure) ------------------------------ */\n\ntype DisclosedTool = {\n /** Full wire name (`server__leaf` or bare). */\n name: string;\n /** Server / namespace prefix before `__`, when present. */\n source: string | null;\n /** Leaf tool name after `__`. */\n leaf: string;\n};\n\nfunction splitToolWireName(name: string): DisclosedTool {\n const boundary = name.indexOf(\"__\");\n if (boundary <= 0) {\n return { name, source: null, leaf: name };\n }\n return {\n name,\n source: name.slice(0, boundary),\n leaf: name.slice(boundary + 2),\n };\n}\n\n/** Capability query from live tool_search args (object or JSON string). */\nfunction toolSearchQuery(item: ToolRendererProps[\"item\"]): string {\n const fromArgs = parseToolArgs(item.arguments);\n if (typeof fromArgs.query === \"string\" && fromArgs.query.trim()) {\n return fromArgs.query.trim();\n }\n const raw = item.raw;\n if (raw && typeof raw === \"object\") {\n const rawArgs = (raw as { arguments?: unknown }).arguments;\n if (typeof rawArgs === \"string\" && rawArgs.trim()) {\n const parsed = tryParseJson(rawArgs);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const query = (parsed as { query?: unknown }).query;\n if (typeof query === \"string\" && query.trim()) {\n return query.trim();\n }\n }\n } else if (rawArgs && typeof rawArgs === \"object\" && !Array.isArray(rawArgs)) {\n const query = (rawArgs as { query?: unknown }).query;\n if (typeof query === \"string\" && query.trim()) {\n return query.trim();\n }\n }\n }\n return \"\";\n}\n\n/**\n * Parse disclosed tools from the runtime event shape.\n * `normalizeSdkEvent` collapses `tool_search_output.tools[]` into text:\n * \"Disclosed tools: a, b\" | \"No matching tools found.\"\n * Also accept a structured `tools` array when a host/enricher preserves it.\n */\nfunction parseDisclosedTools(output: unknown): DisclosedTool[] | null {\n if (output && typeof output === \"object\" && !Array.isArray(output)) {\n const tools = (output as { tools?: unknown }).tools;\n if (Array.isArray(tools)) {\n return tools\n .map((tool) => {\n if (typeof tool === \"string\" && tool.trim()) {\n return splitToolWireName(tool.trim());\n }\n if (\n tool &&\n typeof tool === \"object\" &&\n typeof (tool as { name?: unknown }).name === \"string\"\n ) {\n const name = (tool as { name: string }).name.trim();\n return name ? splitToolWireName(name) : null;\n }\n return null;\n })\n .filter((tool): tool is DisclosedTool => tool != null);\n }\n }\n\n const { text } = unwrapMcpOutput(output);\n const trimmed = text.trim();\n if (!trimmed) {\n return null;\n }\n if (/^no matching tools found\\.?$/i.test(trimmed)) {\n return [];\n }\n const disclosed = trimmed.match(/^disclosed tools:\\s*(.+)$/i);\n if (disclosed?.[1]) {\n return disclosed[1]\n .split(\",\")\n .map((part) => part.trim())\n .filter(Boolean)\n .map(splitToolWireName);\n }\n const parsed = tryParseJson(trimmed);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parseDisclosedTools(parsed);\n }\n return null;\n}\n\nfunction toolSearchPreview(tools: DisclosedTool[] | null, cancelled: boolean): string | undefined {\n if (cancelled) {\n return undefined;\n }\n if (!tools) {\n return \"Done\";\n }\n if (tools.length === 0) {\n return \"No matches\";\n }\n if (tools.length === 1) {\n return tools[0]!.leaf;\n }\n const head = tools[0]!.leaf;\n return `${tools.length} tools · ${truncatePreview(head, 28)}`;\n}\n\nfunction ToolSearchRenderer({ item }: ToolRendererProps) {\n const query = toolSearchQuery(item);\n const icon = <PackageSearchIcon className={ICON_SIZE} />;\n const running = item.status === \"running\";\n const queryPreview = query ? truncatePreview(query, 64) : \"\";\n\n if (running) {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"running\"\n title=\"Looking up tools\"\n running\n preview={\n queryPreview ? (\n <RunningPreview>{queryPreview}</RunningPreview>\n ) : (\n <RunningPreview>Matching capabilities…</RunningPreview>\n )\n }\n >\n {query ? <BodyNote>capability query: {query}</BodyNote> : null}\n <PayloadBlock label=\"Arguments\" value={parseToolArgs(item.arguments)} />\n </ActivityDisclosure>\n );\n }\n\n const { text: outText, isError } = unwrapMcpOutput(item.output);\n if ((isError || item.status === \"failed\") && item.status !== \"cancelled\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"failed\"\n title=\"Tool lookup failed\"\n failed\n preview={truncatePreview(outText, 80) || queryPreview || \"Lookup failed\"}\n >\n {query ? <BodyNote>capability query: {query}</BodyNote> : null}\n <PayloadBlock label=\"Arguments\" value={parseToolArgs(item.arguments)} />\n <PayloadBlock label=\"Error\" value={outText} failed />\n </ActivityDisclosure>\n );\n }\n\n const tools = parseDisclosedTools(item.output);\n const preview = toolSearchPreview(tools, item.status === \"cancelled\");\n\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"muted\"\n title=\"Looked up tools\"\n cancelled={item.status === \"cancelled\"}\n preview={preview}\n >\n {query ? <BodyNote>capability query: {query}</BodyNote> : null}\n {tools && tools.length > 0 ? (\n <ul className=\"grid gap-1.5\">\n {tools.slice(0, 12).map((tool) => (\n <li key={tool.name} className=\"flex min-w-0 items-baseline gap-2\">\n {tool.source ? (\n <span className=\"shrink-0 text-og-xs text-og-fg-subtle\">{tool.source}</span>\n ) : null}\n <span className=\"truncate font-mono text-og-sm text-og-fg\">{tool.leaf}</span>\n </li>\n ))}\n {tools.length > 12 ? (\n <li className=\"text-og-xs text-og-fg-muted\">+{tools.length - 12} more</li>\n ) : null}\n </ul>\n ) : tools && tools.length === 0 ? (\n <BodyNote>no deferred tools matched this capability query.</BodyNote>\n ) : null}\n <PayloadBlock label=\"Arguments\" value={parseToolArgs(item.arguments)} />\n {tools == null && outText ? <PayloadBlock label=\"Result\" value={outText} /> : null}\n </ActivityDisclosure>\n );\n}\n\n/* ---- docs / knowledge search ----------------------------------------------- */\n\nfunction DocsSearchRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const query = typeof args.query === \"string\" ? args.query.trim() : \"\";\n const title = query ? `Search “${truncatePreview(query, 48)}”` : toolDisplayName(item.name);\n const running = item.status === \"running\";\n\n if (running) {\n return (\n <ActivityDisclosure\n icon={<FileSearchIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={title}\n running\n preview={<RunningPreview>Searching…</RunningPreview>}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n </ActivityDisclosure>\n );\n }\n\n const { text: outText, isError } = unwrapMcpOutput(item.output);\n if ((isError || item.status === \"failed\") && item.status !== \"cancelled\") {\n return (\n <ActivityDisclosure\n icon={<FileSearchIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={title}\n failed\n preview={truncatePreview(outText, 80) || \"Search failed\"}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n <PayloadBlock label=\"Error\" value={outText} failed />\n </ActivityDisclosure>\n );\n }\n\n const hits = parseSearchHits(outText);\n const preview =\n item.status === \"cancelled\"\n ? undefined\n : hits\n ? hits.length === 0\n ? \"No hits\"\n : `${hits.length} hit${hits.length === 1 ? \"\" : \"s\"}`\n : \"Done\";\n\n return (\n <ActivityDisclosure\n icon={<FileSearchIcon className={ICON_SIZE} />}\n iconTone=\"muted\"\n title={title}\n cancelled={item.status === \"cancelled\"}\n preview={preview}\n >\n {hits && hits.length > 0 ? (\n <ul className=\"grid gap-2\">\n {hits.slice(0, 8).map((hit) => (\n <li key={`${hit.title}\\u0000${hit.snippet}`} className=\"min-w-0\">\n <div className=\"truncate text-og-sm font-medium text-og-fg\">{hit.title}</div>\n {hit.snippet ? (\n <div className=\"mt-0.5 line-clamp-2 text-og-xs text-og-fg-muted\">{hit.snippet}</div>\n ) : null}\n </li>\n ))}\n </ul>\n ) : null}\n <PayloadBlock label=\"Arguments\" value={args} />\n <PayloadBlock label=\"Result\" value={outText} />\n </ActivityDisclosure>\n );\n}\n\n/* ---- set_session_title / set_other_session_title --------------------------- */\n\nfunction SetSessionTitleRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const titleArg = typeof args.title === \"string\" ? args.title.trim() : \"\";\n const display = toolDisplayName(item.name);\n const previewTitle = titleArg ? truncatePreview(titleArg, 72) : \"\";\n const icon = <MessagesSquareIcon className={ICON_SIZE} />;\n\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"running\"\n title={display}\n running\n preview={\n previewTitle ? (\n <RunningPreview>{previewTitle}</RunningPreview>\n ) : (\n <RunningPreview>Setting title…</RunningPreview>\n )\n }\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n </ActivityDisclosure>\n );\n }\n\n const { text: outText, isError } = unwrapMcpOutput(item.output);\n if ((isError || item.status === \"failed\") && item.status !== \"cancelled\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"failed\"\n title={display}\n failed\n preview={truncatePreview(outText, 80) || \"Rename failed\"}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n <PayloadBlock label=\"Error\" value={outText} failed />\n </ActivityDisclosure>\n );\n }\n\n // Prefer the submitted title; fall back to a title field in the tool result.\n let settledTitle = previewTitle;\n if (!settledTitle) {\n const parsed = tryParseJson(outText);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const fromResult = (parsed as { title?: unknown }).title;\n if (typeof fromResult === \"string\" && fromResult.trim()) {\n settledTitle = truncatePreview(fromResult.trim(), 72);\n }\n }\n }\n\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"muted\"\n title={display}\n cancelled={item.status === \"cancelled\"}\n preview={item.status === \"cancelled\" ? undefined : settledTitle || undefined}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n {outText ? <PayloadBlock label=\"Result\" value={outText} /> : null}\n </ActivityDisclosure>\n );\n}\n\ntype SearchHit = { title: string; snippet: string };\n\nfunction parseSearchHits(outText: string): SearchHit[] | null {\n const parsed = tryParseJson(outText);\n if (parsed == null) {\n return null;\n }\n const list = Array.isArray(parsed)\n ? parsed\n : parsed &&\n typeof parsed === \"object\" &&\n Array.isArray((parsed as { results?: unknown }).results)\n ? (parsed as { results: unknown[] }).results\n : parsed && typeof parsed === \"object\" && Array.isArray((parsed as { hits?: unknown }).hits)\n ? (parsed as { hits: unknown[] }).hits\n : null;\n if (!list) {\n return null;\n }\n return list.map((row) => {\n const r = row && typeof row === \"object\" ? (row as Record<string, unknown>) : {};\n const title =\n (typeof r.title === \"string\" && r.title) ||\n (typeof r.name === \"string\" && r.name) ||\n (typeof r.documentTitle === \"string\" && r.documentTitle) ||\n (typeof r.path === \"string\" && r.path) ||\n (typeof r.id === \"string\" && r.id) ||\n \"Result\";\n const snippet =\n (typeof r.snippet === \"string\" && r.snippet) ||\n (typeof r.text === \"string\" && r.text) ||\n (typeof r.content === \"string\" && r.content) ||\n \"\";\n return { title, snippet: truncatePreview(snippet, 160) };\n });\n}\n\n/* ---- company memory propose (docs MCP) ------------------------------------- */\n\nfunction MemoryProposeRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const text = typeof args.text === \"string\" ? args.text.trim() : \"\";\n const title = \"Propose memory\";\n const running = item.status === \"running\";\n\n if (running) {\n return (\n <ActivityDisclosure\n icon={<BrainCircuitIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={title}\n running\n preview={<RunningPreview>Proposing…</RunningPreview>}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n </ActivityDisclosure>\n );\n }\n\n const { text: outText, isError } = unwrapMcpOutput(item.output);\n if ((isError || item.status === \"failed\") && item.status !== \"cancelled\") {\n return (\n <ActivityDisclosure\n icon={<BrainCircuitIcon className={ICON_SIZE} />}\n iconTone=\"failed\"\n title={title}\n failed\n preview={truncatePreview(outText, 80) || \"Propose failed\"}\n >\n {text ? <BodyNote>{text}</BodyNote> : null}\n <PayloadBlock label=\"Error\" value={outText} failed />\n </ActivityDisclosure>\n );\n }\n\n return (\n <ActivityDisclosure\n icon={<BrainCircuitIcon className={ICON_SIZE} />}\n iconTone=\"muted\"\n title={title}\n cancelled={item.status === \"cancelled\"}\n preview={text ? truncatePreview(text, 90) : \"Done\"}\n >\n {text ? <BodyNote>{text}</BodyNote> : null}\n <PayloadBlock label=\"Result\" value={outText} />\n </ActivityDisclosure>\n );\n}\n\n/* ---- request_human_input --------------------------------------------------- */\n\nfunction askToolPreview(args: unknown): string | null {\n const record = args && typeof args === \"object\" ? (args as Record<string, unknown>) : null;\n const questions = Array.isArray(record?.questions) ? record.questions : null;\n if (!questions || questions.length === 0) {\n return null;\n }\n const first = questions[0];\n if (!first || typeof first !== \"object\") {\n return null;\n }\n const q = first as Record<string, unknown>;\n const text =\n typeof q.label === \"string\" && q.label.trim()\n ? q.label.trim()\n : typeof q.prompt === \"string\" && q.prompt.trim()\n ? q.prompt.trim()\n : null;\n if (!text) {\n return null;\n }\n const preview = truncatePreview(text, 90);\n return questions.length > 1 ? `${preview} · ${questions.length} questions` : preview;\n}\n\nfunction AskRenderer({ item }: ToolRendererProps) {\n const args = parseToolArgs(item.arguments);\n const preview = askToolPreview(args);\n const icon = <MessageCircleQuestionIcon className={ICON_SIZE} />;\n const title = \"Ask\";\n\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"running\"\n title={title}\n running\n preview={\n preview ? (\n <RunningPreview>{preview}</RunningPreview>\n ) : (\n <RunningPreview>Waiting…</RunningPreview>\n )\n }\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n </ActivityDisclosure>\n );\n }\n\n const { text: outText, isError } = unwrapMcpOutput(item.output);\n if ((isError || item.status === \"failed\") && item.status !== \"cancelled\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"failed\"\n title={title}\n chip={{ tone: \"bad\", text: \"error\" }}\n preview={truncatePreview(outText, 80) || preview || \"Error\"}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n <PayloadBlock label=\"Error\" value={outText} failed />\n </ActivityDisclosure>\n );\n }\n\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"muted\"\n title={title}\n cancelled={item.status === \"cancelled\"}\n preview={item.status === \"cancelled\" ? undefined : (preview ?? undefined)}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n {outText ? <PayloadBlock label=\"Result\" value={outText} /> : null}\n </ActivityDisclosure>\n );\n}\n\n/* ---- run_on ---------------------------------------------------------------- */\n\nfunction runOnTargetName(output: unknown): string | null {\n const { text } = unwrapMcpOutput(output);\n const parsed = tryParseJson(text);\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n const name = (parsed as { targetName?: unknown }).targetName;\n if (typeof name === \"string\" && name.trim()) {\n return name.trim();\n }\n }\n return null;\n}\n\nfunction runOnOpPreview(args: Record<string, unknown>): string | null {\n const op = args.op;\n if (!op || typeof op !== \"object\" || Array.isArray(op)) {\n return null;\n }\n const record = op as Record<string, unknown>;\n if (record.kind === \"exec\" && typeof record.cmd === \"string\" && record.cmd.trim()) {\n return `$ ${record.cmd.trim()}`;\n }\n if (\n (record.kind === \"read\" || record.kind === \"write\") &&\n typeof record.path === \"string\" &&\n record.path.trim()\n ) {\n return truncatePreview(record.path.trim(), 72);\n }\n return null;\n}\n\nfunction RunOnRenderer({ item }: ToolRendererProps) {\n const parsedArgs = parseToolArgs(item.arguments);\n const args = parsedArgs;\n const targetName = runOnTargetName(item.output);\n const title = targetName ? `Run on ${targetName}` : \"Run on\";\n const opPreview = runOnOpPreview(parsedArgs);\n const icon = <ServerIcon className={ICON_SIZE} />;\n\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"running\"\n title={title}\n running\n preview={\n opPreview ? (\n <RunningPreview>{opPreview}</RunningPreview>\n ) : (\n <RunningPreview>Running…</RunningPreview>\n )\n }\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n </ActivityDisclosure>\n );\n }\n\n const { text: outText, isError } = unwrapMcpOutput(item.output);\n if ((isError || item.status === \"failed\") && item.status !== \"cancelled\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"failed\"\n title={title}\n chip={{ tone: \"bad\", text: \"error\" }}\n preview={truncatePreview(outText, 80) || opPreview || \"Error\"}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n <PayloadBlock label=\"Error\" value={outText} failed />\n </ActivityDisclosure>\n );\n }\n\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"muted\"\n title={title}\n cancelled={item.status === \"cancelled\"}\n preview={item.status === \"cancelled\" ? undefined : (opPreview ?? undefined)}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n {outText ? <PayloadBlock label=\"Result\" value={outText} /> : null}\n </ActivityDisclosure>\n );\n}\n\n/* ---- generic fallback (first-party MCP, external MCP, unknown) ------------- */\n\n/**\n * Baseline craft for unmatched tools: family icon + title-cased leaf + honest\n * status preview (Running… / Done / error snippet). No argument-field sniffing —\n * JSON stays in the expandable body only.\n */\nfunction GenericRenderer({ item }: ToolRendererProps) {\n const running = item.status === \"running\";\n const args = parseToolArgs(item.arguments);\n const display = toolDisplayName(item.name);\n const icon = <GenericToolIcon name={item.name} />;\n // Goal tools: surface the objective text on the collapsed row so the in-cluster\n // tool replaces the old breakaway GoalRow pill without losing the gist.\n const goalPreview = goalToolPreview(item.name, args);\n\n if (running) {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"running\"\n title={display}\n running\n preview={goalPreview ?? <RunningPreview>Running…</RunningPreview>}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n </ActivityDisclosure>\n );\n }\n\n const { text: outText, isError } = unwrapMcpOutput(item.output);\n // Cancelled is NOT an error — a user-cancelled tool should not surface the red\n // error chip even if the output payload carries an isError flag (the error may be\n // a consequence of the cancellation, not the tool's own failure).\n if ((isError || item.status === \"failed\") && item.status !== \"cancelled\") {\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"failed\"\n title={display}\n chip={{ tone: \"bad\", text: \"error\" }}\n preview={truncatePreview(outText, 80) || \"Error\"}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n <PayloadBlock label=\"Error\" value={outText} failed />\n </ActivityDisclosure>\n );\n }\n\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone=\"muted\"\n title={display}\n cancelled={item.status === \"cancelled\"}\n preview={item.status === \"cancelled\" ? undefined : (goalPreview ?? \"Done\")}\n >\n <PayloadBlock label=\"Arguments\" value={args} />\n <PayloadBlock label=\"Result\" value={outText} />\n </ActivityDisclosure>\n );\n}\n\nfunction goalToolPreview(name: string, args: unknown): string | null {\n const leaf = mcpToolLeaf(name);\n if (\n leaf !== \"goal_set\" &&\n leaf !== \"goal_update\" &&\n leaf !== \"goal_complete\" &&\n leaf !== \"goal_pause\" &&\n leaf !== \"goal_wait\"\n ) {\n return null;\n }\n const record = args && typeof args === \"object\" ? (args as Record<string, unknown>) : null;\n if (!record) {\n return null;\n }\n const text =\n typeof record.text === \"string\"\n ? record.text\n : typeof record.evidence === \"string\"\n ? record.evidence\n : typeof record.rationale === \"string\"\n ? record.rationale\n : typeof record.reason === \"string\"\n ? record.reason\n : typeof record.progressNote === \"string\"\n ? record.progressNote\n : null;\n return text ? truncatePreview(text, 90) : null;\n}\n\nfunction truncatePreview(text: string, max: number): string {\n const cleaned = text.replace(/\\s+/g, \" \").trim();\n if (!cleaned) {\n return \"\";\n }\n return cleaned.length > max ? `${cleaned.slice(0, max - 1)}…` : cleaned;\n}\n\n/** Explicit first-party leaf/prefix → canonical product icons (match nav/pages). */\nfunction GenericToolIcon({ name }: { name: string }) {\n const leaf = mcpToolLeaf(name);\n const Icon =\n leaf === \"request_human_input\"\n ? MessageCircleQuestionIcon\n : leaf.startsWith(\"goal_\")\n ? TargetIcon\n : leaf.startsWith(\"memory_\") ||\n leaf === \"preference_registry_summary\" ||\n leaf === \"preference_registry_get\"\n ? BrainCircuitIcon\n : leaf.startsWith(\"session_\") ||\n leaf === \"sessions_list\" ||\n leaf === \"set_session_title\" ||\n leaf === \"set_other_session_title\"\n ? MessagesSquareIcon\n : leaf.startsWith(\"sandbox\") || leaf === \"sandboxes_list\" || leaf === \"run_on\"\n ? ServerIcon\n : leaf.startsWith(\"rig_\")\n ? ServerCogIcon\n : leaf.startsWith(\"scheduled_\")\n ? CalendarClockIcon\n : leaf.startsWith(\"artifacts_\")\n ? PanelsTopLeftIcon\n : leaf.startsWith(\"social_\")\n ? Share2Icon\n : leaf.startsWith(\"slack_\")\n ? MessageSquareIcon\n : leaf.startsWith(\"github_\")\n ? FolderGitIcon\n : leaf.startsWith(\"variable_\")\n ? BoxIcon\n : leaf.startsWith(\"environment_\")\n ? KeyRoundIcon\n : leaf.includes(\"document\") ||\n leaf.includes(\"knowledge\") ||\n leaf === \"list_document_bases\"\n ? FileSearchIcon\n : leaf === \"tool_search\"\n ? PackageSearchIcon\n : leaf === \"load_skill\"\n ? PlugIcon\n : WrenchIcon;\n return <Icon className={ICON_SIZE} />;\n}\n\n/* ---- the default registry -------------------------------------------------- */\n\nconst BASE_ENTRIES: ToolRegistryEntry[] = [\n // Provider-native items carry `raw.type` on the wire — this is their source of\n // truth and is consulted first by the registry.\n { match: \"rawType\", type: \"apply_patch_call\", render: ApplyPatchRenderer },\n { match: \"rawType\", type: \"computer_call\", render: ComputerCallRenderer },\n { match: \"rawType\", type: \"tool_search_call\", render: ToolSearchRenderer },\n // First-party sandbox + MCP tools resolve by name (exact or MCP leaf).\n { match: \"name\", name: \"exec_command\", render: ExecRenderer },\n { match: \"name\", name: \"request_human_input\", render: AskRenderer },\n { match: \"name\", name: \"run_on\", render: RunOnRenderer },\n { match: \"name\", name: \"write_stdin\", render: WriteStdinRenderer },\n { match: \"name\", name: \"apply_patch_call\", render: ApplyPatchRenderer },\n { match: \"name\", name: \"apply_patch\", render: ApplyPatchRenderer },\n { match: \"name\", name: \"computer_call\", render: ComputerCallRenderer },\n // Function-mode computer tools (codex / chat-wire transports).\n { match: \"name\", name: \"computer_screenshot\", render: ComputerCallRenderer },\n { match: \"name\", name: \"computer_click\", render: ComputerCallRenderer },\n { match: \"name\", name: \"computer_double_click\", render: ComputerCallRenderer },\n { match: \"name\", name: \"computer_move\", render: ComputerCallRenderer },\n { match: \"name\", name: \"computer_scroll\", render: ComputerCallRenderer },\n { match: \"name\", name: \"computer_type\", render: ComputerCallRenderer },\n { match: \"name\", name: \"computer_keypress\", render: ComputerCallRenderer },\n { match: \"name\", name: \"computer_drag\", render: ComputerCallRenderer },\n { match: \"name\", name: \"web_search_call\", render: WebSearchRenderer },\n { match: \"name\", name: \"image_generation_call\", render: GeneratedImageRenderer },\n { match: \"name\", name: \"generate_image\", render: GeneratedImageRenderer },\n { match: \"name\", name: \"generate_video\", render: GeneratedVideoRenderer },\n { match: \"name\", name: \"tool_search\", render: ToolSearchRenderer },\n { match: \"name\", name: \"view_image\", render: ViewImageRenderer },\n { match: \"name\", name: \"sandbox_file_publish\", render: SandboxFilePublishRenderer },\n { match: \"name\", name: \"environment_set_variable\", render: SecretSetRenderer },\n { match: \"name\", name: \"variable_set_set_variable\", render: SecretSetRenderer },\n { match: \"name\", name: \"search_documents\", render: DocsSearchRenderer },\n { match: \"name\", name: \"knowledge_search\", render: DocsSearchRenderer },\n { match: \"name\", name: \"memory_propose\", render: MemoryProposeRenderer },\n { match: \"name\", name: \"set_session_title\", render: SetSessionTitleRenderer },\n { match: \"name\", name: \"set_other_session_title\", render: SetSessionTitleRenderer },\n];\n\n/** The built-in tool renderer registry: every first-party tool plus a fallback. */\nexport const defaultToolRegistry: ToolRegistry = createToolRegistry(BASE_ENTRIES, GenericRenderer);\n\n/** Build a registry that extends the built-ins with consumer entries/fallback. */\nexport function createDefaultToolRegistry(\n options: Parameters<typeof createToolRegistry>[2] = {},\n): ToolRegistry {\n return createToolRegistry(BASE_ENTRIES, GenericRenderer, options);\n}\n","import { createContext, useContext } from \"react\";\n\n/* ----------------------------------------------------------------------------\n Session compute label\n\n Optional host-supplied display name for the session's active compute target\n (e.g. \"Cloud sandbox\" or a Connected Machine name). Used by exec_command\n collapsed previews. The host owns resolution; this package never calls the\n machines API.\n -------------------------------------------------------------------------- */\n\nconst TimelineComputeLabelContext = createContext<string | null>(null);\n\nexport const TimelineComputeLabelProvider = TimelineComputeLabelContext.Provider;\n\nexport function useTimelineComputeLabel(): string | null {\n return useContext(TimelineComputeLabelContext);\n}\n","import type { GitFileDiff } from \"@opengeni/sdk\";\nimport { useState } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { useThemeType } from \"../lib/use-theme-type\";\nimport { PierreDiff } from \"../components/pierre-diff\";\n\n/* ----------------------------------------------------------------------------\n Tool diff\n\n Renders parsed `GitFileDiff[]` (from the V4A apply_patch parser) through the\n EXACT same diff stack the Files/Changes tabs use: `PierreDiff` (Shiki-\n highlighted), with a built-in plain-text degrade for a host without\n `@pierre/diffs` — one renderer, a single data contract. A per-block\n Unified/Split toggle sits in the header.\n -------------------------------------------------------------------------- */\n\nexport function ToolDiff({ files }: { files: GitFileDiff[] }) {\n const [layout, setLayout] = useState<\"unified\" | \"split\">(\"unified\");\n // Resolve the host theme (auto-detect via `data-og-theme`) with the SAME hook\n // the Files tab uses, then thread it into Pierre. Without it Pierre falls back\n // to its hard dark default and renders a github-dark slab inside a light page.\n const themeType = useThemeType(undefined);\n return (\n <div className=\"min-w-0\">\n <div className=\"mb-1.5 flex justify-end\">\n <LayoutToggle layout={layout} onChange={setLayout} />\n </div>\n <PierreDiff diff={files} layout={layout} themeType={themeType} />\n </div>\n );\n}\n\nfunction LayoutToggle({\n layout,\n onChange,\n}: {\n layout: \"unified\" | \"split\";\n onChange: (next: \"unified\" | \"split\") => void;\n}) {\n return (\n <div className=\"inline-flex items-center gap-px rounded-og-xs border border-og-border p-px\">\n {([\"unified\", \"split\"] as const).map((value) => (\n <button\n key={value}\n type=\"button\"\n onClick={() => onChange(value)}\n className={cn(\n \"rounded-og-xs px-2 py-[3px] text-og-xs font-medium capitalize transition-colors\",\n layout === value\n ? \"bg-og-surface-2 text-og-fg\"\n : \"text-og-fg-subtle hover:text-og-fg-muted\",\n )}\n >\n {value}\n </button>\n ))}\n </div>\n );\n}\n\n/** Raw-patch fallback for a V4A hunk string the parser could not structure. */\nexport function RawPatch({ diff }: { diff: string }) {\n const occurrences = new Map<string, number>();\n const lines = diff.split(\"\\n\").map((line) => {\n const occurrence = (occurrences.get(line) ?? 0) + 1;\n occurrences.set(line, occurrence);\n return { key: `${line}\\u0000${occurrence}`, line };\n });\n return (\n <div className=\"min-w-0\">\n <p className=\"mb-1 text-og-xs font-medium uppercase tracking-[0.08em] text-og-fg-subtle\">\n raw patch (could not parse hunks)\n </p>\n <pre className=\"max-h-72 overflow-auto border-l-2 border-og-border pl-3 font-og-mono text-og-xs leading-5\">\n {lines.map(({ key, line }) => (\n <span\n key={key}\n className={cn(\n \"block\",\n line.startsWith(\"@@\")\n ? \"text-og-accent\"\n : line.startsWith(\"+\")\n ? \"text-og-status-idle\"\n : line.startsWith(\"-\")\n ? \"text-og-status-failed\"\n : \"text-og-fg-muted\",\n )}\n >\n {line || \" \"}\n </span>\n ))}\n </pre>\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\n\n/* ----------------------------------------------------------------------------\n useThemeType\n\n Resolve the effective dark/light theme for surfaces (the Pierre/Shiki diff)\n that render outside the reach of host CSS — they need the theme as a value,\n not a cascade. An explicit prop always wins; otherwise read the host's\n `data-og-theme` attribute (set on `<html>` or any ancestor by the same opt-in\n the tokens use) and default to dark, the first-class theme. A MutationObserver\n keeps it live across runtime theme flips.\n\n One detector, shared by every diff surface (the Files tab and the timeline),\n so the two can never drift onto different themes.\n -------------------------------------------------------------------------- */\n\n/**\n * Resolve the diff theme. An explicit `forced` value wins; otherwise auto-detect\n * from the host `data-og-theme` (defaulting to dark) and track live flips.\n */\nexport function useThemeType(forced: \"dark\" | \"light\" | undefined): \"dark\" | \"light\" {\n const [detected, setDetected] = useState<\"dark\" | \"light\">(\"dark\");\n useEffect(() => {\n if (forced || typeof document === \"undefined\") return;\n const read = () => {\n const el = document.querySelector(\"[data-og-theme]\");\n const value = el?.getAttribute(\"data-og-theme\");\n setDetected(value === \"light\" ? \"light\" : \"dark\");\n };\n read();\n const observer = new MutationObserver(read);\n observer.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [\"data-og-theme\"],\n subtree: true,\n });\n return () => observer.disconnect();\n }, [forced]);\n return forced ?? detected;\n}\n","import { ArrowRightIcon, BotIcon, BrainCircuitIcon } from \"lucide-react\";\nimport { lazy, Suspense, useLayoutEffect, useRef } from \"react\";\nimport { jsx as rowJsx, jsxs as rowJsxs } from \"react/jsx-runtime\";\nimport { Markdown } from \"../components/markdown\";\nimport { cn } from \"../lib/cn\";\nimport { truncate } from \"../lib/format\";\nimport { defaultToolRegistry } from \"./tool-renderers\";\nimport { useEntranceAnimation, useEntranceAnimationLive } from \"./entrance\";\nimport type { RetainedArtifactLoader, RetainedScreenshotLoader, ToolRegistry } from \"./registry\";\nimport { useSeenActivityIds } from \"./seen-activity-ids\";\nimport { BodyNote, PayloadBlock, ActivityDisclosure, ToolCallTruncationProvider } from \"./shared\";\nimport { toolDisplayName } from \"./tool-display-name\";\nimport type { ActivityItem, MemoryItem, WorkerItem } from \"./types\";\n\nconst LazyFleetDecisionRow = lazy(() => import(\"./fleet-decision-row\"));\nconst LazyPlatformActivityRow = lazy(() => import(\"./platform-activity-row\"));\n\n/* ----------------------------------------------------------------------------\n Activity rail\n\n Renders a run of clustered activity items (reasoning, tool calls, workers,\n sandbox ops) as the left-bordered column between chat messages. Tool calls\n resolve through the renderer registry; everything else has a first-class row.\n\n Shared by `MessageTimeline` and the component demo so both draw the exact\n same rail — no divergence.\n -------------------------------------------------------------------------- */\n\nexport type ActivityRailProps = {\n items: ActivityItem[];\n /** Renderer registry for tool calls. Defaults to {@link defaultToolRegistry}. */\n toolRegistry?: ToolRegistry | undefined;\n /** Drill into a spawned worker session. */\n onOpenSession?: ((sessionId: string) => void) | undefined;\n /**\n * Deep-link a memory row to its record in the host's memory pane. Opt-in: the\n * library draws no \"View in memory\" affordance without a handler (the memory\n * row is then non-interactive rich content). See {@link MessageTimelineProps}.\n */\n onMemoryClick?: ((memoryId: string) => void) | undefined;\n loadRetainedScreenshot?: RetainedScreenshotLoader | undefined;\n /** Resolve permanent generated-image receipts through the authenticated host SDK. */\n loadRetainedArtifact?: RetainedArtifactLoader | undefined;\n /** Drop the left rule + indent (used inside a folded turn summary). */\n bare?: boolean | undefined;\n className?: string | undefined;\n};\n\n/**\n * The \"family\" a row belongs to, for light intra-rail grouping. Consecutive\n * rows of the same family sit tight; a family change gets a little extra top\n * margin so a long run reads as clusters rather than one undifferentiated wall.\n */\nfunction familyOf(item: ActivityItem): string {\n if (item.kind === \"tool-call\") {\n return item.name === \"exec_command\" || item.name === \"write_stdin\" ? \"terminal\" : item.name;\n }\n return item.kind;\n}\n\nexport function ActivityRail({\n items,\n toolRegistry = defaultToolRegistry,\n onOpenSession,\n onMemoryClick,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n bare,\n className,\n}: ActivityRailProps) {\n const enterMounted = useEntranceAnimation();\n // Live gate: rails born during bulk capture enter=false forever; with a\n // seen-id map we still want later live appends to fade (ids gate remounts).\n const enterLive = useEntranceAnimationLive();\n const seenIds = useSeenActivityIds();\n const enter = seenIds ? enterLive : enterMounted;\n const previousIdsRef = useRef<Set<string> | null>(null);\n const enteringIds = new Set<string>();\n if (enter) {\n for (const item of items) {\n if (seenIds) {\n if (!seenIds.has(item.id)) {\n enteringIds.add(item.id);\n }\n } else if (previousIdsRef.current !== null && !previousIdsRef.current.has(item.id)) {\n // Standalone ActivityRail (tests / demo): append-only, no remount map.\n enteringIds.add(item.id);\n }\n }\n }\n useLayoutEffect(() => {\n previousIdsRef.current = new Set(items.map((item) => item.id));\n if (seenIds) {\n for (const item of items) {\n seenIds.add(item.id);\n }\n }\n });\n return (\n <div\n className={cn(\n // Rows sit TIGHT by default (gap-0.5) so a same-family run reads as one\n // calm cluster; a family change opens real breathing room (mt-3) below,\n // so a long rail reads as a few clusters, not a metronome of rows.\n \"flex flex-col gap-0.5\",\n !bare && \"border-l-2 border-og-border pl-3 sm:pl-4\",\n // Whole-rail enter: standalone rails only (no seen-id map). Inside\n // MessageTimeline, unknown ids take per-row enter — remounts stay quiet.\n !bare && enter && !seenIds && previousIdsRef.current === null && \"animate-og-enter\",\n className,\n )}\n >\n {items.map((item, index) => {\n const newFamily = index > 0 && familyOf(item) !== familyOf(items[index - 1]!);\n const row = renderActivity(\n item,\n toolRegistry,\n onOpenSession,\n onMemoryClick,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n );\n return (\n <div\n key={item.id}\n data-og-timeline-row-anchor=\"\"\n data-og-item={item.id}\n data-og-annotation-source-key={\n item.kind === \"tool-call\" ? item.annotationSource?.eventId : undefined\n }\n className={cn(newFamily && \"mt-3\", enteringIds.has(item.id) && \"animate-og-row-enter\")}\n >\n {row}\n </div>\n );\n })}\n </div>\n );\n}\n\n/** A never-reachable guard: adding an `ActivityItem` kind is now a compile error. */\nfunction assertNever(item: never): never {\n throw new Error(`ActivityRail: unhandled activity item ${JSON.stringify(item)}`);\n}\n\nfunction renderActivity(\n item: ActivityItem,\n toolRegistry: ToolRegistry,\n onOpenSession: ((sessionId: string) => void) | undefined,\n onMemoryClick: ((memoryId: string) => void) | undefined,\n loadRetainedScreenshot: RetainedScreenshotLoader | undefined,\n loadRetainedArtifact: RetainedArtifactLoader | undefined,\n) {\n switch (item.kind) {\n case \"reasoning\":\n case \"sandbox\":\n case \"startup-phase\":\n return (\n <Suspense fallback={null}>\n <LazyPlatformActivityRow\n item={item}\n d={ActivityDisclosure}\n p={PayloadBlock}\n t={toolDisplayName}\n b={BotIcon}\n m={Markdown}\n r={truncate}\n j={rowJsx}\n s={rowJsxs}\n />\n </Suspense>\n );\n case \"tool-call\": {\n const Renderer = toolRegistry.resolve(item);\n return (\n <ToolCallTruncationProvider value={item.truncation ?? null}>\n <Renderer\n item={item}\n loadRetainedScreenshot={loadRetainedScreenshot}\n loadRetainedArtifact={loadRetainedArtifact}\n />\n </ToolCallTruncationProvider>\n );\n }\n case \"worker\":\n return <WorkerRow item={item} onOpenSession={onOpenSession} />;\n case \"memory\":\n return <MemoryRow item={item} onMemoryClick={onMemoryClick} />;\n case \"fleet-decision\":\n return (\n <Suspense fallback={null}>\n <LazyFleetDecisionRow\n item={item}\n d={ActivityDisclosure}\n b={BodyNote}\n j={rowJsx}\n s={rowJsxs}\n />\n </Suspense>\n );\n default:\n return assertNever(item);\n }\n}\n\n/**\n * Human labels for the memory kinds, translated at the SDK boundary so a raw\n * enum slug never renders as UI. Kept local to the library (the app has its own\n * `KIND_LABEL`); an unknown kind simply omits the chip rather than showing a slug.\n */\nconst MEMORY_KIND_LABEL: Record<string, string> = {\n preference: \"Preference\",\n semantic: \"Fact\",\n procedural: \"Procedure\",\n decision: \"Decision\",\n episodic: \"History\",\n};\n\n/**\n * A memory write the agent made mid-turn. A calm, NEUTRAL step (a successful save\n * is ordinary progress, never an exceptional state, so no accent/color): a brain-\n * circuit glyph, \"Saved to memory\" / \"Updated memory\", a human kind chip, and the\n * memory text. Expanding reveals the full text; a supersede shows the old text\n * struck through above the new one. When the host opts in with `onMemoryClick`,\n * a quiet \"View in memory\" affordance deep-links to the LIVE record.\n */\nfunction MemoryRow({\n item,\n onMemoryClick,\n}: {\n item: MemoryItem;\n onMemoryClick?: ((memoryId: string) => void) | undefined;\n}) {\n const corrected = item.variant === \"corrected\";\n const kindLabel = MEMORY_KIND_LABEL[item.memoryKind];\n // A supersede carries both the old text (`preview`) and the new (`replacementPreview`);\n // an in-place update / archive carries only `preview`.\n const superseded = corrected && Boolean(item.replacementPreview);\n // Link to the LIVE record: a supersede's replacement when present, else the memory itself.\n const targetId = corrected ? (item.replacementMemoryId ?? item.memoryId) : item.memoryId;\n const deepLink = Boolean(onMemoryClick);\n return (\n <ActivityDisclosure\n icon={<BrainCircuitIcon className=\"size-3.5\" />}\n iconTone=\"muted\"\n title={\n <span className=\"inline-flex min-w-0 items-center gap-2\">\n <span className=\"shrink-0\">{corrected ? \"Updated memory\" : \"Saved to memory\"}</span>\n {kindLabel ? (\n <span className=\"shrink-0 rounded-og-xs bg-og-surface-2 px-1.5 py-px text-og-xs font-normal leading-tight text-og-fg-subtle\">\n {kindLabel}\n </span>\n ) : null}\n </span>\n }\n preview={superseded ? item.replacementPreview : item.preview}\n >\n {superseded ? (\n // The correction as a before → after: the old memory struck through and\n // dimmed, the new text in the ordinary body weight below it.\n <div className=\"flex flex-col gap-1.5\">\n <p className=\"whitespace-pre-wrap text-og-sm leading-6 text-og-fg-subtle line-through\">\n {item.preview}\n </p>\n <p className=\"whitespace-pre-wrap text-og-base leading-6 text-og-fg-muted\">\n {item.replacementPreview}\n </p>\n </div>\n ) : corrected && item.action === \"updated\" ? (\n // Edited in place, no replacement record: the memory is still live, so\n // show its current text — NOT the archived treatment.\n <>\n <p className=\"whitespace-pre-wrap text-og-base leading-6 text-og-fg-muted\">\n {item.preview}\n </p>\n <BodyNote tone=\"muted\">Updated in place.</BodyNote>\n </>\n ) : corrected ? (\n // A correction with no replacement (and not an in-place update) archived the record.\n <BodyNote tone=\"muted\">Archived.</BodyNote>\n ) : (\n <p className=\"whitespace-pre-wrap text-og-base leading-6 text-og-fg-muted\">\n {item.preview}\n </p>\n )}\n {item.deduped ? <BodyNote tone=\"muted\">Merged into an existing memory.</BodyNote> : null}\n {deepLink ? (\n <button\n type=\"button\"\n onClick={() => onMemoryClick?.(targetId)}\n className={cn(\n \"group/memlink -mx-1 inline-flex w-fit items-center gap-1 rounded-og-sm px-1 py-0.5 text-left text-og-sm text-og-fg-subtle\",\n \"outline-hidden transition-colors duration-150 hover:text-og-fg focus-visible:ring-2 focus-visible:ring-og-accent\",\n )}\n >\n View in memory\n <ArrowRightIcon className=\"size-3.5 transition-transform duration-150 group-hover/memlink:translate-x-0.5\" />\n </button>\n ) : null}\n </ActivityDisclosure>\n );\n}\n\n/** Spawned/messaged worker sessions get a first-class card, not a tool row. */\nfunction WorkerRow({\n item,\n onOpenSession,\n}: {\n item: WorkerItem;\n onOpenSession?: ((sessionId: string) => void) | undefined;\n}) {\n const running = item.status === \"running\";\n const failed = item.status === \"failed\";\n const cancelled = item.status === \"cancelled\";\n const title =\n item.action === \"spawn\"\n ? running\n ? \"Spawning worker\"\n : failed\n ? \"Worker spawn failed\"\n : cancelled\n ? \"Worker interrupted\"\n : \"Worker spawned\"\n : running\n ? \"Messaging worker\"\n : failed\n ? \"Worker message failed\"\n : cancelled\n ? \"Worker interrupted\"\n : \"Worker messaged\";\n // A worker is a first-class actor but still a STEP on the rail — a borderless\n // row (no card), aligned to its sibling tool rows: the chevron column is an\n // empty spacer (a worker doesn't expand), then the bot glyph, then the title\n // with a quiet prompt beneath, and one right-gutter affordance.\n //\n // Once the worker's session id is known, the WHOLE row is a clean, clickable\n // deep-link into that child session (a trailing arrow brightens on hover) —\n // the spawn moment itself is the affordance, not a small side button. A\n // still-in-flight spawn (no id yet) or a failed/cancelled worker is inert, so\n // there is never a dead click target. The gutter mirrors the worker-completion\n // card's calm language: red chip on failure, \"interrupted\" on cancel.\n const sessionId = item.workerSessionId;\n const deepLink = Boolean(sessionId) && Boolean(onOpenSession) && !failed && !cancelled;\n const inner = (\n <>\n <span className=\"size-3.5 shrink-0\" aria-hidden />\n <span className={cn(\"mt-px shrink-0\", failed ? \"text-og-status-failed\" : \"text-og-accent\")}>\n <BotIcon className=\"size-3.5\" />\n </span>\n <div className=\"min-w-0 flex-1\">\n {/* In-flight state is carried ONLY by the shimmering title (no detached\n pulse badge), matching every other running row in the rail. */}\n <span\n className={cn(\n \"text-og-base font-medium\",\n running ? \"og-shimmer-text\" : failed ? \"text-og-status-failed\" : \"text-og-fg\",\n )}\n >\n {title}\n </span>\n {item.prompt ? (\n <p className=\"mt-0.5 truncate text-og-sm text-og-fg-muted\">\n {truncate(item.prompt, 140)}\n </p>\n ) : null}\n {failed && item.failure ? (\n <div className=\"mt-1 min-w-0 text-og-sm text-og-status-failed\">\n <p className=\"font-og-mono text-og-xs\">{item.failure.code}</p>\n <p className=\"mt-0.5 break-words\">{item.failure.message}</p>\n </div>\n ) : null}\n </div>\n {failed ? (\n <span className=\"inline-flex shrink-0 self-center items-center gap-1.5 font-og-mono text-og-xs leading-none text-og-status-failed\">\n <span className=\"size-1.5 rounded-full bg-og-status-failed\" />\n failed\n </span>\n ) : cancelled ? (\n <span className=\"og-cancelled-chip shrink-0 self-center font-og-mono text-og-xs leading-none text-og-fg-subtle\">\n interrupted\n </span>\n ) : deepLink ? (\n <ArrowRightIcon\n aria-hidden\n className=\"mt-0.5 size-3.5 shrink-0 text-og-fg-subtle transition-[transform,color] duration-150 group-hover/worker:translate-x-0.5 group-hover/worker:text-og-fg\"\n />\n ) : null}\n </>\n );\n\n if (deepLink && sessionId && onOpenSession) {\n return (\n <button\n type=\"button\"\n onClick={() => onOpenSession(sessionId)}\n className={cn(\n \"group/worker -mx-1.5 flex w-full items-start gap-2 rounded-og-sm px-1.5 py-1.5 text-left\",\n \"outline-hidden transition-colors duration-150 hover:bg-og-surface-1 focus-visible:ring-2 focus-visible:ring-og-accent\",\n \"pointer-coarse:min-h-11 pointer-coarse:py-2.5\",\n )}\n >\n {inner}\n </button>\n );\n }\n return <div className=\"flex items-start gap-2 px-1.5 py-1.5\">{inner}</div>;\n}\n","import { createContext, useContext, useRef, type ReactNode } from \"react\";\n\n/* ----------------------------------------------------------------------------\n Entrance animation gating\n\n Bulk paints (the initial tail window, a prepended older window) must not run\n per-row entrance animations — hundreds of rows fading in at once reads as a\n full-timeline flash. Toggling `animation: none` on and off is NOT an option:\n removing the override restarts every animation, which is itself the flash.\n\n Instead each animated element decides ONCE, at its own mount, whether it was\n born in a bulk paint — and keeps that decision forever. Rows born in a bulk\n paint never animate; rows appended live animate exactly as before. Nothing\n is ever toggled on existing DOM, so nothing can replay.\n -------------------------------------------------------------------------- */\n\nconst EntranceAnimationContext = createContext(true);\nconst EntranceAnimationLiveContext = createContext(true);\n\n/**\n * Freeze the mount-time gate for this subtree while publishing a separate live\n * gate to activity rails that need later appends to animate after a bulk paint.\n * MessageTimeline mounts one provider per durable group, so existing groups do\n * not receive a context invalidation when a prepend toggles bulk mode and new\n * groups still capture the value from the commit that created them.\n */\nexport function EntranceAnimationProvider({\n value,\n liveValue = value,\n children,\n}: {\n value: boolean;\n liveValue?: boolean | undefined;\n children: ReactNode;\n}) {\n const mountedValue = useRef(value).current;\n return (\n <EntranceAnimationContext.Provider value={mountedValue}>\n <EntranceAnimationLiveContext.Provider value={liveValue}>\n {children}\n </EntranceAnimationLiveContext.Provider>\n </EntranceAnimationContext.Provider>\n );\n}\n\n/**\n * Live entrance gate from the nearest provider. Prefer\n * {@link useEntranceAnimation} for elements that must freeze the decision at\n * mount; use this when a stable parent (e.g. ActivityRail) needs to animate\n * later appends after a bulk window clears.\n */\nexport function useEntranceAnimationLive(): boolean {\n return useContext(EntranceAnimationLiveContext);\n}\n\n/**\n * Whether this element should wear the entrance animation. Captured at mount\n * from the nearest provider (true outside any provider) and stable for the\n * element's lifetime — see the module doctrine above.\n */\nexport function useEntranceAnimation(): boolean {\n const enabled = useContext(EntranceAnimationContext);\n const captured = useRef(enabled);\n return captured.current;\n}\n","import { createContext, useContext } from \"react\";\n\n/* ----------------------------------------------------------------------------\n Seen activity ids\n\n ActivityRails remount across fold wraps / settle key flips. A per-rail\n previousIds set resets on remount, so either every row re-fades (flash) or\n the first live tool never animates (pop). This map lives on MessageTimeline\n and records every activity id that has already painted — live appends of\n unknown ids earn row-enter; remounts of known ids stay quiet.\n -------------------------------------------------------------------------- */\n\nconst SeenActivityIdsContext = createContext<Set<string> | null>(null);\n\nexport const SeenActivityIdsProvider = SeenActivityIdsContext.Provider;\n\nexport function useSeenActivityIds(): Set<string> | null {\n return useContext(SeenActivityIdsContext);\n}\n","import { ChevronRightIcon, CircleSlashIcon, TriangleAlertIcon } from \"lucide-react\";\nimport {\n Component,\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { Collapsible } from \"radix-ui\";\nimport { CopyButton } from \"../components/copy-button\";\nimport { cn } from \"../lib/cn\";\nimport { MOTION_INSPECT_SCALE } from \"../lib/motion-inspect\";\nimport { useForcedDefaultOpen } from \"./disclosure-context\";\nimport { useEntranceAnimation } from \"./entrance\";\nimport { useFoldMemory, type FoldRestingState } from \"./fold-memory\";\nimport {\n applyPatchOpsFromToolItem,\n isApplyPatch,\n mediaPreviewFact,\n screenshotDataUrl,\n} from \"./parsers\";\nimport { rawTypeOf } from \"./registry\";\nimport type { ActivityItem, ToolCallItem, TurnOutcome } from \"./types\";\nexport type { TurnOutcome } from \"./types\";\n\n/* ----------------------------------------------------------------------------\n Turn summary\n\n A completed (or failed/cancelled) turn folds behind one quiet summary chip:\n \"N steps · M files · K commands · 1 screenshot · 4m\". The chip is the default\n surface; expanding it reveals the full settled turn body. Top-level live\n activity keeps the same open shell so settling never remounts the rail into\n a brand-new wrapper (that remount was the hard yank).\n\n This keeps the timeline calm: a finished turn is a single line until the\n reader chooses to look inside it.\n -------------------------------------------------------------------------- */\n\nconst TurnSettleChromeContext = createContext(false);\n\n/**\n * True while settle chrome is active (open beat, slow collapse, or the short\n * cancel-close latch). Nested cluster chips stay mounted and forced OPEN for\n * this window so the body keeps a stable height — never flat-map to bare\n * rails, and never remount closed nested chips mid-collapse (that yanked).\n */\nexport function useTurnSettleOpen(): boolean {\n return useContext(TurnSettleChromeContext);\n}\n\nexport const BUILT_IN_TURN_SUMMARY_FACET_IDS = [\n \"steps\",\n \"files\",\n \"commands\",\n \"screenshots\",\n \"memories\",\n \"compacted\",\n \"duration\",\n] as const;\n\nexport type BuiltInTurnSummaryFacetId = (typeof BUILT_IN_TURN_SUMMARY_FACET_IDS)[number];\n\nexport type TurnSummaryContext = Readonly<{\n /** Every normalized activity item folded into this summary. */\n items: readonly ActivityItem[];\n /** Tool calls from `items`, retained in timeline order for convenient aggregation. */\n toolCalls: readonly ToolCallItem[];\n /** The settled turn verdict, or absent for a neutral/incomplete cluster. */\n outcome: TurnOutcome | undefined;\n /** The bounded failure reason rendered by the enclosing summary, when present. */\n failureText: string | undefined;\n /** Total turn duration when the enclosing group has both valid timestamps. */\n durationMs: number | undefined;\n /** False when any projected activity is still running or streaming. */\n settled: boolean;\n /**\n * Adjacent compaction landmarks next to this fold. Landmark remains the\n * primary UI; this is a secondary chip signal only.\n */\n contextCompactionCount: number;\n}>;\n\nexport type TurnSummaryFacetResult = Readonly<{\n icon?: ReactNode;\n content: ReactNode;\n ariaLabel?: string;\n title?: string;\n}>;\n\nexport type TurnSummaryFacet = Readonly<{\n /** Stable identity used for removal and deterministic de-duplication. */\n id: string;\n /** Return null when this facet has nothing useful to show. */\n summarize(context: TurnSummaryContext): TurnSummaryFacetResult | null;\n}>;\n\ntype ModifyTurnSummaryFacets = Readonly<{\n /** Appended after the remaining built-ins, in supplied order. */\n add?: readonly TurnSummaryFacet[];\n /** Built-ins to omit before custom facets are appended. */\n remove?: readonly BuiltInTurnSummaryFacetId[];\n replace?: never;\n}>;\n\ntype ReplaceTurnSummaryFacets = Readonly<{\n /** The complete ordered facet list. Mutually exclusive with add/remove. */\n replace: readonly TurnSummaryFacet[];\n add?: never;\n remove?: never;\n}>;\n\nexport type TurnSummaryFacetConfiguration = ModifyTurnSummaryFacets | ReplaceTurnSummaryFacets;\n\nexport type TurnSummaryOptions = Readonly<{\n facets?: TurnSummaryFacetConfiguration;\n}>;\n\nexport type TurnSummaryProps = {\n /** The activity items in the turn (used only to compute the facet counts). */\n items: ActivityItem[];\n /**\n * The settled verdict — or absent for a completed CLUSTER of a still-running\n * turn, which folds neutrally: no verdict glyph (the turn has none yet), a\n * quiet pulse dot in its place so alignment and the running feel both hold.\n */\n outcome?: TurnOutcome | undefined;\n /** A short failure reason shown inline on a failed chip (never hidden). */\n failureText?: string | undefined;\n /** Elapsed turn duration; shown as a trailing facet when at least 1s. */\n durationMs?: number | undefined;\n /** Start expanded. */\n defaultOpen?: boolean | undefined;\n /**\n * A nested fold — a cluster or sub-turn INSIDE an already-expanded turn. It\n * drops the bordered/filled chip and renders as a plain disclosure node on the\n * parent's rail (chevron + glyph + facets), so expanding a turn reveals a thread\n * of nodes, never a stack of boxes-in-boxes. The top-level fold stays a chip.\n */\n bare?: boolean | undefined;\n /** Per-instance facet customization. Omit to preserve the built-in summary exactly. */\n facets?: TurnSummaryFacetConfiguration | undefined;\n /**\n * Settle choreography: this fold replaced rows the reader was just watching\n * live. Instead of yanking them behind a chip in one frame, the fold mounts\n * OPEN with the summary chip easing in above the still-visible rows, holds a\n * short beat so the reader registers the settle, then glides closed. Any\n * user interaction during the beat cancels the auto-collapse. Captured at\n * mount; ignored when the fold starts expanded (e.g. a failed turn).\n */\n settleFold?: boolean | undefined;\n /**\n * Durable identity (timeline group id) for cross-remount fold memory. When\n * an ancestor provides a {@link FoldMemoryProvider} map, reaching a resting\n * state is recorded under this key: \"closed\" when the settle choreography\n * completes its collapse or the reader closes the chip, \"open\" when the\n * reader expands it. A later remount under the same key restores that\n * resting state and never replays the open settle beat — the activity→turn\n * wrap and the nested force-open during settle chrome must not re-expand a\n * fold that already settled closed.\n */\n foldKey?: string | undefined;\n /**\n * When set, a hover/focus copy control sits on the chip row (outside the\n * disclosure trigger) so the reader can copy the turn's assistant prose\n * without toggling the fold.\n */\n copyText?: string | undefined;\n /** Adjacent compaction landmark count for the secondary chip facet. */\n contextCompactionCount?: number | undefined;\n /** The rendered activity rail revealed on expand. */\n children: ReactNode;\n};\n\n/** How long a settling fold stays open before gliding closed. */\nconst SETTLE_FOLD_BEAT_MS = 1100 * MOTION_INSPECT_SCALE;\n/** Keep in sync with `--og-duration-disclose-settle`. */\nconst SETTLE_COLLAPSE_MS = 820 * MOTION_INSPECT_SCALE;\n/** Keep in sync with `--og-duration-disclose` (manual / cancel-close). */\nconst DISCLOSE_MS = 120 * MOTION_INSPECT_SCALE;\n\nexport function TurnSummary({\n items,\n outcome,\n failureText,\n durationMs,\n defaultOpen,\n bare,\n facets: facetConfiguration,\n settleFold,\n foldKey,\n copyText,\n contextCompactionCount,\n children,\n}: TurnSummaryProps) {\n // An explicit `defaultOpen` always wins; otherwise an ancestor may seed it\n // (screenshot instrumentation); otherwise the turn starts folded.\n const forcedDefaultOpen = useForcedDefaultOpen();\n const foldMemory = useFoldMemory();\n // A remembered resting state outranks author defaults: a fold that already\n // finished its settle collapse (or that the reader closed) mounts closed\n // even when a remount asks for the settle beat or a forced defaultOpen —\n // and one the reader expanded mounts open instead of snapping shut.\n const remembered = foldKey !== undefined ? foldMemory?.get(foldKey) : undefined;\n const restingOpen =\n remembered === \"closed\"\n ? false\n : remembered === \"open\"\n ? true\n : (defaultOpen ?? forcedDefaultOpen ?? false);\n const initialSettle = Boolean(settleFold) && !restingOpen && remembered === undefined;\n const [settling, setSettling] = useState(initialSettle);\n const [open, setOpen] = useState(initialSettle ? true : restingOpen);\n // While true, a close uses the slow settle collapse. Cleared after that\n // auto-collapse finishes (or on first user interaction) so later manual\n // closes are the fast disclose pair.\n const [settlePhase, setSettlePhase] = useState(initialSettle);\n // Separate from settlePhase CSS: keep nested chips force-open through\n // cancel-close (fast collapse) without forcing the slow settle-collapse.\n const [nestSuppressLatch, setNestSuppressLatch] = useState(initialSettle);\n // Expand animation must NOT run on the settle mount (rows were already\n // visible — a height sweep would flash them). Armed once we leave that\n // initial open, so a later manual reopen animates instead of snapping.\n const [expandReady, setExpandReady] = useState(!initialSettle);\n const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const settleCloseDoneRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const nestLatchClearRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n const settleFoldSeenRef = useRef(Boolean(settleFold));\n const settleArmedRef = useRef(false);\n const clearNestLatchTimer = () => {\n if (nestLatchClearRef.current !== null) {\n clearTimeout(nestLatchClearRef.current);\n nestLatchClearRef.current = null;\n }\n };\n const clearSettleTimers = () => {\n if (settleTimerRef.current !== null) {\n clearTimeout(settleTimerRef.current);\n settleTimerRef.current = null;\n }\n if (settleCloseDoneRef.current !== null) {\n clearTimeout(settleCloseDoneRef.current);\n settleCloseDoneRef.current = null;\n }\n clearNestLatchTimer();\n };\n const rememberResting = (state: FoldRestingState) => {\n if (foldKey !== undefined && foldMemory) {\n foldMemory.set(foldKey, state);\n }\n };\n const armSettleCollapse = () => {\n if (settleArmedRef.current) {\n return;\n }\n settleArmedRef.current = true;\n setSettling(true);\n setSettlePhase(true);\n setNestSuppressLatch(true);\n setExpandReady(false);\n setOpen(true);\n clearSettleTimers();\n settleTimerRef.current = setTimeout(() => {\n settleTimerRef.current = null;\n setExpandReady(true);\n setOpen(false);\n // The glide toward closed IS the choreography completing — record it\n // now, so a wrap that lands mid-collapse still remounts this fold shut.\n rememberResting(\"closed\");\n settleCloseDoneRef.current = setTimeout(() => {\n settleCloseDoneRef.current = null;\n settleArmedRef.current = false;\n setSettlePhase(false);\n setSettling(false);\n setNestSuppressLatch(false);\n }, SETTLE_COLLAPSE_MS);\n }, SETTLE_FOLD_BEAT_MS);\n };\n const mountSettleRef = useRef(initialSettle);\n // Mount-time settle (new turn wrap).\n // Mount-once settle arm + unmount timer cleanup — re-running on foldMemory\n // identity churn would restart the beat mid-choreography.\n useEffect(() => {\n if (mountSettleRef.current) {\n armSettleCollapse();\n }\n return () => {\n clearSettleTimers();\n settleArmedRef.current = false;\n };\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n // Live shell already open: settleFold rises later without remounting.\n // Do not require !restingOpen — live shells mount with defaultOpen and\n // only later receive settleFold. Failed turns mount with both at once\n // (seen=true), so they never take this edge.\n // Edge-trigger on settleFold only; foldMemory/foldKey are reopen guards.\n useEffect(() => {\n const was = settleFoldSeenRef.current;\n settleFoldSeenRef.current = Boolean(settleFold);\n if (!was && settleFold) {\n // A remembered resting state means this fold's story already resolved\n // once (choreography closed it, or the reader chose a state). Replaying\n // the open beat would re-expand it — the exact reopen this guards.\n if (foldKey !== undefined && foldMemory?.get(foldKey) !== undefined) {\n return;\n }\n armSettleCollapse();\n }\n // oxlint-disable-next-line react-hooks/exhaustive-deps\n }, [settleFold]);\n const onOpenChange = (next: boolean) => {\n // The reader took over — cancel the pending auto-collapse for good.\n // Clear settle CSS phase immediately (fast collapse) but keep nest latch\n // through the disclose window so nested chips stay force-open mid-close\n // (remounting them closed here yanks height).\n const wasNestFlat = settling || settlePhase || nestSuppressLatch;\n clearSettleTimers();\n settleArmedRef.current = false;\n rememberResting(next ? \"open\" : \"closed\");\n setExpandReady(true);\n setSettlePhase(false);\n setSettling(false);\n if (next) {\n setNestSuppressLatch(false);\n setOpen(true);\n return;\n }\n setOpen(false);\n if (wasNestFlat) {\n setNestSuppressLatch(true);\n nestLatchClearRef.current = setTimeout(() => {\n nestLatchClearRef.current = null;\n setNestSuppressLatch(false);\n }, DISCLOSE_MS);\n } else {\n setNestSuppressLatch(false);\n }\n };\n const enter = useEntranceAnimation();\n // Capture once: after a settle choreography the chip is already on screen.\n // Re-applying `animate-og-enter` when `settling` clears was the post-collapse\n // flash (opacity replay on the summary row).\n const [allowEnterAnimation] = useState(() =>\n Boolean(enter && !bare && !initialSettle && !restingOpen),\n );\n // Hold duration (and its \"· 8s\" insertion) until settle choreography finishes.\n // Surfacing it mid-beat or on the activity→turn remount made the chip text\n // reflow twice and read as another flash after the fold.\n const context = useMemo(\n () =>\n createTurnSummaryContext(\n items,\n outcome,\n failureText,\n settling || settlePhase ? undefined : durationMs,\n contextCompactionCount ?? 0,\n ),\n [items, outcome, failureText, durationMs, settling, settlePhase, contextCompactionCount],\n );\n const facetDefinitions = useMemo(\n () => resolveTurnSummaryFacets(facetConfiguration),\n [facetConfiguration],\n );\n const facets = useMemo(\n () =>\n facetDefinitions.flatMap((facet) => {\n try {\n const result = facet.summarize(context);\n return result && hasFacetContent(result.content) ? [{ facet, result }] : [];\n } catch {\n // A host extension is presentation-only. It must never take down the\n // durable timeline or hide the remaining built-in evidence.\n return [];\n }\n }),\n [context, facetDefinitions],\n );\n\n // Live open shell: keep the chip in-flow (so settle never inserts layout)\n // and quieter until there is an outcome or a settle beat — but still\n // clickable. `pointer-events-none` here trapped readers who expanded (or\n // who landed on the default-open live rail) with no way to collapse while\n // the turn was still running.\n const liveShell = outcome === undefined && open && !settlePhase && !bare;\n // Settle CSS phase OR cancel-close latch — see useTurnSettleOpen.\n // Nested chips stay force-open for this window (stable height).\n const settleChrome = settling || settlePhase || nestSuppressLatch;\n\n // Copy only on the collapsed chip — when open, per-message copy is enough\n // and a second control on the summary row felt crowded / off.\n const copyable = Boolean(\n copyText && copyText.trim().length > 0 && !bare && !liveShell && !open && !settlePhase,\n );\n\n return (\n <TurnSettleChromeContext.Provider value={settleChrome}>\n <div className={cn(copyable && \"group/copy relative\")}>\n <Collapsible.Root\n open={open}\n onOpenChange={onOpenChange}\n // History-only entrance. Never toggle this on after mount — see\n // allowEnterAnimation. Settle uses animate-og-settle-chip on the trigger.\n className={allowEnterAnimation && !liveShell ? \"animate-og-enter\" : undefined}\n >\n <Collapsible.Trigger\n className={cn(\n settling && \"animate-og-settle-chip\",\n // Top-level turn fold and (when used) nested cluster folds render as\n // FLAT rail rows — chevron + glyph + facets on the page background, no\n // border, no fill. Only a hover tint hints the row is expandable, so a\n // collapsed turn never reads as a boxed card. The top-level row is a\n // touch larger (base text, size-5 glyph, wider gap) so it still reads\n // as a turn landmark above any nested cluster rows it groups.\n \"group flex w-full items-center rounded-og-sm text-left transition-colors\",\n // A folded turn is a touch target on coarse pointers: grow the row so it\n // clears the 44px minimum without disturbing the calm desktop rhythm.\n \"pointer-coarse:min-h-11 pointer-coarse:py-2.5\",\n bare\n ? \"gap-2 px-1.5 py-1.5 text-og-sm text-og-fg-muted\"\n : \"-mx-2 gap-2.5 px-2 py-1.5 text-og-base text-og-fg-muted\",\n // A failed fold keeps its red accent (glyph + inline reason below) and a\n // faint red hover wash so attention still lands there; every other\n // outcome gets the neutral surface hover.\n outcome === \"failed\"\n ? \"hover:bg-og-status-failed/[0.06] hover:text-og-fg\"\n : \"hover:bg-og-surface-1 hover:text-og-fg\",\n liveShell && \"text-og-fg-subtle\",\n )}\n >\n {/* Disclosure grammar matches the rows: chevron leads (far left), then any\n exceptional or active state, then the facets — one expand affordance\n side everywhere. */}\n <ChevronRightIcon\n className={cn(\n \"size-3.5 shrink-0 text-og-fg-subtle transition-transform ease-og-in-out group-data-[state=open]:rotate-90\",\n settlePhase\n ? \"duration-[var(--_og-duration-disclose-settle)]\"\n : \"duration-[var(--_og-duration-disclose)]\",\n )}\n />\n {/* Completion is the quiet default and needs no repeated glyph. Failed,\n cancelled, and still-running folds retain a visible state marker. */}\n {outcome === \"complete\" ? null : (\n <span\n className={cn(\n \"inline-flex shrink-0 items-center justify-center\",\n bare ? \"size-3.5\" : \"size-5\",\n outcome === \"failed\" ? \"text-og-status-failed\" : \"text-og-fg-subtle\",\n )}\n >\n {outcome === \"failed\" ? (\n <TriangleAlertIcon className=\"size-3\" />\n ) : outcome === \"cancelled\" ? (\n <CircleSlashIcon className=\"size-3\" />\n ) : (\n <span className=\"size-1.5 animate-og-pulse rounded-full bg-og-fg-subtle\" />\n )}\n </span>\n )}\n <span\n className={cn(\"min-w-0 flex-1 truncate\", bare ? \"text-og-sm\" : \"text-og-fg-muted\")}\n >\n {facets.map(({ facet, result }, index) => (\n <FacetRenderBoundary key={facet.id}>\n <>\n {index > 0 ? \" · \" : null}\n <span aria-label={result.ariaLabel} title={result.title}>\n {result.icon ? (\n <span aria-hidden className=\"mr-1 inline-flex align-[-0.125em]\">\n {result.icon}\n </span>\n ) : null}\n {result.content}\n </span>\n </>\n </FacetRenderBoundary>\n ))}\n {outcome === \"failed\" && failureText ? (\n <span className=\"text-og-status-failed\"> · {failureText}</span>\n ) : null}\n {outcome === \"cancelled\" ? (\n <span className=\"text-og-fg-subtle\"> · interrupted</span>\n ) : null}\n </span>\n {/* The disclosure hint. Calm at rest on fine pointers (revealed on hover\n and keyboard focus), but always present on coarse pointers where there\n is no hover to lean on — so the fold never reads as a static status\n line. Purely visual: the trigger's aria-expanded already conveys state\n to assistive tech, so the hint is hidden from the accessible name. */}\n <span\n aria-hidden\n className={cn(\n \"ml-auto shrink-0 pl-2 text-og-xs text-og-fg-subtle transition-opacity duration-150\",\n // Leave a sliver so a collapsed-chip copy icon can sit outside.\n copyable ? \"pr-8\" : null,\n \"opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100\",\n \"pointer-coarse:opacity-100\",\n )}\n >\n {open ? \"hide steps\" : \"show steps\"}\n </span>\n </Collapsible.Trigger>\n <Collapsible.Content\n {...(nestSuppressLatch ? { forceMount: true as const } : {})}\n data-og-fold-content=\"\"\n className={cn(\n \"overflow-hidden\",\n expandReady && \"data-[state=open]:animate-og-expand\",\n // Auto-close: slow settle. Manual close (settlePhase cleared): fast.\n settlePhase\n ? \"data-[state=closed]:animate-og-settle-collapse\"\n : \"data-[state=closed]:animate-og-collapse\",\n )}\n >\n {/* A nested node indents its revealed rows under the glyph (thread nesting\n off the parent rail); the top-level turn body owns its own rail. */}\n <div className={bare ? \"pt-1 pl-5\" : \"pt-2\"}>{children}</div>\n </Collapsible.Content>\n </Collapsible.Root>\n {copyable ? (\n <div className=\"pointer-events-none absolute top-1.5 right-0 z-10\">\n <div className=\"pointer-events-auto\">\n <CopyButton text={copyText!} label=\"Copy turn\" reveal=\"group-hover\" />\n </div>\n </div>\n ) : null}\n </div>\n </TurnSettleChromeContext.Provider>\n );\n}\n\nfunction createTurnSummaryContext(\n items: ActivityItem[],\n outcome: TurnOutcome | undefined,\n failureText: string | undefined,\n durationMs: number | undefined,\n contextCompactionCount: number,\n): TurnSummaryContext {\n const itemSnapshot = Object.freeze([...items]);\n const toolCalls = Object.freeze(\n itemSnapshot.filter((item): item is ToolCallItem => item.kind === \"tool-call\"),\n );\n const settled = itemSnapshot.every((item) => {\n if (item.kind === \"reasoning\") {\n return !item.streaming;\n }\n if (\n item.kind === \"tool-call\" ||\n item.kind === \"worker\" ||\n item.kind === \"sandbox\" ||\n item.kind === \"startup-phase\"\n ) {\n return item.status !== \"running\";\n }\n return true;\n });\n return Object.freeze({\n items: itemSnapshot,\n toolCalls,\n outcome,\n failureText,\n durationMs,\n settled,\n contextCompactionCount: Math.max(0, Math.floor(contextCompactionCount)),\n });\n}\n\nconst BUILT_IN_TURN_SUMMARY_FACETS: readonly TurnSummaryFacet[] = Object.freeze([\n {\n id: \"steps\",\n summarize: ({ items }) => ({\n content: `${items.length} ${items.length === 1 ? \"step\" : \"steps\"}`,\n }),\n },\n {\n id: \"files\",\n summarize: ({ toolCalls }) => {\n let files = 0;\n for (const item of toolCalls) {\n if (isApplyPatch(item)) {\n files += applyPatchOpsFromToolItem(item).length;\n }\n }\n return files ? { content: `${files} ${files === 1 ? \"file\" : \"files\"} edited` } : null;\n },\n },\n {\n id: \"commands\",\n summarize: ({ toolCalls }) => {\n const commands = toolCalls.filter((item) => item.name === \"exec_command\").length;\n return commands\n ? { content: `${commands} ${commands === 1 ? \"command\" : \"commands\"}` }\n : null;\n },\n },\n {\n id: \"screenshots\",\n summarize: ({ toolCalls }) => {\n let screenshots = 0;\n for (const item of toolCalls) {\n if (\n (rawTypeOf(item) === \"computer_call\" ||\n item.name === \"computer_call\" ||\n item.name === \"computer_screenshot\") &&\n (screenshotDataUrl(item.output) !== null || mediaPreviewFact(item.output) !== null)\n ) {\n screenshots += 1;\n }\n }\n return screenshots\n ? {\n content: `${screenshots} ${screenshots === 1 ? \"screenshot\" : \"screenshots\"}`,\n }\n : null;\n },\n },\n {\n id: \"memories\",\n summarize: ({ items }) => {\n let saved = 0;\n let updated = 0;\n for (const item of items) {\n if (item.kind !== \"memory\") {\n continue;\n }\n if (item.variant === \"corrected\") {\n updated += 1;\n } else {\n saved += 1;\n }\n }\n const parts: string[] = [];\n if (saved) {\n parts.push(`${saved} ${saved === 1 ? \"memory\" : \"memories\"} saved`);\n }\n if (updated) {\n parts.push(`${updated} ${updated === 1 ? \"memory\" : \"memories\"} updated`);\n }\n return parts.length > 0 ? { content: parts.join(\" · \") } : null;\n },\n },\n {\n id: \"compacted\",\n summarize: ({ contextCompactionCount }) =>\n contextCompactionCount > 0\n ? {\n content:\n contextCompactionCount === 1 ? \"compacted\" : `${contextCompactionCount} compacts`,\n ariaLabel:\n contextCompactionCount === 1\n ? \"Conversation history compacted\"\n : `${contextCompactionCount} conversation history compactions`,\n }\n : null,\n },\n {\n id: \"duration\",\n summarize: ({ durationMs }) => {\n const duration = formatDurationFacet(durationMs);\n return duration ? { content: duration } : null;\n },\n },\n]);\n\nfunction resolveTurnSummaryFacets(\n configuration: TurnSummaryFacetConfiguration | undefined,\n): readonly TurnSummaryFacet[] {\n const requested: readonly TurnSummaryFacet[] = configuration?.replace ?? [\n ...BUILT_IN_TURN_SUMMARY_FACETS.filter(\n (facet) => !configuration?.remove?.includes(facet.id as BuiltInTurnSummaryFacetId),\n ),\n ...(configuration?.add ?? []),\n ];\n const seen = new Set<string>();\n return requested.filter((facet) => {\n if (!facet.id || seen.has(facet.id)) {\n return false;\n }\n seen.add(facet.id);\n return true;\n });\n}\n\nfunction hasFacetContent(content: ReactNode): boolean {\n return content !== null && content !== undefined && content !== false && content !== \"\";\n}\n\nclass FacetRenderBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {\n state = { failed: false };\n\n static getDerivedStateFromError(): { failed: boolean } {\n return { failed: true };\n }\n\n render(): ReactNode {\n return this.state.failed ? null : this.props.children;\n }\n}\n\nfunction formatDurationFacet(durationMs: number | undefined): string | null {\n if (durationMs === undefined || !Number.isFinite(durationMs) || durationMs < 1000) {\n return null;\n }\n const totalSeconds = Math.floor(durationMs / 1000);\n if (totalSeconds < 60) {\n return `${totalSeconds}s`;\n }\n const totalMinutes = Math.floor(totalSeconds / 60);\n if (totalMinutes < 60) {\n return `${totalMinutes}m`;\n }\n const hours = Math.floor(totalMinutes / 60);\n const minutes = totalMinutes % 60;\n return `${hours}h ${String(minutes).padStart(2, \"0\")}m`;\n}\n","import { createContext, useContext } from \"react\";\n\n/* ----------------------------------------------------------------------------\n Fold memory\n\n Remembers, per durable timeline group id, that a fold reached a RESTING\n state: \"closed\" when the settle choreography finished its collapse or the\n reader closed the chip by hand, \"open\" when the reader explicitly expanded\n it. The map lives OUTSIDE the component tree because the timeline\n deliberately remounts chips with fresh keys (the activity→turn wrap, the\n nested-chip key flip around settle chrome) — and a remount must never\n forget that the reader already watched this cluster fold. Re-opening an\n already-settled fold reads as the timeline undoing its own choreography.\n\n With no provider the hook returns null and every fold keeps its\n author-chosen default — standalone TurnSummary usage is unchanged.\n -------------------------------------------------------------------------- */\n\nexport type FoldRestingState = \"open\" | \"closed\";\n\nconst FoldMemoryContext = createContext<Map<string, FoldRestingState> | null>(null);\n\n/** Provide a per-timeline resting-state map (MessageTimeline owns one). */\nexport const FoldMemoryProvider = FoldMemoryContext.Provider;\n\n/** The ancestor fold-memory map, or null when none is mounted (inert). */\nexport function useFoldMemory(): Map<string, FoldRestingState> | null {\n return useContext(FoldMemoryContext);\n}\n\n/**\n * Single-cluster activity→turn wrap: copy the activity resting state onto the\n * new turn-* key. Those ids differ across the wrap; without this the turn\n * remounts settleFold and re-opens a chip the reader already watched collapse.\n *\n * Multi-cluster wraps deliberately do NOT inherit — the outer turn chip is new\n * and still takes one settle beat; nested clusters keep their own activity-*\n * memory so they stay closed under that beat.\n */\nexport function inheritFoldRestingState(\n memory: Map<string, FoldRestingState>,\n targetKey: string,\n sourceKeys: readonly string[],\n): void {\n if (memory.has(targetKey) || sourceKeys.length !== 1) {\n return;\n }\n const state = memory.get(sourceKeys[0]!);\n if (state !== undefined) {\n memory.set(targetKey, state);\n }\n}\n","import type { GeneratedVideoReceipt, VideoArtifactPlaybackSource } from \"@opengeni/sdk\";\nimport { useEffect, useState } from \"react\";\nimport { cn } from \"../lib/cn\";\nimport type { VideoArtifactPlaybackLoader } from \"../timeline\";\n\nexport type GeneratedVideoPlayerProps = {\n receipt: GeneratedVideoReceipt;\n loadPlaybackSource: VideoArtifactPlaybackLoader;\n className?: string | undefined;\n label?: string | undefined;\n};\n\ntype SourceState =\n | { kind: \"loading\" }\n | { kind: \"ready\"; source: VideoArtifactPlaybackSource }\n | { kind: \"error\"; message: string };\n\n/** Native, Range-based playback. Video bytes never pass through React or the SDK heap. */\nexport function GeneratedVideoPlayer({\n receipt,\n loadPlaybackSource,\n className,\n label = \"Generated video\",\n}: GeneratedVideoPlayerProps) {\n const [retry, setRetry] = useState(0);\n const [state, setState] = useState<SourceState>({ kind: \"loading\" });\n\n useEffect(() => {\n const controller = new AbortController();\n setState({ kind: \"loading\" });\n void loadPlaybackSource(receipt.artifact.artifactId, controller.signal).then(\n (source) => {\n if (!controller.signal.aborted) setState({ kind: \"ready\", source });\n },\n (error: unknown) => {\n if (controller.signal.aborted) return;\n setState({\n kind: \"error\",\n message: error instanceof Error ? error.message : \"Playback is unavailable.\",\n });\n },\n );\n return () => controller.abort();\n }, [loadPlaybackSource, receipt.artifact.artifactId, retry]);\n\n if (state.kind === \"loading\") {\n return (\n <div\n aria-label={`Loading ${label.toLowerCase()}`}\n className={cn(\n \"aspect-video w-full animate-pulse rounded-og-md bg-og-surface-2 motion-reduce:animate-none\",\n className,\n )}\n />\n );\n }\n if (state.kind === \"error\") {\n return (\n <div\n role=\"status\"\n className={cn(\n \"rounded-og-md border border-og-status-failed/30 bg-og-status-failed/5 px-3 py-2 text-og-sm text-og-status-failed\",\n className,\n )}\n >\n {state.message}\n </div>\n );\n }\n\n return (\n <video\n key={state.source.url}\n aria-label={label}\n className={cn(\n \"max-h-[32rem] w-full rounded-og-md bg-black object-contain shadow-sm\",\n className,\n )}\n controls\n playsInline\n preload=\"metadata\"\n src={state.source.url}\n onError={() => {\n if (retry === 0) setRetry(1);\n else setState({ kind: \"error\", message: \"Video playback failed.\" });\n }}\n />\n );\n}\n","import type { SessionStatus as SessionStatusValue } from \"@opengeni/sdk\";\nimport { cn } from \"../lib/cn\";\n\nexport type SessionStatusMeta = {\n label: string;\n /** Token-backed color classes for the dot and tinted badge. */\n dotClassName: string;\n badgeClassName: string;\n /** Live states breathe; terminal states hold still. */\n pulse: boolean;\n};\n\nexport const SESSION_STATUS_META: Record<SessionStatusValue, SessionStatusMeta> = {\n queued: {\n label: \"Starting\",\n dotClassName: \"bg-og-status-queued\",\n badgeClassName: \"text-og-fg-muted border-og-border bg-og-status-queued/10\",\n pulse: true,\n },\n running: {\n label: \"Running\",\n dotClassName: \"bg-og-status-running\",\n badgeClassName: \"text-og-status-running border-og-status-running/30 bg-og-status-running/10\",\n pulse: true,\n },\n recovering: {\n label: \"Recovering\",\n dotClassName: \"bg-og-status-running\",\n badgeClassName: \"text-og-status-running border-og-status-running/30 bg-og-status-running/10\",\n pulse: true,\n },\n waiting_capacity: {\n label: \"Waiting for capacity\",\n dotClassName: \"bg-og-status-waiting\",\n badgeClassName: \"text-og-status-waiting border-og-status-waiting/35 bg-og-status-waiting/10\",\n pulse: true,\n },\n idle: {\n label: \"Idle\",\n dotClassName: \"bg-og-status-idle\",\n badgeClassName: \"text-og-status-idle border-og-status-idle/30 bg-og-status-idle/10\",\n pulse: false,\n },\n requires_action: {\n label: \"Waiting on you\",\n dotClassName: \"bg-og-status-waiting\",\n badgeClassName: \"text-og-status-waiting border-og-status-waiting/35 bg-og-status-waiting/10\",\n pulse: true,\n },\n failed: {\n label: \"Failed\",\n dotClassName: \"bg-og-status-failed\",\n badgeClassName: \"text-og-status-failed border-og-status-failed/35 bg-og-status-failed/10\",\n pulse: false,\n },\n cancelled: {\n label: \"Cancelled\",\n dotClassName: \"bg-og-status-cancelled\",\n badgeClassName: \"text-og-fg-subtle border-og-border bg-og-status-cancelled/10\",\n pulse: false,\n },\n};\n\nexport type SessionStatusProps = {\n status: SessionStatusValue;\n /** Override the label (\"Running\" -> \"Deploying\", ...). */\n label?: string | undefined;\n size?: \"sm\" | \"md\" | undefined;\n className?: string | undefined;\n};\n\n/** Status badge with a breathing dot for live states. */\nexport function SessionStatus({ status, label, size = \"md\", className }: SessionStatusProps) {\n const meta = SESSION_STATUS_META[status];\n return (\n <span\n data-status={status}\n className={cn(\n \"og-root inline-flex shrink-0 items-center rounded-full border font-medium\",\n size === \"sm\" ? \"gap-1 px-1.5 py-px text-og-xs\" : \"gap-1.5 px-2 py-0.5 text-og-control\",\n meta.badgeClassName,\n className,\n )}\n >\n <StatusDot status={status} className={size === \"sm\" ? \"size-1\" : \"size-1.5\"} />\n {label ?? meta.label}\n </span>\n );\n}\n\nexport type StatusDotProps = {\n status: SessionStatusValue;\n className?: string | undefined;\n};\n\n/** Just the dot — for dense rows and tiles. */\nexport function StatusDot({ status, className }: StatusDotProps) {\n const meta = SESSION_STATUS_META[status];\n return (\n <span\n className={cn(\n \"relative inline-flex size-1.5 shrink-0 rounded-full\",\n meta.dotClassName,\n className,\n )}\n >\n {meta.pulse ? (\n <span className={cn(\"absolute inset-0 animate-og-pulse rounded-full\", meta.dotClassName)} />\n ) : null}\n </span>\n );\n}\n","import type {\n DraftTimelineAnnotation,\n MediaGenerationResult,\n SessionEvent,\n SessionStatus,\n} from \"@opengeni/sdk\";\nimport { dequal } from \"dequal/lite\";\nimport {\n ArrowDownIcon,\n ArrowRightIcon,\n BotIcon,\n CheckCircle2Icon,\n CheckIcon,\n ChevronRightIcon,\n PauseCircleIcon,\n PauseIcon,\n MessageCircleQuestionIcon,\n PencilLineIcon,\n PlayIcon,\n RefreshCwIcon,\n ShrinkIcon,\n TargetIcon,\n Trash2Icon,\n TriangleAlertIcon,\n XCircleIcon,\n} from \"lucide-react\";\nimport type { ComponentType } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { Collapsible } from \"radix-ui\";\nimport {\n Component,\n Suspense,\n lazy,\n memo,\n useCallback,\n useEffect,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { cn } from \"../lib/cn\";\nimport { formatClockTime, formatRelativeTime, truncate } from \"../lib/format\";\nimport { prefersReducedMotion } from \"../lib/motion\";\nimport {\n invokeOlderHistoryLoaderWithReceiptCapture,\n type OlderHistoryLoadReceipt,\n type OlderHistoryLoader,\n} from \"../older-history\";\nimport { Markdown } from \"./markdown\";\nimport {\n UserMessageBody,\n UserMessageDisclosureProvider,\n type UserMessageDisclosureContextValue,\n} from \"./user-message-body\";\nimport {\n createTipFollowState,\n readerScrollUpPx,\n tipFollowCancel,\n tipFollowCompensateViewportShrink,\n tipFollowObserveContentShrink,\n tipFollowStep,\n supportsScrollEndEvent,\n TIP_FOLLOW_READER_UP_EPS_PX,\n TIP_FOLLOW_SHRINK_EPS_PX,\n type TipFollowContentShrinkBaseline,\n type TipFollowState,\n} from \"./tip-follow\";\nimport {\n ActivityRail,\n buildTimeline,\n defaultToolRegistry,\n groupTimeline,\n LightboxProvider,\n type ActivityItem,\n type AgentMessageItem,\n type AuthNeededItem,\n type ContextCompactionItem,\n type GoalItem,\n type HumanInputItem,\n type MachineInputBatchItem,\n type NoticeItem,\n type TimelineGroup,\n type TimelineItem,\n type TimelineAnnotationSourceDescriptor,\n type RetainedArtifactLoader,\n type RetainedScreenshotLoader,\n type VideoArtifactPlaybackLoader,\n type ToolRegistry,\n type TurnSummaryOptions,\n type UserMessageItem,\n type FoldRestingState,\n type WorkerCompletionItem,\n FoldMemoryProvider,\n inheritFoldRestingState,\n TurnSummary,\n useFoldMemory,\n useTurnSettleOpen,\n} from \"../timeline\";\nimport { CopyHoverFrame } from \"./copy-button\";\nimport { GeneratedVideoPlayer } from \"./generated-video-player\";\nimport {\n MACHINE_INPUT_META,\n cleanMachineInputSummary,\n machineInputBatchLabel,\n machineInputSummaryIsUseful,\n readableMachineInputSource,\n} from \"./machine-input-display\";\nimport { SESSION_STATUS_META, StatusDot } from \"./session-status\";\nimport { TimelineComputeLabelProvider } from \"../timeline/compute-label\";\nimport { EntranceAnimationProvider, useEntranceAnimation } from \"../timeline/entrance\";\nimport { SeenActivityIdsProvider } from \"../timeline/seen-activity-ids\";\nimport { TimelineAnnotationsChip } from \"./timeline-annotations\";\nimport { TooltipProvider } from \"./tooltip\";\n\nconst TimelineAnnotationSelection = lazy(() => import(\"./timeline-annotation-selection\"));\n\nexport type MessageTimelineProps = {\n /** Raw session events (projected internally) … */\n events?: SessionEvent[] | undefined;\n /** … or pre-projected items (e.g. from `useSessionEvents().timeline`). */\n items?: TimelineItem[] | undefined;\n /** Current session status (reserved; tip \"Working…\" chrome removed for now). */\n status?: SessionStatus | null | undefined;\n /** Plug a markdown renderer for message bodies (e.g. streamdown). */\n renderMessageText?:\n | ((text: string, item: AgentMessageItem | UserMessageItem) => ReactNode)\n | undefined;\n /** Drill into a spawned worker session. */\n onOpenSession?: ((sessionId: string) => void) | undefined;\n /**\n * Deep-link a memory row (a `memory.saved` / `memory.corrected` step) to its\n * record in the host's memory pane. Opt-in, exactly like `onReconnect`: the\n * library draws no \"View in memory\" affordance without a handler — the memory\n * row is then non-interactive rich content. This is the switch that makes the\n * deep-link a first-party OpenGeni capability without other SDK consumers\n * opting into it. The app supplies it (it owns routing to the memory pane).\n */\n onMemoryClick?: ((memoryId: string) => void) | undefined;\n /**\n * Start the reconnect flow when a tool needs its connection reauthorized. The\n * app supplies this (it owns the SDK client + workspace): it typically kicks\n * off `startConnectionOAuth` and redirects, or routes to credential entry.\n * Rejecting surfaces a calm inline error on the card; the library never draws\n * a Reconnect button without a handler to run it.\n */\n onReconnect?: ((item: AuthNeededItem) => void | Promise<void>) | undefined;\n /**\n * Decide which durable authentication notices this timeline presents.\n * Defaults to showing every notice. Embedded hosts can suppress notices for\n * credentials they manage elsewhere without discarding the underlying event.\n */\n shouldRenderAuthNeeded?: ((item: AuthNeededItem) => boolean) | undefined;\n /**\n * Resolve a provider domain (from a reconnect card) to a logo URL the host\n * serves itself — the app maps it through its catalog + `catalogAssetUrl`.\n * Return null/undefined to fall back to a calm monogram. The library never\n * fetches an off-origin favicon (CSP + privacy); an unresolved logo is a\n * monogram, not an external image.\n */\n resolveProviderLogo?: ((providerDomain: string) => string | null | undefined) | undefined;\n /**\n * The tool-renderer registry that resolves how each tool call is drawn.\n * Defaults to {@link defaultToolRegistry}; pass a registry from\n * `createDefaultToolRegistry({ entries })` to add custom tool renderers.\n */\n toolRegistry?: ToolRegistry | undefined;\n /** Resolve opaque retained screenshot receipts through the authenticated host SDK. */\n loadRetainedScreenshot?: RetainedScreenshotLoader | undefined;\n /** Resolve permanent workspace image/file receipts through the authenticated host SDK. */\n loadRetainedArtifact?: RetainedArtifactLoader | undefined;\n /** Mint short-lived native playback sources for retained generated videos. */\n loadVideoArtifactPlayback?: VideoArtifactPlaybackLoader | undefined;\n /**\n * Display name of the session's active compute target (Connected Machine or\n * cloud sandbox). When set, exec_command collapsed previews prefix `on {label}`.\n */\n computeLabel?: string | null | undefined;\n /** Customize collapsed turn facets for this timeline instance. */\n turnSummary?: TurnSummaryOptions | undefined;\n /** Follow new events when pinned to the bottom. Defaults to true. */\n autoFollow?: boolean | undefined;\n /** Capture a same-row text selection into the host's canonical composer draft. */\n onAnnotate?: ((annotation: DraftTimelineAnnotation) => void) | undefined;\n /** Older durable history exists above the current window (see useSessionEvents). */\n hasOlder?: boolean | undefined;\n /** An older window is being fetched; shows the quiet top shimmer. */\n loadingOlder?: boolean | undefined;\n /**\n * Called when older history should backfill. Existing void, synchronous-value,\n * and arbitrary-promise callbacks remain supported. Receipt-aware loaders\n * preserve committed-page direction through wrappers and bounded windows.\n */\n onLoadOlder?: OlderHistoryLoader | undefined;\n /** Jump to the durable session start (bounded oldest window, no middle). */\n onJumpToStart?: (() => void | Promise<void>) | undefined;\n /** True while the oldest window is loading. */\n loadingOldest?: boolean | undefined;\n /** Newer durable history exists below the current (history) window. */\n hasNewer?: boolean | undefined;\n /** A newer history page is being fetched. */\n loadingNewer?: boolean | undefined;\n /** Page forward through history without loading the whole gap to the tip. */\n onLoadNewer?: (() => void) | undefined;\n /**\n * Reload the live tip window. When omitted, Jump to latest only re-pins and\n * scrolls the in-memory window.\n */\n onJumpToLatest?: (() => void | Promise<void>) | undefined;\n /** Host-owned content appended after timeline groups, such as startup progress. */\n trailingState?: ReactNode | undefined;\n emptyState?: ReactNode | undefined;\n className?: string | undefined;\n};\n\n/**\n * Scroll ownership, from first principles. Everything the events hook has\n * loaded is mounted — no tip-lock window, no per-frame progressive reveal.\n * (The in-memory window is already byte/count-bounded by useSessionEvents, and\n * rows are memoized, so a full mount is cheap; the drip-feed machinery this\n * replaces was the \"content is hidden, then pops in in batches\" wobble.)\n *\n * Scroll invariant (tip-follow camera — see `./tip-follow.ts`):\n * - Load/remount: hidden until tip is hard-snapped across a short settle; then\n * reveal. Live tip: DOM growth advances the pinned viewport by the same\n * amount, so rendered content is visible immediately. Only debt that already\n * existed before the growth goes through the camera ease.\n * - One continuous follow while hot (faster τ when behind); sleeps when cold.\n * - While pinned, tip-debt from growth/collapse must NEVER unpin — only\n * wheel/keys/pointer-armed scroll-up, or a settled scrollend away from the\n * tip while the tip-follow camera is idle (Vimium / unfocused PageUp).\n * Height shrink compensates scrollTop by Δh (collapse owns motion); tip-ease\n * pauses briefly so the two don't fight. Programmatic camera writes are\n * tagged so their scroll echoes never count as leave.\n * - overflow-anchor off while pinned so the browser cannot instant-correct.\n * - Scrolled up → history prepends restore via the retained group anchor\n * (offsetTop delta); loadOlder can truncate the tip, so scrollHeight delta\n * alone is wrong. Late layout while unpinned stays browser-owned.\n */\nconst PIN_THRESHOLD_PX = 48;\n/**\n * A pinned timeline can still have meaningful pre-existing debt while the\n * tip-follow camera catches up. Surface the existing explicit jump once that\n * debt is large enough to be useful, without flashing the control for ordinary\n * line-sized streaming movement.\n */\nconst JUMP_TO_LATEST_CATCHUP_DEBT_PX = 240;\n/**\n * Prefetch older history when the top sentinel is this far from the viewport.\n * After a page loads we stay cool until the reader leaves this band (scrolls\n * down into content) — never re-fire from continued scroll toward y=0.\n */\nconst OLDER_PREFETCH_MARGIN_PX = 400;\nconst OLDER_PREFETCH_ROOT_MARGIN = `${OLDER_PREFETCH_MARGIN_PX}px 0px 0px 0px`;\nconst PRIMARY_ACTION_CLASS =\n \"inline-flex w-full shrink-0 items-center justify-center gap-1.5 rounded-og-md bg-og-accent px-3 py-1.5 text-og-menu font-medium text-og-accent-fg sm:w-auto\";\nconst MESSAGE_BUBBLE_CLASS =\n \"w-fit max-w-full min-w-0 rounded-og-lg rounded-br-og-xs border border-og-border bg-og-surface-2 px-4 py-2.5 text-og-md leading-6 text-og-fg\";\nconst WAITING_PILL_CLASS =\n \"border-og-status-waiting/35 bg-og-status-waiting/10 text-og-status-waiting\";\nconst LOADING_CHIP_CLASS =\n \"pointer-events-none inline-flex items-center rounded-full border border-og-border bg-og-surface-3/90 px-3 py-1 text-og-control font-medium shadow-og-md backdrop-blur\";\n\n// State: 0 underfill retry, 1 prefetch pending, 2 compatibility-settled,\n// 3 explicit no-progress waiting to become an underfill retry.\n// The tuple identity is the exact request ownership fence. The boundary may rebase\n// forward while that request is pending when a bounded live-tail append evicts\n// its former oldest row. First-party loaders mark the exact owner when their\n// older page commits; retained direction is the fallback for other hosts.\ntype OlderLoadAttempt = [\n boundary: string | undefined,\n state?: number,\n receipt?: OlderHistoryLoadReceipt,\n];\n\nfunction invokeOlderLoad(\n load: OlderHistoryLoader,\n noProgress: () => void,\n attempt: OlderLoadAttempt,\n): 1 | undefined {\n try {\n // Receipt creation is captured synchronously through legacy wrappers such\n // as `() => void loadOlder()`, even when the wrapper discards the return.\n const result = invokeOlderHistoryLoaderWithReceiptCapture(load, (receipt) => {\n attempt[2] = receipt;\n }) as OlderHistoryLoadReceipt | PromiseLike<unknown> | unknown;\n const receipt =\n attempt[2] ??\n (typeof (result as { committed?: unknown } | undefined)?.committed === \"boolean\"\n ? (result as OlderHistoryLoadReceipt)\n : undefined);\n if (receipt) {\n attempt[2] = receipt;\n void receipt.then(\n (value) => value === false && !receipt.committed && noProgress(),\n noProgress,\n );\n return 1;\n }\n if (typeof (result as PromiseLike<unknown> | undefined)?.then != \"function\") {\n return;\n }\n void (result as PromiseLike<unknown>).then(\n (value) => value === false && noProgress(),\n noProgress,\n );\n } catch {\n noProgress();\n }\n return 1;\n}\n\n/**\n * Pinned = the viewport bottom is within PIN_THRESHOLD_PX of the content\n * bottom. When the scroll range itself is shorter than the threshold, the\n * whole range would count as \"at the bottom\" and the reader could never unpin\n * to reach older history — so the effective threshold shrinks to the range,\n * making the very top of a short window count as scrolled up. A window that\n * cannot scroll at all is always pinned.\n */\nfunction maxScrollOf(node: HTMLElement): number {\n // Browser layout guarantees scrollHeight is at least clientHeight.\n return node.scrollHeight - node.clientHeight;\n}\n\n/**\n * Wheel bubbled from a nested overflow scroller that can still move up — not\n * timeline intent (code blocks / notice `<pre>`).\n */\nfunction wheelConsumedByNestedScrollable(event: {\n deltaY: number;\n target: EventTarget | null;\n currentTarget: EventTarget | null;\n}): boolean {\n if (event.deltaY >= 0) {\n return false;\n }\n let el = event.target instanceof Element ? event.target : null;\n const root = event.currentTarget instanceof Element ? event.currentTarget : null;\n while (el && el !== root) {\n if (el instanceof HTMLElement) {\n const style = getComputedStyle(el);\n const overflowY = style.overflowY;\n if (\n (overflowY === \"auto\" || overflowY === \"scroll\" || overflowY === \"overlay\") &&\n el.scrollHeight > el.clientHeight + 1 &&\n el.scrollTop > 0\n ) {\n return true;\n }\n }\n el = el.parentElement;\n }\n return false;\n}\n\nfunction isNearBottom(node: HTMLElement): boolean {\n const maxScroll = maxScrollOf(node);\n if (maxScroll <= 1) {\n return true;\n }\n const gap = maxScroll - node.scrollTop;\n return gap < Math.min(PIN_THRESHOLD_PX, maxScroll);\n}\n\n/** Escape a value for use inside a CSS attribute selector. */\nfunction cssEscapeAttribute(value: string): string {\n if (typeof CSS !== \"undefined\" && typeof CSS.escape === \"function\") {\n return CSS.escape(value);\n }\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\n/**\n * The session timeline: chat messages with streaming deltas, collapsed\n * activity clusters (reasoning, tool calls, sandbox work), spawned-worker\n * cards, goal markers, and status transitions. Owns stick-to-bottom scrolling\n * with a \"jump to latest\" affordance when the reader scrolls back.\n */\nexport function MessageTimeline({\n events,\n items,\n status: _status,\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n shouldRenderAuthNeeded,\n resolveProviderLogo,\n toolRegistry = defaultToolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n computeLabel = null,\n turnSummary,\n autoFollow = true,\n onAnnotate,\n hasOlder = false,\n loadingOlder = false,\n onLoadOlder,\n onJumpToStart,\n loadingOldest = false,\n hasNewer = false,\n loadingNewer = false,\n onLoadNewer,\n onJumpToLatest,\n trailingState,\n emptyState,\n className,\n}: MessageTimelineProps) {\n const resolvedItems = useMemo(() => {\n const projectedItems = items ?? buildTimeline(events ?? []);\n if (!shouldRenderAuthNeeded) {\n return projectedItems;\n }\n return projectedItems.filter(\n (item) => item.kind !== \"auth-needed\" || shouldRenderAuthNeeded(item),\n );\n }, [items, events, shouldRenderAuthNeeded]);\n const sourceItems = items || events;\n const olderBoundaryKey = sourceItems?.[0]?.id;\n const allGroups = useMemo(() => groupTimeline(resolvedItems), [resolvedItems]);\n const annotationSources = useMemo(() => {\n const sources = new Map<string, TimelineAnnotationSourceDescriptor>();\n for (const item of resolvedItems) {\n if (\n (item.kind === \"user-message\" ||\n item.kind === \"agent-message\" ||\n item.kind === \"tool-call\") &&\n item.annotationSource\n ) {\n sources.set(item.annotationSource.eventId, item.annotationSource);\n }\n }\n return sources;\n }, [resolvedItems]);\n const scrollRef = useRef<HTMLDivElement | null>(null);\n const topSentinelRef = useRef<HTMLDivElement | null>(null);\n const bottomSentinelRef = useRef<HTMLDivElement | null>(null);\n const previousBulkFirstKeyRef = useRef<string | null | undefined>(undefined);\n const [pinned, setPinned] = useState(true);\n const [canSkipTipCatchup, setCanSkipTipCatchup] = useState(false);\n const canSkipTipCatchupRef = useRef(false);\n const [bulkActive, setBulkActive] = useState(true);\n // Older history prefetch is user-driven: a window shorter than the viewport\n // + rootMargin would otherwise keep the top sentinel intersecting and fetch\n // history forever while the reader sits at the tip. Arm on first scroll-up.\n const olderPrefetchArmedRef = useRef(false);\n const [olderPrefetchArmed, setOlderPrefetchArmed] = useState(false);\n // A collapsed history tail can be shorter than the viewport. In that state\n // there is no upward scroll range, so reader intent can never arm the top\n // sentinel. Request one older page per loaded window until history either\n // fills the viewport or the host reports that no older rows remain. Each\n // attempt owns the oldest loaded item boundary across BOTH the automatic\n // underfill and reader-driven sentinel paths. Live-tail appends do not\n // advance older pagination or release that exact owner.\n const olderLoadAttemptRef = useRef<OlderLoadAttempt | null>(null);\n const [underfillSettledAttempt, setUnderfillSettledAttempt] = useState<OlderLoadAttempt | null>(\n null,\n );\n const underfillRetryReadyRef = useRef(false);\n const resizeFollowRafRef = useRef<number | null>(null);\n const firstGroupKey = allGroups[0] ? timelineGroupKey(allGroups[0]) : null;\n // Content stays invisible until the tip is hard-parked across a short\n // post-commit settle (two rAFs). That absorbs sync late layout while hidden\n // so load/remount does not ease into the tip — live tip-follow is unchanged\n // once revealed. A flash of the window's TOP is still structurally impossible.\n // The accepted-create handoff uses the reserved local id \"c\" so its known\n // first message is visible immediately; loaded histories still park first.\n const [revealed, setRevealed] = useState(resolvedItems[0]?.id === \"c\");\n // Mirror `pinned` into a ref, written ONLY by applyPinned, so the\n // ResizeObserver rAF (a stable closure) reads the live value and a snap can\n // never race a just-unpinned reader across a pending React commit.\n const pinnedRef = useRef(true);\n // History windows (`hasNewer`) have a bottom that is not the live tip.\n // Pin/follow must ignore that floor — otherwise loadNewer appends yank the\n // reader to the new page bottom. LoadOlder prepends already stay put because\n // the reader is unpinned and scroll anchoring / delta correction owns place.\n const hasNewerRef = useRef(hasNewer);\n hasNewerRef.current = hasNewer;\n // Jump-to-latest pressed while a history window is showing: the pin must\n // wait for the tip window to actually land (`hasNewer` → false) — pinning\n // immediately would snap to the bottom of the CURRENT history page and\n // page-crawl forward through the gap.\n const wantPinRef = useRef(false);\n // Jump-to-start pressed: consume on the commit that swaps the window so the\n // scroll-to-top write races neither the old DOM nor the prepend correction.\n const pendingJumpToStartRef = useRef(false);\n // Identifies the newest Jump-to-start click so a settling promise callback\n // from an earlier click can never clear a re-click's pending flag.\n const jumpToStartSeqRef = useRef(0);\n // Prepend detection: the oldest loaded item's id changes exactly when older\n // history lands (including the merge-into-first-group case where the first\n // GROUP key is retained). Item ids, not group keys, are the durable signal.\n const previousFirstItemIdRef = useRef<string | null>(null);\n const previousScrollHeightRef = useRef(0);\n // Per-commit place memory for unpinned prepend restore (see layout effect).\n // Paired with max/height/client for clamp-conservation reader-intent math.\n const lastScrollTopRef = useRef(0);\n const lastMaxScrollRef = useRef(0);\n const lastScrollHeightRef = useRef(0);\n const lastClientHeightRef = useRef(0);\n /**\n * Armed by pointerdown on the scroller. Immediate geometric scroll-up unpins\n * while armed (scrollbar / touch drag). Wheel/keys unpin directly. Extension\n * jumps (Vimium) settle via scrollend while the camera is idle.\n */\n const readerIntentArmRef = useRef(false);\n /** Gesture-start geometry; cumulative tiny pointer scrolls share one budget. */\n const readerIntentStartRef = useRef<{ scrollTop: number; maxScroll: number } | null>(null);\n /**\n * Count of camera/snap scrollTop writes whose scroll echoes are not yet\n * consumed. A boolean was wrong when the browser coalesced two writes into\n * one scroll event (or fired two) — use a count, and clear to 0 on echo.\n */\n const programmaticScrollRef = useRef(0);\n /**\n * Disclosure height changes are not reader navigation. While an unpinned\n * Show more/less state is active, its clamp/native-anchor scroll echoes must\n * never geometrically re-enable bottom-follow. A later real reader navigation\n * or explicit Jump to latest releases this fence.\n */\n const disclosureKeepsUnpinnedRef = useRef(false);\n /**\n * Unarmed scroll-away observed; waiting for scrollend (or rAF fallback).\n * Blocks layout tip-follow so a stream token cannot yank before leave settles.\n */\n const pendingReaderLeaveRef = useRef(false);\n /** Fallback leave check when `scrollend` is missing (one rAF, not a timer). */\n const leaveFallbackRafRef = useRef<number | null>(null);\n // Resting fold state per durable group id (see fold-memory.ts). Outlives the\n // deliberate chip remounts (activity→turn wrap, nested key flips) so a fold\n // that already settled closed — or that the reader closed — never reopens.\n const foldMemoryRef = useRef<Map<string, FoldRestingState>>(new Map());\n const userMessageDisclosureMemoryRef = useRef<Map<string, boolean>>(new Map());\n const seenActivityIdsRef = useRef<Set<string>>(new Set());\n const firstItemGroupKeyRef = useRef<string | null>(null);\n const firstItemGroupOffsetTopRef = useRef<number | null>(null);\n const firstItemContentTopRef = useRef<number | null>(null);\n const firstItemId = resolvedItems[0]?.id ?? null;\n // Pagination ownership follows the oldest committed input, before host\n // filtering and grouping. A page containing only suppressed auth notices\n // still advances this receipt, while live-tail appends leave it unchanged.\n // Promise fulfillment alone does neither, so delayed prepends stay fenced.\n const underfillRetryReady = (underfillRetryReadyRef.current = !!(\n underfillSettledAttempt &&\n underfillSettledAttempt === olderLoadAttemptRef.current &&\n hasOlder &&\n onLoadOlder &&\n !loadingOlder\n ));\n // Bulk paints (the initial tail window, a prepended older window — detected\n // by the first group key changing) must not run per-row entrance animations.\n const firstKeyChangedForBulk =\n previousBulkFirstKeyRef.current !== undefined &&\n previousBulkFirstKeyRef.current !== firstGroupKey;\n const bulkRender = allGroups.length > 0 && (bulkActive || firstKeyChangedForBulk);\n const groups = useStableTimelineGroupKeys(allGroups, !bulkRender);\n\n const applyCanSkipTipCatchup = useCallback((value: boolean) => {\n if (canSkipTipCatchupRef.current !== value) {\n canSkipTipCatchupRef.current = value;\n setCanSkipTipCatchup(value);\n }\n }, []);\n\n // The ONLY writer of the pinned flag. Ref and state move together, so\n // behavior (refs read by rAF callbacks) and rendering (the anchor class,\n // the Jump-to-latest button) can never desync.\n const applyPinned = useCallback(\n (value: boolean) => {\n if (pinnedRef.current !== value) {\n pinnedRef.current = value;\n setPinned(value);\n }\n if (!value) {\n applyCanSkipTipCatchup(false);\n }\n },\n [applyCanSkipTipCatchup],\n );\n\n const rearmOlderPrefetchAfterLeavingTop = useCallback((node: HTMLElement) => {\n if (node.scrollTop > OLDER_PREFETCH_MARGIN_PX) {\n const state = olderLoadAttemptRef.current?.[1];\n if (state === 2 || state === 3) {\n olderLoadAttemptRef.current = null;\n }\n }\n }, []);\n\n const revealedRef = useRef(revealed);\n revealedRef.current = revealed;\n\n // Pure tip-follow camera. Pin intent uses clamp conservation, not timers.\n const followRef = useRef<TipFollowState>(createTipFollowState());\n const followFrameRef = useRef<number | null>(null);\n const contentShrinkBaselineRef = useRef<TipFollowContentShrinkBaseline | null>(null);\n\n const syncScrollBaseline = useCallback((node: HTMLElement) => {\n lastScrollTopRef.current = node.scrollTop;\n lastMaxScrollRef.current = maxScrollOf(node);\n lastScrollHeightRef.current = node.scrollHeight;\n lastClientHeightRef.current = node.clientHeight;\n }, []);\n\n const writeScrollTop = useCallback((node: HTMLElement, top: number) => {\n const next = Math.max(0, top);\n const before = node.scrollTop;\n if (before === next) {\n return;\n }\n programmaticScrollRef.current += 1;\n node.scrollTop = next;\n if (node.scrollTop === before) {\n // The engine floored a sub-device-pixel write to a no-op: no scroll echo\n // will ever fire. Counting it would leak the echo count and silently eat\n // a later REAL reader scroll as programmatic.\n programmaticScrollRef.current -= 1;\n }\n }, []);\n\n const cancelLeaveFallback = useCallback(() => {\n if (leaveFallbackRafRef.current != null) {\n cancelFrame(leaveFallbackRafRef.current);\n leaveFallbackRafRef.current = null;\n }\n }, []);\n\n const clearPendingReaderLeave = useCallback(() => {\n pendingReaderLeaveRef.current = false;\n cancelLeaveFallback();\n }, [cancelLeaveFallback]);\n\n const clearReaderIntent = useCallback(() => {\n readerIntentArmRef.current = false;\n readerIntentStartRef.current = null;\n }, []);\n\n const stopFollow = useCallback(() => {\n contentShrinkBaselineRef.current = null;\n followRef.current = tipFollowCancel(followRef.current);\n if (followFrameRef.current != null) {\n cancelFrame(followFrameRef.current);\n followFrameRef.current = null;\n }\n }, []);\n\n /** Reader left the tip — wheel, keyboard, pointer-armed scroll-up, or scrollend. */\n const releasePinFromReader = useCallback(\n (node?: HTMLElement | null) => {\n if (!autoFollow || !pinnedRef.current || hasNewerRef.current) {\n return;\n }\n // Unscrollable window: unpin strands Jump-to-latest with no way back.\n if (node && maxScrollOf(node) <= 1) {\n return;\n }\n clearReaderIntent();\n clearPendingReaderLeave();\n stopFollow();\n applyPinned(false);\n if (wantPinRef.current) {\n wantPinRef.current = false;\n }\n if (!olderPrefetchArmedRef.current) {\n olderPrefetchArmedRef.current = true;\n setOlderPrefetchArmed(true);\n }\n },\n [autoFollow, applyPinned, clearPendingReaderLeave, clearReaderIntent, stopFollow],\n );\n\n /**\n * Settled away from the tip while the camera is idle — Vimium / unfocused\n * PageUp. Folds are recovered by layout tip-follow before this fires at tip.\n */\n const releasePinAfterScrollSettled = useCallback(\n (node: HTMLElement) => {\n if (!autoFollow || !pinnedRef.current || hasNewerRef.current) {\n return;\n }\n if (programmaticScrollRef.current > 0) {\n return;\n }\n if (followRef.current.running || followFrameRef.current != null) {\n return;\n }\n if (isNearBottom(node) || maxScrollOf(node) <= 1) {\n clearPendingReaderLeave();\n return;\n }\n releasePinFromReader(node);\n rearmOlderPrefetchAfterLeavingTop(node);\n },\n [autoFollow, clearPendingReaderLeave, rearmOlderPrefetchAfterLeavingTop, releasePinFromReader],\n );\n\n const scheduleLeaveFallback = useCallback(() => {\n // Prefer scrollend when the engine supports it.\n if (supportsScrollEndEvent()) {\n return;\n }\n cancelLeaveFallback();\n leaveFallbackRafRef.current = requestFrame(() => {\n leaveFallbackRafRef.current = null;\n const current = scrollRef.current;\n if (current) {\n releasePinAfterScrollSettled(current);\n }\n });\n }, [cancelLeaveFallback, releasePinAfterScrollSettled]);\n\n const onWheel = (event: {\n deltaY: number;\n deltaX: number;\n target: EventTarget | null;\n currentTarget: EventTarget | null;\n }) => {\n // Nested overflow (code / notice pre) or mostly-horizontal pan: not\n // timeline reader intent. A real timeline wheel in either direction\n // releases the disclosure fence; downward movement may then re-pin\n // naturally when it reaches the bottom.\n if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) {\n return;\n }\n if (wheelConsumedByNestedScrollable(event)) {\n return;\n }\n disclosureKeepsUnpinnedRef.current = false;\n if (event.deltaY >= 0) {\n return;\n }\n const node =\n event.currentTarget instanceof HTMLElement ? event.currentTarget : scrollRef.current;\n releasePinFromReader(node);\n };\n\n /** Touch / stylus / mouse drag on the scroller — explicit leave (not layout). */\n const onPointerDown = (event: {\n button: number;\n pointerType: string;\n target: EventTarget | null;\n currentTarget: EventTarget | null;\n }) => {\n // Primary button / touch / pen only. Ignore right-click etc.\n if (event.button && event.pointerType === \"mouse\") {\n return;\n }\n // Clicks on chips/buttons/links must not arm — their settle collapse\n // also drops scrollTop and would false-unpin. Drag on prose/scroller may.\n if (\n event.target instanceof Element &&\n event.target.closest(\"button, a, input, textarea, select, [role='button']\")\n ) {\n return;\n }\n disclosureKeepsUnpinnedRef.current = false;\n const node =\n event.currentTarget instanceof HTMLElement ? event.currentTarget : scrollRef.current;\n readerIntentArmRef.current = true;\n readerIntentStartRef.current = node\n ? { scrollTop: node.scrollTop, maxScroll: maxScrollOf(node) }\n : null;\n };\n\n const onKeyDown = (event: { key: string; currentTarget: EventTarget | null }) => {\n if (\n event.key === \"ArrowUp\" ||\n event.key === \"ArrowDown\" ||\n event.key === \"PageUp\" ||\n event.key === \"PageDown\" ||\n event.key === \"Home\" ||\n event.key === \"End\"\n ) {\n disclosureKeepsUnpinnedRef.current = false;\n }\n if (event.key !== \"ArrowUp\" && event.key !== \"PageUp\" && event.key !== \"Home\") {\n return;\n }\n const node =\n event.currentTarget instanceof HTMLElement ? event.currentTarget : scrollRef.current;\n releasePinFromReader(node);\n };\n\n const snapToBottom = useCallback(\n (node: HTMLElement) => {\n clearReaderIntent();\n stopFollow();\n cancelLeaveFallback();\n writeScrollTop(node, Math.max(0, node.scrollHeight - node.clientHeight));\n syncScrollBaseline(node);\n followRef.current = {\n ...followRef.current,\n lastHeight: node.scrollHeight,\n lastClientHeight: node.clientHeight,\n cameraTop: null,\n };\n applyCanSkipTipCatchup(false);\n },\n [\n applyCanSkipTipCatchup,\n cancelLeaveFallback,\n clearReaderIntent,\n stopFollow,\n syncScrollBaseline,\n writeScrollTop,\n ],\n );\n\n const beginUserMessageDisclosureChange = useCallback(\n (messageBody: HTMLElement, disclosureControl: HTMLElement) => {\n const node = scrollRef.current;\n if (!node || !node.contains(messageBody)) {\n return null;\n }\n const keepBottom = autoFollow && pinnedRef.current && !hasNewerRef.current;\n if (keepBottom) {\n return () => {\n const current = scrollRef.current;\n if (current) {\n snapToBottom(current);\n }\n };\n }\n\n disclosureKeepsUnpinnedRef.current = true;\n\n const scrollerRect = node.getBoundingClientRect();\n const group = messageBody.closest<HTMLElement>(\"[data-og-timeline-group-anchor]\");\n const groupRect = group?.getBoundingClientRect();\n // Expanding from a visible message top keeps the beginning in place.\n // Collapsing after reading deep in the message keeps the disclosure\n // control in place because the message top is already above the viewport.\n const anchor =\n group &&\n groupRect &&\n groupRect.top >= scrollerRect.top - 1 &&\n groupRect.top < scrollerRect.bottom\n ? group\n : disclosureControl;\n const beforeTop = anchor.getBoundingClientRect().top - scrollerRect.top;\n\n return () => {\n const current = scrollRef.current;\n if (!current || !current.contains(anchor)) {\n return;\n }\n const currentScrollerTop = current.getBoundingClientRect().top;\n const afterTop = anchor.getBoundingClientRect().top - currentScrollerTop;\n const delta = afterTop - beforeTop;\n if (Math.abs(delta) > 0.5) {\n writeScrollTop(current, current.scrollTop + delta);\n }\n applyPinned(false);\n syncScrollBaseline(current);\n };\n },\n [applyPinned, autoFollow, snapToBottom, syncScrollBaseline, writeScrollTop],\n );\n\n const userMessageDisclosureContext = useMemo<UserMessageDisclosureContextValue>(\n () => ({\n expandedByMessageId: userMessageDisclosureMemoryRef.current,\n beginChange: beginUserMessageDisclosureChange,\n }),\n [beginUserMessageDisclosureChange],\n );\n const timelineGroupEntryContext = useMemo<TimelineGroupEntryContext>(\n () => ({\n userMessageDisclosureContext,\n behavior: {\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n resolveProviderLogo,\n toolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n turnSummary,\n },\n }),\n [\n loadRetainedArtifact,\n loadRetainedScreenshot,\n loadVideoArtifactPlayback,\n onMemoryClick,\n onOpenSession,\n onReconnect,\n renderMessageText,\n resolveProviderLogo,\n toolRegistry,\n turnSummary,\n userMessageDisclosureContext,\n ],\n );\n\n const requestOlderIfUnderfilled = useCallback(\n (node: HTMLElement, retry?: OlderLoadAttempt) => {\n let currentAttempt = olderLoadAttemptRef.current;\n if (retry && (currentAttempt !== retry || retry[0] !== olderBoundaryKey)) {\n // AnimatePresence may retain the exiting button briefly. Its stale\n // handler cannot replace a newer exact owner.\n return;\n }\n const underfilled = maxScrollOf(node) <= 1;\n if (!retry && underfilled && currentAttempt?.[1] === 3) {\n // A receipted prefetch already declined or failed while the viewport\n // was still scrollable. Collapse may later remove the scroll range;\n // promote that exact owner to Retry without issuing another request.\n currentAttempt[1] = 0;\n setUnderfillSettledAttempt(currentAttempt);\n return;\n }\n if (!retry && underfilled && currentAttempt?.[1] === 2) {\n // A settled ordinary prefetch owns only this visit to the top band.\n // If its resulting window cannot scroll, yield to automatic underfill\n // so the reader is not stranded behind a cooldown they cannot exit.\n currentAttempt = olderLoadAttemptRef.current = null;\n }\n // clientHeight=0 is pre-layout/headless, not evidence that the rendered\n // history underfills a real viewport.\n if (\n node.clientHeight <= 1 ||\n (!retry && !underfilled) ||\n !hasOlder ||\n loadingOlder ||\n !onLoadOlder ||\n (currentAttempt && !retry)\n ) {\n return;\n }\n const attempt: OlderLoadAttempt = (olderLoadAttemptRef.current = [olderBoundaryKey]);\n setUnderfillSettledAttempt(null);\n // Every underfill request owns the ordinary sentinel too, even if reader\n // intent had not armed it yet when this short-window request began.\n const noProgress = () => {\n if (scrollRef.current && olderLoadAttemptRef.current === attempt) {\n setUnderfillSettledAttempt(attempt);\n }\n };\n // Legacy fire-and-forget callbacks keep the one-shot behavior. Hosts\n // that return the real promise opt into safe rejection/no-progress retry;\n // exact `false` is the first-party request-not-accepted receipt.\n // All other fulfillment retains this exact owner until its prepend\n // boundary commits; promise settlement alone cannot prove progress.\n invokeOlderLoad(onLoadOlder, noProgress, attempt);\n },\n [hasOlder, loadingOlder, olderBoundaryKey, onLoadOlder],\n );\n const driveFollowRef = useRef<(node: HTMLElement, now?: number) => void>(\n requestOlderIfUnderfilled as (node: HTMLElement, now?: number) => void,\n );\n const driveFollow = useCallback(\n (node: HTMLElement, nowMs?: number) => {\n if (!pinnedRef.current || hasNewerRef.current) {\n stopFollow();\n return;\n }\n // Reader/extension leave in flight — do not yank back before scrollend.\n if (pendingReaderLeaveRef.current) {\n stopFollow();\n return;\n }\n cancelLeaveFallback();\n // Prefer the rAF timestamp so ease integrates against vsync (and tests\n // can advance a synthetic clock via requestAnimationFrame callbacks).\n const now =\n typeof nowMs === \"number\"\n ? nowMs\n : typeof performance !== \"undefined\"\n ? performance.now()\n : Date.now();\n let previousHeight = followRef.current.lastHeight;\n const previousObservedHeight = lastScrollHeightRef.current;\n if (\n contentShrinkBaselineRef.current &&\n previousObservedHeight > 0 &&\n node.scrollHeight > previousObservedHeight\n ) {\n // A reversal ends the collapse sequence. If it remains below the held\n // baseline, adopt the recovered height; if it grew beyond the baseline,\n // leave that baseline for tipFollowStep to observe as real growth.\n contentShrinkBaselineRef.current = null;\n if (node.scrollHeight < previousHeight) {\n followRef.current = {\n ...followRef.current,\n lastHeight: node.scrollHeight,\n cameraTop: null,\n };\n previousHeight = node.scrollHeight;\n }\n }\n const shrinkObservation = tipFollowObserveContentShrink(\n contentShrinkBaselineRef.current,\n previousHeight,\n lastScrollTopRef.current,\n node.scrollHeight,\n node.clientHeight,\n );\n contentShrinkBaselineRef.current = shrinkObservation.baseline;\n // Settle-collapse: compensate Δh from the pre-shrink baseline (browser\n // may already have clamped — don't double-subtract). Keep the follow rAF\n // alive so when collapse ends (or stream resumes) we ease instead of a\n // hard stop → flick. Do NOT tip-ease on the same frame as a real shrink\n // (that fight was the top-of-viewport flicker).\n if (shrinkObservation.compensatedScrollTop !== null) {\n let nextTop = shrinkObservation.compensatedScrollTop;\n // A chrome/composer dock can land on the same frame as a settle-fold\n // (the \"turn blocked\" moment). Compensate BOTH in one write — adopting\n // the shrunk clientHeight below without gluing left the chrome height\n // behind as cold tip debt.\n const previousClient = followRef.current.lastClientHeight;\n if (previousClient > 0 && node.clientHeight < previousClient - TIP_FOLLOW_SHRINK_EPS_PX) {\n nextTop = tipFollowCompensateViewportShrink(\n nextTop,\n previousClient,\n node.clientHeight,\n node.scrollHeight,\n );\n }\n writeScrollTop(node, nextTop);\n syncScrollBaseline(node);\n followRef.current = {\n ...followRef.current,\n lastHeight: node.scrollHeight,\n lastClientHeight: node.clientHeight,\n running: true,\n lastTs: now,\n // A direct glue write re-based the camera — drop any stale fraction.\n cameraTop: null,\n };\n if (followFrameRef.current == null) {\n followFrameRef.current = requestFrame((frameNow) => {\n followFrameRef.current = null;\n const current = scrollRef.current;\n if (current) {\n driveFollowRef.current(current, frameNow);\n }\n });\n }\n return;\n }\n const result = tipFollowStep(followRef.current, {\n scrollTop: node.scrollTop,\n scrollHeight: node.scrollHeight,\n clientHeight: node.clientHeight,\n now,\n pinned: true,\n reducedMotion: prefersReducedMotion(),\n revealed: revealedRef.current,\n });\n followRef.current = result.state;\n writeScrollTop(node, result.scrollTop);\n syncScrollBaseline(node);\n applyCanSkipTipCatchup(\n result.state.running &&\n maxScrollOf(node) - node.scrollTop >= JUMP_TO_LATEST_CATCHUP_DEBT_PX,\n );\n if (result.state.running) {\n cancelLeaveFallback();\n if (followFrameRef.current == null) {\n followFrameRef.current = requestFrame((frameNow) => {\n followFrameRef.current = null;\n const current = scrollRef.current;\n if (current) {\n driveFollowRef.current(current, frameNow);\n }\n });\n }\n } else if (followFrameRef.current != null) {\n cancelFrame(followFrameRef.current);\n followFrameRef.current = null;\n }\n },\n [applyCanSkipTipCatchup, cancelLeaveFallback, stopFollow, syncScrollBaseline, writeScrollTop],\n );\n driveFollowRef.current = driveFollow;\n\n useEffect(() => stopFollow, [stopFollow]);\n useEffect(() => () => cancelLeaveFallback(), [cancelLeaveFallback]);\n\n // The single post-commit scroll authority. Runs after EVERY commit (no dep\n // list): any commit may change content height, and the decision is cheap.\n // Also the ONLY writer of the prepend-correction baselines\n // (previousFirstItemIdRef / previousScrollHeightRef / group offset maps).\n // oxlint-disable-next-line react-hooks/exhaustive-deps -- Deliberately runs after every commit.\n useLayoutEffect(() => {\n const node = scrollRef.current;\n if (!node) {\n return;\n }\n const previousFirstItemId = previousFirstItemIdRef.current;\n const previousFirstItemGroupKey = firstItemGroupKeyRef.current;\n const previousFirstItemGroupOffsetTop = firstItemGroupOffsetTopRef.current;\n const previousItemContentTop = firstItemContentTopRef.current;\n const previousScrollTop = lastScrollTopRef.current;\n const previousMaxScroll = lastMaxScrollRef.current;\n const wasAtLiveTailBeforeCommit =\n previousMaxScroll <= 1 ||\n previousMaxScroll - previousScrollTop < Math.min(PIN_THRESHOLD_PX, previousMaxScroll);\n const firstItemChanged = !!previousFirstItemId && firstItemId !== previousFirstItemId;\n const prepended =\n firstItemChanged && resolvedItems.some((item) => item.id === previousFirstItemId);\n const attempt = olderLoadAttemptRef.current;\n const committedZeroOverlapOlderReplacement = !!(\n attempt?.[2]?.committed &&\n firstItemChanged &&\n !prepended\n );\n const restorePrependAnchor = () => {\n // Keep the reader on the same retained rows. Prefer the exact first-item\n // content coordinate (needed when a prepend merges inside one group),\n // then the retained group offset, then scrollHeight as a final fallback.\n // If native anchoring already applied the same shift, leave scrollTop.\n let delta: number | null = null;\n if (previousFirstItemId && previousItemContentTop != null) {\n const itemEl = node.querySelector(\n `[data-og-item=\"${cssEscapeAttribute(previousFirstItemId)}\"]`,\n );\n if (itemEl instanceof HTMLElement) {\n const scrollerTop = node.getBoundingClientRect().top;\n const currentItemTop = itemEl.getBoundingClientRect().top - scrollerTop + node.scrollTop;\n delta = Math.round(currentItemTop - previousItemContentTop);\n }\n }\n const anchorKey = previousFirstItemGroupKey;\n const anchorEl =\n anchorKey != null\n ? node.querySelector(`[data-og-group-key=\"${cssEscapeAttribute(anchorKey)}\"]`)\n : null;\n if (\n delta == null &&\n anchorEl instanceof HTMLElement &&\n previousFirstItemGroupOffsetTop != null\n ) {\n const moved = Math.round(anchorEl.offsetTop - previousFirstItemGroupOffsetTop);\n if (moved) {\n delta = moved;\n }\n }\n if (delta == null) {\n const heightDelta = Math.round(node.scrollHeight - previousScrollHeightRef.current);\n if (heightDelta > 0) {\n delta = heightDelta;\n }\n }\n if (delta != null) {\n const expected = previousScrollTop + delta;\n if (Math.abs(node.scrollTop - expected) > 2) {\n writeScrollTop(node, expected);\n }\n }\n };\n if (pendingJumpToStartRef.current && firstItemChanged) {\n // The oldest window landed — jump against the NEW DOM, and skip the\n // prepend correction (it would shift the reader away from the top).\n pendingJumpToStartRef.current = false;\n stopFollow();\n writeScrollTop(node, 0);\n } else if (wantPinRef.current && !hasNewer) {\n // Jump-to-latest was pressed on a history window and the tip window is\n // in THIS commit — consume pre-paint so the first tip frame is already\n // at the bottom (post-paint consumption flashed one clamped frame).\n wantPinRef.current = false;\n if (autoFollow) {\n applyPinned(true);\n snapToBottom(node);\n }\n } else if (committedZeroOverlapOlderReplacement) {\n // An oldest-directed bounded page can replace every previously mounted\n // row. Its receipt is the only causal proof that this is backward\n // progress rather than live-tail forward eviction. Anchor at the bottom\n // seam before recording this window's scroll baselines so an unpinned\n // reader stays adjacent to the history they were reading.\n clearPendingReaderLeave();\n stopFollow();\n writeScrollTop(node, maxScrollOf(node));\n if (attempt?.[1] === 1 && pinnedRef.current) {\n applyPinned(false);\n }\n } else if (prepended) {\n if (\n autoFollow &&\n pinnedRef.current &&\n !hasNewer &&\n !pendingReaderLeaveRef.current &&\n (wasAtLiveTailBeforeCommit || olderLoadAttemptRef.current)\n ) {\n // A pending short-window load owns the prepend even when live growth\n // has left its still-pinned camera with raw geometry debt. Unrelated\n // prepends retain the prior-tip fallback so a stale pin after an\n // extension/programmatic history jump still restores its row anchor.\n clearPendingReaderLeave();\n snapToBottom(node);\n } else {\n restorePrependAnchor();\n if (autoFollow && pinnedRef.current && !hasNewer) {\n // Geometry or a pending extension/programmatic leave proves the\n // reader was browsing history even if the pin ref has not settled.\n stopFollow();\n clearPendingReaderLeave();\n applyPinned(false);\n }\n }\n } else if (autoFollow && pinnedRef.current && !hasNewer) {\n // Load/remount (still hidden): hard-park. Live tip after reveal: ease.\n // Pending unarmed leave: tip *growth* must not yank (Vimium during stream).\n // Flat/shrink commits (fold) still recover — height did not grow under us.\n if (!revealedRef.current) {\n snapToBottom(node);\n } else if (pendingReaderLeaveRef.current) {\n if (node.scrollHeight <= lastScrollHeightRef.current) {\n clearPendingReaderLeave();\n driveFollow(node);\n }\n } else {\n driveFollow(node);\n }\n }\n // After a prepend, if restore left us below the top prefetch band,\n // re-arm so a later approach can load again. Still cooling while parked\n // inside the band (short pages) — that stops the y=0 load loop.\n if (prepended && !pinnedRef.current && node.scrollTop > OLDER_PREFETCH_MARGIN_PX) {\n rearmOlderPrefetchAfterLeavingTop(node);\n }\n previousFirstItemIdRef.current = firstItemId;\n previousScrollHeightRef.current = node.scrollHeight;\n syncScrollBaseline(node);\n // offsetTop queries are O(groups); skip while pinned at the live tip\n // (every stream token used to remeasure the whole timeline).\n firstItemGroupKeyRef.current = groups[0]?.key ?? null;\n const needOffsets =\n prepended ||\n firstItemChanged ||\n !pinnedRef.current ||\n hasNewer ||\n firstItemContentTopRef.current == null;\n if (needOffsets) {\n const committedFirstGroupKey = firstItemGroupKeyRef.current;\n const firstGroupEl = committedFirstGroupKey\n ? node.querySelector(`[data-og-group-key=\"${cssEscapeAttribute(committedFirstGroupKey)}\"]`)\n : null;\n firstItemGroupOffsetTopRef.current =\n firstGroupEl instanceof HTMLElement ? firstGroupEl.offsetTop : null;\n const firstItemEl = firstItemId\n ? node.querySelector(`[data-og-item=\"${cssEscapeAttribute(firstItemId)}\"]`)\n : null;\n firstItemContentTopRef.current =\n firstItemId && firstItemEl instanceof HTMLElement\n ? firstItemEl.getBoundingClientRect().top -\n node.getBoundingClientRect().top +\n node.scrollTop\n : null;\n }\n\n // Promise settlement is not itself permission to retry. A receipt-marked\n // accepted page retires its exact owner on this commit even when projection\n // is empty or merges into the same first item. Without that mark, retain\n // the compatibility fallback: a retained prior boundary proves prepend,\n // while a missing prior boundary is forward eviction and merely rebases.\n if (!attempt) {\n return;\n }\n if (!attempt[2]?.committed && attempt[0] === olderBoundaryKey) {\n return;\n }\n if (\n !attempt[2]?.committed &&\n attempt[0] &&\n !sourceItems?.find((entry) => entry.id === attempt[0])\n ) {\n attempt[0] = olderBoundaryKey;\n return;\n }\n if (!attempt[1] || !hasOlder) {\n setUnderfillSettledAttempt((olderLoadAttemptRef.current = null));\n return;\n }\n // Boundary progress retires the request owner. A late settlement from\n // that completed prefetch cannot mutate the new window's cooldown owner.\n olderLoadAttemptRef.current = [olderBoundaryKey, 2];\n rearmOlderPrefetchAfterLeavingTop(node);\n requestOlderIfUnderfilled(node);\n });\n\n // First paint / session remount: keep the scroller hidden, snap to tip for\n // two animation frames (late sync layout), then reveal. Does not change the\n // live tip-follow law used once `revealed` is true.\n useLayoutEffect(() => {\n if (revealed || !allGroups.length) {\n return;\n }\n let cancelled = false;\n let frame2 = 0;\n const park = () => {\n const node = scrollRef.current;\n if (node && autoFollow && pinnedRef.current && !hasNewerRef.current) {\n snapToBottom(node);\n }\n };\n park();\n const frame1 = requestFrame(() => {\n if (cancelled) {\n return;\n }\n park();\n frame2 = requestFrame(() => {\n if (cancelled) {\n return;\n }\n park();\n setRevealed(true);\n });\n });\n return () => {\n cancelled = true;\n cancelFrame(frame1);\n if (frame2) {\n cancelFrame(frame2);\n }\n };\n }, [revealed, allGroups.length, autoFollow, snapToBottom]);\n\n // A cleared timeline (stream identity change) re-arms the reveal + prefetch\n // gate and returns to bottom-follow for the next session's first paint.\n useLayoutEffect(() => {\n if (allGroups.length > 0) {\n return;\n }\n if (revealed) {\n setRevealed(false);\n }\n if (olderPrefetchArmedRef.current) {\n olderPrefetchArmedRef.current = false;\n setOlderPrefetchArmed(false);\n }\n wantPinRef.current = false;\n pendingJumpToStartRef.current = false;\n previousFirstItemIdRef.current = null;\n previousScrollHeightRef.current = 0;\n lastScrollTopRef.current = 0;\n lastMaxScrollRef.current = 0;\n lastScrollHeightRef.current = 0;\n lastClientHeightRef.current = 0;\n firstItemGroupKeyRef.current = null;\n firstItemGroupOffsetTopRef.current = null;\n firstItemContentTopRef.current = null;\n foldMemoryRef.current.clear();\n userMessageDisclosureMemoryRef.current.clear();\n disclosureKeepsUnpinnedRef.current = false;\n clearReaderIntent();\n contentShrinkBaselineRef.current = null;\n seenActivityIdsRef.current.clear();\n applyPinned(true);\n }, [allGroups.length, revealed, applyPinned, clearReaderIntent]);\n\n // Parent commits cover the initial/history-loading cases. Disclosure state\n // changes are child-local, so the ResizeObserver below owns dynamic collapse\n // and expansion after mount.\n useEffect(() => {\n const node = scrollRef.current;\n if (node) {\n requestOlderIfUnderfilled(node);\n }\n });\n\n // Clear the bulk-paint marker a frame after it renders, so rows appended\n // live (streams, new turns) animate exactly as before.\n useLayoutEffect(() => {\n previousBulkFirstKeyRef.current = firstGroupKey;\n if (!bulkRender) {\n return;\n }\n setBulkActive(true);\n const frame = requestFrame(() => setBulkActive(false));\n return () => cancelFrame(frame);\n }, [bulkRender, firstGroupKey]);\n\n // Prefetch older history only after the reader scrolls up from the tip.\n // Once armed, the sentinel trips early so backfill is usually rendered\n // (and its scroll delta corrected) before the reader reaches it. Gated so\n // a short prepend that leaves the sentinel intersecting cannot loop.\n useEffect(() => {\n const root = scrollRef.current;\n const target = topSentinelRef.current;\n if (\n !root ||\n !target ||\n !olderPrefetchArmed ||\n !hasOlder ||\n loadingOlder ||\n !onLoadOlder ||\n typeof IntersectionObserver === \"undefined\"\n ) {\n return;\n }\n const observer = new IntersectionObserver(\n (entries) => {\n const intersecting = entries.some((entry) => entry.isIntersecting);\n if (!intersecting) {\n // Left the top band. A settled ordinary prefetch releases its exact\n // owner here; a still-pending request remains cooling so a quick\n // leave/re-enter cannot overlap it.\n const attempt = olderLoadAttemptRef.current;\n if (attempt?.[1] === 2 || attempt?.[1] === 3) {\n olderLoadAttemptRef.current = null;\n }\n return;\n }\n // Both automatic underfill and ordinary prefetch use one boundary\n // owner. In particular, live growth cannot arm a second sentinel load\n // while the short-window request that preceded it is still pending.\n if (olderLoadAttemptRef.current) {\n return;\n }\n const attempt: OlderLoadAttempt = (olderLoadAttemptRef.current = [olderBoundaryKey, 1]);\n const noProgress = () => {\n if (!scrollRef.current || olderLoadAttemptRef.current !== attempt) {\n return;\n }\n attempt[1] = 3;\n if (root.scrollTop > OLDER_PREFETCH_MARGIN_PX) {\n olderLoadAttemptRef.current = null;\n } else if (maxScrollOf(root) <= 1) {\n attempt[1] = 0;\n setUnderfillSettledAttempt(attempt);\n }\n };\n // Preserve legacy fire-and-forget top-band retries: the callback has\n // synchronously returned, but this visit remains cooling until exit.\n // Only rejection/throw/exact `false` is a no-progress receipt. Other\n // fulfillment retains the pending owner until boundary commit;\n // otherwise a delayed prepend could overlap a same-boundary request.\n if (\n !invokeOlderLoad(onLoadOlder, noProgress, attempt) &&\n olderLoadAttemptRef.current === attempt\n ) {\n olderLoadAttemptRef.current[1] = 2;\n requestOlderIfUnderfilled(root);\n }\n },\n { root, rootMargin: OLDER_PREFETCH_ROOT_MARGIN },\n );\n observer.observe(target);\n return () => observer.disconnect();\n }, [\n firstGroupKey,\n hasOlder,\n loadingOlder,\n olderBoundaryKey,\n olderPrefetchArmed,\n onLoadOlder,\n requestOlderIfUnderfilled,\n ]);\n\n // History view: page forward when the reader nears the bottom of the current\n // non-tip window. Does not pull the whole gap — one density-bounded page.\n useEffect(() => {\n const root = scrollRef.current;\n const target = bottomSentinelRef.current;\n if (\n !root ||\n !target ||\n !hasNewer ||\n loadingNewer ||\n !onLoadNewer ||\n typeof IntersectionObserver === \"undefined\"\n ) {\n return;\n }\n const observer = new IntersectionObserver(\n (entries) => {\n if (entries.some((entry) => entry.isIntersecting)) {\n onLoadNewer();\n }\n },\n { root, rootMargin: \"0px 0px 1200px 0px\" },\n );\n observer.observe(target);\n return () => observer.disconnect();\n }, [hasNewer, loadingNewer, onLoadNewer, firstGroupKey]);\n\n // Late layout that React commits cannot see (images decoding, fonts, code\n // blocks) grows content without a commit. While pinned, soft-follow the tip;\n // unpinned: do nothing — chasing those shifts was the wobble. Coalesce RO\n // into one rAF.\n useEffect(() => {\n const node = scrollRef.current;\n const inner = node?.firstElementChild;\n if (!node || !inner || typeof ResizeObserver === \"undefined\") {\n return;\n }\n const observer = new ResizeObserver(() => {\n if (resizeFollowRafRef.current != null) {\n return;\n }\n resizeFollowRafRef.current = requestFrame(() => {\n resizeFollowRafRef.current = null;\n const current = scrollRef.current;\n if (!current) {\n return;\n }\n requestOlderIfUnderfilled(current);\n if (!autoFollow || !pinnedRef.current || hasNewerRef.current) {\n return;\n }\n // Still unveiling the first tip frame: hard-park (no ease settle).\n if (!revealedRef.current) {\n snapToBottom(current);\n return;\n }\n driveFollow(current);\n });\n });\n observer.observe(inner);\n // The scroller's own box moves the bottom too (window resize, composer\n // growing): clientHeight changes with no inner resize and no commit.\n observer.observe(node);\n return () => {\n observer.disconnect();\n if (resizeFollowRafRef.current != null) {\n cancelFrame(resizeFollowRafRef.current);\n resizeFollowRafRef.current = null;\n }\n };\n }, [autoFollow, driveFollow, requestOlderIfUnderfilled, snapToBottom]);\n\n // Entering a non-tip history window: drop any live pin so the page bottom\n // cannot re-stick follow across loadNewer. Leaving it (the tip window\n // landed): honor a pending Jump-to-latest, or re-pin a reader already parked\n // at what just became the live bottom — paging forward to the tip must not\n // strand them unpinned watching new content grow below.\n useEffect(() => {\n if (hasNewer) {\n stopFollow();\n applyPinned(false);\n return;\n }\n const node = scrollRef.current;\n if (!node) {\n return;\n }\n if (wantPinRef.current) {\n wantPinRef.current = false;\n if (autoFollow) {\n applyPinned(true);\n snapToBottom(node);\n }\n return;\n }\n if (autoFollow && !pinnedRef.current && isNearBottom(node)) {\n applyPinned(true);\n }\n }, [hasNewer, autoFollow, applyPinned, snapToBottom, stopFollow]);\n\n // Pinned: layout/camera recover tip debt; wheel/keys/pointer-arm unpin\n // immediately; extension jumps settle via scrollend (or one-rAF fallback).\n // Do not tip-follow-yank an in-flight unarmed scroll-away — that ate Vimium.\n const onScroll = () => {\n const node = scrollRef.current;\n if (!node) {\n return;\n }\n const previousTop = lastScrollTopRef.current;\n const previousMaxScroll = lastMaxScrollRef.current;\n const nextTop = node.scrollTop;\n const nextMaxScroll = maxScrollOf(node);\n const nextHeight = node.scrollHeight;\n const readerUp = readerScrollUpPx(previousTop, nextTop, previousMaxScroll, nextMaxScroll);\n const maxFell = nextMaxScroll < previousMaxScroll - 1;\n const readerArmed = readerIntentArmRef.current;\n const readerIntentStart = readerIntentStartRef.current;\n const cumulativeReaderUp =\n readerArmed && readerIntentStart\n ? readerScrollUpPx(\n readerIntentStart.scrollTop,\n nextTop,\n readerIntentStart.maxScroll,\n nextMaxScroll,\n )\n : readerUp;\n const heightShrunk =\n followRef.current.lastHeight > 0 &&\n nextHeight < followRef.current.lastHeight - TIP_FOLLOW_SHRINK_EPS_PX;\n // Consume all pending camera-write echoes (browsers may coalesce writes).\n const programmatic = programmaticScrollRef.current > 0;\n if (programmatic) {\n programmaticScrollRef.current = 0;\n }\n if (disclosureKeepsUnpinnedRef.current) {\n stopFollow();\n applyPinned(false);\n syncScrollBaseline(node);\n return;\n }\n\n if (autoFollow && pinnedRef.current && !hasNewer) {\n // Fold / composer / SessionChrome: viewport shrink raises maxScroll without\n // growing content. Must hit tipFollow before we adopt the new clientHeight\n // (the near-bottom branch used to poison lastClientHeight and skip glue).\n const previousClient = followRef.current.lastClientHeight;\n const viewportShrunk =\n previousClient > 0 && node.clientHeight < previousClient - TIP_FOLLOW_SHRINK_EPS_PX;\n // Fold / composer content shrink: compensate before baseline sync so\n // driveFollow still sees the pre-shrink scrollTop (avoid double-subtract).\n if (heightShrunk || maxFell || viewportShrunk) {\n clearReaderIntent();\n clearPendingReaderLeave();\n driveFollow(node);\n return;\n }\n if (programmatic) {\n // Camera-write echo: consume it, sync the SHELL baselines only. The\n // camera's growth baselines (lastHeight / lastClientHeight) belong to\n // tipFollowStep — adopting them here made every echo \"consume\" growth\n // that arrived without a commit (motion/Radix height animations of\n // nested tools, late layout). Echoes fire before rAF callbacks, so the\n // step saw frameGrowth=0, never heated, and the cold ~42px/s settle\n // let bursty growth park the tip under the chrome.\n syncScrollBaseline(node);\n return;\n }\n syncScrollBaseline(node);\n const nearBottomPinned = isNearBottom(node);\n if (nearBottomPinned) {\n clearPendingReaderLeave();\n }\n // Pointer-dragged scroll-up away from tip. Layout churn never arms this.\n if (readerArmed && cumulativeReaderUp > TIP_FOLLOW_READER_UP_EPS_PX && !nearBottomPinned) {\n clearReaderIntent();\n releasePinFromReader(node);\n rearmOlderPrefetchAfterLeavingTop(node);\n return;\n }\n // Tip grew under a still viewport (no reader-up): track the new growth\n // immediately and ease only any debt that already existed.\n // Reader/extension scroll-up in progress: do not yank — scrollend decides.\n // Near-bottom with tipDebt≈0 stays the quiet path (do not broaden follow\n // inside PIN_THRESHOLD — that fights small intentional scroll-ups).\n if (!nearBottomPinned && readerUp <= TIP_FOLLOW_READER_UP_EPS_PX) {\n if (!pendingReaderLeaveRef.current) {\n driveFollow(node);\n }\n } else if (!nearBottomPinned && readerUp > TIP_FOLLOW_READER_UP_EPS_PX) {\n pendingReaderLeaveRef.current = true;\n scheduleLeaveFallback();\n }\n // Near-bottom reader jiggle: stay quiet, and leave the camera's growth\n // baselines alone — adopting them here stole the heat of growth the\n // step had not seen yet (the next driveFollow then settled cold and\n // parked short inside the pin band).\n return;\n }\n\n syncScrollBaseline(node);\n const nearBottom = isNearBottom(node);\n\n // Re-pin only when the reader moved toward/at the tip — not when a fold\n // clamp dragged scrollTop down onto nearBottom.\n const nextPinned =\n !hasNewer && nearBottom && nextTop >= previousTop - TIP_FOLLOW_READER_UP_EPS_PX;\n if (!nextPinned) {\n stopFollow();\n }\n applyPinned(nextPinned);\n // A far-from-bottom scroll while a Jump-to-latest is pending is the reader\n // changing their mind: drop the latch, or a stale one (host rejected or\n // never flipped hasNewer) would fire a surprise pin + snap whenever the\n // reader later pages to the tip themselves. Our own snaps land AT the\n // bottom, so their echoes read nearBottom and keep a live latch.\n if (wantPinRef.current && !nearBottom) {\n wantPinRef.current = false;\n }\n if (nextPinned) {\n return;\n }\n if (!olderPrefetchArmedRef.current) {\n olderPrefetchArmedRef.current = true;\n setOlderPrefetchArmed(true);\n }\n // Re-arm older prefetch only after leaving the top band (scroll down into\n // content). Never re-arm/load from continued scroll toward y=0.\n rearmOlderPrefetchAfterLeavingTop(node);\n };\n\n const onScrollEnd = () => {\n const node = scrollRef.current;\n if (!node) {\n return;\n }\n cancelLeaveFallback();\n if (disclosureKeepsUnpinnedRef.current) {\n programmaticScrollRef.current = 0;\n stopFollow();\n applyPinned(false);\n syncScrollBaseline(node);\n return;\n }\n if (programmaticScrollRef.current > 0) {\n programmaticScrollRef.current = 0;\n syncScrollBaseline(node);\n return;\n }\n releasePinAfterScrollSettled(node);\n };\n\n return (\n <LightboxProvider>\n <FoldMemoryProvider value={foldMemoryRef.current}>\n <SeenActivityIdsProvider value={seenActivityIdsRef.current}>\n <TimelineComputeLabelProvider value={computeLabel ?? null}>\n <EntranceAnimationProvider value={false}>\n <TooltipProvider delayDuration={400}>\n <div className={cn(\"og-root relative flex min-h-0 flex-col\", className)}>\n {onAnnotate ? (\n <Suspense fallback={null}>\n <TimelineAnnotationSelection\n rootRef={scrollRef}\n sources={annotationSources}\n onAnnotate={onAnnotate}\n />\n </Suspense>\n ) : null}\n {/* Pinned: anchoring off so the tip-follow camera owns the motion.\n Unpinned: native scroll anchoring holds the reader's place. */}\n <div\n ref={scrollRef}\n data-og-timeline-scroller=\"\"\n data-og-bottom-follow={autoFollow && pinned && !hasNewer ? \"true\" : \"false\"}\n tabIndex={-1}\n onScroll={onScroll}\n onScrollEnd={onScrollEnd}\n onWheel={onWheel}\n onPointerDown={onPointerDown}\n onKeyDown={onKeyDown}\n style={groups.length > 0 && !revealed ? { visibility: \"hidden\" } : undefined}\n className={cn(\n // tabIndex=-1 is programmatic only — never paint a focus ring on\n // the whole scroller (click + Shift used to flash a blue outline).\n \"min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 py-6 sm:px-6 outline-hidden\",\n autoFollow && pinned && !hasNewer\n ? \"[overflow-anchor:none]\"\n : \"[overflow-anchor:auto]\",\n )}\n >\n <div className=\"relative mx-auto flex w-full max-w-3xl flex-col gap-5\">\n {!groups.length\n ? (emptyState ?? (\n <p className=\"py-10 text-center text-og-menu text-og-fg-subtle\">\n No activity yet.\n </p>\n ))\n : null}\n {hasOlder && olderPrefetchArmed ? (\n // Overlaid, not a layout row: mounting/unmounting the sentinel\n // must never shift content (that shift was itself a wobble).\n <div\n ref={topSentinelRef}\n data-og-top-sentinel=\"\"\n data-og-timeline-chrome=\"\"\n aria-hidden=\"true\"\n className=\"pointer-events-none absolute inset-x-0 top-0 h-px\"\n />\n ) : null}\n {groups.map(({ group, key, entranceEnabled }, index) => {\n return (\n <TimelineGroupEntry\n key={key}\n groupKey={key}\n group={group}\n nextGroup={groups[index + 1]?.group}\n entranceEnabled={entranceEnabled}\n liveEntranceEnabled={\n group.kind === \"activity\" ? !bulkRender : undefined\n }\n context={timelineGroupEntryContext}\n />\n );\n })}\n {groups.length > 0 && trailingState ? (\n <div data-og-timeline-trailing-state=\"\">{trailingState}</div>\n ) : null}\n {hasNewer ? (\n <div\n ref={bottomSentinelRef}\n data-og-bottom-sentinel=\"\"\n data-og-timeline-chrome=\"\"\n aria-hidden=\"true\"\n className=\"h-px w-full\"\n />\n ) : null}\n </div>\n </div>\n <AnimatePresence>\n {loadingOlder ||\n loadingOldest ||\n (hasOlder && onJumpToStart && olderPrefetchArmed) ||\n underfillRetryReady ? (\n // Floating over the scroller (not a timeline row) so showing and\n // hiding it never reflows history under the reader.\n <motion.div\n initial={{ opacity: 0, y: -6 }}\n animate={{ opacity: 1, y: 0 }}\n exit={{ opacity: 0, y: -6 }}\n transition={{ duration: 0.15, ease: \"easeOut\" }}\n data-og-loading-older=\"\"\n aria-live=\"polite\"\n className=\"absolute inset-x-0 top-3 z-10 flex justify-center\"\n >\n {loadingOlder || loadingOldest ? (\n <span className={LOADING_CHIP_CLASS}>\n <span className=\"og-shimmer-text\">\n {loadingOldest ? \"Jumping to start…\" : \"Loading earlier activity…\"}\n </span>\n </span>\n ) : null}\n {hasOlder &&\n !loadingOlder &&\n !loadingOldest &&\n (underfillRetryReady || onJumpToStart) ? (\n <button\n type=\"button\"\n data-og-retry={underfillRetryReady || undefined}\n data-og-jump-to-start={!underfillRetryReady || undefined}\n onClick={() => {\n const node = scrollRef.current;\n if (underfillRetryReady) {\n if (node && underfillRetryReadyRef.current) {\n // AnimatePresence retains this handler during\n // exit. Current authorization plus the exact\n // attempt check prevent stale dispatch.\n requestOlderIfUnderfilled(node, underfillSettledAttempt!);\n }\n return;\n }\n applyPinned(false);\n pendingJumpToStartRef.current = true;\n const seq = ++jumpToStartSeqRef.current;\n void Promise.resolve(onJumpToStart!()).then(\n () => {\n // The commit that swaps in the oldest window consumes\n // the flag against the new DOM; this write covers the\n // already-committed order and the no-window-change\n // case (jumping within the current window).\n const scroller = scrollRef.current ?? node;\n if (scroller) {\n scroller.scrollTop = 0;\n }\n // A host may resolve without ever changing the\n // window (already on the oldest page). Any swap\n // commit runs its layout effect before the next\n // frame, so a flag still armed by then is the\n // no-change case — clear it, or a LATER prepend\n // would spuriously jump the reader to the top.\n requestFrame(() => {\n if (jumpToStartSeqRef.current === seq) {\n pendingJumpToStartRef.current = false;\n }\n });\n },\n () => {\n if (jumpToStartSeqRef.current === seq) {\n pendingJumpToStartRef.current = false;\n }\n },\n );\n }}\n className=\"rounded-full border border-og-border px-3 py-1.5 text-og-control\"\n >\n {underfillRetryReady ? \"Retry earlier activity\" : \"Jump to start\"}\n </button>\n ) : null}\n </motion.div>\n ) : null}\n </AnimatePresence>\n <AnimatePresence>\n {loadingNewer ? (\n <motion.div\n initial={{ opacity: 0, y: 6 }}\n animate={{ opacity: 1, y: 0 }}\n exit={{ opacity: 0, y: 6 }}\n transition={{ duration: 0.15, ease: \"easeOut\" }}\n data-og-loading-newer=\"\"\n aria-live=\"polite\"\n className=\"pointer-events-none absolute inset-x-0 bottom-14 z-10 flex justify-center\"\n >\n <span className={LOADING_CHIP_CLASS}>\n <span className=\"og-shimmer-text\">Loading later activity…</span>\n </span>\n </motion.div>\n ) : null}\n </AnimatePresence>\n <AnimatePresence>\n {((!pinned && autoFollow) || hasNewer || canSkipTipCatchup) && autoFollow ? (\n <motion.button\n type=\"button\"\n data-og-jump-to-latest=\"\"\n initial={{ opacity: 0, y: 8 }}\n animate={{ opacity: 1, y: 0 }}\n exit={{ opacity: 0, y: 8 }}\n transition={{ duration: 0.15, ease: \"easeOut\" }}\n onClick={() => {\n disclosureKeepsUnpinnedRef.current = false;\n if (hasNewer) {\n // Do not pin against the current history page — its bottom\n // is not the tip. The pin + snap run when the tip window\n // actually lands (`hasNewer` flips false).\n wantPinRef.current = true;\n const node = scrollRef.current;\n if (onJumpToLatest) {\n void Promise.resolve(onJumpToLatest()).then(\n () => {\n // Covers a host that flipped hasNewer before\n // resolving; otherwise the tip-window commit\n // consumes the flag.\n const current = scrollRef.current;\n if (current && wantPinRef.current && !hasNewerRef.current) {\n wantPinRef.current = false;\n applyPinned(true);\n snapToBottom(current);\n }\n },\n () => {\n // The tip reload failed (ordinary network error):\n // an armed latch would fire a surprise snap when\n // the reader later pages to the tip themselves.\n wantPinRef.current = false;\n },\n );\n } else if (node) {\n // No tip reload available: jump within the in-memory\n // window so the newer sentinel can page forward; the\n // latch pins if the tip window eventually lands.\n snapToBottom(node);\n }\n return;\n }\n const node = scrollRef.current;\n if (node) {\n applyPinned(true);\n snapToBottom(node);\n }\n }}\n className={cn(\n \"absolute inset-x-0 bottom-4 mx-auto w-fit\",\n \"inline-flex items-center gap-1.5 rounded-full border border-og-border bg-og-surface-3/90 px-3 py-1.5\",\n \"text-og-control font-medium text-og-fg shadow-og-md backdrop-blur\",\n \"hover:border-og-border-strong\",\n )}\n >\n <ArrowDownIcon className=\"size-3.5\" />\n Jump to latest\n </motion.button>\n ) : null}\n </AnimatePresence>\n </div>\n </TooltipProvider>\n </EntranceAnimationProvider>\n </TimelineComputeLabelProvider>\n </SeenActivityIdsProvider>\n </FoldMemoryProvider>\n </LightboxProvider>\n );\n}\n\ntype KeyedTimelineGroup = {\n group: TimelineGroup;\n key: string;\n entranceEnabled: boolean;\n};\n\nfunction timelineGroupsRenderEqual(previous: TimelineGroup, next: TimelineGroup): boolean {\n try {\n return dequal(previous, next);\n } catch {\n // Consumer-owned `unknown` payloads may be proxies/getters. Equality is an\n // optimization only; a hostile comparator surface must fall back to the\n // authoritative new group rather than taking down the timeline render.\n return false;\n }\n}\n\n/**\n * Projection can legitimately change a group's content-derived key while\n * retaining its existing rows. The common pagination case is an older activity\n * item merging into the first activity group; live appends grow the same group\n * from the other side. Match the new authoritative groups to the previous\n * committed groups by their durable item IDs so both the React key and the\n * progressive-window anchor survive either change.\n */\nfunction useStableTimelineGroupKeys(\n allGroups: TimelineGroup[],\n entranceEnabled: boolean,\n): KeyedTimelineGroup[] {\n const previousRef = useRef<KeyedTimelineGroup[]>([]);\n const keyedGroups = useMemo(() => {\n const previousByItemId = new Map<string, KeyedTimelineGroup>();\n for (const previous of previousRef.current) {\n for (const itemId of timelineGroupItemIds(previous.group)) {\n previousByItemId.set(itemId, previous);\n }\n }\n\n const usedKeys = new Set<string>();\n return allGroups.map((group, index) => {\n const itemIds = timelineGroupItemIds(group);\n let retainedGroup: KeyedTimelineGroup | undefined;\n for (const itemId of itemIds) {\n const previous = previousByItemId.get(itemId);\n // Retain only same-kind matches. Activity → turn wrap must NOT keep the\n // activity chip's React key: that reused a collapsed TurnSummary and\n // skipped the settle beat (insta-collapse / content flash).\n if (previous && previous.group.kind === group.kind && !usedKeys.has(previous.key)) {\n retainedGroup = previous;\n break;\n }\n }\n\n const canonicalKey = timelineGroupKey(group);\n let key = retainedGroup?.key ?? canonicalKey;\n let collision = 0;\n while (usedKeys.has(key)) {\n key = `${canonicalKey}:${index}:${collision}`;\n collision += 1;\n }\n usedKeys.add(key);\n return {\n group:\n retainedGroup && timelineGroupsRenderEqual(retainedGroup.group, group)\n ? retainedGroup.group\n : group,\n key,\n entranceEnabled: retainedGroup?.entranceEnabled ?? entranceEnabled,\n };\n });\n }, [allGroups, entranceEnabled]);\n\n useLayoutEffect(() => {\n previousRef.current = keyedGroups;\n }, [keyedGroups]);\n\n return keyedGroups;\n}\n\nfunction requestFrame(callback: FrameRequestCallback): number {\n if (typeof requestAnimationFrame === \"function\") {\n return requestAnimationFrame(callback);\n }\n return window.setTimeout(() => callback(performance.now()), 16);\n}\n\nfunction cancelFrame(id: number): void {\n if (typeof cancelAnimationFrame === \"function\") {\n cancelAnimationFrame(id);\n return;\n }\n window.clearTimeout(id);\n}\n\ntype TimelineGroupRenderBoundaryProps = {\n children: ReactNode;\n resetKeys: readonly unknown[];\n};\n\ntype TimelineGroupRenderBoundaryState = {\n failed: boolean;\n resetKeys: readonly unknown[];\n};\n\nfunction timelineRenderResetKeysChanged(\n previous: readonly unknown[],\n next: readonly unknown[],\n): boolean {\n return (\n previous.length !== next.length || previous.some((key, index) => !Object.is(key, next[index]))\n );\n}\n\n/**\n * A malformed historical payload or consumer renderer must not take down the\n * entire conversation. Keep the boundary outside the row component so React\n * can replace an invalid element type (error #130) with a bounded fallback.\n */\nclass TimelineGroupRenderBoundary extends Component<\n TimelineGroupRenderBoundaryProps,\n TimelineGroupRenderBoundaryState\n> {\n state: TimelineGroupRenderBoundaryState = {\n failed: false,\n resetKeys: this.props.resetKeys,\n };\n\n static getDerivedStateFromError(): Partial<TimelineGroupRenderBoundaryState> {\n return { failed: true };\n }\n\n static getDerivedStateFromProps(\n props: TimelineGroupRenderBoundaryProps,\n state: TimelineGroupRenderBoundaryState,\n ): Partial<TimelineGroupRenderBoundaryState> | null {\n if (timelineRenderResetKeysChanged(state.resetKeys, props.resetKeys)) {\n return { failed: false, resetKeys: props.resetKeys };\n }\n return null;\n }\n\n render(): ReactNode {\n if (this.state.failed) {\n return (\n <div\n data-testid=\"timeline-group-render-error\"\n role=\"status\"\n className=\"flex items-start gap-2 rounded-lg border border-og-border bg-og-surface-muted px-3 py-2 text-og-menu text-og-fg-muted\"\n >\n <TriangleAlertIcon aria-hidden=\"true\" className=\"mt-0.5 size-4 shrink-0\" />\n <div>\n <p className=\"font-medium text-og-fg\">Timeline item unavailable</p>\n <p>\n This item could not be displayed. The rest of the conversation is still available.\n </p>\n </div>\n </div>\n );\n }\n return this.props.children;\n }\n}\n\ntype TimelineGroupEntryProps = {\n groupKey: string;\n group: TimelineGroup;\n nextGroup?: TimelineGroup | undefined;\n entranceEnabled: boolean;\n liveEntranceEnabled?: boolean | undefined;\n context: TimelineGroupEntryContext;\n};\n\ntype TimelineGroupEntryContext = {\n userMessageDisclosureContext: UserMessageDisclosureContextValue;\n behavior: TimelineGroupBehaviorProps;\n};\n\ntype TimelineGroupBehaviorProps = {\n renderMessageText: MessageTimelineProps[\"renderMessageText\"];\n onOpenSession: MessageTimelineProps[\"onOpenSession\"];\n onMemoryClick: MessageTimelineProps[\"onMemoryClick\"];\n onReconnect: MessageTimelineProps[\"onReconnect\"];\n resolveProviderLogo: MessageTimelineProps[\"resolveProviderLogo\"];\n toolRegistry: ToolRegistry;\n loadRetainedScreenshot: MessageTimelineProps[\"loadRetainedScreenshot\"];\n loadRetainedArtifact: MessageTimelineProps[\"loadRetainedArtifact\"];\n loadVideoArtifactPlayback: MessageTimelineProps[\"loadVideoArtifactPlayback\"];\n turnSummary: MessageTimelineProps[\"turnSummary\"];\n};\n\n/**\n * Keep the complete settled-row shell behind one shallow memo boundary. A\n * prepend still reconciles the keyed list, but render-equivalent suffix groups\n * skip their providers, error boundaries, disclosure wrappers, and row trees.\n */\nconst TimelineGroupEntry = memo(function TimelineGroupEntry({\n groupKey,\n group,\n nextGroup,\n entranceEnabled,\n liveEntranceEnabled,\n context,\n}: TimelineGroupEntryProps) {\n const { behavior, userMessageDisclosureContext } = context;\n const contextCompactionCount =\n group.kind === \"turn\"\n ? (group.contextCompactionCount ?? 0)\n : group.kind === \"activity\" &&\n nextGroup?.kind === \"item\" &&\n nextGroup.item.kind === \"context-compaction\" &&\n nextGroup.item.phase === \"compacted\"\n ? 1\n : 0;\n return (\n <div data-og-timeline-group-anchor=\"\" data-og-group-key={groupKey}>\n <EntranceAnimationProvider value={entranceEnabled} liveValue={liveEntranceEnabled}>\n <TimelineGroupRenderBoundary resetKeys={[group, behavior]}>\n <UserMessageDisclosureProvider value={userMessageDisclosureContext}>\n <TimelineGroupView\n {...behavior}\n group={group}\n foldLiveCluster={isAgentProgress(nextGroup)}\n trailingAgentText={trailingAgentTextAfterTurn(group, nextGroup)}\n contextCompactionCount={\n contextCompactionCount > 0 ? contextCompactionCount : undefined\n }\n />\n </UserMessageDisclosureProvider>\n </TimelineGroupRenderBoundary>\n </EntranceAnimationProvider>\n </div>\n );\n});\n\n// The full loaded window stays mounted, so settled history rows must be cheap\n// on every commit: the stable-key projection reuses render-equivalent group\n// objects, so memo skips them. Changed projection content receives a new group\n// object, and behavior/callback changes are separate props, so ordinary\n// streaming and host updates still invalidate immediately.\nconst TimelineGroupView = memo(function TimelineGroupView({\n group,\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n resolveProviderLogo,\n toolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n turnSummary,\n insideTurn = false,\n nestClusterChips = false,\n foldLiveCluster = false,\n trailingAgentText,\n contextCompactionCount,\n}: {\n group: TimelineGroup;\n renderMessageText?:\n | ((text: string, item: AgentMessageItem | UserMessageItem) => ReactNode)\n | undefined;\n onOpenSession?: ((sessionId: string) => void) | undefined;\n onMemoryClick?: ((memoryId: string) => void) | undefined;\n onReconnect?: ((item: AuthNeededItem) => void | Promise<void>) | undefined;\n resolveProviderLogo?: ((providerDomain: string) => string | null | undefined) | undefined;\n toolRegistry: ToolRegistry;\n loadRetainedScreenshot?: RetainedScreenshotLoader | undefined;\n loadRetainedArtifact?: RetainedArtifactLoader | undefined;\n loadVideoArtifactPlayback?: VideoArtifactPlaybackLoader | undefined;\n turnSummary?: TurnSummaryOptions | undefined;\n /** A completed cluster of a still-RUNNING turn (not the live tail) folds\n behind a neutral chip — the one place activity without an outcome still\n folds, bounding the DOM of days-long autonomous turns. */\n foldLiveCluster?: boolean;\n /** Rendering inside an expanded turn group: the outer chip already owns the\n failure surface, so nested chips stay tinted but quiet (no repeated\n failure text, no auto-open) — one loud error, N calm sub-expands. */\n insideTurn?: boolean;\n /**\n * Parent turn has ≥2 foldable activity clusters. Only then do we wrap settled\n * clusters in nested chips — a single cluster under \"N steps\" is redundant.\n * During outer settle chrome, nested chips stay force-open (structure kept,\n * height stable) instead of flat-mapping to bare rails.\n */\n nestClusterChips?: boolean;\n /**\n * Final agent answer extracted as a sibling after a settled turn — folded\n * into \"Copy turn\" so the chip copies the whole assistant reply, not only\n * mid-turn narration still inside the fold.\n */\n trailingAgentText?: string | undefined;\n /** Secondary chip facet when this fold sits next to a compaction landmark. */\n contextCompactionCount?: number | undefined;\n}) {\n const enter = useEntranceAnimation();\n const settleChrome = useTurnSettleOpen();\n const foldMemory = useFoldMemory();\n // Settled (or live-fold) activity clusters get a chip. Inside an expanded\n // turn that is the second layer — quiet nested chips under the outer turn\n // summary when contiguous activity naturally clusters (≥2 only).\n const activityShouldFold =\n group.kind === \"activity\" && !!(group.outcome || (foldLiveCluster && clusterIsSettled(group)));\n const containsGeneratedImage = timelineGroupContainsGeneratedImage(group);\n // Latch live→folded so a top-level shell that was already mounted open can\n // start the settle beat without remounting bare rail → wrapper.\n const liveActivitySettle = useLiveSettleFold(activityShouldFold && !insideTurn);\n const turnDefaultOpen =\n !insideTurn &&\n group.kind === \"turn\" &&\n (group.outcome === \"failed\" ||\n timelineGroupContainsAuthNeeded(group) ||\n containsGeneratedImage);\n // activity-* → turn-* remount: carry resting state so settleFold does not\n // re-open a chip the reader already watched collapse.\n if (group.kind === \"turn\" && foldMemory && !insideTurn) {\n inheritFoldRestingState(\n foldMemory,\n group.id,\n group.groups.flatMap((child) => (child.kind === \"activity\" ? [child.id] : [])),\n );\n }\n const settleFold =\n group.kind === \"turn\" ? !!(enter && !insideTurn && !turnDefaultOpen) : liveActivitySettle;\n switch (group.kind) {\n case \"activity\":\n if (insideTurn) {\n // Nested chips whenever the parent has ≥2 clusters. During outer settle\n // chrome they stay force-open so structure is visible and height stays\n // stable through collapse — never flat-map to bare rails (that flash\n // was the \"inner steps vanish then reappear nested\" bug). Key flips\n // when chrome clears so they remount closed inside the already-hidden\n // parent (safe; mid-collapse remount of closed chips was the snap).\n // foldKey memory overrides the force-open: a cluster that already\n // settled closed pre-wrap was showing as a CHIP, so mounting it closed\n // is both the stable height and the honest state — force-opening it\n // was the \"already-collapsed cluster auto-expands at the end\" reopen.\n const useNestedChip = nestClusterChips && activityShouldFold && !containsGeneratedImage;\n if (!useNestedChip) {\n return (\n <ActivityRail\n items={group.items}\n onOpenSession={onOpenSession}\n onMemoryClick={onMemoryClick}\n toolRegistry={toolRegistry}\n loadRetainedScreenshot={loadRetainedScreenshot}\n loadRetainedArtifact={loadRetainedArtifact}\n bare\n />\n );\n }\n return (\n <TurnSummary\n key={settleChrome ? \"settle\" : \"rest\"}\n items={group.items}\n outcome={group.outcome}\n failureText={undefined}\n bare\n defaultOpen={settleChrome ? true : undefined}\n foldKey={group.id}\n facets={turnSummary?.facets}\n contextCompactionCount={contextCompactionCount}\n >\n <ActivityRail\n items={group.items}\n onOpenSession={onOpenSession}\n onMemoryClick={onMemoryClick}\n toolRegistry={toolRegistry}\n loadRetainedScreenshot={loadRetainedScreenshot}\n loadRetainedArtifact={loadRetainedArtifact}\n bare\n />\n </TurnSummary>\n );\n }\n // Always the same TurnSummary shell while live so mid-turn fold only\n // flips settleFold (collapse) instead of remounting bare rail → wrapper.\n return (\n <TurnSummary\n items={group.items}\n outcome={group.outcome}\n failureText={group.failureText}\n defaultOpen={!activityShouldFold || group.outcome === \"failed\" ? true : undefined}\n foldKey={group.id}\n facets={turnSummary?.facets}\n settleFold={settleFold}\n contextCompactionCount={contextCompactionCount}\n >\n <FoldBody>\n <TurnRailFrame>\n <ActivityRail\n items={group.items}\n onOpenSession={onOpenSession}\n onMemoryClick={onMemoryClick}\n toolRegistry={toolRegistry}\n loadRetainedScreenshot={loadRetainedScreenshot}\n loadRetainedArtifact={loadRetainedArtifact}\n bare\n />\n </TurnRailFrame>\n </FoldBody>\n </TurnSummary>\n );\n case \"turn\": {\n const activityItems = flattenActivityItems(group.groups);\n // Second-layer chips only when there are natural multi-cluster seams —\n // otherwise the outer turn chip alone is enough (\"N steps\" wrapping one\n // more \"N steps\" was the redundant double fold).\n const nestClusters = foldableActivityClusterCount(group.groups) >= 2;\n const turnCopyText = collectTurnCopyText(group.groups, trailingAgentText);\n const body = group.groups.map((child) => {\n const key = timelineGroupKey(child);\n return (\n <TimelineGroupRenderBoundary\n key={key}\n resetKeys={[\n child,\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n resolveProviderLogo,\n toolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n turnSummary,\n ]}\n >\n <TimelineGroupView\n group={child}\n renderMessageText={renderMessageText}\n onOpenSession={onOpenSession}\n onMemoryClick={onMemoryClick}\n onReconnect={onReconnect}\n resolveProviderLogo={resolveProviderLogo}\n toolRegistry={toolRegistry}\n loadRetainedScreenshot={loadRetainedScreenshot}\n loadRetainedArtifact={loadRetainedArtifact}\n loadVideoArtifactPlayback={loadVideoArtifactPlayback}\n turnSummary={turnSummary}\n insideTurn\n nestClusterChips={nestClusters}\n />\n </TimelineGroupRenderBoundary>\n );\n });\n return (\n <TurnSummary\n items={activityItems}\n outcome={group.outcome}\n failureText={insideTurn ? undefined : group.failureText}\n durationMs={durationBetween(group.startedAt, group.endedAt)}\n defaultOpen={turnDefaultOpen ? true : undefined}\n bare={insideTurn}\n foldKey={group.id}\n facets={turnSummary?.facets}\n settleFold={settleFold}\n copyText={insideTurn ? undefined : turnCopyText}\n contextCompactionCount={contextCompactionCount ?? group.contextCompactionCount}\n >\n <FoldBody>\n {insideTurn ? (\n // A nested turn is already on an ancestor rail — its body just stacks\n // flush (the bare-node body already indents it), so no second rule.\n <div className=\"flex flex-col gap-4\">{body}</div>\n ) : (\n <TurnRailFrame>{body}</TurnRailFrame>\n )}\n </FoldBody>\n </TurnSummary>\n );\n }\n case \"item\":\n return (\n <TimelineRow\n item={group.item}\n renderMessageText={renderMessageText}\n onReconnect={onReconnect}\n resolveProviderLogo={resolveProviderLogo}\n onOpenSession={onOpenSession}\n loadVideoArtifactPlayback={loadVideoArtifactPlayback}\n />\n );\n }\n});\n\n/**\n * Body under a turn/activity chip. Remount flashes are gated by the timeline\n * seen-activity-id map (not by killing entrance): FoldBody used to force\n * entrance off, which made every live tool pop with no fade.\n */\nfunction FoldBody({ children }: { children: ReactNode }) {\n return <>{children}</>;\n}\n\n/** Stable left rule for turn/activity bodies — always present so settle wrap\n never inserts or removes the rail chrome. */\nfunction TurnRailFrame({ children }: { children: ReactNode }) {\n return (\n <div className=\"flex flex-col gap-4 border-l-2 border-og-border pl-3 sm:pl-4\">{children}</div>\n );\n}\n\n/**\n * True once THIS component instance has seen its group transition from\n * unfolded to folded — i.e. the reader watched the rows live and the fold is\n * new information worth choreographing. Latched: TurnSummary captures the flag\n * at its own mount (the flip render), so later prop churn is inert. History\n * that mounts already folded initializes folded and never latches.\n */\nfunction useLiveSettleFold(folded: boolean): boolean {\n const previousFoldedRef = useRef(folded);\n const latchedRef = useRef(false);\n if (!previousFoldedRef.current && folded) {\n latchedRef.current = true;\n }\n useLayoutEffect(() => {\n previousFoldedRef.current = folded;\n });\n return latchedRef.current;\n}\n\nfunction timelineGroupKey(group: TimelineGroup): string {\n switch (group.kind) {\n case \"item\":\n return group.item.kind === \"user-message\" && group.item.reconciliationKey\n ? group.item.reconciliationKey\n : group.item.id;\n case \"activity\":\n return group.id;\n case \"turn\":\n return group.id;\n }\n}\n\nfunction timelineGroupContainsAuthNeeded(group: TimelineGroup): boolean {\n switch (group.kind) {\n case \"item\":\n return group.item.kind === \"auth-needed\";\n case \"activity\":\n return false;\n case \"turn\":\n return group.groups.some(timelineGroupContainsAuthNeeded);\n }\n}\n\n/** Generated images are primary user-visible output, not incidental activity. */\nfunction timelineGroupContainsGeneratedImage(group: TimelineGroup): boolean {\n switch (group.kind) {\n case \"item\":\n return false;\n case \"activity\":\n return group.items.some(\n (item) => item.kind === \"tool-call\" && item.name === \"generate_image\",\n );\n case \"turn\":\n return group.groups.some(timelineGroupContainsGeneratedImage);\n }\n}\n\nfunction timelineGroupItemIds(group: TimelineGroup): string[] {\n switch (group.kind) {\n case \"item\":\n return [group.item.id];\n case \"activity\":\n return group.items.map((item) => item.id);\n case \"turn\":\n return group.groups.flatMap(timelineGroupItemIds);\n }\n}\n\n/** The agent has moved PAST a cluster only when what follows is more agent\n progress — new activity, a settled turn, or narration. A waiting notice\n (approval pause), a pending queued message, a goal pill, or nothing at all\n do NOT advance the story, and folding on them would hide exactly the work\n the reader needs in view. */\nfunction isAgentProgress(next: TimelineGroup | undefined): boolean {\n if (!next) {\n return false;\n }\n return (\n next.kind === \"activity\" ||\n next.kind === \"turn\" ||\n (next.kind === \"item\" && next.item.kind === \"agent-message\")\n );\n}\n\n/** No item still running or streaming — the only state safe to fold live.\n Position alone is a broken proxy: a pending queued message (or any trailing\n item) can sit after the ACTIVE cluster, which must never fold mid-work. */\nfunction clusterIsSettled(group: Extract<TimelineGroup, { kind: \"activity\" }>): boolean {\n return group.items.every((item) => {\n if (item.kind === \"reasoning\") {\n return !item.streaming;\n }\n // Memory writes and fleet observations are discrete, already-settled events.\n if (item.kind === \"memory\" || item.kind === \"fleet-decision\") {\n return true;\n }\n return item.status !== \"running\";\n });\n}\n\n/** Settled activity clusters that could become nested chips under a turn. */\nfunction foldableActivityClusterCount(groups: readonly TimelineGroup[]): number {\n let count = 0;\n for (const child of groups) {\n if (child.kind === \"activity\" && (child.outcome || clusterIsSettled(child))) {\n count += 1;\n }\n }\n return count;\n}\n\nfunction flattenActivityItems(groups: TimelineGroup[]): ActivityItem[] {\n const items: ActivityItem[] = [];\n for (const group of groups) {\n if (group.kind === \"activity\") {\n items.push(...group.items);\n } else if (group.kind === \"turn\") {\n items.push(...flattenActivityItems(group.groups));\n }\n }\n return items;\n}\n\n/** Assistant prose inside a turn fold (mid-turn narration), joined for copy. */\nfunction collectAgentMessageText(groups: readonly TimelineGroup[]): string {\n const parts: string[] = [];\n for (const group of groups) {\n if (group.kind === \"item\" && group.item.kind === \"agent-message\") {\n const text = group.item.text.trim();\n if (text.length > 0) {\n parts.push(text);\n }\n } else if (group.kind === \"turn\") {\n const nested = collectAgentMessageText(group.groups);\n if (nested.length > 0) {\n parts.push(nested);\n }\n }\n }\n return parts.join(\"\\n\\n\");\n}\n\n/** Non-null turnIds projected into a turn body (activity + nested messages). */\nfunction collectTurnIdsFromGroups(groups: readonly TimelineGroup[]): Set<string> {\n const ids = new Set<string>();\n for (const group of groups) {\n if (group.kind === \"item\") {\n const turnId = \"turnId\" in group.item ? group.item.turnId : null;\n if (typeof turnId === \"string\" && turnId.length > 0) {\n ids.add(turnId);\n }\n } else if (group.kind === \"activity\") {\n for (const item of group.items) {\n if (item.turnId) {\n ids.add(item.turnId);\n }\n }\n } else if (group.kind === \"turn\") {\n for (const nested of collectTurnIdsFromGroups(group.groups)) {\n ids.add(nested);\n }\n }\n }\n return ids;\n}\n\n/**\n * Settled turns lift the final agent answer out as a sibling group. Include it\n * in \"Copy turn\" when present so the chip copies the full assistant reply.\n * Fenced by turnId so the next turn's answer is never stolen.\n */\nexport function trailingAgentTextAfterTurn(\n group: TimelineGroup,\n next: TimelineGroup | undefined,\n): string | undefined {\n if (group.kind !== \"turn\") {\n return undefined;\n }\n if (next?.kind === \"item\" && next.item.kind === \"agent-message\") {\n const turnIds = collectTurnIdsFromGroups(group.groups);\n // Degenerate body with no turnIds: do not guess — safer than lifting wrong.\n if (!turnIds.size) {\n return undefined;\n }\n if (!next.item.turnId || !turnIds.has(next.item.turnId)) {\n return undefined;\n }\n const text = next.item.text.trim();\n return text.length > 0 ? text : undefined;\n }\n return undefined;\n}\n\nfunction collectTurnCopyText(\n groups: readonly TimelineGroup[],\n trailingAgentText: string | undefined,\n): string | undefined {\n const parts = [collectAgentMessageText(groups), trailingAgentText?.trim() ?? \"\"].filter(\n (part) => part.length > 0,\n );\n if (!parts.length) {\n return undefined;\n }\n return parts.join(\"\\n\\n\");\n}\n\nfunction durationBetween(startedAt: string, endedAt: string): number | undefined {\n const started = Date.parse(startedAt);\n const ended = Date.parse(endedAt);\n if (!Number.isFinite(started) || !Number.isFinite(ended) || ended < started) {\n return undefined;\n }\n return ended - started;\n}\n\n/* --- single rows ------------------------------------------------------------ */\n\n/**\n * Render one non-activity timeline item (chat message, status divider, goal\n * landmark, notice). Exported so the component demo draws the EXACT same rows as\n * the live app — no forked bubble/goal markup.\n */\nexport function TimelineRow({\n item,\n renderMessageText,\n onReconnect,\n resolveProviderLogo,\n onOpenSession,\n loadVideoArtifactPlayback,\n}: {\n item: TimelineItem;\n renderMessageText?:\n | ((text: string, item: AgentMessageItem | UserMessageItem) => ReactNode)\n | undefined;\n onReconnect?: ((item: AuthNeededItem) => void | Promise<void>) | undefined;\n resolveProviderLogo?: ((providerDomain: string) => string | null | undefined) | undefined;\n onOpenSession?: ((sessionId: string) => void) | undefined;\n loadVideoArtifactPlayback?: VideoArtifactPlaybackLoader | undefined;\n}) {\n switch (item.kind) {\n case \"user-message\":\n return <UserMessageRow item={item} renderMessageText={renderMessageText} />;\n case \"human-input\":\n return <HumanInputConversationRow item={item} />;\n case \"agent-message\":\n return <AgentMessageRow item={item} renderMessageText={renderMessageText} />;\n case \"worker-completion\":\n return <WorkerCompletionRow item={item} onOpenSession={onOpenSession} />;\n case \"session-status\":\n return <SessionStatusRow item={item} />;\n case \"goal\":\n return <GoalRow item={item} />;\n case \"machine-input-batch\":\n return (\n <MachineInputBatchRow item={item} loadVideoArtifactPlayback={loadVideoArtifactPlayback} />\n );\n case \"notice\":\n return <NoticeRow item={item} />;\n case \"context-compaction\":\n return <CompactionRow item={item} />;\n case \"auth-needed\":\n return (\n <AuthNeededRow\n item={item}\n onReconnect={onReconnect}\n resolveProviderLogo={resolveProviderLogo}\n />\n );\n default:\n return null;\n }\n}\n\nconst COMPACTION_TRIGGER_LABEL: Record<NonNullable<ContextCompactionItem[\"trigger\"]>, string> = {\n auto: \"Auto\",\n operator: \"Manual\",\n proactive: \"Auto\",\n overflow: \"Overflow\",\n};\n\nfunction CompactionRow({ item }: { item: ContextCompactionItem }) {\n const enter = useEntranceAnimation();\n const trigger =\n item.trigger && item.phase !== \"started\" ? COMPACTION_TRIGGER_LABEL[item.trigger] : null;\n const before =\n item.estimatedTokensBefore != null\n ? Math.round(item.estimatedTokensBefore).toLocaleString(\"en-US\")\n : null;\n const after =\n item.estimatedTokensAfter != null\n ? Math.round(item.estimatedTokensAfter).toLocaleString(\"en-US\")\n : null;\n const title =\n item.phase === \"started\"\n ? \"Compacting conversation history…\"\n : item.phase === \"compacted\"\n ? before && after\n ? `Conversation history compacted · ~${before} → ~${after} estimated history tokens`\n : \"Conversation history compacted\"\n : \"Couldn’t compact conversation history\";\n const subtitle =\n item.phase === \"compacted\"\n ? \"Chat history above is unchanged\"\n : item.phase === \"skipped\"\n ? compactionSkipSubtitle(item.skipReason)\n : null;\n const pill =\n item.phase === \"skipped\" && item.skipReason === \"summarization_failed\"\n ? \"border-og-status-failed/35 bg-og-status-failed/10 text-og-status-failed\"\n : item.phase === \"started\"\n ? WAITING_PILL_CLASS\n : \"border-og-border bg-og-surface-1 text-og-fg-muted\";\n return (\n <div className={cn(enter && \"animate-og-enter\", \"flex justify-center\")}>\n <div\n className={cn(\n \"inline-flex max-w-full flex-col items-center gap-0.5 rounded-full border px-3 py-1.5 text-og-sm\",\n pill,\n )}\n role=\"status\"\n >\n <span className=\"inline-flex max-w-full items-center gap-1.5\">\n <ShrinkIcon className=\"size-3.5 shrink-0\" />\n <span className=\"truncate\">\n {title}\n {trigger ? ` · ${trigger}` : \"\"}\n </span>\n </span>\n {subtitle ? <span className=\"truncate text-og-xs opacity-80\">{subtitle}</span> : null}\n </div>\n </div>\n );\n}\n\nfunction compactionSkipSubtitle(reason: string | null): string {\n switch (reason) {\n case \"no_history\":\n return \"No active history to compact\";\n case \"replacement_not_smaller\":\n return \"Checkpoint would not reduce memory size\";\n case \"replacement_unchanged\":\n return \"Checkpoint made no progress\";\n case \"summarization_failed\":\n return \"Request it again to retry. Chat history is unchanged.\";\n default:\n return \"Compaction was not needed. Chat history is unchanged.\";\n }\n}\n\n/** Hover-reveal clock beside the copy control (sent / finished). */\nfunction MessageFooterTime({ occurredAt }: { occurredAt: string }) {\n return (\n <time\n dateTime={occurredAt}\n className={cn(\n \"shrink-0 tabular-nums text-og-xs text-og-fg-subtle\",\n \"opacity-0 transition-opacity duration-150\",\n \"group-hover/copy:opacity-100 group-focus-within/copy:opacity-100 pointer-coarse:opacity-100\",\n )}\n >\n {formatClockTime(occurredAt)}\n </time>\n );\n}\n\nfunction UserMessageRow({\n item,\n renderMessageText,\n}: {\n item: UserMessageItem;\n renderMessageText?:\n | ((text: string, item: AgentMessageItem | UserMessageItem) => ReactNode)\n | undefined;\n}) {\n const enter = useEntranceAnimation();\n const deliveryFailed = item.delivery?.state === \"failed\";\n return (\n <div className={cn(enter && \"animate-og-enter\", \"flex justify-end\")}>\n <div className=\"flex max-w-[85%] min-w-0 flex-col items-end gap-1\">\n <CopyHoverFrame\n copyText={\n item.text ||\n (item.annotations ?? [])\n .map((annotation) => `${annotation.quote}\\n${annotation.note}`)\n .join(\"\\n\\n\")\n }\n label=\"Copy message\"\n className=\"w-fit max-w-full min-w-0\"\n trailing={<MessageFooterTime occurredAt={item.occurredAt} />}\n >\n <div className={MESSAGE_BUBBLE_CLASS}>\n {item.text ? (\n <div data-og-annotation-source-key={item.annotationSource?.eventId}>\n {renderMessageText ? (\n renderMessageText(item.text, item)\n ) : (\n <UserMessageBody messageId={item.id} text={item.text}>\n <Markdown>{item.text}</Markdown>\n </UserMessageBody>\n )}\n </div>\n ) : null}\n {(item.annotations?.length ?? 0) > 0 ? (\n <TimelineAnnotationsChip\n annotations={item.annotations ?? []}\n className={item.text ? \"mt-2\" : undefined}\n />\n ) : null}\n </div>\n </CopyHoverFrame>\n {deliveryFailed ? (\n <div\n role=\"status\"\n className=\"flex max-w-full items-center gap-2 px-1 text-og-xs text-og-status-failed\"\n >\n <span className=\"inline-flex items-center gap-1\" title={item.delivery?.error}>\n <TriangleAlertIcon className=\"size-3.5 shrink-0\" aria-hidden=\"true\" />\n <span>Message not sent</span>\n </span>\n {item.delivery?.onRetry ? (\n <button\n type=\"button\"\n className=\"font-medium text-og-status-failed underline decoration-og-status-failed/50 underline-offset-2 hover:text-og-fg\"\n onClick={item.delivery.onRetry}\n >\n Retry\n </button>\n ) : null}\n {item.delivery?.onRemove ? (\n <button\n type=\"button\"\n className=\"font-medium text-og-fg-subtle underline decoration-og-border underline-offset-2 hover:text-og-fg\"\n onClick={item.delivery.onRemove}\n >\n Remove\n </button>\n ) : null}\n </div>\n ) : null}\n </div>\n </div>\n );\n}\n\nfunction HumanInputConversationRow({ item }: { item: HumanInputItem }) {\n const enter = useEntranceAnimation();\n const multipleQuestions = Math.max(item.questions.length, item.answers.length) > 1;\n const questionNumberById = new Map(\n item.questions.map((question, index) => [question.id, index + 1]),\n );\n const settledLabel =\n item.response.outcome === \"answered\"\n ? \"You answered\"\n : item.response.outcome === \"skipped\"\n ? \"Skipped\"\n : item.response.outcome === \"expired\"\n ? \"Expired\"\n : \"Cancelled\";\n const copyText = humanInputConversationCopyText(item, settledLabel);\n\n return (\n <div\n className={cn(enter && \"animate-og-enter\", \"flex w-full flex-col gap-2.5\")}\n data-human-input-history={item.requestId}\n >\n <div className=\"flex max-w-[90%] items-start gap-3 rounded-og-lg rounded-bl-og-xs border border-og-border bg-og-surface-1 px-3.5 py-3 sm:max-w-[82%]\">\n <span className=\"mt-0.5 inline-flex size-8 shrink-0 items-center justify-center rounded-og-md bg-og-status-waiting/10 text-og-status-waiting\">\n <MessageCircleQuestionIcon aria-hidden=\"true\" className=\"size-4\" />\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-og-xs font-medium text-og-fg-subtle\">Agent asked</p>\n <div className=\"mt-1.5 space-y-3\">\n {item.questions.length > 0 ? (\n item.questions.map((question, index) => (\n <div key={question.id}>\n {question.label ? (\n <p className=\"text-og-sm font-semibold text-og-fg\">\n {multipleQuestions ? (\n <span className=\"mr-1.5 tabular-nums text-og-fg-muted\">{index + 1}.</span>\n ) : null}\n {multipleQuestions ? \" \" : null}\n {question.label}\n </p>\n ) : null}\n <p\n className={cn(\n \"text-og-md leading-6 text-og-fg\",\n question.label && \"mt-0.5 text-og-sm text-og-fg-muted\",\n )}\n >\n {!question.label && multipleQuestions ? (\n <span className=\"mr-1.5 tabular-nums text-og-fg-muted\">{index + 1}.</span>\n ) : null}\n {!question.label && multipleQuestions ? \" \" : null}\n {question.prompt}\n </p>\n </div>\n ))\n ) : (\n <p className=\"text-og-sm text-og-fg-muted\">The agent requested structured input.</p>\n )}\n </div>\n </div>\n </div>\n\n <div className=\"flex justify-end\">\n <CopyHoverFrame\n copyText={copyText}\n label=\"Copy answer\"\n className=\"w-fit max-w-[90%] min-w-0 sm:max-w-[82%]\"\n trailing={<MessageFooterTime occurredAt={item.occurredAt} />}\n >\n <div className={MESSAGE_BUBBLE_CLASS}>\n <p className=\"text-og-xs font-medium text-og-fg-subtle\">{settledLabel}</p>\n {item.response.outcome === \"answered\" ? (\n <div className=\"mt-1.5 space-y-3\">\n {item.answers.length > 0 ? (\n item.answers.map((answer, answerIndex) => (\n <div key={answer.questionId}>\n {multipleQuestions ? (\n <p className=\"text-og-sm font-semibold text-og-fg\">\n <span className=\"mr-1.5 tabular-nums text-og-fg-muted\">\n {questionNumberById.get(answer.questionId) ?? answerIndex + 1}.\n </span>{\" \"}\n {answer.label}\n </p>\n ) : null}\n <div className={cn(\"text-og-md text-og-fg\", multipleQuestions && \"mt-0.5\")}>\n {answer.values.length > 1 ? (\n <ul className=\"list-disc space-y-0.5 pl-5\">\n {answer.values.map((value) => (\n <li key={`${answer.questionId}-${value}`}>{value}</li>\n ))}\n </ul>\n ) : (\n <p>{answer.values[0] || \"Answered\"}</p>\n )}\n </div>\n </div>\n ))\n ) : (\n <p>Answered</p>\n )}\n </div>\n ) : null}\n </div>\n </CopyHoverFrame>\n </div>\n </div>\n );\n}\n\nfunction humanInputConversationCopyText(item: HumanInputItem, settledLabel: string): string {\n const questions = item.questions\n .map(\n (question, index) =>\n `${item.questions.length > 1 ? `${index + 1}. ` : \"\"}${question.label || \"Question\"}: ${question.prompt}`,\n )\n .join(\"\\n\\n\");\n const questionNumberById = new Map(\n item.questions.map((question, index) => [question.id, index + 1]),\n );\n const answers = item.answers\n .map(\n (answer, index) =>\n `${\n item.questions.length > 1\n ? `${questionNumberById.get(answer.questionId) ?? index + 1}. `\n : \"\"\n }${answer.label}: ${answer.values.join(\", \") || \"Answered\"}`,\n )\n .join(\"\\n\\n\");\n return [questions, `${settledLabel}${answers ? `\\n\\n${answers}` : \"\"}`]\n .filter(Boolean)\n .join(\"\\n\\n\");\n}\n\nfunction AgentMessageRow({\n item,\n renderMessageText,\n}: {\n item: AgentMessageItem;\n renderMessageText?:\n | ((text: string, item: AgentMessageItem | UserMessageItem) => ReactNode)\n | undefined;\n}) {\n const enter = useEntranceAnimation();\n // No streaming caret: it fought the trailing block layout (inline ↔ block)\n // and snapped on exit. Live text carries the stream via tip ink.\n const body = renderMessageText ? (\n renderMessageText(item.text, item)\n ) : (\n <Markdown streaming={item.streaming}>{item.text}</Markdown>\n );\n // While streaming, copy is still useful (current text) but keep chrome calm —\n // stamp only after the message finishes (occurredAt tracks completion).\n return (\n <div data-og-annotation-source-key={item.annotationSource?.eventId}>\n <CopyHoverFrame\n copyText={item.text}\n label=\"Copy message\"\n align=\"start\"\n className={cn(enter && \"animate-og-enter\", \"min-w-0 text-og-md leading-7 text-og-fg\")}\n trailing={item.streaming ? null : <MessageFooterTime occurredAt={item.occurredAt} />}\n >\n {body}\n </CopyHoverFrame>\n </div>\n );\n}\n\n/**\n * A worker session reporting back to its manager. The child's completion arrives\n * as a `user.message` carrying a `childCompletion` payload (the raw message text\n * used to render as an \"ugly\" user bubble); it projects to a `worker-completion`\n * item and draws here as a quietly-confident card — an inbound result, not\n * something the human said. One glyph + one line carry the outcome; the worker's\n * full report, evidence, and any paused reason live behind a collapsed\n * disclosure, and a \"View session\" affordance deep-links into the child.\n *\n * Color follows the timeline's restraint: green only for a completed goal, the\n * waiting hue only for a paused one, red only for a failed child — everything\n * else is a neutral inbound card.\n */\ntype WorkerCompletionMeta = {\n label: string;\n icon: ComponentType<{ className?: string }>;\n iconClass: string;\n /** The 2px left-accent hue — color spent only on the exceptional outcomes. */\n accentClass: string;\n};\n\nfunction workerCompletionMeta(item: WorkerCompletionItem): WorkerCompletionMeta {\n if (item.childStatus === \"failed\") {\n return {\n label: \"Worker failed\",\n icon: XCircleIcon,\n iconClass: \"text-og-status-failed\",\n accentClass: \"border-og-status-failed/60\",\n };\n }\n if (item.goalStatus === \"paused\") {\n return {\n label: \"Worker paused\",\n icon: PauseCircleIcon,\n iconClass: \"text-og-status-waiting\",\n accentClass: \"border-og-status-waiting/50\",\n };\n }\n if (item.goalStatus === \"completed\") {\n return {\n label: \"Worker completed\",\n icon: CheckCircle2Icon,\n iconClass: \"text-og-status-idle\",\n accentClass: \"border-og-status-idle/45\",\n };\n }\n return {\n label: \"Worker reported back\",\n icon: BotIcon,\n iconClass: \"text-og-accent\",\n accentClass: \"border-og-border-strong\",\n };\n}\n\nfunction WorkerCompletionRow({\n item,\n onOpenSession,\n}: {\n item: WorkerCompletionItem;\n onOpenSession?: ((sessionId: string) => void) | undefined;\n}) {\n const enter = useEntranceAnimation();\n const [open, setOpen] = useState(false);\n const meta = workerCompletionMeta(item);\n const Icon = meta.icon;\n // The worker's own report is the substance behind the fold; evidence and any\n // paused reason sit alongside it as quieter, labelled context.\n // \"Paused because\" only when the outcome actually IS a pause — completion\n // payloads can carry a leftover pausedReason/rationale from earlier in the\n // worker's life, and a \"Worker completed\" card must not show a pause section.\n const showPausedReason =\n item.childStatus !== \"failed\" && item.goalStatus === \"paused\" && !!item.pausedReason?.trim();\n const details: { label: string; value: string; muted?: boolean }[] = [\n ...(item.text.trim() ? [{ label: \"Report\", value: item.text.trim() }] : []),\n ...(item.evidence?.trim()\n ? [{ label: \"Evidence\", value: item.evidence.trim(), muted: true }]\n : []),\n ...(showPausedReason\n ? [{ label: \"Paused because\", value: item.pausedReason!.trim(), muted: true }]\n : []),\n ];\n const hasDetails = details.length > 0;\n return (\n <div className={cn(enter && \"animate-og-enter\", \"min-w-0\")}>\n {/* An inbound result, not a bubble: a 2px left accent carries the outcome —\n no full frame, no surface fill. The report unfolds flush beneath. */}\n <div className={cn(\"flex flex-col gap-2 border-l-2 pl-3\", meta.accentClass)}>\n <div className=\"flex items-start gap-2.5\">\n <span className={cn(\"mt-0.5 shrink-0\", meta.iconClass)}>\n <Icon className=\"size-4\" />\n </span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-og-base leading-5 text-og-fg\">\n <span className=\"font-medium\">{meta.label}</span>\n {item.goalText ? (\n <span className=\"text-og-fg-muted\"> · {truncate(item.goalText, 90)}</span>\n ) : null}\n </p>\n </div>\n {item.childSessionId && onOpenSession ? (\n <button\n type=\"button\"\n onClick={() => onOpenSession(item.childSessionId)}\n className={cn(\n \"-my-0.5 -mr-1 inline-flex shrink-0 items-center gap-1 rounded-og-sm px-2 py-1 text-og-sm font-medium text-og-fg-muted pointer-coarse:py-2\",\n \"outline-hidden transition-colors duration-150 hover:bg-og-surface-2 hover:text-og-fg\",\n \"focus-visible:ring-2 focus-visible:ring-og-accent\",\n )}\n >\n View session\n <ArrowRightIcon className=\"size-3.5\" />\n </button>\n ) : null}\n </div>\n {hasDetails ? (\n <Collapsible.Root open={open} onOpenChange={setOpen}>\n <Collapsible.Trigger asChild>\n <button\n type=\"button\"\n className={cn(\n \"group/wc -mx-1 inline-flex w-fit items-center gap-1 rounded-og-sm px-1 py-0.5 text-og-xs font-medium text-og-fg-subtle\",\n \"outline-hidden transition-colors duration-150 hover:text-og-fg-muted focus-visible:ring-2 focus-visible:ring-og-accent\",\n )}\n >\n <ChevronRightIcon className=\"size-3 transition-transform duration-150 ease-og-in-out group-data-[state=open]/wc:rotate-90\" />\n {open ? \"Hide details\" : \"Show details\"}\n </button>\n </Collapsible.Trigger>\n <Collapsible.Content className=\"overflow-hidden data-[state=closed]:animate-og-collapse data-[state=open]:animate-og-expand\">\n <div className=\"ml-1 mt-1.5 flex flex-col gap-2.5\">\n {details.map((detail) => (\n <div key={detail.label} className=\"min-w-0\">\n <p className=\"mb-1 text-og-xs font-medium uppercase tracking-[0.08em] text-og-fg-subtle\">\n {detail.label}\n </p>\n <p\n className={cn(\n \"whitespace-pre-wrap break-words text-og-sm leading-6\",\n detail.muted ? \"text-og-fg-subtle\" : \"text-og-fg-muted\",\n )}\n >\n {detail.value}\n </p>\n </div>\n ))}\n </div>\n </Collapsible.Content>\n </Collapsible.Root>\n ) : null}\n </div>\n </div>\n );\n}\n\nfunction SessionStatusRow({ item }: { item: { status: SessionStatus; occurredAt: string } }) {\n const enter = useEntranceAnimation();\n const meta = SESSION_STATUS_META[item.status];\n return (\n <div\n className={cn(\n enter && \"animate-og-enter\",\n \"flex items-center gap-3 text-og-xs text-og-fg-subtle\",\n )}\n role=\"status\"\n >\n <span className=\"h-px flex-1 bg-og-border\" />\n <span className=\"inline-flex items-center gap-1.5\">\n <StatusDot status={item.status} className=\"size-1\" />\n {meta.label.toLowerCase()} · {formatRelativeTime(item.occurredAt)}\n </span>\n <span className=\"h-px flex-1 bg-og-border\" />\n </div>\n );\n}\n\n/**\n * The per-action presentation of a goal landmark pill. Each of the six goal\n * actions reads distinctly, but the palette stays quiet — color is spent only on\n * the two states that genuinely earn it, the rest are neutral pills set apart by\n * their glyph alone:\n *\n * completed success green (status-idle) check — the only \"done\" hue\n * paused attention waiting-tinted pause — a held goal asks to resume\n * set a landmark a quiet accent target — opening a fresh goal\n * resumed forward neutral play — motion picking back up\n * updated a revision neutral pencil — the goal text changed\n * continuation steady on neutral arrow — still tracking the same goal\n *\n * The pill class is the established badge convention (`text-X border-X/30\n * bg-X/10`); neutral actions reuse the surface/border tokens so a clean run of\n * landmarks stays calm rather than a row of colored chips.\n */\ntype GoalMeta = { label: string; pill: string; icon: ComponentType<{ className?: string }> };\n\nconst NEUTRAL_PILL = \"border-og-border bg-og-surface-1 text-og-fg-muted\";\n\nconst GOAL_META: Record<GoalItem[\"action\"], GoalMeta> = {\n set: {\n label: \"Goal set\",\n pill: \"border-og-accent/30 bg-og-accent/10 text-og-accent\",\n icon: TargetIcon,\n },\n updated: { label: \"Goal updated\", pill: NEUTRAL_PILL, icon: PencilLineIcon },\n completed: {\n label: \"Goal completed\",\n pill: \"border-og-status-idle/30 bg-og-status-idle/10 text-og-status-idle\",\n icon: CheckIcon,\n },\n paused: {\n label: \"Goal paused\",\n pill: WAITING_PILL_CLASS,\n icon: PauseIcon,\n },\n resumed: { label: \"Goal resumed\", pill: NEUTRAL_PILL, icon: PlayIcon },\n cleared: { label: \"Goal cleared\", pill: NEUTRAL_PILL, icon: Trash2Icon },\n held: {\n label: \"Goal held\",\n pill: WAITING_PILL_CLASS,\n icon: PauseCircleIcon,\n },\n continuation: { label: \"Continuing toward the goal\", pill: NEUTRAL_PILL, icon: ArrowRightIcon },\n};\n\n/**\n * A goal landmark pill. Resolves its label, accent/tone, and glyph from\n * {@link GOAL_META} so all six actions are visually distinguishable while the\n * palette stays restrained — see that table for the per-action rationale.\n */\nfunction GoalRow({ item }: { item: GoalItem }) {\n const enter = useEntranceAnimation();\n const { label, pill, icon: Icon } = GOAL_META[item.action];\n return (\n <div className={cn(enter && \"animate-og-enter\", \"flex justify-center\")}>\n <span\n className={cn(\n \"inline-flex max-w-full items-center gap-1.5 rounded-full border px-3 py-1 text-og-sm\",\n pill,\n )}\n >\n <Icon className=\"size-3.5 shrink-0\" />\n <span className=\"truncate\">\n {label}\n {item.text ? `: ${truncate(item.text, 90)}` : \"\"}\n </span>\n </span>\n </div>\n );\n}\n\nfunction MachineInputBatchRow({\n item,\n loadVideoArtifactPlayback,\n}: {\n item: MachineInputBatchItem;\n loadVideoArtifactPlayback?: VideoArtifactPlaybackLoader | undefined;\n}) {\n const enter = useEntranceAnimation();\n const label = machineInputBatchLabel(item.members);\n const single = item.members.length === 1 ? item.members[0]! : null;\n if (single?.kind === \"media_generation_result\" && single.result) {\n return (\n <VideoGenerationResultRow\n result={single.result}\n loadVideoArtifactPlayback={loadVideoArtifactPlayback}\n />\n );\n }\n const singleSummary = single ? cleanMachineInputSummary(single.summary) : \"\";\n const showCollapsedSummary =\n single != null && machineInputSummaryIsUseful(single.kind, singleSummary);\n\n return (\n <div className={cn(enter && \"animate-og-enter\", \"flex flex-col items-center gap-1.5\")}>\n <details className=\"group w-full max-w-full\" data-og-machine-input-batch=\"\">\n <summary className=\"flex cursor-pointer list-none justify-center [&::-webkit-details-marker]:hidden\">\n <span\n className={cn(\n \"inline-flex max-w-full items-center gap-1.5 rounded-full border px-3 py-1 text-og-sm\",\n NEUTRAL_PILL,\n )}\n >\n <ChevronRightIcon\n aria-hidden\n className=\"size-3.5 shrink-0 transition-transform group-open:rotate-90\"\n />\n <span className=\"truncate\">{label}</span>\n </span>\n </summary>\n <div className=\"mx-auto mt-2 w-full max-w-lg space-y-2 border-t border-og-border/50 pt-2\">\n {item.members.map((member) => (\n <MachineInputRow\n key={member.id}\n member={member}\n loadVideoArtifactPlayback={loadVideoArtifactPlayback}\n />\n ))}\n </div>\n </details>\n {showCollapsedSummary ? (\n <p className=\"max-w-lg px-3 text-center text-og-xs leading-4 text-og-fg-subtle\">\n {truncate(singleSummary, 160)}\n </p>\n ) : null}\n </div>\n );\n}\n\nfunction MachineInputRow({\n member,\n loadVideoArtifactPlayback,\n}: {\n member: MachineInputBatchItem[\"members\"][number];\n loadVideoArtifactPlayback?: VideoArtifactPlaybackLoader | undefined;\n}) {\n if (member.kind === \"media_generation_result\" && member.result) {\n return (\n <VideoGenerationResultRow\n result={member.result}\n loadVideoArtifactPlayback={loadVideoArtifactPlayback}\n compact\n />\n );\n }\n const source = readableMachineInputSource(member.sourceId);\n const summary = cleanMachineInputSummary(member.summary);\n return (\n <div className=\"flex min-w-0 items-start gap-2.5\">\n <span className=\"mt-2 size-1.5 shrink-0 rounded-full bg-og-fg-subtle\" aria-hidden />\n <div className=\"min-w-0 flex-1\">\n <span className=\"text-og-control font-medium text-og-fg-muted\">\n {MACHINE_INPUT_META[member.kind]}\n </span>\n {source && <span className=\"ml-1.5 text-og-control text-og-fg-subtle\">from {source}</span>}\n {summary ? (\n <p className=\"mt-0.5 whitespace-pre-wrap break-words text-og-menu leading-5 text-og-fg\">\n {truncate(summary, 320)}\n </p>\n ) : null}\n </div>\n </div>\n );\n}\n\nfunction VideoGenerationResultRow({\n result,\n loadVideoArtifactPlayback,\n compact = false,\n}: {\n result: MediaGenerationResult;\n loadVideoArtifactPlayback?: VideoArtifactPlaybackLoader | undefined;\n compact?: boolean | undefined;\n}) {\n const enter = useEntranceAnimation();\n if (result.status !== \"ready\") {\n return (\n <div\n className={cn(\n enter && \"animate-og-enter\",\n \"mx-auto w-full max-w-lg rounded-og-md border border-og-status-failed/30 bg-og-status-failed/5 px-3.5 py-3\",\n )}\n >\n <div className=\"flex items-center gap-2 text-og-sm font-medium text-og-status-failed\">\n <XCircleIcon aria-hidden className=\"size-4\" />\n Video generation failed\n </div>\n <p className=\"mt-1 text-og-sm leading-5 text-og-fg-muted\">{result.boundedPublicReason}</p>\n </div>\n );\n }\n const { receipt } = result;\n const facts = receipt.video;\n return (\n <section\n aria-label=\"Generated video\"\n className={cn(\n enter && \"animate-og-enter\",\n \"mx-auto w-full max-w-2xl overflow-hidden rounded-og-lg border border-og-border bg-og-surface-1 shadow-sm\",\n compact && \"max-w-lg\",\n )}\n >\n {loadVideoArtifactPlayback ? (\n <GeneratedVideoPlayer\n receipt={receipt}\n loadPlaybackSource={loadVideoArtifactPlayback}\n className=\"rounded-none border-0 shadow-none\"\n />\n ) : (\n <div className=\"flex aspect-video items-center justify-center bg-og-surface-2 text-og-fg-subtle\">\n <PlayIcon aria-hidden className=\"size-6\" />\n </div>\n )}\n <div className=\"flex items-center justify-between gap-4 px-3.5 py-2.5\">\n <div className=\"min-w-0\">\n <p className=\"text-og-sm font-medium text-og-fg\">Generated video</p>\n <p className=\"truncate text-og-xs text-og-fg-subtle\">\n {facts.width}×{facts.height} · {formatVideoDuration(facts.durationSeconds)}\n {facts.hasAudio ? \" · Audio\" : \"\"}\n </p>\n </div>\n <CheckCircle2Icon aria-label=\"Ready\" className=\"size-4 shrink-0 text-og-status-success\" />\n </div>\n </section>\n );\n}\n\nfunction formatVideoDuration(seconds: number): string {\n return `${Math.round(seconds * 10) / 10}s`;\n}\n\nfunction NoticeRow({ item }: { item: NoticeItem }) {\n const enter = useEntranceAnimation();\n const tone =\n item.tone === \"failed\"\n ? \"border-og-status-failed/35 bg-og-status-failed/10 text-og-status-failed\"\n : item.tone === \"waiting\"\n ? WAITING_PILL_CLASS\n : \"border-og-border bg-og-surface-1 text-og-fg-muted\";\n return (\n <div\n className={cn(\n enter && \"animate-og-enter\",\n \"flex items-start gap-2.5 rounded-og-md border px-3.5 py-2.5 text-og-menu\",\n tone,\n )}\n role=\"status\"\n >\n <TriangleAlertIcon\n className={cn(\"mt-0.5 size-4 shrink-0\", item.tone === \"cancelled\" && \"opacity-60\")}\n />\n <div className=\"min-w-0 flex-1\">\n <span className=\"whitespace-pre-wrap break-words\">{item.text}</span>\n {item.details ? (\n <details className=\"mt-2 text-og-control\">\n <summary className=\"cursor-pointer font-medium\">{item.details.label}</summary>\n <pre className=\"mt-2 max-h-64 overflow-auto whitespace-pre-wrap break-all rounded-og-sm bg-black/5 p-2 font-mono dark:bg-white/5\">\n {JSON.stringify(item.details.value, null, 2)}\n </pre>\n </details>\n ) : null}\n </div>\n {item.action ? (\n <a\n className=\"shrink-0 rounded-og-sm border border-current/25 px-2 py-1 text-og-control font-medium hover:bg-current/10\"\n href={item.action.url}\n rel=\"noreferrer\"\n target=\"_blank\"\n >\n {item.action.label}\n </a>\n ) : null}\n </div>\n );\n}\n\n/**\n * The inline connection-recovery card: missing or lapsed access surfaces as a\n * calm, tappable affordance instead of a raw provider-domain error. The `reason`\n * only shapes human copy; no domain or enum code is shown as a label.\n * `onReconnect` (from the app, which owns the SDK client) starts the flow;\n * without it, a pre-minted authorization link is offered, or the card stays\n * informative. Recovery never claims to resume/replay the failed tool call.\n */\nfunction AuthNeededRow({\n item,\n onReconnect,\n resolveProviderLogo,\n}: {\n item: AuthNeededItem;\n onReconnect?: ((item: AuthNeededItem) => void | Promise<void>) | undefined;\n resolveProviderLogo?: ((providerDomain: string) => string | null | undefined) | undefined;\n}) {\n const enter = useEntranceAnimation();\n const [busy, setBusy] = useState(false);\n const [failed, setFailed] = useState(false);\n const recommendation = item.capability ?? null;\n const provider =\n recommendation?.name ??\n (item.serverId === \"codex_apps\" ? \"Codex Apps\" : providerLabel(item.providerDomain));\n const unavailable =\n item.reason === \"personal_authority_unavailable\" ||\n item.reason === \"unsupported_auth\" ||\n item.reason === \"resource_scope_unavailable\";\n const missing = item.reason === \"missing_connection\";\n const actionLabel = recommendation\n ? recommendation.action === \"connect\"\n ? \"Connect\"\n : \"Review\"\n : missing\n ? \"Connect\"\n : \"Reconnect\";\n const title = recommendation\n ? recommendation.action === \"connect\"\n ? `Connect ${provider}`\n : recommendation.action === \"add_credentials\"\n ? `Set up ${provider}`\n : `Enable ${provider}`\n : unavailable\n ? `${provider} tools unavailable`\n : `${actionLabel} ${provider}`;\n const reasonLine = recommendation?.rationale ?? authReasonLine(item.reason);\n const hostAuthorizationUrl = item.authoritySource === \"host\" ? item.authorizationUrl : null;\n\n const start = async () => {\n if (!onReconnect || busy) {\n return;\n }\n setBusy(true);\n setFailed(false);\n try {\n // On success the app redirects to consent (or routes to credential entry),\n // so this row unmounts; a resolve without navigation just relaxes the button.\n // The callback starts authorization only. It never resumes this tool call.\n await onReconnect(item);\n setBusy(false);\n } catch {\n setFailed(true);\n setBusy(false);\n }\n };\n\n return (\n <div className={cn(enter && \"animate-og-enter\", \"flex flex-col gap-2\")} role=\"status\">\n <div className=\"flex flex-col gap-3 rounded-og-lg border border-og-border bg-og-surface-1 px-3.5 py-3 sm:flex-row sm:items-center\">\n <div className=\"flex min-w-0 flex-1 items-center gap-3\">\n <AuthProviderLogo\n src={resolveProviderLogo?.(item.providerDomain) ?? null}\n label={provider}\n />\n <div className=\"min-w-0\">\n <p className=\"truncate text-og-md font-medium text-og-fg\">{title}</p>\n <p className=\"line-clamp-2 text-og-sm text-og-fg-subtle\">{reasonLine}</p>\n {recommendation ? (\n <p className=\"mt-1 truncate text-og-xs text-og-fg-muted\">\n Provider: {item.providerDomain}\n </p>\n ) : null}\n {recommendation && recommendation.requiredVariables.length > 0 ? (\n <p className=\"mt-1 truncate text-og-xs text-og-fg-muted\">\n Needs variables: {recommendation.requiredVariables.join(\", \")}\n </p>\n ) : null}\n </div>\n </div>\n {hostAuthorizationUrl ? (\n <a\n href={hostAuthorizationUrl}\n rel=\"noreferrer\"\n target=\"_blank\"\n className={cn(\n PRIMARY_ACTION_CLASS,\n \"transition-colors hover:bg-og-accent-strong pointer-coarse:min-h-9\",\n )}\n >\n <RefreshCwIcon className=\"size-3.5\" aria-hidden />\n {actionLabel}\n </a>\n ) : item.authoritySource !== \"host\" && !unavailable && onReconnect ? (\n <button\n type=\"button\"\n onClick={() => void start()}\n disabled={busy}\n className={cn(\n PRIMARY_ACTION_CLASS,\n \"transition-colors hover:bg-og-accent-strong disabled:opacity-70 pointer-coarse:min-h-9\",\n )}\n >\n <RefreshCwIcon className={cn(\"size-3.5\", busy && \"animate-og-spin\")} aria-hidden />\n {busy ? \"Opening…\" : actionLabel}\n </button>\n ) : item.authoritySource !== \"host\" && !unavailable && item.authorizationUrl ? (\n <a\n href={item.authorizationUrl}\n rel=\"noreferrer\"\n target=\"_blank\"\n className={cn(\n PRIMARY_ACTION_CLASS,\n \"transition-colors hover:bg-og-accent-strong pointer-coarse:min-h-9\",\n )}\n >\n <RefreshCwIcon className=\"size-3.5\" aria-hidden />\n {actionLabel}\n </a>\n ) : null}\n </div>\n {!unavailable ? (\n <p className=\"px-1 text-og-xs text-og-fg-subtle\">\n {recommendation\n ? \"No access has been granted. Review and confirm the provider before continuing.\"\n : `This tool call wasn't replayed. After ${missing ? \"connecting\" : \"reconnecting\"}, send a new message to try again.`}\n </p>\n ) : null}\n {failed ? (\n <p className=\"px-1 text-og-xs text-og-status-failed\">\n Couldn't start {missing ? \"connecting\" : \"reconnecting\"} {provider}. Try again.\n </p>\n ) : null}\n </div>\n );\n}\n\n/**\n * The provider's logo in a rounded tile, from a URL the HOST serves itself\n * (resolved via `resolveProviderLogo` → the app's catalog assets). A missing or\n * failed image falls back to a calm letter monogram — same as the rest of the\n * app — so the card never shows a broken-image glyph and never reaches off-origin\n * for a favicon (CSP + privacy).\n */\nfunction AuthProviderLogo({ src, label }: { src: string | null; label: string }) {\n const [failed, setFailed] = useState(false);\n // A resolver that only returns the URL after a lazy catalog fetch means `src`\n // can arrive on a later render; reset the error latch so it gets its attempt.\n useEffect(() => setFailed(false), [src]);\n const showImage = src && !failed;\n return (\n <span\n className=\"relative flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-og-md border border-og-border bg-og-surface-2 text-og-menu font-semibold text-og-fg-muted\"\n aria-hidden\n >\n {showImage ? (\n <img\n src={src}\n alt=\"\"\n loading=\"lazy\"\n decoding=\"async\"\n className=\"size-full object-contain p-1.5\"\n onError={() => setFailed(true)}\n />\n ) : (\n <span>{monogram(label)}</span>\n )}\n </span>\n );\n}\n\n/** First one or two initials for the monogram fallback — mirrors the app's\n `capabilityMonogram` so the reconnect tile reads like every other logo tile. */\nfunction monogram(label: string): string {\n const words = label.trim().split(/\\s+/).filter(Boolean);\n if (!words.length) {\n return \"?\";\n }\n if (words.length === 1) {\n return words[0]!.slice(0, 2).toUpperCase();\n }\n return (words[0]![0]! + words[1]![0]!).toUpperCase();\n}\n\n/** \"linear.app\" -> \"Linear\": the first domain label, capitalized. A calm human\n name for the provider — never the raw domain shown as a label. */\nfunction providerLabel(domain: string): string {\n const host =\n domain\n .trim()\n .replace(/^https?:\\/\\//, \"\")\n .replace(/^www\\./, \"\")\n .split(\"/\")[0] ?? \"\";\n const first = host.split(\".\")[0] ?? host;\n if (!first) {\n return \"this service\";\n }\n return first.charAt(0).toUpperCase() + first.slice(1);\n}\n\n/** A calm, human helper line per reauth reason — the `reason` informs the copy\n but is never rendered as a raw enum/code. */\nfunction authReasonLine(reason: AuthNeededItem[\"reason\"]): string {\n switch (reason) {\n case \"insufficient_scope\":\n return \"It needs additional access to continue.\";\n case \"missing_connection\":\n return \"It isn't connected yet.\";\n case \"expired\":\n case \"refresh_failed\":\n return \"Its access expired.\";\n case \"personal_authority_unavailable\":\n return \"This automation was not granted access to your personal connection.\";\n case \"unsupported_auth\":\n return \"This connection cannot authenticate the configured tool endpoint.\";\n case \"resource_scope_unavailable\":\n return \"This tool endpoint cannot enforce the selected repository access.\";\n default:\n return \"Its connection needs attention.\";\n }\n}\n","/* ----------------------------------------------------------------------------\n Tip-follow camera (pure)\n\n DOM truth is immediate; while pinned, the viewport tracks new layout growth\n immediately so already-rendered content is never hidden behind the camera.\n Any debt that existed before the growth still closes through the camera.\n No React, no DOM — the shell reads metrics, calls step, writes scrollTop.\n\n One law for pre-existing debt — second-order camera:\n\n desiredVel = debt / τ\n scrollVel → exponential approach to desiredVel (accel τ = k·τ)\n scrollTop += scrollVel · dt (clamp: no overshoot past tip)\n\n - Layout growth advances cameraTop by the same amount, preserving rather\n than increasing existing debt. This keeps the visible stream truthful.\n - Existing debt eases out as desiredVel→0 (soft settle).\n - τ still adapts (calm / catch-up / line / idle settle).\n - maxStep is a speed ceiling for catch-up, never a source of stream lag.\n - Shrink is separate: compensate Δh so collapse doesn't fight the ease\n - Snap only for first paint / reduced motion / cold oversized jumps\n -------------------------------------------------------------------------- */\n\nimport { MOTION_INSPECT_SCALE } from \"../lib/motion-inspect\";\n\nconst _t = (ms: number) => ms * MOTION_INSPECT_SCALE;\nconst _s = (pxPerSec: number) => pxPerSec / MOTION_INSPECT_SCALE;\n\n/** Calm ease while live: remaining debt shrinks ~63% every τ_max ms. */\nexport const TIP_FOLLOW_TAU_MAX_MS = _t(720);\n/** Catch-up ease under large tip-debt (reader far behind / big paste). */\nexport const TIP_FOLLOW_TAU_MIN_MS = _t(200);\n/**\n * Idle settle τ — stream quiet, soft landing into the tip. Longer than live\n * calm so the last pixels decelerate instead of linear-crawling then stopping.\n */\nexport const TIP_FOLLOW_SETTLE_TAU_MS = _t(960);\n/** Debt that saturates urgency toward τ_min. */\nexport const TIP_FOLLOW_CATCHUP_DEBT_PX = 240;\n/** Keep the rAF alive this long after the last height growth. */\nexport const TIP_FOLLOW_HOT_IDLE_MS = _t(320);\n/** Cold oversized debt snaps (session switch / huge fold), not eases. */\nexport const TIP_FOLLOW_SNAP_PX = 480;\n/** Soft speed floor while live with tiny debt (px/s). */\nexport const TIP_FOLLOW_CALM_MAX_PX_S = _s(42);\n/** Soft speed ceiling while catching a fast stream / modest tip-debt (px/s). */\nexport const TIP_FOLLOW_BURST_MAX_PX_S = _s(420);\n/** Ceiling for huge tip-debt / large single-frame walls (px/s). */\nexport const TIP_FOLLOW_SURGE_MAX_PX_S = _s(1800);\n/**\n * @deprecated Position growth-track removed — camera is velocity-smoothed.\n * Kept so older tests/imports do not break.\n */\nexport const TIP_FOLLOW_GROWTH_TRACK = 0;\n/** @deprecated */\nexport const TIP_FOLLOW_LINE_TRACK = 0;\n/** @deprecated Sub-line special-case removed with growth-track. */\nexport const TIP_FOLLOW_TOKEN_GROWTH_PX = 10;\n/** Hot line-sized tip-debt uses the short {@link TIP_FOLLOW_LINE_TAU_MS}. */\nexport const TIP_FOLLOW_LINE_GROWTH_PX = 48;\n/** Hot τ ceiling while closing a line-sized tip-debt (ms). */\nexport const TIP_FOLLOW_LINE_TAU_MS = _t(140);\n/**\n * Velocity ease-in/out: scrollVel approaches desiredVel with this fraction of τ.\n * Lower → snappier accel; higher → softer start (and slower reaction).\n */\nexport const TIP_FOLLOW_ACCEL_TAU_FRAC = 0.45;\n/** @deprecated Soft-rise FLIP removed — line glue was the bug. */\nexport const TIP_FOLLOW_SOFT_RISE_MS = 0;\n/** @deprecated */\nexport const TIP_FOLLOW_SOFT_RISE_MAX_PX = 96;\n/** @deprecated */\nexport const TIP_FOLLOW_SOFT_RISE_EASING = \"cubic-bezier(0.22, 1, 0.36, 1)\";\n/** Ignore sub-pixel / reflow height noise for shrink compensate. */\nexport const TIP_FOLLOW_SHRINK_EPS_PX = 4;\n/** Growth speed (px/s) that saturates velocity urgency. */\nexport const TIP_FOLLOW_VELOCITY_REF_PX_S = _s(420);\n/**\n * Tip-debt below which growth velocity must not tighten τ.\n * Sparse tokens are high-velocity by nature; only arm once actually behind.\n */\nexport const TIP_FOLLOW_VELOCITY_ARM_DEBT_PX = 72;\n/** EMA decay τ for growthVelocity when height is flat (ms). */\nexport const TIP_FOLLOW_VELOCITY_DECAY_MS = _t(180);\n/** Reader-up pixels above clamp budget that count as leaving the tip. */\nexport const TIP_FOLLOW_READER_UP_EPS_PX = 2;\n/**\n * Browsers snap scrollTop writes to device pixels (whole px at dpr 1). A DOM\n * position within this window of the camera's own fractional position is that\n * quantization echo, not external motion — keep the fraction so sub-pixel\n * settle steps accumulate. Anything larger (clamp, user, glue) re-bases.\n */\nexport const TIP_FOLLOW_QUANTIZE_WINDOW_PX = 1;\n\n/** Test-only override for scrollend feature detection (`null` = probe DOM). */\nlet scrollEndSupportOverride: boolean | null = null;\n\n/** @internal */ export function setScrollEndSupportForTests(value: boolean | null): void {\n scrollEndSupportOverride = value;\n}\n\n/** True when the engine exposes element `scrollend` (prefer over rAF leave). */\nexport function supportsScrollEndEvent(): boolean {\n if (scrollEndSupportOverride !== null) {\n return scrollEndSupportOverride;\n }\n return typeof HTMLElement !== \"undefined\" && \"onscrollend\" in HTMLElement.prototype;\n}\n/** @deprecated Shrink lock removed; kept so old imports do not break. */\nexport const TIP_FOLLOW_SHRINK_LOCK_MS = 0;\n/** @deprecated Absorb thresholds removed — growth track is continuous. */\nexport const TIP_FOLLOW_GROWTH_ABSORB_PX = 96;\n\n/**\n * ScrollTop decrease not explained by a maxScroll clamp (fold / composer\n * shrink). Fold clamp: top falls by ≈ maxScroll fall → 0. Real scroll-up:\n * top falls while maxScroll holds → positive. No timers.\n */\nexport function readerScrollUpPx(\n prevTop: number,\n nextTop: number,\n prevMaxScroll: number,\n nextMaxScroll: number,\n): number {\n const topDelta = prevTop - nextTop;\n const clampBudget = Math.max(0, prevMaxScroll - nextMaxScroll);\n return topDelta - clampBudget;\n}\n\nexport type TipFollowState = {\n running: boolean;\n hotUntil: number;\n lastTs: number;\n lastHeight: number;\n /** Last observed scroller clientHeight — viewport shrink heats like tip growth. */\n lastClientHeight: number;\n lastGrowthAt: number;\n /** EMA of recent height growth (px/s); nudges τ / ceiling under bursts. */\n growthVelocity: number;\n /** Camera velocity toward tip (px/s). Smoothed — never jumps with debt. */\n scrollVelocity: number;\n /**\n * Fractional camera position. The DOM quantizes scrollTop to device pixels,\n * so settle steps under 1px would be discarded every frame if the camera\n * re-based on the DOM — it then parks 20-50px short of the tip forever.\n * `null` = no fraction in flight; adopt the DOM position.\n */\n cameraTop: number | null;\n};\n\nexport type TipFollowStepInput = {\n scrollTop: number;\n scrollHeight: number;\n clientHeight: number;\n now: number;\n pinned: boolean;\n reducedMotion: boolean;\n revealed: boolean;\n};\n\nexport type TipFollowStepResult = {\n scrollTop: number;\n state: TipFollowState;\n};\n\nexport function createTipFollowState(): TipFollowState {\n return {\n running: false,\n hotUntil: 0,\n lastTs: 0,\n lastHeight: 0,\n lastClientHeight: 0,\n lastGrowthAt: 0,\n growthVelocity: 0,\n scrollVelocity: 0,\n cameraTop: null,\n };\n}\n\nexport function tipFollowCancel(state: TipFollowState): TipFollowState {\n return {\n ...state,\n running: false,\n lastTs: 0,\n scrollVelocity: 0,\n cameraTop: null,\n };\n}\n\n/**\n * Record content height. Positive growth extends the hot window so sparse\n * lines do not tear down the follow loop between appends.\n */\nexport function tipFollowNoteGrowth(\n state: TipFollowState,\n height: number,\n now: number,\n): TipFollowState {\n const previous = state.lastHeight;\n if (previous <= 0) {\n return { ...state, lastHeight: height };\n }\n if (height < previous && previous - height <= TIP_FOLLOW_SHRINK_EPS_PX) {\n // Match viewport-shrink deadband memory: the shell retains the paired\n // pre-shrink scrollTop and this state retains the corresponding height.\n return state;\n }\n if (height <= previous) {\n return { ...state, lastHeight: height };\n }\n const dt = state.lastGrowthAt > 0 ? now - state.lastGrowthAt : 0;\n let growthVelocity = state.growthVelocity;\n if (dt > 0) {\n const instant = ((height - previous) / dt) * 1000;\n growthVelocity = growthVelocity * 0.65 + instant * 0.35;\n }\n return {\n ...state,\n lastHeight: height,\n lastGrowthAt: now,\n growthVelocity,\n hotUntil: now + TIP_FOLLOW_HOT_IDLE_MS,\n };\n}\n\n/**\n * Record scroller viewport height. A shrink (composer / SessionChrome /\n * window) raises tip debt (`scrollHeight - clientHeight`) without growing\n * content — the same debt content-growth would create. Heat the camera so\n * catch-up does not fall into cold soft-settle (~42px/s) and leave the tip\n * parked under the chrome.\n */\nexport function tipFollowNoteViewportShrink(\n state: TipFollowState,\n clientHeight: number,\n now: number,\n): TipFollowState {\n const previous = state.lastClientHeight;\n if (previous <= 0) {\n return { ...state, lastClientHeight: clientHeight };\n }\n const shrink = previous - clientHeight;\n if (shrink <= 0) {\n return { ...state, lastClientHeight: clientHeight };\n }\n if (shrink <= TIP_FOLLOW_SHRINK_EPS_PX) {\n // Sub-eps shrink: HOLD the baseline (deadband with memory). An animated\n // chrome/composer ease-out delivers many ≤eps frames; adopting each one\n // leaked the whole tail into cold debt with no glue and no heat.\n return state;\n }\n const dt = state.lastGrowthAt > 0 ? now - state.lastGrowthAt : 0;\n let growthVelocity = state.growthVelocity;\n if (dt > 0) {\n const instant = (shrink / dt) * 1000;\n growthVelocity = growthVelocity * 0.65 + instant * 0.35;\n } else {\n growthVelocity = Math.max(growthVelocity, shrink * (1000 / TIP_FOLLOW_HOT_IDLE_MS));\n }\n return {\n ...state,\n lastClientHeight: clientHeight,\n lastGrowthAt: now,\n growthVelocity,\n hotUntil: now + TIP_FOLLOW_HOT_IDLE_MS,\n };\n}\n\n/**\n * Adaptive τ: small debt → calm; large debt / armed velocity → catch-up.\n * While hot, floor urgency so live streams are not stuck on calm τ.\n * Idle settle uses the longer settle τ.\n */\nexport function tipFollowTauMs(\n debtPx: number,\n growthVelocityPxPerSec = 0,\n settling = false,\n hot = false,\n): number {\n if (settling) {\n return TIP_FOLLOW_SETTLE_TAU_MS;\n }\n const absDebt = Math.abs(debtPx);\n const debtT = Math.min(1, absDebt / TIP_FOLLOW_CATCHUP_DEBT_PX);\n let velUrgency = 0;\n if (absDebt >= TIP_FOLLOW_VELOCITY_ARM_DEBT_PX) {\n const velT = Math.min(1, Math.max(0, growthVelocityPxPerSec) / TIP_FOLLOW_VELOCITY_REF_PX_S);\n velUrgency = velT * 0.55;\n }\n const hotUrgency = hot ? 0.65 : 0;\n const urgency = Math.min(1, Math.max(debtT, velUrgency, hotUrgency));\n let tau = TIP_FOLLOW_TAU_MAX_MS + (TIP_FOLLOW_TAU_MIN_MS - TIP_FOLLOW_TAU_MAX_MS) * urgency;\n // Line-sized live debt: close over ~LINE_TAU so the glide finishes before\n // the next newline without needing 1:1 tip-glue.\n if (hot && absDebt > 0 && absDebt <= TIP_FOLLOW_LINE_GROWTH_PX) {\n tau = Math.min(tau, TIP_FOLLOW_LINE_TAU_MS);\n }\n return tau;\n}\n\n/**\n * Soft speed ceiling from continuous signals (debt, velocity EMA, this-frame\n * growth). No mode switches — larger inputs raise the ceiling smoothly.\n */\nexport function tipFollowMaxStepPx(\n debtPx: number,\n growthVelocityPxPerSec: number,\n dtMs: number,\n frameGrowthPx = 0,\n hot = false,\n): number {\n const absDebt = Math.abs(debtPx);\n const debtT = Math.min(1, absDebt / TIP_FOLLOW_CATCHUP_DEBT_PX);\n const velT = Math.min(1, Math.max(0, growthVelocityPxPerSec) / TIP_FOLLOW_VELOCITY_REF_PX_S);\n const armed = absDebt >= TIP_FOLLOW_VELOCITY_ARM_DEBT_PX;\n const blend = Math.max(debtT, armed ? velT : 0, hot ? 0.35 : 0);\n let maxPxS =\n TIP_FOLLOW_CALM_MAX_PX_S +\n (TIP_FOLLOW_BURST_MAX_PX_S - TIP_FOLLOW_CALM_MAX_PX_S) * blend * blend;\n if (hot && frameGrowthPx > 0 && dtMs > 0) {\n // Allow pre-existing debt to close without falling behind current growth.\n maxPxS = Math.max(maxPxS, (frameGrowthPx / dtMs) * 1000);\n }\n if (hot && growthVelocityPxPerSec > TIP_FOLLOW_CALM_MAX_PX_S) {\n // Live stream: slightly outrun the EMA so tip-debt cannot ratchet forever.\n maxPxS = Math.max(maxPxS, Math.min(TIP_FOLLOW_BURST_MAX_PX_S, growthVelocityPxPerSec * 1.25));\n }\n if (hot && absDebt > 8) {\n // Continuous debt horizon (no catch-up cliff at CATCHUP_DEBT).\n maxPxS = Math.max(maxPxS, Math.min(TIP_FOLLOW_SURGE_MAX_PX_S, absDebt / 0.2));\n } else if (absDebt >= TIP_FOLLOW_CATCHUP_DEBT_PX) {\n maxPxS = Math.max(maxPxS, Math.min(TIP_FOLLOW_SURGE_MAX_PX_S, absDebt / 0.12));\n }\n return (maxPxS / 1000) * dtMs;\n}\n\nfunction targetScrollTop(scrollHeight: number, clientHeight: number): number {\n return Math.max(0, scrollHeight - clientHeight);\n}\n\n/**\n * Counter-offset for soft-rise after tip-glue: start from the mid-flight\n * translateY (if any) plus this frame's glued scroll delta, capped.\n * Shell applies translateY(from) → 0 over {@link TIP_FOLLOW_SOFT_RISE_MS}.\n */\nexport function tipFollowSoftRiseFrom(\n currentTranslateY: number,\n gluedScrollDelta: number,\n maxPx: number = TIP_FOLLOW_SOFT_RISE_MAX_PX,\n): number {\n const stacked = Math.max(0, currentTranslateY) + Math.max(0, gluedScrollDelta);\n return Math.min(maxPx, stacked);\n}\n\n/** Read live translateY from a transformed content column (mid soft-rise). */\nexport function readTranslateY(el: HTMLElement): number {\n const raw = getComputedStyle(el).transform;\n if (!raw || raw === \"none\") {\n return 0;\n }\n try {\n return new DOMMatrixReadOnly(raw).m42;\n } catch {\n return 0;\n }\n}\n\n/**\n * Cancel the tip-glue pop: start at translateY(+δ) and ease to 0.\n * Uses WAAPI — a same-frame CSS transition never paints the counter-offset,\n * so the scroll jump stays an instant one-line pop.\n */\nexport function tipFollowPlaySoftRise(\n el: HTMLElement,\n gluedScrollDelta: number,\n opts?: {\n durationMs?: number;\n maxPx?: number;\n easing?: string;\n },\n): void {\n if (gluedScrollDelta <= 0.5) {\n return;\n }\n const durationMs = opts?.durationMs ?? TIP_FOLLOW_SOFT_RISE_MS;\n const maxPx = opts?.maxPx ?? TIP_FOLLOW_SOFT_RISE_MAX_PX;\n const easing = opts?.easing ?? TIP_FOLLOW_SOFT_RISE_EASING;\n const from = tipFollowSoftRiseFrom(readTranslateY(el), gluedScrollDelta, maxPx);\n if (from <= 0.5) {\n return;\n }\n // Drop any in-flight rise / leftover CSS transition before starting clean.\n if (typeof el.getAnimations === \"function\") {\n for (const animation of el.getAnimations()) {\n animation.cancel();\n }\n }\n el.style.transition = \"\";\n // Hold the counter-offset in style until WAAPI’s first keyframe applies.\n // Clearing to \"\" here painted one frame of hard tip-glue (the pop).\n el.style.transform = `translateY(${from}px)`;\n if (typeof el.animate !== \"function\") {\n return;\n }\n const animation = el.animate(\n [{ transform: `translateY(${from}px)` }, { transform: \"translateY(0px)\" }],\n // `backwards`: first keyframe applies immediately (no gap after cancel).\n { duration: durationMs, easing, fill: \"backwards\" },\n );\n const clearHold = () => {\n if (el.style.transform === `translateY(${from}px)`) {\n el.style.transform = \"\";\n }\n };\n animation.addEventListener(\"finish\", clearHold, { once: true });\n animation.addEventListener(\"cancel\", clearHold, { once: true });\n}\n\n/** Stop soft-rise and clear any CSS transform residue. */\nexport function tipFollowClearSoftRise(el: HTMLElement): void {\n if (typeof el.getAnimations === \"function\") {\n for (const animation of el.getAnimations()) {\n animation.cancel();\n }\n }\n el.style.transition = \"\";\n el.style.transform = \"\";\n}\n\n/**\n * Height left the document (settle collapse / composer). Keep the same pixels\n * on screen: scrollTop -= Δh, clamped to the new max.\n */\nexport function tipFollowCompensateShrink(\n scrollTop: number,\n previousHeight: number,\n nextHeight: number,\n clientHeight: number,\n epsPx: number = TIP_FOLLOW_SHRINK_EPS_PX,\n): number {\n const delta = previousHeight - nextHeight;\n if (delta <= epsPx) {\n return scrollTop;\n }\n const maxScroll = Math.max(0, nextHeight - clientHeight);\n return Math.max(0, Math.min(maxScroll, scrollTop - delta));\n}\n\nexport type TipFollowContentShrinkBaseline = {\n scrollHeight: number;\n scrollTop: number;\n};\n\nexport type TipFollowContentShrinkObservation = {\n baseline: TipFollowContentShrinkBaseline | null;\n compensatedScrollTop: number | null;\n};\n\n/**\n * Retain the geometry from the first sub-epsilon content-shrink frame until\n * the cumulative collapse crosses the deadband. Browsers may clamp scrollTop\n * after every tiny frame, so compensating from the latest DOM top would count\n * those already-applied clamps twice and make the result animation-cadence\n * dependent.\n */\nexport function tipFollowObserveContentShrink(\n baseline: TipFollowContentShrinkBaseline | null,\n previousHeight: number,\n previousScrollTop: number,\n nextHeight: number,\n clientHeight: number,\n epsPx: number = TIP_FOLLOW_SHRINK_EPS_PX,\n): TipFollowContentShrinkObservation {\n if (previousHeight <= 0 || nextHeight >= previousHeight) {\n return { baseline: null, compensatedScrollTop: null };\n }\n const retained = baseline ?? {\n scrollHeight: previousHeight,\n scrollTop: previousScrollTop,\n };\n if (retained.scrollHeight - nextHeight <= epsPx) {\n return { baseline: retained, compensatedScrollTop: null };\n }\n return {\n baseline: null,\n compensatedScrollTop: tipFollowCompensateShrink(\n retained.scrollTop,\n retained.scrollHeight,\n nextHeight,\n clientHeight,\n epsPx,\n ),\n };\n}\n\n/**\n * Viewport shrank (SessionChrome / composer / window). maxScroll rises by ≈Δc;\n * keep the same tip distance: scrollTop += Δc. Without this, pinned follow only\n * sees new tip debt and soft-settles under the chrome.\n */\nexport function tipFollowCompensateViewportShrink(\n scrollTop: number,\n previousClientHeight: number,\n nextClientHeight: number,\n scrollHeight: number,\n epsPx: number = TIP_FOLLOW_SHRINK_EPS_PX,\n): number {\n if (previousClientHeight <= 0) {\n return scrollTop;\n }\n const shrink = previousClientHeight - nextClientHeight;\n if (shrink <= epsPx) {\n return scrollTop;\n }\n const maxScroll = Math.max(0, scrollHeight - nextClientHeight);\n return Math.max(0, Math.min(maxScroll, scrollTop + shrink));\n}\n\n/**\n * One camera step. Shell schedules the next rAF while `result.state.running`.\n */\nexport function tipFollowStep(\n state: TipFollowState,\n input: TipFollowStepInput,\n): TipFollowStepResult {\n const { scrollTop, scrollHeight, clientHeight, now, pinned, reducedMotion, revealed } = input;\n const previousHeight = state.lastHeight;\n const previousClient = state.lastClientHeight;\n const frameGrowth =\n previousHeight > 0 && scrollHeight > previousHeight ? scrollHeight - previousHeight : 0;\n const frameViewportShrink =\n previousClient > 0 && clientHeight < previousClient - TIP_FOLLOW_SHRINK_EPS_PX\n ? previousClient - clientHeight\n : 0;\n const grew = frameGrowth > 0 || frameViewportShrink > 0;\n let noted = tipFollowNoteGrowth(state, scrollHeight, now);\n noted = tipFollowNoteViewportShrink(noted, clientHeight, now);\n // Sub-device-pixel writes are floored by the engine: a DOM position within\n // the quantization window of our own fractional camera is the echo of our\n // last write, not external motion — keep the fraction so settle steps\n // accumulate. Larger disagreement (clamp / reader / snap) re-bases.\n let cameraTop = scrollTop;\n if (\n state.cameraTop !== null &&\n Math.abs(state.cameraTop - scrollTop) <= TIP_FOLLOW_QUANTIZE_WINDOW_PX\n ) {\n cameraTop = state.cameraTop;\n }\n // Chrome/composer dock: tip-glue before ease so debt from ΔclientHeight is\n // not left for cold soft-settle (content still under the new bar).\n if (pinned && frameViewportShrink > 0) {\n cameraTop = tipFollowCompensateViewportShrink(\n cameraTop,\n previousClient,\n clientHeight,\n scrollHeight,\n );\n }\n const target = targetScrollTop(scrollHeight, clientHeight);\n if (pinned && frameGrowth > 0) {\n // Preserve the distance that existed before this layout growth instead of\n // manufacturing new visual debt. The content is already in the DOM; while\n // pinned, hiding it behind an eased scroll makes frontend streaming appear\n // slower than the provider and leaves a visible catch-up tail after the\n // final token. Existing debt still goes through the camera below.\n cameraTop = Math.min(target, cameraTop + frameGrowth);\n }\n const debt = target - cameraTop;\n const hot = now < noted.hotUntil;\n const settling = !hot && Math.abs(debt) < TIP_FOLLOW_CATCHUP_DEBT_PX;\n\n if (!pinned) {\n return {\n scrollTop,\n state: tipFollowCancel(noted),\n };\n }\n\n if (!revealed || reducedMotion) {\n return {\n scrollTop: target,\n state: tipFollowCancel(noted),\n };\n }\n\n if (Math.abs(debt) > TIP_FOLLOW_SNAP_PX && !hot) {\n return {\n scrollTop: target,\n state: tipFollowCancel(noted),\n };\n }\n\n const dt = noted.lastTs === 0 ? 16 : Math.min(64, Math.max(8, now - noted.lastTs));\n if (!grew && noted.growthVelocity > 0) {\n const decayed = noted.growthVelocity * Math.exp(-dt / TIP_FOLLOW_VELOCITY_DECAY_MS);\n noted = {\n ...noted,\n growthVelocity: decayed < 1 ? 0 : decayed,\n };\n }\n\n if (Math.abs(debt) <= 0.75) {\n return {\n scrollTop: Math.abs(debt) > 0 ? target : cameraTop,\n state: {\n ...tipFollowCancel(noted),\n growthVelocity: hot ? noted.growthVelocity : 0,\n },\n };\n }\n\n const tau = tipFollowTauMs(debt, noted.growthVelocity, settling, hot);\n const dtSec = dt / 1000;\n const tauSec = Math.max(tau / 1000, 1e-3);\n // P-gain: held desiredVel would close debt in ~τ. Velocity cannot jump —\n // pre-existing debt accelerates toward desiredVel and then settles out.\n const desiredVel = debt / tauSec;\n const accelTauSec = Math.max(tauSec * TIP_FOLLOW_ACCEL_TAU_FRAC, 0.02);\n const velAlpha = 1 - Math.exp(-dtSec / accelTauSec);\n let scrollVelocity =\n (noted.scrollVelocity ?? 0) + (desiredVel - (noted.scrollVelocity ?? 0)) * velAlpha;\n\n const maxStep = tipFollowMaxStepPx(\n debt,\n noted.growthVelocity,\n dt,\n frameGrowth + frameViewportShrink,\n hot,\n );\n const maxVel = maxStep / dtSec;\n if (Math.abs(scrollVelocity) > maxVel) {\n scrollVelocity = Math.sign(scrollVelocity) * maxVel;\n }\n\n let next = cameraTop + scrollVelocity * dtSec;\n // Never overshoot the tip — stop and kill velocity on arrival.\n if (debt > 0 && next >= target - 0.35) {\n next = target;\n scrollVelocity = 0;\n } else if (debt < 0 && next <= target + 0.35) {\n next = target;\n scrollVelocity = 0;\n }\n next = Math.max(0, next);\n\n const running = Math.abs(target - next) > 0.35 || Math.abs(scrollVelocity) > 1;\n return {\n scrollTop: next,\n state: {\n ...noted,\n scrollVelocity,\n running,\n lastTs: now,\n // Carry the fraction the DOM will floor away; drop it once landed.\n cameraTop: running ? next : null,\n },\n };\n}\n","import type { MachineInputMember } from \"../timeline/types\";\n\nexport const MACHINE_INPUT_META: Record<MachineInputMember[\"kind\"], string> = {\n scheduled_occurrence: \"Scheduled update\",\n goal_continuation: \"Goal continued\",\n agent_message: \"Agent update\",\n agent_steer_instruction: \"Agent direction\",\n child_terminal_result: \"Agent finished\",\n media_generation_result: \"Video update\",\n child_requires_action: \"Agent needs input\",\n child_requires_action_resolved: \"Agent unblocked\",\n child_paused: \"Agent paused\",\n child_waiting_capacity: \"Agent waiting for capacity\",\n child_progress: \"Agent progress\",\n};\n\n/**\n * Collapsed landmark label for a coalesced machine-input batch.\n * Same-kind batches get a natural plural; mixed kinds stay short.\n */\nexport function machineInputBatchLabel(members: readonly MachineInputMember[]): string {\n if (members.length === 0) return \"Updates\";\n const counts = new Map<MachineInputMember[\"kind\"], number>();\n for (const member of members) {\n counts.set(member.kind, (counts.get(member.kind) ?? 0) + 1);\n }\n if (counts.size === 1) {\n const kind = members[0]!.kind;\n const n = members.length;\n switch (kind) {\n case \"child_terminal_result\":\n return n === 1 ? \"Agent finished\" : `${n} agents finished`;\n case \"goal_continuation\":\n return n === 1 ? \"Goal continued\" : `${n} goal continuations`;\n case \"scheduled_occurrence\":\n return n === 1 ? \"Scheduled update\" : `${n} scheduled updates`;\n case \"agent_message\":\n return n === 1 ? \"Agent update\" : `${n} agent updates`;\n case \"agent_steer_instruction\":\n return n === 1 ? \"Agent direction\" : `${n} agent directions`;\n case \"media_generation_result\":\n return n === 1 ? \"Video ready\" : `${n} video updates`;\n case \"child_requires_action\":\n return n === 1 ? \"Agent needs input\" : `${n} agents need input`;\n case \"child_requires_action_resolved\":\n return n === 1 ? \"Agent unblocked\" : `${n} agents unblocked`;\n case \"child_paused\":\n return n === 1 ? \"Agent paused\" : `${n} agents paused`;\n case \"child_waiting_capacity\":\n return n === 1 ? \"Agent waiting for capacity\" : `${n} agents waiting for capacity`;\n case \"child_progress\":\n return n === 1 ? \"Agent progress\" : `${n} agent progress notes`;\n }\n }\n const parts = [...counts.entries()].map(([kind, count]) => {\n const label = MACHINE_INPUT_META[kind];\n return count === 1 ? label : `${count}× ${label}`;\n });\n const preview = parts.slice(0, 2).join(\", \");\n const suffix = parts.length > 2 ? \", …\" : \"\";\n return `${members.length} updates · ${preview}${suffix}`;\n}\n\n/** Strip protocol prefixes and worker/session UUIDs from display summaries. */\nexport function cleanMachineInputSummary(summary: string): string {\n return summary\n .replace(/^\\[[A-Z][A-Z _-]*(?:\\s+\\d+\\/\\d+)?\\]\\s*/, \"\")\n .replace(/\\bWorker session id:\\s*[0-9a-f]{8}-[0-9a-f-]{27,}\\b/gi, \"\")\n .replace(/\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi, \"\")\n .replace(/\\(\\s*\\)/g, \"\")\n .replace(/\\s*[·|]\\s*$/g, \"\")\n .replace(/\\s{2,}/g, \" \")\n .replace(/\\s+([.,;:])/g, \"$1\")\n .trim();\n}\n\nexport function readableMachineInputSource(sourceId: string): string | null {\n const value = sourceId.trim();\n if (!value || /^[0-9a-f]{8}-[0-9a-f-]{27,}$/i.test(value)) return null;\n if (/^(goal|schedule|system):/i.test(value)) return null;\n return value.replaceAll(\"_\", \" \");\n}\n\n/** True when a cleaned single-member summary adds meaning beyond the pill label. */\nexport function machineInputSummaryIsUseful(\n kind: MachineInputMember[\"kind\"],\n cleanedSummary: string,\n): boolean {\n if (!cleanedSummary) return false;\n const label = MACHINE_INPUT_META[kind].toLowerCase();\n const text = cleanedSummary.toLowerCase();\n if (text === label || text === `${label}.`) return false;\n // Generic child-finished boilerplate after UUID scrub is still noise.\n if (\n kind === \"child_terminal_result\" &&\n /^a worker session you spawned has finished/i.test(cleanedSummary)\n ) {\n return false;\n }\n return true;\n}\n","import { Loader2Icon } from \"lucide-react\";\nimport { lazy, Suspense, type ComponentType } from \"react\";\n\nimport type { QueueSurfaceProps } from \"./queue-surface-implementation\";\nexport { requestQueueDraftEdit } from \"./queue-draft-policy\";\nimport { EmptyQueueStateSurface } from \"./queue-surface-state\";\n\nexport type { QueueSurfaceProps } from \"./queue-surface-implementation\";\n\nconst loadQueueSurface = () => import(\"./queue-surface-implementation\");\ntype QueueSurfaceModule = { QueueSurface: ComponentType<QueueSurfaceProps> };\ntype QueueSurfaceLoader = () => Promise<QueueSurfaceModule>;\n\n/** The sole pending-input surface: compact above Goal, Agents, and composer. */\nexport const QueueSurface = createQueueSurface(loadQueueSurface);\n\n/** @internal Deterministic Suspense seam for the QueueSurface regression suite. */\nexport function createQueueSurfaceForTest(loadImplementation: QueueSurfaceLoader) {\n return createQueueSurface(loadImplementation);\n}\n\nfunction createQueueSurface(loadImplementation: QueueSurfaceLoader) {\n const LazyQueueSurface = lazy(async () => ({\n default: (await loadImplementation()).QueueSurface,\n }));\n\n return function QueueSurfaceBoundary(props: QueueSurfaceProps) {\n const { queue } = props;\n if (queue.queue.length + queue.pendingInputs.length === 0) {\n if (!queue.stoppingPreviousAttempt && !queue.error && !queue.mutationError) return null;\n return <EmptyQueueStateSurface queue={queue} />;\n }\n\n return (\n <Suspense fallback={<QueueSurfaceFallback />}>\n <LazyQueueSurface {...props} />\n </Suspense>\n );\n };\n}\n\nfunction QueueSurfaceFallback() {\n return (\n <div\n aria-live=\"polite\"\n className=\"og-root mx-auto mb-2 w-full max-w-3xl shrink-0 px-4 sm:px-6\"\n data-testid=\"queue-surface-loading\"\n role=\"status\"\n >\n <div className=\"overflow-hidden rounded-lg border border-border bg-surface/80 shadow-sm\">\n <div className=\"flex items-center gap-2 px-3 py-2 text-og-control text-fg-muted pointer-coarse:min-h-[44px]\">\n <Loader2Icon\n aria-hidden=\"true\"\n className=\"size-3.5 shrink-0 animate-spin motion-reduce:animate-none\"\n />\n Loading inputs…\n </div>\n </div>\n </div>\n );\n}\n","/**\n * SessionChrome — compact merged session signals above the composer.\n *\n * Built-in session chrome for production and embeds. Token-themed\n * (`--og-session-chrome-*`); hosts override on `.og-session-chrome` or an ancestor.\n *\n * ## Host tokens\n * Defaults live in `tokens.css`.\n *\n * | Token | Role |\n * | --- | --- |\n * | `--og-session-chrome-surface` / `-open` | Dock fill (collapsed / expanded) |\n * | `--og-session-chrome-border` / `-open` | Dock edge |\n * | `--og-session-chrome-highlight` / `-ring` | Sliding chip selection fill + edge |\n * | `--og-session-chrome-shadow` / `-open` | Elevation |\n * | `--og-session-chrome-radius` | Dock corner radius |\n * | `--og-session-chrome-chip-min-height` | Signal chip height |\n * | `--og-session-chrome-chip-pad-x` / `--og-session-chrome-chip-gap` | Chip padding / rail gap |\n * | `--og-session-chrome-rail-pad` | Outer rail inset |\n * | `--og-session-chrome-panel-pad-x` / `-y` | Expanded panel padding |\n * | `--og-session-chrome-panel-max-height` | Cap for expanded body (scrolls inside) |\n * | `--og-session-chrome-duration` / `--og-session-chrome-ease` | Expand + pill motion |\n * | `--og-session-chrome-crossfade-duration` | Segment content opacity crossfade |\n * | `--og-session-chrome-row-hover` | Inbox / queue row hover wash |\n *\n * Inbox and queue stay separate segments. Queue hover actions wire to\n * `UseTurnQueueResult` (`editTurn` / `steerTurn` / `moveTurn` / `removeTurn`).\n * Inbox has no product dismiss API; pass `onDismissIncoming` when the host\n * wants a visible action (dev harness may use a local dummy).\n *\n * Segment switches keep the panel shell mounted and crossfade content. The\n * shell uses one CSS grid-track transition for deliberate open/close actions;\n * live queue reconciliation never feeds measurements back into layout.\n */\nimport type { SessionGoal, SessionPendingInputPreview, SessionTurn } from \"@opengeni/sdk\";\nimport {\n AudioLinesIcon,\n ArrowDownIcon,\n ArrowUpIcon,\n BotIcon,\n CheckIcon,\n InboxIcon,\n ListOrderedIcon,\n Loader2Icon,\n PauseIcon,\n PencilIcon,\n PlayIcon,\n Trash2Icon,\n TriangleAlertIcon,\n XIcon,\n ZapIcon,\n} from \"lucide-react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { useEffect, useId, useMemo, useRef, useState, type ReactNode } from \"react\";\n\nimport type { ComposerOptimisticMessage, ComposerState } from \"../hooks/use-composer\";\nimport type { UseGoalResult } from \"../hooks/use-goal\";\nimport type { UseTurnQueueResult } from \"../hooks/use-turn-queue\";\nimport { cn } from \"../lib/cn\";\nimport { formatClockTime } from \"../lib/format\";\nimport { requestQueueDraftEdit } from \"./queue-draft-policy\";\nimport { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from \"./tooltip\";\n\nexport type SessionChromeSignalId = \"incoming\" | \"steering\" | \"queue\" | \"goal\" | \"agents\";\n\nexport type SessionChromeSignalTone = \"neutral\" | \"accent\" | \"waiting\" | \"running\";\n\nexport type SessionChromeAgentsSignal = {\n count: number;\n detail?: string | undefined;\n tone?: SessionChromeSignalTone | undefined;\n};\n\nexport type SessionChromeProps = {\n queue: UseTurnQueueResult;\n /** Needed for queue edit → composer checkout. Omit with `readOnly`. */\n composer?: ComposerState | undefined;\n goal?: UseGoalResult | null | undefined;\n /** Expanded agents body (host supplies tree / list). */\n agentsPanel?: ReactNode;\n /** Chip summary; when `count > 0` the agents segment appears. */\n agentsSignal?: SessionChromeAgentsSignal | undefined;\n /**\n * Optional inbox dismiss. Product pending-inputs have no remove API — hosts\n * (and the gallery) may still pass a handler so the action is visible.\n */\n onDismissIncoming?: ((inputId: string) => void) | undefined;\n readOnly?: boolean | undefined;\n className?: string | undefined;\n /** Controlled active segment; omit for uncontrolled. */\n active?: SessionChromeSignalId | null | undefined;\n defaultActive?: SessionChromeSignalId | null | undefined;\n onActiveChange?: ((next: SessionChromeSignalId | null) => void) | undefined;\n};\n\ntype GoalPillState =\n | \"pursuing\"\n | \"waiting\"\n | \"scheduled\"\n | \"blocked\"\n | \"held\"\n | \"paused\"\n | \"invariant_broken\"\n | \"completed\";\n\ntype QueuedTurnPresentation = {\n kind: \"prompt\" | \"realtime_voice\" | \"realtime_voice_handoff\";\n text: string;\n};\n\nconst GOAL_LABEL: Record<GoalPillState, string> = {\n pursuing: \"Pursuing\",\n waiting: \"Waiting\",\n scheduled: \"Scheduled\",\n blocked: \"Blocked\",\n held: \"Held\",\n paused: \"Paused\",\n invariant_broken: \"Needs attention\",\n completed: \"Done\",\n};\n\n/**\n * Short pill suffix per `pausedReason`. `max_auto_continuations` is pacing\n * (new input resumes it); `limits` is budget/admission; `user_pause`/`api` is\n * the human's own override; `agent` is the model declaring it is blocked on a\n * human decision. Unknown or legacy reasons keep the bare \"Paused\".\n */\nconst GOAL_PAUSED_REASON_SUFFIX: Record<string, string> = {\n max_auto_continuations: \"cap\",\n limits: \"budget\",\n user_pause: \"manually\",\n api: \"manually\",\n agent: \"agent\",\n};\n\nconst GOAL_PAUSED_REASON_EXPLANATION: Record<string, string> = {\n max_auto_continuations:\n \"Paused at the automatic continuation cap. New input (a child result, an agent message, or your prompt) resumes it; you can also resume it here.\",\n limits: \"Paused because budget or usage limits block another run. Resume once limits allow.\",\n user_pause:\n \"Paused manually by a person or an API call. Resume to let the goal continue on its own.\",\n api: \"Paused manually by a person or an API call. Resume to let the goal continue on its own.\",\n agent: \"Paused by the agent: it is waiting on a human decision before continuing.\",\n};\n\ntype GoalPillRecord = Pick<SessionGoal, \"status\" | \"pausedReason\"> & {\n continuation?: SessionGoal[\"continuation\"] | null | undefined;\n};\n\n/** Pill label, with the pause reason spelled out: \"Paused · cap\" / \"Paused · manually\". */\nexport function sessionChromeGoalPillLabel(\n state: GoalPillState,\n record: GoalPillRecord | null | undefined,\n): string {\n if (state !== \"paused\") return GOAL_LABEL[state];\n const suffix = record?.pausedReason ? GOAL_PAUSED_REASON_SUFFIX[record.pausedReason] : undefined;\n return suffix ? `Paused · ${suffix}` : \"Paused\";\n}\n\n/**\n * One human sentence explaining WHY the goal is not pursuing right now: the\n * pause reason, the agent's own `goal_wait` hold (reason + deadline), or the\n * next idle-backoff check time. Null when the state needs no explanation.\n */\nexport function sessionChromeGoalPillExplanation(\n state: GoalPillState,\n record: GoalPillRecord | null | undefined,\n): string | null {\n const continuation = record?.continuation ?? null;\n if (state === \"paused\") {\n return record?.pausedReason\n ? (GOAL_PAUSED_REASON_EXPLANATION[record.pausedReason] ?? null)\n : null;\n }\n if (state === \"scheduled\" && continuation?.reason === \"backoff_pending\") {\n return continuation.nextAttemptAt\n ? `Next goal check at ${formatClockTime(continuation.nextAttemptAt)}.`\n : \"Next goal check is scheduled.\";\n }\n if (state === \"held\" && continuation?.reason === \"held_for_input\") {\n const reason = continuation.holdReason?.trim();\n const until = continuation.nextAttemptAt\n ? ` until ${formatClockTime(continuation.nextAttemptAt)}`\n : \"\";\n return `Waiting for input${reason ? `: ${reason}` : \"\"}${until}. A child result, an agent message, or your prompt wakes it sooner.`;\n }\n return null;\n}\n\nfunction queuedTurnPresentation(turn: SessionTurn): QueuedTurnPresentation {\n const realtimeDelegation = objectValue(turn.metadata.realtimeDelegation);\n const inputTranscript = realtimeDelegation?.inputTranscript;\n if (typeof inputTranscript === \"string\" && inputTranscript.trim()) {\n return { kind: \"realtime_voice\", text: inputTranscript.trim() };\n }\n if (objectValue(turn.metadata.realtimeTailFlush)) {\n return { kind: \"realtime_voice_handoff\", text: \"Remaining voice context\" };\n }\n return { kind: \"prompt\", text: turn.prompt };\n}\n\nfunction isSteeringTurn(turn: SessionTurn): boolean {\n return turn.metadata.delivery === \"steer\";\n}\n\nfunction objectValue(value: unknown): Record<string, unknown> | null {\n return value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : null;\n}\n\n/** Select pill state from the goal's authoritative continuation projection. */\nexport function sessionChromeGoalPillState(\n goalStatus: \"active\" | \"paused\" | \"completed\",\n continuation: SessionGoal[\"continuation\"] | null | undefined,\n): GoalPillState {\n if (goalStatus === \"completed\") return \"completed\";\n if (goalStatus === \"paused\") return \"paused\";\n if (!continuation) return \"invariant_broken\";\n if (continuation.state === \"running\") {\n return continuation.reason === \"goal_turn_running\"\n ? \"pursuing\"\n : continuation.reason === \"human_turn_running\"\n ? \"waiting\"\n : \"invariant_broken\";\n }\n // `backoff_pending` (idle pacing between consecutive no-input continuations,\n // next evaluation at `nextAttemptAt`) is an ordinary scheduled state.\n if (continuation.state === \"scheduled\") return \"scheduled\";\n if (continuation.state === \"blocked\") {\n // `held_for_input` is the agent's own goal_wait hold (waiting for child\n // results / external input until a deadline); it shares the Held pill.\n return continuation.reason === \"workstream_paused\" || continuation.reason === \"held_for_input\"\n ? \"held\"\n : \"blocked\";\n }\n return \"invariant_broken\";\n}\n\nfunction formatCoarseElapsed(ms: number): string {\n const totalSeconds = Math.max(0, Math.floor(ms / 1000));\n const days = Math.floor(totalSeconds / 86_400);\n const hours = Math.floor((totalSeconds % 86_400) / 3_600);\n const minutes = Math.floor((totalSeconds % 3_600) / 60);\n const seconds = totalSeconds % 60;\n if (days > 0) return `${days}d ${hours}h`;\n if (hours > 0) return `${hours}h ${minutes}m`;\n if (minutes > 0) return `${minutes}m ${seconds}s`;\n return `${seconds}s`;\n}\n\nfunction useLiveElapsed(\n startIso: string | null | undefined,\n live: boolean,\n endIso?: string | null,\n) {\n const start = startIso ? Date.parse(startIso) : Number.NaN;\n const [now, setNow] = useState(() => Date.now());\n useEffect(() => {\n if (!live) return;\n const id = setInterval(() => setNow(Date.now()), 1_000);\n return () => clearInterval(id);\n }, [live]);\n if (!Number.isFinite(start)) return null;\n const end = live ? now : endIso ? Date.parse(endIso) : now;\n return formatCoarseElapsed((Number.isFinite(end) ? end : now) - start);\n}\n\nfunction pendingKindLabel(kind: SessionPendingInputPreview[\"kind\"]): string {\n switch (kind) {\n case \"child_terminal_result\":\n return \"Child result\";\n case \"child_requires_action\":\n return \"Child needs input\";\n case \"child_requires_action_resolved\":\n return \"Child unblocked\";\n case \"child_paused\":\n return \"Child paused\";\n case \"child_waiting_capacity\":\n return \"Child waiting\";\n case \"child_progress\":\n return \"Child progress\";\n case \"agent_steer_instruction\":\n return \"Steer\";\n case \"scheduled_occurrence\":\n return \"Schedule\";\n case \"goal_continuation\":\n return \"Goal wake\";\n case \"agent_message\":\n return \"Update\";\n default:\n return \"Incoming\";\n }\n}\n\nfunction toneClass(tone: SessionChromeSignalTone, selected: boolean): string {\n switch (tone) {\n case \"accent\":\n return \"text-og-accent\";\n case \"waiting\":\n return \"text-og-status-waiting\";\n case \"running\":\n return \"text-og-status-running\";\n default:\n return selected ? \"text-og-fg\" : \"text-og-fg-subtle\";\n }\n}\n\nexport function SessionChrome({\n queue,\n composer,\n goal,\n agentsPanel,\n agentsSignal,\n onDismissIncoming,\n readOnly = false,\n className,\n active: activeControlled,\n defaultActive = null,\n onActiveChange,\n}: SessionChromeProps) {\n const reactId = useId();\n const panelId = `og-session-chrome-panel-${reactId}`;\n const reduceMotion = useReducedMotion();\n const record = goal?.goal ?? null;\n const incoming = queue.pendingInputs;\n const turns = queue.queue;\n const queueMutationFor = queue.mutationFor;\n const queuedTurns = useMemo(\n () => turns.filter((turn) => !isSteeringTurn(turn) && queueMutationFor(turn.id) !== \"steer\"),\n [queueMutationFor, turns],\n );\n const queuedTurnIds = useMemo(() => new Set(queuedTurns.map((turn) => turn.id)), [queuedTurns]);\n const optimisticQueued = useMemo(\n () =>\n (composer?.optimisticMessages ?? []).filter(\n (message) =>\n message.delivery === \"send\" &&\n message.destination === \"queue\" &&\n (!message.turnId || !queuedTurnIds.has(message.turnId)) &&\n !(\n message.turnId &&\n message.appliedQueueVersion !== null &&\n message.appliedQueueVersion !== undefined &&\n queue.snapshot &&\n queue.snapshot.version >= message.appliedQueueVersion\n ),\n ),\n [composer?.optimisticMessages, queue.snapshot, queuedTurnIds],\n );\n const stoppingKind =\n composer?.stoppingAttempt ??\n (queue.stoppingPreviousAttempt\n ? queue.effectiveControl?.state === \"paused\"\n ? \"current\"\n : \"previous\"\n : null);\n const stopping = stoppingKind !== null;\n const canMutateQueue = !readOnly && composer !== undefined;\n\n const liveGoal = record?.status === \"active\";\n const elapsed = useLiveElapsed(\n record?.createdAt,\n Boolean(liveGoal),\n !liveGoal ? record?.updatedAt : null,\n );\n const goalState = record ? sessionChromeGoalPillState(record.status, record.continuation) : null;\n\n const signals = useMemo(() => {\n const rows: Array<{\n id: SessionChromeSignalId;\n label: string;\n detail?: string | undefined;\n /** Hover explanation (why paused / held / when the next check is). */\n title?: string | undefined;\n tone: SessionChromeSignalTone;\n icon: ReactNode;\n }> = [];\n if (incoming.length > 0) {\n const detail = incoming[0]?.summary;\n rows.push({\n id: \"incoming\",\n label: `${incoming.length} in`,\n ...(detail ? { detail } : {}),\n tone: incoming.some(\n (item) => item.classification === \"action_required\" || item.classification === \"failure\",\n )\n ? \"waiting\"\n : \"neutral\",\n icon: <InboxIcon className=\"size-3\" />,\n });\n }\n const queuedCount = queuedTurns.length + optimisticQueued.length;\n const queueProblem = queue.mutationError ?? queue.error;\n if (queuedCount > 0 || queueProblem) {\n const presentations = queuedTurns.map(queuedTurnPresentation);\n const first = presentations[0];\n const allVoiceRequests =\n optimisticQueued.length === 0 &&\n presentations.length > 0 &&\n presentations.every(({ kind }) => kind === \"realtime_voice\");\n const onlyVoiceHandoff =\n optimisticQueued.length === 0 &&\n presentations.length === 1 &&\n first?.kind === \"realtime_voice_handoff\";\n const voiceOnly = allVoiceRequests || onlyVoiceHandoff;\n const detail = queueProblem\n ? queue.mutationError\n ? \"Action not confirmed\"\n : \"Queue unavailable\"\n : (first?.text ?? optimisticQueued[0]?.text);\n rows.push({\n id: \"queue\",\n label: queueProblem\n ? queuedCount > 0\n ? `${queuedCount} queued · needs attention`\n : \"Queue needs attention\"\n : allVoiceRequests\n ? queuedCount === 1\n ? \"Voice request queued\"\n : `${queuedCount} voice requests queued`\n : onlyVoiceHandoff\n ? \"Voice handoff queued\"\n : `${queuedCount} queued prompt${queuedCount === 1 ? \"\" : \"s\"}`,\n ...(detail ? { detail } : {}),\n tone: queueProblem ? \"waiting\" : \"neutral\",\n icon: queueProblem ? (\n <TriangleAlertIcon className=\"size-3\" />\n ) : voiceOnly ? (\n <AudioLinesIcon className=\"size-3\" />\n ) : (\n <ListOrderedIcon className=\"size-3\" />\n ),\n });\n }\n if (record && goalState) {\n const waiting =\n goalState === \"waiting\" ||\n goalState === \"blocked\" ||\n goalState === \"held\" ||\n goalState === \"paused\";\n const explanation = sessionChromeGoalPillExplanation(goalState, record);\n rows.push({\n id: \"goal\",\n label: sessionChromeGoalPillLabel(goalState, record),\n detail: elapsed ? `${elapsed} · ${record.text}` : record.text,\n ...(explanation ? { title: explanation } : {}),\n tone: waiting\n ? \"waiting\"\n : goalState === \"pursuing\" || goalState === \"scheduled\"\n ? \"accent\"\n : \"neutral\",\n icon:\n goalState === \"blocked\" || goalState === \"invariant_broken\" ? (\n <TriangleAlertIcon className=\"size-3\" />\n ) : goalState === \"waiting\" ? (\n <Loader2Icon className=\"size-3 animate-og-spin\" />\n ) : goalState === \"paused\" || goalState === \"held\" ? (\n <PauseIcon className=\"size-3\" />\n ) : (\n <ZapIcon className=\"size-3\" />\n ),\n });\n }\n if (agentsSignal && agentsSignal.count > 0) {\n const detail = agentsSignal.detail;\n rows.push({\n id: \"agents\",\n label: `${agentsSignal.count} agent${agentsSignal.count === 1 ? \"\" : \"s\"}`,\n ...(detail ? { detail } : {}),\n tone: agentsSignal.tone ?? \"neutral\",\n icon: <BotIcon className=\"size-3\" />,\n });\n }\n return rows;\n }, [\n agentsSignal,\n elapsed,\n goalState,\n incoming,\n optimisticQueued,\n queue.error,\n queue.mutationError,\n queuedTurns,\n record,\n ]);\n\n const [activeUncontrolled, setActiveUncontrolled] = useState<SessionChromeSignalId | null>(\n defaultActive,\n );\n const active = activeControlled !== undefined ? activeControlled : activeUncontrolled;\n const setActive = (next: SessionChromeSignalId | null) => {\n if (activeControlled === undefined) setActiveUncontrolled(next);\n onActiveChange?.(next);\n };\n const optimisticQueueKeys = optimisticQueued.map((message) => message.clientEventId).join(\",\");\n const previousOptimisticQueueKeys = useRef(optimisticQueueKeys);\n const [queueArrivalNonce, setQueueArrivalNonce] = useState(0);\n useEffect(() => {\n const previous = new Set(previousOptimisticQueueKeys.current.split(\",\").filter(Boolean));\n const arrived = optimisticQueued.some((message) => !previous.has(message.clientEventId));\n previousOptimisticQueueKeys.current = optimisticQueueKeys;\n if (!arrived) return;\n // Queue admission must not move the conversation or open a drawer beneath\n // the pointer. A stable, paint-only receipt on the queue chip communicates\n // destination without participating in layout.\n setQueueArrivalNonce((current) => current + 1);\n }, [optimisticQueueKeys, optimisticQueued]);\n const [replaceDraftFor, setReplaceDraftFor] = useState<string | null>(null);\n\n const chipRefs = useRef<Partial<Record<SessionChromeSignalId, HTMLButtonElement | null>>>({});\n const railRef = useRef<HTMLDivElement | null>(null);\n const [pill, setPill] = useState({ left: 0, top: 0, width: 0, height: 0, opacity: 0 });\n\n const signalIds = signals.map((signal) => signal.id).join(\",\");\n useEffect(() => {\n if (active && !signalIds.split(\",\").includes(active)) {\n if (activeControlled === undefined) setActiveUncontrolled(null);\n onActiveChange?.(null);\n }\n }, [active, activeControlled, onActiveChange, signalIds]);\n\n useEffect(() => {\n if (active !== \"queue\" || !replaceDraftFor) return;\n if (!queuedTurns.some((turn) => turn.id === replaceDraftFor)) {\n setReplaceDraftFor(null);\n }\n }, [active, queuedTurns, replaceDraftFor]);\n\n useEffect(() => {\n const rail = railRef.current;\n const measure = () => {\n if (!rail || !active) {\n setPill((prev) => (prev.opacity === 0 ? prev : { ...prev, opacity: 0 }));\n return;\n }\n const chip = chipRefs.current[active];\n if (!chip) return;\n // Measure against the chip's own box so a wrapped multi-row rail never\n // stretches the highlight into a tall stripe across every signal.\n const railBox = rail.getBoundingClientRect();\n const chipBox = chip.getBoundingClientRect();\n setPill({\n left: chipBox.left - railBox.left,\n top: chipBox.top - railBox.top,\n width: chipBox.width,\n height: chipBox.height,\n opacity: 1,\n });\n };\n measure();\n if (!rail) return;\n const observer = new ResizeObserver(measure);\n observer.observe(rail);\n for (const chip of Object.values(chipRefs.current)) {\n if (chip) observer.observe(chip);\n }\n window.addEventListener(\"resize\", measure);\n return () => {\n observer.disconnect();\n window.removeEventListener(\"resize\", measure);\n };\n }, [active, signals]);\n\n const open = active !== null;\n\n if (signals.length === 0 && !stopping) return null;\n\n const shellDuration = reduceMotion ? 0 : 0.22;\n const crossfadeDuration = reduceMotion ? 0 : 0.18;\n const ease = [0.22, 1, 0.36, 1] as const;\n\n const panelBody =\n active === \"incoming\" ? (\n <IncomingPanel inputs={incoming} onDismiss={onDismissIncoming} />\n ) : active === \"queue\" ? (\n <QueuePanel\n turns={queuedTurns}\n optimistic={optimisticQueued}\n loadError={queue.error}\n mutationError={queue.mutationError}\n onRefresh={queue.refresh}\n onClearMutationError={queue.clearMutationError}\n onRetryOptimistic={composer?.retryOptimisticMessage}\n onRemoveOptimistic={composer?.removeOptimisticMessage}\n readOnly={!canMutateQueue}\n mutationFor={queue.mutationFor}\n replaceDraftFor={replaceDraftFor}\n onCancelReplace={() => setReplaceDraftFor(null)}\n onConfirmReplace={\n canMutateQueue && composer && replaceDraftFor\n ? () => {\n const turnId = replaceDraftFor;\n setReplaceDraftFor(null);\n void (async () => {\n const checkedOut = await queue.editTurn(turnId, {\n expectedDraftRevision: composer.draftRevision,\n replaceDraft: true,\n });\n if (checkedOut) composer.applyDraft(checkedOut);\n })();\n }\n : undefined\n }\n onEdit={\n canMutateQueue && composer\n ? (turn) => {\n requestQueueDraftEdit(\n composer,\n () => setReplaceDraftFor(turn.id),\n () => {\n void (async () => {\n const checkedOut = await queue.editTurn(turn.id, {\n expectedDraftRevision: composer.draftRevision,\n replaceDraft: false,\n });\n if (checkedOut) composer.applyDraft(checkedOut);\n })();\n },\n );\n }\n : undefined\n }\n onSteer={\n canMutateQueue\n ? (turnId) => {\n void queue.steerTurn(turnId);\n }\n : undefined\n }\n onRemove={\n canMutateQueue\n ? (turnId) => {\n void queue.removeTurn(turnId);\n }\n : undefined\n }\n onMove={\n canMutateQueue\n ? (turnId, beforeTurnId) => {\n void queue.moveTurn(turnId, beforeTurnId);\n }\n : undefined\n }\n />\n ) : active === \"goal\" && record && goalState && goal ? (\n <GoalPanel goal={goal} state={goalState} elapsed={elapsed} readOnly={readOnly} />\n ) : active === \"agents\" ? (\n <div data-og-session-chrome-panel=\"agents\">\n {agentsPanel ?? <p className=\"text-og-xs text-og-fg-muted\">No agent details.</p>}\n </div>\n ) : null;\n\n return (\n <TooltipProvider delayDuration={300}>\n <div\n className={cn(\"og-session-chrome og-root w-full\", className)}\n data-testid=\"session-chrome\"\n data-og-session-chrome=\"\"\n data-og-session-chrome-open={open ? \"true\" : \"false\"}\n >\n <div\n className={cn(\n \"relative overflow-hidden border\",\n \"transition-[background-color,border-color,box-shadow] motion-reduce:transition-none\",\n )}\n style={{\n borderRadius: \"var(--_og-session-chrome-radius)\",\n background: open\n ? \"var(--_og-session-chrome-surface-open)\"\n : \"var(--_og-session-chrome-surface)\",\n borderColor: open\n ? \"var(--_og-session-chrome-border-open)\"\n : \"var(--_og-session-chrome-border)\",\n boxShadow: open\n ? \"var(--og-session-chrome-shadow-open)\"\n : \"var(--og-session-chrome-shadow)\",\n transitionDuration: \"var(--og-session-chrome-duration)\",\n transitionTimingFunction: \"var(--_og-session-chrome-ease)\",\n }}\n >\n <div\n className=\"relative\"\n style={{\n paddingTop: \"var(--og-session-chrome-rail-pad)\",\n paddingBottom: \"var(--og-session-chrome-rail-pad)\",\n paddingLeft: \"var(--og-session-chrome-rail-pad)\",\n paddingRight: \"var(--og-session-chrome-rail-pad)\",\n }}\n >\n <div\n ref={railRef}\n className=\"relative flex flex-wrap items-center\"\n style={{\n gap: \"var(--og-session-chrome-chip-gap)\",\n }}\n >\n <motion.div\n aria-hidden\n className=\"pointer-events-none absolute left-0 top-0 rounded-og-md\"\n style={{\n background: \"var(--_og-session-chrome-highlight)\",\n boxShadow: \"inset 0 0 0 1px var(--_og-session-chrome-highlight-ring)\",\n }}\n initial={false}\n animate={{\n x: pill.left,\n y: pill.top,\n width: pill.width,\n height: pill.height,\n opacity: pill.opacity,\n }}\n transition={{ duration: shellDuration, ease }}\n />\n {signals.map((signal) => {\n const selected = active === signal.id;\n return (\n <button\n key={signal.id}\n type=\"button\"\n ref={(node) => {\n chipRefs.current[signal.id] = node;\n }}\n aria-expanded={selected}\n aria-controls={panelId}\n aria-label={selected ? `Close ${signal.label}` : undefined}\n data-testid={`session-chrome-${signal.id}`}\n data-og-session-chrome-signal={signal.id}\n title={signal.title}\n onClick={() => setActive(selected ? null : signal.id)}\n className={cn(\n \"group relative z-[1] inline-flex min-h-[var(--og-session-chrome-chip-min-height)] max-w-full items-center gap-1 rounded-og-md py-1 text-left text-og-xs outline-hidden\",\n // Coarse pointers keep a 44px target (session-pins acceptance).\n \"pointer-coarse:min-h-11\",\n \"transition-colors duration-150 motion-reduce:transition-none\",\n \"hover:text-og-fg focus-visible:bg-og-surface-3/50\",\n selected ? \"text-og-fg\" : \"text-og-fg-muted\",\n )}\n style={{\n paddingInline: \"var(--og-session-chrome-chip-pad-x)\",\n }}\n >\n {signal.id === \"queue\" && queueArrivalNonce > 0 && !reduceMotion ? (\n <motion.span\n key={queueArrivalNonce}\n aria-hidden=\"true\"\n data-testid=\"session-chrome-queue-arrival\"\n className=\"pointer-events-none absolute inset-0 rounded-og-md bg-og-accent-soft\"\n initial={{ opacity: 0 }}\n animate={{ opacity: [0, 0.38, 0] }}\n transition={{ duration: 0.72, times: [0, 0.18, 1], ease }}\n />\n ) : null}\n <span className={cn(\"shrink-0\", toneClass(signal.tone, selected))}>\n {signal.icon}\n </span>\n <span className=\"shrink-0 font-medium text-og-fg\">{signal.label}</span>\n {signal.detail ? (\n <>\n <span aria-hidden className=\"shrink-0 text-og-fg-subtle/60\">\n ·\n </span>\n <span className=\"min-w-0 max-w-[8.5rem] truncate text-og-fg sm:max-w-[12rem]\">\n {signal.detail}\n </span>\n </>\n ) : null}\n {selected ? (\n <span\n data-testid=\"session-chrome-close\"\n className=\"ml-0.5 inline-flex size-4 shrink-0 items-center justify-center rounded-og-sm text-og-fg-subtle transition-colors group-hover:text-og-fg pointer-coarse:size-5\"\n aria-hidden\n >\n <XIcon className=\"size-3\" />\n </span>\n ) : null}\n </button>\n );\n })}\n {stopping ? (\n <span\n role=\"status\"\n aria-live=\"polite\"\n className=\"inline-flex min-h-[var(--og-session-chrome-chip-min-height)] items-center gap-1.5 px-1.5 text-og-xs text-og-fg-muted\"\n data-testid=\"session-chrome-stopping\"\n >\n <Loader2Icon\n aria-hidden=\"true\"\n className=\"size-3 animate-og-spin motion-reduce:animate-none\"\n />\n {stoppingKind === \"current\" ? \"Current work stopping\" : \"Previous work stopping\"}\n </span>\n ) : null}\n </div>\n </div>\n\n <div\n id={panelId}\n data-og-session-chrome-panel-shell=\"\"\n aria-hidden={!open}\n inert={!open ? true : undefined}\n className=\"grid overflow-hidden motion-reduce:transition-none\"\n style={{\n gridTemplateRows: open ? \"1fr\" : \"0fr\",\n opacity: open ? 1 : 0,\n pointerEvents: open ? \"auto\" : \"none\",\n transitionProperty: \"grid-template-rows, opacity\",\n transitionDuration: \"var(--og-session-chrome-duration)\",\n transitionTimingFunction: \"var(--_og-session-chrome-ease)\",\n }}\n >\n <div className=\"min-h-0 overflow-hidden\">\n <div\n className=\"relative overflow-y-auto overscroll-contain border-t border-og-border/50\"\n style={{\n maxHeight: \"var(--og-session-chrome-panel-max-height)\",\n paddingInline: \"var(--og-session-chrome-panel-pad-x)\",\n paddingBlock: \"var(--og-session-chrome-panel-pad-y)\",\n }}\n >\n <AnimatePresence initial={false}>\n {active && panelBody ? (\n <motion.div\n key={active}\n data-og-session-chrome-panel-frame={active}\n initial={reduceMotion ? false : { opacity: 0 }}\n animate={{ opacity: 1, position: \"relative\" }}\n exit={\n reduceMotion\n ? { opacity: 1, position: \"relative\" }\n : {\n opacity: 0,\n position: \"absolute\",\n top: 0,\n left: 0,\n right: 0,\n }\n }\n transition={{ duration: crossfadeDuration, ease }}\n >\n {panelBody}\n </motion.div>\n ) : null}\n </AnimatePresence>\n </div>\n </div>\n </div>\n </div>\n </div>\n </TooltipProvider>\n );\n}\n\nfunction IncomingPanel({\n inputs,\n onDismiss,\n}: {\n inputs: SessionPendingInputPreview[];\n onDismiss?: ((inputId: string) => void) | undefined;\n}) {\n return (\n <ul\n className=\"flex flex-col gap-0.5\"\n aria-label=\"Incoming updates\"\n data-og-session-chrome-panel=\"incoming\"\n >\n {inputs.map((input) => (\n <li\n key={input.id}\n className=\"group flex items-start gap-1.5 rounded-og-sm px-1.5 py-1 transition-colors hover:bg-[var(--_og-session-chrome-row-hover)]\"\n >\n <span\n className={cn(\n \"mt-px shrink-0 rounded px-1 py-px text-[10px] font-medium leading-4\",\n input.classification === \"action_required\" || input.classification === \"failure\"\n ? \"bg-og-status-waiting/12 text-og-status-waiting\"\n : \"bg-og-surface-3/80 text-og-fg-muted\",\n )}\n >\n {pendingKindLabel(input.kind)}\n </span>\n <p className=\"min-w-0 flex-1 text-og-xs leading-4 text-og-fg\">{input.summary}</p>\n {onDismiss ? (\n <div className=\"flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100 max-sm:opacity-100\">\n <IconAction\n label={`Dismiss incoming ${pendingKindLabel(input.kind)}`}\n tip=\"Dismiss\"\n onClick={() => onDismiss(input.id)}\n danger\n >\n <Trash2Icon className=\"size-3\" />\n </IconAction>\n </div>\n ) : null}\n </li>\n ))}\n </ul>\n );\n}\n\nfunction QueuePanel({\n turns,\n optimistic,\n loadError,\n mutationError,\n onRefresh,\n onClearMutationError,\n onRetryOptimistic,\n onRemoveOptimistic,\n readOnly,\n mutationFor,\n replaceDraftFor,\n onCancelReplace,\n onConfirmReplace,\n onEdit,\n onSteer,\n onRemove,\n onMove,\n}: {\n turns: SessionTurn[];\n optimistic: ComposerOptimisticMessage[];\n loadError: Error | null;\n mutationError: Error | null;\n onRefresh: () => Promise<void>;\n onClearMutationError: () => void;\n onRetryOptimistic?: ((clientEventId: string) => void) | undefined;\n onRemoveOptimistic?: ((clientEventId: string) => void) | undefined;\n readOnly: boolean;\n mutationFor: UseTurnQueueResult[\"mutationFor\"];\n replaceDraftFor?: string | null | undefined;\n onCancelReplace?: (() => void) | undefined;\n onConfirmReplace?: (() => void) | undefined;\n onEdit?: ((turn: SessionTurn) => void) | undefined;\n onSteer?: ((turnId: string) => void) | undefined;\n onRemove?: ((turnId: string) => void) | undefined;\n onMove?: ((turnId: string, beforeTurnId: string | null) => void) | undefined;\n}) {\n const reduceMotion = useReducedMotion();\n const turnIdsKey = turns.map((turn) => turn.id).join(\",\");\n const [interactiveTurnIds, setInteractiveTurnIds] = useState<ReadonlySet<string>>(\n () => new Set(),\n );\n useEffect(() => {\n const visibleTurnIds = new Set(turnIdsKey ? turnIdsKey.split(\",\") : []);\n setInteractiveTurnIds((current) => {\n const retained = new Set([...current].filter((turnId) => visibleTurnIds.has(turnId)));\n return retained.size === current.size ? current : retained;\n });\n if (visibleTurnIds.size === 0) return;\n // An optimistic queue row and its authoritative replacement have different\n // React identities. Do not expose an actionable control during that short\n // handoff: a pointer can otherwise press the outgoing DOM node and release\n // over its replacement, producing a completed-looking click with no event.\n const timer = setTimeout(\n () => setInteractiveTurnIds((current) => new Set([...current, ...visibleTurnIds])),\n reduceMotion ? 0 : 240,\n );\n return () => clearTimeout(timer);\n }, [reduceMotion, turnIdsKey]);\n return (\n <ol\n className=\"flex flex-col gap-0.5\"\n aria-label=\"Queued prompts\"\n data-og-session-chrome-panel=\"queue\"\n >\n {turns.map((turn, index) => {\n const presentation = queuedTurnPresentation(turn);\n const voice = presentation.kind !== \"prompt\";\n const pending = mutationFor(turn.id);\n const settling = !interactiveTurnIds.has(turn.id);\n const beforeUp = index > 0 ? (turns[index - 1]?.id ?? null) : null;\n const beforeDown = index < turns.length - 1 ? (turns[index + 2]?.id ?? null) : null;\n const showActions = !readOnly && (onEdit || onSteer || onRemove || onMove);\n const confirmingReplace = replaceDraftFor === turn.id;\n return (\n <li\n key={turn.id}\n data-queue-turn-id={turn.id}\n className=\"group flex flex-col gap-1 rounded-og-sm px-1.5 py-1 transition-colors hover:bg-[var(--_og-session-chrome-row-hover)]\"\n >\n <div className=\"flex items-start gap-1.5\">\n {voice ? (\n <AudioLinesIcon\n aria-hidden=\"true\"\n className=\"mt-0.5 size-3 shrink-0 text-og-accent\"\n />\n ) : (\n <span className=\"mt-px shrink-0 font-og-mono text-[10px] leading-4 text-og-fg-subtle\">\n {index + 1}\n </span>\n )}\n <p className=\"min-w-0 flex-1 truncate text-og-xs leading-4 text-og-fg\">\n {presentation.text}\n </p>\n {showActions ? (\n <div className=\"flex shrink-0 items-center gap-0.5 opacity-0 transition-opacity group-hover:opacity-100 focus-within:opacity-100 max-sm:opacity-100\">\n {onMove && turns.length > 1 ? (\n <>\n <IconAction\n label={`Move queued prompt ${index + 1} up`}\n tip=\"Move up\"\n disabled={settling || pending !== null || index === 0}\n onClick={() => onMove(turn.id, beforeUp)}\n >\n <ArrowUpIcon className=\"size-3\" />\n </IconAction>\n <IconAction\n label={`Move queued prompt ${index + 1} down`}\n tip=\"Move down\"\n disabled={settling || pending !== null || index >= turns.length - 1}\n onClick={() => onMove(turn.id, beforeDown)}\n >\n <ArrowDownIcon className=\"size-3\" />\n </IconAction>\n </>\n ) : null}\n {onSteer ? (\n <IconAction\n label={`Steer queued prompt ${index + 1}`}\n tip={QUEUE_STEER_TIP}\n disabled={settling || pending !== null}\n onClick={() => onSteer(turn.id)}\n >\n {pending === \"steer\" ? (\n <Loader2Icon className=\"size-3 animate-og-spin\" />\n ) : (\n <ZapIcon className=\"size-3\" />\n )}\n </IconAction>\n ) : null}\n {onEdit ? (\n <IconAction\n label={`Edit queued prompt ${index + 1}`}\n tip={QUEUE_EDIT_TIP}\n disabled={settling || pending !== null}\n onClick={() => onEdit(turn)}\n >\n {pending === \"edit\" ? (\n <Loader2Icon className=\"size-3 animate-og-spin\" />\n ) : (\n <PencilIcon className=\"size-3\" />\n )}\n </IconAction>\n ) : null}\n {onRemove ? (\n <IconAction\n label={`Remove queued prompt ${index + 1}`}\n tip={QUEUE_DELETE_TIP}\n disabled={settling || pending !== null}\n onClick={() => onRemove(turn.id)}\n danger\n >\n {pending === \"delete\" ? (\n <Loader2Icon className=\"size-3 animate-og-spin\" />\n ) : (\n <Trash2Icon className=\"size-3\" />\n )}\n </IconAction>\n ) : null}\n </div>\n ) : null}\n </div>\n {confirmingReplace ? (\n <div className=\"rounded-og-sm border border-og-status-waiting/30 bg-og-status-waiting/10 p-2 text-og-xs text-og-fg\">\n <p>Your composer already has a draft. Replace it with this queued prompt?</p>\n <p className=\"mt-0.5 text-og-fg-muted\">\n The current draft will be permanently discarded; this queued prompt is preserved\n until you confirm.\n </p>\n <div className=\"mt-2 flex justify-end gap-1.5\">\n <button\n type=\"button\"\n className=\"rounded-og-sm px-2 py-1 font-medium hover:bg-og-surface-3/70 focus-visible:ring-2 focus-visible:ring-og-accent/40\"\n onClick={onCancelReplace}\n >\n Keep current draft\n </button>\n <button\n type=\"button\"\n className=\"rounded-og-sm bg-og-accent px-2 py-1 font-medium text-og-accent-fg hover:opacity-90 focus-visible:ring-2 focus-visible:ring-og-accent/40\"\n onClick={onConfirmReplace}\n >\n Replace and edit\n </button>\n </div>\n </div>\n ) : null}\n </li>\n );\n })}\n <AnimatePresence initial={false}>\n {optimistic.map((message, index) => (\n <motion.li\n key={message.clientEventId}\n aria-live=\"polite\"\n data-optimistic-queue-message={message.clientEventId}\n initial={reduceMotion ? false : { opacity: 0 }}\n animate={{ opacity: 1 }}\n transition={{ duration: reduceMotion ? 0 : 0.12, ease: [0.22, 1, 0.36, 1] }}\n className={cn(\n \"flex min-h-6 items-center gap-1.5 rounded-og-sm px-1.5 py-1\",\n message.state === \"failed\" ? \"bg-og-danger/8 text-og-danger\" : \"bg-og-accent-soft/45\",\n )}\n >\n <span className=\"shrink-0 font-og-mono text-[10px] leading-4 text-og-fg-subtle\">\n {turns.length + index + 1}\n </span>\n <p className=\"min-w-0 flex-1 truncate text-og-xs leading-4 text-og-fg\">\n {message.text}\n </p>\n <span className=\"sr-only\">\n {message.state === \"failed\"\n ? \"Not confirmed\"\n : message.state === \"sending\"\n ? \"Placing in queue\"\n : \"Queued\"}\n </span>\n {message.state === \"failed\" ? (\n <div className=\"flex shrink-0 items-center gap-1 text-[10px]\">\n {onRetryOptimistic ? (\n <button\n type=\"button\"\n className=\"rounded-og-sm px-1.5 py-1 font-medium hover:bg-og-surface-2 pointer-coarse:min-h-11 pointer-coarse:min-w-11\"\n onClick={() => onRetryOptimistic(message.clientEventId)}\n >\n Retry\n </button>\n ) : null}\n {onRemoveOptimistic ? (\n <button\n type=\"button\"\n aria-label=\"Dismiss unconfirmed queued prompt\"\n className=\"rounded-og-sm p-1 text-og-fg-muted hover:bg-og-surface-2 hover:text-og-fg pointer-coarse:min-h-11 pointer-coarse:min-w-11\"\n onClick={() => onRemoveOptimistic(message.clientEventId)}\n >\n <XIcon className=\"size-3\" />\n </button>\n ) : null}\n </div>\n ) : message.state === \"sending\" ? (\n <Loader2Icon\n aria-hidden=\"true\"\n className=\"size-3 shrink-0 animate-og-spin text-og-accent motion-reduce:animate-none\"\n />\n ) : (\n <CheckIcon aria-hidden=\"true\" className=\"size-3 shrink-0 text-og-accent\" />\n )}\n </motion.li>\n ))}\n </AnimatePresence>\n {loadError ? (\n <li\n role=\"alert\"\n className=\"flex items-center gap-1.5 rounded-og-sm bg-og-danger/8 px-1.5 py-1 text-og-xs text-og-danger\"\n >\n <TriangleAlertIcon className=\"size-3 shrink-0\" />\n <span className=\"min-w-0 flex-1\">Queue unavailable.</span>\n <button\n type=\"button\"\n className=\"rounded-og-sm px-1.5 py-1 font-medium hover:bg-og-surface-2 pointer-coarse:min-h-11 pointer-coarse:min-w-11\"\n onClick={() => void onRefresh()}\n >\n Retry\n </button>\n </li>\n ) : null}\n {mutationError ? (\n <li\n role=\"alert\"\n className=\"flex items-center gap-1.5 rounded-og-sm bg-og-danger/8 px-1.5 py-1 text-og-xs text-og-danger\"\n >\n <TriangleAlertIcon className=\"size-3 shrink-0\" />\n <span className=\"min-w-0 flex-1\">Not confirmed. Check the queue before retrying.</span>\n <button\n type=\"button\"\n className=\"rounded-og-sm px-1.5 py-1 font-medium hover:bg-og-surface-2 pointer-coarse:min-h-11 pointer-coarse:min-w-11\"\n onClick={onClearMutationError}\n >\n Dismiss\n </button>\n </li>\n ) : null}\n </ol>\n );\n}\n\nfunction GoalPanel({\n goal,\n state,\n elapsed,\n readOnly,\n}: {\n goal: UseGoalResult;\n state: GoalPillState;\n elapsed: string | null;\n readOnly: boolean;\n}) {\n const record = goal.goal;\n if (!record) return null;\n const canToggle = !readOnly && (record.status === \"active\" || record.status === \"paused\");\n const explanation = sessionChromeGoalPillExplanation(state, record);\n\n return (\n <div className=\"space-y-1.5\" data-og-session-chrome-panel=\"goal\">\n <div className=\"flex flex-wrap items-center gap-1.5 text-[10px] font-medium uppercase tracking-wider text-og-fg-subtle\">\n <span>{sessionChromeGoalPillLabel(state, record)}</span>\n {elapsed ? (\n <span className=\"tabular-nums normal-case tracking-normal text-og-fg-muted\">\n · {elapsed}\n </span>\n ) : null}\n <span className=\"normal-case tracking-normal text-og-fg-muted\">· v{record.version}</span>\n </div>\n <p className=\"text-og-sm leading-5 text-og-fg\">{record.text}</p>\n {record.successCriteria ? (\n <p className=\"text-og-xs leading-4 text-og-fg-muted\">\n <span className=\"font-medium text-og-fg\">Done when</span> {record.successCriteria}\n </p>\n ) : null}\n {explanation ? (\n <p\n data-og-session-chrome-goal-explanation\n className=\"text-og-xs leading-4 text-og-fg-muted\"\n >\n {explanation}\n </p>\n ) : null}\n {record.continuation?.lastError ? (\n <p className=\"rounded-og-sm bg-og-status-waiting/10 px-1.5 py-1 text-og-xs leading-4 text-og-status-waiting\">\n {record.continuation.lastError}\n </p>\n ) : null}\n <div className=\"flex flex-wrap items-center justify-between gap-1.5 pt-0.5\">\n <div className=\"flex flex-wrap gap-1 text-[10px] text-og-fg-muted\">\n <span className=\"rounded bg-og-surface-3/70 px-1 py-px\">\n {record.autoContinuations} consecutive unattended continues\n </span>\n <span className=\"rounded bg-og-surface-3/70 px-1 py-px\">\n {record.noProgressStreak} stalled\n </span>\n </div>\n {!readOnly ? (\n <div className=\"flex items-center gap-0.5\">\n {canToggle ? (\n <button\n type=\"button\"\n disabled={goal.updating}\n onClick={() =>\n void (record.status === \"paused\"\n ? goal.resume()\n : goal.pause(\"Paused from session chrome\"))\n }\n className=\"inline-flex h-6 items-center gap-1 rounded-og-sm px-1.5 text-og-xs font-medium text-og-fg-muted outline-hidden transition-colors hover:bg-og-surface-3/70 hover:text-og-fg focus-visible:ring-2 focus-visible:ring-og-accent/40 disabled:opacity-50\"\n >\n {goal.updating ? (\n <Loader2Icon className=\"size-3 animate-og-spin\" />\n ) : record.status === \"paused\" ? (\n <PlayIcon className=\"size-3\" />\n ) : (\n <PauseIcon className=\"size-3\" />\n )}\n {record.status === \"paused\" ? \"Resume\" : \"Pause\"}\n </button>\n ) : null}\n <button\n type=\"button\"\n disabled={goal.updating}\n onClick={() => void goal.deleteGoal()}\n className=\"inline-flex h-6 items-center gap-1 rounded-og-sm px-1.5 text-og-xs font-medium text-og-fg-subtle outline-hidden transition-colors hover:bg-og-surface-3/70 hover:text-og-danger focus-visible:ring-2 focus-visible:ring-og-accent/40 disabled:opacity-50\"\n >\n <Trash2Icon className=\"size-3\" />\n Clear\n </button>\n </div>\n ) : null}\n </div>\n </div>\n );\n}\n\nconst QUEUE_STEER_TIP = (\n <span className=\"flex flex-col gap-0.5 text-left\">\n <span className=\"font-medium\">Steer</span>\n <span className=\"opacity-80\">Interrupt the current turn and send this message now</span>\n </span>\n);\nconst QUEUE_EDIT_TIP = \"Edit in composer\";\nconst QUEUE_DELETE_TIP = \"Delete this queued prompt\";\n\nfunction IconAction({\n label,\n tip,\n onClick,\n disabled,\n danger,\n children,\n}: {\n label: string;\n tip: ReactNode;\n onClick: () => void;\n disabled?: boolean;\n danger?: boolean;\n children: ReactNode;\n}) {\n return (\n <Tooltip>\n <TooltipTrigger asChild>\n <button\n type=\"button\"\n aria-label={label}\n disabled={disabled}\n onClick={onClick}\n className={cn(\n \"inline-flex size-6 items-center justify-center rounded-og-sm text-og-fg-subtle outline-hidden transition-colors\",\n \"hover:bg-og-surface-2 hover:text-og-fg focus-visible:ring-2 focus-visible:ring-og-accent/40\",\n \"disabled:pointer-events-none disabled:opacity-40 pointer-coarse:size-9\",\n danger && \"hover:text-og-danger\",\n )}\n >\n {children}\n </button>\n </TooltipTrigger>\n <TooltipContent side=\"top\">{tip}</TooltipContent>\n </Tooltip>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAS,iBAAiB,eAAe,iCAAiC;AAC1E,SAAS,WAAW,OAAO,QAAQ,gBAAgD;AAuF1E,SAmJH,UAnJG,KAmJH,YAnJG;AAxDF,IAAM,gCAAwD;AAAA,EACnE,OAAO;AAAA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AAM,kBACJ,gBAAAZ,OAAC,UAAK,WAAU,mCACd;AAAA,kBAAAD,MAAC,UAAK,WAAU,eAAc,mBAAK;AAAA,EACnC,gBAAAA,MAAC,UAAK,WAAU,cAAa,kEAAoD;AAAA,GACnF;AAEF,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAEzB,SAAS,WAAW;AAAA,EAClB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAOG;AACD,SACE,gBAAAC,OAAC,WACC;AAAA,oBAAAD,MAAC,kBAAe,SAAO,MACrB,0BAAAA;AAAA,MAAC;AAAA;AAAA,QACC,MAAK;AAAA,QACL,cAAY;AAAA,QACZ;AAAA,QACA;AAAA,QACA,WAAW;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,UACA,UAAU;AAAA,QACZ;AAAA,QAEC;AAAA;AAAA,IACH,GACF;AAAA,IACA,gBAAAA,MAAC,kBAAe,MAAK,OAAO,eAAI;AAAA,KAClC;AAEJ;","names":["useEffect","useRef","jsx","useRef","useEffect","useEffect","useRef","useState","jsx","jsxs","useState","useRef","useEffect","useEffect","useMemo","useRef","useState","jsx","jsxs","useState","useRef","useEffect","useMemo","useId","useRef","useState","jsx","jsxs","useState","useRef","useId","createContext","useContext","jsx","createContext","useContext","useState","Fragment","jsx","jsxs","createContext","useState","useContext","useEffect","useState","jsx","useState","useEffect","query","CameraIcon","CameraOffIcon","MessageCircleQuestionIcon","useEffect","useRef","useState","createContext","useContext","useState","useEffect","useState","jsx","jsxs","useState","jsx","jsxs","file","CameraIcon","CameraOffIcon","useState","useRef","useEffect","query","MessageCircleQuestionIcon","BrainCircuitIcon","lazy","Suspense","useLayoutEffect","useRef","createContext","useContext","useRef","jsx","createContext","useContext","Fragment","jsx","jsxs","lazy","useRef","useLayoutEffect","Suspense","BrainCircuitIcon","ChevronRightIcon","createContext","useContext","useEffect","useMemo","useRef","useState","createContext","useContext","Fragment","jsx","jsxs","createContext","useContext","useState","useRef","useEffect","useMemo","ChevronRightIcon","useEffect","useState","jsx","useState","useEffect","jsx","jsxs","ArrowRightIcon","BotIcon","CheckIcon","ChevronRightIcon","MessageCircleQuestionIcon","TargetIcon","TriangleAlertIcon","Collapsible","Component","Suspense","lazy","memo","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","Fragment","jsx","jsxs","lazy","receipt","useMemo","useRef","useState","useCallback","useEffect","useLayoutEffect","attempt","Suspense","node","Component","TriangleAlertIcon","memo","TimelineGroupEntry","TimelineGroupView","MessageCircleQuestionIcon","BotIcon","ArrowRightIcon","Collapsible","ChevronRightIcon","TargetIcon","CheckIcon","lazy","Suspense","jsx","jsxs","lazy","jsx","Suspense","jsxs","ArrowDownIcon","BotIcon","CheckIcon","Loader2Icon","PauseIcon","PlayIcon","Trash2Icon","TriangleAlertIcon","AnimatePresence","motion","useEffect","useId","useMemo","useRef","useState","Fragment","jsx","jsxs","useState","useEffect","useId","useMemo","TriangleAlertIcon","Loader2Icon","PauseIcon","BotIcon","useRef","motion","AnimatePresence","Trash2Icon","ArrowDownIcon","CheckIcon","PlayIcon"]}