Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadGitControls.tsx

599 lines19.4 KB

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)}`;
40​
41function compactMenuBranchLabel(branch: string): string {
42 return truncateMiddle(branch, 24);
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(" · ");
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 = 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 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 }, [gitStatus, openPullRequest]);
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 };
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 );
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 );
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 );
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 <Toolbar placement="right">
461 {showActionControls && props.auxiliaryPaneControl ? (
462 <Toolbar.Button
463 accessibilityLabel={props.auxiliaryPaneControl.accessibilityLabel}
464 icon="sidebar.right"
465 onPress={props.auxiliaryPaneControl.onPress}
466 separateBackground
467 />
468 ) : null}
469 {showActionControls ? (
470 <Toolbar.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 <Toolbar.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 <Toolbar.Label>{projectScriptMenuLabel(script)}</Toolbar.Label>
486 </Toolbar.MenuAction>
487 ))
488 ) : (
489 <Toolbar.MenuAction
490 icon="play"
491 disabled
492 onPress={() => {}}
493 subtitle="This project has no saved scripts yet"
494 >
495 <Toolbar.Label>No project scripts</Toolbar.Label>
496 </Toolbar.MenuAction>
497 )}
498 {props.terminalSessions.map((session) => (
499 <Toolbar.MenuAction
500 key={session.terminalId}
501 icon="terminal"
502 onPress={() => props.onOpenTerminal(session.terminalId)}
503 subtitle={[
504 getTerminalStatusLabel({
505 status: session.status,
506 hasRunningSubprocess: session.hasRunningSubprocess,
507 }),
508 basename(session.cwd),
509 ]
510 .filter(Boolean)
511 .join(" · ")}
512 >
513 <Toolbar.Label>{session.displayLabel}</Toolbar.Label>
514 </Toolbar.MenuAction>
515 ))}
516 <Toolbar.MenuAction
517 icon="plus"
518 disabled={!props.canOperateTerminal}
519 onPress={props.onOpenNewTerminal}
520 subtitle="Start another shell for this thread"
521 >
522 <Toolbar.Label>Open new terminal</Toolbar.Label>
523 </Toolbar.MenuAction>
524 </Toolbar.Menu>
525 ) : null}
526 {showActionControls && props.showDirectFileControl ? (
527 <Toolbar.Button
528 accessibilityLabel="Open files"
529 disabled={!props.canOpenFiles}
530 icon="folder"
531 onPress={model.openFiles}
532 separateBackground
533 />
534 ) : null}
535 {showActionControls ? createNativeHeaderMenu(threadGitMenuDefinition(props, model)) : null}
536 </Toolbar>
537 );
539​
540/**
541 * The standalone git actions menu (branch status, quick commit/push action,
542 * review, more). Rendered inside a Toolbar by both the thread
543 * chat header and the review screen's toolbar.
544 */
545export function ThreadGitMenu(props: ThreadGitMenuProps) {
546 const menu = useThreadGitMenuDefinition(props);
547 return menu ? createNativeHeaderMenu(menu) : null;
549​
550/** Returns menu data because native toolbars serialize direct items rather than rendering component children. */
551export function useThreadGitMenuDefinition(props: ThreadGitMenuProps): AppBarMenu | null {
552 return threadGitMenuDefinition(props, useThreadGitControlModel(props));
554​
555function threadGitMenuDefinition(
556 props: ThreadGitMenuProps,
557 model: ReturnType<typeof useThreadGitControlModel>,
558): AppBarMenu {
559 return {
560 title: "Git controls",
561 icon: "point.topleft.down.curvedto.point.bottomright.up",
562 separateBackground: false,
563 items: [
564 {
565 id: "git-status",
566 title: compactMenuBranchLabel(model.currentBranchLabel),
567 icon: "point.topleft.down.curvedto.point.bottomright.up",
568 disabled: true,
569 subtitle: compactMenuStatus(props.gitStatus),
570 onPress: () => {},
571 },
572 {
573 id: "git-quick-action",
574 title: model.quickAction.label,
575 icon: model.quickActionIcon,
576 disabled: model.quickAction.disabled,
577 subtitle: model.quickActionHint ?? undefined,
578 onPress: () => {
579 void model.runQuickAction();
580 },
581 },
582 {
583 id: "git-review",
584 title: "Review changes",
585 icon: "text.bubble",
586 disabled: !model.isRepo,
587 subtitle: "Turn diffs and worktree changes",
588 onPress: model.openReview,
589 },
590 {
591 id: "git-more",
592 title: "More",
593 icon: "ellipsis",
594 subtitle: "Commit, files, branches",
595 onPress: model.openGitInspector,
596 },
597 ],
598 };