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

ThreadGitControls.tsx

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