@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 2,111 lines 79.8 KB
Raw
1 import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2 import { sourceControlInstallHintText } from "@t3tools/client-runtime/contract-labels";
3 import { msg, T, useGT, useMessages, Var } from "gt-react";
4 import { m, type MessageResolver } from "../i18n/messages";
5 import { changeRequestTermKind } from "./pullRequest/changeRequestTerm";
6 import { ThreadDetailsControl } from "./chat/ThreadDetailsControl";
7 import { useAtomMount, useAtomValue } from "@effect/atom-react";
8 import {
9 AuthOrchestrationOperateScope,
10 AuthSourceControlWriteScope,
11 SourceControlProviderKind,
12 type ScopedThreadRef,
13 } from "@t3tools/contracts";
14 import {
15 isAtomCommandInterrupted,
16 squashAtomCommandFailure,
17 } from "@t3tools/client-runtime/state/runtime";
18 import type {
19 GitRunStackedActionResult,
20 GitStackedAction,
21 SourceControlCloneProtocol,
22 SourceControlProviderDiscoveryItem,
23 SourceControlPublishRepositoryResult,
24 SourceControlRepositoryVisibility,
25 VcsStatusResult,
26 } from "@t3tools/contracts";
27 import { useNavigate } from "@tanstack/react-router";
28 import * as Option from "effect/Option";
29 import { memo, useEffect, useEffectEvent, useId, useRef, useState } from "react";
30 import { useDeadlinePassed } from "../hooks/useDeadline";
31 import { useNowSecond } from "../hooks/useNowSecond";
32 import { flushSync } from "react-dom";
33 import {
34 CheckIcon,
35 ChevronDownIcon,
36 CloudDownloadIcon,
37 CloudUploadIcon,
38 FileDiffIcon,
39 GitBranchPlusIcon,
40 GitCommitIcon,
41 InfoIcon,
42 LockIcon,
43 GlobeIcon,
44 } from "lucide-react";
45 import { Radio as RadioPrimitive } from "@base-ui/react/radio";
46 import { RadioGroup } from "~/components/ui/radio-group";
47 import { Spinner } from "~/components/ui/spinner";
48 import { Toggle, ToggleGroup } from "~/components/ui/toggle-group";
49 import { cn } from "~/lib/utils";
50 import {
51 buildMenuItems,
52 formatGitActionElapsed,
53 GIT_ACTION_SUCCESS_VISIBLE_MS,
54 hasUsableGitMenuContent,
55 type GitActionProgressPresentation,
56 type GitActionIconName,
57 type GitActionMenuItem,
58 type GitQuickAction,
59 type DefaultBranchConfirmableAction,
60 requiresDefaultBranchConfirmation,
61 resolveChangesTotals,
62 resolveDefaultBranchActionDialogCopy,
63 resolveFeatureBranchUnavailableReason,
64 resolveGitActionProgressPresentation,
65 resolveGitActionResultToastTiming,
66 resolveLiveThreadBranchUpdate,
67 getMenuActionDisabledReason,
68 resolveThreadBranchMetadataPatch,
69 resolveQuickAction,
70 resolveThreadBranchUpdate,
71 } from "./GitActionsControl.logic";
72 import { WizardPopup, WizardHeader, WizardSteps, WizardPanel, WizardFooter } from "./ui/wizard";
73 import { StartTruncatedPath } from "./StartTruncatedPath";
74 import { Button } from "~/components/ui/button";
75 import { Checkbox } from "~/components/ui/checkbox";
76 import {
77 Dialog,
78 DialogDescription,
79 DialogFooter,
80 DialogHeader,
81 DialogPanel,
82 DialogPopup,
83 DialogTitle,
84 } from "~/components/ui/dialog";
85 import { Input } from "~/components/ui/input";
86 import { Menu, MenuItem, MenuItemLabel, MenuPopup, MenuTrigger } from "~/components/ui/menu";
87 import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
88 import { ScrollArea } from "~/components/ui/scroll-area";
89 import { Textarea } from "~/components/ui/textarea";
90 import { stackedThreadToast, toastManager } from "~/components/ui/toast";
91 import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
92 import { useOpenInPreferredEditor } from "~/editorPreferences";
93 import {
94 useGitStackedAction,
95 useSourceControlActionRunning,
96 useSourceControlPublishRepositoryAction,
97 useVcsInitAction,
98 useVcsPullAction,
99 } from "../state/sourceControlActions";
100 import { useQuietThreadProjection, useQuietThreadShell } from "~/state/entities";
101 import { useProjectClone } from "~/state/projectClones";
102 import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";
103 import { useEnvironmentQuery } from "~/state/query";
104 import { useFilesystemReadAccess } from "~/state/filesystem";
105 import { reviewEnvironment } from "~/state/review";
106 import { revisionedQuery } from "~/state/revisionedQuery";
107 import {
108 selectThreadBranchBaseRef,
109 useDiffPanelSessionStore,
110 useDiffPanelStore,
111 } from "~/diffPanelStore";
112 import { useClientSettings } from "~/hooks/useSettings";
113 import { serverEnvironment } from "~/state/server";
114 import { sourceControlEnvironment } from "~/state/sourceControl";
115 import { threadEnvironment } from "~/state/threads";
116 import { useAtomCommand } from "~/state/use-atom-command";
117 import { vcsActionManager, vcsEnvironment, vcsStatusRevalidation } from "~/state/vcs";
118 import { randomUUID } from "~/lib/utils";
119 import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
120 import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";
121 import {
122 THREAD_DETAILS_PANEL_CHEVRON_CLASS,
123 THREAD_DETAILS_PANEL_ICON_CLASS,
124 THREAD_DETAILS_PANEL_LABEL_CLASS,
125 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
126 THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS,
127 } from "./chat/threadDetailsPanelStyles";
128 import { getSourceControlPresentation, sourceControlIcon } from "~/sourceControlPresentation";
129 import {
130 isSourceControlProviderOffered,
131 type OfferedSourceControlProviders,
132 } from "@t3tools/client-runtime/operations/projects";
133 import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
134 import { scopeProjectRef } from "@t3tools/client-runtime/environment";
135 import { formatDiffCount } from "@t3tools/client-runtime/diff-count";
136 import { ChangeBreakdownGrid } from "./pullRequest/ChangeBreakdownGrid";
137 import { useOpenLink } from "~/browser/useOpenLink";
138
139 interface GitActionsControlProps {
140 gitCwd: string | null;
141 activeThreadRef: ScopedThreadRef | null;
142 draftId?: DraftId;
143 compact?: boolean;
144 showActions?: boolean;
145 showChanges?: boolean;
146 onOpenChanges?: () => void;
147 workspaceMutationId?: string | null;
148 }
149
150 interface PendingDefaultBranchAction {
151 action: DefaultBranchConfirmableAction;
152 branchName: string;
153 includesCommit: boolean;
154 commitMessage?: string;
155 onConfirmed?: () => void;
156 filePaths?: string[];
157 }
158
159 interface RunGitActionWithToastInput {
160 action: GitStackedAction;
161 commitMessage?: string;
162 onConfirmed?: () => void;
163 skipDefaultBranchPrompt?: boolean;
164 statusOverride?: VcsStatusResult | null;
165 featureBranch?: boolean;
166 filePaths?: string[];
167 }
168
169 interface InlineGitActionSuccess {
170 readonly title: string;
171 readonly description: string | null;
172 readonly expiresAtMs: number;
173 }
174
175 const inlineSuccessExpiresAt = () => Date.now() + GIT_ACTION_SUCCESS_VISIBLE_MS;
176
177 type RefreshVcsStatus = (target: {
178 readonly environmentId: ScopedThreadRef["environmentId"];
179 readonly input: { readonly cwd: string };
180 }) => Promise<unknown>;
181
182 function requestVcsStatusRefresh(
183 refresh: RefreshVcsStatus,
184 environmentId: ScopedThreadRef["environmentId"] | null,
185 cwd: string | null,
186 ): void {
187 if (environmentId === null || cwd === null) {
188 return;
189 }
190 void refresh({ environmentId, input: { cwd } });
191 }
192 const RUNNING_SOURCE_CONTROL_ACTIONS = ["runStackedAction", "pull", "publishRepository"] as const;
193
194 const PUBLISH_PROVIDER_OPTIONS = sourceControlClients.definitions.map((definition) => ({
195 value: definition.kind,
196 label: definition.pickerLabel,
197 description: definition.publishDescription,
198 pathPlaceholder: definition.repositoryPathHint,
199 definition,
200 Icon: sourceControlIcon(definition),
201 }));
202
203 function publishProviderOption(provider: SourceControlProviderKind) {
204 return (
205 PUBLISH_PROVIDER_OPTIONS.find((option) => option.value === provider) ??
206 PUBLISH_PROVIDER_OPTIONS[0]!
207 );
208 }
209
210 function getPublishProviderReadiness(
211 input: {
212 provider: SourceControlProviderKind;
213 sourceControlProviders: ReadonlyArray<SourceControlProviderDiscoveryItem>;
214 },
215 resolve: MessageResolver = m,
216 ): { readonly ready: boolean; readonly hint: string | null } {
217 const discovered = input.sourceControlProviders.find(
218 (provider) => provider.kind === input.provider,
219 );
220 if (!discovered) {
221 return {
222 ready: false,
223 hint: resolve(
224 msg("Provider status unavailable. Open Settings -> Source control & issues and rescan."),
225 ),
226 };
227 }
228 if (discovered.status !== "available") {
229 return { ready: false, hint: sourceControlInstallHintText(discovered.installHint, resolve) };
230 }
231 if (discovered.auth.status === "unauthenticated") {
232 return {
233 ready: false,
234 hint:
235 Option.getOrNull(discovered.auth.detail) ??
236 resolve(
237 msg(
238 "{provider} is not authenticated. Open Settings -> Source control & issues for setup guidance.",
239 {
240 provider: discovered.label,
241 },
242 ),
243 ),
244 };
245 }
246 return { ready: true, hint: null };
247 }
248
249 const COMMIT_DIALOG_TITLE = msg("Commit changes");
250 const COMMIT_DIALOG_DESCRIPTION = msg(
251 "Review and confirm your commit. Leave the message blank to auto-generate one.",
252 );
253
254 function GitActionItemIcon({
255 icon,
256 SourceControlIcon,
257 }: {
258 icon: GitActionIconName;
259 SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
260 }) {
261 if (icon === "commit") return <GitCommitIcon />;
262 if (icon === "push") return <CloudUploadIcon />;
263 return <SourceControlIcon />;
264 }
265
266 function GitQuickActionIcon({
267 quickAction,
268 SourceControlIcon,
269 className = "size-3.5",
270 }: {
271 quickAction: GitQuickAction;
272 className?: string;
273 SourceControlIcon: ReturnType<typeof getSourceControlPresentation>["Icon"];
274 }) {
275 const messages = useMessages();
276 if (quickAction.kind === "open_publish") return <CloudUploadIcon className={className} />;
277 if (quickAction.kind === "run_pull") return <CloudDownloadIcon className={className} />;
278 if (quickAction.kind === "run_action") {
279 if (quickAction.action === "commit") return <GitCommitIcon className={className} />;
280 if (quickAction.action === "push" || quickAction.action === "commit_push") {
281 return <CloudUploadIcon className={className} />;
282 }
283 return <SourceControlIcon className={className} />;
284 }
285 // show_hint carries no action, so match the label resolveQuickAction gave it.
286 if (quickAction.label === messages(msg("Commit", { $context: "verb, git action" }))) {
287 return <GitCommitIcon className={className} />;
288 }
289 if (quickAction.label === messages(msg("Push", { $context: "verb, git action" }))) {
290 return <CloudUploadIcon className={className} />;
291 }
292 return <InfoIcon className={className} />;
293 }
294
295 function GitActionElapsedTime({
296 startedAtMs,
297 className,
298 }: {
299 startedAtMs: number | null;
300 className?: string;
301 }) {
302 return startedAtMs === null ? null : (
303 <RunningGitActionElapsedTime startedAtMs={startedAtMs} className={className} />
304 );
305 }
306
307 function RunningGitActionElapsedTime({
308 startedAtMs,
309 className,
310 }: {
311 startedAtMs: number;
312 className: string | undefined;
313 }) {
314 const messages = useMessages();
315 const nowMs = useNowSecond();
316 const elapsed = formatGitActionElapsed(startedAtMs, nowMs, messages);
317 if (!elapsed) {
318 return null;
319 }
320
321 return (
322 <p aria-live="off" className={className}>
323 {elapsed}
324 </p>
325 );
326 }
327
328 function GitActionProgressButtonContent({
329 progress,
330 id,
331 }: {
332 progress: GitActionProgressPresentation;
333 id: string;
334 }) {
335 const hasOutput = progress.output !== null;
336
337 return (
338 <div
339 id={id}
340 aria-atomic="false"
341 aria-live="polite"
342 className={cn(
343 "grid min-w-0 flex-1 items-center",
344 "grid-cols-[auto_minmax(0,1fr)_auto] grid-rows-[1.125rem] gap-x-3",
345 )}
346 role="status"
347 >
348 <Spinner aria-hidden="true" className="row-start-1 -mx-0.5 shrink-0" />
349 <p
350 className={cn(
351 "row-start-1 min-w-0 self-baseline truncate text-left",
352 THREAD_DETAILS_PANEL_LABEL_CLASS,
353 )}
354 >
355 {progress.status}
356 </p>
357 <GitActionElapsedTime
358 startedAtMs={progress.startedAtMs}
359 className="col-start-3 row-start-1 self-baseline text-2xs font-normal tabular-nums text-muted-foreground"
360 />
361 <div
362 className={cn(
363 "col-start-2 grid min-w-0 transition-[grid-template-rows,opacity] duration-200 ease-out motion-reduce:transition-none",
364 hasOutput ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
365 )}
366 >
367 <div className="min-h-0 overflow-hidden">
368 <Tooltip>
369 <TooltipTrigger
370 render={
371 <p className="truncate pt-0.5 text-left text-2xs font-normal text-muted-foreground" />
372 }
373 >
374 {progress.output}
375 </TooltipTrigger>
376 <TooltipPopup side="bottom" className="max-w-96 break-words">
377 {progress.output}
378 </TooltipPopup>
379 </Tooltip>
380 </div>
381 </div>
382 </div>
383 );
384 }
385
386 function GitActionSuccessButtonContent({ success }: { success: InlineGitActionSuccess }) {
387 const hasDescription = success.description !== null;
388
389 return (
390 <div
391 aria-live="polite"
392 className="grid min-w-0 flex-1 grid-cols-[auto_minmax(0,1fr)] grid-rows-[1.125rem] items-center gap-x-3"
393 role="status"
394 >
395 <CheckIcon aria-hidden="true" className="size-3.5 shrink-0 text-success" />
396 <p className={cn("min-w-0 truncate text-left", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
397 {success.title}
398 </p>
399 <div
400 className={cn(
401 "col-start-2 grid min-w-0 transition-[grid-template-rows,opacity] duration-200 ease-out motion-reduce:transition-none",
402 hasDescription ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0",
403 )}
404 >
405 <div className="min-h-0 overflow-hidden">
406 <Tooltip>
407 <TooltipTrigger
408 render={
409 <p className="truncate pt-0.5 text-left text-2xs font-normal text-muted-foreground" />
410 }
411 >
412 {success.description}
413 </TooltipTrigger>
414 <TooltipPopup side="bottom" className="max-w-96 break-words">
415 {success.description}
416 </TooltipPopup>
417 </Tooltip>
418 </div>
419 </div>
420 </div>
421 );
422 }
423
424 interface PublishRepositoryDialogProps {
425 readonly open: boolean;
426 readonly onOpenChange: (open: boolean) => void;
427 readonly environmentId: ScopedThreadRef["environmentId"] | null;
428 readonly threadRef: ScopedThreadRef | null;
429 readonly gitCwd: string;
430 readonly offeredProviders: OfferedSourceControlProviders | undefined;
431 }
432
433 export function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
434 const gt = useGT();
435 const messages = useMessages();
436 const openLink = useOpenLink(props.threadRef);
437 const navigate = useNavigate();
438 const sourceControlDiscovery = useEnvironmentQuery(
439 props.environmentId === null
440 ? null
441 : sourceControlEnvironment.discovery({
442 environmentId: props.environmentId,
443 input: {},
444 }),
445 );
446 const [selectedPublishProvider, setSelectedPublishProvider] =
447 useState<SourceControlProviderKind | null>(null);
448 const [publishRepositoryOverride, setPublishRepositoryOverride] = useState<string | null>(null);
449 const [publishVisibility, setPublishVisibility] =
450 useState<SourceControlRepositoryVisibility>("private");
451 const [publishRemoteName, setPublishRemoteName] = useState("origin");
452 const [publishProtocol, setPublishProtocol] = useState<SourceControlCloneProtocol>("ssh");
453 const [publishWizardStep, setPublishWizardStep] = useState(0);
454 const [publishAdvancedOpen, setPublishAdvancedOpen] = useState(false);
455 const [publishError, setPublishError] = useState<string | null>(null);
456 const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
457 null,
458 );
459 const sourceControlScope = {
460 environmentId: props.environmentId,
461 cwd: props.gitCwd,
462 };
463 const publishRepositoryAction = useSourceControlPublishRepositoryAction(sourceControlScope);
464 const publishAccountByProvider = new Map<string, string | null>();
465 for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
466 publishAccountByProvider.set(provider.kind, Option.getOrNull(provider.auth.account));
467 }
468 const publishSourceControlProviders = sourceControlDiscovery.data?.sourceControlProviders ?? [];
469 const publishReadinessByProvider = new Map(
470 PUBLISH_PROVIDER_OPTIONS.map((option) => [
471 option.value,
472 getPublishProviderReadiness(
473 {
474 provider: option.value,
475 sourceControlProviders: publishSourceControlProviders,
476 },
477 messages,
478 ),
479 ]),
480 );
481 const publishProviderReadiness = (provider: SourceControlProviderKind) =>
482 publishReadinessByProvider.get(provider) ?? { ready: false, hint: null };
483 const offeredPublishProviderOptions = PUBLISH_PROVIDER_OPTIONS.filter((option) =>
484 isSourceControlProviderOffered(props.offeredProviders, option.value),
485 );
486 const hasReadyPublishProvider = offeredPublishProviderOptions.some(
487 (option) => publishProviderReadiness(option.value).ready,
488 );
489 const sortedPublishProviderOptions = offeredPublishProviderOptions.toSorted((left, right) => {
490 const leftReady = publishProviderReadiness(left.value).ready;
491 const rightReady = publishProviderReadiness(right.value).ready;
492 if (leftReady !== rightReady) {
493 return leftReady ? -1 : 1;
494 }
495 return left.label.localeCompare(right.label);
496 });
497 const firstReadyPublishProvider = sortedPublishProviderOptions.find(
498 (option) => publishProviderReadiness(option.value).ready,
499 )?.value;
500 // The dialog stays mounted, so a host turned off after it was picked must not stay selected.
501 const offeredSelection =
502 selectedPublishProvider !== null &&
503 isSourceControlProviderOffered(props.offeredProviders, selectedPublishProvider)
504 ? selectedPublishProvider
505 : null;
506 const publishProvider =
507 offeredSelection !== null && publishProviderReadiness(offeredSelection).ready
508 ? offeredSelection
509 : (firstReadyPublishProvider ?? offeredSelection ?? sourceControlClients.get(undefined).kind);
510 const selectedPublishProviderReadiness = publishProviderReadiness(publishProvider);
511 const publishAccount = publishAccountByProvider.get(publishProvider) ?? null;
512 const publishRepositoryPrefill = publishAccount ? `${publishAccount}/` : "";
513 const publishRepository = publishRepositoryOverride ?? publishRepositoryPrefill;
514 const currentPublishProvider = publishProviderOption(publishProvider);
515 const publishHost = currentPublishProvider.definition.publishHost(
516 Option.getOrNull(
517 sourceControlDiscovery.data?.sourceControlProviders.find(
518 (provider) => provider.kind === publishProvider,
519 )?.auth.host ?? Option.none(),
520 ),
521 );
522 const publishPathPlaceholder = currentPublishProvider.pathPlaceholder;
523 const publishProviderLabel = currentPublishProvider.label;
524 const publishWizardSteps = [gt("Provider"), gt("Repository"), gt("Summary")] as const;
525 const publishWizardStepSummaries = [
526 publishProviderLabel,
527 publishResult?.repository.nameWithOwner ?? null,
528 null,
529 ] as const;
530
531 const publishRepositoryParts = publishRepository.trim().split("/");
532 const publishRepositoryOwner = publishRepositoryParts[0]?.trim() ?? "";
533 const publishRepositoryName = publishRepositoryParts.slice(1).join("/").trim();
534 const canSubmitPublishRepository =
535 publishRepositoryAction.isAllowed &&
536 hasReadyPublishProvider &&
537 selectedPublishProviderReadiness.ready &&
538 !publishRepositoryAction.isPending &&
539 publishRepositoryOwner.length > 0 &&
540 publishRepositoryName.length > 0;
541
542 const submitPublishRepository = () => {
543 if (!canSubmitPublishRepository) {
544 return;
545 }
546
547 setPublishError(null);
548
549 void (async () => {
550 const result = await publishRepositoryAction.run({
551 provider: publishProvider,
552 repository: publishRepository.trim(),
553 visibility: publishVisibility,
554 remoteName: publishRemoteName.trim() || "origin",
555 protocol: publishProtocol,
556 });
557
558 if (result._tag === "Failure") {
559 if (!isAtomCommandInterrupted(result)) {
560 const error = squashAtomCommandFailure(result);
561 setPublishError(thrownErrorMessage(error, m) ?? gt("An error occurred."));
562 }
563 return;
564 }
565
566 flushSync(() => {
567 setPublishResult(result.value);
568 setPublishWizardStep(2);
569 });
570 })();
571 };
572
573 const resetState = () => {
574 setPublishRemoteName("origin");
575 setPublishRepositoryOverride(null);
576 setPublishWizardStep(0);
577 setPublishAdvancedOpen(false);
578 setPublishError(null);
579 setPublishResult(null);
580 };
581
582 const handleOpenChange = (open: boolean) => {
583 props.onOpenChange(open);
584 if (!open) {
585 resetState();
586 }
587 };
588
589 const openSourceControlSettings = () => {
590 handleOpenChange(false);
591 void navigate({ to: "/settings/source-control" });
592 };
593
594 return (
595 <Dialog open={props.open} onOpenChange={handleOpenChange}>
596 <WizardPopup>
597 <WizardHeader
598 title={gt("Publish repository")}
599 description={gt("Pick where to host it, then point us at a repo to push to.")}
600 >
601 <WizardSteps
602 steps={publishWizardSteps}
603 currentStep={publishWizardStep}
604 summaries={publishWizardStepSummaries}
605 showSummaries
606 isStepDisabled={(index) =>
607 publishWizardStep === 2 ||
608 index >= publishWizardSteps.length - 1 ||
609 index > publishWizardStep
610 }
611 onStepChange={setPublishWizardStep}
612 />
613 </WizardHeader>
614
615 <WizardPanel>
616 <div className={cn("space-y-2", publishWizardStep !== 0 && "hidden")}>
617 <span id="publish-provider-cards-label" className="text-xs font-medium text-foreground">
618 <T>Provider</T>
619 </span>
620 <RadioGroup
621 value={publishProvider}
622 onValueChange={(value) => {
623 setSelectedPublishProvider(value as SourceControlProviderKind);
624 setPublishRepositoryOverride(null);
625 }}
626 aria-labelledby="publish-provider-cards-label"
627 className="grid grid-cols-2"
628 >
629 {sortedPublishProviderOptions.map((option) => {
630 const readiness = publishProviderReadiness(option.value);
631 const isSelected = publishProvider === option.value && readiness.ready;
632 if (!readiness.ready) {
633 return (
634 <div
635 key={option.value}
636 className="relative flex cursor-not-allowed items-center gap-3 rounded-lg border border-border bg-background px-3 py-3 text-left opacity-64 dark:border-transparent dark:bg-white/[0.035]"
637 >
638 <option.Icon className="size-5 shrink-0 text-muted-foreground" aria-hidden />
639 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
640 {option.label}
641 </span>
642 <Tooltip>
643 <TooltipTrigger
644 render={
645 <Button
646 variant="warning-outline"
647 size="micro"
648 onClick={(event) => {
649 event.preventDefault();
650 event.stopPropagation();
651 openSourceControlSettings();
652 }}
653 >
654 <T>Setup Required</T>
655 </Button>
656 }
657 />
658 <TooltipPopup side="top" align="end">
659 {readiness.hint ??
660 gt(
661 "Open Settings -> Source control & issues to configure this provider.",
662 )}
663 </TooltipPopup>
664 </Tooltip>
665 </div>
666 );
667 }
668
669 return (
670 <RadioPrimitive.Root
671 key={option.value}
672 value={option.value}
673 className={cn(
674 "relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-3 text-left outline-none transition-[background-color,border-color,box-shadow]",
675 "focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
676 isSelected
677 ? "border-primary bg-background shadow-sm ring-2 ring-inset ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
678 : "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
679 )}
680 >
681 <option.Icon className="size-5 shrink-0" aria-hidden />
682 <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">
683 {option.label}
684 </span>
685 </RadioPrimitive.Root>
686 );
687 })}
688 </RadioGroup>
689 </div>
690
691 <div className={cn("space-y-5", publishWizardStep !== 1 && "hidden")}>
692 <div className="space-y-2">
693 <label
694 htmlFor="publish-repository-path"
695 className="text-xs font-medium text-foreground"
696 >
697 <T>Repository</T>
698 </label>
699 <div className="flex items-stretch overflow-hidden rounded-md border border-input bg-background focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-ring">
700 <span className="flex shrink-0 items-center gap-1.5 border-r border-input bg-muted/50 px-2.5 font-mono text-xs text-muted-foreground">
701 <currentPublishProvider.Icon className="size-3.5" />
702 {publishHost}/
703 </span>
704 <input
705 id="publish-repository-path"
706 name="publish-repository-path"
707 value={publishRepository}
708 onChange={(event) => {
709 setPublishRepositoryOverride(event.target.value);
710 }}
711 onKeyDown={(event) => {
712 if (event.key !== "Enter") {
713 return;
714 }
715 if (event.nativeEvent.isComposing || event.keyCode === 229) {
716 return;
717 }
718 event.preventDefault();
719 submitPublishRepository();
720 }}
721 placeholder={publishPathPlaceholder}
722 disabled={publishRepositoryAction.isPending}
723 className="w-full bg-transparent px-3 py-2 font-mono text-sm placeholder:text-muted-foreground/60 focus:outline-none"
724 />
725 </div>
726 </div>
727
728 <div className="space-y-2">
729 <span
730 id="publish-visibility-cards-label"
731 className="text-xs font-medium text-foreground"
732 >
733 <T>Visibility</T>
734 </span>
735 <RadioGroup
736 value={publishVisibility}
737 onValueChange={(value) =>
738 setPublishVisibility(value as SourceControlRepositoryVisibility)
739 }
740 aria-labelledby="publish-visibility-cards-label"
741 disabled={publishRepositoryAction.isPending}
742 className="grid grid-cols-2"
743 >
744 {[
745 {
746 value: "private" as const,
747 label: gt("Private"),
748 description: gt("Only invited people"),
749 Icon: LockIcon,
750 },
751 {
752 value: "public" as const,
753 label: gt("Public"),
754 description: gt("Anyone on the web"),
755 Icon: GlobeIcon,
756 },
757 ].map((option) => {
758 const isSelected = publishVisibility === option.value;
759 return (
760 <RadioPrimitive.Root
761 key={option.value}
762 value={option.value}
763 className={cn(
764 "relative flex cursor-pointer items-center gap-3 rounded-lg border px-3 py-2.5 text-left outline-none transition-[background-color,border-color,box-shadow]",
765 "focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
766 isSelected
767 ? "border-primary bg-background shadow-sm ring-2 ring-inset ring-primary/35 dark:border-transparent dark:bg-primary/10 dark:shadow-none dark:ring-1 dark:ring-primary/30"
768 : "border-border bg-background hover:border-foreground/20 hover:bg-muted/50 dark:border-transparent dark:bg-white/[0.035] dark:hover:bg-accent",
769 )}
770 >
771 <option.Icon className="size-4 shrink-0 text-muted-foreground" aria-hidden />
772 <span className="min-w-0 flex-1">
773 <span className="block text-sm font-medium text-foreground">
774 {option.label}
775 </span>
776 <span className="block text-xs text-muted-foreground">
777 {option.description}
778 </span>
779 </span>
780 </RadioPrimitive.Root>
781 );
782 })}
783 </RadioGroup>
784 </div>
785
786 <div>
787 <button
788 type="button"
789 onClick={() => setPublishAdvancedOpen((prev) => !prev)}
790 aria-expanded={publishAdvancedOpen}
791 className="flex items-center gap-1 text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"
792 >
793 <ChevronDownIcon
794 className={cn(
795 "size-3.5 transition-transform",
796 publishAdvancedOpen ? "" : "-rotate-90",
797 )}
798 />
799 <T context="publish dialog section of advanced options">Advanced</T>
800 </button>
801 {publishAdvancedOpen ? (
802 <div className="mt-3 grid gap-3 sm:grid-cols-2">
803 <label className="space-y-1.5" htmlFor="publish-remote-name">
804 <span className="text-xs font-medium text-foreground">
805 <T context="git remote name">Remote</T>
806 </span>
807 <Input
808 id="publish-remote-name"
809 value={publishRemoteName}
810 onChange={(event) => setPublishRemoteName(event.target.value)}
811 placeholder="origin"
812 disabled={publishRepositoryAction.isPending}
813 />
814 </label>
815 <div className="space-y-1.5">
816 <span
817 id="publish-protocol-label"
818 className="text-xs font-medium text-foreground"
819 >
820 <T>Protocol</T>
821 </span>
822 <ToggleGroup
823 value={[publishProtocol]}
824 onValueChange={(next) => {
825 const protocol = next[0];
826 if (protocol === "ssh" || protocol === "https") {
827 setPublishProtocol(protocol);
828 }
829 }}
830 aria-labelledby="publish-protocol-label"
831 disabled={publishRepositoryAction.isPending}
832 >
833 <Toggle value="ssh">SSH</Toggle>
834 <Toggle value="https">HTTPS</Toggle>
835 </ToggleGroup>
836 </div>
837 </div>
838 ) : null}
839 </div>
840
841 {publishRepositoryAction.isPending ? (
842 <div
843 role="status"
844 aria-live="polite"
845 className="flex items-center gap-2 rounded-md border border-input bg-muted/40 px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]"
846 >
847 <Spinner size="sm" aria-hidden />
848 <T>
849 Publishing repository to <Var>{publishProviderLabel}</Var>...
850 </T>
851 </div>
852 ) : null}
853 {publishError && !publishRepositoryAction.isPending ? (
854 <div
855 role="alert"
856 className="rounded-md border border-destructive/40 bg-destructive/10 px-3 py-2 text-xs text-destructive"
857 >
858 <p className="font-medium">
859 <T>Publish failed</T>
860 </p>
861 <p className="mt-0.5 text-destructive/90">{publishError}</p>
862 </div>
863 ) : null}
864 </div>
865
866 <div className={cn("space-y-4", publishWizardStep !== 2 && "hidden")}>
867 {publishResult ? (
868 <>
869 <div className="flex flex-col items-center gap-2 py-1 text-center">
870 <span className="grid size-8 place-items-center rounded-full bg-success/15 text-success">
871 <CheckIcon className="size-4" aria-hidden />
872 </span>
873 <h3 className="text-sm font-semibold text-foreground">
874 {publishResult.status === "pushed"
875 ? gt("Repository published")
876 : gt("Repository created")}
877 </h3>
878 <p className="max-w-xs text-pretty text-xs text-muted-foreground">
879 {publishResult.status === "pushed"
880 ? gt("{branch} is now live on {provider}.", {
881 branch: publishResult.branch,
882 provider: publishProviderLabel,
883 })
884 : gt(
885 'Remote "{remote}" is set up. Make a commit and push it to share your code.',
886 { remote: publishResult.remoteName },
887 )}
888 </p>
889 </div>
890 <div className="flex items-center gap-2 rounded-lg border border-input bg-muted/40 px-3 py-2 dark:border-transparent dark:bg-white/[0.035]">
891 <currentPublishProvider.Icon className="size-3.5 shrink-0 text-muted-foreground" />
892 <span className="min-w-0 flex-1 truncate font-mono text-xs text-foreground">
893 {publishResult.repository.nameWithOwner}
894 </span>
895 </div>
896 <Button
897 variant="outline"
898 size="sm"
899 className="w-full"
900 onClick={() => {
901 void openLink(publishResult.repository.url).catch(() => undefined);
902 }}
903 >
904 <T>
905 Open on <Var>{publishProviderLabel}</Var>
906 </T>
907 </Button>
908 </>
909 ) : (
910 <div className="rounded-md border border-input bg-background px-3 py-2 text-xs text-muted-foreground dark:border-transparent dark:bg-white/[0.035]">
911 <T>Publish result unavailable.</T>
912 </div>
913 )}
914 </div>
915 </WizardPanel>
916
917 <WizardFooter>
918 {publishWizardStep === 2 ? (
919 <Button onClick={() => handleOpenChange(false)}>
920 <T context="button, closes the finished publish dialog">Done</T>
921 </Button>
922 ) : (
923 <>
924 <Button
925 variant="outline"
926 disabled={publishRepositoryAction.isPending}
927 onClick={() => {
928 if (publishWizardStep === 0) {
929 handleOpenChange(false);
930 return;
931 }
932 setPublishWizardStep((step) => Math.max(0, step - 1));
933 }}
934 >
935 {publishWizardStep === 0 ? <T>Cancel</T> : <T>Back</T>}
936 </Button>
937 {publishWizardStep < 1 ? (
938 <Button
939 disabled={!hasReadyPublishProvider || !selectedPublishProviderReadiness.ready}
940 onClick={() => setPublishWizardStep((step) => Math.min(1, step + 1))}
941 >
942 <T>Next</T>
943 </Button>
944 ) : (
945 <Button disabled={!canSubmitPublishRepository} onClick={submitPublishRepository}>
946 {publishRepositoryAction.isPending ? (
947 <>
948 <Spinner size="sm" aria-hidden />
949 <T>Publishing...</T>
950 </>
951 ) : (
952 <T context="verb">Publish</T>
953 )}
954 </Button>
955 )}
956 </>
957 )}
958 </WizardFooter>
959 </WizardPopup>
960 </Dialog>
961 );
962 }
963
964 export default memo(function GitActionsControl(props: GitActionsControlProps) {
965 const checkoutKey = JSON.stringify([props.activeThreadRef?.environmentId ?? null, props.gitCwd]);
966 return <CheckoutGitActionsControl key={checkoutKey} {...props} />;
967 });
968
969 function CheckoutGitActionsControl({
970 gitCwd,
971 activeThreadRef,
972 draftId,
973 compact = false,
974 showActions = true,
975 showChanges = true,
976 onOpenChanges,
977 workspaceMutationId = null,
978 }: GitActionsControlProps) {
979 const gt = useGT();
980 const messages = useMessages();
981 const progressLabelId = useId();
982 const panelAnchorRef = useRef<HTMLDivElement | null>(null);
983 const updateThreadMetadata = useAtomCommand(
984 threadEnvironment.updateMetadata,
985 "thread branch metadata update",
986 );
987 const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
988 const canWriteSourceControl = useEnvironmentScope(
989 activeEnvironmentId,
990 AuthSourceControlWriteScope,
991 );
992 const canOperateThread = useEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope);
993 const serverConfig = useAtomValue(serverEnvironment.configValueAtom(activeEnvironmentId));
994 const openInPreferredEditor = useOpenInPreferredEditor(
995 activeEnvironmentId,
996 serverConfig?.availableEditors ?? [],
997 );
998 const threadToastData = activeThreadRef ? { threadRef: activeThreadRef } : undefined;
999 const activeServerThreadShell = useQuietThreadShell(activeThreadRef);
1000 const activeDraftThread = useComposerDraftStore((store) =>
1001 draftId
1002 ? store.getDraftSession(draftId)
1003 : activeThreadRef
1004 ? store.getDraftThreadByRef(activeThreadRef)
1005 : null,
1006 );
1007 const activeServerThreadProjection = useQuietThreadProjection(
1008 activeDraftThread !== null && activeServerThreadShell === null ? null : activeThreadRef,
1009 );
1010 const activeServerThread =
1011 activeServerThreadShell ?? activeServerThreadProjection?.projection.thread ?? null;
1012 const isLocalDraftThread = activeDraftThread !== null && activeServerThread === null;
1013 const canChangeThreadBranch = canWriteSourceControl && (isLocalDraftThread || canOperateThread);
1014 const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
1015 const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
1016 const [dialogCommitMessage, setDialogCommitMessage] = useState("");
1017 const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
1018 const [isEditingFiles, setIsEditingFiles] = useState(false);
1019 const [isPublishDialogOpen, setIsPublishDialogOpen] = useState(false);
1020 const [inlineSuccess, setInlineSuccess] = useState<InlineGitActionSuccess | null>(null);
1021 const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
1022 useState<PendingDefaultBranchAction | null>(null);
1023 const sourceControlScope = { environmentId: activeEnvironmentId, cwd: gitCwd };
1024 const vcsActionState = useAtomValue(vcsActionManager.stateAtom(sourceControlScope));
1025 const inlineSuccessExpired = useDeadlinePassed(inlineSuccess?.expiresAtMs ?? null);
1026 const visibleInlineSuccess = inlineSuccessExpired ? null : inlineSuccess;
1027
1028 const persistThreadBranchSync = (branch: string | null, manualSelection = false) => {
1029 if (!activeThreadRef) {
1030 return;
1031 }
1032
1033 if (activeServerThread) {
1034 if (
1035 !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) ||
1036 activeServerThread.branch === branch
1037 ) {
1038 return;
1039 }
1040
1041 void updateThreadMetadata({
1042 environmentId: activeThreadRef.environmentId,
1043 input: {
1044 threadId: activeThreadRef.threadId,
1045 ...resolveThreadBranchMetadataPatch(branch, activeServerThread.branch),
1046 },
1047 });
1048
1049 return;
1050 }
1051
1052 if (!activeDraftThread || activeDraftThread.branch === branch) {
1053 return;
1054 }
1055
1056 setDraftThreadContext(draftId ?? activeThreadRef, {
1057 branch,
1058 worktreePath: activeDraftThread.worktreePath,
1059 environmentSelection: manualSelection
1060 ? "manual"
1061 : (activeDraftThread.environmentSelection ??
1062 (activeDraftThread.branch ? "manual" : "auto")),
1063 });
1064 };
1065 const persistLiveThreadBranch = useEffectEvent((branch: string | null) => {
1066 persistThreadBranchSync(branch);
1067 });
1068
1069 const syncThreadBranchAfterGitAction = (result: GitRunStackedActionResult) => {
1070 const branchUpdate = resolveThreadBranchUpdate(result);
1071 if (!branchUpdate) {
1072 return;
1073 }
1074
1075 persistThreadBranchSync(branchUpdate.branch, true);
1076 };
1077
1078 const gitStatusQuery = useEnvironmentQuery(
1079 activeEnvironmentId !== null && gitCwd !== null
1080 ? vcsEnvironment.status({
1081 environmentId: activeEnvironmentId,
1082 input: { cwd: gitCwd },
1083 })
1084 : null,
1085 );
1086 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
1087 reportFailure: false,
1088 });
1089 const { data: gitStatus, error: gitStatusError } = gitStatusQuery;
1090 const sourceControlPresentation = getSourceControlPresentation(gitStatus?.sourceControlProvider);
1091 const changeRequestTerminology = sourceControlPresentation.terminology;
1092 const SourceControlIcon = sourceControlPresentation.Icon;
1093 const isRepo = gitStatus?.isRepo ?? true;
1094 const hasPrimaryRemote = gitStatus?.hasPrimaryRemote ?? false;
1095 const gitStatusForActions = gitStatus;
1096 const changesBaseRef = useDiffPanelStore((state) =>
1097 selectThreadBranchBaseRef(state, activeThreadRef),
1098 );
1099 const ignoreWhitespaceSetting = useClientSettings((settings) => settings.diffIgnoreWhitespace);
1100 const ignoreWhitespace =
1101 useDiffPanelSessionStore((state) => state.ignoreWhitespace) ?? ignoreWhitespaceSetting;
1102 const { canReadFiles } = useFilesystemReadAccess(activeEnvironmentId, messages);
1103 // Same input as the Diff panel's branch query, so both read one cached result. Status
1104 // totals join the revision because edits, pulls and resets outside a turn leave the mutation
1105 // id as is.
1106 const changesRevision = gitStatusForActions
1107 ? JSON.stringify([
1108 workspaceMutationId,
1109 gitStatusForActions.refName,
1110 gitStatusForActions.workingTree.insertions,
1111 gitStatusForActions.workingTree.deletions,
1112 gitStatusForActions.branchChanges?.baseRef,
1113 gitStatusForActions.branchChanges?.insertions,
1114 gitStatusForActions.branchChanges?.deletions,
1115 ])
1116 : null;
1117 const changesPreview = useEnvironmentQuery(
1118 showChanges &&
1119 isRepo &&
1120 canReadFiles &&
1121 changesRevision !== null &&
1122 activeEnvironmentId !== null &&
1123 gitCwd !== null
1124 ? revisionedQuery(
1125 reviewEnvironment.diffPreview({
1126 environmentId: activeEnvironmentId,
1127 input: {
1128 cwd: gitCwd,
1129 ...(changesBaseRef ? { baseRef: changesBaseRef } : {}),
1130 ignoreWhitespace,
1131 metadataOnly: true,
1132 sourceKind: "branch-range",
1133 },
1134 }),
1135 changesRevision,
1136 )
1137 : null,
1138 );
1139 const resolvedChangesTotals = resolveChangesTotals(
1140 gitStatusForActions,
1141 changesPreview.data?.sources.find((source) => source.kind === "branch-range"),
1142 );
1143 const changesTotals = resolvedChangesTotals ?? { insertions: 0, deletions: 0 };
1144 const changesBreakdown = resolvedChangesTotals?.breakdown ?? null;
1145 const changesBaseLabel = resolvedChangesTotals
1146 ? resolvedChangesTotals.baseRef === null
1147 ? gt("Uncommitted")
1148 : gt("vs {ref}", { ref: resolvedChangesTotals.baseRef })
1149 : null;
1150
1151 const allFiles = gitStatusForActions?.workingTree.files ?? [];
1152 // Changed-file paths are repository-relative, so they must resolve against
1153 // the worktree root from the same status snapshot, not the project cwd.
1154 const workingTreeRoot = gitStatusForActions?.workingTree.rootPath ?? null;
1155 const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
1156 const allSelected = excludedFiles.size === 0;
1157 const noneSelected = selectedFiles.length === 0;
1158
1159 const initAction = useVcsInitAction(sourceControlScope);
1160 const runImmediateGitAction = useGitStackedAction(sourceControlScope);
1161 const pullAction = useVcsPullAction(sourceControlScope);
1162 const isGitActionRunning = useSourceControlActionRunning(
1163 sourceControlScope,
1164 RUNNING_SOURCE_CONTROL_ACTIONS,
1165 );
1166 const isSelectingWorktreeBase =
1167 !activeServerThread &&
1168 activeDraftThread?.envMode === "worktree" &&
1169 activeDraftThread.worktreePath === null;
1170
1171 // Until a clone finishes, the status names an unborn HEAD that the repository may never have.
1172 const activeProjectClone = useProjectClone(
1173 activeDraftThread
1174 ? scopeProjectRef(activeDraftThread.environmentId, activeDraftThread.projectId)
1175 : null,
1176 );
1177 const isProjectCloning = activeProjectClone !== null && activeProjectClone.phase !== "done";
1178
1179 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- persists the draft thread branch when the live git status subscription reports a different branch
1180 useEffect(() => {
1181 if (isGitActionRunning || isSelectingWorktreeBase || activeServerThread || isProjectCloning) {
1182 return;
1183 }
1184
1185 const branchUpdate = resolveLiveThreadBranchUpdate({
1186 threadBranch: activeDraftThread?.branch ?? null,
1187 gitStatus: gitStatusForActions,
1188 });
1189 if (!branchUpdate) {
1190 return;
1191 }
1192
1193 persistLiveThreadBranch(branchUpdate.branch);
1194 }, [
1195 activeServerThread,
1196 activeDraftThread?.branch,
1197 gitStatusForActions,
1198 isGitActionRunning,
1199 isProjectCloning,
1200 isSelectingWorktreeBase,
1201 ]);
1202
1203 const isDefaultRef = gitStatusForActions?.isDefaultRef ?? false;
1204
1205 const gitActionMenuItems = buildMenuItems(
1206 gitStatusForActions,
1207 isGitActionRunning,
1208 hasPrimaryRemote,
1209 messages,
1210 );
1211 const quickAction = resolveQuickAction(
1212 gitStatusForActions,
1213 isGitActionRunning,
1214 isDefaultRef,
1215 hasPrimaryRemote,
1216 messages,
1217 );
1218 const quickActionDisabledReason = !canWriteSourceControl
1219 ? gt("This connection cannot change source control.")
1220 : quickAction.disabled
1221 ? (quickAction.hint ?? gt("This action is currently unavailable."))
1222 : null;
1223 const gitActionProgress = resolveGitActionProgressPresentation(vcsActionState, messages);
1224 // A fresh draft or a thread with no turns hides commit, push, and diff rows until there is work.
1225 const quietEmptyDraft =
1226 (draftId !== undefined || activeServerThreadShell?.latestRun === null) &&
1227 gitActionProgress === null &&
1228 !gitStatusError &&
1229 quickAction.disabled &&
1230 !changesTotals.insertions &&
1231 !changesTotals.deletions;
1232 const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
1233 ? resolveDefaultBranchActionDialogCopy(
1234 {
1235 action: pendingDefaultBranchAction.action,
1236 branchName: pendingDefaultBranchAction.branchName,
1237 includesCommit: pendingDefaultBranchAction.includesCommit,
1238 terminology: changeRequestTerminology,
1239 },
1240 messages,
1241 )
1242 : null;
1243 // Keep enabled until live status loads; the server rejects stale requests.
1244 const featureBranchUnavailableReason = pendingDefaultBranchAction
1245 ? resolveFeatureBranchUnavailableReason(
1246 {
1247 action: pendingDefaultBranchAction.action,
1248 branchName: pendingDefaultBranchAction.branchName,
1249 hasWorkingTreeChanges: gitStatus?.hasWorkingTreeChanges ?? true,
1250 },
1251 messages,
1252 )
1253 : null;
1254
1255 useAtomMount(
1256 vcsStatusRevalidation(
1257 activeEnvironmentId !== null && gitCwd !== null
1258 ? { environmentId: activeEnvironmentId, cwd: gitCwd }
1259 : null,
1260 ),
1261 );
1262
1263 async function runGitActionWithToast({
1264 action,
1265 commitMessage,
1266 onConfirmed,
1267 skipDefaultBranchPrompt = false,
1268 statusOverride,
1269 featureBranch = false,
1270 filePaths,
1271 }: RunGitActionWithToastInput) {
1272 if (
1273 activeEnvironmentId === null ||
1274 !readEnvironmentScope(activeEnvironmentId, AuthSourceControlWriteScope) ||
1275 (featureBranch &&
1276 !isLocalDraftThread &&
1277 !readEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope))
1278 )
1279 return false;
1280 const actionStatus = statusOverride ?? gitStatusForActions;
1281 const actionBranch = actionStatus?.refName ?? null;
1282 const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
1283 const actionCanCommit =
1284 action === "commit" || action === "commit_push" || action === "commit_push_pr";
1285 const includesCommit =
1286 actionCanCommit &&
1287 (action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch);
1288 if (
1289 !skipDefaultBranchPrompt &&
1290 requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
1291 actionBranch
1292 ) {
1293 if (
1294 action !== "push" &&
1295 action !== "create_pr" &&
1296 action !== "commit_push" &&
1297 action !== "commit_push_pr"
1298 ) {
1299 return false;
1300 }
1301 setPendingDefaultBranchAction({
1302 action,
1303 branchName: actionBranch,
1304 includesCommit,
1305 ...(commitMessage ? { commitMessage } : {}),
1306 ...(onConfirmed ? { onConfirmed } : {}),
1307 ...(filePaths ? { filePaths } : {}),
1308 });
1309 return false;
1310 }
1311 onConfirmed?.();
1312 setInlineSuccess(null);
1313
1314 const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
1315 const actionId = randomUUID();
1316
1317 const result = await runImmediateGitAction.run({
1318 actionId,
1319 action,
1320 ...(commitMessage ? { commitMessage } : {}),
1321 ...(featureBranch ? { featureBranch } : {}),
1322 ...(filePaths ? { filePaths } : {}),
1323 ...(activeServerThread ? { threadId: activeServerThread.id } : {}),
1324 ...(activeDraftThread ? { projectId: activeDraftThread.projectId } : {}),
1325 });
1326
1327 if (result._tag === "Failure") {
1328 if (isAtomCommandInterrupted(result)) {
1329 return false;
1330 }
1331
1332 const error = squashAtomCommandFailure(result);
1333 const errorToastTiming = resolveGitActionResultToastTiming("error");
1334 toastManager.add(
1335 stackedThreadToast({
1336 type: "error",
1337 title: gt("Action failed"),
1338 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1339 timeout: errorToastTiming.timeout,
1340 ...(scopedToastData !== undefined ? { data: scopedToastData } : {}),
1341 }),
1342 );
1343 return false;
1344 }
1345
1346 const actionResult = result.value;
1347 syncThreadBranchAfterGitAction(actionResult);
1348 const createdPullRequest = actionResult.pr.status === "created";
1349 setInlineSuccess({
1350 title: createdPullRequest
1351 ? gt("Created {term, select, mr {MR} cr {change request} other {PR}}", {
1352 term: changeRequestTermKind(changeRequestTerminology),
1353 })
1354 : actionResult.toast.title,
1355 description: createdPullRequest ? null : (actionResult.toast.description ?? null),
1356 expiresAtMs: inlineSuccessExpiresAt(),
1357 });
1358 return true;
1359 }
1360
1361 const continuePendingDefaultBranchAction = (featureBranch: boolean) => {
1362 if (!pendingDefaultBranchAction || !canWriteSourceControl) return;
1363 if (featureBranch && (!canChangeThreadBranch || featureBranchUnavailableReason !== null))
1364 return;
1365 const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
1366 setPendingDefaultBranchAction(null);
1367 void runGitActionWithToast({
1368 action,
1369 ...(commitMessage ? { commitMessage } : {}),
1370 ...(onConfirmed ? { onConfirmed } : {}),
1371 ...(filePaths ? { filePaths } : {}),
1372 featureBranch,
1373 skipDefaultBranchPrompt: true,
1374 });
1375 };
1376
1377 // Keep a typed message for the retry unless the user already started a new one.
1378 const restoreDialogCommitMessageOnFailure = (commitMessage: string) => (committed: boolean) => {
1379 if (committed || !commitMessage) return;
1380 setDialogCommitMessage((current) => current || commitMessage);
1381 };
1382
1383 const runDialogActionOnNewBranch = () => {
1384 if (!isCommitDialogOpen) return;
1385 const commitMessage = dialogCommitMessage.trim();
1386
1387 setIsCommitDialogOpen(false);
1388 setDialogCommitMessage("");
1389 setExcludedFiles(new Set());
1390 setIsEditingFiles(false);
1391
1392 void runGitActionWithToast({
1393 action: "commit",
1394 ...(commitMessage ? { commitMessage } : {}),
1395 ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
1396 featureBranch: true,
1397 skipDefaultBranchPrompt: true,
1398 }).then(restoreDialogCommitMessageOnFailure(commitMessage));
1399 };
1400
1401 const runQuickAction = () => {
1402 if (quickAction.kind === "open_publish") {
1403 setIsPublishDialogOpen(true);
1404 return;
1405 }
1406 if (quickAction.kind === "run_pull") {
1407 void (async () => {
1408 setInlineSuccess(null);
1409 const result = await pullAction.run();
1410 if (result._tag === "Failure") {
1411 if (isAtomCommandInterrupted(result)) {
1412 return;
1413 }
1414 const error = squashAtomCommandFailure(result);
1415 const errorToastTiming = resolveGitActionResultToastTiming("error");
1416 toastManager.add(
1417 stackedThreadToast({
1418 type: "error",
1419 title: gt("Pull failed"),
1420 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1421 timeout: errorToastTiming.timeout,
1422 ...(threadToastData !== undefined ? { data: threadToastData } : {}),
1423 }),
1424 );
1425 return;
1426 }
1427
1428 const pullResult = result.value;
1429 const title = pullResult.status === "pulled" ? gt("Pulled") : gt("Already up to date");
1430 const description =
1431 pullResult.status === "pulled"
1432 ? pullResult.upstreamRef
1433 ? gt("Updated {ref} from {upstream}", {
1434 ref: pullResult.refName,
1435 upstream: pullResult.upstreamRef,
1436 })
1437 : gt("Updated {ref} from upstream", { ref: pullResult.refName })
1438 : gt("{ref} is already synchronized.", { ref: pullResult.refName });
1439 setInlineSuccess({
1440 title,
1441 description,
1442 expiresAtMs: inlineSuccessExpiresAt(),
1443 });
1444 })();
1445 return;
1446 }
1447 if (quickAction.kind === "show_hint") {
1448 toastManager.add({
1449 type: "info",
1450 title: quickAction.label,
1451 description: quickAction.hint,
1452 data: threadToastData,
1453 });
1454 return;
1455 }
1456 if (quickAction.action) {
1457 void runGitActionWithToast({ action: quickAction.action });
1458 }
1459 };
1460
1461 const openDialogForMenuItem = (item: GitActionMenuItem) => {
1462 if (item.disabled) return;
1463 if (item.dialogAction === "push") {
1464 void runGitActionWithToast({ action: "push" });
1465 return;
1466 }
1467 if (item.dialogAction === "create_pr") {
1468 void runGitActionWithToast({ action: "create_pr" });
1469 return;
1470 }
1471 setExcludedFiles(new Set());
1472 setIsEditingFiles(false);
1473 setIsCommitDialogOpen(true);
1474 };
1475
1476 const runDialogAction = () => {
1477 if (!isCommitDialogOpen) return;
1478 const commitMessage = dialogCommitMessage.trim();
1479 setIsCommitDialogOpen(false);
1480 setDialogCommitMessage("");
1481 setExcludedFiles(new Set());
1482 setIsEditingFiles(false);
1483 void runGitActionWithToast({
1484 action: "commit",
1485 ...(commitMessage ? { commitMessage } : {}),
1486 ...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
1487 }).then(restoreDialogCommitMessageOnFailure(commitMessage));
1488 };
1489
1490 const openChangedFileInEditor = (filePath: string) => {
1491 if (workingTreeRoot === null) {
1492 toastManager.add({
1493 type: "error",
1494 title: gt("Editor opening is unavailable."),
1495 data: threadToastData,
1496 });
1497 return;
1498 }
1499 const target = resolvePathLinkTarget(filePath, workingTreeRoot);
1500 void (async () => {
1501 const result = await openInPreferredEditor(target);
1502 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1503 return;
1504 }
1505 const error = squashAtomCommandFailure(result);
1506 toastManager.add(
1507 stackedThreadToast({
1508 type: "error",
1509 title: gt("Unable to open file"),
1510 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1511 ...(threadToastData !== undefined ? { data: threadToastData } : {}),
1512 }),
1513 );
1514 })();
1515 };
1516
1517 const canPublishRepository =
1518 canWriteSourceControl && isRepo && gitStatusForActions !== null && !hasPrimaryRemote;
1519 const isDetachedHead = gitStatusForActions?.refName === null;
1520 const isCleanAndBehind =
1521 gitStatusForActions !== null &&
1522 gitStatusForActions.refName !== null &&
1523 !gitStatusForActions.hasWorkingTreeChanges &&
1524 gitStatusForActions.behindCount > 0 &&
1525 gitStatusForActions.aheadCount === 0;
1526 const hasGitMenuContent = hasUsableGitMenuContent({
1527 menuItems: gitActionMenuItems,
1528 canWriteSourceControl,
1529 canPublishRepository,
1530 hasNotice: isDetachedHead || isCleanAndBehind || Boolean(gitStatusError),
1531 });
1532
1533 // A disabled menu cannot refresh on open, and terminal edits or commits publish no status.
1534 const refreshStatusForEmptyMenu = () =>
1535 requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);
1536
1537 const initializeGit = () => {
1538 void (async () => {
1539 const result = await initAction.run();
1540 if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
1541 return;
1542 }
1543 const error = squashAtomCommandFailure(result);
1544 toastManager.add(
1545 stackedThreadToast({
1546 type: "error",
1547 title: gt("Git initialization failed"),
1548 description: thrownErrorMessage(error, m) ?? gt("An error occurred."),
1549 ...(threadToastData !== undefined ? { data: threadToastData } : {}),
1550 }),
1551 );
1552 })();
1553 };
1554 const gitItems = (
1555 <>
1556 {gitActionMenuItems.map((item) => {
1557 const disabledReason = getMenuActionDisabledReason(
1558 {
1559 item,
1560 gitStatus: gitStatusForActions,
1561 isBusy: isGitActionRunning,
1562 hasPrimaryRemote,
1563 },
1564 messages,
1565 );
1566 if (item.disabled && disabledReason) {
1567 return (
1568 <Popover key={`${item.id}-${item.label}`}>
1569 <PopoverTrigger
1570 openOnHover
1571 nativeButton={false}
1572 render={<span className="block w-full cursor-not-allowed" />}
1573 >
1574 <MenuItem className="w-full" disabled>
1575 <GitActionItemIcon icon={item.icon} SourceControlIcon={SourceControlIcon} />
1576 <MenuItemLabel>{item.label}</MenuItemLabel>
1577 </MenuItem>
1578 </PopoverTrigger>
1579 <PopoverPopup tooltipStyle side="left" align="center">
1580 {disabledReason}
1581 </PopoverPopup>
1582 </Popover>
1583 );
1584 }
1585
1586 return (
1587 <MenuItem
1588 key={`${item.id}-${item.label}`}
1589 disabled={!canWriteSourceControl || item.disabled}
1590 onClick={() => {
1591 openDialogForMenuItem(item);
1592 }}
1593 >
1594 <GitActionItemIcon icon={item.icon} SourceControlIcon={SourceControlIcon} />
1595 <MenuItemLabel>{item.label}</MenuItemLabel>
1596 </MenuItem>
1597 );
1598 })}
1599 {canPublishRepository ? (
1600 <MenuItem
1601 disabled={isGitActionRunning}
1602 onClick={() => {
1603 setIsPublishDialogOpen(true);
1604 }}
1605 >
1606 <CloudUploadIcon />
1607 <MenuItemLabel>
1608 <T>Publish repository...</T>
1609 </MenuItemLabel>
1610 </MenuItem>
1611 ) : null}
1612 {isDetachedHead && (
1613 <p className="px-2 py-1.5 text-xs text-warning">
1614 {gt(
1615 "Detached HEAD: create and check out a branch to enable push and {term, select, mr {merge request} cr {change request} other {pull request}} actions.",
1616 { term: changeRequestTermKind(changeRequestTerminology) },
1617 )}
1618 </p>
1619 )}
1620 {isCleanAndBehind && (
1621 <p className="px-2 py-1.5 text-xs text-warning">
1622 <T>Behind upstream. Pull/rebase first.</T>
1623 </p>
1624 )}
1625 {gitStatusError && <p className="px-2 py-1.5 text-xs text-destructive">{gitStatusError}</p>}
1626 </>
1627 );
1628
1629 if (!gitCwd) return null;
1630
1631 return (
1632 <>
1633 {!showActions ? null : !isRepo ? (
1634 <ThreadDetailsControl
1635 size="xs"
1636 variant="ghost"
1637 part="row"
1638 panel
1639 disabled={!canWriteSourceControl || initAction.isPending}
1640 onClick={initializeGit}
1641 >
1642 <GitBranchPlusIcon className="size-3.5" aria-hidden />
1643 <span className={cn("ml-0.5", THREAD_DETAILS_PANEL_LABEL_CLASS)}>
1644 {initAction.isPending ? <T>Initializing...</T> : <T>Initialize Git</T>}
1645 </span>
1646 </ThreadDetailsControl>
1647 ) : quietEmptyDraft || (compact && !gitActionProgress && !visibleInlineSuccess) ? null : (
1648 <div
1649 role="group"
1650 aria-label={gt("Git actions")}
1651 ref={panelAnchorRef}
1652 onPointerEnter={hasGitMenuContent ? undefined : refreshStatusForEmptyMenu}
1653 onFocus={hasGitMenuContent ? undefined : refreshStatusForEmptyMenu}
1654 className={cn(
1655 "shrink-0",
1656 THREAD_DETAILS_PANEL_SPLIT_GROUP_CLASS,
1657 gitActionProgress && "bg-black/[0.035] dark:bg-white/[0.055]",
1658 )}
1659 >
1660 {gitActionProgress ? (
1661 <ThreadDetailsControl
1662 aria-labelledby={progressLabelId}
1663 part="primary"
1664 panel
1665 multiline
1666 disabled
1667 size="xs"
1668 variant="ghost"
1669 >
1670 <GitActionProgressButtonContent id={progressLabelId} progress={gitActionProgress} />
1671 </ThreadDetailsControl>
1672 ) : visibleInlineSuccess ? (
1673 <ThreadDetailsControl part="primary" multiline disabled size="xs" variant="ghost">
1674 <GitActionSuccessButtonContent success={visibleInlineSuccess} />
1675 </ThreadDetailsControl>
1676 ) : quickActionDisabledReason ? (
1677 <Popover>
1678 <PopoverTrigger
1679 openOnHover
1680 render={
1681 <ThreadDetailsControl
1682 aria-disabled="true"
1683 part="primary"
1684 panel
1685 size="xs"
1686 variant="ghost"
1687 />
1688 }
1689 >
1690 <GitQuickActionIcon
1691 quickAction={quickAction}
1692 SourceControlIcon={SourceControlIcon}
1693 className={THREAD_DETAILS_PANEL_ICON_CLASS}
1694 />
1695 <span
1696 className={cn(
1697 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
1698 cn("not-sr-only ml-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
1699 )}
1700 >
1701 {quickAction.label}
1702 </span>
1703 </PopoverTrigger>
1704 <PopoverPopup tooltipStyle side="bottom" align="start">
1705 {quickActionDisabledReason}
1706 </PopoverPopup>
1707 </Popover>
1708 ) : (
1709 <Tooltip>
1710 <TooltipTrigger
1711 render={
1712 <ThreadDetailsControl
1713 data-toolbar-control=""
1714 variant="ghost"
1715 size="xs"
1716 part="primary"
1717 panel
1718 disabled={!canWriteSourceControl || isGitActionRunning || quickAction.disabled}
1719 onClick={runQuickAction}
1720 />
1721 }
1722 >
1723 <GitQuickActionIcon
1724 quickAction={quickAction}
1725 SourceControlIcon={SourceControlIcon}
1726 className={THREAD_DETAILS_PANEL_ICON_CLASS}
1727 />
1728 <span
1729 className={cn(
1730 "sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5",
1731 cn("not-sr-only ml-0 truncate", THREAD_DETAILS_PANEL_LABEL_CLASS),
1732 )}
1733 >
1734 {quickAction.label}
1735 </span>
1736 </TooltipTrigger>
1737 <TooltipPopup side="top">{quickAction.label}</TooltipPopup>
1738 </Tooltip>
1739 )}
1740 {!gitActionProgress ? (
1741 <>
1742 <span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
1743 <Menu
1744 onOpenChange={(open) => {
1745 if (open) {
1746 requestVcsStatusRefresh(refreshVcsStatus, activeEnvironmentId, gitCwd);
1747 }
1748 }}
1749 >
1750 <Tooltip>
1751 <TooltipTrigger
1752 render={
1753 <MenuTrigger
1754 render={
1755 <ThreadDetailsControl
1756 aria-label={gt("Git action options")}
1757 data-toolbar-control=""
1758 size="sm"
1759 variant="ghost"
1760 part="secondary"
1761 panel
1762 />
1763 }
1764 disabled={isGitActionRunning || !hasGitMenuContent}
1765 />
1766 }
1767 >
1768 <ChevronDownIcon
1769 aria-hidden="true"
1770 className={THREAD_DETAILS_PANEL_CHEVRON_CLASS}
1771 />
1772 </TooltipTrigger>
1773 <TooltipPopup side="top">
1774 <T>Git action options</T>
1775 </TooltipPopup>
1776 </Tooltip>
1777 <MenuPopup align="end" anchor={panelAnchorRef} className="w-(--anchor-width)">
1778 {gitItems}
1779 </MenuPopup>
1780 </Menu>
1781 </>
1782 ) : null}
1783 </div>
1784 )}
1785
1786 {showChanges && isRepo && !quietEmptyDraft ? (
1787 <Tooltip>
1788 <TooltipTrigger
1789 render={
1790 <ThreadDetailsControl
1791 type="button"
1792 variant="ghost"
1793 size="sm"
1794 part="row"
1795 disabled={!onOpenChanges}
1796 onClick={onOpenChanges}
1797 />
1798 }
1799 >
1800 <FileDiffIcon className={THREAD_DETAILS_PANEL_ICON_CLASS} aria-hidden />
1801 <span className="flex min-w-0 flex-1 items-baseline gap-1.5">
1802 <span className="shrink-0">
1803 <T>Changes</T>
1804 </span>
1805 {changesBaseLabel ? (
1806 <Tooltip>
1807 <TooltipTrigger
1808 render={
1809 <span className="pointer-events-auto min-w-0 truncate font-normal text-muted-foreground" />
1810 }
1811 >
1812 {changesBaseLabel}
1813 </TooltipTrigger>
1814 <TooltipPopup side="top" className="max-w-96 break-words">
1815 {changesBaseLabel}
1816 </TooltipPopup>
1817 </Tooltip>
1818 ) : null}
1819 <span className="ml-auto flex shrink-0 items-baseline gap-2 ps-2 font-mono tabular-nums">
1820 <span
1821 className={
1822 changesTotals.insertions
1823 ? "text-diff-addition-foreground"
1824 : "text-muted-foreground"
1825 }
1826 >
1827 +{formatDiffCount(changesTotals.insertions)}
1828 </span>
1829 <span
1830 className={
1831 changesTotals.deletions
1832 ? "text-diff-deletion-foreground"
1833 : "text-muted-foreground"
1834 }
1835 >
1836 -{formatDiffCount(changesTotals.deletions)}
1837 </span>
1838 </span>
1839 </span>
1840 </TooltipTrigger>
1841 {changesBreakdown && (changesTotals.insertions > 0 || changesTotals.deletions > 0) ? (
1842 // Base UI fixes the popup width on open; remeasure when the breakdown changes.
1843 <TooltipPopup key={JSON.stringify(changesBreakdown)} side="bottom">
1844 <ChangeBreakdownGrid
1845 breakdown={changesBreakdown}
1846 total={{ additions: changesTotals.insertions, deletions: changesTotals.deletions }}
1847 />
1848 </TooltipPopup>
1849 ) : null}
1850 </Tooltip>
1851 ) : null}
1852
1853 <Dialog
1854 open={isCommitDialogOpen}
1855 onOpenChange={(open) => {
1856 if (!open) {
1857 setIsCommitDialogOpen(false);
1858 setDialogCommitMessage("");
1859 setExcludedFiles(new Set());
1860 setIsEditingFiles(false);
1861 }
1862 }}
1863 >
1864 <DialogPopup>
1865 <DialogHeader>
1866 <DialogTitle>{messages(COMMIT_DIALOG_TITLE)}</DialogTitle>
1867 <DialogDescription>{messages(COMMIT_DIALOG_DESCRIPTION)}</DialogDescription>
1868 </DialogHeader>
1869 <DialogPanel>
1870 <div className="space-y-3 rounded-xl bg-zinc-25 p-3 text-sm ring-1 ring-black/5 dark:bg-white/[0.035] dark:ring-white/5">
1871 <div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
1872 <span className="text-muted-foreground">
1873 <T context="git branch">Branch</T>
1874 </span>
1875 <span className="flex items-center justify-between gap-2">
1876 <span className="font-medium">
1877 {gitStatusForActions?.refName ?? gt("(detached HEAD)")}
1878 </span>
1879 {isDefaultRef && (
1880 <span className="text-right text-warning">
1881 <T>Default branch</T>
1882 </span>
1883 )}
1884 </span>
1885 </div>
1886 <div className="space-y-1">
1887 <div className="flex items-center justify-between">
1888 <div className="flex items-center gap-2">
1889 {isEditingFiles && allFiles.length > 0 && (
1890 <Checkbox
1891 aria-label={gt("Include all files")}
1892 checked={allSelected}
1893 indeterminate={!allSelected && !noneSelected}
1894 onCheckedChange={() => {
1895 setExcludedFiles(
1896 allSelected ? new Set(allFiles.map((f) => f.path)) : new Set(),
1897 );
1898 }}
1899 />
1900 )}
1901 <span className="text-muted-foreground">
1902 <T>Files</T>
1903 </span>
1904 {!allSelected && !isEditingFiles && (
1905 <span className="text-muted-foreground">
1906 {gt("({selected} of {total})", {
1907 selected: selectedFiles.length,
1908 total: allFiles.length,
1909 })}
1910 </span>
1911 )}
1912 </div>
1913 {allFiles.length > 0 && (
1914 <Button
1915 variant="ghost"
1916 size="xs"
1917 onClick={() => setIsEditingFiles((prev) => !prev)}
1918 >
1919 {isEditingFiles ? (
1920 <T context="button, finish editing the file list">Done</T>
1921 ) : (
1922 <T context="verb">Edit</T>
1923 )}
1924 </Button>
1925 )}
1926 </div>
1927 {!gitStatusForActions || allFiles.length === 0 ? (
1928 <p className="font-medium">
1929 <T context="no files">none</T>
1930 </p>
1931 ) : (
1932 <div className="space-y-2">
1933 <div className="h-44 rounded-lg bg-card ring-1 ring-black/5 dark:bg-white/[0.025] dark:ring-white/5">
1934 <ScrollArea>
1935 <div className="space-y-1 p-1">
1936 {allFiles.map((file) => {
1937 const isExcluded = excludedFiles.has(file.path);
1938 return (
1939 <div
1940 key={file.path}
1941 className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono hover:bg-accent/50"
1942 >
1943 {isEditingFiles && (
1944 <Checkbox
1945 aria-label={gt("Include {path}", { path: file.path })}
1946 checked={!excludedFiles.has(file.path)}
1947 onCheckedChange={() => {
1948 setExcludedFiles((prev) => {
1949 const next = new Set(prev);
1950 if (next.has(file.path)) {
1951 next.delete(file.path);
1952 } else {
1953 next.add(file.path);
1954 }
1955 return next;
1956 });
1957 }}
1958 />
1959 )}
1960 <button
1961 type="button"
1962 className="flex min-w-0 flex-1 items-center justify-between gap-3 text-left enabled:cursor-pointer"
1963 disabled={!canOperateThread || workingTreeRoot === null}
1964 aria-label={gt("Open {path} in editor", { path: file.path })}
1965 onClick={() => openChangedFileInEditor(file.path)}
1966 >
1967 <StartTruncatedPath
1968 path={file.path}
1969 className={`flex-1${isExcluded ? " text-muted-foreground" : ""}`}
1970 />
1971 <span className="shrink-0">
1972 {isExcluded ? (
1973 <span className="text-muted-foreground">
1974 <T>Excluded</T>
1975 </span>
1976 ) : (
1977 <>
1978 <span className="text-diff-addition">
1979 +{formatDiffCount(file.insertions)}
1980 </span>
1981 <span className="text-muted-foreground"> / </span>
1982 <span className="text-diff-deletion">
1983 -{formatDiffCount(file.deletions)}
1984 </span>
1985 </>
1986 )}
1987 </span>
1988 </button>
1989 </div>
1990 );
1991 })}
1992 </div>
1993 </ScrollArea>
1994 </div>
1995 <div className="flex justify-end font-mono">
1996 <span className="text-diff-addition">
1997 +{formatDiffCount(selectedFiles.reduce((sum, f) => sum + f.insertions, 0))}
1998 </span>
1999 <span className="text-muted-foreground"> / </span>
2000 <span className="text-diff-deletion">
2001 -{formatDiffCount(selectedFiles.reduce((sum, f) => sum + f.deletions, 0))}
2002 </span>
2003 </div>
2004 </div>
2005 )}
2006 </div>
2007 </div>
2008 <div className="space-y-1">
2009 <p className="text-sm font-medium">
2010 <T>Commit message (optional)</T>
2011 </p>
2012 <Textarea
2013 value={dialogCommitMessage}
2014 onChange={(event) => setDialogCommitMessage(event.target.value)}
2015 placeholder={gt("Leave empty to auto-generate")}
2016 size="sm"
2017 />
2018 </div>
2019 </DialogPanel>
2020 <DialogFooter variant="bare">
2021 <Button
2022 variant="outline"
2023 size="sm"
2024 onClick={() => {
2025 setIsCommitDialogOpen(false);
2026 setDialogCommitMessage("");
2027 setExcludedFiles(new Set());
2028 setIsEditingFiles(false);
2029 }}
2030 >
2031 <T>Cancel</T>
2032 </Button>
2033 <Button
2034 variant="outline"
2035 size="sm"
2036 disabled={!canChangeThreadBranch || noneSelected}
2037 onClick={runDialogActionOnNewBranch}
2038 >
2039 <T>Commit on new branch</T>
2040 </Button>
2041 <Button
2042 size="sm"
2043 disabled={!canWriteSourceControl || noneSelected}
2044 onClick={runDialogAction}
2045 >
2046 <T context="verb">Commit</T>
2047 </Button>
2048 </DialogFooter>
2049 </DialogPopup>
2050 </Dialog>
2051
2052 {/* Its discovery query should stop when the Git actions row that opens it is hidden. */}
2053 {showActions ? (
2054 <PublishRepositoryDialog
2055 open={isPublishDialogOpen}
2056 onOpenChange={setIsPublishDialogOpen}
2057 environmentId={activeEnvironmentId}
2058 threadRef={activeThreadRef}
2059 gitCwd={gitCwd}
2060 offeredProviders={serverConfig?.settings.offeredSourceControlProviders}
2061 />
2062 ) : null}
2063
2064 <Dialog
2065 open={pendingDefaultBranchAction !== null}
2066 onOpenChange={(open) => {
2067 if (!open) setPendingDefaultBranchAction(null);
2068 }}
2069 >
2070 <DialogPopup className="max-w-xl">
2071 <DialogHeader>
2072 <DialogTitle>
2073 {pendingDefaultBranchActionCopy?.title ?? gt("Run action on default branch?")}
2074 </DialogTitle>
2075 <DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
2076 {featureBranchUnavailableReason && (
2077 <p className="text-xs text-muted-foreground">{featureBranchUnavailableReason}</p>
2078 )}
2079 </DialogHeader>
2080 <DialogFooter variant="bare" className="sm:flex-wrap sm:items-center">
2081 <Button
2082 className="w-full sm:mr-auto sm:w-auto"
2083 variant="outline"
2084 size="sm"
2085 onClick={() => setPendingDefaultBranchAction(null)}
2086 >
2087 <T>Abort</T>
2088 </Button>
2089 <Button
2090 className="w-full max-w-full sm:w-auto"
2091 variant="outline"
2092 size="sm-multiline"
2093 onClick={() => continuePendingDefaultBranchAction(false)}
2094 disabled={!canWriteSourceControl}
2095 >
2096 {pendingDefaultBranchActionCopy?.continueLabel ?? gt("Continue")}
2097 </Button>
2098 <Button
2099 className="w-full max-w-full sm:w-auto"
2100 size="sm-multiline"
2101 onClick={() => continuePendingDefaultBranchAction(true)}
2102 disabled={!canChangeThreadBranch || featureBranchUnavailableReason !== null}
2103 >
2104 <T>Check out feature branch & continue</T>
2105 </Button>
2106 </DialogFooter>
2107 </DialogPopup>
2108 </Dialog>
2109 </>
2110 );
2111 }