The best way to control Claude Code, Codex and more from any computer or phone

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