Skip to content
TypeScript

perf(web): Git actions control compiles without manual memoization (#20777)

Julius Marmingeb38aa027dcb4
diff --git a/apps/web/src/components/GitActionsControl.test.ts b/apps/web/src/components/GitActionsControl.test.ts
index 18651179654..9da21b4de1a 100644
--- a/apps/web/src/components/GitActionsControl.test.ts
+++ b/apps/web/src/components/GitActionsControl.test.ts
@@ -1,3 +1,4 @@
+// @vitest-environment jsdom
import {
AuthOrchestrationOperateScope,
AuthSourceControlWriteScope,
@@ -6,7 +7,7 @@ import {
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import { AsyncResult } from "effect/reactivity";
-import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
const state = vi.hoisted(() => ({
scopes: new Set<string>(),
@@ -18,20 +19,8 @@ const state = vi.hoisted(() => ({
commits: 0,
metadataRequests: [] as { environmentId: string; branch: string }[],
afterGitAction: undefined as (() => void) | undefined,
- run: null as ((input: { action: "commit"; featureBranch?: boolean }) => Promise<void>) | null,
}));
-vi.mock("react", async (importOriginal) => ({
- ...(await importOriginal<typeof import("react")>()),
- useCallback: (callback: typeof state.run) => {
- if (callback?.constructor.name === "AsyncFunction") state.run = callback;
- return callback;
- },
- useMemo: (factory: () => unknown) => factory(),
- useState: (initial: unknown) => [typeof initial === "function" ? initial() : initial, () => {}],
- useRef: (current: unknown) => ({ current }),
- useEffect: () => {},
-}));
vi.mock("@effect/atom-react", () => ({
useAtomValue: (atom: unknown) => (atom === "vcs-state" ? { isRunning: false } : null),
}));
@@ -48,7 +37,8 @@ vi.mock("~/state/session", () => ({
}));
vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command }));
vi.mock("~/state/server", () => ({ serverEnvironment: { configValueAtom: () => null } }));
-vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: {} }));
+vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: { discovery: () => null } }));
+vi.mock("@tanstack/react-router", () => ({ useNavigate: () => () => {} }));
vi.mock("~/state/vcs", () => ({
vcsEnvironment: { status: () => null },
vcsActionManager: { stateAtom: () => "vcs-state" },
@@ -74,8 +64,9 @@ vi.mock("~/state/threads", () => ({
vi.mock("~/state/query", () => ({
useEnvironmentQuery: () => ({
data: {
+ sourceControlProviders: [],
isRepo: true,
- refName: "main",
+ refName: state.branch,
isDefaultRef: false,
hasPrimaryRemote: true,
hasWorkingTreeChanges: true,
@@ -171,18 +162,53 @@ vi.mock("./AnimatedHeight", () => ({ AnimatedHeight: "AnimatedHeight" }));
import GitActionsControl from "./GitActionsControl";
-function renderActions() {
- GitActionsControl({
+import { createElement } from "react";
+import { act, create, type ReactTestRenderer } from "react-test-renderer";
+
+vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+
+let renderer: ReactTestRenderer | null = null;
+
+// Opens the commit dialog and returns its buttons' handlers from this render, so a test can
+// change grants afterwards and still click what the user saw.
+async function renderActions() {
+ const element = createElement(GitActionsControl, {
gitCwd: "/repo",
activeThreadRef: {
environmentId: EnvironmentId.make("environment"),
threadId: ThreadId.make("thread"),
},
});
- if (!state.run) throw new Error("Git action missing");
- return state.run;
+ await act(async () => {
+ if (renderer) renderer.update(element);
+ else renderer = create(element);
+ });
+ const root = renderer!.root;
+ const commitMenuItem = root.find(
+ (node) => String(node.type) === "MenuItemLabel" && node.props.children === "Commit",
+ ).parent!;
+ await act(async () => {
+ commitMenuItem.props.onClick();
+ });
+ const buttonHandler = (label: string): (() => void) =>
+ root.find((node) => String(node.type) === "Button" && node.props.children === label).props
+ .onClick;
+ const commit = buttonHandler("Commit");
+ const commitOnNewBranch = buttonHandler("Commit on new branch");
+ return async ({ featureBranch }: { action: "commit"; featureBranch?: boolean }) => {
+ await act(async () => {
+ (featureBranch ? commitOnNewBranch : commit)();
+ });
+ };
}
+afterEach(async () => {
+ await act(async () => {
+ renderer?.unmount();
+ });
+ renderer = null;
+});
+
describe("Git actions while thread details load", () => {
beforeEach(() => {
state.scopes = new Set([AuthSourceControlWriteScope]);
@@ -194,11 +220,12 @@ describe("Git actions while thread details load", () => {
state.commits = 0;
state.metadataRequests = [];
state.afterGitAction = undefined;
- state.run = null;
});
it("does not create a feature branch for a server thread without task permission", async () => {
- await renderActions()({ action: "commit", featureBranch: true });
+ await (
+ await renderActions()
+ )({ action: "commit", featureBranch: true });
expect(state.branch).toBe("main");
expect(state.commits).toBe(0);
@@ -208,7 +235,9 @@ describe("Git actions while thread details load", () => {
it("commits and synchronizes the server thread before details finish loading", async () => {
state.primaryScopes.clear();
state.scopes.add(AuthOrchestrationOperateScope);
- await renderActions()({ action: "commit", featureBranch: true });
+ await (
+ await renderActions()
+ )({ action: "commit", featureBranch: true });
expect(state.branch).toBe("feature");
expect(state.commits).toBe(1);
@@ -219,10 +248,12 @@ describe("Git actions while thread details load", () => {
it("synchronizes archived thread detail after its shell disappears", async () => {
state.scopes.add(AuthOrchestrationOperateScope);
state.detail = { branch: "main" };
- renderActions();
+ await renderActions();
state.shell = null;
- await renderActions()({ action: "commit", featureBranch: true });
+ await (
+ await renderActions()
+ )({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.branch).toBe("feature");
@@ -234,7 +265,9 @@ describe("Git actions while thread details load", () => {
state.shell = null;
state.detail = { branch: "main" };
- await renderActions()({ action: "commit", featureBranch: true });
+ await (
+ await renderActions()
+ )({ action: "commit", featureBranch: true });
expect(state.commits).toBe(0);
expect(state.detail.branch).toBe("main");
@@ -245,7 +278,9 @@ describe("Git actions while thread details load", () => {
state.scopes.add(AuthOrchestrationOperateScope);
state.detail = { branch: "feature" };
- await renderActions()({ action: "commit", featureBranch: true });
+ await (
+ await renderActions()
+ )({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.shell?.branch).toBe("feature");
@@ -253,7 +288,7 @@ describe("Git actions while thread details load", () => {
});
it("synchronizes a retained callback after the thread grant is gained", async () => {
- const run = renderActions();
+ const run = await renderActions();
state.scopes.add(AuthOrchestrationOperateScope);
await run({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
@@ -269,7 +304,9 @@ describe("Git actions while thread details load", () => {
async (revokedScope, syncsThread) => {
state.scopes.add(AuthOrchestrationOperateScope);
state.afterGitAction = () => state.scopes.delete(revokedScope);
- await renderActions()({ action: "commit", featureBranch: true });
+ await (
+ await renderActions()
+ )({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.branch).toBe("feature");
expect(state.shell?.branch).toBe(syncsThread ? "feature" : "main");
@@ -278,7 +315,9 @@ describe("Git actions while thread details load", () => {
);
it("keeps ordinary commits available while details load", async () => {
- await renderActions()({ action: "commit" });
+ await (
+ await renderActions()
+ )({ action: "commit" });
expect(state.commits).toBe(1);
expect(state.branch).toBe("main");
@@ -287,7 +326,9 @@ describe("Git actions while thread details load", () => {
it("keeps feature-branch commits available for a local draft", async () => {
state.shell = null;
state.draft = { branch: "main", worktreePath: null, envMode: "local" };
- await renderActions()({ action: "commit", featureBranch: true });
+ await (
+ await renderActions()
+ )({ action: "commit", featureBranch: true });
expect(state.commits).toBe(1);
expect(state.draft.branch).toBe("feature");
diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx
index d72fb0f7e6a..04bd3a61cb3 100644
--- a/apps/web/src/components/GitActionsControl.tsx
+++ b/apps/web/src/components/GitActionsControl.tsx
@@ -21,7 +21,7 @@ import type {
} from "@t3tools/contracts";
import { useNavigate } from "@tanstack/react-router";
import * as Option from "effect/Option";
-import { type MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { type MouseEvent, useEffect, useEffectEvent, useRef, useState } from "react";
import { flushSync } from "react-dom";
import {
CheckIcon,
@@ -481,48 +481,38 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
const [publishResult, setPublishResult] = useState<SourceControlPublishRepositoryResult | null>(
null,
);
- const sourceControlScope = useMemo(
- () => ({
- environmentId: props.environmentId,
- cwd: props.gitCwd,
- }),
- [props.environmentId, props.gitCwd],
- );
+ const sourceControlScope = {
+ environmentId: props.environmentId,
+ cwd: props.gitCwd,
+ };
const publishRepositoryAction = useSourceControlPublishRepositoryAction(sourceControlScope);
- const publishAccountByProvider = useMemo(() => {
- const accounts = new Map<string, string | null>();
- for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
- accounts.set(provider.kind, Option.getOrNull(provider.auth.account));
- }
- return accounts;
- }, [sourceControlDiscovery.data]);
- const publishProviderReadiness = useMemo(() => {
- const sourceControlProviders = sourceControlDiscovery.data?.sourceControlProviders ?? [];
- const readiness = new Map(
- PUBLISH_PROVIDER_OPTIONS.map((option) => [
- option.value,
- getPublishProviderReadiness({ provider: option.value, sourceControlProviders }),
- ]),
- );
- return (provider: SourceControlProviderKind) =>
- readiness.get(provider) ?? { ready: false, hint: null };
- }, [sourceControlDiscovery.data]);
- const hasReadyPublishProvider = useMemo(
- () => PUBLISH_PROVIDER_OPTIONS.some((option) => publishProviderReadiness(option.value).ready),
- [publishProviderReadiness],
- );
- const sortedPublishProviderOptions = useMemo(
- () =>
- PUBLISH_PROVIDER_OPTIONS.toSorted((left, right) => {
- const leftReady = publishProviderReadiness(left.value).ready;
- const rightReady = publishProviderReadiness(right.value).ready;
- if (leftReady !== rightReady) {
- return leftReady ? -1 : 1;
- }
- return left.label.localeCompare(right.label);
+ const publishAccountByProvider = new Map<string, string | null>();
+ for (const provider of sourceControlDiscovery.data?.sourceControlProviders ?? []) {
+ publishAccountByProvider.set(provider.kind, Option.getOrNull(provider.auth.account));
+ }
+ const publishSourceControlProviders = sourceControlDiscovery.data?.sourceControlProviders ?? [];
+ const publishReadinessByProvider = new Map(
+ PUBLISH_PROVIDER_OPTIONS.map((option) => [
+ option.value,
+ getPublishProviderReadiness({
+ provider: option.value,
+ sourceControlProviders: publishSourceControlProviders,
}),
- [publishProviderReadiness],
+ ]),
+ );
+ const publishProviderReadiness = (provider: SourceControlProviderKind) =>
+ publishReadinessByProvider.get(provider) ?? { ready: false, hint: null };
+ const hasReadyPublishProvider = PUBLISH_PROVIDER_OPTIONS.some(
+ (option) => publishProviderReadiness(option.value).ready,
);
+ const sortedPublishProviderOptions = PUBLISH_PROVIDER_OPTIONS.toSorted((left, right) => {
+ const leftReady = publishProviderReadiness(left.value).ready;
+ const rightReady = publishProviderReadiness(right.value).ready;
+ if (leftReady !== rightReady) {
+ return leftReady ? -1 : 1;
+ }
+ return left.label.localeCompare(right.label);
+ });
const firstReadyPublishProvider = sortedPublishProviderOptions.find(
(option) => publishProviderReadiness(option.value).ready,
)?.value;
@@ -553,22 +543,17 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
null,
] as const;
- const canSubmitPublishRepository = useMemo(() => {
- if (!publishRepositoryAction.isAllowed || !selectedPublishProviderReadiness.ready) return false;
- if (publishRepositoryAction.isPending) return false;
- const repositoryParts = publishRepository.trim().split("/");
- const owner = repositoryParts[0]?.trim() ?? "";
- const rest = repositoryParts.slice(1);
- const name = rest.join("/").trim();
- return owner.length > 0 && name.length > 0;
- }, [
- publishRepository,
- publishRepositoryAction.isAllowed,
- publishRepositoryAction.isPending,
- selectedPublishProviderReadiness,
- ]);
-
- const submitPublishRepository = useCallback(() => {
+ const publishRepositoryParts = publishRepository.trim().split("/");
+ const publishRepositoryOwner = publishRepositoryParts[0]?.trim() ?? "";
+ const publishRepositoryName = publishRepositoryParts.slice(1).join("/").trim();
+ const canSubmitPublishRepository =
+ publishRepositoryAction.isAllowed &&
+ selectedPublishProviderReadiness.ready &&
+ !publishRepositoryAction.isPending &&
+ publishRepositoryOwner.length > 0 &&
+ publishRepositoryName.length > 0;
+
+ const submitPublishRepository = () => {
if (!canSubmitPublishRepository) {
return;
}
@@ -597,41 +582,28 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {
setPublishWizardStep(2);
});
})();
- }, [
- canSubmitPublishRepository,
- props.environmentId,
- props.gitCwd,
- publishProtocol,
- publishProvider,
- publishRemoteName,
- publishRepository,
- publishRepositoryAction,
- publishVisibility,
- ]);
+ };
- const resetState = useCallback(() => {
+ const resetState = () => {
setPublishRemoteName("origin");
setPublishRepositoryOverride(null);
setPublishWizardStep(0);
setPublishAdvancedOpen(false);
setPublishError(null);
setPublishResult(null);
- }, []);
+ };
- const handleOpenChange = useCallback(
- (open: boolean) => {
- props.onOpenChange(open);
- if (!open) {
- resetState();
- }
- },
- [props, resetState],
- );
+ const handleOpenChange = (open: boolean) => {
+ props.onOpenChange(open);
+ if (!open) {
+ resetState();
+ }
+ };
- const openSourceControlSettings = useCallback(() => {
+ const openSourceControlSettings = () => {
handleOpenChange(false);
void navigate({ to: "/settings/source-control" });
- }, [handleOpenChange, navigate]);
+ };
return (
<Dialog open={props.open} onOpenChange={handleOpenChange}>
@@ -1009,10 +981,7 @@ export default function GitActionsControl({
activeEnvironmentId,
serverConfig?.availableEditors ?? [],
);
- const threadToastData = useMemo(
- () => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
- [activeThreadRef],
- );
+ const threadToastData = activeThreadRef ? { threadRef: activeThreadRef } : undefined;
const activeServerThreadShell = useThreadShell(activeThreadRef);
const openPrLink = useOpenPrLink(activeThreadRef ?? undefined);
const activeDraftThread = useComposerDraftStore((store) =>
@@ -1038,10 +1007,7 @@ export default function GitActionsControl({
const [inlineSuccess, setInlineSuccess] = useState<InlineGitActionSuccess | null>(null);
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
- const sourceControlScope = useMemo(
- () => ({ environmentId: activeEnvironmentId, cwd: gitCwd }),
- [activeEnvironmentId, gitCwd],
- );
+ const sourceControlScope = { environmentId: activeEnvironmentId, cwd: gitCwd };
const vcsActionState = useAtomValue(vcsActionManager.stateAtom(sourceControlScope));
const visibleInlineSuccess = inlineSuccess?.scopeKey === successScopeKey ? inlineSuccess : null;
@@ -1053,65 +1019,55 @@ export default function GitActionsControl({
return () => window.clearTimeout(timeoutId);
}, [inlineSuccess]);
- const persistThreadBranchSync = useCallback(
- (branch: string | null, manualSelection = false) => {
- if (!activeThreadRef) {
+ const persistThreadBranchSync = (branch: string | null, manualSelection = false) => {
+ if (!activeThreadRef) {
+ return;
+ }
+
+ if (activeServerThread) {
+ if (
+ !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) ||
+ activeServerThread.branch === branch
+ ) {
return;
}
- if (activeServerThread) {
- if (
- !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) ||
- activeServerThread.branch === branch
- ) {
- return;
- }
-
- void updateThreadMetadata({
- environmentId: activeThreadRef.environmentId,
- input: {
- threadId: activeThreadRef.threadId,
- ...resolveThreadBranchMetadataPatch(branch, activeServerThread.branch),
- },
- });
+ void updateThreadMetadata({
+ environmentId: activeThreadRef.environmentId,
+ input: {
+ threadId: activeThreadRef.threadId,
+ ...resolveThreadBranchMetadataPatch(branch, activeServerThread.branch),
+ },
+ });
- return;
- }
+ return;
+ }
- if (!activeDraftThread || activeDraftThread.branch === branch) {
- return;
- }
+ if (!activeDraftThread || activeDraftThread.branch === branch) {
+ return;
+ }
- setDraftThreadContext(draftId ?? activeThreadRef, {
- branch,
- worktreePath: activeDraftThread.worktreePath,
- environmentSelection: manualSelection
- ? "manual"
- : (activeDraftThread.environmentSelection ??
- (activeDraftThread.branch ? "manual" : "auto")),
- });
- },
- [
- activeDraftThread,
- activeServerThread,
- activeThreadRef,
- draftId,
- setDraftThreadContext,
- updateThreadMetadata,
- ],
- );
+ setDraftThreadContext(draftId ?? activeThreadRef, {
+ branch,
+ worktreePath: activeDraftThread.worktreePath,
+ environmentSelection: manualSelection
+ ? "manual"
+ : (activeDraftThread.environmentSelection ??
+ (activeDraftThread.branch ? "manual" : "auto")),
+ });
+ };
+ const persistLiveThreadBranch = useEffectEvent((branch: string | null) => {
+ persistThreadBranchSync(branch);
+ });
- const syncThreadBranchAfterGitAction = useCallback(
- (result: GitRunStackedActionResult) => {
- const branchUpdate = resolveThreadBranchUpdate(result);
- if (!branchUpdate) {
- return;
- }
+ const syncThreadBranchAfterGitAction = (result: GitRunStackedActionResult) => {
+ const branchUpdate = resolveThreadBranchUpdate(result);
+ if (!branchUpdate) {
+ return;
+ }
- persistThreadBranchSync(branchUpdate.branch, true);
- },
- [persistThreadBranchSync],
- );
+ persistThreadBranchSync(branchUpdate.branch, true);
+ };
const gitStatusQuery = useEnvironmentQuery(
activeEnvironmentId !== null && gitCwd !== null
@@ -1125,10 +1081,7 @@ export default function GitActionsControl({
reportFailure: false,
});
const { data: gitStatus, error: gitStatusError } = gitStatusQuery;
- const sourceControlPresentation = useMemo(
- () => getSourceControlPresentation(gitStatus?.sourceControlProvider),
- [gitStatus?.sourceControlProvider],
- );
+ const sourceControlPresentation = getSourceControlPresentation(gitStatus?.sourceControlProvider);
const changeRequestTerminology = sourceControlPresentation.terminology;
const SourceControlIcon = sourceControlPresentation.Icon;
const isRepo = gitStatus?.isRepo ?? true;
@@ -1166,28 +1119,27 @@ export default function GitActionsControl({
return;
}
- persistThreadBranchSync(branchUpdate.branch);
+ persistLiveThreadBranch(branchUpdate.branch);
}, [
activeServerThread,
activeDraftThread?.branch,
gitStatusForActions,
isGitActionRunning,
isSelectingWorktreeBase,
- persistThreadBranchSync,
]);
- const isDefaultRef = useMemo(() => {
- return gitStatusForActions?.isDefaultRef ?? false;
- }, [gitStatusForActions?.isDefaultRef]);
+ const isDefaultRef = gitStatusForActions?.isDefaultRef ?? false;
- const gitActionMenuItems = useMemo(
- () => buildMenuItems(gitStatusForActions, isGitActionRunning, hasPrimaryRemote),
- [gitStatusForActions, hasPrimaryRemote, isGitActionRunning],
+ const gitActionMenuItems = buildMenuItems(
+ gitStatusForActions,
+ isGitActionRunning,
+ hasPrimaryRemote,
);
- const quickAction = useMemo(
- () =>
- resolveQuickAction(gitStatusForActions, isGitActionRunning, isDefaultRef, hasPrimaryRemote),
- [gitStatusForActions, hasPrimaryRemote, isDefaultRef, isGitActionRunning],
+ const quickAction = resolveQuickAction(
+ gitStatusForActions,
+ isGitActionRunning,
+ isDefaultRef,
+ hasPrimaryRemote,
);
const quickActionDisabledReason = !canWriteSourceControl
? "This connection cannot change source control."
@@ -1239,176 +1191,160 @@ export default function GitActionsControl({
// React 19.2 leaves useEffectEvent stale inside the memoized details panel.
// Bind each render's actions to its checkout and thread, including retained toast actions.
- const runGitActionWithToast = useCallback(
- async function runGitActionWithToast({
- action,
- commitMessage,
- onConfirmed,
- skipDefaultBranchPrompt = false,
- statusOverride,
- featureBranch = false,
- filePaths,
- }: RunGitActionWithToastInput) {
- if (
- activeEnvironmentId === null ||
- !readEnvironmentScope(activeEnvironmentId, AuthSourceControlWriteScope) ||
- (featureBranch &&
- !isLocalDraftThread &&
- !readEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope))
- )
- return;
- const actionStatus = statusOverride ?? gitStatusForActions;
- const actionBranch = actionStatus?.refName ?? null;
- const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
- const actionCanCommit =
- action === "commit" || action === "commit_push" || action === "commit_push_pr";
- const includesCommit =
- actionCanCommit &&
- (action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch);
+ async function runGitActionWithToast({
+ action,
+ commitMessage,
+ onConfirmed,
+ skipDefaultBranchPrompt = false,
+ statusOverride,
+ featureBranch = false,
+ filePaths,
+ }: RunGitActionWithToastInput) {
+ if (
+ activeEnvironmentId === null ||
+ !readEnvironmentScope(activeEnvironmentId, AuthSourceControlWriteScope) ||
+ (featureBranch &&
+ !isLocalDraftThread &&
+ !readEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope))
+ )
+ return;
+ const actionStatus = statusOverride ?? gitStatusForActions;
+ const actionBranch = actionStatus?.refName ?? null;
+ const actionIsDefaultBranch = featureBranch ? false : isDefaultRef;
+ const actionCanCommit =
+ action === "commit" || action === "commit_push" || action === "commit_push_pr";
+ const includesCommit =
+ actionCanCommit &&
+ (action === "commit" || !!actionStatus?.hasWorkingTreeChanges || featureBranch);
+ if (
+ !skipDefaultBranchPrompt &&
+ requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
+ actionBranch
+ ) {
if (
- !skipDefaultBranchPrompt &&
- requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
- actionBranch
+ action !== "push" &&
+ action !== "create_pr" &&
+ action !== "commit_push" &&
+ action !== "commit_push_pr"
) {
- if (
- action !== "push" &&
- action !== "create_pr" &&
- action !== "commit_push" &&
- action !== "commit_push_pr"
- ) {
- return;
- }
- setPendingDefaultBranchAction({
- action,
- branchName: actionBranch,
- includesCommit,
- ...(commitMessage ? { commitMessage } : {}),
- ...(onConfirmed ? { onConfirmed } : {}),
- ...(filePaths ? { filePaths } : {}),
- });
return;
}
- onConfirmed?.();
- setInlineSuccess(null);
-
- const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
- const actionId = randomUUID();
-
- const result = await runImmediateGitAction.run({
- actionId,
+ setPendingDefaultBranchAction({
action,
+ branchName: actionBranch,
+ includesCommit,
...(commitMessage ? { commitMessage } : {}),
- ...(featureBranch ? { featureBranch } : {}),
+ ...(onConfirmed ? { onConfirmed } : {}),
...(filePaths ? { filePaths } : {}),
- ...(activeServerThread ? { threadId: activeServerThread.id } : {}),
- ...(activeDraftThread ? { projectId: activeDraftThread.projectId } : {}),
});
+ return;
+ }
+ onConfirmed?.();
+ setInlineSuccess(null);
- if (result._tag === "Failure") {
- if (isAtomCommandInterrupted(result)) {
- return;
- }
+ const scopedToastData = threadToastData ? { ...threadToastData } : undefined;
+ const actionId = randomUUID();
- const error = squashAtomCommandFailure(result);
- const errorToastTiming = resolveGitActionResultToastTiming("error");
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Action failed",
- description: error instanceof Error ? error.message : "An error occurred.",
- timeout: errorToastTiming.timeout,
- ...(scopedToastData !== undefined ? { data: scopedToastData } : {}),
- }),
- );
- return;
- }
+ const result = await runImmediateGitAction.run({
+ actionId,
+ action,
+ ...(commitMessage ? { commitMessage } : {}),
+ ...(featureBranch ? { featureBranch } : {}),
+ ...(filePaths ? { filePaths } : {}),
+ ...(activeServerThread ? { threadId: activeServerThread.id } : {}),
+ ...(activeDraftThread ? { projectId: activeDraftThread.projectId } : {}),
+ });
- const actionResult = result.value;
- syncThreadBranchAfterGitAction(actionResult);
- if (isPanel) {
- setInlineSuccess({
- title: actionResult.toast.title,
- description: actionResult.toast.description ?? null,
- scopeKey: successScopeKey,
- });
+ if (result._tag === "Failure") {
+ if (isAtomCommandInterrupted(result)) {
return;
}
- let resultToastId: GitActionToastId | null = null;
- const closeResultToast = () => {
- if (resultToastId !== null) {
- toastManager.close(resultToastId);
- }
- };
- const toastCta = actionResult.toast.cta;
- let toastActionProps: {
- children: string;
- onClick: (event: MouseEvent<HTMLButtonElement>) => void;
- } | null = null;
- if (toastCta.kind === "run_action") {
- toastActionProps = {
- children: toastCta.label,
- onClick: () => {
- closeResultToast();
- void runGitActionWithToast({
- action: toastCta.action.kind,
- });
- },
- };
- } else if (toastCta.kind === "open_pr") {
- toastActionProps = {
- children: toastCta.label,
- onClick: (event) => {
- closeResultToast();
- openPrLink(event, toastCta.url);
- },
- };
+ const error = squashAtomCommandFailure(result);
+ const errorToastTiming = resolveGitActionResultToastTiming("error");
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Action failed",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ timeout: errorToastTiming.timeout,
+ ...(scopedToastData !== undefined ? { data: scopedToastData } : {}),
+ }),
+ );
+ return;
+ }
+
+ const actionResult = result.value;
+ syncThreadBranchAfterGitAction(actionResult);
+ if (isPanel) {
+ setInlineSuccess({
+ title: actionResult.toast.title,
+ description: actionResult.toast.description ?? null,
+ scopeKey: successScopeKey,
+ });
+ return;
+ }
+ let resultToastId: GitActionToastId | null = null;
+ const closeResultToast = () => {
+ if (resultToastId !== null) {
+ toastManager.close(resultToastId);
}
+ };
- const successToastTiming = resolveGitActionResultToastTiming("success");
- const successToastData = {
- ...scopedToastData,
- ...(successToastTiming.dismissAfterVisibleMs !== null
- ? { dismissAfterVisibleMs: successToastTiming.dismissAfterVisibleMs }
- : {}),
+ const toastCta = actionResult.toast.cta;
+ let toastActionProps: {
+ children: string;
+ onClick: (event: MouseEvent<HTMLButtonElement>) => void;
+ } | null = null;
+ if (toastCta.kind === "run_action") {
+ toastActionProps = {
+ children: toastCta.label,
+ onClick: () => {
+ closeResultToast();
+ void runGitActionWithToast({
+ action: toastCta.action.kind,
+ });
+ },
};
+ } else if (toastCta.kind === "open_pr") {
+ toastActionProps = {
+ children: toastCta.label,
+ onClick: (event) => {
+ closeResultToast();
+ openPrLink(event, toastCta.url);
+ },
+ };
+ }
- if (toastActionProps) {
- resultToastId = toastManager.add(
- stackedThreadToast({
- type: "success",
- title: actionResult.toast.title,
- description: actionResult.toast.description,
- timeout: successToastTiming.timeout,
- actionProps: toastActionProps,
- data: successToastData,
- }),
- );
- } else {
- resultToastId = toastManager.add({
+ const successToastTiming = resolveGitActionResultToastTiming("success");
+ const successToastData = {
+ ...scopedToastData,
+ ...(successToastTiming.dismissAfterVisibleMs !== null
+ ? { dismissAfterVisibleMs: successToastTiming.dismissAfterVisibleMs }
+ : {}),
+ };
+
+ if (toastActionProps) {
+ resultToastId = toastManager.add(
+ stackedThreadToast({
type: "success",
title: actionResult.toast.title,
description: actionResult.toast.description,
timeout: successToastTiming.timeout,
+ actionProps: toastActionProps,
data: successToastData,
- });
- }
- },
- [
- activeDraftThread,
- activeEnvironmentId,
- activeServerThread,
- gitStatusForActions,
- isDefaultRef,
- isLocalDraftThread,
- isPanel,
- openPrLink,
- runImmediateGitAction,
- successScopeKey,
- syncThreadBranchAfterGitAction,
- threadToastData,
- ],
- );
+ }),
+ );
+ } else {
+ resultToastId = toastManager.add({
+ type: "success",
+ title: actionResult.toast.title,
+ description: actionResult.toast.description,
+ timeout: successToastTiming.timeout,
+ data: successToastData,
+ });
+ }
+ }
const continuePendingDefaultBranchAction = () => {
if (!pendingDefaultBranchAction) return;
@@ -1424,7 +1360,7 @@ export default function GitActionsControl({
};
const checkoutFeatureBranchAndContinuePendingAction = () => {
- if (!canChangeThreadBranch || !pendingDefaultBranchAction) return;
+ if (!pendingDefaultBranchAction) return;
const { action, commitMessage, onConfirmed, filePaths } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
@@ -1438,7 +1374,7 @@ export default function GitActionsControl({
};
const runDialogActionOnNewBranch = () => {
- if (!canChangeThreadBranch || !isCommitDialogOpen) return;
+ if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
@@ -1551,35 +1487,32 @@ export default function GitActionsControl({
});
};
- const openChangedFileInEditor = useCallback(
- (filePath: string) => {
- if (!gitCwd) {
- toastManager.add({
- type: "error",
- title: "Editor opening is unavailable.",
- data: threadToastData,
- });
+ const openChangedFileInEditor = (filePath: string) => {
+ if (!gitCwd) {
+ toastManager.add({
+ type: "error",
+ title: "Editor opening is unavailable.",
+ data: threadToastData,
+ });
+ return;
+ }
+ const target = resolvePathLinkTarget(filePath, gitCwd);
+ void (async () => {
+ const result = await openInPreferredEditor(target);
+ if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
return;
}
- const target = resolvePathLinkTarget(filePath, gitCwd);
- void (async () => {
- const result = await openInPreferredEditor(target);
- if (result._tag === "Success" || isAtomCommandInterrupted(result)) {
- return;
- }
- const error = squashAtomCommandFailure(result);
- toastManager.add(
- stackedThreadToast({
- type: "error",
- title: "Unable to open file",
- description: error instanceof Error ? error.message : "An error occurred.",
- ...(threadToastData !== undefined ? { data: threadToastData } : {}),
- }),
- );
- })();
- },
- [gitCwd, openInPreferredEditor, threadToastData],
- );
+ const error = squashAtomCommandFailure(result);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Unable to open file",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ ...(threadToastData !== undefined ? { data: threadToastData } : {}),
+ }),
+ );
+ })();
+ };
const canPublishRepository =
canWriteSourceControl && isRepo && gitStatusForActions !== null && !hasPrimaryRemote;