import { ArrowUpRight } from "lucide-react"; import { AsyncQuestions } from "./AsyncQuestions"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Button } from "@/components/ui/button"; import { Dialog, DialogClose, DialogContent, DialogTitle, } from "@/components/ui/dialog"; import { Download, X } from "lucide-react"; import { Children, Fragment, isValidElement, cloneElement, createContext, memo, useContext, useEffect, useMemo, useRef, useState, type DetailsHTMLAttributes, type ReactElement, type ReactNode, } from "react"; import { ErrorBoundary } from "@/components/ErrorBoundary"; import { Check, CircleAlert, CircleDashed, CircleHelp, CircleMinus, Copy, GitFork, LoaderCircle } from "lucide-react"; import Markdown, { defaultUrlTransform, type Components } from "react-markdown"; import { markdownBlocks, useSmoothText } from "./smooth-text"; import { diffLines, diffStat, hunks, parsePatch, type DiffLine } from "./line-diff"; import { grammarForPath, useHighlight, type HighlightToken } from "./highlight"; import { fileTarget } from "./file-target"; import { messageTime } from "./session-time"; import remarkGfm from "remark-gfm"; import type { ContentBlock, ToolCallContent, UserContext } from "@linkshell/wire"; import { answeredQuestions, askedQuestions, compactionLabel, describeFailures, describeSteps, exitNote, foldStepRuns, formatElapsed, isQuietTool, presentError, proposedPlan, reconnectLabel, reconnectOf, startedSession, toolCommand, toolLabel, toolLabelParts, toolLabelText, toolOutput, toolOutcome, wrapUpOf, inboxLabel, questionReplies, tallySteps, userEventLabel, userMessageView, type Step, type TimelineItem, } from "@linkshell/client-core"; import { ChevronRight, ClipboardPaste, FileText, GitMerge, GitPullRequest, Globe, Highlighter, History, Image as ImageIcon, Layers, MessageSquareText, Paperclip, SearchCheck, TextSelect, type LucideIcon } from "lucide-react"; import { AgentMark, ErrorNotice, useActions, useConnection, useSessionOnline, useJob, } from "./common"; /** * Lines added and removed, each only when there are some: a "−0" in red reads as an error, and a * file that only gained lines says "+38". Nothing at all when nothing changed. */ export function DiffStat({ added, removed, className = "diff-stat" }: { added: number; removed: number; className?: string }) { if (!added && !removed) return null; return ( {added > 0 && +{added}} {added > 0 && removed > 0 && " "} {removed > 0 && −{removed}} ); } /** Active `⌘F` find query (lowercased & trimmed), or `""` when closed/empty. */ export const TimelineSearch = createContext(""); export function highlightSearchText(text: string, query: string): ReactNode { if (!query || !text) return text; const lowerText = text.toLowerCase(); const lowerQuery = query.toLowerCase(); if (!lowerText.includes(lowerQuery)) return text; const escaped = query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); const parts = text.split(new RegExp(`(${escaped})`, "gi")); if (parts.length <= 1) return text; return parts.map((part, index) => part.toLowerCase() === lowerQuery ? ( {part} ) : ( part ), ); } function highlightReactChildren(node: ReactNode, query: string): ReactNode { if (!query || node === null || node === undefined || typeof node === "boolean") return node; if (typeof node === "string") return highlightSearchText(node, query); if (typeof node === "number") return highlightSearchText(String(node), query); if (Array.isArray(node)) return node.map((child, idx) => {highlightReactChildren(child, query)}); if (isValidElement(node)) { const element = node as ReactElement<{ children?: ReactNode }>; if (element.type === "mark" || element.props.children === undefined) return node; return cloneElement(element, undefined, highlightReactChildren(element.props.children, query)); } return node; } function SearchableText({ text }: { text: string }) { const query = useContext(TimelineSearch); return <>{query ? highlightSearchText(text, query) : text}; } /** Extracts full searchable text for a timeline item, including folded tool outputs, diffs and thoughts. */ export function timelineItemSearchText(item: TimelineItem): string { switch (item.kind) { case "user": return [ userMessageView(item.blocks).text, ...(item.agentMessages?.flatMap((m) => [m.sender, m.summary, m.body]) ?? []), ] .filter(Boolean) .join("\n"); case "agent": case "thought": return item.text; case "error": { const shown = presentError(item); return [item.message, shown.title, shown.hint, shown.detail].filter(Boolean).join("\n"); } case "notice": return [item.title, item.detail].filter(Boolean).join("\n"); case "plan": return [item.title, item.markdown, ...item.entries.map((entry) => entry.content)] .filter(Boolean) .join("\n"); case "permission-result": return [ item.title, item.optionName, ...(item.answers?.map((answer) => `${answer.question} ${answer.answer}`) ?? []), ] .filter(Boolean) .join("\n"); case "tool": { const label = toolLabel(item); const command = label.action === "command" ? toolCommand(item) : undefined; const plan = label.action === "plan" ? proposedPlan(item) : undefined; const out = toolOutput(item); const diffTexts = item.content.flatMap((entry) => { if (entry.type === "diff") return [entry.path, entry.oldText, entry.newText]; if (entry.type === "patch") return [entry.path, entry.movePath, entry.diff]; if (entry.type === "content" && entry.content.type === "text") return [entry.content.text]; return []; }); const rawIn = item.rawInput === undefined ? "" : typeof item.rawInput === "string" ? item.rawInput : JSON.stringify(item.rawInput); const rawOut = item.rawOutput === undefined ? "" : typeof item.rawOutput === "string" ? item.rawOutput : JSON.stringify(item.rawOutput); const subText = item.sub ? item.sub.items.map(timelineItemSearchText).join("\n") : ""; return [ item.title, toolLabelText(label, { note: true }), command, plan, item.output, out, ...diffTexts, ...(item.locations?.map((loc) => loc.path) ?? []), rawIn, rawOut, subText, ] .filter(Boolean) .join("\n"); } default: return ""; } } /** A folded run of finished steps — "已编辑 2 个文件,已运行 5 个命令", one click open. */ export function StepsSummary({ steps, open, onToggle, historical, }: { steps: Step[]; open: boolean; onToggle: () => void; historical?: boolean; }) { const t = tallySteps(steps); const label = describeSteps(t); const failures = describeFailures(t); return ( ); } /** * A `
` whose body mounts when opened and unmounts again when closed, keeping folded * diffs, command outputs and sub-agent logs out of the DOM unless expanded or matched by `⌘F`. */ /** Folds build their bodies up front (a static render, which can't open one). */ export const FoldsBuilt = createContext(false); export interface FoldClickLikeEvent { defaultPrevented: boolean; currentTarget: unknown; target: unknown; preventDefault(): void; } export function consumeDirectFoldSummaryClick(event: FoldClickLikeEvent): boolean { if (event.defaultPrevented) return false; const target = event.target as { closest?: (selector: string) => { parentElement?: unknown } | null } | null; const summary = target?.closest?.("summary"); if (!summary || summary.parentElement !== event.currentTarget) return false; event.preventDefault(); return true; } export function Fold({ summary, children, className, defaultOpen = false, open: controlledOpen, searchText, onClick, ...rest }: { summary: ReactNode; children: ReactNode; className?: string; defaultOpen?: boolean; open?: boolean; searchText?: string; } & Omit, "open" | "onToggle" | "children">) { const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen); const userOpen = controlledOpen ?? uncontrolledOpen; const built = useContext(FoldsBuilt); const searchQuery = useContext(TimelineSearch); const searchMatched = Boolean( searchQuery && searchText && searchText.toLowerCase().includes(searchQuery), ); const effectiveOpen = userOpen || searchMatched; return (
{ onClick?.(event); if (consumeDirectFoldSummaryClick(event) && !searchMatched) { setUncontrolledOpen((prev) => !prev); } }} {...rest} > {summary} {(effectiveOpen || built) && children}
); } function CopyText({ text, label = "复制消息", }: { text: string; label?: string; }) { const [copied, setCopied] = useState(false); const job = useJob(); useEffect(() => { if (!copied) return; const timer = setTimeout(() => setCopied(false), 2000); return () => clearTimeout(timer); }, [copied]); return ( {job.error && ( 复制失败,请选中文本复制。 )} ); } export const TimelineNavigation = createContext<{ cwd: string; open: (path: string, line?: number) => void; /** Opens an MCP App call's page in the inspector (Codex sessions on the desktop). */ openApp?: (callId: string) => void; /** The session the agent's app knows by `appId` (the Claude app's `local_…`), when this computer has it. */ findSession?: (appId: string) => { title: string; open: () => void } | undefined; } | null>(null); /** The end-of-turn box whose buttons still answer (see `openWrapUp`); the conversation sets it. */ export const OpenWrapUp = createContext(undefined); /** Whether code blocks below may be highlighted: off for the block of a reply still streaming. */ const HighlightCode = createContext(true); /** The text of a node react-markdown made: strings, possibly nested in elements. */ function nodeText(node: ReactNode): string { if (typeof node === "string" || typeof node === "number") return String(node); if (Array.isArray(node)) return node.map(nodeText).join(""); if (isValidElement(node)) return nodeText((node.props as { children?: ReactNode }).children); return ""; } /** Highlighted lines, joined as the source was so copying and selecting give back the same text. */ export function TokenLines({ tokens }: { tokens: HighlightToken[][] }) { return tokens.map((line, index) => ( {index > 0 && "\n"} {line.map((token, at) => (token.color ? {token.content} : token.content))} )); } function CodeBlock({ children }: { children: ReactNode }) { const element = Children.toArray(children).find(isValidElement); const className = element && (element.props as { className?: string }).className; const language = className?.match(/language-([\w+-]+)/)?.[1]; const source = useMemo(() => nodeText(element).replace(/\n$/, ""), [element]); const searchQuery = useContext(TimelineSearch); const tokens = useHighlight(source, language, useContext(HighlightCode) && !searchQuery); const code = useRef(null); const [copied, setCopied] = useState(false); const job = useJob(); useEffect(() => { if (!copied) return; const timer = setTimeout(() => setCopied(false), 2000); return () => clearTimeout(timer); }, [copied]); return (
{language ?? "代码"}
        {/* Keep identical line breaks before and after the idle highlighter finishes. */}
        
          {searchQuery ? highlightSearchText(source, searchQuery) : tokens ?  : source}
        
      
); } function MarkdownLink({ href, children }: { href?: string; children?: React.ReactNode }) { const navigation = useContext(TimelineNavigation); const target = href && fileTarget(href, navigation?.cwd); return ( { if (target && navigation) { event.preventDefault(); navigation.open(target.path, target.line); } }} > {children} ); } // Stable, so a block whose text didn't change is not parsed again when its message re-renders. const markdownPlugins = [remarkGfm]; const markdownURL = (url: string) => (url.startsWith("file://") ? url : defaultUrlTransform(url)); const markdownComponents: Components = { pre: ({ children }) => {children}, a: ({ href, children }) => {children}, table: ({ children }) => (
{children}
), th: ({ children, ...props }) => {children}, img: ({ src, alt }) => ( {alt || "查看图片"} ), }; const MarkdownBlock = memo(function MarkdownBlock({ text }: { text: string }) { const searchQuery = useContext(TimelineSearch); const components = useMemo(() => { if (!searchQuery) return markdownComponents; return { ...markdownComponents, p: ({ children, ...props }) =>

{highlightReactChildren(children, searchQuery)}

, li: ({ children, ...props }) =>
  • {highlightReactChildren(children, searchQuery)}
  • , td: ({ children, ...props }) => {highlightReactChildren(children, searchQuery)}, th: ({ children, ...props }) => {highlightReactChildren(children, searchQuery)}, h1: ({ children, ...props }) =>

    {highlightReactChildren(children, searchQuery)}

    , h2: ({ children, ...props }) =>

    {highlightReactChildren(children, searchQuery)}

    , h3: ({ children, ...props }) =>

    {highlightReactChildren(children, searchQuery)}

    , h4: ({ children, ...props }) =>

    {highlightReactChildren(children, searchQuery)}

    , blockquote: ({ children, ...props }) =>
    {highlightReactChildren(children, searchQuery)}
    , code: ({ children, className, ...props }) => ( {className ? children : highlightReactChildren(children, searchQuery)} ), }; }, [searchQuery]); return ( {text} ); }); export function RichText({ text }: { text: string }) { return (
    ); } /** * A reply as it streams: released smoothly (useSmoothText), and parsed a block at a time so * only the block still growing is parsed again. History snapshots never fade in block by block. */ export function StreamingText({ text, streaming }: { text: string; streaming: boolean }) { const shown = useSmoothText(text, streaming); const blocks = useMemo(() => markdownBlocks(shown), [shown]); return (
    {blocks.map((block, index) => (
    {/* The last block may still be growing: its code is coloured once the reply moves past it. */}
    ))}
    ); } /** Click any `.message-image` to open it full-size in a centered lightbox. Keeps the download as a corner action rather than the default click. */ function ImageLightbox({ uri, alt, download, onError, }: { uri: string; alt: string; download?: string; onError?: () => void; }) { const [open, setOpen] = useState(false); return ( {alt} {alt} ); } function Picture({ block, sessionId, }: { block: Extract; sessionId: string; }) { const actions = useActions(); const [uri, setUri] = useState( block.data ? `data:${block.mimeType};base64,${block.data}` : block.uri && /^(data:image\/|https?:\/\/)/.test(block.uri) ? block.uri : undefined, ); const [error, setError] = useState(); const [attempt, setAttempt] = useState(0); const loadImage = actions.loadImage; useEffect(() => { let alive = true; setError(undefined); setUri( block.data ? `data:${block.mimeType};base64,${block.data}` : block.uri && /^(data:image\/|https?:\/\/)/.test(block.uri) ? block.uri : undefined, ); if (block.uri?.startsWith("linkshell-event:")) void loadImage(sessionId, block.uri).then( (value) => { if (alive) setUri(value); }, () => { if (alive) setError("图片加载失败"); }, ); return () => { alive = false; }; }, [loadImage, block.uri, block.data, block.mimeType, sessionId, attempt]); return uri ? ( { setUri(undefined); setError("图片加载失败"); }} /> ) : ( {error ?? "图片加载中…"} {error && ( )} ); } function Asset({ block, sessionId, download, }: { block: { data?: string; uri?: string; mimeType: string }; sessionId: string; download?: string; }) { const { loadImage } = useActions(); const [uri, setUri] = useState( block.data ? `data:${block.mimeType};base64,${block.data}` : block.uri?.startsWith("linkshell-event:") ? undefined : block.uri, ); const [error, setError] = useState(); useEffect(() => { let alive = true; setError(undefined); setUri( block.data ? `data:${block.mimeType};base64,${block.data}` : block.uri?.startsWith("linkshell-event:") ? undefined : block.uri, ); if (block.uri?.startsWith("linkshell-event:")) void loadImage(sessionId, block.uri).then( (value) => { if (alive) setUri(value); }, () => { if (alive) setError("附件加载失败"); }, ); return () => { alive = false; }; }, [block.data, block.uri, block.mimeType, loadImage, sessionId]); if (!uri) return {error ?? "附件加载中…"}; if (!/^(data:|https?:\/\/)/.test(uri)) return 附件地址无效; return (
    {block.mimeType.startsWith("audio/") ? (
    ); } export function Blocks({ blocks, sessionId, onFile, }: { blocks: ContentBlock[]; sessionId: string; onFile: (path: string, line?: number) => void; }) { return ( <> {blocks.map((block, index) => block.type === "text" ? ( ) : block.type === "image" ? ( ) : block.type === "audio" ? ( ) : block.type === "resource" ? (
    {block.resource.uri} · {block.resource.mimeType ?? "附件"} {block.resource.text !== undefined ? ( <>
    {block.resource.text}
    ) : ( )}
    ) : /^https?:\/\//.test(block.uri) ? ( {block.name} ) : ( ), )} ); } /** A change's lines, whatever form the agent reported it in (before and after, or a patch). */ export function changeLines(change: Extract): DiffLine[] { return change.type === "diff" ? diffLines(change.oldText ?? "", change.newText) : parsePatch(change.diff); } export interface SplitDiffRow { left?: DiffLine; right?: DiffLine; } /** Pairs contiguous deletion/addition runs side-by-side while aligning unchanged context lines. */ export function pairSplitLines(lines: DiffLine[]): SplitDiffRow[] { const rows: SplitDiffRow[] = []; let cursor = 0; while (cursor < lines.length) { const current = lines[cursor]!; if (current.kind === "same") { rows.push({ left: current, right: current }); cursor++; continue; } const dels: DiffLine[] = []; while (cursor < lines.length && lines[cursor]!.kind === "del") { dels.push(lines[cursor]!); cursor++; } const adds: DiffLine[] = []; while (cursor < lines.length && lines[cursor]!.kind === "add") { adds.push(lines[cursor]!); cursor++; } const count = Math.max(dels.length, adds.length); for (let i = 0; i < count; i++) { rows.push({ left: dels[i], right: adds[i] }); } } return rows; } /** A file's change as a unified or side-by-side diff: numbered lines, what went and what came tinted, the unchanged stretches between folded to a line. */ export function DiffView({ lines, path, viewMode = "unified", comments, activeLine, onSelectLine, renderLineEditor, }: { lines: DiffLine[]; path?: string; viewMode?: "unified" | "split"; comments?: Readonly>; activeLine?: number | null; onSelectLine?: (lineIndex: number, line: DiffLine) => void; renderLineEditor?: (lineIndex: number, line: DiffLine) => ReactNode; }) { const parts = useMemo(() => hunks(lines), [lines]); // Each side is highlighted as one text, so a line inside a string or comment that began // earlier is coloured as it is in the file; each line then takes its tokens from its side. const language = path ? grammarForPath(path) : undefined; const sides = useMemo(() => { const before: string[] = [], after: string[] = []; // Where each line sits in its side's text: removed lines in the old, the rest in the new. const at = lines.map((line) => { if (line.kind === "del") return before.push(line.text) - 1; if (line.kind === "same") before.push(line.text); return after.push(line.text) - 1; }); return { before: before.join("\n"), after: after.join("\n"), at }; }, [lines]); const oldTokens = useHighlight(sides.before, language); const newTokens = useHighlight(sides.after, language); const index = useMemo(() => new Map(lines.map((line, at) => [line, at])), [lines]); const tokensOf = (line: DiffLine) => { const tokens = line.kind === "del" ? oldTokens : newTokens; return tokens?.[sides.at[index.get(line)!]!]; }; const interactive = Boolean(onSelectLine || comments || activeLine !== undefined); if (viewMode === "split") { return (
    {parts.map((part, partIndex) => { const splitRows = pairSplitLines(part.lines); return ( {part.skipped > 0 &&
    {part.skipped} 行未改动
    } {splitRows.map((pair, rowAt) => { const leftIdx = pair.left ? (index.get(pair.left) ?? -1) : -1; const rightIdx = pair.right ? (index.get(pair.right) ?? -1) : -1; const sameLine = pair.left && pair.left === pair.right; const leftComment = leftIdx >= 0 ? comments?.[leftIdx] : undefined; const rightComment = !sameLine && rightIdx >= 0 ? comments?.[rightIdx] : undefined; const leftEditing = leftIdx >= 0 && activeLine === leftIdx && Boolean(renderLineEditor); const rightEditing = !sameLine && rightIdx >= 0 && activeLine === rightIdx && Boolean(renderLineEditor); return (
    = 0 ? () => onSelectLine(leftIdx, pair.left!) : undefined } > {pair.left?.old ?? ""} {pair.left?.kind === "del" ? "−" : ""} {pair.left?.text ? : " "}
    = 0 ? () => onSelectLine(rightIdx, pair.right!) : undefined } > {pair.right?.new ?? ""} {pair.right?.kind === "add" ? "+" : ""} {pair.right?.text ? : " "}
    {leftComment && !leftEditing && pair.left && (
    onSelectLine(leftIdx, pair.left!) : undefined} > {leftComment}
    )} {rightComment && !rightEditing && pair.right && (
    onSelectLine(rightIdx, pair.right!) : undefined} > {rightComment}
    )} {leftEditing && pair.left && (
    {renderLineEditor?.(leftIdx, pair.left)}
    )} {rightEditing && pair.right && (
    {renderLineEditor?.(rightIdx, pair.right)}
    )}
    ); })}
    ); })} {!parts.length &&
    没有内容变化
    }
    ); } return (
    {parts.map((part, partIndex) => ( {part.skipped > 0 &&
    {part.skipped} 行未改动
    } {part.lines.map((line, at) => { if (!interactive) { return (
    {line.old ?? ""} {line.new ?? ""} {line.kind === "add" ? "+" : line.kind === "del" ? "−" : ""} {line.text ? : " "}
    ); } const fullIndex = index.get(line) ?? at; const comment = comments?.[fullIndex]; const editing = activeLine === fullIndex && Boolean(renderLineEditor); return (
    onSelectLine(fullIndex, line) : undefined} > {line.old ?? ""} {line.new ?? ""} {line.kind === "add" ? "+" : line.kind === "del" ? "−" : ""} {line.text ? : " "}
    {comment && !editing && (
    onSelectLine(fullIndex, line) : undefined} > {comment}
    )} {editing && (
    {renderLineEditor?.(fullIndex, line)}
    )}
    ); })}
    ))} {!parts.length &&
    没有内容变化
    }
    ); } function DiffCode({ text, tokens }: { text: string; tokens?: HighlightToken[] }) { // Tokens that don't spell the line (a grammar that skipped a pattern) would show the wrong text. if (!tokens || tokens.map((token) => token.content).join("") !== text) return text; return tokens.map((token, at) => (token.color ? {token.content} : token.content)); } export function Diff({ change, }: { change: Extract; }) { // Inside the session's own directory the path reads from the project root; the full one is on hover. const cwd = useContext(TimelineNavigation)?.cwd; const shown = (path: string) => cwd && path.startsWith(`${cwd.replace(/\/$/, "")}/`) ? path.slice(cwd.replace(/\/$/, "").length + 1) : path; const lines = useMemo(() => changeLines(change), [change]); const stat = diffStat(lines); const title = change.type === "patch" && change.movePath ? `${change.path} → ${change.movePath}` : change.path; return (
    {shown(change.path)} {change.type === "patch" && change.movePath ? ` → ${shown(change.movePath)}` : ""}
    ); } /** A user message, with a reply to async questions shown as each question and its answer. */ function UserBlocks({ blocks, sessionId, onFile, }: { blocks: ContentBlock[]; sessionId: string; onFile: (path: string, line?: number) => void; }) { // The words, not the envelope around them (reminders, Codex Desktop's file and browser context): // what came with them shows as chips above the bubble, pictures and files below the words. const view = userMessageView(blocks); const replies = questionReplies(view.text); if (replies) return ( <> {replies.map((reply, index) => (
    {reply.question}

    {reply.answer}

    ))} ); const attached = blocks.filter((block) => block.type !== "text"); return ( <> {view.text && } {attached.length > 0 && } ); } /** Past 20 lines (or a wall of text without breaks) a message folds. */ function longMessage(text: string): boolean { return text.length > 2400 || text.split("\n").length > 20; } const CONTEXT_ICONS: Record = { file: FileText, image: ImageIcon, pasted: ClipboardPaste, selection: TextSelect, comments: MessageSquareText, checks: CircleAlert, annotations: Highlighter, browser: Globe, review: SearchCheck, "pull-request": GitPullRequest, merge: GitMerge, history: History, other: Paperclip, }; /** What a client attached to the message (files, a selection, the browser it had open). */ function UserContextChips({ context }: { context: UserContext[] }) { return (
    {context.map((entry, index) => { const Icon = CONTEXT_ICONS[entry.kind]; return ( {entry.label} ); })}
    ); } interface EntryProps { sessionId: string; agent: string; onFile: (path: string, line?: number) => void; onFork?: (id: string) => void; onTerminal?: (id: string) => void; showAsyncQuestions: boolean; /** The whole conversation's answered async questions (Codex Desktop), for dedup. */ answered: ReadonlyMap; /** The conversation's last item while its turn runs: a retry on it is still being tried. */ live?: boolean; /** Optional DOM anchor id (`data-item-id`) used by Conversation search & outline jump. */ anchorId?: string; /** Historical item strictly above the bottom 10 items (receives `content-visibility: auto` unless `⌘F` is open). */ historical?: boolean; } /** * One timeline item. Memoized: a conversation re-renders only the item that * changed while a reply streams, not every message above it. */ export const TimelineEntry = memo(function TimelineEntry({ item, sessionId, agent, onFile, onFork, onTerminal, showAsyncQuestions, answered, live = false, anchorId, historical = false, }: EntryProps & { item: TimelineItem }) { const actions = useActions(); const navigation = useContext(TimelineNavigation); const searchQuery = useContext(TimelineSearch); // A long message folds to its first lines past 20. const [unfolded, setUnfolded] = useState(false); const job = useJob(); const online = useSessionOnline(); const historicalAttr = historical ? "" : undefined; const entry = (() => { if (item.kind === "turn-end" || item.kind === "driver") return (

    {item.kind === "driver" ? `会话控制:${item.driver === "desktop" ? "电脑端" : item.driver === "remote" ? "远程端" : "空闲"}` : item.stopReason === "cancelled" ? "本轮已停止" : item.stopReason === "error" ? "本轮执行失败" : item.stopReason === "max_tokens" ? "达到输出上限,回复被截断" : item.stopReason === "max_turn_requests" ? "达到本轮请求次数上限" : item.stopReason === "refusal" ? "Agent 拒绝了这个请求" : item.stopReason === "unknown" ? "本轮已结束,Agent 未提供明确原因" : "本轮结束"}

    ); if (item.kind === "user" && item.agentMessages?.length) return (
    {item.agentMessages.map((message, index) => { // Another session's message names it by the app's id: its title now, and a way there. const sender = message.sessionId ? navigation?.findSession?.(message.sessionId) : undefined; return ( {message.summary ? <> · : ""} {sender && ( )} } > ); })}
    ); const said = item.kind === "user" ? userMessageView(item.blocks) : undefined; if (said?.event) return (

    {userEventLabel(said.event)}

    ); if (said?.shell || said?.output !== undefined) { // A command run from the prompt (`!`), or what a local slash command printed: the // person's, so on their side, in the terminal's type. const output = said.shell ? [said.shell.stdout, said.shell.stderr].filter(Boolean).join("\n") : said.output; return (
    {said.shell?.command && ( ! )} {output &&
    }
    ); } if (item.kind === "user") { const searchHitsUser = Boolean(searchQuery && said && said.text.toLowerCase().includes(searchQuery)); return (
    {said && said.context.length > 0 && } {/* The words in their own box, so the desktop can hang the time and actions under the bubble instead of inside it. */}
    {said && longMessage(said.text) && ( )} {item.failed && (
    发送失败,草稿仍在
    )}
    {item.blocks.some( (block) => block.type === "text" && block.text, ) && ( block.type === "text") .map((block) => block.text) .join("\n\n")} /> )} {onFork && !item.pending && !item.failed && ( )}
    ); } if (item.kind === "agent") return (
    {item.senderSessionId || item.recipientSessionId ? ( {item.senderSessionId ?? "Agent"} →{" "} {item.recipientSessionId ?? "当前会话"} ) : null} {item.streaming && (
    {online ? "正在回复…" : "等待会话恢复…"}
    )} {showAsyncQuestions && item.questions && !item.streaming && ( )} {item.attachments && ( )} {!item.streaming && (
    {item.text && } {onFork && ( )}
    )}
    ); if (item.kind === "thought") return ( {item.streaming ? "思考中…" : item.endedTs && item.endedTs - item.ts >= 1000 ? `思考了 ${formatElapsed(item.endedTs - item.ts)}` : "思考过程"}} > ); if (item.kind === "error") return ; if (item.kind === "notice") { const reconnect = reconnectOf(item.title, item.detail); if (reconnect) return (

    {live && }

    ); return ( {item.detail ? (
    ) : null}
    ); } if (item.kind === "plan") return (
    {item.markdown ? : null} {item.path ? ( ) : null}
      {item.entries.map((entry, index) => (
    • {/* Done is a filled check, under way a ring, still to do a dashed ring. */} {entry.status === "completed" ? : null}
    • ))}
    ); if (item.kind === "permission-result") return ( `${a.question} ${a.answer}`) ?? [])].join(" ")} summary={ {item.asked ? "已回答" : item.allowed ? "已允许" : "已拒绝"} ·{" "} } > {item.optionName &&

    } {item.answers?.map((answer, index) => (

    ))}
    ); return ( ); })(); return job.error ? ( <> {entry} ) : ( entry ); }); type ToolItem = Extract; /** An error: what kind of failure, what to do, the agent's words one click away. */ function ErrorCard({ item, anchorId, historical }: { item: Extract; anchorId?: string; historical?: boolean }) { const shown = presentError(item); return ( {(shown.hint || (shown.kind && shown.detail)) ? ( {shown.hint &&

    } {shown.kind && shown.detail && ( 查看详情}>
    )}
    ) : null}
    ); } function ToolState({ item }: { item: ToolItem }) { const outcome = toolOutcome(item); return ( {item.detail?.type === "subagent" && item.detail.state === "unknown" ? ( ) : outcome === "declined" || outcome === "stopped" ? ( ) : item.status === "completed" ? ( ) : item.status === "failed" ? ( ) : item.status === "in_progress" ? ( ) : ( )} ); } const SUBAGENT_STATES: Record = { pending: "待开始", running: "运行中", paused: "等待操作", completed: null, failed: "失败", stopped: "已停止", unknown: "状态未确认", }; /** * The Claude app's end-of-turn box: its recap, the question it leaves, and its buttons. While it is * the open box (the last, nobody has written since), a reply button sends its words as the next * message, as the app's does; the app's own actions (commit, create a PR…) are done in the app. */ function WrapUpCard({ item, sessionId, anchorId, historical }: { item: ToolItem; sessionId: string; anchorId?: string; historical?: boolean }) { const box = wrapUpOf(item); const open = useContext(OpenWrapUp) === item.id; const actions = useActions(); const online = useSessionOnline(); const job = useJob(); const [sent, setSent] = useState(); return (
    已收尾 {box.recap && } {box.ask &&

    } {box.actions.length > 0 && (
    {box.actions.map((action, index) => open && action.message !== undefined ? ( ) : ( {action.label} ), )}
    )}
    ); } const SESSION_STATES = { starting: "正在启动", started: "已启动", proposed: "已提议,等你开始", failed: "启动失败" } as const; /** A session the Claude app started from this one: opens it when this computer has it. */ function SessionCard({ item, anchorId, historical }: { item: ToolItem; anchorId?: string; historical?: boolean }) { const navigation = useContext(TimelineNavigation); const started = startedSession(item); const target = started.appId ? navigation?.findSession?.(started.appId) : undefined; const body = ( <> {started.state === "starting" ? : } {SESSION_STATES[started.state]} ); return target ? ( ) : (
    {body}
    ); } /** A command as it ran: the command, what it printed, and how it ended. */ function CommandBody({ item, command }: { item: ToolItem; command: string }) { const output = toolOutput(item); const ended = exitNote(item); return (
    $ 
    {output && ( <>
    )} {ended && {ended}}
    ); } /** * One tool call, worded as the verb and what it acted on ("已读取 foo.ts", "正在运行 npm test"); its file * opens from the row. Opens to what it did: a command's run, a diff, a search's matches. Reading a * file and listing a directory have nothing more to show and stay one line. */ function ToolRecord({ item, sessionId, agent, onFile, onTerminal, anchorId, historical, }: { item: ToolItem; sessionId: string; agent: string; onFile: (path: string, line?: number) => void; onTerminal?: (id: string) => void; anchorId?: string; historical?: boolean; }) { const { link } = useConnection(); const navigation = useContext(TimelineNavigation); const searchQuery = useContext(TimelineSearch); const job = useJob(); const online = useSessionOnline(); const label = toolLabel(item); const action = label.action; const historicalAttr = historical ? "" : undefined; if (action === "compaction") return (

    {item.status === "in_progress" && }

    ); if (action === "chapter") return

    ; if (action === "wrap_up") return ; if (action === "start_session") return ; const parts = toolLabelParts(label); const command = action === "command" ? toolCommand(item) : undefined; const plan = action === "plan" ? proposedPlan(item) : undefined; const questions = action === "question" ? askedQuestions(item) : []; const exploring = action === "read" || action === "list" || action === "search" || action === "find"; const changed = item.content.filter((entry) => entry.type === "diff" || entry.type === "patch"); const stat = changed.reduce( (sum, change) => { const lines = diffStat(changeLines(change)); return { added: sum.added + lines.added, removed: sum.removed + lines.removed }; }, { added: 0, removed: 0 }, ); const cancel = item.detail?.type === "subagent" && item.detail.canCancel && item.detail.nativeSessionId && ["running", "paused", "pending"].includes(item.detail.state ?? "") ? item.detail.nativeSessionId : undefined; // A search's matches are worth opening; a file read or a directory listed are not. const hasBody = isQuietTool(item) ? false : exploring ? !!toolOutput(item) : !!command || !!plan || questions.length > 0 || !!cancel || !!item.output || item.content.length > 0 || !!item.locations?.length || item.rawInput !== undefined || item.rawOutput !== undefined || !!item.sub; const meta = item.detail?.type === "subagent" && item.detail.state ? SUBAGENT_STATES[item.detail.state] : null; const agentFailed = item.detail?.type === "subagent" && label.outcome === "failed"; const summary = ( <> {parts.subject && (label.style === "file" && label.path ? ( ) : label.style === "code" ? ( ) : ( ))} {/* Keep the outcome visible when the command itself is truncated. */} {parts.suffix && {parts.suffix}} {label.note && {label.note}} {meta && {meta}} {item.detail?.type === "mcp" && item.detail.app && navigation?.openApp && ( // The call's page: open it here without unfolding the row. )} {hasBody && } ); if (!hasBody) return (
    {summary}
    ); const rawInputText = item.rawInput === undefined ? undefined : typeof item.rawInput === "string" ? item.rawInput : JSON.stringify(item.rawInput, null, 2); const rawOutputText = item.rawOutput === undefined ? undefined : typeof item.rawOutput === "string" ? item.rawOutput : JSON.stringify(item.rawOutput, null, 2); const bodySearchText = searchQuery ? timelineItemSearchText(item) : undefined; return ( {summary}} > {cancel ? ( ) : null} {job.error && } {command ? ( ) : plan ? ( ) : questions.length > 0 ? ( <>
      {questions.map((question, index) => (
    • {question.header && {question.header}{question.multiple ? "(可多选)" : ""}}

      {question.options.length > 0 &&

      }
    • ))}
    {toolOutput(item) &&
    } ) : exploring ? (
    ) : ( <> {item.output && ( <>
                    
                  
    )} {item.content.map((content, index) => content.type === "content" ? ( ) : content.type === "terminal" ? ( Agent 终端输出{item.output ? "见上方" : "正在等待输出"} ) : ( ), )} {item.locations?.map((location, index) => ( ))} {rawInputText !== undefined && ( 工具参数}>
    )} {rawOutputText !== undefined && ( 原始结果}>
    )} )} {item.sub && }
    ); } /** Whole-timeline map of async questions already answered by a later message. */ export function answeredMap(items: TimelineItem[]): Map { return new Map( items.flatMap((item) => item.kind === "user" && !item.failed && !item.pending ? item.blocks.flatMap((block) => block.type === "text" ? answeredQuestions(block.text) : [], ) : [], ), ); } export function Timeline({ items, sessionId, agent, onFile, onFork, onTerminal, showAsyncQuestions = true, searchOpen = false, searchQuery = "", nested = false, }: { items: TimelineItem[]; sessionId: string; agent: string; onFile: (path: string, line?: number) => void; onFork?: (id: string) => void; onTerminal?: (id: string) => void; showAsyncQuestions?: boolean; searchOpen?: boolean; searchQuery?: string; nested?: boolean; }) { const inheritedSearch = useContext(TimelineSearch); const activeQuery = nested ? inheritedSearch : searchOpen ? searchQuery.trim().toLowerCase() : ""; // Which folded step runs the reader has opened in place. const [openSteps, setOpenSteps] = useState>(new Set()); const toggleSteps = (key: string) => setOpenSteps((previous) => { const next = new Set(previous); if (next.has(key)) next.delete(key); else next.add(key); return next; }); const effectiveOpenSteps = useMemo(() => { if (!activeQuery) return openSteps; const base = foldStepRuns(items, openSteps); let expanded: Set | undefined; for (const row of base) { if ( row.type === "steps" && !openSteps.has(row.key) && row.steps.some((step) => timelineItemSearchText(step).toLowerCase().includes(activeQuery)) ) { expanded ??= new Set(openSteps); expanded.add(row.key); } } return expanded ?? openSteps; }, [items, openSteps, activeQuery]); // Finished runs of tool/thought steps fold into one summary line, Desktop-style. const rows = foldStepRuns(items, effectiveOpenSteps); // The agent's async questions (Codex Desktop) are answered by a message quoting them, here or on the computer. const answered = answeredMap(items); const hideDeferred = nested || searchOpen || Boolean(activeQuery); const list = (
    {rows.map((row, index) => { const historical = !hideDeferred && index < rows.length - 10; return row.type === "steps" ? ( toggleSteps(row.key)} /> ) : ( ); })}
    ); return nested ? list : {list}; }