Open History to see the last commit
1import type {
2 EnvironmentId,
3 GitRunStackedActionResult,
4 ProjectScript,
5 ThreadId,
6 VcsStatusResult,
7} from "@t3tools/contracts";
8import {
9 type GitActionRequestInput,
10 requiresDefaultBranchConfirmation,
11 resolveQuickAction,
12} from "@t3tools/client-runtime";
13import { useLocalSearchParams, useRouter } from "expo-router";
14import Stack from "expo-router/stack";
15import { useCallback, useMemo } from "react";
16import { Alert, Linking } from "react-native";
17import { buildThreadReviewRoutePath } from "../../lib/routes";
18import {
19 basename,
20 getTerminalStatusLabel,
21 projectScriptMenuIcon,
22 projectScriptMenuLabel,
23 type TerminalMenuSession,
24} from "../terminal/terminalMenu";
25
26function truncateMiddle(value: string, maxLength: number): string {
27 if (value.length <= maxLength) {
28 return value;
29 }
30
31 const headLength = Math.ceil((maxLength - 1) / 2);
32 const tailLength = Math.floor((maxLength - 1) / 2);
33 return `${value.slice(0, headLength)}…${value.slice(value.length - tailLength)}`;
34}
35
36function compactMenuBranchLabel(branch: string): string {
37 return truncateMiddle(branch, 24);
38}
39
40function compactMenuStatus(gitStatus: VcsStatusResult | null): string {
41 if (!gitStatus) {
42 return "Checking status";
43 }
44 if (!gitStatus.isRepo) {
45 return "Not a repo";
46 }
47
48 const parts: string[] = [];
49 if (gitStatus.hasWorkingTreeChanges) {
50 parts.push(`${gitStatus.workingTree.files.length} changed`);
51 } else if (gitStatus.aheadCount === 0 && gitStatus.behindCount === 0) {
52 parts.push("Clean");
53 }
54 if (gitStatus.aheadCount > 0) {
55 parts.push(`${gitStatus.aheadCount} ahead`);
56 }
57 if (gitStatus.behindCount > 0) {
58 parts.push(`${gitStatus.behindCount} behind`);
59 }
60 if (gitStatus.pr?.state === "open") {
61 parts.push(`PR #${gitStatus.pr.number}`);
62 }
63
64 return parts.join(" · ");
65}
66
67export function ThreadGitControls(props: {
68 readonly currentBranch: string | null;
69 readonly gitStatus: VcsStatusResult | null;
70 readonly gitOperationLabel: string | null;
71 readonly canOpenTerminal: boolean;
72 readonly projectScripts: ReadonlyArray<ProjectScript>;
73 readonly terminalSessions: ReadonlyArray<TerminalMenuSession>;
74 readonly onOpenTerminal: (terminalId?: string | null) => void;
75 readonly onOpenNewTerminal: () => void;
76 readonly onRunProjectScript: (script: ProjectScript) => Promise<void>;
77 readonly onPull: () => Promise<void>;
78 readonly onRunAction: (input: GitActionRequestInput) => Promise<GitRunStackedActionResult | null>;
79}) {
80 const router = useRouter();
81 const { environmentId, threadId } = useLocalSearchParams<{
82 environmentId: EnvironmentId;
83 threadId: ThreadId;
84 }>();
85 const { gitStatus, gitOperationLabel, onPull, onRunAction } = props;
86
87 const currentBranchLabel = gitStatus?.refName ?? props.currentBranch ?? "Detached HEAD";
88 const busy = gitOperationLabel !== null;
89 const isRepo = gitStatus?.isRepo ?? true;
90 const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
91 const isDefaultRef = gitStatus?.isDefaultRef ?? false;
92
93 const quickAction = useMemo(
94 () =>
95 isRepo
96 ? resolveQuickAction(gitStatus, busy, isDefaultRef, hasPrimaryRemote)
97 : {
98 label: "Git unavailable",
99 disabled: true,
100 kind: "show_hint" as const,
101 hint: "This workspace is not a git repository.",
102 },
103 [busy, gitStatus, hasPrimaryRemote, isDefaultRef, isRepo],
104 );
105
106 const quickActionHint = quickAction.disabled
107 ? (quickAction.hint ?? "This action is unavailable.")
108 : null;
109
110 const quickActionIcon = (() => {
111 if (quickAction.kind === "run_pull") return "arrow.down.circle";
112 if (quickAction.kind === "open_pr") return "arrow.up.right.circle";
113 if (quickAction.kind === "run_action") {
114 if (quickAction.action === "commit") return "checkmark.circle";
115 if (quickAction.action === "push" || quickAction.action === "commit_push")
116 return "arrow.up.circle";
117 }
118 return "arrow.up.right.circle";
119 })();
120
121 const openExistingPr = useCallback(async () => {
122 const prUrl = gitStatus?.pr?.state === "open" ? gitStatus.pr.url : null;
123 if (!prUrl) {
124 Alert.alert("No open PR", "This branch does not have an open pull request.");
125 return;
126 }
127 try {
128 await Linking.openURL(prUrl);
129 } catch (error) {
130 Alert.alert(
131 "Unable to open PR",
132 error instanceof Error ? error.message : "An error occurred.",
133 );
134 }
135 }, [gitStatus]);
136
137 const runActionWithPrompt = useCallback(
138 async (input: GitActionRequestInput) => {
139 const confirmableAction =
140 input.action === "push" ||
141 input.action === "create_pr" ||
142 input.action === "commit_push" ||
143 input.action === "commit_push_pr"
144 ? input.action
145 : null;
146 const branchName = gitStatus?.refName;
147 if (
148 branchName &&
149 confirmableAction &&
150 !input.featureBranch &&
151 requiresDefaultBranchConfirmation(input.action, isDefaultRef)
152 ) {
153 router.push({
154 pathname: "/threads/[environmentId]/[threadId]/git-confirm",
155 params: {
156 environmentId,
157 threadId,
158 confirmAction: confirmableAction,
159 branchName,
160 includesCommit: String(
161 input.action === "commit_push" || input.action === "commit_push_pr",
162 ),
163 },
164 });
165 return;
166 }
167
168 await onRunAction(input);
169 },
170 [environmentId, gitStatus, isDefaultRef, onRunAction, router, threadId],
171 );
172
173 const runQuickAction = useCallback(async () => {
174 if (quickAction.kind === "open_pr") {
175 await openExistingPr();
176 return;
177 }
178 if (quickAction.kind === "run_pull") {
179 await onPull();
180 return;
181 }
182 if (quickAction.kind === "run_action" && quickAction.action) {
183 await runActionWithPrompt({ action: quickAction.action });
184 }
185 }, [onPull, openExistingPr, quickAction, runActionWithPrompt]);
186
187 return (
188 <Stack.Toolbar placement="right">
189 <Stack.Toolbar.Menu icon="terminal" disabled={!props.canOpenTerminal} separateBackground>
190 {props.projectScripts.length > 0 ? (
191 props.projectScripts.map((script) => (
192 <Stack.Toolbar.MenuAction
193 key={script.id}
194 icon={projectScriptMenuIcon(script.icon)}
195 onPress={() => void props.onRunProjectScript(script)}
196 subtitle={script.command}
197 >
198 <Stack.Toolbar.Label>{projectScriptMenuLabel(script)}</Stack.Toolbar.Label>
199 </Stack.Toolbar.MenuAction>
200 ))
201 ) : (
202 <Stack.Toolbar.MenuAction
203 icon="play"
204 disabled
205 onPress={() => {}}
206 subtitle="This project has no saved scripts yet"
207 >
208 <Stack.Toolbar.Label>No project scripts</Stack.Toolbar.Label>
209 </Stack.Toolbar.MenuAction>
210 )}
211 {props.terminalSessions.map((session) => (
212 <Stack.Toolbar.MenuAction
213 key={session.terminalId}
214 icon="terminal"
215 onPress={() => props.onOpenTerminal(session.terminalId)}
216 subtitle={[
217 getTerminalStatusLabel({
218 status: session.status,
219 hasRunningSubprocess: session.hasRunningSubprocess,
220 }),
221 basename(session.cwd),
222 ]
223 .filter(Boolean)
224 .join(" · ")}
225 >
226 <Stack.Toolbar.Label>{session.displayLabel}</Stack.Toolbar.Label>
227 </Stack.Toolbar.MenuAction>
228 ))}
229 <Stack.Toolbar.MenuAction
230 icon="plus"
231 onPress={props.onOpenNewTerminal}
232 subtitle="Start another shell for this thread"
233 >
234 <Stack.Toolbar.Label>Open new terminal</Stack.Toolbar.Label>
235 </Stack.Toolbar.MenuAction>
236 </Stack.Toolbar.Menu>
237 <Stack.Toolbar.Menu icon="point.topleft.down.curvedto.point.bottomright.up">
238 <Stack.Toolbar.MenuAction
239 icon="point.topleft.down.curvedto.point.bottomright.up"
240 disabled
241 onPress={() => {}}
242 subtitle={compactMenuStatus(gitStatus)}
243 >
244 <Stack.Toolbar.Label>{compactMenuBranchLabel(currentBranchLabel)}</Stack.Toolbar.Label>
245 </Stack.Toolbar.MenuAction>
246 <Stack.Toolbar.MenuAction
247 icon={quickActionIcon}
248 disabled={quickAction.disabled}
249 onPress={() => void runQuickAction()}
250 subtitle={quickActionHint ?? undefined}
251 >
252 <Stack.Toolbar.Label>{quickAction.label}</Stack.Toolbar.Label>
253 </Stack.Toolbar.MenuAction>
254 <Stack.Toolbar.MenuAction
255 icon="text.bubble"
256 disabled={!isRepo}
257 onPress={() => router.push(buildThreadReviewRoutePath({ environmentId, threadId }))}
258 subtitle="Turn diffs and worktree changes"
259 >
260 <Stack.Toolbar.Label>Review changes</Stack.Toolbar.Label>
261 </Stack.Toolbar.MenuAction>
262 <Stack.Toolbar.MenuAction
263 icon="ellipsis.circle"
264 onPress={() =>
265 router.push({
266 pathname: "/threads/[environmentId]/[threadId]/git",
267 params: { environmentId, threadId },
268 })
269 }
270 subtitle="Commit, files, branches"
271 >
272 <Stack.Toolbar.Label>More</Stack.Toolbar.Label>
273 </Stack.Toolbar.MenuAction>
274 </Stack.Toolbar.Menu>
275 </Stack.Toolbar>
276 );
277}