import { worktreeSetupStageLabel, type WorktreeSetupSnapshot, type WorktreeSetupStage, } from "@t3tools/contracts"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import { CheckIcon, CircleAlertIcon, CircleIcon, LaptopIcon, MinusIcon, TerminalIcon, XIcon, } from "lucide-react"; import { ChevronDown, ChevronRight } from "lucide"; import { useEffect, useState, type ReactNode } from "react"; import { Button } from "~/components/ui/button"; import { MorphIcon } from "~/components/MorphIcon"; import { Spinner } from "~/components/ui/spinner"; import { MiddleTruncate } from "../ui/middle-truncate"; import { observeVisibleAnimation } from "~/lib/visibleAnimation"; import { cn } from "~/lib/utils"; import { WorkLogRow } from "./WorkLog"; interface WorktreeSetupCardProps { snapshot: WorktreeSetupSnapshot; /** Interrupts the server-side bootstrap. Hidden once the setup has settled. */ onCancel: (() => void) | null; /** Restarts the same message in the project checkout instead of a worktree. */ onWorkLocally: (() => void) | null; /** Reveals the setup script terminal tab. Null when no script ran. */ onOpenTerminal: (() => void) | null; } function stageElapsedMs(stage: WorktreeSetupStage, nowMs: number): number | null { if (!stage.startedAt) return null; const start = Date.parse(stage.startedAt); const end = stage.endedAt ? Date.parse(stage.endedAt) : nowMs; if (!Number.isFinite(start) || !Number.isFinite(end)) return null; return Math.max(0, end - start); } /** * Ticks once a second while any stage runs so elapsed labels stay live * without pushing a React commit through the timeline for every second. */ function useNowWhile(active: boolean): number { const [nowMs, setNowMs] = useState(() => Date.now()); useEffect(() => { if (!active) return; const id = setInterval(() => setNowMs(Date.now()), 1_000); return () => clearInterval(id); }, [active]); return nowMs; } function StageIcon({ status }: { status: WorktreeSetupStage["status"] }) { const className = "size-4 shrink-0 stroke-2"; switch (status) { case "done": return ; case "running": return ; case "failed": return ; case "warning": return ; case "skipped": return ; case "pending": return ; } } function stageRowClassName(status: WorktreeSetupStage["status"]): string { switch (status) { case "failed": return "text-destructive-foreground"; case "warning": return "text-warning-foreground"; case "pending": return "text-secondary-label opacity-40"; case "running": case "skipped": case "done": return "text-secondary-label"; } } /** Same shimmer treatment as the live tool rows in the timeline. */ function ShimmerOverlay({ children }: { children: ReactNode }) { return ( {children} ); } function headerLabel(snapshot: WorktreeSetupSnapshot): string { switch (snapshot.phase) { case "running": return "Setting up worktree…"; case "done": return snapshot.stages.some((stage) => stage.status === "failed") ? "Worktree ready, setup script failed" : "Worktree ready"; case "failed": return "Worktree setup failed"; case "cancelled": return "Worktree setup cancelled"; } } /** * Occupies the same slot, with the same metrics, as the "Working for" header * so the handoff to the agent's turn only swaps the text. */ function SetupHeaderRow({ snapshot, totalElapsed, }: { snapshot: WorktreeSetupSnapshot; totalElapsed: number | null; }) { const running = snapshot.phase === "running"; const failed = snapshot.phase === "failed"; const finishedWithFailedStage = snapshot.phase === "done" && snapshot.stages.some((stage) => stage.status === "failed"); const text = headerLabel(snapshot); const tone = failed ? "text-destructive-foreground" : finishedWithFailedStage ? "text-warning-foreground" : "text-muted-foreground"; return (
{text} {running ? {text} : null} {totalElapsed !== null ? ( {formatDuration(totalElapsed)} ) : null}
); } /** One stage, rendered like a live work entry row. */ function StageRow({ stage, nowMs, scriptName, }: { stage: WorktreeSetupStage; nowMs: number; scriptName: string | null; }) { const elapsed = stageElapsedMs(stage, nowMs); const label = stage.id === "setup-script" && scriptName ? scriptName : worktreeSetupStageLabel(stage.id); const running = stage.status === "running"; const trailing = stage.status === "pending" ? null : stage.status === "skipped" ? (stage.detail ?? "skipped") : stage.id === "checkout" && running && stage.percent !== null ? `${stage.percent}%` : stage.detail; return ( } label={ {label} {running ? {label} : null} } trailing={ <> {trailing ? ( {trailing} ) : null} {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? ( {formatDuration(elapsed)} ) : null} } /> ); } /** The server keeps this many trailing lines; the box is sized for exactly that. */ const OUTPUT_TAIL_LINES = 4; const OUTPUT_TAIL_SLOTS = Array.from({ length: OUTPUT_TAIL_LINES }, (_, slot) => slot); /** * Fixed-height window onto the script's last lines. Rows never wrap and the * box never grows or shrinks, so streaming output cannot push the timeline * around while the script runs. */ function OutputTail({ lines, failed }: { lines: ReadonlyArray; failed: boolean }) { const rows = OUTPUT_TAIL_SLOTS.map((slot) => ({ slot, line: lines[lines.length - OUTPUT_TAIL_LINES + slot] ?? "", })); return (
      {rows.map(({ slot, line }) => (
        
{line.length === 0 ? "\u00a0" : line}
))}
); } function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) { return (
{snapshot.branch ? ( <>
Branch
) : null} {snapshot.baseRef ? ( <>
Base
) : null} {snapshot.worktreePath ? ( <>
Path
) : null} {snapshot.setupScript ? ( <>
Setup
{snapshot.setupScript.command}
) : null}
); } /** * One-line summary of a settled setup under a live turn. A clean finish is * removed from the timeline altogether, so this only renders the outcomes * worth keeping: a failed script, a failed setup, or a cancelled one. */ function CollapsedSummaryRow({ snapshot, totalElapsed, }: { snapshot: WorktreeSetupSnapshot; totalElapsed: number | null; }) { const status: WorktreeSetupStage["status"] = snapshot.phase === "failed" || snapshot.phase === "cancelled" ? "failed" : snapshot.stages.some((stage) => stage.id === "setup-script" && stage.status === "failed") ? "failed" : "done"; const label = headerLabel(snapshot); return ( } label={{label}} trailing={ totalElapsed !== null ? ( {formatDuration(totalElapsed)} ) : null } /> ); } export function WorktreeSetupCard({ snapshot, onCancel, onWorkLocally, onOpenTerminal, embedded = false, }: WorktreeSetupCardProps & { /** * The agent's turn is live and owns the "Working for" header. The stage * list stays exactly where it was so the handoff never moves anything; a * failed script that outlives the handoff collapses to a single row. */ embedded?: boolean; }) { const running = snapshot.phase === "running"; const nowMs = useNowWhile(running); const [detailsOpen, setDetailsOpen] = useState(false); const totalElapsed = (() => { const start = Date.parse(snapshot.startedAt); const end = snapshot.endedAt ? Date.parse(snapshot.endedAt) : nowMs; return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null; })(); const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script"); const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending"; const collapsed = embedded && !running; // While running, and after a clean finish until the agent's turn is live, // the timeline's working row above the card carries the label (and keeps // that slot when the agent takes over). The card only brings its own // header for a failed or cancelled setup that has no working row above it. const showHeader = !embedded && !running && snapshot.phase !== "done"; // The tail box is part of the script row's footprint while the script runs // (and after it failed, so the last lines explain the failure). It mounts // with the first output line at its full fixed height, so the card grows // once instead of with each line. A script that ends before printing // anything never flashes an empty box. const showTail = setupStage !== undefined && (setupStage.status === "failed" || (setupStage.status === "running" && setupStage.tail.length > 0)); return (
{showHeader ? : null} {collapsed ? ( ) : (
{snapshot.stages.map((stage) => (
{stage.id === "setup-script" && showTail ? ( ) : null}
))}
)} {snapshot.phase === "failed" && snapshot.error ? (

{snapshot.error}

) : null} {detailsOpen ? : null} {/* Indented so the first label lines up with the stage labels: the icon column, minus the xs button's own horizontal padding. */}
{showTerminal ? ( ) : null} {onWorkLocally ? ( ) : null} {onCancel && running ? ( ) : null}
); }