Open History to see the last commit
1import {
2 worktreeSetupStageLabel,
3 type WorktreeSetupSnapshot,
4 type WorktreeSetupStage,
5} from "@t3tools/contracts";
6import { formatDuration } from "@t3tools/shared/orchestrationTiming";
7import {
8 CheckIcon,
9 ChevronDownIcon,
10 ChevronRightIcon,
11 CircleAlertIcon,
12 CircleIcon,
13 LaptopIcon,
14 MinusIcon,
15 TerminalIcon,
16 XIcon,
17} from "lucide-react";
18import { useEffect, useState, type ReactNode } from "react";
19
20import { Button } from "~/components/ui/button";
21import { Spinner } from "~/components/ui/spinner";
22import { MiddleTruncate } from "../ui/middle-truncate";
23import { observeVisibleAnimation } from "~/lib/visibleAnimation";
24import { cn } from "~/lib/utils";
25
26interface WorktreeSetupCardProps {
27 snapshot: WorktreeSetupSnapshot;
28 /** Interrupts the server-side bootstrap. Hidden once the setup has settled. */
29 onCancel: (() => void) | null;
30 /** Restarts the same message in the project checkout instead of a worktree. */
31 onWorkLocally: (() => void) | null;
32 /** Reveals the setup script terminal tab. Null when no script ran. */
33 onOpenTerminal: (() => void) | null;
34}
35
36function stageElapsedMs(stage: WorktreeSetupStage, nowMs: number): number | null {
37 if (!stage.startedAt) return null;
38 const start = Date.parse(stage.startedAt);
39 const end = stage.endedAt ? Date.parse(stage.endedAt) : nowMs;
40 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
41 return Math.max(0, end - start);
42}
43
44/**
45 * Ticks once a second while any stage runs so elapsed labels stay live
46 * without pushing a React commit through the timeline for every second.
47 */
48function useNowWhile(active: boolean): number {
49 const [nowMs, setNowMs] = useState(() => Date.now());
50 useEffect(() => {
51 if (!active) return;
52 const id = setInterval(() => setNowMs(Date.now()), 1_000);
53 return () => clearInterval(id);
54 }, [active]);
55 return nowMs;
56}
57
58function StageIcon({ status }: { status: WorktreeSetupStage["status"] }) {
59 const className = "size-4 shrink-0 stroke-[1.8]";
60 switch (status) {
61 case "done":
62 return <CheckIcon aria-hidden className={className} />;
63 case "running":
64 return <Spinner size="md" className="shrink-0" />;
65 case "failed":
66 return <XIcon aria-hidden className={className} />;
67 case "warning":
68 return <CircleAlertIcon aria-hidden className={className} />;
69 case "skipped":
70 return <MinusIcon aria-hidden className={className} />;
71 case "pending":
72 return <CircleIcon aria-hidden className={className} />;
73 }
74}
75
76function stageRowClassName(status: WorktreeSetupStage["status"]): string {
77 switch (status) {
78 case "failed":
79 return "text-destructive-foreground";
80 case "warning":
81 return "text-warning-foreground";
82 case "pending":
83 return "text-secondary-label opacity-40";
84 case "running":
85 case "skipped":
86 case "done":
87 return "text-secondary-label";
88 }
89}
90
91/** Same shimmer treatment as the live tool rows in the timeline. */
92function ShimmerOverlay({ children }: { children: ReactNode }) {
93 return (
94 <span
95 aria-hidden
96 className="live-activity-focus pointer-events-none absolute inset-y-0 select-none"
97 >
98 <span className="live-activity-focus-counter block">
99 <span className="live-activity-focus-aligned block text-foreground">{children}</span>
100 </span>
101 </span>
102 );
103}
104
105function headerLabel(snapshot: WorktreeSetupSnapshot): string {
106 switch (snapshot.phase) {
107 case "running":
108 return "Setting up worktree…";
109 case "done":
110 return snapshot.stages.some((stage) => stage.status === "failed")
111 ? "Worktree ready, setup script failed"
112 : "Worktree ready";
113 case "failed":
114 return "Worktree setup failed";
115 case "cancelled":
116 return "Worktree setup cancelled";
117 }
118}
119
120/**
121 * Occupies the same slot, with the same metrics, as the "Working for" header
122 * so the handoff to the agent's turn only swaps the text.
123 */
124function SetupHeaderRow({
125 snapshot,
126 totalElapsed,
127}: {
128 snapshot: WorktreeSetupSnapshot;
129 totalElapsed: number | null;
130}) {
131 const running = snapshot.phase === "running";
132 const failed = snapshot.phase === "failed";
133 const finishedWithFailedStage =
134 snapshot.phase === "done" && snapshot.stages.some((stage) => stage.status === "failed");
135 const text = headerLabel(snapshot);
136 const tone = failed
137 ? "text-destructive-foreground"
138 : finishedWithFailedStage
139 ? "text-warning-foreground"
140 : "text-muted-foreground";
141 return (
142 <div className="border-b border-border/60 pb-2 pt-1">
143 <div
144 className={cn(
145 "flex h-6 min-w-0 items-baseline gap-2 px-1 text-sm leading-relaxed tabular-nums",
146 tone,
147 )}
148 >
149 <span
150 ref={running ? observeVisibleAnimation : undefined}
151 className="relative min-w-0 shrink overflow-hidden whitespace-nowrap"
152 >
153 <span className="block truncate">{text}</span>
154 {running ? <ShimmerOverlay>{text}</ShimmerOverlay> : null}
155 </span>
156 {totalElapsed !== null ? (
157 <span className="ml-auto shrink-0 text-xs text-muted-foreground">
158 {formatDuration(totalElapsed)}
159 </span>
160 ) : null}
161 </div>
162 </div>
163 );
164}
165
166/** One stage, rendered like a live work entry row. */
167function StageRow({
168 stage,
169 nowMs,
170 scriptName,
171}: {
172 stage: WorktreeSetupStage;
173 nowMs: number;
174 scriptName: string | null;
175}) {
176 const elapsed = stageElapsedMs(stage, nowMs);
177 const label =
178 stage.id === "setup-script" && scriptName ? scriptName : worktreeSetupStageLabel(stage.id);
179 const running = stage.status === "running";
180 const trailing =
181 stage.status === "pending"
182 ? null
183 : stage.status === "skipped"
184 ? (stage.detail ?? "skipped")
185 : stage.id === "checkout" && running && stage.percent !== null
186 ? `${stage.percent}%`
187 : stage.detail;
188 return (
189 <div
190 ref={running ? observeVisibleAnimation : undefined}
191 className={cn(
192 "relative flex min-h-6 min-w-0 items-center gap-1.5 overflow-hidden rounded-md px-0.5 py-0.5 text-sm leading-relaxed",
193 stageRowClassName(stage.status),
194 )}
195 data-worktree-setup-stage={stage.id}
196 data-worktree-setup-status={stage.status}
197 >
198 <span className="flex size-6 shrink-0 items-center justify-center text-icon-muted">
199 <StageIcon status={stage.status} />
200 </span>
201 <span className="min-w-0 flex-1 truncate">{label}</span>
202 {trailing ? (
203 <span className="min-w-0 truncate text-xs text-muted-foreground tabular-nums">
204 {trailing}
205 </span>
206 ) : null}
207 {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (
208 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
209 {formatDuration(elapsed)}
210 </span>
211 ) : null}
212 {running ? (
213 <ShimmerOverlay>
214 <span className="flex min-h-6 items-center gap-1.5 px-0.5 py-0.5">
215 <span className="flex size-6 shrink-0 items-center justify-center">
216 <StageIcon status={stage.status} />
217 </span>
218 <span className="min-w-0 flex-1 truncate">{label}</span>
219 </span>
220 </ShimmerOverlay>
221 ) : null}
222 </div>
223 );
224}
225
226/** The server keeps this many trailing lines; the box is sized for exactly that. */
227const OUTPUT_TAIL_LINES = 4;
228const OUTPUT_TAIL_SLOTS = Array.from({ length: OUTPUT_TAIL_LINES }, (_, slot) => slot);
229
230/**
231 * Fixed-height window onto the script's last lines. Rows never wrap and the
232 * box never grows or shrinks, so streaming output cannot push the timeline
233 * around while the script runs.
234 */
235function OutputTail({ lines, failed }: { lines: ReadonlyArray<string>; failed: boolean }) {
236 const rows = OUTPUT_TAIL_SLOTS.map((slot) => ({
237 slot,
238 line: lines[lines.length - OUTPUT_TAIL_LINES + slot] ?? "",
239 }));
240 return (
241 <pre
242 className={cn(
243 "mb-1 ml-8 overflow-hidden rounded-md border px-2.5 py-1.5 font-mono text-[11px] leading-relaxed select-text",
244 failed
245 ? "border-destructive/20 bg-error-surface text-destructive-foreground"
246 : "border-border bg-code text-muted-foreground",
247 )}
248 >
249 {rows.map(({ slot, line }) => (
250 <div key={slot} className="truncate whitespace-pre">
251 {line.length === 0 ? "\u00a0" : line}
252 </div>
253 ))}
254 </pre>
255 );
256}
257
258function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
259 return (
260 <dl className="mt-1 mb-1.5 ml-8 grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs text-muted-foreground">
261 {snapshot.branch ? (
262 <>
263 <dt className="text-foreground/80">Branch</dt>
264 <dd className="min-w-0 font-mono">
265 <MiddleTruncate value={snapshot.branch} className="flex" />
266 </dd>
267 </>
268 ) : null}
269 {snapshot.baseRef ? (
270 <>
271 <dt className="text-foreground/80">Base</dt>
272 <dd className="min-w-0 font-mono">
273 <MiddleTruncate value={snapshot.baseRef} className="flex" />
274 </dd>
275 </>
276 ) : null}
277 {snapshot.worktreePath ? (
278 <>
279 <dt className="text-foreground/80">Path</dt>
280 <dd className="min-w-0 font-mono">
281 <MiddleTruncate value={snapshot.worktreePath} className="flex" />
282 </dd>
283 </>
284 ) : null}
285 {snapshot.setupScript ? (
286 <>
287 <dt className="text-foreground/80">Setup</dt>
288 <dd className="truncate font-mono">{snapshot.setupScript.command}</dd>
289 </>
290 ) : null}
291 </dl>
292 );
293}
294
295/**
296 * One-line summary of a settled setup under a live turn. A clean finish is
297 * removed from the timeline altogether, so this only renders the outcomes
298 * worth keeping: a failed script, a failed setup, or a cancelled one.
299 */
300function CollapsedSummaryRow({
301 snapshot,
302 totalElapsed,
303}: {
304 snapshot: WorktreeSetupSnapshot;
305 totalElapsed: number | null;
306}) {
307 const status: WorktreeSetupStage["status"] =
308 snapshot.phase === "failed" || snapshot.phase === "cancelled"
309 ? "failed"
310 : snapshot.stages.some((stage) => stage.id === "setup-script" && stage.status === "failed")
311 ? "failed"
312 : "done";
313 const label = headerLabel(snapshot);
314 return (
315 <div
316 className={cn(
317 "flex min-h-6 min-w-0 items-center gap-1.5 rounded-md px-0.5 py-0.5 text-sm leading-relaxed",
318 stageRowClassName(status),
319 )}
320 data-worktree-setup-stage="summary"
321 data-worktree-setup-status={status}
322 >
323 <span className="flex size-6 shrink-0 items-center justify-center text-icon-muted">
324 <StageIcon status={status} />
325 </span>
326 <span className="min-w-0 flex-1 truncate">{label}</span>
327 {totalElapsed !== null ? (
328 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
329 {formatDuration(totalElapsed)}
330 </span>
331 ) : null}
332 </div>
333 );
334}
335
336export function WorktreeSetupCard({
337 snapshot,
338 onCancel,
339 onWorkLocally,
340 onOpenTerminal,
341 embedded = false,
342}: WorktreeSetupCardProps & {
343 /**
344 * The agent's turn is live and owns the "Working for" header. The stage
345 * list stays exactly where it was so the handoff never moves anything; a
346 * failed script that outlives the handoff collapses to a single row.
347 */
348 embedded?: boolean;
349}) {
350 const running = snapshot.phase === "running";
351 const nowMs = useNowWhile(running);
352 const [detailsOpen, setDetailsOpen] = useState(false);
353 const totalElapsed = (() => {
354 const start = Date.parse(snapshot.startedAt);
355 const end = snapshot.endedAt ? Date.parse(snapshot.endedAt) : nowMs;
356 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
357 })();
358 const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script");
359 const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending";
360 const collapsed = embedded && !running;
361 // While running, the timeline's working row above the card carries the
362 // "Setting up worktree…" label (and keeps that slot when the agent takes
363 // over). The card only brings its own header for a settled outcome that
364 // has no working row to sit under.
365 const showHeader = !embedded && !running;
366 // The tail box is part of the script row's footprint while the script runs
367 // (and after it failed, so the last lines explain the failure). It mounts
368 // as soon as the script is running, empty lines and all, so the card takes
369 // its final height once instead of growing with each output line.
370 const showTail =
371 setupStage !== undefined && (setupStage.status === "running" || setupStage.status === "failed");
372
373 return (
374 <section aria-label="Worktree setup" data-worktree-setup-phase={snapshot.phase}>
375 {showHeader ? <SetupHeaderRow snapshot={snapshot} totalElapsed={totalElapsed} /> : null}
376 {collapsed ? (
377 <CollapsedSummaryRow snapshot={snapshot} totalElapsed={totalElapsed} />
378 ) : (
379 <div className={showHeader ? "pt-1.5" : undefined}>
380 {snapshot.stages.map((stage) => (
381 <div key={stage.id}>
382 <StageRow
383 stage={stage}
384 nowMs={nowMs}
385 scriptName={snapshot.setupScript?.name ?? null}
386 />
387 {stage.id === "setup-script" && showTail ? (
388 <OutputTail lines={stage.tail} failed={stage.status === "failed"} />
389 ) : null}
390 </div>
391 ))}
392 </div>
393 )}
394
395 {snapshot.phase === "failed" && snapshot.error ? (
396 <p className="mt-1 ml-8 text-xs text-muted-foreground">{snapshot.error}</p>
397 ) : null}
398
399 {detailsOpen ? <SetupDetails snapshot={snapshot} /> : null}
400
401 {/* Indented so the first label lines up with the stage labels: the icon
402 column, minus the xs button's own horizontal padding. */}
403 <div className="mt-0.5 ml-[calc(--spacing(6)+2px-(--spacing(2)-1px))] flex flex-wrap items-center gap-0.5">
404 <Button
405 type="button"
406 size="xs"
407 variant="ghost-muted"
408 aria-expanded={detailsOpen}
409 onClick={() => setDetailsOpen((open) => !open)}
410 >
411 {detailsOpen ? <ChevronDownIcon aria-hidden /> : <ChevronRightIcon aria-hidden />}
412 Details
413 </Button>
414 {showTerminal ? (
415 <Button type="button" size="xs" variant="ghost-muted" onClick={onOpenTerminal}>
416 <TerminalIcon aria-hidden />
417 Open terminal
418 </Button>
419 ) : null}
420 {onWorkLocally ? (
421 <Button type="button" size="xs" variant="ghost-muted" onClick={onWorkLocally}>
422 <LaptopIcon aria-hidden />
423 Work locally
424 </Button>
425 ) : null}
426 {onCancel && running ? (
427 <Button type="button" size="xs" variant="ghost-muted" onClick={onCancel}>
428 <XIcon aria-hidden />
429 Cancel
430 </Button>
431 ) : null}
432 </div>
433 </section>
434 );
435}