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