// Timeline item components (§8.6): user bubble, body, thinking, tool group, plan, todo, permission, question, error, turn end. import { useEffect, useMemo, useRef, useState } from "react"; import type { DisplayItem, ToolStep } from "../timeline/reducer"; import { Markdown, copyText } from "./Markdown"; import { Reveal } from "../timeline/reveal"; import { Icon } from "./Icons"; import { ws } from "../main"; import { getToken } from "../api/token"; import { normalizeHunks } from "../timeline/diffHunks"; import { fmtDur, fmtTokens, fmtCost } from "../util/format"; import { useUi } from "../stores/ui"; import { localizeDaemonMessage, t, tf } from "../i18n/index.js"; const token = () => getToken(); export function attachmentUrl(id: string): string { return `/attachments/${id}?t=${token()}`; } // ---------- user message ---------- export function UserItem({ it, onRetry }: { it: Extract; onRetry?: (text: string) => void }) { return (
{it.attachments?.map((a) => ( {a.name} ))} {it.text}
{onRetry && }
{it.steered &&
{t("timeline.steer")}
}
); } // ---------- body (streaming reveal) ---------- export function AssistantItem({ it }: { it: Extract }) { const [shown, setShown] = useState(it.streaming ? "" : it.text); const reveal = useRef(null); useEffect(() => { if (!reveal.current) reveal.current = new Reveal(setShown); reveal.current.push(it.text); if (!it.streaming) reveal.current.flush(); }, [it.text, it.streaming]); useEffect(() => () => reveal.current?.stop(), []); return ; } // ---------- thinking ---------- export function ReasoningItem({ it }: { it: Extract }) { const [open, setOpen] = useState(false); const secs = Math.max(1, Math.round(it.text.length / 40)); return (
{open &&
{it.text}
}
); } // ---------- tool group ---------- function toolKind(k: string): string { const key = `timeline.tool.${k}` as const; const v = t(key); return v.startsWith("timeline.tool.") ? t("timeline.tool.other") : v; } export function ToolGroupItem({ it }: { it: Extract }) { // Failed steps or steps with a diff are worth seeing directly → auto-expand (never reopened after the user collapses them) const hasFail = it.steps.some((s) => s.status === "failed"); const hasDiff = it.steps.some((s) => { const d = s.detail as { hunks?: unknown[]; diff?: { hunks?: unknown[] } } | undefined; const h = d?.hunks ?? d?.diff?.hunks; return Array.isArray(h) && h.length > 0; }); const [open, setOpen] = useState(hasFail || hasDiff); const userToggled = useRef(false); useEffect(() => { if (!userToggled.current && (hasFail || hasDiff)) setOpen(true); }, [hasFail, hasDiff]); const summary = useMemo(() => { const counts = new Map(); for (const s of it.steps) counts.set(s.kind, (counts.get(s.kind) ?? 0) + 1); const parts = [...counts.entries()].map(([k, n]) => `${toolKind(k)} ${n}`); return tf("timeline.toolSummary", { n: it.steps.length, parts: parts.join(" · ") }); }, [it.steps]); const runningStep = it.steps.find((s) => s.status === "running"); return (
{open && (
{it.steps.map((s) => )}
)}
); } function ToolStepRow({ s }: { s: ToolStep }) { // Failed steps and steps with a diff expand their details by default (the diff is what the user wants to see) const detail = s.detail as { hunks?: unknown[] } | undefined; const [open, setOpen] = useState(s.status === "failed" || (Array.isArray(detail?.hunks) && detail.hunks.length > 0)); const icon = s.status === "running" ? "…" : s.status === "ok" ? "✓" : "✗"; const cls = s.status === "running" ? "run" : s.status === "ok" ? "ok" : "fail"; const hasDetail = s.output || s.detail; return (
{open && }
); } function ToolDetail({ s }: { s: ToolStep }) { const [full, setFull] = useState(false); // editDetail outputs {path, hunks, added, removed}; the {diff:{hunks}} shape is also accepted const detail = s.detail as { hunks?: unknown; diff?: { path?: string; hunks?: unknown }; path?: string } | undefined; const rawHunks = detail?.hunks ?? detail?.diff?.hunks; if (rawHunks) { return ; } if (s.output != null) { const lines = s.output.split("\n"); const tail = lines.length > 50 && !full; const text = tail ? lines.slice(-50).join("\n") : s.output; return (
{tail && }
{text}
); } if (s.input != null) { return
{JSON.stringify(s.input, null, 2).slice(0, 4000)}
; } return null; } // ---------- line-level diff (unified view) ---------- export type DiffHunk = { head?: string; lines: { t: "+" | "-" | " "; text: string }[] }; export function DiffView({ hunks, path, max = 3000 }: { hunks: DiffHunk[]; path?: string; max?: number }) { let shown = 0; let clipped = false; return (
{path &&
{path}
}
        {hunks.map((h, hi) => (
          
            {h.head ?? "@@"}
            {h.lines.map((l, li) => {
              shown++;
              if (shown > max) { clipped = true; return null; }
              return {l.t} {l.text}{"\n"};
            })}
          
        ))}
      
