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