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