Open History to see the last commit
1import { createNativeHeaderMenu } from "../../components/nativeHeaderMenu.ios";
2import type { ScreenHeaderMenu } from "../../components/ScreenHeader.types";
3import {
4 EnvironmentId,
5 type GitRunStackedActionResult,
6 type ProjectScript,
7 ThreadId,
8 type VcsStatusResult,
9} from "@t3tools/contracts";
10import {
11 type GitActionRequestInput,
12 requiresDefaultBranchConfirmation,
13 resolveQuickAction,
14} from "@t3tools/client-runtime/state/vcs";
15import { useNavigation } from "@react-navigation/native";
16import { NativeHeaderToolbar } from "../../native/StackHeader";
17import { useCallback, useMemo } from "react";
18import { Alert } from "react-native";
19import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
20import {
21 basename,
22 getTerminalStatusLabel,
23 projectScriptMenuIcon,
24 projectScriptMenuLabel,
25 type TerminalMenuSession,
26} from "../terminal/terminalMenu";
27
28function truncateMiddle(value: string, maxLength: number): string {
29 if (value.length <= maxLength) {
30 return value;
31 }
32
33 const headLength = Math.ceil((maxLength - 1) / 2);
34 const tailLength = Math.floor((maxLength - 1) / 2);
35 return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`;
36}
37
38function compactMenuBranchLabel(branch: string): string {
39 return truncateMiddle(branch, 24);
40}
41
42function compactMenuStatus(gitStatus: VcsStatusResult | null): string {
43 if (!gitStatus) {
44 return "Checking status";
45 }
46 if (!gitStatus.isRepo) {
47 return "Not a repo";
48 }
49
50 const parts: string[] = [];
51 if (gitStatus.hasWorkingTreeChanges) {
52 parts.push(`${gitStatus.workingTree.files.length} changed`);
53 } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
54 parts.push("Clean");
55 }
56 if (gitStatus.aheadCount > 0) {
57 parts.push(`${gitStatus.aheadCount} ahead`);
58 }
59 if (gitStatus.behindCount > 0) {
60 parts.push(`${gitStatus.behindCount} behind`);
61 }
62 if (gitStatus.pr?.state === "open") {
63 parts.push(`PR #${gitStatus.pr.number}`);
64 }
65
66 return parts.join(" · ");
67}
68
69type HeaderItem = Record<string, unknown>;
70type HeaderItems = HeaderItem[];
71type ThreadGitHeaderActionItems = {
72 readonly terminal: HeaderItem;
73 readonly files: HeaderItem;
74 readonly git: HeaderItem;
75};
76type QuickActionIcon =
77 | "arrow.down.circle"
78 | "arrow.up.right.circle"
79 | "checkmark.circle"
80 | "arrow.up.circle";
81
82/** The subset of git-control wiring the standalone git menu needs. */
83export type ThreadGitMenuProps = {
84 readonly environmentId: EnvironmentId | string;
85 readonly threadId: ThreadId | string;
86 readonly currentBranch: string | null;
87 readonly gitStatus: VcsStatusResult | null;
88 readonly gitOperationLabel: string | null;
89 readonly onOpenFilesInspector?: () => void;
90 readonly onOpenGitInspector?: () => void;
91 readonly onPull: () => Promise<void>;
92 readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
93};
94
95type ThreadGitControlsProps = ThreadGitMenuProps & {
96 readonly auxiliaryPaneControl?: {
97 readonly accessibilityLabel: string;
98 readonly onPress: () => void;
99 };
100 readonly canOpenTerminal: boolean;
101 readonly canOpenFiles: boolean;
102 readonly projectScripts: ReadonlyArray<ProjectScript>;
103 readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
104 readonly showActionControls?: boolean;
105 readonly showDirectFileControl?: boolean;
106 readonly onOpenTerminal: (terminalId?: string | null) => void;
107 readonly onOpenNewTerminal: () => void;
108 readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
109};
110
111function useThreadGitControlModel(props: ThreadGitMenuProps) {
112 const navigation = useNavigation();
113 const environmentId = props.environmentId;
114 const threadId = props.threadId;
115 const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
116
117 const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? "Detached HEAD";
118 const busy = gitOperationLabel !== null;
119 const isRepo = gitStatus?.isRepo ?? true;
120 const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
121 const isDefaultRef = gitStatus?.isDefaultRef ?? false;
122
123 const quickAction = useMemo(
124 () =>
125 isRepo
126 ? resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote)
127 : {
128 label: "Git unavailable",
129 disabled: true,
130 kind: "show_hint" as const,
131 hint: "This workspace is not a git repository.",
132 },
133 [busy, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo],
134 );
135
136 const quickActionHint = quickAction.disabled
137 ? (quickAction.hint ?? "This action is unavailable.")
138 : null;
139
140 const quickActionIcon: QuickActionIcon = (() => {
141 if (quickAction.kind === "run_pull") return "arrow.down.circle";
142 if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
143 if (quickAction.kind === "run_action") {
144 if (quickAction.action === "commit") return "checkmark.circle";
145 if (quickAction.action === "push" || quickAction.action === "commit_push")
146 return "arrow.up.circle";
147 }
148 return "arrow.up.right.circle";
149 })();
150
151 const openExistingPr = useCallback(async () => {
152 const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
153 if (!prUrl) {
154 Alert.alert("No open PR", "This branch does not have an open pull request.");
155 return;
156 }
157 if (!(await tryOpenExternalUrl(prUrl, "pull-request"))) {
158 Alert.alert("Unable to open PR", "The pull request could not be opened.");
159 }
160 }, [gitStatus]);
161
162 const runActionWithPrompt = useCallback(
163 async (input: GitActionRequestInput) => {
164 const confirmableAction =
165 input.action === "push" ||
166 input.action === "create_pr" ||
167 input.action === "commit_push" ||
168 input.action === "commit_push_pr"
169 ? input.action
170 : null;
171 const branchName = gitStatus?.refName;
172 if (
173 branchName &&
174 confirmableAction &&
175 !input.featureBranch &&
176 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
177 ) {
178 navigation.navigate("GitConfirm", {
179 environmentId: String(environmentId),
180 threadId: String(threadId),
181 confirmAction: confirmableAction,
182 branchName,
183 includesCommit: String(
184 input.action === "commit_push" || input.action === "commit_push_pr",
185 ),
186 });
187 return;
188 }
189
190 await onRunAction(input);
191 },
192 [environmentId, gitStatus, isDefaultRef, onRunAction, navigation, threadId],
193 );
194
195 const runQuickAction = useCallback(async () => {
196 if (quickAction.kind === "open_pr") {
197 await openExistingPr();
198 return;
199 }
200 if (quickAction.kind === "run_pull") {
201 await onPull();
202 return;
203 }
204 if (quickAction.kind === "run_action" && quickAction.action) {
205 await runActionWithPrompt({ action: quickAction.action });
206 }
207 }, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
208
209 const openFiles = useCallback(() => {
210 if (props.onOpenFilesInspector) {
211 props.onOpenFilesInspector();
212 return;
213 }
214 navigation.navigate("ThreadFiles", {
215 environmentId: String(environmentId),
216 threadId: String(threadId),
217 });
218 }, [environmentId, props.onOpenFilesInspector, navigation, threadId]);
219
220 const openReview = useCallback(() => {
221 navigation.navigate("ThreadReview", {
222 environmentId: EnvironmentId.make(String(environmentId)),
223 threadId: ThreadId.make(String(threadId)),
224 });
225 }, [environmentId, navigation, threadId]);
226
227 const openGitInspector = useCallback(() => {
228 if (props.onOpenGitInspector) {
229 props.onOpenGitInspector();
230 return;
231 }
232 navigation.navigate("GitOverview", {
233 environmentId: String(environmentId),
234 threadId: String(threadId),
235 });
236 }, [environmentId, props.onOpenGitInspector, navigation, threadId]);
237
238 return {
239 currentBranchLabel,
240 isRepo,
241 openFiles,
242 openGitInspector,
243 openReview,
244 quickAction,
245 quickActionHint,
246 quickActionIcon,
247 runQuickAction,
248 };
249}
250
251function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGitHeaderActionItems {
252 const model = useThreadGitControlModel(props);
253
254 return useMemo(
255 () => ({
256 terminal: {
257 accessibilityLabel: "Open terminal",
258 disabled: !props.canOpenTerminal,
259 icon: { name: "terminal", type: "sfSymbol" },
260 identifier: "thread-right-terminal",
261 label: "Terminal",
262 menu: {
263 items: [
264 ...props.projectScripts.map((script) => ({
265 description: script.command,
266 icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
267 label: projectScriptMenuLabel(script),
268 onPress: () => void props.onRunProjectScript(script),
269 type: "action" as const,
270 })),
271 ...(props.projectScripts.length === 0
272 ? [
273 {
274 description: "This project has no saved scripts yet",
275 disabled: true,
276 icon: { name: "play", type: "sfSymbol" as const },
277 label: "No project scripts",
278 onPress: () => {},
279 type: "action" as const,
280 },
281 ]
282 : []),
283 ...props.terminalSessions.map((session) => ({
284 description: [
285 getTerminalStatusLabel({
286 status: session.status,
287 hasRunningSubprocess: session.hasRunningSubprocess,
288 }),
289 basename(session.cwd),
290 ]
291 .filter(Boolean)
292 .join(" · "),
293 icon: { name: "terminal", type: "sfSymbol" as const },
294 label: session.displayLabel,
295 onPress: () => props.onOpenTerminal(session.terminalId),
296 type: "action" as const,
297 })),
298 {
299 description: "Start another shell for this thread",
300 icon: { name: "plus", type: "sfSymbol" },
301 label: "Open new terminal",
302 onPress: props.onOpenNewTerminal,
303 type: "action",
304 },
305 ],
306 title: "Terminal",
307 },
308 sharesBackground: true,
309 type: "menu",
310 variant: "plain",
311 },
312 files: {
313 accessibilityLabel: "Open files",
314 disabled: !props.canOpenFiles,
315 icon: { name: "folder", type: "sfSymbol" },
316 identifier: "thread-right-files",
317 label: "Files",
318 onPress: model.openFiles,
319 sharesBackground: true,
320 type: "button",
321 variant: "plain",
322 },
323 git: {
324 accessibilityLabel: "Git actions",
325 icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
326 identifier: "thread-right-git",
327 label: "Git",
328 menu: {
329 items: [
330 {
331 description: compactMenuStatus(props.gitStatus),
332 disabled: true,
333 icon: {
334 name: "point.topleft.down.curvedto.point.bottomright.up",
335 type: "sfSymbol",
336 },
337 label: compactMenuBranchLabel(model.currentBranchLabel),
338 onPress: (): void => {},
339 type: "action",
340 },
341 {
342 description: model.quickActionHint ?? undefined,
343 disabled: model.quickAction.disabled,
344 icon: { name: model.quickActionIcon, type: "sfSymbol" },
345 label: model.quickAction.label,
346 onPress: (): void => void model.runQuickAction(),
347 type: "action",
348 },
349 {
350 description: "Turn diffs and worktree changes",
351 disabled: !model.isRepo,
352 icon: { name: "text.bubble", type: "sfSymbol" },
353 label: "Review changes",
354 onPress: model.openReview,
355 type: "action",
356 },
357 {
358 description: "Commit, files, branches",
359 icon: { name: "ellipsis", type: "sfSymbol" },
360 label: "More",
361 onPress: model.openGitInspector,
362 type: "action",
363 },
364 ],
365 title: "Git",
366 },
367 sharesBackground: true,
368 type: "menu",
369 variant: "plain",
370 },
371 }),
372 [
373 model.currentBranchLabel,
374 model.isRepo,
375 model.openFiles,
376 model.openGitInspector,
377 model.openReview,
378 model.quickAction.disabled,
379 model.quickAction.label,
380 model.quickActionHint,
381 model.quickActionIcon,
382 model.runQuickAction,
383 props.canOpenFiles,
384 props.canOpenTerminal,
385 props.gitStatus,
386 props.onOpenNewTerminal,
387 props.onOpenTerminal,
388 props.onRunProjectScript,
389 props.projectScripts,
390 props.terminalSessions,
391 ],
392 );
393}
394
395export function useThreadGitRightHeaderItems(props: ThreadGitControlsProps): HeaderItems {
396 const actionItems = useThreadGitHeaderActionItems(props);
397 return useMemo(
398 () => [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems,
399 [actionItems],
400 );
401}
402
403export function useThreadGitCenterHeaderItems(props: ThreadGitControlsProps): HeaderItems {
404 const actionItems = useThreadGitHeaderActionItems(props);
405 return useMemo(
406 () => [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems,
407 [actionItems],
408 );
409}
410
411export function ThreadGitControls(props: ThreadGitControlsProps) {
412 const model = useThreadGitControlModel(props);
413 const showActionControls = props.showActionControls ?? true;
414
415 if (!showActionControls) {
416 return null;
417 }
418
419 return (
420 <NativeHeaderToolbar placement="right">
421 {showActionControls && props.auxiliaryPaneControl ? (
422 <NativeHeaderToolbar.Button
423 accessibilityLabel={props.auxiliaryPaneControl.accessibilityLabel}
424 icon="sidebar.right"
425 onPress={props.auxiliaryPaneControl.onPress}
426 separateBackground
427 />
428 ) : null}
429 {showActionControls ? (
430 <NativeHeaderToolbar.Menu
431 accessibilityLabel="Open terminal"
432 icon="terminal"
433 disabled={!props.canOpenTerminal}
434 separateBackground
435 >
436 {props.projectScripts.length > 0 ? (
437 props.projectScripts.map((script) => (
438 <NativeHeaderToolbar.MenuAction
439 key={script.id}
440 icon={projectScriptMenuIcon(script.icon)}
441 onPress={() => void props.onRunProjectScript(script)}
442 subtitle={script.command}
443 >
444 <NativeHeaderToolbar.Label>
445 {projectScriptMenuLabel(script)}
446 </NativeHeaderToolbar.Label>
447 </NativeHeaderToolbar.MenuAction>
448 ))
449 ) : (
450 <NativeHeaderToolbar.MenuAction
451 icon="play"
452 disabled
453 onPress={() => {}}
454 subtitle="This project has no saved scripts yet"
455 >
456 <NativeHeaderToolbar.Label>No project scripts</NativeHeaderToolbar.Label>
457 </NativeHeaderToolbar.MenuAction>
458 )}
459 {props.terminalSessions.map((session) => (
460 <NativeHeaderToolbar.MenuAction
461 key={session.terminalId}
462 icon="terminal"
463 onPress={() => props.onOpenTerminal(session.terminalId)}
464 subtitle={[
465 getTerminalStatusLabel({
466 status: session.status,
467 hasRunningSubprocess: session.hasRunningSubprocess,
468 }),
469 basename(session.cwd),
470 ]
471 .filter(Boolean)
472 .join(" · ")}
473 >
474 <NativeHeaderToolbar.Label>{session.displayLabel}</NativeHeaderToolbar.Label>
475 </NativeHeaderToolbar.MenuAction>
476 ))}
477 <NativeHeaderToolbar.MenuAction
478 icon="plus"
479 onPress={props.onOpenNewTerminal}
480 subtitle="Start another shell for this thread"
481 >
482 <NativeHeaderToolbar.Label>Open new terminal</NativeHeaderToolbar.Label>
483 </NativeHeaderToolbar.MenuAction>
484 </NativeHeaderToolbar.Menu>
485 ) : null}
486 {showActionControls && props.showDirectFileControl ? (
487 <NativeHeaderToolbar.Button
488 accessibilityLabel="Open files"
489 disabled={!props.canOpenFiles}
490 icon="folder"
491 onPress={model.openFiles}
492 separateBackground
493 />
494 ) : null}
495 {showActionControls ? createNativeHeaderMenu(threadGitMenuDefinition(props, model)) : null}
496 </NativeHeaderToolbar>
497 );
498}
499
500/**
501 * The standalone git actions menu (branch status, quick commit/push action,
502 * review, more). Rendered inside a NativeHeaderToolbar by both the thread
503 * chat header and the review screen's toolbar.
504 */
505export function ThreadGitMenu(props: ThreadGitMenuProps) {
506 const menu = useThreadGitMenuDefinition(props);
507 return menu ? createNativeHeaderMenu(menu) : null;
508}
509
510/** Returns menu data because native toolbars serialize direct items rather than rendering component children. */
511export function useThreadGitMenuDefinition(props: ThreadGitMenuProps): ScreenHeaderMenu | null {
512 return threadGitMenuDefinition(props, useThreadGitControlModel(props));
513}
514
515function threadGitMenuDefinition(
516 props: ThreadGitMenuProps,
517 model: ReturnType<typeof useThreadGitControlModel>,
518): ScreenHeaderMenu {
519 return {
520 title: "Git controls",
521 icon: "point.topleft.down.curvedto.point.bottomright.up",
522 separateBackground: false,
523 items: [
524 {
525 id: "git-status",
526 title: compactMenuBranchLabel(model.currentBranchLabel),
527 icon: "point.topleft.down.curvedto.point.bottomright.up",
528 disabled: true,
529 subtitle: compactMenuStatus(props.gitStatus),
530 onPress: () => {},
531 },
532 {
533 id: "git-quick-action",
534 title: model.quickAction.label,
535 icon: model.quickActionIcon,
536 disabled: model.quickAction.disabled,
537 subtitle: model.quickActionHint ?? undefined,
538 onPress: () => {
539 void model.runQuickAction();
540 },
541 },
542 {
543 id: "git-review",
544 title: "Review changes",
545 icon: "text.bubble",
546 disabled: !model.isRepo,
547 subtitle: "Turn diffs and worktree changes",
548 onPress: model.openReview,
549 },
550 {
551 id: "git-more",
552 title: "More",
553 icon: "ellipsis",
554 subtitle: "Commit, files, branches",
555 onPress: model.openGitInspector,
556 },
557 ],
558 };
559}