@opengeni/react 6.0.0-canary.1 → 6.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -0
- package/dist/{chunk-PZ27MCZP.js → chunk-L2NBTKRX.js} +14 -2
- package/dist/chunk-L2NBTKRX.js.map +1 -0
- package/dist/{chunk-CC7AVRIJ.js → chunk-TDSEILUH.js} +80 -7
- package/dist/chunk-TDSEILUH.js.map +1 -0
- package/dist/components/message-timeline.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/session-ui.js +2 -2
- package/dist/session.js +1 -1
- package/package.json +3 -3
- package/src/components/message-timeline.tsx +88 -4
- package/src/components/session-conversation.tsx +1 -3
- package/src/hooks/use-session-events.ts +17 -1
- package/styles/compiled.css +3 -0
- package/dist/chunk-CC7AVRIJ.js.map +0 -1
- package/dist/chunk-PZ27MCZP.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/components/human-input-form.tsx","../src/components/human-input-surface.tsx","../src/components/approval-surface.tsx","../src/timeline/disclosure-context.tsx","../src/timeline/shared.tsx","../src/timeline/knowledge-receipt.tsx","../src/timeline/startup-preference.ts","../src/timeline/parsers.ts","../src/timeline/registry.ts","../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/genie-loading.tsx","../src/timeline/entrance.tsx","../src/timeline/seen-activity-ids.ts","../src/components/user-message-body.tsx","../src/timeline/turn-summary.tsx","../src/timeline/fold-memory.ts","../src/components/generated-video-player.tsx","../src/components/session-status.tsx","../src/timeline/rolling-activity.tsx","../src/components/child-session-link.tsx","../src/components/message-timeline.tsx","../src/components/timeline-anchor.tsx","../src/components/tip-follow.ts","../src/components/machine-input-display.ts","../src/components/queue-surface.tsx","../src/hooks/use-available-models.ts","../src/components/chat-composer.tsx","../src/components/session-conversation.tsx","../src/conversation-timeline.ts","../src/components/session-chrome.tsx","../src/components/session-commands-panel.tsx","../src/timeline/startup-timings.tsx"],"sourcesContent":["import type {\n HumanInputAnswer,\n HumanInputQuestion,\n SkillRecord,\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 /** Scoped immutable revision reader. Saving a Skill fails closed without its full preview. */\n loadSkillReview?:\n | ((reference: NonNullable<HumanInputQuestion[\"skillReview\"]>) => Promise<SkillRecord>)\n | undefined;\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 loadSkillReview,\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 const reviewIdentity = JSON.stringify(\n request.questions\n .filter((question) => question.skillReview)\n .map((question) => ({\n id: question.id,\n reference: {\n sourceOperationId: question.skillReview!.sourceOperationId,\n skillId: question.skillReview!.skillId,\n revisionId: question.skillReview!.revisionId,\n expectedRevisionId: question.skillReview!.expectedRevisionId,\n expectedScopeVersion: question.skillReview!.expectedScopeVersion,\n },\n })),\n );\n const [reviewReload, setReviewReload] = useState(0);\n const [reviews, setReviews] = useState<{\n loader: typeof loadSkillReview;\n identity: string;\n records: Record<string, SkillRecord>;\n error: string | null;\n } | null>(null);\n useEffect(() => {\n let current = true;\n const questions = JSON.parse(reviewIdentity) as Array<{\n id: string;\n reference: NonNullable<HumanInputQuestion[\"skillReview\"]>;\n }>;\n if (!questions.length) return;\n setReviews(null);\n void Promise.all(\n questions.map(async (question) => {\n if (!loadSkillReview)\n throw new Error(\n \"This client cannot preview Skill files. Open this request in OpenGeni to review it.\",\n );\n const reference = question.reference;\n const record = await loadSkillReview(reference);\n if (\n record.id !== reference.skillId ||\n record.revisionId !== reference.revisionId ||\n !record.files.some((file) => file.path === \"SKILL.md\")\n ) {\n throw new Error(\"The requested Skill revision could not be verified.\");\n }\n return [question.id, record] as const;\n }),\n )\n .then((records) => {\n if (current)\n setReviews({\n loader: loadSkillReview,\n identity: reviewIdentity,\n records: Object.fromEntries(records),\n error: null,\n });\n })\n .catch((cause) => {\n if (current)\n setReviews({\n loader: loadSkillReview,\n identity: reviewIdentity,\n records: {},\n error: cause instanceof Error ? cause.message : \"Could not load the Skill files.\",\n });\n });\n return () => {\n current = false;\n };\n }, [loadSkillReview, reviewIdentity, reviewReload]);\n const visibleReviews =\n reviews?.loader === loadSkillReview && reviews?.identity === reviewIdentity ? reviews : null;\n const preview = (question: HumanInputQuestion) => {\n if (!question.skillReview) return null;\n const record = visibleReviews?.records[question.id];\n return (\n <div className=\"mb-3 min-w-0 space-y-2\" data-skill-review=\"\">\n {record ? (\n <>\n <p className=\"text-og-sm\">\n {record.title ?? \"Skill\"} · {record.scope} · {record.files.length} files\n </p>\n <p className=\"text-og-xs text-og-fg-muted\">\n Saving activates these exact files. No additional review is required.\n </p>\n {record.files.map((file) => (\n <details key={file.path} open={file.path === \"SKILL.md\"}>\n <summary className=\"cursor-pointer break-all text-og-sm\">{file.path}</summary>\n <pre className=\"max-h-64 overflow-auto whitespace-pre-wrap break-words rounded-og-md bg-og-surface-1 p-2 text-og-xs\">\n {file.content}\n </pre>\n </details>\n ))}\n </>\n ) : visibleReviews?.error ? (\n <>\n <p role=\"alert\" className=\"text-og-sm\">\n {visibleReviews.error}\n </p>\n <button type=\"button\" onClick={() => setReviewReload((value) => value + 1)}>\n Retry preview\n </button>\n </>\n ) : (\n <p role=\"status\" className=\"text-og-sm\">\n Loading the exact Skill files…\n </p>\n )}\n </div>\n );\n };\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 const unreviewedSave = request.questions.find(\n (question) =>\n question.skillReview &&\n !visibleReviews?.records[question.id] &&\n result.answers.some(\n (answer) => answer.questionId === question.id && answer.values.includes(\"save\"),\n ),\n );\n if (unreviewedSave) {\n setValidationErrors({ [unreviewedSave.id]: \"Load the exact Skill files before saving.\" });\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 {preview(question)}\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 {preview(question)}\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 {!question.skillReview ? (\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 ) : null}\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 loadSkillReview?: HumanInputFormProps[\"loadSkillReview\"];\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 loadSkillReview,\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 loadSkillReview,\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, ShieldCheckIcon, XIcon } from \"lucide-react\";\nimport { useEffect, useId, useRef, useState, type ReactNode } from \"react\";\nimport type { PendingApproval } from \"../approvals\";\nimport { cn } from \"../lib/cn\";\n\nexport type ApprovalSurfaceMessages = {\n title: string;\n description: string;\n approve: string;\n reject: string;\n approving: string;\n rejecting: string;\n formatToolName: (name: string) => string;\n};\n\nexport const defaultApprovalSurfaceMessages: ApprovalSurfaceMessages = {\n title: \"Approval required\",\n description: \"Review the requested action before the agent continues.\",\n approve: \"Approve\",\n reject: \"Reject\",\n approving: \"Approving…\",\n rejecting: \"Rejecting…\",\n formatToolName: (name) => name.replaceAll(\"_\", \" \").replaceAll(\".\", \" › \"),\n};\n\nexport type ApprovalSurfaceProps = {\n approvals: PendingApproval[];\n onApprove: (approval: PendingApproval) => void | Promise<void>;\n onReject: (approval: PendingApproval) => void | Promise<void>;\n responding?: boolean | undefined;\n error?: string | Error | null | undefined;\n messages?: Partial<ApprovalSurfaceMessages> | undefined;\n renderApproval?: ((approval: PendingApproval) => ReactNode) | undefined;\n className?: string | undefined;\n};\n\nconst APPROVAL_ARGUMENT_PREVIEW_CHARACTERS = 4_000;\n\nfunction approvalArgumentsPreview(value: unknown): string | null {\n if (value === undefined) return null;\n let serialized: string;\n try {\n serialized =\n typeof value === \"string\" ? value : (JSON.stringify(value, null, 2) ?? String(value));\n } catch {\n serialized = \"[Arguments unavailable]\";\n }\n const characters = Array.from(serialized);\n if (characters.length <= APPROVAL_ARGUMENT_PREVIEW_CHARACTERS) return serialized;\n return `${characters.slice(0, APPROVAL_ARGUMENT_PREVIEW_CHARACTERS).join(\"\")}\\n… ${characters.length - APPROVAL_ARGUMENT_PREVIEW_CHARACTERS} characters omitted`;\n}\n\nfunction approvalOwnershipKey(approval: PendingApproval): string {\n return `${approval.id}\\u0000${approval.name}\\u0000${approvalArgumentsPreview(approval.arguments) ?? \"\"}`;\n}\n\n/**\n * Host-neutral approval presentation backed by the native pending-approval\n * projection and control callbacks. It owns only presentation and duplicate\n * click fencing; OpenGeni remains the authority for approval state.\n */\nexport function ApprovalSurface({\n approvals,\n onApprove,\n onReject,\n responding = false,\n error,\n messages: overrides,\n renderApproval,\n className,\n}: ApprovalSurfaceProps) {\n const titleId = useId();\n const messages = { ...defaultApprovalSurfaceMessages, ...overrides };\n const [pending, setPending] = useState<{\n approvalKey: string;\n decision: \"approve\" | \"reject\";\n token: symbol;\n } | null>(null);\n const pendingRef = useRef<{ approvalKey: string; token: symbol } | null>(null);\n const [decisionError, setDecisionError] = useState<Error | null>(null);\n\n useEffect(() => {\n if (\n pending &&\n !approvals.some((approval) => approvalOwnershipKey(approval) === pending.approvalKey)\n ) {\n if (pendingRef.current?.token === pending.token) {\n pendingRef.current = null;\n }\n setPending((current) => (current?.token === pending.token ? null : current));\n }\n }, [approvals, pending]);\n\n if (approvals.length === 0) return null;\n const busy = responding || pendingRef.current !== null;\n const decide = async (\n approval: PendingApproval,\n decision: \"approve\" | \"reject\",\n ): Promise<void> => {\n if (responding || pendingRef.current !== null) return;\n const approvalKey = approvalOwnershipKey(approval);\n const token = Symbol(approvalKey);\n pendingRef.current = { approvalKey, token };\n setPending({ approvalKey, decision, token });\n setDecisionError(null);\n try {\n await (decision === \"approve\" ? onApprove(approval) : onReject(approval));\n // Keep the decision fenced until the authoritative projection removes or\n // replaces this exact approval. A successful callback is transport\n // acceptance, not settlement.\n } catch (cause) {\n if (pendingRef.current?.token === token) {\n pendingRef.current = null;\n setPending((current) => (current?.token === token ? null : current));\n setDecisionError(cause instanceof Error ? cause : new Error(String(cause)));\n }\n }\n };\n const errorMessage = decisionError?.message ?? (error instanceof Error ? error.message : error);\n\n return (\n <section\n className={cn(\n \"og-root flex w-full flex-col gap-3 rounded-og-lg border border-og-status-waiting/35 bg-og-status-waiting/5 p-4 shadow-og-sm\",\n className,\n )}\n aria-labelledby={titleId}\n >\n <header 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 <ShieldCheckIcon aria-hidden=\"true\" className=\"size-4\" />\n </span>\n <div className=\"min-w-0\">\n <h2 id={titleId} className=\"text-og-md font-semibold text-og-fg\">\n {messages.title}\n </h2>\n <p className=\"mt-0.5 text-og-sm text-og-fg-muted\">{messages.description}</p>\n </div>\n </header>\n\n <div className=\"flex flex-col gap-2\">\n {approvals.map((approval) => {\n const approvalKey = approvalOwnershipKey(approval);\n const active = pending?.approvalKey === approvalKey ? pending.decision : null;\n const argumentsPreview = approvalArgumentsPreview(approval.arguments);\n return (\n <article\n key={approval.id}\n data-approval-id={approval.id}\n className=\"rounded-og-md border border-og-border bg-og-surface-1 p-3\"\n >\n {renderApproval ? (\n renderApproval(approval)\n ) : (\n <>\n <p className=\"text-og-sm font-medium text-og-fg\">\n {messages.formatToolName(approval.name)}\n </p>\n {argumentsPreview !== null ? (\n <pre className=\"mt-2 max-h-48 overflow-auto whitespace-pre-wrap break-words rounded-og-sm bg-og-surface-2 p-2 font-mono text-og-xs text-og-fg-muted\">\n {argumentsPreview}\n </pre>\n ) : null}\n </>\n )}\n <div className=\"mt-3 flex flex-wrap justify-end gap-2\">\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => void decide(approval, \"reject\")}\n className=\"inline-flex min-h-9 items-center gap-1.5 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-2 hover:text-og-fg disabled:opacity-50\"\n >\n <XIcon aria-hidden=\"true\" className=\"size-3.5\" />\n {active === \"reject\" ? messages.rejecting : messages.reject}\n </button>\n <button\n type=\"button\"\n disabled={busy}\n onClick={() => void decide(approval, \"approve\")}\n className=\"inline-flex min-h-9 items-center gap-1.5 rounded-og-md bg-og-accent px-3 py-1.5 text-og-sm font-medium text-og-accent-fg transition-colors hover:bg-og-accent-strong disabled:opacity-50\"\n >\n <CheckIcon aria-hidden=\"true\" className=\"size-3.5\" />\n {active === \"approve\" ? messages.approving : messages.approve}\n </button>\n </div>\n </article>\n );\n })}\n </div>\n\n {errorMessage ? (\n <p role=\"alert\" className=\"text-og-sm text-og-status-failed\">\n {errorMessage}\n </p>\n ) : null}\n </section>\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 /** Override the rolling preview; null keeps rapidly streaming details out of the header. */\n compactPreview?: ReactNode;\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 const CompactActivityContext = createContext(false);\n\nexport function ActivityDisclosure({\n icon,\n iconTone: iconToneProp = \"muted\",\n title,\n titleMono,\n running,\n preview,\n compactPreview,\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 compact = useContext(CompactActivityContext);\n if (compact)\n return (\n <span className=\"og-rolling-label\">\n <span className={cn(\"shrink-0\", ICON_TONE[iconTone])}>{icon}</span>\n <span className=\"og-command-reel\">\n <span className=\"og-reel-title\">{title}</span>\n {(compactPreview === undefined ? preview : compactPreview) ? (\n <span className=\"og-reel-preview text-og-fg-subtle\">\n {compactPreview === undefined ? preview : compactPreview}\n </span>\n ) : null}\n </span>\n </span>\n );\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 className={cn(\"og-command-reel\", running && \"og-command-reel-running\")}>\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 )}\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 </span>\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 { createContext, useContext, useState, type ReactNode } from \"react\";\nimport { BrainCircuitIcon } from \"lucide-react\";\nimport { ActivityDisclosure, BodyNote } from \"./shared\";\n\nexport type KnowledgeActivityActions = {\n onInspect?: ((entryId: string) => void) | undefined;\n onRetryFile?: ((fileId: string) => Promise<boolean | void>) | undefined;\n retryDisabled?: boolean | undefined;\n};\nconst KnowledgeActions = createContext<KnowledgeActivityActions>({});\nexport function KnowledgeActivityProvider({\n children,\n ...actions\n}: KnowledgeActivityActions & { children: ReactNode }) {\n return <KnowledgeActions.Provider value={actions}>{children}</KnowledgeActions.Provider>;\n}\n\n/** A saved/pending result never opens or blocks the human-input surface. */\nexport function KnowledgeReceiptRow(props: {\n outcome: \"published\" | \"pending\" | \"rejected\" | \"archived\" | \"failed\";\n entryId?: string | undefined;\n fileId?: string | undefined;\n title?: string | undefined;\n source?: boolean | undefined;\n}) {\n const actions = useContext(KnowledgeActions);\n const [retrying, setRetrying] = useState(false);\n const [retrySent, setRetrySent] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const label =\n props.outcome === \"pending\"\n ? \"Knowledge saved for review\"\n : props.outcome === \"failed\"\n ? \"Source preparation failed\"\n : props.outcome === \"rejected\"\n ? \"Source remains rejected\"\n : props.outcome === \"archived\"\n ? \"Knowledge archived\"\n : props.source\n ? \"Source saved to Knowledge\"\n : \"Saved to Knowledge\";\n const actionClass =\n \"rounded-og-sm px-1 py-0.5 text-og-sm text-og-fg-muted hover:text-og-fg focus-visible:outline-2 focus-visible:outline-og-accent disabled:opacity-50\";\n return (\n <ActivityDisclosure\n icon={<BrainCircuitIcon className=\"size-3.5\" />}\n iconTone=\"muted\"\n title={label}\n preview={props.title}\n >\n {props.outcome === \"pending\" ? (\n <BodyNote>\n Saved in Needs review. This task continues; future tasks can use it after approval.\n </BodyNote>\n ) : null}\n {props.outcome === \"failed\" ? (\n <BodyNote>\n The original file remains attached. Searchable text has not been retained.\n </BodyNote>\n ) : null}\n {props.outcome === \"rejected\" ? (\n <BodyNote>Processing the file again leaves the review decision unchanged.</BodyNote>\n ) : null}\n {props.entryId && actions.onInspect ? (\n <button\n className={actionClass}\n type=\"button\"\n onClick={() => actions.onInspect?.(props.entryId!)}\n >\n {props.outcome === \"pending\" ? \"Review in Knowledge\" : \"View in Knowledge\"}\n </button>\n ) : null}\n {props.outcome === \"failed\" && props.fileId && actions.onRetryFile ? (\n <button\n className={actionClass}\n type=\"button\"\n disabled={retrying || retrySent || actions.retryDisabled}\n onClick={() => {\n setRetrying(true);\n setError(null);\n void actions.onRetryFile!(props.fileId!)\n .then((sent) => {\n if (sent !== false) setRetrySent(true);\n else setError(\"Could not start the retry. Try again when the chat is ready.\");\n })\n .catch(() => setError(\"Could not start the retry. Please try again.\"))\n .finally(() => setRetrying(false));\n }}\n >\n {retrying ? \"Starting retry…\" : retrySent ? \"Retry requested\" : \"Retry preparation\"}\n </button>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-og-sm\">\n {error}\n </p>\n ) : null}\n </ActivityDisclosure>\n );\n}\n","import { useSyncExternalStore } from \"react\";\n\nconst KEY = \"opengeni:startup-details:v1\";\nconst EVENT = \"opengeni:startup-details-changed\";\nlet fallback = false;\nfunction snapshot() {\n try {\n return window.localStorage.getItem(KEY) === \"true\";\n } catch {\n return fallback;\n }\n}\nfunction subscribe(listener: () => void) {\n window.addEventListener(EVENT, listener);\n window.addEventListener(\"storage\", listener);\n return () => {\n window.removeEventListener(EVENT, listener);\n window.removeEventListener(\"storage\", listener);\n };\n}\nexport function setStartupDetails(value: boolean) {\n fallback = value;\n try {\n window.localStorage.setItem(KEY, String(value));\n } catch {\n /* Private storage is optional. */\n }\n window.dispatchEvent(new Event(EVENT));\n}\n/** Presentation preference only. Startup evidence is always retained. */\nexport function useStartupDetails() {\n return useSyncExternalStore(subscribe, snapshot, () => false);\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 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. allowed 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 | {\n match: \"name\";\n name: string;\n render: ToolRenderer;\n /** Disable untrusted `<server>__${name}` leaf matching for identity-sensitive renderers. */\n matchPrefixedLeaf?: boolean | undefined;\n };\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 const byPrefixedLeaf = 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 if (entry.match === \"name\" && entry.matchPrefixedLeaf !== false) {\n if (!byPrefixedLeaf.has(entry.name)) {\n byPrefixedLeaf.set(entry.name, entry.render);\n }\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 = byPrefixedLeaf.get(leaf);\n if (byLeaf) {\n return byLeaf;\n }\n }\n return fallback;\n };\n\n return { resolve, fallback };\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 { KnowledgeReceiptRow } from \"./knowledge-receipt\";\nimport { isRetainedImageContentType, useRetainedImageObjectUrl } from \"./retained-image\";\nimport {\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 { useContext, 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 CompactActivityContext,\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 const compact = useContext(CompactActivityContext);\n return (\n <span className=\"inline-flex items-center gap-1.5\">\n {!compact && (\n <span className=\"size-1.5 shrink-0 animate-og-pulse rounded-full bg-og-status-running\" />\n )}\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'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\nfunction RetainedSessionImageDisclosure({\n artifact,\n load,\n title,\n caption,\n noun,\n icon,\n lightboxLabel,\n batched,\n failed,\n cancelled,\n filename,\n defaultOpen,\n children,\n}: {\n artifact: RetainedArtifactReference;\n load: ToolRendererProps[\"loadRetainedArtifact\"];\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 filename?: string;\n defaultOpen?: boolean;\n children?: ReactNode;\n}) {\n const state = useRetainedImageObjectUrl(artifact, load);\n const downloadFilename = filename ?? retainedImageFilename(artifact);\n\n return (\n <ActivityDisclosure\n icon={icon}\n iconTone={failed ? \"failed\" : state.kind === \"ready\" ? \"accent\" : \"muted\"}\n title={title}\n defaultOpen={defaultOpen}\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 {children}\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 // The closed SDK receipt has already checked the workspace-qualified route.\n const workspaceId = /^\\/v1\\/workspaces\\/([0-9a-f-]+)\\/artifacts\\//.exec(\n receipt.artifact.retrieval.path,\n )?.[1];\n const openLink = workspaceId ? (\n <a\n href={`/workspaces/${workspaceId}/artifacts/files/${receipt.artifact.artifactId}`}\n aria-label={`Open ${receipt.filename} in Artifacts`}\n className=\"inline-flex min-h-7 items-center rounded-og-sm px-2 text-og-sm font-medium text-og-accent-strong hover:bg-og-surface-2 hover:underline focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-og-accent pointer-coarse:min-h-10\"\n onClick={(event) => event.stopPropagation()}\n onKeyDown={(event) => event.stopPropagation()}\n >\n Open in Artifacts\n </a>\n ) : null;\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 const downloadButton = (\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 );\n\n if (isRetainedImageContentType(receipt.artifact.contentType)) {\n return (\n <RetainedSessionImageDisclosure\n artifact={receipt.artifact}\n load={loadRetainedArtifact}\n title={`Published ${receipt.filename}`}\n caption={receipt.filename}\n noun=\"image\"\n icon={<ImageIcon className={ICON_SIZE} />}\n lightboxLabel=\"Image\"\n batched={null}\n failed={false}\n cancelled={false}\n filename={receipt.filename}\n defaultOpen\n >\n {downloadButton}\n {openLink}\n </RetainedSessionImageDisclosure>\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 {downloadButton}\n {openLink}\n </ActivityDisclosure>\n );\n}\n\ntype PublishedSiteReceipt = {\n workspaceId: string;\n artifactId: string;\n title: string;\n revision: number;\n replayed: boolean;\n};\n\nfunction publishedSiteReceipt(output: unknown): PublishedSiteReceipt | null {\n const { text, isError } = unwrapMcpOutput(output);\n if (isError) return null;\n const parsed = tryParseJson(text);\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) return null;\n const artifact = (parsed as Record<string, unknown>).artifact;\n const version = (parsed as Record<string, unknown>).version;\n if (\n !artifact ||\n typeof artifact !== \"object\" ||\n Array.isArray(artifact) ||\n !version ||\n typeof version !== \"object\" ||\n Array.isArray(version)\n ) {\n return null;\n }\n const artifactRecord = artifact as Record<string, unknown>;\n const versionRecord = version as Record<string, unknown>;\n if (\n typeof artifactRecord.workspaceId !== \"string\" ||\n typeof artifactRecord.id !== \"string\" ||\n typeof artifactRecord.title !== \"string\" ||\n typeof versionRecord.revision !== \"number\" ||\n !Number.isInteger(versionRecord.revision) ||\n versionRecord.revision < 1\n ) {\n return null;\n }\n return {\n workspaceId: artifactRecord.workspaceId,\n artifactId: artifactRecord.id,\n title: artifactRecord.title,\n revision: versionRecord.revision,\n replayed: (parsed as Record<string, unknown>).replayed === true,\n };\n}\n\nfunction SiteOpenLink({ receipt }: { receipt: PublishedSiteReceipt }) {\n const href = `/workspaces/${encodeURIComponent(receipt.workspaceId)}/artifacts/${encodeURIComponent(receipt.artifactId)}`;\n return (\n <a\n href={href}\n aria-label={`Open ${receipt.title}`}\n className=\"inline-flex min-h-7 items-center rounded-og-sm px-2 text-og-sm font-medium text-og-accent-strong hover:bg-og-surface-2 hover:underline focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-og-accent pointer-coarse:min-h-10\"\n onClick={(event) => event.stopPropagation()}\n onKeyDown={(event) => event.stopPropagation()}\n >\n Open\n </a>\n );\n}\n\nfunction SiteArtifactRenderer({ item }: ToolRendererProps) {\n const leaf = mcpToolLeaf(item.name);\n const publishingExisting = leaf === \"artifacts_publish\";\n if (item.status === \"running\") {\n return (\n <ActivityDisclosure\n icon={<PanelsTopLeftIcon className={ICON_SIZE} />}\n iconTone=\"running\"\n title={publishingExisting ? \"Publishing Site update\" : \"Publishing Site\"}\n running\n preview={<RunningPreview>retaining source and compiled HTML…</RunningPreview>}\n />\n );\n }\n const receipt = publishedSiteReceipt(item.output);\n if (!receipt || item.status === \"failed\") return <GenericRenderer item={item} />;\n return (\n <ActivityDisclosure\n icon={<PanelsTopLeftIcon className={ICON_SIZE} />}\n iconTone=\"accent\"\n title={publishingExisting ? `Updated ${receipt.title}` : `Published ${receipt.title}`}\n media={<SiteOpenLink receipt={receipt} />}\n >\n <BodyNote>\n Version {receipt.revision} is live\n {receipt.replayed ? \" (replayed from the original publication).\" : \".\"}\n </BodyNote>\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 !== \"wait_for_input\"\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.startsWith(\"skill_\")\n ? PlugIcon\n : WrenchIcon;\n return <Icon className={ICON_SIZE} />;\n}\n\n/* ---- the default registry -------------------------------------------------- */\n\nfunction KnowledgeSaveRenderer({ item }: ToolRendererProps) {\n const output = unwrapMcpOutput(item.output);\n const parsed = tryParseJson(output.text);\n if (item.status === \"running\" || output.isError || !parsed || typeof parsed !== \"object\")\n return <GenericRenderer item={item} />;\n const value = parsed as Record<string, unknown>;\n const receipt = (value.status === \"retained\" ? value.receipt : value) as\n | Record<string, unknown>\n | undefined;\n if (\n !receipt ||\n typeof receipt.entryId !== \"string\" ||\n ![\"published\", \"pending\", \"rejected\", \"archived\"].includes(String(receipt.outcome))\n )\n return <GenericRenderer item={item} />;\n const args = parseToolArgs(item.arguments);\n const entry = args.entry as Record<string, unknown> | undefined;\n return (\n <KnowledgeReceiptRow\n outcome={receipt.outcome as \"published\" | \"pending\" | \"rejected\" | \"archived\"}\n entryId={receipt.entryId}\n title={\n typeof entry?.title === \"string\"\n ? entry.title\n : typeof value.filename === \"string\"\n ? value.filename\n : undefined\n }\n source={value.status === \"retained\" || value.retained === true}\n />\n );\n}\n\nconst BASE_ENTRIES: ToolRegistryEntry[] = [\n ...[\n \"knowledge_save\",\n \"knowledge_archive\",\n \"knowledge_retain_file\",\n \"knowledge_retain_message\",\n \"task_note_promote_knowledge\",\n ].flatMap((name) =>\n [name, `opengeni__${name}`, `mcp__opengeni__${name}`].map((trustedName) => ({\n match: \"name\" as const,\n name: trustedName,\n matchPrefixedLeaf: false,\n render: KnowledgeSaveRenderer,\n })),\n ),\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 {\n match: \"name\",\n name: \"artifacts_create\",\n render: SiteArtifactRenderer,\n matchPrefixedLeaf: false,\n },\n {\n match: \"name\",\n name: \"artifacts_publish\",\n render: SiteArtifactRenderer,\n matchPrefixedLeaf: false,\n },\n {\n match: \"name\",\n name: \"opengeni__artifacts_create\",\n render: SiteArtifactRenderer,\n matchPrefixedLeaf: false,\n },\n {\n match: \"name\",\n name: \"opengeni__artifacts_publish\",\n render: SiteArtifactRenderer,\n matchPrefixedLeaf: false,\n },\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 { KnowledgeReceiptRow } from \"./knowledge-receipt\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { GenieLoading } from \"./genie-loading\";\nimport { useStartupDetails } from \"./startup-preference\";\nimport { ArrowRightIcon, BotIcon, BrainCircuitIcon } from \"lucide-react\";\nimport { lazy, Suspense, useContext, useLayoutEffect, useRef, useState } 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 {\n BodyNote,\n PayloadBlock,\n ActivityDisclosure,\n CompactActivityContext,\n ToolCallTruncationProvider,\n} 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 /** The owning turn remains active between individual phase receipts. */\n startupActive?: boolean;\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 startupActive,\n toolRegistry = defaultToolRegistry,\n onOpenSession,\n onMemoryClick,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n bare,\n className,\n}: ActivityRailProps) {\n const debug = useStartupDetails();\n const reducedMotion = useReducedMotion();\n const [detailsOpen, setDetailsOpen] = useState(false);\n const phases = items.filter((item) => item.kind === \"startup-phase\");\n // Empty reasoning envelopes can arrive before any visible model output.\n const hasWork = items.some(\n (item) =>\n item.kind !== \"startup-phase\" && (item.kind !== \"reasoning\" || item.text.trim().length > 0),\n );\n const interrupted = phases.some(\n (item) => item.status === \"failed\" || item.status === \"cancelled\",\n );\n const providerResponded = phases.some(\n (item) => item.phase === \"provider_first_byte\" && item.status === \"complete\",\n );\n const preparing =\n !hasWork &&\n !interrupted &&\n (startupActive ?? (!providerResponded && phases.some((item) => item.status === \"running\")));\n const visibleItems =\n debug || detailsOpen\n ? items\n : items.filter((item) =>\n item.kind === \"startup-phase\"\n ? item.status === \"failed\" || item.status === \"cancelled\"\n : item.kind !== \"reasoning\" || item.text.trim().length > 0,\n );\n const startedAt = phases.reduce(\n (first, item) => (item.startedAt < first ? item.startedAt : first),\n phases[0]?.startedAt ?? \"\",\n );\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 \"relative 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 <AnimatePresence initial={false}>\n {preparing && !debug ? (\n <motion.div\n key=\"startup\"\n initial={{ opacity: 0 }}\n animate={{ opacity: 1, height: \"auto\" }}\n exit={{\n opacity: 0,\n height: 0,\n pointerEvents: \"none\",\n }}\n transition={{\n height: { duration: reducedMotion ? 0 : 0.32, ease: [0.22, 1, 0.36, 1] },\n opacity: { duration: reducedMotion ? 0 : 0.16 },\n }}\n style={{ overflow: \"hidden\" }}\n >\n <GenieLoading\n startedAt={startedAt}\n detailsOpen={detailsOpen}\n onShowDetails={() => setDetailsOpen((open) => !open)}\n />\n </motion.div>\n ) : null}\n </AnimatePresence>\n {detailsOpen && !debug && !preparing ? (\n <button\n type=\"button\"\n className=\"og-genie-details self-start\"\n onClick={() => setDetailsOpen(false)}\n >\n Hide startup details\n </button>\n ) : null}\n {visibleItems.map((item, index) => {\n const newFamily = index > 0 && familyOf(item) !== familyOf(visibleItems[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\nexport function 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 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 \"knowledge\":\n return (\n <KnowledgeReceiptRow\n outcome={item.outcome}\n entryId={item.entryId}\n fileId={item.fileId}\n title={item.filename}\n source={Boolean(item.fileId)}\n />\n );\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 compact = useContext(CompactActivityContext);\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 if (compact) {\n return (\n <ActivityDisclosure\n icon={<BotIcon className=\"size-3.5\" />}\n title={title}\n preview={item.prompt}\n running={running}\n />\n );\n }\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 { ThinkingOrb } from \"thinking-orbs\";\nimport { useThemeType } from \"../lib/use-theme-type\";\nimport { createContext, useContext, useEffect, useState, type ReactNode } from \"react\";\n\nexport type GenieLoadingRenderProps = {\n startedAt: string;\n detailsOpen: boolean;\n onShowDetails: () => void;\n};\n\nexport type GenieLoadingOptions = {\n /** Replace the visual while preserving SDK loading visibility and transitions. */\n render?: (props: GenieLoadingRenderProps) => ReactNode;\n phrases?: readonly string[];\n /** Native copy overrides. Omitted messages retain the default English copy. */\n messages?: {\n status?: string;\n slowStatus?: string;\n slowText?: string;\n showDetails?: string;\n hideDetails?: string;\n };\n /** Public adapter options; the renderer dependency's declarations stay private. */\n orb?: {\n state?:\n | \"working\"\n | \"searching\"\n | \"solving\"\n | \"listening\"\n | \"connecting\"\n | \"weaving\"\n | \"composing\"\n | \"breathing\"\n | \"shaping\";\n size?: 64 | 20;\n speed?: number;\n };\n};\nexport const GenieLoadingOptionsContext = createContext<GenieLoadingOptions | undefined>(undefined);\n\nconst PHRASES = [\n \"Polishing the lamp…\",\n \"Consulting the carpet…\",\n \"Untangling wishes…\",\n \"Summoning a little cleverness…\",\n \"Checking the fine print on infinity…\",\n \"Warming up the abracadabra…\",\n \"Rearranging the stars…\",\n \"Negotiating with the lamp…\",\n \"Dusting off a thousand years…\",\n \"Wishful thinking…\",\n \"Decanting a little magic…\",\n \"Finding the good stardust…\",\n \"Fluffing the magic carpet…\",\n \"Putting a wish into motion…\",\n \"A little hocus. A little pocus…\",\n];\n\n/** Decorative copy never substitutes for a failure or claims measurable progress. */\nexport function GenieLoading({\n startedAt,\n onShowDetails,\n detailsOpen = false,\n}: {\n startedAt: string;\n onShowDetails: () => void;\n detailsOpen?: boolean;\n}) {\n const options = useContext(GenieLoadingOptionsContext);\n const phrases = options?.phrases?.length ? options.phrases : PHRASES;\n const theme = useThemeType(undefined);\n const [phrase, setPhrase] = useState(0);\n const [showDetails, setShowDetails] = useState(false);\n const [slow, setSlow] = useState(false);\n useEffect(() => {\n const update = () => {\n setShowDetails(Date.now() - Date.parse(startedAt) >= 15_000);\n setSlow(Date.now() - Date.parse(startedAt) >= 30_000);\n if (!document.hidden) setPhrase(Math.floor(Math.random() * phrases.length));\n };\n update();\n const timer = window.setInterval(update, 5_000);\n return () => window.clearInterval(timer);\n }, [startedAt, phrases]);\n if (options?.render) return options.render({ startedAt, detailsOpen, onShowDetails });\n return (\n <div className=\"og-genie-loading\">\n <div\n className=\"og-genie-orb\"\n aria-hidden=\"true\"\n style={{\n width: options?.orb?.size ?? 64,\n height: options?.orb?.size ?? 64,\n flexBasis: options?.orb?.size ?? 64,\n }}\n >\n <ThinkingOrb state=\"searching\" size={64} theme={theme} speed={0.8} {...options?.orb} />\n </div>\n <div className=\"og-genie-copy\">\n <span className=\"sr-only\" role=\"status\">\n {slow\n ? (options?.messages?.slowStatus ?? \"Preparing your task. Taking longer than usual.\")\n : (options?.messages?.status ?? \"Preparing your task.\")}\n </span>\n <span key={slow ? \"slow\" : phrase} className=\"og-genie-phrase\" aria-hidden=\"true\">\n {slow\n ? (options?.messages?.slowText ?? \"A little longer than usual…\")\n : phrases[phrase % phrases.length]}\n </span>\n {showDetails || detailsOpen ? (\n <button\n type=\"button\"\n className=\"og-genie-details\"\n aria-expanded={detailsOpen}\n onClick={onShowDetails}\n >\n {detailsOpen\n ? (options?.messages?.hideDetails ?? \"Hide details\")\n : (options?.messages?.showDetails ?? \"Behind the magic\")}\n <span aria-hidden=\"true\"> ↗</span>\n </button>\n ) : null}\n </div>\n </div>\n );\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 {\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 UserMessageDisclosureLabels = {\n /** Collapsed disclosure action. Defaults to \"Show more\". */\n showMore?: string | undefined;\n /** Expanded disclosure action. Defaults to \"Show less\". */\n showLess?: string | undefined;\n};\n\nexport type UserMessageDisclosureContextValue = {\n labels?: UserMessageDisclosureLabels | undefined;\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 /** Per-field overrides for timeline labels, then the English defaults. */\n disclosureLabels?: UserMessageDisclosureLabels | 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({\n messageId,\n text,\n children,\n className,\n disclosureLabels,\n}: 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\n ? (disclosureLabels?.showLess ?? disclosure?.labels?.showLess ?? \"Show less\")\n : (disclosureLabels?.showMore ?? disclosure?.labels?.showMore ?? \"Show more\")}\n </button>\n </div>\n );\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 /** Experimental compact live activity reel. */\n rolling?: boolean;\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 liveHeader?: ReactNode;\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 liveHeader,\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\" || (liveHeader && !outcome) ? 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 {liveHeader && !open\n ? liveHeader\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 const count = items.filter((item) => item.kind !== \"startup-phase\").length;\n return count\n ? { content: `${count} ${count === 1 ? \"step\" : \"steps\"}` }\n : items.length\n ? { content: \"Preparation\" }\n : null;\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 { renderActivity } from \"./activity-rail\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { WrenchIcon } from \"lucide-react\";\nimport { Suspense, useEffect, useState } from \"react\";\nimport { CompactActivityContext } from \"./shared\";\nimport { defaultToolRegistry } from \"./tool-renderers\";\nimport type { ToolRegistry } from \"./registry\";\nimport { toolDisplayName } from \"./tool-display-name\";\nimport type { ActivityItem } from \"./types\";\n\n/** One stable viewport; updates replace its content without moving the conversation. */\nexport function RollingActivity({\n items,\n toolRegistry = defaultToolRegistry,\n previousItem,\n}: {\n items: ActivityItem[];\n /** The standalone item visible immediately before this reel mounted. */\n previousItem?: ActivityItem | undefined;\n toolRegistry?: ToolRegistry;\n}) {\n const reduced = useReducedMotion();\n const [mounted, setMounted] = useState(false);\n useEffect(() => setMounted(true), []);\n const work = items.filter((item) => item.kind !== \"startup-phase\");\n const active = work.filter((item) =>\n item.kind === \"reasoning\" ? item.streaming : \"status\" in item && item.status === \"running\",\n );\n // Advance with the event order; finishing a parallel tool must not replay an older one.\n const item = !mounted && previousItem ? previousItem : work.at(-1);\n if (!item) return null;\n const earlierCount = Math.max(\n 0,\n work.findIndex((entry) => entry.id === item.id),\n );\n const fallback = (\n <span className=\"og-rolling-label\">\n <WrenchIcon className=\"size-3.5\" />\n <span>{item.kind === \"tool-call\" ? toolDisplayName(item.name) : \"Working\"}</span>\n </span>\n );\n return (\n <span\n className=\"og-rolling-status\"\n data-running={active.some((entry) => entry.id === item.id) ? \"true\" : undefined}\n >\n <span className=\"sr-only\">\n {item.kind === \"tool-call\"\n ? toolDisplayName(item.name)\n : item.kind === \"reasoning\"\n ? \"Thinking\"\n : \"Working\"}\n </span>\n <span className=\"og-rolling-window\" aria-hidden=\"true\">\n <AnimatePresence initial={false} mode=\"sync\">\n <motion.span\n key={item.id}\n className=\"og-rolling-face\"\n initial={{\n opacity: 0,\n y: reduced ? 0 : 24,\n }}\n animate={{ opacity: 1, y: 0 }}\n exit={{\n opacity: 0,\n y: reduced ? 0 : -24,\n }}\n transition={{ duration: reduced ? 0 : 0.4, ease: [0.22, 1, 0.36, 1] }}\n >\n <CompactActivityContext.Provider value={true}>\n <Suspense fallback={fallback}>\n {renderActivity(item, toolRegistry, undefined, undefined, undefined, undefined)}\n </Suspense>\n </CompactActivityContext.Provider>\n </motion.span>\n </AnimatePresence>\n </span>\n {earlierCount > 0 ? (\n <span className=\"og-rolling-count\">{`+${earlierCount} earlier`}</span>\n ) : null}\n </span>\n );\n}\n","import type { MachineInputMember } from \"../timeline/types\";\n\n/** Source IDs are routing coordinates only for typed child updates, never parsed from prose. */\nexport function ChildSessionLink({\n kind,\n sourceId,\n onOpenSession,\n}: Pick<MachineInputMember, \"kind\" | \"sourceId\"> & {\n onOpenSession?: ((sessionId: string) => void) | undefined;\n}) {\n if (\n !onOpenSession ||\n !kind.startsWith(\"child_\") ||\n !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sourceId)\n ) {\n return null;\n }\n return (\n <button\n type=\"button\"\n onClick={() => onOpenSession(sourceId)}\n className=\"mt-1 rounded-og-sm text-og-xs font-medium text-og-accent underline-offset-4 hover:underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-og-accent\"\n >\n View session\n </button>\n );\n}\n","import { RollingActivity } from \"../timeline/rolling-activity\";\nimport { GenieLoadingOptionsContext, type GenieLoadingOptions } from \"../timeline/genie-loading\";\nimport { ChildSessionLink } from \"./child-session-link\";\nimport { useStartupDetails } from \"../timeline/startup-preference\";\nimport { parseSandboxFileArtifactReceipt } from \"@opengeni/sdk\";\nimport { unwrapMcpOutput } from \"../timeline/parsers\";\nimport { isRetainedImageContentType } from \"../timeline/retained-image\";\nimport { mcpToolLeaf } from \"../timeline/tool-display-name\";\nimport 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, useReducedMotion } 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 TimelineBeforeLayout,\n captureTimelineAnchor,\n timelineAnchorCorrection,\n type TimelineAnchor,\n} from \"./timeline-anchor\";\nimport {\n UserMessageBody,\n UserMessageDisclosureProvider,\n type UserMessageDisclosureContextValue,\n type UserMessageDisclosureLabels,\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 { TimelineAnnotationSourceRootContext } from \"./timeline-annotation-reveal-context\";\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 { TimelineAnnotationCards } from \"./timeline-annotations\";\nimport { TooltipProvider } from \"./tooltip\";\n\nconst TimelineAnnotationSelection = lazy(() => import(\"./timeline-annotation-selection\"));\nconst TimelineAnnotationMarkers = lazy(() => import(\"./timeline-annotation-markers\"));\n\nexport type MessageTimelineProps = {\n /** Localized user-message disclosure actions, including custom UserMessageBody renderers. */\n userMessageDisclosureLabels?: UserMessageDisclosureLabels | undefined;\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 /** Host-owned controls beside Copy and the timestamp on settled message rows. */\n renderMessageActions?: ((item: AgentMessageItem | UserMessageItem) => ReactNode) | 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 /** Host-owned inline connection setup. Return undefined to use the default recovery card. */\n renderAuthNeeded?: ((item: AuthNeededItem) => ReactNode | undefined) | 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 genieLoading?: GenieLoadingOptions | undefined;\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 /** Composer draft quotes currently attached to the next send. */\n draftAnnotations?: readonly DraftTimelineAnnotation[] | undefined;\n /** Open the composer review list for one numbered draft badge. */\n onDraftAnnotationSelect?: ((id: string) => 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. Return the request promise to enable inline error/retry. */\n onLoadNewer?: (() => unknown) | 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 preserveTail = false,\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(\n load,\n (receipt) => {\n attempt[2] = receipt;\n },\n preserveTail,\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 userMessageDisclosureLabels,\n events,\n items,\n status: _status,\n renderMessageActions,\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n renderAuthNeeded,\n shouldRenderAuthNeeded,\n resolveProviderLogo,\n toolRegistry = defaultToolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n computeLabel = null,\n genieLoading,\n turnSummary,\n autoFollow = true,\n onAnnotate,\n draftAnnotations,\n onDraftAnnotationSelect,\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 // Event-window identity is independent of projected rows (partial messages\n // can acquire a different first-delta id when older text arrives).\n const sourceItems = events ?? items;\n const olderBoundaryKey = sourceItems?.[0]?.id;\n const newerBoundaryKey = `${events?.[0]?.sessionId ?? \"\"}:${olderBoundaryKey ?? \"\"}`;\n const newerScopeRef = useRef(newerBoundaryKey);\n newerScopeRef.current = newerBoundaryKey;\n const newerAttemptRef = useRef<{ pending: boolean } | null>(null);\n const newerRetryButtonRef = useRef<HTMLButtonElement | null>(null);\n const [newerRetryPending, setNewerRetryPending] = useState(false);\n const [newerFailure, setNewerFailure] = useState<{ key: string; message: string } | null>(null);\n useEffect(() => {\n newerScopeRef.current = newerBoundaryKey;\n newerAttemptRef.current = null;\n setNewerFailure(null);\n setNewerRetryPending(false);\n return () => {\n newerScopeRef.current = \"\";\n newerAttemptRef.current = null;\n };\n }, [newerBoundaryKey]);\n const requestNewer = useCallback(\n (explicitRetry = false) => {\n if (\n newerScopeRef.current !== newerBoundaryKey ||\n !onLoadNewer ||\n loadingNewer ||\n (newerAttemptRef.current && (!explicitRetry || newerAttemptRef.current.pending))\n ) {\n return;\n }\n const attempt = { pending: true };\n newerAttemptRef.current = attempt;\n if (explicitRetry) setNewerRetryPending(true);\n const isCurrent = () =>\n newerAttemptRef.current === attempt && newerScopeRef.current === newerBoundaryKey;\n // Both synchronous host errors and rejected promises belong to this\n // boundary. Retain the failed attempt so observers cannot hot-retry it.\n void Promise.resolve()\n .then(() => (isCurrent() ? onLoadNewer() : undefined))\n .then(\n () => {\n if (!isCurrent()) return;\n newerAttemptRef.current = null;\n // The successful page removes the recovery control. Return focus\n // to the reading surface without moving the reader's viewport.\n if (document.activeElement === newerRetryButtonRef.current) {\n scrollRef.current?.focus({ preventScroll: true });\n }\n setNewerFailure(null);\n setNewerRetryPending(false);\n },\n (reason: unknown) => {\n if (!isCurrent()) return;\n attempt.pending = false;\n setNewerRetryPending(false);\n setNewerFailure({\n key: newerBoundaryKey,\n message: reason instanceof Error ? reason.message : String(reason),\n });\n },\n );\n },\n [onLoadNewer, loadingNewer, newerBoundaryKey],\n );\n const previousSourceIdsRef = useRef(new Set<string>());\n const previousSourceBoundaryRef = useRef<string | undefined>(undefined);\n const readingAnchorRef = useRef<TimelineAnchor | null>(null);\n const olderPageBudgetRef = useRef(0);\n const [olderDemand, setOlderDemand] = useState(0);\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 const turnsWithOutput = useMemo(\n () =>\n new Set(\n resolvedItems.flatMap((item) =>\n \"turnId\" in item &&\n item.turnId &&\n (item.kind === \"tool-call\" ||\n ((item.kind === \"agent-message\" || item.kind === \"reasoning\") && item.text.trim()))\n ? [item.turnId]\n : [],\n ),\n ),\n [resolvedItems],\n );\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 if (!autoFollow || !pinnedRef.current || hasNewerRef.current) {\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 }, [autoFollow, applyPinned, clearPendingReaderLeave, clearReaderIntent, stopFollow]);\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();\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 requestEarlierFromReader = () => {\n releasePinFromReader();\n wantPinRef.current = false;\n // A stationary upward gesture is still demand. Successful short/folded\n // pages may never create enough range to leave the prefetch band.\n olderPageBudgetRef.current = 8;\n if (olderLoadAttemptRef.current?.[1] === 2) {\n olderLoadAttemptRef.current = null;\n setOlderDemand((value) => value + 1);\n }\n };\n const touchPositionRef = useRef<{ x: number; y: number } | null>(null);\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 programmaticScrollRef.current = 0;\n if (event.deltaY >= 0) {\n return;\n }\n requestEarlierFromReader();\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 programmaticScrollRef.current = 0;\n requestEarlierFromReader();\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 labels: {\n showMore: userMessageDisclosureLabels?.showMore,\n showLess: userMessageDisclosureLabels?.showLess,\n },\n }),\n [\n beginUserMessageDisclosureChange,\n userMessageDisclosureLabels?.showMore,\n userMessageDisclosureLabels?.showLess,\n ],\n );\n const timelineGroupEntryContext = useMemo<TimelineGroupEntryContext>(\n () => ({\n userMessageDisclosureContext,\n behavior: {\n renderMessageActions,\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n renderAuthNeeded,\n resolveProviderLogo,\n toolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n genieLoading,\n turnSummary,\n },\n }),\n [\n loadRetainedArtifact,\n loadRetainedScreenshot,\n loadVideoArtifactPlayback,\n onMemoryClick,\n onOpenSession,\n onReconnect,\n renderAuthNeeded,\n renderMessageActions,\n renderMessageText,\n resolveProviderLogo,\n toolRegistry,\n genieLoading,\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, !retry);\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 sourceChanged = olderBoundaryKey !== previousSourceBoundaryRef.current;\n const retainedSource =\n sourceItems?.some((item) => previousSourceIdsRef.current.has(item.id)) ?? false;\n const prepended = sourceChanged && retainedSource;\n previousSourceBoundaryRef.current = olderBoundaryKey;\n previousSourceIdsRef.current = new Set(sourceItems?.map((item) => item.id));\n const readingAnchor = readingAnchorRef.current;\n readingAnchorRef.current = null;\n const attempt = olderLoadAttemptRef.current;\n const committedZeroOverlapOlderReplacement = !!(\n attempt?.[2]?.committed &&\n sourceChanged &&\n !retainedSource\n );\n const restorePrependAnchor = () => {\n const correction = readingAnchor && timelineAnchorCorrection(node, readingAnchor);\n if (correction != null) {\n if (Math.abs(correction) > 1) writeScrollTop(node, node.scrollTop + correction);\n return;\n }\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 const olderAttemptState = olderLoadAttemptRef.current?.[1];\n const underfillOwned =\n !!olderLoadAttemptRef.current &&\n olderAttemptState !== 1 &&\n olderAttemptState !== 2 &&\n olderAttemptState !== 3;\n if (\n autoFollow &&\n pinnedRef.current &&\n !hasNewer &&\n !pendingReaderLeaveRef.current &&\n (wasAtLiveTailBeforeCommit || underfillOwned)\n ) {\n // Still following the live tip: underfill, or a prefetch the reader\n // started and then returned from. Park at the new tip. A stale pin\n // while they are actually up in a short window (gap is not inside\n // PIN_THRESHOLD of maxScroll, so wasAtLiveTail is false) restores.\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 // Bound automatic work, but let continued upward input replenish demand.\n // Only a committed first-party receipt proves that another page is safe.\n if (\n attempt[2]?.committed &&\n !pinnedRef.current &&\n hasOlder &&\n node.scrollTop <= OLDER_PREFETCH_MARGIN_PX &&\n olderPageBudgetRef.current > 0\n ) {\n olderPageBudgetRef.current -= 1;\n olderLoadAttemptRef.current = null;\n setOlderDemand((value) => value + 1);\n }\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 olderDemand,\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 // An underfilled history window has both sentinels visible. Advancing\n // it automatically would undo an explicit older-page navigation.\n if (maxScrollOf(root) > 1 && entries.some((entry) => entry.isIntersecting)) {\n requestNewer();\n }\n },\n { root, rootMargin: \"0px 0px 1200px 0px\" },\n );\n observer.observe(target);\n return () => observer.disconnect();\n }, [hasNewer, loadingNewer, onLoadNewer, requestNewer, 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 (programmatic && !pinnedRef.current) {\n // Restore/camera writes while reading history are not a return to the tip.\n // Still expire a pending Jump-to-latest latch: the in-window jump itself\n // is a programmatic snap, and a later reader scroll-away can arrive\n // before that echo is consumed. Skipping this left the latch armed and\n // snapped the reader when hasNewer later flipped false.\n syncScrollBaseline(node);\n if (wantPinRef.current && !isNearBottom(node)) {\n wantPinRef.current = false;\n }\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 requestEarlierFromReader();\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 if (programmatic) {\n // Anchor restoration is never permission to resume tip-follow.\n return;\n }\n const nearBottom = isNearBottom(node);\n\n // Re-pin only when the reader moved toward/at the tip without a content\n // insertion. Prepend restore and overflow-anchor raise scrollTop by\n // roughly the same amount as maxScroll; treating that as a scroll-down\n // re-pinned a compact-tail history reader (their preserved gap falls\n // inside PIN_THRESHOLD once the window is tall) and snapped them back.\n const inserted = Math.max(0, nextMaxScroll - previousMaxScroll);\n const towardTip = nextTop - previousTop - inserted;\n const nextPinned = !hasNewer && nearBottom && towardTip > 0.5 && inserted <= 1;\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 <TimelineAnnotationSourceRootContext.Provider value={scrollRef}>\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 onTouchStart={(event) => {\n const touch = event.touches.length === 1 ? event.touches[0] : undefined;\n touchPositionRef.current = touch\n ? { x: touch.clientX, y: touch.clientY }\n : null;\n }}\n onTouchMove={(event) => {\n const touch = event.touches[0];\n const previous = touchPositionRef.current;\n if (!touch || !previous || event.touches.length !== 1) {\n touchPositionRef.current = null;\n return;\n }\n const deltaX = previous.x - touch.clientX;\n const deltaY = previous.y - touch.clientY;\n if (Math.max(Math.abs(deltaX), Math.abs(deltaY)) < 4) return;\n touchPositionRef.current = { x: touch.clientX, y: touch.clientY };\n onWheel({\n deltaX,\n deltaY,\n target: event.target,\n currentTarget: event.currentTarget,\n });\n }}\n onTouchEnd={() => {\n touchPositionRef.current = null;\n }}\n onTouchCancel={() => {\n touchPositionRef.current = null;\n }}\n onClickCapture={(event) => {\n const target =\n event.target instanceof Element\n ? event.target.closest(\"button[aria-expanded]\")\n : null;\n if (target) {\n releasePinFromReader();\n disclosureKeepsUnpinnedRef.current = true;\n }\n }}\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 pt-16 pb-6 sm:px-6 outline-hidden\",\n autoFollow && pinned && !hasNewer\n ? \"[overflow-anchor:none]\"\n : \"[overflow-anchor:auto]\",\n )}\n >\n <TimelineBeforeLayout\n capture={() => {\n readingAnchorRef.current =\n !pinnedRef.current && scrollRef.current\n ? captureTimelineAnchor(scrollRef.current)\n : null;\n }}\n >\n <div className=\"relative mx-auto flex w-full max-w-3xl flex-col gap-5\">\n <AnimatePresence>\n {loadingOlder ||\n loadingOldest ||\n (hasOlder && onJumpToStart && olderPrefetchArmed) ||\n underfillRetryReady ? (\n // Reserved top gutter: controls scroll with history and cannot\n // cover a disclosure. Visibility never changes content height.\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=\"pointer-events-none absolute inset-x-0 -top-11 z-10 flex justify-center\"\n >\n {loadingOlder || loadingOldest ? (\n <span className={LOADING_CHIP_CLASS}>\n <span className=\"og-shimmer-text\">\n {loadingOldest\n ? \"Jumping to start…\"\n : \"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=\"pointer-events-auto rounded-full border border-og-border px-3 py-1.5 text-og-control\"\n >\n {underfillRetryReady\n ? underfillSettledAttempt?.[2]?.tailPreserved\n ? \"Load earlier activity\"\n : \"Retry earlier activity\"\n : \"Jump to start\"}\n </button>\n ) : null}\n </motion.div>\n ) : null}\n </AnimatePresence>\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 // End at the scroll origin above the pt-16 gutter so the\n // observer and scrollTop cooldown share the same 400px band.\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-16 h-px -translate-y-full\"\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 startupDismissed={\n group.kind === \"activity\" &&\n group.items.some(\n (item) => item.turnId && turnsWithOutput.has(item.turnId),\n )\n }\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 && newerFailure?.key === newerBoundaryKey ? (\n <div\n data-og-newer-error=\"\"\n className=\"flex flex-col items-center gap-2 px-4 py-3 text-center text-og-menu text-og-fg-muted\"\n >\n <p role=\"status\" className=\"max-w-prose [overflow-wrap:anywhere]\">\n Couldn’t load later activity. {newerFailure.message}\n </p>\n <button\n ref={newerRetryButtonRef}\n type=\"button\"\n data-og-retry-newer=\"\"\n className=\"min-h-11 rounded-og-md border border-og-border px-3 py-2 text-og-fg hover:bg-og-surface-2 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-og-accent\"\n aria-disabled={loadingNewer || newerRetryPending}\n aria-busy={newerRetryPending}\n onClick={() => requestNewer(true)}\n >\n {newerRetryPending\n ? \"Retrying later activity…\"\n : \"Retry later activity\"}\n </button>\n </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 </TimelineBeforeLayout>\n </div>\n {draftAnnotations && draftAnnotations.length > 0 ? (\n <Suspense fallback={null}>\n <TimelineAnnotationMarkers\n rootRef={scrollRef}\n annotations={draftAnnotations}\n onSelect={onDraftAnnotationSelect}\n />\n </Suspense>\n ) : null}\n\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 </TimelineAnnotationSourceRootContext.Provider>\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 const startupCompletion =\n previous?.group.kind === \"activity\" &&\n previous.group.items.every(\n (item) =>\n item.kind === \"startup-phase\" || (item.kind === \"reasoning\" && !item.text.trim()),\n ) &&\n group.kind === \"turn\" &&\n group.outcome === \"complete\" &&\n group.groups.every(\n (child) =>\n child.kind === \"activity\" &&\n child.items.every((item) => item.kind === \"startup-phase\"),\n );\n if (\n previous &&\n (previous.group.kind === group.kind || startupCompletion) &&\n !usedKeys.has(previous.key)\n ) {\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 startupDismissed: boolean;\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 renderMessageActions: MessageTimelineProps[\"renderMessageActions\"];\n renderMessageText: MessageTimelineProps[\"renderMessageText\"];\n onOpenSession: MessageTimelineProps[\"onOpenSession\"];\n onMemoryClick: MessageTimelineProps[\"onMemoryClick\"];\n onReconnect: MessageTimelineProps[\"onReconnect\"];\n renderAuthNeeded: MessageTimelineProps[\"renderAuthNeeded\"];\n resolveProviderLogo: MessageTimelineProps[\"resolveProviderLogo\"];\n toolRegistry: ToolRegistry;\n loadRetainedScreenshot: MessageTimelineProps[\"loadRetainedScreenshot\"];\n loadRetainedArtifact: MessageTimelineProps[\"loadRetainedArtifact\"];\n loadVideoArtifactPlayback: MessageTimelineProps[\"loadVideoArtifactPlayback\"];\n genieLoading: MessageTimelineProps[\"genieLoading\"];\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 startupDismissed,\n entranceEnabled,\n liveEntranceEnabled,\n context,\n}: TimelineGroupEntryProps) {\n const reducedMotion = useReducedMotion();\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 const content = (\n <TimelineGroupView\n {...behavior}\n group={group}\n foldLiveCluster={isAgentProgress(nextGroup)}\n startupDismissed={startupDismissed}\n trailingAgentText={trailingAgentTextAfterTurn(group, nextGroup)}\n contextCompactionCount={contextCompactionCount > 0 ? contextCompactionCount : undefined}\n />\n );\n return (\n <GenieLoadingOptionsContext.Provider value={behavior.genieLoading}>\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 {/* Item groups never switch the preparation/content key. Keep their\n DOM shell without mounting inert presence and motion lifecycles\n for every historical message in a prepend. */}\n {group.kind === \"item\" ? (\n <div>{content}</div>\n ) : (\n <AnimatePresence initial={false}>\n <motion.div\n key={\n !startupDismissed &&\n group.kind === \"activity\" &&\n group.items.every(\n (item) =>\n item.kind === \"startup-phase\" ||\n (item.kind === \"reasoning\" && !item.text.trim()),\n )\n ? \"preparation\"\n : \"content\"\n }\n initial={false}\n exit={{ opacity: 0, height: 0 }}\n transition={{ duration: reducedMotion ? 0 : 0.2 }}\n >\n {content}\n </motion.div>\n </AnimatePresence>\n )}\n </UserMessageDisclosureProvider>\n </TimelineGroupRenderBoundary>\n </EntranceAnimationProvider>\n </div>\n </GenieLoadingOptionsContext.Provider>\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 renderMessageActions,\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n renderAuthNeeded,\n resolveProviderLogo,\n toolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n turnSummary,\n insideTurn = false,\n nestClusterChips = false,\n foldLiveCluster = false,\n startupDismissed = false,\n trailingAgentText,\n contextCompactionCount,\n}: {\n group: TimelineGroup;\n renderMessageActions?: ((item: AgentMessageItem | UserMessageItem) => ReactNode) | undefined;\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 /** Host-owned inline connection setup. Return undefined to use the default recovery card. */\n renderAuthNeeded?: ((item: AuthNeededItem) => ReactNode | undefined) | 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 startupDismissed?: 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 startupDetails = useStartupDetails();\n const enter = useEntranceAnimation();\n const settleChrome = useTurnSettleOpen();\n const previousSingleActivity = useRef<ActivityItem | undefined>(undefined);\n useLayoutEffect(() => {\n const work =\n group.kind === \"activity\" ? group.items.filter((item) => item.kind !== \"startup-phase\") : [];\n previousSingleActivity.current = work.length === 1 ? work[0] : undefined;\n }, [group]);\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 containsPresentedImage = timelineGroupContainsPresentedImage(group);\n const hasRememberedImageFold =\n group.kind === \"activity\" && containsPresentedImage && foldMemory?.has(group.id);\n // Primary images stay visible through live narration and the turn wrap.\n // Manual collapse still belongs to TurnSummary's existing fold memory.\n const activityShouldFold =\n group.kind === \"activity\" &&\n !containsPresentedImage &&\n !!(group.outcome || (foldLiveCluster && clusterIsSettled(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 containsPresentedImage);\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 !turnSummary?.rolling &&\n (group.kind === \"turn\" ? !!(enter && !insideTurn && !turnDefaultOpen) : liveActivitySettle);\n switch (group.kind) {\n case \"activity\":\n // Preparation is one quiet surface, not a fold with eight technical steps.\n if (\n !startupDetails &&\n !insideTurn &&\n !group.outcome &&\n group.items.every(\n (item) =>\n item.kind === \"startup-phase\" || (item.kind === \"reasoning\" && !item.text.trim()),\n )\n ) {\n return (\n <ActivityRail\n items={group.items}\n startupActive={!startupDismissed && !foldLiveCluster}\n bare\n toolRegistry={toolRegistry}\n onOpenSession={onOpenSession}\n onMemoryClick={onMemoryClick}\n loadRetainedScreenshot={loadRetainedScreenshot}\n loadRetainedArtifact={loadRetainedArtifact}\n />\n );\n }\n if (\n turnSummary?.rolling &&\n !startupDetails &&\n !hasRememberedImageFold &&\n group.items.filter((item) => item.kind !== \"startup-phase\").length === 1\n ) {\n return (\n <ActivityRail\n items={group.items}\n startupActive={false}\n bare\n toolRegistry={toolRegistry}\n onOpenSession={onOpenSession}\n onMemoryClick={onMemoryClick}\n loadRetainedScreenshot={loadRetainedScreenshot}\n loadRetainedArtifact={loadRetainedArtifact}\n />\n );\n }\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 visibleActivity = group.items.filter((item) => item.kind !== \"startup-phase\");\n const singleThought =\n !startupDetails &&\n visibleActivity.length === 1 &&\n visibleActivity[0]?.kind === \"reasoning\";\n // Untouched images stay primary output, but a reader-owned image fold\n // must keep its shell across a multi-cluster wrap. A bare rail would\n // bypass the remembered choice; retaining either state also lets the\n // reader reopen and close the same chip after settlement.\n const useNestedChip =\n nestClusterChips && (activityShouldFold || hasRememberedImageFold) && !singleThought;\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 // Apply the primary-output default when a rolling activity first\n // produces an image; the stable foldKey still preserves user choices.\n key={containsPresentedImage ? \"primary-image\" : \"activity\"}\n items={group.items}\n outcome={group.outcome}\n failureText={group.failureText}\n defaultOpen={\n group.outcome === \"failed\" ||\n containsPresentedImage ||\n (!turnSummary?.rolling && !activityShouldFold)\n ? true\n : undefined\n }\n liveHeader={\n turnSummary?.rolling &&\n !containsPresentedImage &&\n !group.outcome &&\n !foldLiveCluster ? (\n <RollingActivity\n items={group.items}\n toolRegistry={toolRegistry}\n previousItem={previousSingleActivity.current}\n />\n ) : undefined\n }\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 if (\n !startupDetails &&\n group.outcome === \"complete\" &&\n group.groups.every(\n (child) =>\n child.kind === \"activity\" &&\n child.items.every(\n (item) => item.kind === \"startup-phase\" && item.status === \"complete\",\n ),\n )\n )\n return <ActivityRail items={activityItems} startupActive={false} bare />;\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 renderMessageActions,\n renderMessageText,\n onOpenSession,\n onMemoryClick,\n onReconnect,\n renderAuthNeeded,\n resolveProviderLogo,\n toolRegistry,\n loadRetainedScreenshot,\n loadRetainedArtifact,\n loadVideoArtifactPlayback,\n turnSummary,\n ]}\n >\n <TimelineGroupView\n group={child}\n renderMessageActions={renderMessageActions}\n renderMessageText={renderMessageText}\n onOpenSession={onOpenSession}\n onMemoryClick={onMemoryClick}\n onReconnect={onReconnect}\n renderAuthNeeded={renderAuthNeeded}\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 renderMessageActions={renderMessageActions}\n renderMessageText={renderMessageText}\n onReconnect={onReconnect}\n renderAuthNeeded={renderAuthNeeded}\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/** Deliberately published images are primary output, not incidental screenshots. */\nfunction timelineGroupContainsPresentedImage(group: TimelineGroup): boolean {\n switch (group.kind) {\n case \"item\":\n return false;\n case \"activity\":\n return group.items.some((item) => {\n if (item.kind !== \"tool-call\") return false;\n const name = mcpToolLeaf(item.name);\n if (name === \"generate_image\" || name === \"image_generation_call\") return true;\n if (item.status !== \"complete\" || name !== \"sandbox_file_publish\") return false;\n const output = unwrapMcpOutput(item.output);\n if (output.isError) return false;\n const receipt = parseSandboxFileArtifactReceipt(output.text);\n return receipt !== null && isRetainedImageContentType(receipt.artifact.contentType);\n });\n case \"turn\":\n return group.groups.some(timelineGroupContainsPresentedImage);\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\" && next.item.text.trim().length > 0)\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 renderMessageActions,\n renderMessageText,\n onReconnect,\n renderAuthNeeded,\n resolveProviderLogo,\n onOpenSession,\n loadVideoArtifactPlayback,\n}: {\n item: TimelineItem;\n renderMessageActions?: ((item: AgentMessageItem | UserMessageItem) => ReactNode) | undefined;\n renderMessageText?:\n | ((text: string, item: AgentMessageItem | UserMessageItem) => ReactNode)\n | undefined;\n onReconnect?: ((item: AuthNeededItem) => void | Promise<void>) | undefined;\n /** Host-owned inline connection setup. Return undefined to use the default recovery card. */\n renderAuthNeeded?: ((item: AuthNeededItem) => ReactNode | undefined) | 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 (\n <UserMessageRow\n item={item}\n renderMessageActions={renderMessageActions}\n renderMessageText={renderMessageText}\n />\n );\n case \"human-input\":\n return <HumanInputConversationRow item={item} />;\n case \"agent-message\":\n return (\n <AgentMessageRow\n item={item}\n renderMessageActions={renderMessageActions}\n renderMessageText={renderMessageText}\n />\n );\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\n item={item}\n onOpenSession={onOpenSession}\n loadVideoArtifactPlayback={loadVideoArtifactPlayback}\n />\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 renderAuthNeeded?.(item) ?? (\n <AuthNeededRow\n item={item}\n onReconnect={onReconnect}\n resolveProviderLogo={resolveProviderLogo}\n />\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 : NEUTRAL_PILL;\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 renderMessageActions,\n renderMessageText,\n}: {\n item: UserMessageItem;\n renderMessageActions?: ((item: AgentMessageItem | UserMessageItem) => ReactNode) | undefined;\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={\n <>\n {renderMessageActions?.(item)}\n <MessageFooterTime occurredAt={item.occurredAt} />\n </>\n }\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 <TimelineAnnotationCards\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 renderMessageActions,\n renderMessageText,\n}: {\n item: AgentMessageItem;\n renderMessageActions?: ((item: AgentMessageItem | UserMessageItem) => ReactNode) | undefined;\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 <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={\n item.streaming ? null : (\n <>\n {renderMessageActions?.(item)}\n <MessageFooterTime occurredAt={item.occurredAt} />\n </>\n )\n }\n >\n <div\n data-og-wide-table-message=\"\"\n data-og-annotation-source-key={item.annotationSource?.eventId}\n >\n {body}\n </div>\n </CopyHoverFrame>\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\n// Shared production chunks can be cyclic. Resolve icon bindings during render,\n// after their modules initialize, rather than permanently capturing undefined.\nfunction goalMeta(action: GoalItem[\"action\"]): GoalMeta {\n const metadata: 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 return metadata[action];\n}\n\n/**\n * A goal landmark pill. Resolves its label, accent/tone, and glyph from\n * {@link goalMeta} 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 } = goalMeta(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 onOpenSession,\n loadVideoArtifactPlayback,\n}: {\n item: MachineInputBatchItem;\n onOpenSession?: ((sessionId: string) => void) | undefined;\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\n className=\"group w-full max-w-full\"\n data-og-machine-input-batch=\"\"\n title={`Received ${formatClockTime(item.occurredAt)}`}\n >\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 <p className=\"text-og-xs text-og-fg-subtle\">\n Received <time dateTime={item.occurredAt}>{formatClockTime(item.occurredAt)}</time>\n </p>\n {item.members.map((member) => (\n <MachineInputRow\n key={member.id}\n member={member}\n onOpenSession={onOpenSession}\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 onOpenSession,\n loadVideoArtifactPlayback,\n}: {\n member: MachineInputBatchItem[\"members\"][number];\n onOpenSession?: ((sessionId: string) => void) | undefined;\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 <ChildSessionLink\n kind={member.kind}\n sourceId={member.sourceId}\n onOpenSession={onOpenSession}\n />\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 if (item.recordedOutcome) {\n return (\n <details\n className=\"group text-og-sm text-og-fg-muted\"\n role=\"note\"\n data-og-recorded-outcome=\"wait\"\n >\n <summary className=\"flex cursor-pointer list-none items-center gap-2 py-1 [&::-webkit-details-marker]:hidden\">\n <ChevronRightIcon\n aria-hidden\n className=\"size-3.5 transition-transform group-open:rotate-90\"\n />\n <span>\n Wait recorded ·{\" \"}\n <time dateTime={item.occurredAt}>\n {new Date(item.occurredAt).toLocaleString(undefined, {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n })}\n </time>\n </span>\n </summary>\n <p className=\"mt-1 whitespace-pre-wrap break-words pl-5 text-og-fg-muted\">{item.text}</p>\n </details>\n );\n }\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 : NEUTRAL_PILL;\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={item.recordedOutcome ? \"note\" : \"status\"}\n data-og-recorded-outcome={item.recordedOutcome ? \"wait\" : undefined}\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 {item.recordedOutcome ? (\n <p className=\"mb-1 text-og-control font-medium\">\n Wait recorded{\" \"}\n <time dateTime={item.occurredAt}>\n {new Date(item.occurredAt).toLocaleString(undefined, {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n })}\n </time>\n </p>\n ) : null}\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-og-fg/5 p-2 font-mono\">\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","import { Component, type ReactNode } from \"react\";\n\ntype Anchor = { element: HTMLElement; key: string | null; text: string | null; top: number };\nexport type TimelineAnchor = Anchor[];\n\n/** Read the old DOM immediately before React changes it, not when a fetch starts. */\nexport class TimelineBeforeLayout extends Component<{\n capture: () => void;\n children: ReactNode;\n}> {\n getSnapshotBeforeUpdate() {\n this.props.capture();\n return null;\n }\n componentDidUpdate() {}\n render() {\n return this.props.children;\n }\n}\n\nexport function captureTimelineAnchor(scroller: HTMLElement): TimelineAnchor | null {\n const viewport = scroller.getBoundingClientRect();\n if (viewport.height <= 0) return null;\n const groups = Array.from(scroller.querySelectorAll<HTMLElement>(\"[data-og-group-key]\")).filter(\n (group) => group.getBoundingClientRect().height > 0,\n );\n const anchors: TimelineAnchor = [];\n // A disclosure is the reader's explicit point of interaction. In particular,\n // anchoring a paragraph below an expanding disclosure would move its button.\n const focused = scroller.ownerDocument.activeElement;\n if (\n focused instanceof HTMLElement &&\n scroller.contains(focused) &&\n focused.matches(\"button[aria-expanded]\")\n ) {\n const box = focused.getBoundingClientRect();\n if (box.bottom > viewport.top && box.top < viewport.bottom) {\n anchors.push({ element: focused, key: null, text: null, top: box.top });\n }\n }\n // A paragraph survives even when earlier deltas reconstruct its containing message.\n for (const group of groups) {\n const rect = group.getBoundingClientRect();\n if (rect.bottom <= viewport.top || rect.top >= viewport.bottom) continue;\n for (const element of group.querySelectorAll<HTMLElement>(\"p, li, pre, h1, h2, h3, h4\")) {\n const box = element.getBoundingClientRect();\n const text = element.textContent;\n if (box.bottom > viewport.top && box.top < viewport.bottom && text && text.length >= 12) {\n anchors.push({ element, key: null, text, top: box.top });\n }\n }\n }\n // Prefer a retained visible row, then a following row. A following row also\n // anchors the unchanged suffix of a partially loaded message above it.\n const rows = groups.map((element) => ({\n element,\n key: element.getAttribute(\"data-og-group-key\"),\n text: null,\n top: element.getBoundingClientRect().top,\n }));\n anchors.push(...rows.filter((row) => row.top >= viewport.top));\n anchors.push(...rows.filter((row) => row.top < viewport.top).reverse());\n return anchors;\n}\n\n/** Return only the correction native browser anchoring has not already made. */\nexport function timelineAnchorCorrection(\n scroller: HTMLElement,\n anchors: TimelineAnchor,\n): number | null {\n let blocks: HTMLElement[] | undefined;\n const groups = Array.from(scroller.querySelectorAll<HTMLElement>(\"[data-og-group-key]\"));\n for (const anchor of anchors) {\n let element: HTMLElement | undefined;\n if (\n scroller.contains(anchor.element) &&\n (!anchor.text || anchor.element.textContent === anchor.text)\n ) {\n element = anchor.element;\n } else if (anchor.key) {\n element = groups.find((group) => group.getAttribute(\"data-og-group-key\") === anchor.key);\n } else if (anchor.text) {\n blocks ??= Array.from(scroller.querySelectorAll<HTMLElement>(\"p, li, pre, h1, h2, h3, h4\"));\n const matches = blocks.filter((block) => block.textContent === anchor.text);\n // Repeated boilerplate is not sufficient evidence of retained content.\n if (matches.length === 1) element = matches[0];\n }\n if (element) return element.getBoundingClientRect().top - anchor.top;\n }\n return null;\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 background_command_result: \"Command result received\",\n session_wait_timeout: \"Wait ended\",\n agent_message: \"Agent update\",\n agent_steer_instruction: \"Agent direction\",\n child_terminal_result: \"Agent result received\",\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 \"background_command_result\":\n return n === 1 ? \"Command result received\" : `${n} command results received`;\n case \"session_wait_timeout\":\n return n === 1 ? \"Wait ended\" : `${n} waits ended`;\n case \"child_terminal_result\":\n return n === 1 ? \"Agent result received\" : `${n} agent results received`;\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","import type { WorkspaceModelCatalogModel } from \"@opengeni/sdk\";\nimport { useCallback } from \"react\";\nimport { projectPickerRows, sortPickerRows, type PickerModelRow } from \"../model-policy\";\nimport { useOpenGeniClient, type ClientOverride } from \"../provider\";\nimport { usePolledValue } from \"./internal\";\n\nexport type UseAvailableModelsOptions = Pick<ClientOverride, \"client\"> & {\n /** Refresh interval (ms). Off by default — the host model list rarely moves. */\n pollIntervalMs?: number | undefined;\n enabled?: boolean | undefined;\n};\n\nexport type UseAvailableModelsResult = {\n models: import(\"@opengeni/sdk\").ClientModel[];\n defaultModel: string | null;\n loading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n};\n\nexport type UseWorkspaceModelCatalogOptions = Pick<ClientOverride, \"client\"> & {\n workspaceId: string | null;\n pollIntervalMs?: number | undefined;\n enabled?: boolean | undefined;\n};\n\nexport type UseWorkspaceModelCatalogResult = {\n models: WorkspaceModelCatalogModel[];\n rows: PickerModelRow[];\n defaultModel: string | null;\n loading: boolean;\n error: Error | null;\n refresh: () => Promise<void>;\n};\n\n/**\n * The host-exposed model list for a <ModelPicker>: fetches the deployment's\n * public client config (`GET /v1/config/client`) and surfaces the richer\n * provider-grouped `models` plus the `defaultModel` the picker should preselect.\n * Deployment-scoped, so it only needs the client (no workspace).\n */\nexport function useAvailableModels(\n options: UseAvailableModelsOptions = {},\n): UseAvailableModelsResult {\n const client = useOpenGeniClient(options);\n const load = useCallback(\n async (signal?: AbortSignal) => await client.getClientConfig({ signal }),\n [client],\n );\n const state = usePolledValue(load, {\n pollIntervalMs: options.pollIntervalMs,\n enabled: options.enabled,\n });\n return {\n models: state.data?.models ?? [],\n defaultModel: state.data?.defaultModel ?? null,\n loading: state.loading,\n error: state.error,\n refresh: state.refresh,\n };\n}\n\n/** Workspace-scoped catalog with selectability and billing-class picker rows. */\nexport function useWorkspaceModelCatalog(\n options: UseWorkspaceModelCatalogOptions,\n): UseWorkspaceModelCatalogResult {\n const client = useOpenGeniClient(options);\n const load = useCallback(\n async (signal?: AbortSignal) => {\n if (!options.workspaceId) {\n return { models: [], defaultModel: null };\n }\n const [catalog, config] = await Promise.all([\n client.getWorkspaceModelCatalog(options.workspaceId, { signal }),\n client.getClientConfig({ signal }),\n ]);\n return {\n models: catalog.models,\n defaultModel: config.defaultModel,\n };\n },\n [client, options.workspaceId],\n );\n const state = usePolledValue(load, {\n pollIntervalMs: options.pollIntervalMs,\n enabled: options.enabled !== false && Boolean(options.workspaceId),\n });\n const rows = sortPickerRows(projectPickerRows(state.data?.models ?? []));\n return {\n models: state.data?.models ?? [],\n rows,\n defaultModel: state.data?.defaultModel ?? null,\n loading: state.loading,\n error: state.error,\n refresh: state.refresh,\n };\n}\n","import type { ClientModel, EffectiveSessionControl } from \"@opengeni/sdk\";\nimport { LayoutGroup, motion } from \"motion/react\";\nimport type { ClipboardEvent, ReactNode } from \"react\";\nimport type { SlashCommand } from \"../commands/types\";\nimport type { ComposerState } from \"../hooks/use-composer\";\nimport type { UseFileAttachmentsResult } from \"../hooks/use-file-attachments\";\nimport type { SlashCommandContext } from \"../hooks/use-slash-commands\";\nimport { OPEN_WORKSTREAM_CONTROL_EVENT } from \"../workstream-control-event\";\nimport {\n Actions,\n AttachButton,\n Attachments,\n CommandPalette,\n Confirmation,\n Controls,\n Footer,\n Frame,\n Help,\n Hint,\n Input,\n ModelPicker,\n PauseButton,\n PausedState,\n RestoredResources,\n Root,\n SendButton,\n Status,\n Surface,\n useChatComposerController,\n type ChatComposerMessages,\n type ComposerControlLinks,\n type ResponsiveBasis,\n} from \"./composer\";\nimport {\n ComposerTranscriptionControl,\n type ComposerTranscriptionControlProps,\n} from \"./composer-transcription-control\";\nimport { TimelineAnnotationsChip } from \"./timeline-annotations\";\n\nexport { OPEN_WORKSTREAM_CONTROL_EVENT };\n\nexport type ChatComposerProps = {\n composer: ComposerState;\n /**\n * Measurement surface for responsive chrome. Defaults to the historical\n * viewport breakpoints; opt into `container` for narrow embedded panels.\n */\n responsiveBasis?: ResponsiveBasis | undefined;\n /** Canonical workstream control, separate from lifecycle status. */\n effectiveControl?: EffectiveSessionControl | null | undefined;\n /** Waiting prompts already ahead of a normal Send. */\n queuedAheadCount?: number | undefined;\n /** Whether broader Workspace Resume is authorized for this viewer. */\n canControlWorkspace?: boolean | undefined;\n /** Optional host routes used to navigate from effective Pause blockers. */\n controlLinks?: ComposerControlLinks | undefined;\n placeholder?: string | undefined;\n disabled?: boolean | undefined;\n autoFocus?: boolean | undefined;\n /** Replaces the default keyboard hint under the field. */\n hint?: string | undefined;\n /** App controls ahead of attach (e.g. mobile “+” overflow). */\n controlsLeading?: ReactNode | undefined;\n /** App controls in the footer row, replacing the hint. */\n controlsStart?: ReactNode | undefined;\n /** App actions beside Pause/Send, ordered before the built-in actions. */\n actionsStart?: ReactNode | undefined;\n /** Extra classes for the built-in attach control (e.g. `max-sm:hidden`). */\n attachButtonClassName?: string | undefined;\n /** Provider-neutral speech capability. Provider configuration stays in workspace settings. */\n transcription?: ComposerTranscriptionControlProps | undefined;\n /** Extra classes on the transcription control. */\n transcriptionClassName?: string | undefined;\n /** Soft-hide dictate while realtime voice is active (animated collapse). */\n transcriptionSuppressed?: boolean | undefined;\n /** Content rendered above the textarea, inside the field chrome. */\n header?: ReactNode | undefined;\n /** Paste hook composed with the attachment paste path. */\n onPaste?: ((event: ClipboardEvent<HTMLTextAreaElement>) => void) | undefined;\n /** Opt-in file attachment state, typically from `useFileAttachments`. */\n attachments?: UseFileAttachmentsResult | undefined;\n /** Opt-in model picker choices. */\n models?: ClientModel[] | undefined;\n selectedModel?: string | undefined;\n onSelectModel?: ((modelId: string) => void) | undefined;\n className?: string | undefined;\n commands?: readonly SlashCommand[] | undefined;\n commandContext?: SlashCommandContext | undefined;\n onClearView?: (() => void) | undefined;\n /** Partial overrides for all composer-owned visible and accessible copy. */\n messages?: Partial<ChatComposerMessages> | undefined;\n};\n\n/**\n * Batteries-included chat composer. This preset is assembled exclusively from\n * the public controller and compound primitives exported by the composer\n * subpath, so custom and default layouts share one behavioral implementation.\n */\nexport function ChatComposer({\n composer,\n responsiveBasis,\n effectiveControl,\n queuedAheadCount,\n canControlWorkspace,\n controlLinks,\n placeholder,\n disabled,\n autoFocus,\n hint,\n controlsLeading,\n controlsStart,\n actionsStart,\n attachButtonClassName,\n transcription,\n transcriptionClassName,\n transcriptionSuppressed = false,\n header,\n onPaste,\n attachments,\n models,\n selectedModel,\n onSelectModel,\n className,\n commands,\n commandContext,\n onClearView,\n messages,\n}: ChatComposerProps) {\n const controller = useChatComposerController({\n delivery: composer,\n draft: composer,\n control: composer,\n effectiveControl,\n queuedAheadCount,\n canControlWorkspace,\n controlLinks,\n disabled,\n attachments,\n commands,\n commandContext,\n onClearView,\n onPaste,\n messages,\n });\n const hasControls = Boolean(\n attachments || models || controlsLeading || controlsStart || transcription,\n );\n const stackActions = hasControls && Boolean(actionsStart);\n\n return (\n <>\n <Root controller={controller} responsiveBasis={responsiveBasis} className={className}>\n <Frame>\n <CommandPalette />\n <Surface>\n <PausedState />\n <RestoredResources />\n <Attachments />\n {header}\n {composer.annotations &&\n composer.annotations.length > 0 &&\n composer.updateAnnotation &&\n composer.removeAnnotation ? (\n <div className=\"px-3.5 pt-2 md:px-4\">\n <TimelineAnnotationsChip\n annotations={composer.annotations}\n editable\n focusAnnotationId={composer.annotationReviewTargetId}\n onFocusConsumed={composer.clearAnnotationReviewTarget}\n onUpdate={composer.updateAnnotation}\n onRemove={composer.removeAnnotation}\n />\n </div>\n ) : null}\n <Input placeholder={placeholder} autoFocus={autoFocus} />\n {controller.confirmState ? (\n <Confirmation />\n ) : (\n <Footer\n data-og-stack-actions={stackActions ? \"\" : undefined}\n className={stackActions ? \"max-sm:flex-nowrap sm:flex-wrap\" : undefined}\n >\n <LayoutGroup id=\"og-composer-footer\">\n {hasControls ? (\n <Controls\n className={stackActions ? \"min-w-0 max-sm:flex-1 sm:w-auto\" : undefined}\n >\n {controlsLeading}\n <AttachButton className={attachButtonClassName} />\n {transcription ? (\n <ComposerTranscriptionControl\n {...transcription}\n suppressed={transcriptionSuppressed}\n className={[transcription.className, transcriptionClassName]\n .filter(Boolean)\n .join(\" \")}\n />\n ) : null}\n {models ? (\n <motion.span\n layout\n transition={{ duration: 0.36, ease: [0.22, 1, 0.36, 1] }}\n className=\"inline-flex min-w-0\"\n >\n <ModelPicker\n models={models}\n value={selectedModel}\n onChange={onSelectModel}\n />\n </motion.span>\n ) : null}\n {controlsStart ? (\n <motion.span\n layout\n transition={{ duration: 0.36, ease: [0.22, 1, 0.36, 1] }}\n className=\"inline-flex min-w-0 flex-1 items-center gap-1.5\"\n >\n {controlsStart}\n </motion.span>\n ) : null}\n </Controls>\n ) : (\n <Hint>{hint}</Hint>\n )}\n <Actions\n className={\n stackActions ? \"max-sm:shrink-0 sm:w-auto sm:justify-end\" : undefined\n }\n >\n {actionsStart}\n <PauseButton />\n <SendButton />\n </Actions>\n </LayoutGroup>\n </Footer>\n )}\n </Surface>\n </Frame>\n <Help />\n <Status />\n </Root>\n </>\n );\n}\n","import { useRef, type CSSProperties } from \"react\";\nimport { useOpenGeni, type ClientOverride } from \"../session-context\";\nimport { useWorkspaceModelCatalog } from \"../hooks/use-available-models\";\nimport { ModelPolicyPicker } from \"./model-policy-picker\";\nimport { useSessionEvents } from \"../hooks/use-session-events\";\nimport { useSession } from \"../hooks/use-session\";\nimport { useTurnQueue } from \"../hooks/use-turn-queue\";\nimport { useComposer } from \"../hooks/use-composer\";\nimport { useHumanInputRequests } from \"../hooks/use-human-input\";\nimport { ChatComposer, type ChatComposerProps } from \"./chat-composer\";\nimport { QueueSurface } from \"./queue-surface\";\nimport { HumanInputSurface, type HumanInputSurfaceProps } from \"./human-input-surface\";\nimport { MessageTimeline } from \"./message-timeline\";\nimport type { UserMessageDisclosureLabels } from \"./user-message-body\";\nimport { conversationTimeline } from \"../conversation-timeline\";\nimport { cn } from \"../lib/cn\";\n\nexport type SessionConversationProps = ClientOverride & {\n sessionId: string;\n /** Localized actions for already-sent user-message disclosure. */\n userMessageDisclosureLabels?: UserMessageDisclosureLabels | undefined;\n loadSkillReview?: HumanInputSurfaceProps[\"loadSkillReview\"];\n className?: string;\n /** Defaults to filling the host. The host owns available height. */\n height?: CSSProperties[\"height\"];\n /** Presentation/custom controls only; queue and delivery wiring stay owned here. */\n composerProps?: Omit<ChatComposerProps, \"composer\" | \"effectiveControl\" | \"queuedAheadCount\">;\n};\n\n/** Complete existing-session conversation. Uses the provider's normal SDK client\n * (including Site clients), one shared event feed, and authoritative queue state. */\nexport function SessionConversation(props: SessionConversationProps) {\n return <Conversation key={`${props.workspaceId ?? \"\"}:${props.sessionId}`} {...props} />;\n}\n\nfunction Conversation({\n sessionId,\n userMessageDisclosureLabels,\n loadSkillReview,\n client,\n workspaceId,\n className,\n height = \"100%\",\n composerProps,\n}: SessionConversationProps) {\n const scope = { client, workspaceId };\n const context = useOpenGeni(scope);\n const catalog = useWorkspaceModelCatalog({\n client: context.client,\n workspaceId: context.workspaceId,\n });\n const feed = useSessionEvents(sessionId, scope);\n const options = { ...scope, events: feed.events };\n const detail = useSession(sessionId, options);\n const queue = useTurnQueue(sessionId, options);\n const human = useHumanInputRequests(sessionId, options);\n const status = feed.sessionStatus ?? detail.session?.status;\n const terminal = status === \"cancelled\";\n const composer = useComposer(sessionId, {\n ...options,\n effectiveControl: queue.effectiveControl ?? detail.session?.effectiveControl,\n sendDestination: () => (queue.queue.length > 0 || status === \"running\" ? \"queue\" : \"chat\"),\n });\n const region = useRef<HTMLDivElement>(null);\n const error = detail.error ?? feed.error ?? human.error;\n return (\n <div\n className={cn(\n \"og-root flex min-h-0 min-w-0 flex-col gap-2 overflow-hidden bg-og-bg text-og-fg\",\n className,\n )}\n ref={region}\n style={{ height }}\n data-og-conversation=\"\"\n >\n {error && <p role=\"alert\">{error.message}</p>}\n <MessageTimeline\n userMessageDisclosureLabels={userMessageDisclosureLabels}\n className=\"min-h-0 flex-1\"\n items={conversationTimeline(feed.timeline, queue, composer)}\n status={status}\n hasOlder={feed.hasOlder}\n loadingOlder={feed.loadingOlder}\n onLoadOlder={feed.loadOlder}\n hasNewer={feed.hasNewer}\n loadingNewer={feed.loadingNewer}\n onLoadNewer={feed.loadNewer}\n onJumpToStart={async () => {\n await feed.loadOldest();\n }}\n loadingOldest={feed.loadingOldest}\n onJumpToLatest={feed.jumpToLatest}\n onAnnotate={composer.addAnnotation}\n />\n <div className=\"min-h-0 max-h-[40%] shrink-0 overflow-y-auto\" data-og-conversation-inputs=\"\">\n <HumanInputSurface\n loadSkillReview={loadSkillReview}\n requests={human.requests}\n onSubmit={async (id, response) => {\n await human.respond(id, response);\n }}\n respondingRequestId={human.respondingRequestId}\n error={human.mutationError?.message}\n autoFocus={false}\n />\n {terminal ? (\n <QueueSurface queue={queue} readOnly />\n ) : (\n <QueueSurface\n queue={queue}\n composer={composer}\n onRequestComposerFocus={() =>\n region.current?.querySelector<HTMLTextAreaElement>(\"textarea\")?.focus()\n }\n />\n )}\n </div>\n <div className=\"shrink-0\" data-og-conversation-composer=\"\">\n <ChatComposer\n {...composerProps}\n composer={composer}\n disabled={terminal || composerProps?.disabled}\n controlsStart={\n composerProps?.controlsStart ??\n (composer.policy && (\n <ModelPolicyPicker\n rows={catalog.rows}\n model={composer.policy.model}\n effort={composer.policy.reasoningEffort}\n latencyMode={composer.policy.latencyMode}\n loading={catalog.loading}\n error={catalog.error?.message}\n disabled={terminal}\n sessionKey={sessionId}\n onModelChange={(model) => composer.setModel?.(model)}\n onEffortChange={(effort) => composer.setReasoningEffort?.(effort)}\n onLatencyModeChange={(mode) => composer.setLatencyMode?.(mode)}\n />\n ))\n }\n responsiveBasis={composerProps?.responsiveBasis ?? \"container\"}\n effectiveControl={\n composer.effectiveControl ?? queue.effectiveControl ?? detail.session?.effectiveControl\n }\n queuedAheadCount={queue.queue.length}\n />\n </div>\n </div>\n );\n}\n","import type { ComposerState } from \"./hooks/use-composer\";\nimport type { UseTurnQueueResult } from \"./hooks/use-turn-queue\";\nimport type { TimelineItem, UserMessageItem } from \"./timeline/types\";\n\n/** Keep pending prompts in the queue, not duplicated in the conversation. */\nexport function conversationTimeline(\n items: TimelineItem[],\n queue: Pick<UseTurnQueueResult, \"queue\" | \"snapshot\" | \"acceptedSteers\">,\n composer: Pick<\n ComposerState,\n \"optimisticMessages\" | \"retryOptimisticMessage\" | \"removeOptimisticMessage\"\n >,\n): TimelineItem[] {\n const queued = new Set(\n queue.queue\n .filter((turn) => turn.metadata.delivery !== \"steer\")\n .map((turn) => turn.triggerEventId),\n );\n const pending = composer.optimisticMessages ?? [];\n const pendingQueue = new Set(\n pending\n .filter(\n (message) =>\n message.destination === \"queue\" &&\n !(\n message.turnId &&\n message.appliedQueueVersion != null &&\n queue.snapshot &&\n queue.snapshot.version >= message.appliedQueueVersion &&\n !queue.queue.some((turn) => turn.id === message.turnId)\n ),\n )\n .map((message) => `user-message:${message.clientEventId}`),\n );\n const visible = items.filter(\n (item) =>\n item.kind !== \"user-message\" ||\n (!queued.has(item.id) && !pendingQueue.has(item.reconciliationKey ?? \"\")),\n );\n const keys = new Set(\n visible.flatMap((item) => (item.kind === \"user-message\" ? [item.reconciliationKey] : [])),\n );\n const optimistic: UserMessageItem[] = pending\n .filter(\n (message) =>\n !keys.has(`user-message:${message.clientEventId}`) &&\n !queue.queue.some((turn) => turn.id === message.turnId),\n )\n .map((message) => ({\n kind: \"user-message\",\n id: `optimistic:${message.clientEventId}`,\n reconciliationKey: `user-message:${message.clientEventId}`,\n text: message.text,\n annotations: message.annotations.map((annotation, ordinal) => ({ ...annotation, ordinal })),\n resources: message.resources,\n tools: [],\n occurredAt: message.occurredAt,\n delivery: {\n state: message.state,\n ...(message.error ? { error: message.error } : {}),\n ...(message.state === \"failed\"\n ? {\n onRetry: () => composer.retryOptimisticMessage?.(message.clientEventId),\n onRemove: () => composer.removeOptimisticMessage?.(message.clientEventId),\n }\n : {}),\n },\n }));\n const ids = new Set(visible.map((item) => item.id));\n const steers: UserMessageItem[] = (queue.acceptedSteers ?? [])\n .filter((steer) => !ids.has(steer.triggerEventId))\n .map((steer) => ({\n kind: \"user-message\",\n id: steer.triggerEventId,\n text: steer.text,\n annotations: steer.annotations,\n resources: steer.resources,\n tools: steer.tools,\n occurredAt: steer.occurredAt,\n delivery: { state: steer.state },\n }));\n return [...visible, ...optimistic, ...steers];\n}\n","import { ChildSessionLink } from \"./child-session-link\";\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 * Queue opens by default when chrome is idle and at least one authoritative\n * prompt is queued. Closing the queue dismisses that session's offer until\n * occupancy drains; a different session on the same chrome instance may\n * offer again. An in-flight optimistic Send never opens the drawer —\n * admission stays a paint-only receipt on the chip so layout does not jump\n * under the pointer.\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 {\n SessionGoal,\n SessionPendingInputPreview,\n SessionStatus,\n SessionTurn,\n} from \"@opengeni/sdk\";\nimport {\n ActivityIcon,\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 TerminalIcon,\n TriangleAlertIcon,\n XIcon,\n CornerDownRightIcon,\n TargetIcon,\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 =\n | \"incoming\"\n | \"steering\"\n | \"queue\"\n | \"goal\"\n | \"agents\"\n | \"commands\";\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 compact?: boolean;\n /** Authoritative execution status; omitted by older embedding hosts. */\n sessionStatus?: SessionStatus | undefined;\n queue: UseTurnQueueResult;\n /** Needed for queue edit → composer checkout. Omit with `readOnly`. */\n composer?: ComposerState | undefined;\n /** Focus the composer after a successful queue checkout has applied its draft.\n * Connect to the composer controller's `focusInput`, or a custom input ref.\n * Never called for failed checkout or while replacement awaits confirmation.\n */\n onComposerFocus?: (() => void) | undefined;\n goal?: UseGoalResult | null | undefined;\n /** Expanded agents body (host supplies tree / list). */\n agentsPanel?: ReactNode;\n /** Active commands only. The host mounts the body only when opened. */\n commandsPanel?: ReactNode;\n commandsCount?: number | undefined;\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 /** Open a typed child update's source through the host's normal authorized route. */\n onOpenSession?: ((sessionId: 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 | \"session_failed\"\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: \"Waiting\",\n blocked: \"Blocked\",\n session_failed: \"Blocked by session failure\",\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 `wait_for_input` 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 === \"session_failed\") {\n return \"Resolve the session failure, then use Continue or send a message to continue this active goal.\";\n }\n if (state === \"paused\") {\n return record?.pausedReason\n ? (GOAL_PAUSED_REASON_EXPLANATION[record.pausedReason] ?? null)\n : null;\n }\n if (state === \"scheduled\") {\n return continuation?.nextAttemptAt\n ? `Continues at ${formatClockTime(continuation.nextAttemptAt)}.`\n : \"Waiting to continue automatically.\";\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}. Relevant session input—including a child result, background-command result, agent message, schedule, 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 isAuthoritativeQueuedTurn(\n turn: SessionTurn,\n mutationFor: UseTurnQueueResult[\"mutationFor\"],\n): boolean {\n return !isSteeringTurn(turn) && mutationFor(turn.id) !== \"steer\";\n}\n\nexport function countAuthoritativeQueuedTurns(\n turns: readonly SessionTurn[],\n mutationFor: UseTurnQueueResult[\"mutationFor\"],\n): number {\n return turns.filter((turn) => isAuthoritativeQueuedTurn(turn, mutationFor)).length;\n}\n\nfunction isOptimisticQueuedMessage(\n message: ComposerOptimisticMessage,\n queuedTurnIds: ReadonlySet<string>,\n snapshot: UseTurnQueueResult[\"snapshot\"],\n): boolean {\n return (\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 snapshot &&\n snapshot.version >= message.appliedQueueVersion\n )\n );\n}\n\nexport function countOptimisticQueuedMessages(\n messages: readonly ComposerOptimisticMessage[] | undefined,\n queuedTurnIds: ReadonlySet<string>,\n snapshot: UseTurnQueueResult[\"snapshot\"],\n): number {\n return (messages ?? []).filter((message) =>\n isOptimisticQueuedMessage(message, queuedTurnIds, snapshot),\n ).length;\n}\n\n/**\n * First uncontrolled segment. An existing authoritative queue opens itself\n * when the host did not pick another default; optimistic-only occupancy\n * stays collapsed so a live Send does not shove a drawer under the pointer.\n */\nexport function sessionChromeInitialActive(input: {\n defaultActive: SessionChromeSignalId | null;\n authoritativeQueuedCount: number;\n}): SessionChromeSignalId | null {\n if (input.defaultActive != null) return input.defaultActive;\n return input.authoritativeQueuedCount >= 1 ? \"queue\" : null;\n}\n\n/**\n * Whether idle chrome should offer the queue panel. A dismissed session\n * stays collapsed until occupancy drains. Controlled hosts own this.\n */\nexport function sessionChromeShouldOfferQueue(input: {\n controlled: boolean;\n active: SessionChromeSignalId | null;\n activityOpen: boolean;\n authoritativeQueuedCount: number;\n suppressed: boolean;\n}): boolean {\n return (\n !input.controlled &&\n input.active === null &&\n !input.activityOpen &&\n input.authoritativeQueuedCount >= 1 &&\n !input.suppressed\n );\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 sessionStatus?: SessionStatus,\n): GoalPillState {\n if (goalStatus === \"completed\") return \"completed\";\n if (goalStatus === \"paused\") return \"paused\";\n if (sessionStatus === \"failed\") return \"session_failed\";\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 if (continuation.reason === \"human_turn_running\") return \"waiting\";\n // `held_for_input` is the agent's own wait_for_input 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 case \"background_command_result\":\n return \"Command result\";\n case \"session_wait_timeout\":\n return \"Wait ended\";\n case \"media_generation_result\":\n return \"Video result\";\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 compact = false,\n sessionStatus,\n queue,\n composer,\n onComposerFocus,\n goal,\n agentsPanel,\n commandsPanel,\n commandsCount = 0,\n agentsSignal,\n onDismissIncoming,\n onOpenSession,\n readOnly = false,\n className,\n active: activeControlled,\n defaultActive = null,\n onActiveChange,\n}: SessionChromeProps) {\n const [activityRequested, setActivityOpen] = useState(\n Boolean(compact && defaultActive && [\"incoming\", \"agents\", \"commands\"].includes(defaultActive)),\n );\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) => isAuthoritativeQueuedTurn(turn, queueMutationFor)),\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((message) =>\n isOptimisticQueuedMessage(message, queuedTurnIds, queue.snapshot),\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 elapsed = useLiveElapsed(record?.createdAt, Boolean(record));\n const goalState = record\n ? sessionChromeGoalPillState(record.status, record.continuation, sessionStatus)\n : null;\n\n const initialAuthoritativeQueuedCount = countAuthoritativeQueuedTurns(\n queue.queue,\n queue.mutationFor,\n );\n const [activeUncontrolled, setActiveUncontrolled] = useState<SessionChromeSignalId | null>(() =>\n sessionChromeInitialActive({\n defaultActive,\n authoritativeQueuedCount: initialAuthoritativeQueuedCount,\n }),\n );\n const active = activeControlled !== undefined ? activeControlled : activeUncontrolled;\n const activityOpen =\n activityRequested ||\n Boolean(compact && active && [\"incoming\", \"agents\", \"commands\"].includes(active));\n const activityVisibleRef = useRef(activityOpen);\n activityVisibleRef.current = activityOpen;\n // Two independent suppressions, both occupancy-scoped:\n // - admission: a live Send while idle must not open a drawer under the pointer\n // - dismiss: closing the queue remembers that session until occupancy drains\n const queueOfferAdmissionSuppressedRef = useRef(\n defaultActive == null &&\n initialAuthoritativeQueuedCount === 0 &&\n countOptimisticQueuedMessages(composer?.optimisticMessages, queuedTurnIds, queue.snapshot) >\n 0,\n );\n const queueOfferDismissedSessionIdsRef = useRef<Set<string>>(new Set());\n const occupancySessionId = queuedTurns[0]?.sessionId ?? null;\n const setActive = (next: SessionChromeSignalId | null) => {\n if (active === \"queue\" && next === null) {\n if (occupancySessionId) {\n queueOfferDismissedSessionIdsRef.current.add(occupancySessionId);\n } else {\n queueOfferAdmissionSuppressedRef.current = true;\n }\n }\n if (activeControlled === undefined) setActiveUncontrolled(next);\n onActiveChange?.(next);\n };\n\n const hasCommandsPanel = commandsPanel != null;\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 === \"session_failed\" ||\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: <TargetIcon className=\"size-3\" />,\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 if (commandsCount > 0 || (active === \"commands\" && hasCommandsPanel)) {\n rows.push({\n id: \"commands\",\n label:\n commandsCount > 0\n ? `${commandsCount} command${commandsCount === 1 ? \"\" : \"s\"}`\n : \"Commands\",\n tone: commandsCount > 0 ? \"running\" : \"neutral\",\n icon: <TerminalIcon className=\"size-3\" />,\n });\n }\n return rows;\n }, [\n commandsCount,\n hasCommandsPanel,\n active,\n agentsSignal,\n elapsed,\n goalState,\n incoming,\n optimisticQueued,\n queue.error,\n queue.mutationError,\n queuedTurns,\n record,\n ]);\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 if (activeControlled === undefined && active === null) {\n queueOfferAdmissionSuppressedRef.current = true;\n }\n }, [active, activeControlled, optimisticQueueKeys, optimisticQueued]);\n const queueOccupied = queuedTurns.length > 0 || optimisticQueued.length > 0;\n useEffect(() => {\n if (queueOccupied) return;\n // A later wave may offer again. A prior session's dismiss must not stick\n // after this instance has actually gone empty.\n queueOfferAdmissionSuppressedRef.current = false;\n queueOfferDismissedSessionIdsRef.current.clear();\n }, [queueOccupied]);\n const queueOfferSuppressed =\n queueOfferAdmissionSuppressedRef.current ||\n (occupancySessionId != null &&\n queueOfferDismissedSessionIdsRef.current.has(occupancySessionId));\n useEffect(() => {\n if (\n !sessionChromeShouldOfferQueue({\n controlled: activeControlled !== undefined,\n active,\n activityOpen,\n authoritativeQueuedCount: queuedTurns.length,\n suppressed: queueOfferSuppressed,\n })\n ) {\n return;\n }\n if (activeControlled === undefined) setActiveUncontrolled(\"queue\");\n onActiveChange?.(\"queue\");\n }, [\n active,\n activeControlled,\n activityOpen,\n occupancySessionId,\n onActiveChange,\n queueOfferSuppressed,\n queuedTurns.length,\n ]);\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 (\n compact &&\n !signals.some((signal) => [\"incoming\", \"agents\", \"commands\"].includes(signal.id))\n )\n setActivityOpen(false);\n }, [compact, signals]);\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) {\n setPill((prev) => ({ ...prev, opacity: 0 }));\n return;\n }\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\n inputs={incoming}\n onDismiss={onDismissIncoming}\n onOpenSession={onOpenSession}\n />\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) {\n composer.applyDraft(checkedOut);\n onComposerFocus?.();\n }\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) {\n composer.applyDraft(checkedOut);\n onComposerFocus?.();\n }\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 === \"commands\" ? (\n <div data-og-session-chrome-panel=\"commands\">{commandsPanel}</div>\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: compact\n ? \"transparent\"\n : open\n ? \"var(--_og-session-chrome-surface-open)\"\n : \"var(--_og-session-chrome-surface)\",\n borderColor: compact\n ? \"transparent\"\n : open\n ? \"var(--_og-session-chrome-border-open)\"\n : \"var(--_og-session-chrome-border)\",\n boxShadow: compact\n ? \"none\"\n : 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={cn(\"relative flex items-center\", compact ? \"flex-nowrap\" : \"flex-wrap\")}\n style={{\n gap: compact ? \"10px\" : \"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\n .filter(\n (signal) => !compact || ![\"incoming\", \"agents\", \"commands\"].includes(signal.id),\n )\n .map((signal) => {\n const selected = active === signal.id;\n return (\n <div\n key={signal.id}\n role=\"group\"\n aria-label={\n signal.id === \"queue\"\n ? \"Queued messages and actions\"\n : signal.id === \"goal\"\n ? \"Goal and actions\"\n : signal.label\n }\n className={cn(\n \"group/signal relative z-[1] inline-flex min-w-0 max-w-full items-center rounded-og-md\",\n compact && \"bg-og-surface-2/60 px-0.5\",\n compact && selected && \"bg-og-surface-3\",\n )}\n >\n <button\n type=\"button\"\n ref={(node) => {\n chipRefs.current[signal.id] = node;\n }}\n aria-expanded={selected}\n aria-controls={panelId}\n aria-label={\n compact && signal.id === \"goal\"\n ? `Goal · ${goalState === \"pursuing\" ? \"Running\" : signal.label}`\n : selected\n ? `Close ${signal.label}`\n : undefined\n }\n data-testid={`session-chrome-${signal.id}`}\n data-og-session-chrome-signal={signal.id}\n title={signal.title ?? (compact ? signal.label : undefined)}\n onClick={() => {\n if (compact) setActivityOpen(false);\n setActive(selected ? null : signal.id);\n }}\n className={cn(\n \"group relative z-[1] inline-flex min-w-0 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\n className={cn(\n \"font-medium text-og-fg\",\n compact ? \"min-w-0 truncate\" : \"shrink-0\",\n )}\n >\n {compact && signal.id === \"goal\" ? \"Goal · \" : null}\n {compact && signal.id === \"goal\"\n ? goalState === \"pursuing\"\n ? \"Running\"\n : signal.label\n : compact && signal.id === \"queue\"\n ? `${queuedTurns.length + optimisticQueued.length} queued`\n : signal.label}\n </span>\n {signal.detail && !compact ? (\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 && !compact ? (\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 {signal.id === \"goal\" && goal && record && !readOnly ? (\n <div className={cn(\"flex shrink-0 items-center pr-1\", compact && \"pl-0.5\")}>\n {record.status === \"active\" || record.status === \"paused\" ? (\n <IconAction\n label={record.status === \"paused\" ? \"Resume goal\" : \"Pause goal\"}\n tip={record.status === \"paused\" ? \"Resume goal\" : \"Pause goal\"}\n disabled={goal.updating}\n onClick={() =>\n void (record.status === \"paused\"\n ? goal.resume()\n : goal.pause(\"Paused from session chrome\"))\n }\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 </IconAction>\n ) : null}\n <IconAction\n label=\"Clear goal\"\n tip=\"Clear goal\"\n danger\n disabled={goal.updating}\n onClick={() => void goal.deleteGoal()}\n >\n <Trash2Icon className=\"size-3\" />\n </IconAction>\n </div>\n ) : signal.id === \"queue\" && canMutateQueue && queuedTurns[0] ? (\n <div className={cn(\"flex shrink-0 items-center pr-1\", compact && \"pl-0.5\")}>\n <IconAction\n label=\"Steer first queued message\"\n text=\"Steer\"\n tip={QUEUE_STEER_TIP}\n disabled={\n queue.mutating || Boolean(queue.mutationFor(queuedTurns[0].id))\n }\n onClick={() => void queue.steerTurn(queuedTurns[0]!.id)}\n >\n <CornerDownRightIcon className=\"size-3\" />\n </IconAction>\n </div>\n ) : null}\n </div>\n );\n })}\n {compact &&\n signals.some((signal) => [\"incoming\", \"agents\", \"commands\"].includes(signal.id)) ? (\n <button\n type=\"button\"\n aria-label=\"Session activity\"\n title={activityOpen ? \"Close activity\" : \"Inbox, agents and commands\"}\n aria-controls={panelId}\n aria-expanded={activityOpen}\n onClick={() => {\n setActivityOpen(!activityOpen);\n setActive(\n activityOpen\n ? null\n : (signals.find((signal) =>\n [\"incoming\", \"agents\", \"commands\"].includes(signal.id),\n )?.id ?? null),\n );\n }}\n className={cn(\n \"ml-auto inline-flex min-h-8 shrink-0 items-center justify-center gap-1.5 rounded-og-md px-2 text-og-xs transition-colors outline-hidden focus-visible:ring-2 focus-visible:ring-og-accent/40 pointer-coarse:min-h-11 pointer-coarse:min-w-11\",\n activityOpen\n ? \"bg-og-surface-3 text-og-fg\"\n : \"text-og-fg-muted hover:bg-og-surface-2 hover:text-og-fg\",\n )}\n >\n <ActivityIcon className=\"size-3.5\" />\n <span className=\"sr-only\">Activity</span>\n {incoming.length > 0 ? (\n <span className=\"size-1.5 rounded-full bg-og-accent\" />\n ) : null}\n </button>\n ) : null}\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 <AnimatePresence initial={false}>\n {compact && activityOpen ? (\n <motion.div\n key=\"activity-tabs\"\n initial={{ height: 0, opacity: 0 }}\n animate={{ height: \"auto\", opacity: 1 }}\n exit={{ height: 0, opacity: 0 }}\n transition={{ duration: shellDuration, ease }}\n style={{ overflow: \"hidden\" }}\n >\n <div className=\"mt-1 flex items-center gap-1 rounded-t-og-lg bg-og-surface-2/50 px-2 py-1\">\n {signals\n .filter((signal) => [\"incoming\", \"agents\", \"commands\"].includes(signal.id))\n .map((signal) => (\n <button\n key={signal.id}\n type=\"button\"\n aria-expanded={active === signal.id}\n onClick={() => {\n if (activityVisibleRef.current) setActive(signal.id);\n }}\n className={cn(\n \"inline-flex min-h-9 items-center gap-1.5 rounded-og-md px-2 text-og-xs pointer-coarse:min-h-11\",\n active === signal.id\n ? \"bg-og-surface-3 text-og-fg\"\n : \"text-og-fg-muted hover:text-og-fg\",\n )}\n >\n {signal.icon}\n {signal.id === \"incoming\" ? `${incoming.length} incoming` : signal.label}\n </button>\n ))}\n </div>\n </motion.div>\n ) : null}\n </AnimatePresence>\n {goal?.mutationError ? (\n <p role=\"alert\" className=\"px-3 pb-2 text-og-xs text-og-danger\">\n Goal action not confirmed. {goal.mutationError.message}\n </p>\n ) : null}\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={cn(\n \"relative overflow-y-auto overscroll-contain\",\n compact\n ? activityOpen\n ? \"rounded-b-og-lg bg-og-surface-2/50\"\n : \"mt-1 rounded-og-lg bg-og-surface-2/50\"\n : \"border-t border-og-border/50\",\n )}\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 && active !== \"commands\" && 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 {active === \"commands\" ? (\n <motion.div\n key=\"commands\"\n initial={reduceMotion ? false : { opacity: 0 }}\n animate={{ opacity: 1 }}\n transition={{ duration: crossfadeDuration, ease }}\n >\n {panelBody}\n </motion.div>\n ) : null}\n </div>\n </div>\n </div>\n </div>\n </div>\n </TooltipProvider>\n );\n}\n\nfunction IncomingPanel({\n inputs,\n onDismiss,\n onOpenSession,\n}: {\n inputs: SessionPendingInputPreview[];\n onDismiss?: ((inputId: string) => void) | undefined;\n onOpenSession?: ((sessionId: string) => void) | undefined;\n}) {\n return (\n <div>\n <p className=\"mb-2 text-og-xs text-og-fg-subtle\">Waiting to be included in an agent turn.</p>\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 <div className=\"min-w-0 flex-1\">\n <p className=\"break-words text-og-xs leading-4 text-og-fg\">{input.summary}</p>\n <ChildSessionLink\n kind={input.kind}\n sourceId={input.sourceId}\n onOpenSession={onOpenSession}\n />\n </div>\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 </div>\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 text=\"Steer\"\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 <CornerDownRightIcon 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 · Created {elapsed} ago\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 text,\n label,\n tip,\n onClick,\n disabled,\n danger,\n children,\n}: {\n label: string;\n text?: 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 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 text ? \"text-og-fg\" : \"text-og-fg-subtle\",\n text && \"w-auto gap-1 px-1.5 text-og-xs pointer-coarse:w-auto\",\n danger && \"hover:text-og-danger\",\n )}\n >\n {children}\n {text}\n </button>\n </TooltipTrigger>\n <TooltipContent side=\"top\">{tip}</TooltipContent>\n </Tooltip>\n );\n}\n","import { ChevronRightIcon, Loader2Icon, SquareIcon } from \"lucide-react\";\nimport { useState } from \"react\";\nimport type { UseSessionBackgroundCommandsResult } from \"../hooks/use-session-background-commands\";\nimport { formatClockTime } from \"../lib/format\";\n\n/** The current session's live commands. Settled commands belong to the timeline. */\nexport function SessionCommandsPanel({\n commands: state,\n readOnly = false,\n}: {\n commands: UseSessionBackgroundCommandsResult;\n readOnly?: boolean;\n}) {\n const [pending, setPending] = useState<string | null>(null);\n const [error, setError] = useState<string | null>(null);\n const active = state.commands.filter(\n (command) => command.state === \"running\" || command.state === \"stopping\",\n );\n const stop = async (id: string) => {\n setPending(id);\n setError(null);\n try {\n await state.cancel(id);\n } catch (cause) {\n setError(cause instanceof Error ? cause.message : \"Stop was not confirmed. Try again.\");\n } finally {\n setPending(null);\n }\n };\n return (\n <div className=\"space-y-2 text-og-xs\" data-og-session-commands=\"\">\n {state.loading && active.length === 0 ? (\n <p role=\"status\" className=\"text-og-fg-muted\">\n Loading commands…\n </p>\n ) : null}\n {state.error ? (\n <div role=\"alert\" className=\"flex items-center justify-between gap-2 text-og-danger\">\n <span>Commands unavailable.</span>\n <button\n type=\"button\"\n className=\"underline outline-hidden focus-visible:ring-2 focus-visible:ring-og-accent/40\"\n onClick={() => void state.refresh()}\n >\n Retry\n </button>\n </div>\n ) : null}\n {!state.loading && !state.error && active.length === 0 ? (\n <p role=\"status\" className=\"text-og-fg-muted\">\n No background commands running.\n </p>\n ) : null}\n {active.length > 0 ? (\n <ul className=\"max-h-64 overflow-y-auto overscroll-contain divide-y divide-og-border/40\">\n {active.map((command) => (\n <li key={command.id} className=\"flex items-start gap-3 py-2 first:pt-0 last:pb-0\">\n <div className=\"min-w-0 flex-1\">\n <details className=\"group/command\">\n <summary\n className=\"flex cursor-pointer list-none items-center gap-1.5 rounded-og-sm font-mono text-og-fg outline-hidden focus-visible:ring-2 focus-visible:ring-og-accent/40\"\n title=\"Expand command\"\n >\n <ChevronRightIcon className=\"size-3 shrink-0 text-og-fg-subtle transition-transform group-open/command:rotate-90\" />\n <span className=\"truncate\">\n {command.commandPreview || \"Background command\"}\n </span>\n </summary>\n <div className=\"mt-2 space-y-1\">\n <p className=\"whitespace-pre-wrap break-all font-mono text-og-fg-muted\">\n {command.commandPreview || \"Background command\"}\n </p>\n <time\n className=\"block text-og-fg-subtle\"\n dateTime={command.startedAt}\n title={new Date(command.startedAt).toLocaleString()}\n >\n Started {formatClockTime(command.startedAt)}\n </time>\n </div>\n </details>\n <p className=\"mt-1 text-og-fg-subtle\">\n {command.observationStatus === \"unavailable\"\n ? command.state === \"stopping\"\n ? \"Stop requested · status unavailable\"\n : \"Command status unavailable\"\n : command.state === \"stopping\"\n ? \"Stopping…\"\n : \"Running\"}\n </p>\n </div>\n {!readOnly ? (\n <button\n type=\"button\"\n aria-label={`Stop ${command.commandPreview || \"background command\"}`}\n disabled={pending !== null || command.state === \"stopping\"}\n onClick={() => void stop(command.id)}\n className=\"inline-flex min-h-7 shrink-0 items-center gap-1 rounded-og-sm px-2 text-og-fg-muted outline-hidden hover:bg-og-surface-3/70 hover:text-og-fg focus-visible:ring-2 focus-visible:ring-og-accent/40 disabled:opacity-50 pointer-coarse:min-h-11\"\n >\n {pending === command.id || command.state === \"stopping\" ? (\n <Loader2Icon className=\"size-3 animate-og-spin motion-reduce:animate-none\" />\n ) : (\n <SquareIcon className=\"size-3\" />\n )}\n Stop\n </button>\n ) : null}\n </li>\n ))}\n </ul>\n ) : null}\n {error ? (\n <p role=\"alert\" className=\"text-og-danger\">\n {error}\n </p>\n ) : null}\n </div>\n );\n}\n","import type { StartupPhaseItem } from \"./types\";\n\nconst LABELS: Record<StartupPhaseItem[\"phase\"], string> = {\n queue: \"Worker queue\",\n sandbox: \"Sandbox\",\n rig: \"Rig\",\n repository: \"Repository\",\n files: \"Files\",\n tools: \"Tools\",\n model_preparation: \"Runtime & model request\",\n provider_first_byte: \"First model response\",\n};\n\nexport function StartupTimings({ phases }: { phases: StartupPhaseItem[] }) {\n if (!phases.length)\n return <p className=\"text-og-sm text-og-fg-subtle\">No startup timings recorded yet.</p>;\n const byTurn = new Map<string | null, StartupPhaseItem[]>();\n for (const phase of phases) {\n const group = byTurn.get(phase.turnId) ?? [];\n group.push(phase);\n byTurn.set(phase.turnId, group);\n }\n const turns = [...byTurn.entries()]\n .map(([turnId, turnPhases]) => ({\n turnId,\n phases: turnPhases,\n startedAt: turnPhases.reduce(\n (earliest, phase) => (phase.startedAt < earliest ? phase.startedAt : earliest),\n turnPhases[0]!.startedAt,\n ),\n }))\n .sort((a, b) => b.startedAt.localeCompare(a.startedAt));\n return (\n <div className=\"space-y-3\">\n <p className=\"text-og-xs text-og-fg-subtle\">\n Each turn has its own startup. Phases can overlap; durations are not additive.\n </p>\n {turns.map((turn, index) => (\n <StartupTurn\n key={turn.turnId ?? \"unassigned\"}\n {...turn}\n latest={index === 0 && turn.turnId !== null}\n />\n ))}\n </div>\n );\n}\n\nfunction StartupTurn({\n turnId,\n phases,\n startedAt,\n latest,\n}: {\n turnId: string | null;\n phases: StartupPhaseItem[];\n startedAt: string;\n latest: boolean;\n}) {\n const status = phases.some((phase) => phase.status === \"failed\")\n ? \"Failed\"\n : phases.some((phase) => phase.status === \"running\")\n ? \"In progress\"\n : phases.some((phase) => phase.status === \"cancelled\")\n ? \"Interrupted\"\n : \"Ready\";\n return (\n <details open={latest} className=\"group border-b border-og-border pb-3\">\n <summary className=\"cursor-pointer rounded py-3 text-og-sm text-og-fg-muted focus-visible:outline-2 focus-visible:outline-og-accent\">\n <span className=\"font-medium\">\n {turnId === null ? \"Unassigned events\" : latest ? \"Latest turn\" : \"Earlier turn\"}\n </span>\n <span className=\"ml-2 text-og-xs text-og-fg-subtle\">\n {new Date(startedAt).toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n })}\n </span>\n <span\n className={\n status === \"Failed\"\n ? \"ml-2 text-og-xs text-og-status-failed\"\n : \"ml-2 text-og-xs text-og-fg-subtle\"\n }\n >\n {status}\n </span>\n <span className=\"mt-1 block break-all pl-4 font-og-mono text-og-xs text-og-fg-subtle\">\n {turnId ?? \"No turn ID recorded\"}\n </span>\n </summary>\n <div className=\"pb-2\">\n <p className=\"text-og-xs text-og-fg-subtle\">\n Started <time dateTime={startedAt}>{new Date(startedAt).toLocaleString()}</time>\n </p>\n <div className=\"overflow-x-auto\">\n <table className=\"w-full text-left text-og-xs\">\n <caption className=\"sr-only\">\n Startup phases for {turnId ?? \"unassigned events\"}\n </caption>\n <thead>\n <tr className=\"border-b border-og-border text-og-fg-subtle\">\n <th scope=\"col\" className=\"py-2 font-medium\">\n Phase\n </th>\n <th scope=\"col\" className=\"px-3 py-2 font-medium\">\n Status\n </th>\n <th scope=\"col\" className=\"py-2 text-right font-medium\">\n Duration\n </th>\n </tr>\n </thead>\n <tbody>\n {phases.map((phase) => (\n <tr\n key={phase.id}\n className=\"border-b border-og-border/40\"\n title={`Turn: ${phase.turnId ?? \"unknown\"} · Started: ${phase.startedAt}`}\n >\n <th scope=\"row\" className=\"py-2.5 font-normal text-og-fg-muted\">\n {LABELS[phase.phase]}\n </th>\n <td\n className={`px-3 py-2.5 ${phase.status === \"failed\" ? \"text-og-status-failed\" : \"text-og-fg-subtle\"}`}\n >\n {phase.status === \"running\" ? \"In progress\" : phase.status}\n </td>\n <td className=\"py-2.5 text-right font-og-mono tabular-nums text-og-fg-muted\">\n {phase.durationMs === null\n ? \"—\"\n : phase.durationMs < 1000\n ? `${Math.round(phase.durationMs)} ms`\n : `${(phase.durationMs / 1000).toFixed(1)} s`}\n </td>\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n </div>\n </details>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,iBAAiB,eAAe,iCAAiC;AAC1E,SAAS,WAAW,OAAO,QAAQ,gBAAgD;AA2F1E,SAgIC,UAhID,KAiIG,YAjIH;AA5DF,IAAM,gCAAwD;AAAA,EACnE,OAAO;AAAA;AAAA,E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AEJ;","names":["useEffect","useRef","jsx","useRef","useEffect","useEffect","useId","useRef","useState","Fragment","jsx","jsxs","useId","useState","useRef","useEffect","jsx","createContext","useContext","useState","Fragment","jsx","jsxs","createContext","useState","useContext","createContext","useContext","useState","jsx","jsxs","createContext","useContext","useState","fallback","useEffect","useState","jsx","fallback","useState","useEffect","BrainCircuitIcon","CameraIcon","CameraOffIcon","MessageCircleQuestionIcon","useContext","useState","createContext","useContext","useState","useEffect","useState","jsx","jsxs","useState","jsx","jsxs","useContext","file","CameraIcon","CameraOffIcon","useState","BrainCircuitIcon","MessageCircleQuestionIcon","createContext","useContext","useEffect","useState","jsx","jsxs","BrainCircuitIcon","lazy","Suspense","useContext","useRef","useState","createContext","useContext","useRef","jsx","createContext","useContext","Fragment","jsx","jsxs","lazy","useState","useRef","Suspense","BrainCircuitIcon","useContext","createContext","useContext","useId","useLayoutEffect","useRef","useState","jsx","jsxs","createContext","useContext","useState","useRef","useId","useLayoutEffect","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","AnimatePresence","motion","useReducedMotion","WrenchIcon","Suspense","useEffect","useState","jsx","jsxs","useReducedMotion","useState","useEffect","item","fallback","WrenchIcon","AnimatePresence","motion","Suspense","jsx","parseSandboxFileArtifactReceipt","ArrowRightIcon","BotIcon","CheckIcon","ChevronRightIcon","MessageCircleQuestionIcon","TargetIcon","TriangleAlertIcon","AnimatePresence","motion","useReducedMotion","Collapsible","Component","Suspense","lazy","useCallback","useEffect","useLayoutEffect","useMemo","useRef","useState","Component","Fragment","jsx","jsxs","lazy","receipt","useMemo","useRef","useState","useEffect","useCallback","useLayoutEffect","attempt","Suspense","AnimatePresence","motion","node","Component","TriangleAlertIcon","TimelineGroupEntry","useReducedMotion","TimelineGroupView","parseSandboxFileArtifactReceipt","MessageCircleQuestionIcon","BotIcon","ArrowRightIcon","Collapsible","ChevronRightIcon","TargetIcon","CheckIcon","lazy","Suspense","jsx","jsxs","lazy","jsx","Suspense","jsxs","useCallback","useCallback","motion","Fragment","jsx","jsxs","jsx","Fragment","jsxs","motion","useRef","jsx","jsxs","useRef","ArrowDownIcon","BotIcon","CheckIcon","Loader2Icon","PauseIcon","PlayIcon","Trash2Icon","TerminalIcon","TriangleAlertIcon","XIcon","TargetIcon","AnimatePresence","motion","useReducedMotion","useEffect","useId","useMemo","useRef","useState","Fragment","jsx","jsxs","snapshot","useState","useEffect","useId","useReducedMotion","useMemo","useRef","TriangleAlertIcon","TargetIcon","BotIcon","TerminalIcon","motion","XIcon","Loader2Icon","PlayIcon","PauseIcon","Trash2Icon","AnimatePresence","ArrowDownIcon","CheckIcon","ChevronRightIcon","Loader2Icon","useState","jsx","jsxs","useState","ChevronRightIcon","Loader2Icon","jsx","jsxs"]}
|