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

worktree-setup-card.tsx

474 lines15.4 KB

1import { msg, T, useGT, useMessages, type Msg } from "gt-react-native";
2​
3import type { MessageResolver } from "../../i18n/messages";
4​
5import { Button } from "../../components/ui/Button";
6import {
7 WORKTREE_SETUP_STAGE_ORDER,
8 type WorktreeSetupSnapshot,
9 type WorktreeSetupStage,
10} from "@t3tools/contracts";
11import { worktreeSetupAgentStarted } from "@t3tools/client-runtime/worktree-setup";
12import { formatDuration } from "@t3tools/shared/orchestrationTimingCopy";
13import { Platform, Pressable, ScrollView, View } from "react-native";
14import { useSafeAreaInsets } from "react-native-safe-area-context";
15import { AppActivityIndicator } from "../../components/ui/AppActivityIndicator";
16import { AppText as Text } from "../../components/ui/AppText";
17import { SymbolView, type AppSymbolName } from "../../components/ui/AppSymbol";
18import { Sheet } from "../../components/ui/Sheet";
19import { ShimmeringWorkContent } from "./thread-work-log";
20import { useVisibleSecondClock } from "./use-visible-second-clock";
21import { worktreeSetupCardMode } from "./worktree-setup-state";
22​
23export interface WorktreeSetupCardProps {
24 snapshot: WorktreeSetupSnapshot;
25 turnStarted: boolean;
26 onCancel: () => void;
27 onWorkLocally: (() => void) | null;
29​
30function elapsed(start: string | null, end: string | null, now: number, resolve: MessageResolver) {
31 const duration = (end ? Date.parse(end) : now) - (start ? Date.parse(start) : NaN);
32 return Number.isFinite(duration) ? formatDuration(Math.max(0, duration), resolve) : null;
34​
35const statusLabels = {
36 pending: msg({ context: "setup stage status" })`pending`,
37 running: msg({ context: "setup stage status" })`running`,
38 done: msg({ context: "setup stage status" })`done`,
39 skipped: msg({ context: "setup stage status" })`skipped`,
40 failed: msg({ context: "setup stage status" })`failed`,
41 warning: msg({ context: "setup stage status" })`warning`,
42} as const satisfies Record<WorktreeSetupStage["status"], string | Msg>;
43​
44const stageLabels = {
45 fetch: msg("Fetch base branch"),
46 checkout: msg("Check out files"),
47 submodules: msg("Init submodules"),
48 "setup-script": msg("Run setup script"),
49 agent: msg("Start agent"),
50} as const satisfies Record<WorktreeSetupStage["id"], string>;
51​
52const icons: Record<WorktreeSetupStage["status"], AppSymbolName> = {
53 pending: "circle",
54 running: "clock",
55 done: "checkmark",
56 skipped: "minus",
57 failed: "xmark",
58 warning: "exclamationmark.triangle",
59};
60​
61/** The feed owns whether the details sheet is open, so it survives the card turning into a chip or summary. */
62interface SetupDetailsControl {
63 readonly detailsOpen: boolean;
64 readonly onOpenDetails: () => void;
66​
67export function WorktreeSetupCard(
68 props: WorktreeSetupCardProps & SetupDetailsControl & { readonly chipCarried: boolean },
69) {
70 const mode = worktreeSetupCardMode(
71 props.snapshot,
72 worktreeSetupHandedOff(props),
73 props.chipCarried,
74 );
75 if (mode === "summary") return <WorktreeSetupSummaryRow {...props} />;
76 return mode === "card" ? <WorktreeSetupHeaderCard {...props} /> : null;
78​
79function WorktreeSetupHeaderCard(props: WorktreeSetupCardProps & SetupDetailsControl) {
80 const { snapshot, detailsOpen } = props;
81 const gt = useGT();
82 const messages = useMessages();
83 const running = snapshot.phase === "running";
84 const now = useVisibleSecondClock(running);
85 const failed =
86 snapshot.phase === "failed" || snapshot.stages.some((stage) => stage.status === "failed");
87 const label = running
88 ? gt`Setting up worktree…`
89 : snapshot.phase === "cancelled"
90 ? gt`Worktree setup cancelled`
91 : snapshot.phase === "failed"
92 ? gt`Worktree setup failed`
93 : failed
94 ? gt`Setup script failed`
95 : gt`Worktree ready`;
96​
97 return (
98 <View accessibilityLabel={gt`Worktree setup`} className="py-1">
99 <View className="min-h-11 flex-row items-center gap-2 border-b border-border px-1">
100 <HeaderLabel label={label} active={running && !detailsOpen} failed={failed} />
101 <Text
102 className="text-2xs text-foreground-secondary"
103 style={{ fontVariant: ["tabular-nums"] }}
104 >
105 {elapsed(snapshot.startedAt, snapshot.endedAt, now, messages)}
106 </Text>
107 <Pressable
108 accessibilityRole="button"
109 accessibilityLabel={gt`Worktree setup details`}
110 accessibilityState={{ expanded: detailsOpen }}
111 onPress={props.onOpenDetails}
112 className="min-h-11 max-w-[55%] justify-center px-2"
113 >
114 <View className="flex-row items-center gap-1">
115 {failed ? (
116 <SymbolView
117 name="exclamationmark.circle"
118 size={12}
119 tintColorClassName="accent-danger-foreground"
120 />
121 ) : null}
122 <Text numberOfLines={1} className="shrink text-2xs text-foreground-secondary">
123 <T>Details</T>
124 </Text>
125 <SymbolView name="chevron.right" size={10} tintColorClassName="accent-icon-muted" />
126 </View>
127 </Pressable>
128 </View>
129 <View className="pt-1 pb-2">
130 {snapshot.stages
131 .filter((stage) => stage.id !== "agent")
132 .map((stage) => (
133 <StageRow
134 key={stage.id}
135 stage={stage}
136 scriptName={snapshot.setupScript?.name ?? null}
137 now={now}
138 compact
139 animate={!detailsOpen}
140 />
141 ))}
142 </View>
143 </View>
144 );
146​
147/** True once the agent has the turn; the turn's fold row then carries the setup instead of the card. */
148export function worktreeSetupHandedOff(props: WorktreeSetupCardProps): boolean {
149 return props.turnStarted && worktreeSetupAgentStarted(props.snapshot);
151​
152/** The card's state on the turn's fold row: setup still running, or a failure to look at. */
153export function WorktreeSetupFoldChip(props: WorktreeSetupCardProps & SetupDetailsControl) {
154 const gt = useGT();
155 const scriptName = props.snapshot.setupScript?.name ?? gt`Setup script`;
156 return (
157 <Pressable
158 accessibilityRole="button"
159 accessibilityLabel={gt`Background setup is still running: ${{ scriptName }}. Show setup progress.`}
160 onPress={props.onOpenDetails}
161 hitSlop={8}
162 className="ml-2 min-w-0 max-w-[55%] flex-row items-center gap-1 rounded-full border border-border px-2 py-1 active:opacity-70"
163 >
164 <AppActivityIndicator
165 size={Platform.OS === "android" ? 12 : "small"}
166 colorClassName="accent-icon-muted"
167 style={{
168 width: 12,
169 height: 12,
170 transform: Platform.OS === "android" ? undefined : [{ scale: 0.65 }],
171 }}
172 />
173 <Text numberOfLines={1} className="shrink text-2xs text-foreground-secondary">
174 <T>Background setup</T>
175 </Text>
176 </Pressable>
177 );
179​
180/**
181 * Setup that ended after the agent took the turn, as one row under the prompt, like web's
182 * collapsed summary. Tapping it opens the details.
183 */
184function WorktreeSetupSummaryRow(props: WorktreeSetupCardProps & SetupDetailsControl) {
185 const { snapshot } = props;
186 const gt = useGT();
187 const messages = useMessages();
188 const now = useVisibleSecondClock(false);
189 const label =
190 snapshot.phase === "failed"
191 ? gt`Worktree setup failed`
192 : snapshot.phase === "cancelled"
193 ? gt`Worktree setup cancelled`
194 : gt`Worktree ready, setup script failed`;
195 return (
196 <Pressable
197 accessibilityRole="button"
198 accessibilityLabel={gt`${{ label }}. Show setup details.`}
199 onPress={props.onOpenDetails}
200 className="mb-1 min-h-8 flex-row items-center px-1 active:opacity-70"
201 style={{ columnGap: 8 }}
202 >
203 <View className="w-6 items-center">
204 <SymbolView name="xmark" size={14} tintColorClassName="accent-danger-foreground" />
205 </View>
206 <Text numberOfLines={1} className="flex-1 text-sm text-danger-foreground">
207 {label}
208 </Text>
209 <Text
210 className="text-2xs text-foreground-secondary"
211 style={{ fontVariant: ["tabular-nums"] }}
212 >
213 {elapsed(snapshot.startedAt, snapshot.endedAt, now, messages)}
214 </Text>
215 <SymbolView name="chevron.right" size={10} tintColorClassName="accent-icon-muted" />
216 </Pressable>
217 );
219​
220/** The one setup details sheet, opened from the card, the chip, or the summary row. */
221export function WorktreeSetupDetails(
222 props: WorktreeSetupCardProps & { readonly onClose: () => void },
223) {
224 const now = useVisibleSecondClock(props.snapshot.phase === "running");
225 return <SetupDetailsSheet {...props} now={now} />;
227​
228/** Holds the card's place until the server publishes the first setup snapshot. */
229// Same rows the first snapshot brings, so the card keeps its height when that snapshot lands.
230const PREPARING_STAGES: ReadonlyArray<WorktreeSetupStage> = WORKTREE_SETUP_STAGE_ORDER.filter(
231 (id) => id !== "agent",
232).map((id) => ({
233 id,
234 status: "pending",
235 startedAt: null,
236 endedAt: null,
237 percent: null,
238 detail: null,
239 tail: [],
240}));
241​
242export function WorktreePreparingHeader() {
243 const gt = useGT();
244 return (
245 <View className="py-1">
246 <View className="min-h-11 flex-row items-center border-b border-border px-1">
247 <HeaderLabel label={gt`Setting up worktree…`} active />
248 </View>
249 <View className="pt-1 pb-2">
250 {PREPARING_STAGES.map((stage) => (
251 <StageRow key={stage.id} stage={stage} scriptName={null} now={0} compact />
252 ))}
253 </View>
254 </View>
255 );
257​
258function HeaderLabel({
259 label,
260 active,
261 failed = false,
262}: {
263 label: string;
264 active: boolean;
265 failed?: boolean;
266}) {
267 return active ? (
268 <ShimmeringWorkContent
269 icon="clock"
270 iconSubtleColor="transparent"
271 label={label}
272 showIcon={false}
273 />
274 ) : (
275 <Text
276 numberOfLines={1}
277 className={
278 failed
279 ? "flex-1 text-sm text-danger-foreground"
280 : "flex-1 text-sm text-foreground-secondary"
281 }
282 style={{ fontVariant: ["tabular-nums"] }}
283 >
284 {label}
285 </Text>
286 );
288​
289function SetupDetailsSheet({
290 snapshot,
291 turnStarted,
292 onCancel,
293 onWorkLocally,
294 onClose,
295 now,
296}: WorktreeSetupCardProps & { onClose: () => void; now: number }) {
297 const gt = useGT();
298 const insets = useSafeAreaInsets();
299 const canCancel = snapshot.phase === "running" && !turnStarted;
300 return (
301 <Sheet title={gt`Worktree setup`} onClose={onClose}>
302 <ScrollView
303 contentInsetAdjustmentBehavior="automatic"
304 bounces={false}
305 contentContainerStyle={{
306 paddingHorizontal: 20,
307 paddingTop: 12,
308 paddingBottom: Math.max(20, insets.bottom),
309 }}
310 >
311 {snapshot.stages
312 .filter((stage) => stage.id !== "agent")
313 .map((stage) => (
314 <View key={stage.id}>
315 <StageRow stage={stage} scriptName={snapshot.setupScript?.name ?? null} now={now} />
316 {stage.id === "setup-script" &&
317 (stage.status === "running" || stage.status === "failed" || stage.tail.length > 0) ? (
318 <OutputTail lines={stage.tail} failed={stage.status === "failed"} />
319 ) : null}
320 </View>
321 ))}
322 {snapshot.phase === "failed" && snapshot.error ? (
323 <Text selectable className="ml-8 mt-2 text-xs text-danger-foreground">
324 {snapshot.error}
325 </Text>
326 ) : null}
327 {canCancel ? (
328 <View className="mt-3 flex-row items-center justify-end gap-4 border-t border-border pt-1">
329 <Button
330 label={gt`Cancel setup`}
331 tone="danger"
332 accessibilityLabel={gt`Cancel worktree setup`}
333 onPress={() => {
334 onClose();
335 onCancel();
336 }}
337 />
338 {onWorkLocally ? (
339 <Button
340 label={gt`Work locally`}
341 tone="secondary"
342 onPress={() => {
343 onClose();
344 onWorkLocally();
345 }}
346 />
347 ) : null}
348 </View>
349 ) : null}
350 </ScrollView>
351 </Sheet>
352 );
354​
355function StageRow({
356 stage,
357 scriptName,
358 now,
359 compact = false,
360 animate = true,
361}: {
362 stage: WorktreeSetupStage;
363 scriptName: string | null;
364 now: number;
365 compact?: boolean;
366 animate?: boolean;
367}) {
368 const gt = useGT();
369 const m = useMessages();
370 const label =
371 stage.id === "setup-script"
372 ? (scriptName ?? m(stageLabels[stage.id]))
373 : m(stageLabels[stage.id]);
374 const detail =
375 stage.status === "pending"
376 ? null
377 : stage.status === "skipped"
378 ? (stage.detail ?? m(statusLabels.skipped))
379 : stage.id === "checkout" && stage.status === "running" && stage.percent !== null
380 ? `${stage.percent}%`
381 : stage.detail;
382 return (
383 <View
384 accessibilityLabel={gt`${{ label }}, ${{ status: m(statusLabels[stage.status]) }}`}
385 className={compact ? "min-h-8 flex-row items-center" : "min-h-11 flex-row items-center"}
386 style={{ columnGap: 8, opacity: stage.status === "pending" ? 0.4 : 1 }}
387 >
388 <View className="w-6 items-center">
389 {stage.status === "running" && animate ? (
390 <AppActivityIndicator
391 size="small"
392 colorClassName="accent-icon-muted"
393 style={{ transform: [{ scale: 0.75 }] }}
394 />
395 ) : (
396 <SymbolView
397 name={icons[stage.status]}
398 size={14}
399 tintColorClassName={
400 stage.status === "failed"
401 ? "accent-danger-foreground"
402 : stage.status === "warning"
403 ? "accent-warning-foreground"
404 : "accent-icon-muted"
405 }
406 />
407 )}
408 </View>
409 {stage.status === "running" && animate ? (
410 <ShimmeringWorkContent
411 icon="clock"
412 iconSubtleColor="transparent"
413 label={label}
414 showIcon={false}
415 />
416 ) : (
417 <Text
418 numberOfLines={1}
419 className={
420 stage.status === "failed"
421 ? "flex-1 text-sm text-danger-foreground"
422 : "flex-1 text-sm text-foreground-secondary"
423 }
424 >
425 {label}
426 </Text>
427 )}
428 {detail ? (
429 <Text numberOfLines={1} className="max-w-[25%] shrink text-2xs text-foreground-secondary">
430 {detail}
431 </Text>
432 ) : null}
433 {stage.status !== "pending" && stage.status !== "skipped" ? (
434 <Text
435 className="text-2xs text-foreground-secondary"
436 style={{ fontVariant: ["tabular-nums"] }}
437 >
438 {elapsed(stage.startedAt, stage.endedAt, now, m)}
439 </Text>
440 ) : null}
441 </View>
442 );
444​
445const OUTPUT_TAIL_SLOTS = [0, 1, 2, 3] as const;
446​
447function OutputTail({ lines, failed }: { lines: ReadonlyArray<string>; failed: boolean }) {
448 const gt = useGT();
449 return (
450 <View
451 accessibilityLabel={gt`Setup script output`}
452 className={
453 failed
454 ? "mb-2 ml-8 rounded-md border border-danger-border bg-danger px-3 py-2"
455 : "mb-2 ml-8 rounded-md border border-border bg-card-alt px-3 py-2"
456 }
457 >
458 {OUTPUT_TAIL_SLOTS.map((slot) => (
459 <Text
460 key={slot}
461 selectable
462 numberOfLines={1}
463 className={
464 failed
465 ? "text-2xs leading-5 text-danger-foreground ios:font-[family-name:Menlo] android:font-mono"
466 : "text-2xs leading-5 text-foreground-secondary ios:font-[family-name:Menlo] android:font-mono"
467 }
468 >
469 {lines[lines.length - OUTPUT_TAIL_SLOTS.length + slot] || "\u00a0"}
470 </Text>
471 ))}
472 </View>
473 );