{clipped &&
{tf("timeline.diffClip", { n: max })}
}
); } // ---------- plan ---------- export function PlanItem({ it }: { it: Extract }) { return (
); } // ---------- todo ---------- export function TodoItem({ it }: { it: Extract }) { const [open, setOpen] = useState(false); const done = it.items.filter((i) => i.status === "done" || i.status === "completed").length; return (
{open && (
    {it.items.map((i, n) => (
  • {i.status === "done" || i.status === "completed" ? "☑" : i.status === "in_progress" ? "◐" : "☐"} {i.text}
  • ))}
)}
); } // ---------- permission ---------- export function PermissionItem({ it, threadId }: { it: Extract; threadId: string }) { const [busy, setBusy] = useState(false); const respond = (optionId: string) => { setBusy(true); void ws.call("thread.respond", { id: threadId, requestId: it.requestId, optionId }).catch(() => setBusy(false)); }; const detail = it.detail as { command?: string; path?: string; plan?: string; hunks?: DiffHunk[]; diff?: { path?: string; hunks?: DiffHunk[] } } | undefined; const hunks = detail?.hunks ?? detail?.diff?.hunks; const label = it.status === "resolved" ? it.choice === "allow_always" || it.choice === "acceptForSession" ? t("timeline.permAllowSession") : it.choice === "deny" || it.choice === "reject" || it.choice === "decline" ? t("timeline.permDenied") : it.choice === "implement" ? t("timeline.permAllowed") : t("timeline.permAllowed") : t("timeline.permCancelled"); return (
{it.title}
{detail?.command &&
{detail.command}
} {detail?.path &&
{detail.path}
} {hunks && } {it.status === "pending" ? (
{it.options.map((o) => ( ))}
) : (
{label}
)}
); } // ---------- question ---------- export function QuestionItem({ it, threadId }: { it: Extract; threadId: string }) { const [free, setFree] = useState>({}); const [sel, setSel] = useState>({}); const qs = it.questions as { id?: string; question?: string; header?: string; options?: { label: string; description?: string }[] }[]; // answers keys: the question id first (codex/mock schema), then the question text const qkey = (q: (typeof qs)[number], i: number) => q.id ?? q.question ?? q.header ?? `q${i}`; const submit = () => { const answers: Record = {}; qs.forEach((q, i) => { answers[qkey(q, i)] = free[i]?.trim() || sel[i] || ""; }); void ws.call("thread.respond", { id: threadId, requestId: it.requestId, answers }); }; return (
{qs.map((q, i) => (
{q.header ?? q.question}
{it.status === "pending" ? ( <>
{q.options?.map((o) => ( ))}
setFree((f) => ({ ...f, [i]: e.target.value }))} /> ) : (
{it.answers ? tf("timeline.submitted", { ans: Object.values(it.answers).join("、") }) : t("timeline.permCancelled")}
)}
))} {it.status === "pending" && }
); } // ---------- error / turn end ---------- export function TurnEndItem({ it, onRetry }: { it: Extract; onRetry?: () => void }) { const ui = useUi(); const [showErr, setShowErr] = useState(false); if (it.status === "failed") { return (
{tf("timeline.turnError", { err: localizeDaemonMessage(it.error ?? t("timeline.unknownError")) })}
{onRetry && } {it.error && it.error.length > 60 && ( )}
{showErr &&
{localizeDaemonMessage(it.error ?? "")}
}
); } const parts: string[] = []; if (it.durationMs != null) parts.push(fmtDur(it.durationMs)); if (it.usage) { const tk = it.usage.inputTokens + it.usage.outputTokens; if (tk) parts.push(`${fmtTokens(tk)} tokens`); if (it.usage.costUsd) parts.push(fmtCost(it.usage.costUsd)); } if (it.status === "interrupted") parts.push(t("timeline.interrupted")); return (
{parts.join(" · ") || it.status} {it.filesChanged != null && it.filesChanged > 0 && ( )}
); } // ---------- dispatch ---------- export function TimelineRow({ it, threadId, onEditResend, onRetryLast }: { it: DisplayItem; threadId: string; onEditResend?: (text: string) => void; onRetryLast?: () => void; }) { switch (it.kind) { case "user": return ; case "assistant": return
; case "reasoning": return ; case "toolgroup": return ; case "plan": return ; case "todo": return ; case "permission": return ; case "question": return ; case "notice": return
{localizeDaemonMessage(it.message)}
; case "turnend": return ; case "gone": return null; default: return null; } }