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
225function OutputTail({ lines, failed }: { lines: ReadonlyArray<string>; failed: boolean }) {
226 if (lines.length === 0) return null;
227 return (
228 <pre
229 className={cn(
230 "mb-1 ml-8 rounded-md border px-2.5 py-1.5 font-mono text-[11px] leading-relaxed whitespace-pre-wrap break-all select-text",
231 failed
232 ? "border-destructive/20 bg-error-surface text-destructive-foreground"
233 : "border-border bg-code text-muted-foreground",
234 )}
235 >
236 {lines.join("\n")}
237 </pre>
238 );
239}
240
241function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
242 return (
243 <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">
244 {snapshot.branch ? (
245 <>
246 <dt className="text-foreground/80">Branch</dt>
247 <dd className="truncate font-mono">{snapshot.branch}</dd>
248 </>
249 ) : null}
250 {snapshot.baseRef ? (
251 <>
252 <dt className="text-foreground/80">Base</dt>
253 <dd className="truncate font-mono">{snapshot.baseRef}</dd>
254 </>
255 ) : null}
256 {snapshot.worktreePath ? (
257 <>
258 <dt className="text-foreground/80">Path</dt>
259 <dd className="truncate font-mono">{snapshot.worktreePath}</dd>
260 </>
261 ) : null}
262 {snapshot.setupScript ? (
263 <>
264 <dt className="text-foreground/80">Setup</dt>
265 <dd className="truncate font-mono">{snapshot.setupScript.command}</dd>
266 </>
267 ) : null}
268 </dl>
269 );
270}
271
272export function WorktreeSetupCard({
273 snapshot,
274 onCancel,
275 onWorkLocally,
276 onOpenTerminal,
277 embedded = false,
278}: WorktreeSetupCardProps & {
279 /**
280 * The agent already started (async setup script), so the turn owns the
281 * "Working for" header and only the script's row sits among the worklog.
282 */
283 embedded?: boolean;
284}) {
285 const running = snapshot.phase === "running";
286 const nowMs = useNowWhile(running);
287 const [detailsOpen, setDetailsOpen] = useState(false);
288 const totalElapsed = (() => {
289 const start = Date.parse(snapshot.startedAt);
290 const end = snapshot.endedAt ? Date.parse(snapshot.endedAt) : nowMs;
291 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
292 })();
293 const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script");
294 const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending";
295 const stages = embedded
296 ? snapshot.stages.filter((stage) => stage.id === "setup-script")
297 : snapshot.stages;
298
299 return (
300 <section aria-label="Worktree setup" data-worktree-setup-phase={snapshot.phase}>
301 {embedded ? null : <SetupHeaderRow snapshot={snapshot} totalElapsed={totalElapsed} />}
302 <div className={embedded ? undefined : "pt-1.5"}>
303 {stages.map((stage) => (
304 <div key={stage.id}>
305 <StageRow stage={stage} nowMs={nowMs} scriptName={snapshot.setupScript?.name ?? null} />
306 {stage.id === "setup-script" &&
307 (stage.status === "running" || stage.status === "failed") ? (
308 <OutputTail lines={stage.tail} failed={stage.status === "failed"} />
309 ) : null}
310 </div>
311 ))}
312 </div>
313
314 {snapshot.phase === "failed" && snapshot.error ? (
315 <p className="mt-1 ml-8 text-xs text-muted-foreground">{snapshot.error}</p>
316 ) : null}
317
318 {detailsOpen ? <SetupDetails snapshot={snapshot} /> : null}
319
320 {/* Indented so the first label lines up with the stage labels: the icon
321 column, minus the xs button's own horizontal padding. */}
322 <div className="mt-0.5 ml-[calc(--spacing(6)+2px-(--spacing(2)-1px))] flex flex-wrap items-center gap-0.5">
323 <Button
324 type="button"
325 size="xs"
326 variant="ghost-muted"
327 aria-expanded={detailsOpen}
328 onClick={() => setDetailsOpen((open) => !open)}
329 >
330 {detailsOpen ? <ChevronDownIcon aria-hidden /> : <ChevronRightIcon aria-hidden />}
331 Details
332 </Button>
333 {showTerminal ? (
334 <Button type="button" size="xs" variant="ghost-muted" onClick={onOpenTerminal}>
335 <TerminalIcon aria-hidden />
336 Open terminal
337 </Button>
338 ) : null}
339 {onWorkLocally ? (
340 <Button type="button" size="xs" variant="ghost-muted" onClick={onWorkLocally}>
341 <LaptopIcon aria-hidden />
342 Work locally
343 </Button>
344 ) : null}
345 {onCancel && running ? (
346 <Button type="button" size="xs" variant="ghost-muted" onClick={onCancel}>
347 <XIcon aria-hidden />
348 Cancel
349 </Button>
350 ) : null}
351 </div>
352 </section>
353 );
354}