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

WorktreeSetupCard.tsx

395 lines12.4 KB

1import {
2 worktreeSetupStageLabel,
3 type WorktreeSetupSnapshot,
4 type WorktreeSetupStage,
5} from "@t3tools/contracts";
6import { formatDuration } from "@t3tools/shared/orchestrationTiming";
7import {
8 CheckIcon,
9 CircleAlertIcon,
10 CircleIcon,
11 LaptopIcon,
12 MinusIcon,
13 TerminalIcon,
14 XIcon,
15} from "lucide-react";
16import { ChevronDown, ChevronRight } from "lucide";
17import { useEffect, useState, type ReactNode } from "react";
18​
19import { Button } from "~/components/ui/button";
20import { MorphIcon } from "~/components/MorphIcon";
21import { Spinner } from "~/components/ui/spinner";
22import { MiddleTruncate } from "../ui/middle-truncate";
23import { observeVisibleAnimation } from "~/lib/visibleAnimation";
24import { cn } from "~/lib/utils";
25import { WorkLogRow } from "./WorkLog";
26​
27interface WorktreeSetupCardProps {
28 snapshot: WorktreeSetupSnapshot;
29 onCancel: (() => void) | null;
30 onWorkLocally: (() => void) | null;
31 onOpenTerminal: (() => void) | null;
33​
34function stageElapsedMs(stage: WorktreeSetupStage, nowMs: number): number | null {
35 if (!stage.startedAt) return null;
36 const start = Date.parse(stage.startedAt);
37 const end = stage.endedAt ? Date.parse(stage.endedAt) : nowMs;
38 if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
39 return Math.max(0, end - start);
41​
42function useNowWhile(active: boolean): number {
43 const [nowMs, setNowMs] = useState(() => Date.now());
44 useEffect(() => {
45 if (!active) return;
46 const id = setInterval(() => setNowMs(Date.now()), 1_000);
47 return () => clearInterval(id);
48 }, [active]);
49 return nowMs;
51​
52function StageIcon({ status }: { status: WorktreeSetupStage["status"] }) {
53 const className = "size-4 shrink-0 stroke-2";
54 switch (status) {
55 case "done":
56 return <CheckIcon aria-hidden className={className} />;
57 case "running":
58 return <Spinner size="md" className="shrink-0" />;
59 case "failed":
60 return <XIcon aria-hidden className={className} />;
61 case "warning":
62 return <CircleAlertIcon aria-hidden className={className} />;
63 case "skipped":
64 return <MinusIcon aria-hidden className={className} />;
65 case "pending":
66 return <CircleIcon aria-hidden className={className} />;
67 }
69​
70function stageRowClassName(status: WorktreeSetupStage["status"]): string {
71 switch (status) {
72 case "failed":
73 return "text-destructive-foreground";
74 case "warning":
75 return "text-warning-foreground";
76 case "pending":
77 return "text-secondary-label opacity-40";
78 case "running":
79 case "skipped":
80 case "done":
81 return "text-secondary-label";
82 }
84​
85function ShimmerOverlay({ children }: { children: ReactNode }) {
86 return (
87 <span
88 aria-hidden
89 className="live-activity-focus pointer-events-none absolute inset-y-0 select-none"
90 >
91 <span className="live-activity-focus-counter block">
92 <span className="live-activity-focus-aligned block text-foreground">{children}</span>
93 </span>
94 </span>
95 );
97​
98function headerLabel(snapshot: WorktreeSetupSnapshot): string {
99 switch (snapshot.phase) {
100 case "running":
101 return "Setting up worktree…";
102 case "done":
103 return snapshot.stages.some((stage) => stage.status === "failed")
104 ? "Worktree ready, setup script failed"
105 : "Worktree ready";
106 case "failed":
107 return "Worktree setup failed";
108 case "cancelled":
109 return "Worktree setup cancelled";
110 }
112​
113function SetupHeaderRow({
114 snapshot,
115 totalElapsed,
116}: {
117 snapshot: WorktreeSetupSnapshot;
118 totalElapsed: number | null;
119}) {
120 const running = snapshot.phase === "running";
121 const failed = snapshot.phase === "failed";
122 const finishedWithFailedStage =
123 snapshot.phase === "done" && snapshot.stages.some((stage) => stage.status === "failed");
124 const text = headerLabel(snapshot);
125 const tone = failed
126 ? "text-destructive-foreground"
127 : finishedWithFailedStage
128 ? "text-warning-foreground"
129 : "text-muted-foreground";
130 return (
131 <div className="border-b border-border/60 pb-2 pt-1">
132 <div
133 className={cn(
134 "flex h-6 min-w-0 items-baseline gap-2 px-1 text-sm leading-relaxed tabular-nums",
135 tone,
136 )}
137 >
138 <span
139 ref={running ? observeVisibleAnimation : undefined}
140 className="relative min-w-0 shrink overflow-hidden whitespace-nowrap"
141 >
142 <span className="block truncate">{text}</span>
143 {running ? <ShimmerOverlay>{text}</ShimmerOverlay> : null}
144 </span>
145 {totalElapsed !== null ? (
146 <span className="ml-auto shrink-0 text-xs text-muted-foreground">
147 {formatDuration(totalElapsed)}
148 </span>
149 ) : null}
150 </div>
151 </div>
152 );
154​
155function StageRow({
156 stage,
157 nowMs,
158 scriptName,
159}: {
160 stage: WorktreeSetupStage;
161 nowMs: number;
162 scriptName: string | null;
163}) {
164 const elapsed = stageElapsedMs(stage, nowMs);
165 const label =
166 stage.id === "setup-script" && scriptName ? scriptName : worktreeSetupStageLabel(stage.id);
167 const running = stage.status === "running";
168 const trailing =
169 stage.status === "pending"
170 ? null
171 : stage.status === "skipped"
172 ? (stage.detail ?? "skipped")
173 : stage.id === "checkout" && running && stage.percent !== null
174 ? `${stage.percent}%`
175 : stage.detail;
176 return (
177 <WorkLogRow
178 data-worktree-setup-stage={stage.id}
179 data-worktree-setup-status={stage.status}
180 icon={
181 <span className={cn("text-icon-muted", stage.status === "pending" && "opacity-40")}>
182 <StageIcon status={stage.status} />
183 </span>
184 }
185 label={
186 <span
187 ref={running ? observeVisibleAnimation : undefined}
188 className={cn("relative block truncate", stageRowClassName(stage.status))}
189 >
190 {label}
191 {running ? <ShimmerOverlay>{label}</ShimmerOverlay> : null}
192 </span>
193 }
194 trailing={
195 <>
196 {trailing ? (
197 <span className="min-w-0 truncate text-xs text-muted-foreground tabular-nums">
198 {trailing}
199 </span>
200 ) : null}
201 {elapsed !== null && stage.status !== "skipped" && stage.status !== "pending" ? (
202 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
203 {formatDuration(elapsed)}
204 </span>
205 ) : null}
206 </>
207 }
208 />
209 );
211​
212const OUTPUT_TAIL_LINES = 4;
213const OUTPUT_TAIL_SLOTS = Array.from({ length: OUTPUT_TAIL_LINES }, (_, slot) => slot);
214​
215function OutputTail({ lines, failed }: { lines: ReadonlyArray<string>; failed: boolean }) {
216 const rows = OUTPUT_TAIL_SLOTS.map((slot) => ({
217 slot,
218 line: lines[lines.length - OUTPUT_TAIL_LINES + slot] ?? "",
219 }));
220 return (
221 <pre
222 className={cn(
223 "mb-1 ml-8 overflow-hidden rounded-md border px-2.5 py-1.5 font-mono text-2xs leading-relaxed select-text",
224 failed
225 ? "border-destructive/20 bg-error-surface text-destructive-foreground"
226 : "border-border bg-code text-muted-foreground",
227 )}
228 >
229 {rows.map(({ slot, line }) => (
230 <div key={slot} className="truncate whitespace-pre">
231 {line.length === 0 ? "\u00a0" : line}
232 </div>
233 ))}
234 </pre>
235 );
237​
238function SetupDetails({ snapshot }: { snapshot: WorktreeSetupSnapshot }) {
239 return (
240 <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">
241 {snapshot.branch ? (
242 <>
243 <dt className="text-foreground/80">Branch</dt>
244 <dd className="min-w-0 font-mono">
245 <MiddleTruncate value={snapshot.branch} className="flex" />
246 </dd>
247 </>
248 ) : null}
249 {snapshot.baseRef ? (
250 <>
251 <dt className="text-foreground/80">Base</dt>
252 <dd className="min-w-0 font-mono">
253 <MiddleTruncate value={snapshot.baseRef} className="flex" />
254 </dd>
255 </>
256 ) : null}
257 {snapshot.worktreePath ? (
258 <>
259 <dt className="text-foreground/80">Path</dt>
260 <dd className="min-w-0 font-mono">
261 <MiddleTruncate value={snapshot.worktreePath} className="flex" />
262 </dd>
263 </>
264 ) : null}
265 {snapshot.setupScript ? (
266 <>
267 <dt className="text-foreground/80">Setup</dt>
268 <dd className="truncate font-mono">{snapshot.setupScript.command}</dd>
269 </>
270 ) : null}
271 </dl>
272 );
274​
275function CollapsedSummaryRow({
276 snapshot,
277 totalElapsed,
278}: {
279 snapshot: WorktreeSetupSnapshot;
280 totalElapsed: number | null;
281}) {
282 const status: WorktreeSetupStage["status"] =
283 snapshot.phase === "failed" || snapshot.phase === "cancelled"
284 ? "failed"
285 : snapshot.stages.some((stage) => stage.id === "setup-script" && stage.status === "failed")
286 ? "failed"
287 : "done";
288 const label = headerLabel(snapshot);
289 return (
290 <WorkLogRow
291 data-worktree-setup-stage="summary"
292 data-worktree-setup-status={status}
293 icon={
294 <span className="text-icon-muted">
295 <StageIcon status={status} />
296 </span>
297 }
298 label={<span className={stageRowClassName(status)}>{label}</span>}
299 trailing={
300 totalElapsed !== null ? (
301 <span className="shrink-0 text-xs text-muted-foreground tabular-nums">
302 {formatDuration(totalElapsed)}
303 </span>
304 ) : null
305 }
306 />
307 );
309​
310export function WorktreeSetupCard({
311 snapshot,
312 onCancel,
313 onWorkLocally,
314 onOpenTerminal,
315 embedded = false,
316}: WorktreeSetupCardProps & {
317 embedded?: boolean;
318}) {
319 const running = snapshot.phase === "running";
320 const nowMs = useNowWhile(running);
321 const [detailsOpen, setDetailsOpen] = useState(false);
322 const totalElapsed = (() => {
323 const start = Date.parse(snapshot.startedAt);
324 const end = snapshot.endedAt ? Date.parse(snapshot.endedAt) : nowMs;
325 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
326 })();
327 const setupStage = snapshot.stages.find((stage) => stage.id === "setup-script");
328 const showTerminal = onOpenTerminal && setupStage && setupStage.status !== "pending";
329 const collapsed = embedded && !running;
330 const showHeader = !embedded && !running && snapshot.phase !== "done";
331 const showTail =
332 setupStage !== undefined &&
333 (setupStage.status === "failed" ||
334 (setupStage.status === "running" && setupStage.tail.length > 0));
335​
336 return (
337 <section aria-label="Worktree setup" data-worktree-setup-phase={snapshot.phase}>
338 {showHeader ? <SetupHeaderRow snapshot={snapshot} totalElapsed={totalElapsed} /> : null}
339 {collapsed ? (
340 <CollapsedSummaryRow snapshot={snapshot} totalElapsed={totalElapsed} />
341 ) : (
342 <div className={showHeader ? "pt-1.5" : undefined}>
343 {snapshot.stages.map((stage) => (
344 <div key={stage.id}>
345 <StageRow
346 stage={stage}
347 nowMs={nowMs}
348 scriptName={snapshot.setupScript?.name ?? null}
349 />
350 {stage.id === "setup-script" && showTail ? (
351 <OutputTail lines={stage.tail} failed={stage.status === "failed"} />
352 ) : null}
353 </div>
354 ))}
355 </div>
356 )}
357​
358 {snapshot.phase === "failed" && snapshot.error ? (
359 <p className="mt-1 ml-8 text-xs text-muted-foreground">{snapshot.error}</p>
360 ) : null}
361​
362 <div className="mt-0.5 ml-[calc(--spacing(6)+2px-(--spacing(2)-1px))] flex flex-wrap items-center gap-0.5">
363 <Button
364 type="button"
365 size="xs"
366 variant="ghost-muted"
367 aria-expanded={detailsOpen}
368 onClick={() => setDetailsOpen((open) => !open)}
369 >
370 <MorphIcon aria-hidden icon={detailsOpen ? ChevronDown : ChevronRight} />
371 Details
372 </Button>
373 {showTerminal ? (
374 <Button type="button" size="xs" variant="ghost-muted" onClick={onOpenTerminal}>
375 <TerminalIcon aria-hidden />
376 Open terminal
377 </Button>
378 ) : null}
379 {onWorkLocally ? (
380 <Button type="button" size="xs" variant="ghost-muted" onClick={onWorkLocally}>
381 <LaptopIcon aria-hidden />
382 Work locally
383 </Button>
384 ) : null}
385 {onCancel && running ? (
386 <Button type="button" size="xs" variant="ghost-muted" onClick={onCancel}>
387 <XIcon aria-hidden />
388 Cancel
389 </Button>
390 ) : null}
391 </div>
392 {detailsOpen ? <SetupDetails snapshot={snapshot} /> : null}
393 </section>
394 );