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 { useEnvironmentScope } from "../../state/session";
22import { PullRequestGlyph } from "../pull-requests/pullRequestGlyphs";
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
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 readonly onMergeBack?: () => void;
94 readonly onPull: () => Promise<void>;
95 readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
96};
97
98type ThreadGitControlsProps = ThreadGitMenuProps & {
99 readonly auxiliaryPaneControl?: {
100 readonly accessibilityLabel: string;
101 readonly onPress: () => void;
102 };
103 readonly canOpenTerminal: boolean;
104 readonly canOperateTerminal: boolean;
105 readonly canOpenFiles: boolean;
106 readonly projectScripts: ReadonlyArray<ProjectScript>;
107 readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
108 readonly showActionControls?: boolean;
109 readonly showDirectFileControl?: boolean;
110 readonly onOpenTerminal: (terminalId?: string | null) => void;
111 readonly onOpenNewTerminal: () => void;
112 readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
113};
114
115function useThreadGitControlModel(props: ThreadGitMenuProps) {
116 const navigation = useNavigation();
117 const openPullRequest = useOpenPullRequest();
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 = (() => {
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 })();
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 = async () => {
167 const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
168 if (!prUrl) {
169 Dialog.alert("No open PR", "This branch does not have an open pull request.");
170 return;
171 }
172 if (!(await openPullRequest(prUrl))) {
173 Dialog.alert("Unable to open PR", "The pull request could not be opened.");
174 }
175 };
176
177 const runActionWithPrompt = async (input: GitActionRequestInput) => {
178 if (!canWriteSourceControl) return;
179 const confirmableAction =
180 input.action === "push" ||
181 input.action === "create_pr" ||
182 input.action === "commit_push" ||
183 input.action === "commit_push_pr"
184 ? input.action
185 : null;
186 const branchName = gitStatus?.refName;
187 if (
188 branchName &&
189 confirmableAction &&
190 !input.featureBranch &&
191 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
192 ) {
193 navigation.navigate("GitConfirm", {
194 environmentId: String(environmentId),
195 threadId: String(threadId),
196 confirmAction: confirmableAction,
197 branchName,
198 includesCommit: String(input.action === "commit_push" || input.action === "commit_push_pr"),
199 });
200 return;
201 }
202
203 await onRunAction(input);
204 };
205
206 const runQuickAction = async () => {
207 if (quickAction.disabled) return;
208 if (quickAction.kind === "open_pr") {
209 await openExistingPr();
210 return;
211 }
212 if (quickAction.kind === "run_pull") {
213 await onPull();
214 return;
215 }
216 if (quickAction.kind === "run_action" && quickAction.action) {
217 await runActionWithPrompt({ action: quickAction.action });
218 }
219 };
220
221 const openFiles = () => {
222 if (props.onOpenFilesInspector) {
223 props.onOpenFilesInspector();
224 return;
225 }
226 navigation.navigate("ThreadFiles", {
227 environmentId: String(environmentId),
228 threadId: String(threadId),
229 });
230 };
231
232 const openReview = () => {
233 navigation.navigate("ThreadReview", {
234 environmentId: EnvironmentId.make(String(environmentId)),
235 threadId: ThreadId.make(String(threadId)),
236 });
237 };
238
239 const openGitInspector = () => {
240 if (props.onOpenGitInspector) {
241 props.onOpenGitInspector();
242 return;
243 }
244 navigation.navigate("GitOverview", {
245 environmentId: String(environmentId),
246 threadId: String(threadId),
247 });
248 };
249
250 return {
251 currentBranchLabel,
252 isRepo,
253 openFiles,
254 openGitInspector,
255 openReview,
256 quickAction,
257 quickActionHint,
258 quickActionIcon,
259 runQuickAction,
260 };
261}
262
263function useThreadGitHeaderActionItems(props: ThreadGitControlsProps): ThreadGitHeaderActionItems {
264 const model = useThreadGitControlModel(props);
265
266 return {
267 terminal: {
268 accessibilityLabel: "Open terminal",
269 disabled: !props.canOpenTerminal,
270 icon: { name: "terminal", type: "sfSymbol" },
271 identifier: "thread-right-terminal",
272 label: "Terminal",
273 menu: {
274 items: [
275 ...props.projectScripts.map((script) => ({
276 description: script.command,
277 disabled: !props.canOperateTerminal,
278 icon: { name: projectScriptMenuIcon(script.icon), type: "sfSymbol" as const },
279 label: projectScriptMenuLabel(script),
280 onPress: () => void props.onRunProjectScript(script),
281 type: "action" as const,
282 })),
283 ...(props.projectScripts.length === 0
284 ? [
285 {
286 description: "This project has no saved scripts yet",
287 disabled: true,
288 icon: { name: "play", type: "sfSymbol" as const },
289 label: "No project scripts",
290 onPress: () => {},
291 type: "action" as const,
292 },
293 ]
294 : []),
295 ...props.terminalSessions.map((session) => ({
296 description: [
297 getTerminalStatusLabel({
298 status: session.status,
299 hasRunningSubprocess: session.hasRunningSubprocess,
300 }),
301 basename(session.cwd),
302 ]
303 .filter(Boolean)
304 .join(" · "),
305 icon: { name: "terminal", type: "sfSymbol" as const },
306 label: session.displayLabel,
307 onPress: () => props.onOpenTerminal(session.terminalId),
308 type: "action" as const,
309 })),
310 {
311 description: "Start another shell for this thread",
312 disabled: !props.canOperateTerminal,
313 icon: { name: "plus", type: "sfSymbol" },
314 label: "Open new terminal",
315 onPress: props.onOpenNewTerminal,
316 type: "action",
317 },
318 ],
319 title: "Terminal",
320 },
321 sharesBackground: true,
322 type: "menu",
323 variant: "plain",
324 },
325 files: {
326 accessibilityLabel: "Open files",
327 disabled: !props.canOpenFiles,
328 icon: { name: "folder", type: "sfSymbol" },
329 identifier: "thread-right-files",
330 label: "Files",
331 onPress: model.openFiles,
332 sharesBackground: true,
333 type: "button",
334 variant: "plain",
335 },
336 git: {
337 accessibilityLabel: "Git actions",
338 icon: { name: "point.topleft.down.curvedto.point.bottomright.up", type: "sfSymbol" },
339 identifier: "thread-right-git",
340 label: "Git",
341 menu: {
342 items: [
343 {
344 description: compactMenuStatus(props.gitStatus),
345 disabled: true,
346 icon: {
347 name: "point.topleft.down.curvedto.point.bottomright.up",
348 type: "sfSymbol",
349 },
350 label: compactMenuBranchLabel(model.currentBranchLabel),
351 onPress: (): void => {},
352 type: "action",
353 },
354 {
355 description: model.quickActionHint ?? undefined,
356 disabled: model.quickAction.disabled,
357 icon: { name: model.quickActionIcon, type: "sfSymbol" },
358 label: model.quickAction.label,
359 onPress: (): void => void model.runQuickAction(),
360 type: "action",
361 },
362 {
363 description: "Turn diffs and worktree changes",
364 disabled: !model.isRepo,
365 icon: { name: "text.bubble", type: "sfSymbol" },
366 label: "Review changes",
367 onPress: model.openReview,
368 type: "action",
369 },
370 ...(props.onMergeBack
371 ? [
372 {
373 description: "Bring this thread's latest turn into its source",
374 icon: { name: PullRequestGlyph.merged, type: "sfSymbol" as const },
375 label: "Merge back to source",
376 onPress: props.onMergeBack,
377 type: "action" as const,
378 },
379 ]
380 : []),
381 {
382 description: "Commit, files, branches",
383 icon: { name: "ellipsis", type: "sfSymbol" },
384 label: "More",
385 onPress: model.openGitInspector,
386 type: "action",
387 },
388 ],
389 title: "Git",
390 },
391 sharesBackground: true,
392 type: "menu",
393 variant: "plain",
394 },
395 };
396}
397
398export function useThreadGitRightHeaderItems(props: ThreadGitControlsProps): HeaderItems {
399 const actionItems = useThreadGitHeaderActionItems(props);
400 return [actionItems.git, actionItems.files, actionItems.terminal] as HeaderItems;
401}
402
403export function useThreadGitCenterHeaderItems(props: ThreadGitControlsProps): HeaderItems {
404 const actionItems = useThreadGitHeaderActionItems(props);
405 return [actionItems.files, actionItems.git, actionItems.terminal] as HeaderItems;
406}
407
408export function ThreadGitControls(props: ThreadGitControlsProps) {
409 const model = useThreadGitControlModel(props);
410 const showActionControls = props.showActionControls ?? true;
411
412 if (!showActionControls) {
413 return null;
414 }
415
416 return (
417 <Toolbar placement="right">
418 {showActionControls && props.auxiliaryPaneControl ? (
419 <Toolbar.Button
420 accessibilityLabel={props.auxiliaryPaneControl.accessibilityLabel}
421 icon="sidebar.right"
422 onPress={props.auxiliaryPaneControl.onPress}
423 separateBackground
424 />
425 ) : null}
426 {showActionControls ? (
427 <Toolbar.Menu
428 accessibilityLabel="Open terminal"
429 icon="terminal"
430 disabled={!props.canOpenTerminal}
431 separateBackground
432 >
433 {props.projectScripts.length > 0 ? (
434 props.projectScripts.map((script) => (
435 <Toolbar.MenuAction
436 key={script.id}
437 icon={projectScriptMenuIcon(script.icon)}
438 disabled={!props.canOperateTerminal}
439 onPress={() => void props.onRunProjectScript(script)}
440 subtitle={script.command}
441 >
442 <Toolbar.Label>{projectScriptMenuLabel(script)}</Toolbar.Label>
443 </Toolbar.MenuAction>
444 ))
445 ) : (
446 <Toolbar.MenuAction
447 icon="play"
448 disabled
449 onPress={() => {}}
450 subtitle="This project has no saved scripts yet"
451 >
452 <Toolbar.Label>No project scripts</Toolbar.Label>
453 </Toolbar.MenuAction>
454 )}
455 {props.terminalSessions.map((session) => (
456 <Toolbar.MenuAction
457 key={session.terminalId}
458 icon="terminal"
459 onPress={() => props.onOpenTerminal(session.terminalId)}
460 subtitle={[
461 getTerminalStatusLabel({
462 status: session.status,
463 hasRunningSubprocess: session.hasRunningSubprocess,
464 }),
465 basename(session.cwd),
466 ]
467 .filter(Boolean)
468 .join(" · ")}
469 >
470 <Toolbar.Label>{session.displayLabel}</Toolbar.Label>
471 </Toolbar.MenuAction>
472 ))}
473 <Toolbar.MenuAction
474 icon="plus"
475 disabled={!props.canOperateTerminal}
476 onPress={props.onOpenNewTerminal}
477 subtitle="Start another shell for this thread"
478 >
479 <Toolbar.Label>Open new terminal</Toolbar.Label>
480 </Toolbar.MenuAction>
481 </Toolbar.Menu>
482 ) : null}
483 {showActionControls && props.showDirectFileControl ? (
484 <Toolbar.Button
485 accessibilityLabel="Open files"
486 disabled={!props.canOpenFiles}
487 icon="folder"
488 onPress={model.openFiles}
489 separateBackground
490 />
491 ) : null}
492 {showActionControls ? createNativeHeaderMenu(threadGitMenuDefinition(props, model)) : null}
493 </Toolbar>
494 );
495}
496
497/**
498 * The standalone git actions menu (branch status, quick commit/push action,
499 * review, more). Rendered inside a Toolbar by both the thread
500 * chat header and the review screen's toolbar.
501 */
502export function ThreadGitMenu(props: ThreadGitMenuProps) {
503 const menu = useThreadGitMenuDefinition(props);
504 return menu ? createNativeHeaderMenu(menu) : null;
505}
506
507/** Returns menu data because native toolbars serialize direct items rather than rendering component children. */
508export function useThreadGitMenuDefinition(props: ThreadGitMenuProps): AppBarMenu | null {
509 return threadGitMenuDefinition(props, useThreadGitControlModel(props));
510}
511
512function threadGitMenuDefinition(
513 props: ThreadGitMenuProps,
514 model: ReturnType<typeof useThreadGitControlModel>,
515): AppBarMenu {
516 return {
517 title: "Git controls",
518 icon: "point.topleft.down.curvedto.point.bottomright.up",
519 separateBackground: false,
520 items: [
521 {
522 id: "git-status",
523 title: compactMenuBranchLabel(model.currentBranchLabel),
524 icon: "point.topleft.down.curvedto.point.bottomright.up",
525 disabled: true,
526 subtitle: compactMenuStatus(props.gitStatus),
527 onPress: () => {},
528 },
529 {
530 id: "git-quick-action",
531 title: model.quickAction.label,
532 icon: model.quickActionIcon,
533 disabled: model.quickAction.disabled,
534 subtitle: model.quickActionHint ?? undefined,
535 onPress: () => {
536 void model.runQuickAction();
537 },
538 },
539 {
540 id: "git-review",
541 title: "Review changes",
542 icon: "text.bubble",
543 disabled: !model.isRepo,
544 subtitle: "Turn diffs and worktree changes",
545 onPress: model.openReview,
546 },
547 {
548 id: "git-more",
549 title: "More",
550 icon: "ellipsis",
551 subtitle: "Commit, files, branches",
552 onPress: model.openGitInspector,
553 },
554 ],
555 };
556}