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