Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

WorktreeSetupCard.tsx

426 lines14.1 KB

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";
24import { WorkLogRow } from "./WorkLog";
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;
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);
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;
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 className={className} />;
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 }
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 }
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 );
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 }
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 );
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 <WorkLogRow
190 data-worktree-setup-stage={stage.id}
191 data-worktree-setup-status={stage.status}
192 icon={
193 <span className={cn("text-icon-muted", stage.status === "pending" && "opacity-40")}>
194 <StageIcon status={stage.status} />
195 </span>
196 }
197 label={
198 <span
199 ref={running ? observeVisibleAnimation : undefined}
200 className={cn("relative block truncate", stageRowClassName(stage.status))}
201 >
202 {label}
203 {running ? <ShimmerOverlay>{label}</ShimmerOverlay> : null}
204 </span>
205 }
206 trailing={
207 <>
208 {trailing ? (
209 <span className="min-w-0 truncate text-xs text-muted-foreground tabular-nums">
210 {trailing}
211 </span>
212 ) : null}
213 {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (
214 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
215 {formatDuration(elapsed)}
216 </span>
217 ) : null}
218 </>
219 }
220 />
221 );
223​
224/** The server keeps this many trailing lines; the box is sized for exactly that. */
225const OUTPUT_TAIL_LINES = 4;
226const OUTPUT_TAIL_SLOTS = Array.from({ length: OUTPUT_TAIL_LINES }, (_, slot) => slot);
227​
228/**
229 * Fixed-height window onto the script's last lines. Rows never wrap and the
230 * box never grows or shrinks, so streaming output cannot push the timeline
231 * around while the script runs.
232 */
233function OutputTail({ lines, failed }: { lines: ReadonlyArray<string>; failed: boolean }) {
234 const rows = OUTPUT_TAIL_SLOTS.map((slot) => ({
235 slot,
236 line: lines[lines.length - OUTPUT_TAIL_LINES + slot] ?? "",
237 }));
238 return (
239 <pre
240 className={cn(
241 "mb-1 ml-8 overflow-hidden rounded-md border px-2.5 py-1.5 font-mono text-[11px] leading-relaxed select-text",
242 failed
243 ? "border-destructive/20 bg-error-surface text-destructive-foreground"
244 : "border-border bg-code text-muted-foreground",
245 )}
246 >
247 {rows.map(({ slot, line }) => (
248 <div key={slot} className="truncate whitespace-pre">
249 {line.length === 0 ? "\u00a0" : line}
250 </div>
251 ))}
252 </pre>
253 );
255​
256function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
257 return (
258 <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">
259 {snapshot.branch ? (
260 <>
261 <dt className="text-foreground/80">Branch</dt>
262 <dd className="truncate font-mono">{snapshot.branch}</dd>
263 </>
264 ) : null}
265 {snapshot.baseRef ? (
266 <>
267 <dt className="text-foreground/80">Base</dt>
268 <dd className="truncate font-mono">{snapshot.baseRef}</dd>
269 </>
270 ) : null}
271 {snapshot.worktreePath ? (
272 <>
273 <dt className="text-foreground/80">Path</dt>
274 <dd className="truncate font-mono">{snapshot.worktreePath}</dd>
275 </>
276 ) : null}
277 {snapshot.setupScript ? (
278 <>
279 <dt className="text-foreground/80">Setup</dt>
280 <dd className="truncate font-mono">{snapshot.setupScript.command}</dd>
281 </>
282 ) : null}
283 </dl>
284 );
286​
287/**
288 * One-line summary of a settled setup under a live turn. A clean finish is
289 * removed from the timeline altogether, so this only renders the outcomes
290 * worth keeping: a failed script, a failed setup, or a cancelled one.
291 */
292function CollapsedSummaryRow({
293 snapshot,
294 totalElapsed,
295}: {
296 snapshot: WorktreeSetupSnapshot;
297 totalElapsed: number | null;
298}) {
299 const status: WorktreeSetupStage["status"] =
300 snapshot.phase === "failed" || snapshot.phase === "cancelled"
301 ? "failed"
302 : snapshot.stages.some((stage) => stage.id === "setup-script" && stage.status === "failed")
303 ? "failed"
304 : "done";
305 const label = headerLabel(snapshot);
306 return (
307 <WorkLogRow
308 data-worktree-setup-stage="summary"
309 data-worktree-setup-status={status}
310 icon={
311 <span className="text-icon-muted">
312 <StageIcon status={status} />
313 </span>
314 }
315 label={<span className={stageRowClassName(status)}>{label}</span>}
316 trailing={
317 totalElapsed !== null ? (
318 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
319 {formatDuration(totalElapsed)}
320 </span>
321 ) : null
322 }
323 />
324 );
326​
327export function WorktreeSetupCard({
328 snapshot,
329 onCancel,
330 onWorkLocally,
331 onOpenTerminal,
332 embedded = false,
333}: WorktreeSetupCardProps & {
334 /**
335 * The agent's turn is live and owns the "Working for" header. The stage
336 * list stays exactly where it was so the handoff never moves anything; a
337 * failed script that outlives the handoff collapses to a single row.
338 */
339 embedded?: boolean;
340}) {
341 const running = snapshot.phase === "running";
342 const nowMs = useNowWhile(running);
343 const [detailsOpen, setDetailsOpen] = useState(false);
344 const totalElapsed = (() => {
345 const start = Date.parse(snapshot.startedAt);
346 const end = snapshot.endedAt ? Date.parse(snapshot.endedAt) : nowMs;
347 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
348 })();
349 const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script");
350 const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending";
351 const collapsed = embedded && !running;
352 // While running, the timeline's working row above the card carries the
353 // "Setting up worktree…" label (and keeps that slot when the agent takes
354 // over). The card only brings its own header for a settled outcome that
355 // has no working row to sit under.
356 const showHeader = !embedded && !running;
357 // The tail box is part of the script row's footprint while the script runs
358 // (and after it failed, so the last lines explain the failure). It mounts
359 // as soon as the script is running, empty lines and all, so the card takes
360 // its final height once instead of growing with each output line.
361 const showTail =
362 setupStage !== undefined && (setupStage.status === "running" || setupStage.status === "failed");
363​
364 return (
365 <section aria-label="Worktree setup" data-worktree-setup-phase={snapshot.phase}>
366 {showHeader ? <SetupHeaderRow snapshot={snapshot} totalElapsed={totalElapsed} /> : null}
367 {collapsed ? (
368 <CollapsedSummaryRow snapshot={snapshot} totalElapsed={totalElapsed} />
369 ) : (
370 <div className={showHeader ? "pt-1.5" : undefined}>
371 {snapshot.stages.map((stage) => (
372 <div key={stage.id}>
373 <StageRow
374 stage={stage}
375 nowMs={nowMs}
376 scriptName={snapshot.setupScript?.name ?? null}
377 />
378 {stage.id === "setup-script" && showTail ? (
379 <OutputTail lines={stage.tail} failed={stage.status === "failed"} />
380 ) : null}
381 </div>
382 ))}
383 </div>
384 )}
385​
386 {snapshot.phase === "failed" && snapshot.error ? (
387 <p className="mt-1 ml-8 text-xs text-muted-foreground">{snapshot.error}</p>
388 ) : null}
389​
390 {detailsOpen ? <SetupDetails snapshot={snapshot} /> : null}
391​
392 {/* Indented so the first label lines up with the stage labels: the icon
393 column, minus the xs button's own horizontal padding. */}
394 <div className="mt-0.5 ml-[calc(--spacing(6)+2px-(--spacing(2)-1px))] flex flex-wrap items-center gap-0.5">
395 <Button
396 type="button"
397 size="xs"
398 variant="ghost-muted"
399 aria-expanded={detailsOpen}
400 onClick={() => setDetailsOpen((open) => !open)}
401 >
402 {detailsOpen ? <ChevronDownIcon aria-hidden /> : <ChevronRightIcon aria-hidden />}
403 Details
404 </Button>
405 {showTerminal ? (
406 <Button type="button" size="xs" variant="ghost-muted" onClick={onOpenTerminal}>
407 <TerminalIcon aria-hidden />
408 Open terminal
409 </Button>
410 ) : null}
411 {onWorkLocally ? (
412 <Button type="button" size="xs" variant="ghost-muted" onClick={onWorkLocally}>
413 <LaptopIcon aria-hidden />
414 Work locally
415 </Button>
416 ) : null}
417 {onCancel && running ? (
418 <Button type="button" size="xs" variant="ghost-muted" onClick={onCancel}>
419 <XIcon aria-hidden />
420 Cancel
421 </Button>
422 ) : null}
423 </div>
424 </section>
425 );