Compare commits

...
Author SHA1 Message Date
Julius Marmingeandcodex 839feaf250 fix: address latest git action review feedback
Co-authored-by: codex <[email protected]>
2026-03-01 19:50:05 -08:00
Julius Marmingeandcodex 075df4ef4f fix: reuse git action toast after feature-branch checkout
Co-authored-by: codex <[email protected]>
2026-03-01 19:29:40 -08:00
Julius Marmingeandcodex e4ab109427 fix: widen default-branch action dialog
Co-authored-by: codex <[email protected]>
2026-03-01 19:28:29 -08:00
Cursor AgentandJulius Marminge 522d929ce9 Fix: reset hasUpstream, aheadCount, behindCount in statusOverride after branch checkout
Co-authored-by: Julius Marminge <[email protected]>

Applied via @cursor push command
2026-03-02 03:20:28 +00:00
Julius Marmingeandcodex bb7c9c7af4 fix: make default-branch confirmation copy action-aware
Co-authored-by: codex <[email protected]>
2026-03-01 19:00:53 -08:00
Julius Marmingeandcodex 3a81ca2aaf test: use dynamic default branch in remote-base-ahead case
Co-authored-by: codex <[email protected]>
2026-03-01 15:53:44 -08:00
Julius Marmingeandcodex 7475e522b3 fix: resolve no-upstream base from origin tracking branches
Co-authored-by: codex <[email protected]>
2026-03-01 13:35:57 -08:00
Julius Marmingeandcodex a511de39da fix: keep toast CTA git actions on the active feature branch
Co-authored-by: codex <[email protected]>
2026-03-01 11:55:07 -08:00
Julius Marmingeandcodex 0697ff8123 fix: avoid no-upstream push skip when base cannot be resolved
Co-authored-by: codex <[email protected]>
2026-03-01 11:36:41 -08:00
Julius Marmingeandcodex 425b32fcec refactor: dedupe git action new-branch flow
Co-authored-by: codex <[email protected]>
2026-03-01 11:34:36 -08:00
Julius Marminge 79f636ae90 Handle no-upstream branches by comparing commits against base
- Compute ahead count from base branch when upstream is missing
- Skip push/PR actions when no local commits are ahead
- Update server and UI tests for no-upstream push/PR behavior
2026-03-01 11:28:44 -08:00
Julius Marminge a059886e9d Require ahead commits before offering Create PR on untracked branches
- Change quick action to `Push` (not `Push & create PR`) when branch has no upstream and is not ahead
- Keep `Create PR` menu item disabled until the branch has commits ahead
- Add/adjust logic tests for both no-ahead and ahead scenarios
2026-03-01 11:07:27 -08:00
Julius Marminge 57ebd79211 Add coverage for no-upstream default-branch quick actions
- test push-only quick action on default branch without upstream
- verify push and create PR stay disabled when branch is behind
2026-03-01 11:00:13 -08:00
Julius Marminge 4dfc28ff26 Enable push/PR actions for branches without upstream
- Treat no-upstream branches as publishable: enable Push/Create PR and update quick actions
- Route Create PR menu action through commit+push+PR flow when appropriate
- Simplify Git action dialog to commit-only and add "Commit on new branch" option
2026-03-01 10:58:38 -08:00
Julius Marminge 1d34656952 Add default-branch safeguard with auto feature branch fallback
- Prompt before commit/push actions on the default branch
- Allow one-click create+checkout of an auto-named feature branch and continue
- Add logic/tests for date-based unique auto feature branch naming
2026-02-28 23:28:29 -08:00
6 changed files with 900 additions and 154 deletions

No files matched your search

+129
View File
@@ -972,6 +972,135 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-ahead" });
yield* writeTextFile(path.join(tmp, "feature.txt"), "ahead of base\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature commit"]);
const details = yield* core.statusDetails(tmp);
expect(details.branch).toBe("feature/no-upstream-ahead");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect(
"computes ahead count against origin/default when local default branch is missing",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const initialBranch = (yield* listGitBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", initialBranch]);
yield* git(source, ["checkout", "-b", "feature/remote-base-only"]);
yield* writeTextFile(
path.join(source, "feature.txt"),
`ahead of origin/${initialBranch}\n`,
);
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature commit"]);
yield* git(source, ["branch", "-D", initialBranch]);
const core = yield* GitCore;
const details = yield* core.statusDetails(source);
expect(details.branch).toBe("feature/remote-base-only");
expect(details.hasUpstream).toBe(false);
expect(details.aheadCount).toBe(1);
expect(details.behindCount).toBe(0);
}),
);
it.effect("skips push when no upstream is configured and branch is not ahead of base", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const core = yield* GitCore;
yield* core.createBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
yield* core.checkoutBranch({ cwd: tmp, branch: "feature/no-upstream-no-ahead" });
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("skipped_up_to_date");
expect(pushed.branch).toBe("feature/no-upstream-no-ahead");
expect(pushed.setUpstream).toBeUndefined();
}),
);
it.effect("pushes with upstream setup when no comparable base branch exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(tmp, ["init", "--initial-branch=trunk"]);
yield* git(tmp, ["config", "user.email", "[email protected]"]);
yield* git(tmp, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(tmp, "README.md"), "hello\n");
yield* git(tmp, ["add", "README.md"]);
yield* git(tmp, ["commit", "-m", "initial"]);
yield* git(remote, ["init", "--bare"]);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["checkout", "-b", "feature/no-base"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe("origin/feature/no-base");
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
"origin/feature/no-base",
);
}),
);
it.effect(
"pushes with upstream setup when comparable base exists but remote branch is missing",
() =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
yield* initRepoWithCommit(tmp);
const initialBranch = (yield* listGitBranches({ cwd: tmp })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* writeTextFile(path.join(tmp, "default-ahead.txt"), "ahead on default\n");
yield* git(tmp, ["add", "default-ahead.txt"]);
yield* git(tmp, ["commit", "-m", "default ahead"]);
const featureBranch = "feature/publish-no-upstream";
yield* git(tmp, ["checkout", "-b", featureBranch]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(true);
expect(pushed.upstreamBranch).toBe(`origin/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`origin/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", "origin", featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
+155 -6
View File
@@ -7,6 +7,7 @@ import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
class StatusUpstreamRefreshCacheKey extends Data.Class<{
cwd: string;
@@ -80,6 +81,16 @@ function commandLabel(args: readonly string[]): string {
return `git ${args.join(" ")}`;
}
function parseDefaultBranchFromRemoteHeadRef(value: string): string | null {
const trimmed = value.trim();
const prefix = "refs/remotes/origin/";
if (!trimmed.startsWith(prefix)) {
return null;
}
const branch = trimmed.slice(prefix.length).trim();
return branch.length > 0 ? branch : null;
}
function createGitCommandError(
operation: string,
cwd: string,
@@ -259,6 +270,108 @@ const makeGitCore = Effect.gen(function* () {
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
executeGit("GitCore.resolveDefaultBranchName", cwd, ["symbolic-ref", "refs/remotes/origin/HEAD"], {
allowNonZeroExit: true,
}).pipe(
Effect.map((result) => {
if (result.code !== 0) {
return null;
}
return parseDefaultBranchFromRemoteHeadRef(result.stdout);
}),
);
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
executeGit("GitCore.branchExists", cwd, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0));
const remoteBranchExists = (
cwd: string,
branch: string,
): Effect.Effect<boolean, GitCommandError> =>
executeGit(
"GitCore.remoteBranchExists",
cwd,
["show-ref", "--verify", "--quiet", `refs/remotes/origin/${branch}`],
{
allowNonZeroExit: true,
},
).pipe(Effect.map((result) => result.code === 0));
const originRemoteExists = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], {
allowNonZeroExit: true,
}).pipe(Effect.map((result) => result.code === 0));
const resolveBaseBranchForNoUpstream = (
cwd: string,
branch: string,
): Effect.Effect<string | null, GitCommandError> =>
Effect.gen(function* () {
const configuredBaseBranch = yield* runGitStdout(
"GitCore.resolveBaseBranchForNoUpstream.config",
cwd,
["config", "--get", `branch.${branch}.gh-merge-base`],
true,
).pipe(Effect.map((stdout) => stdout.trim()));
const defaultBranch = yield* resolveDefaultBranchName(cwd);
const candidates = [
configuredBaseBranch.length > 0 ? configuredBaseBranch : null,
defaultBranch,
...DEFAULT_BASE_BRANCH_CANDIDATES,
];
for (const candidate of candidates) {
if (!candidate) {
continue;
}
const normalizedCandidate = candidate.startsWith("origin/")
? candidate.slice("origin/".length)
: candidate;
if (normalizedCandidate.length === 0 || normalizedCandidate === branch) {
continue;
}
if (yield* branchExists(cwd, normalizedCandidate)) {
return normalizedCandidate;
}
if (yield* remoteBranchExists(cwd, normalizedCandidate)) {
return `origin/${normalizedCandidate}`;
}
}
return null;
});
const computeAheadCountAgainstBase = (
cwd: string,
branch: string,
): Effect.Effect<number, GitCommandError> =>
Effect.gen(function* () {
const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch);
if (!baseBranch) {
return 0;
}
const result = yield* executeGit(
"GitCore.computeAheadCountAgainstBase",
cwd,
["rev-list", "--count", `${baseBranch}..HEAD`],
{ allowNonZeroExit: true },
);
if (result.code !== 0) {
return 0;
}
const parsed = Number.parseInt(result.stdout.trim(), 10);
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
});
const readBranchRecency = (cwd: string): Effect.Effect<Map<string, number>, GitCommandError> =>
Effect.gen(function* () {
const branchRecency = yield* executeGit(
@@ -343,6 +456,14 @@ const makeGitCore = Effect.gen(function* () {
if (pathValue) changedFilesWithoutNumstat.add(pathValue);
}
}
if (!upstreamRef && branch) {
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(0)),
);
behindCount = 0;
}
const stagedEntries = parseNumstatEntries(stagedNumstatStdout);
const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout);
const fileStatMap = new Map<string, { insertions: number; deletions: number }>();
@@ -452,12 +573,40 @@ const makeGitCore = Effect.gen(function* () {
);
}
if (details.hasUpstream && details.aheadCount === 0 && details.behindCount === 0) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0;
if (hasNoLocalDelta) {
if (details.hasUpstream) {
return {
status: "skipped_up_to_date" as const,
branch,
...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}),
};
}
const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(null)),
);
if (comparableBaseBranch) {
const hasOriginRemote = yield* originRemoteExists(cwd).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (!hasOriginRemote) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
const hasRemoteBranch = yield* remoteBranchExists(cwd, branch).pipe(
Effect.catch(() => Effect.succeed(false)),
);
if (hasRemoteBranch) {
return {
status: "skipped_up_to_date" as const,
branch,
};
}
}
}
if (!details.hasUpstream) {
@@ -551,6 +551,56 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect(
"pushes and creates PR from a no-upstream branch when local commits are ahead of base",
() =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
yield* runGit(repoDir, ["checkout", "-b", "feature/no-upstream-pr"]);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
fs.writeFileSync(path.join(repoDir, "feature.txt"), "feature\n");
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
"[]",
JSON.stringify([
{
number: 77,
title: "Add no-upstream PR flow",
url: "https://github.com/pingdotgg/codething-mvp/pull/77",
baseRefName: "main",
headRefName: "feature/no-upstream-pr",
},
]),
],
},
});
const result = yield* runStackedAction(manager, {
cwd: repoDir,
action: "commit_push_pr",
});
expect(result.commit.status).toBe("created");
expect(result.push.status).toBe("pushed");
expect(result.push.setUpstream).toBe(true);
expect(result.pr.status).toBe("created");
expect(
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "@{upstream}"]).pipe(
Effect.map((result) => result.stdout.trim()),
),
).toBe("origin/feature/no-upstream-pr");
expect(
ghCalls.some((call) =>
call.includes("pr create --base main --head feature/no-upstream-pr"),
),
).toBe(true);
}),
);
it.effect("skips push when branch is already up to date", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
@@ -4,6 +4,8 @@ import {
buildGitActionProgressStages,
buildMenuItems,
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
@@ -514,19 +516,20 @@ describe("when: HEAD is detached and there are no local changes", () => {
});
describe("when: branch has no upstream configured", () => {
it("resolveQuickAction returns disabled commit state when clean and no commits are ahead", () => {
it("resolveQuickAction is disabled when clean, no upstream, and no local commits are ahead", () => {
const quick = resolveQuickAction(
status({ hasUpstream: false, pr: null, aheadCount: 0 }),
false,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Commit",
label: "Push",
hint: "No local commits to push.",
disabled: true,
});
});
it("resolveQuickAction remains disabled when clean, no upstream, and no local commits ahead", () => {
it("resolveQuickAction opens PR when clean, no upstream, no local commits are ahead, and PR exists", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
@@ -543,9 +546,9 @@ describe("when: branch has no upstream configured", () => {
false,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Commit",
disabled: true,
kind: "open_pr",
label: "Open PR",
disabled: false,
});
});
@@ -605,6 +608,132 @@ describe("when: branch has no upstream configured", () => {
},
]);
});
it("resolveQuickAction runs push and create PR when no upstream and commits are ahead", () => {
const quick = resolveQuickAction(
status({
hasUpstream: false,
aheadCount: 2,
pr: null,
}),
false,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push_pr",
label: "Push & create PR",
disabled: false,
});
});
it("buildMenuItems enables create PR when no upstream and commits are ahead", () => {
const items = buildMenuItems(
status({ hasUpstream: false, pr: null, aheadCount: 2 }),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: false,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: false,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
it("resolveQuickAction is disabled on default branch when no upstream exists and no commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
hasUpstream: false,
aheadCount: 0,
pr: null,
}),
false,
true,
);
assert.deepInclude(quick, {
kind: "show_hint",
label: "Push",
hint: "No local commits to push.",
disabled: true,
});
});
it("resolveQuickAction uses push-only on default branch when no upstream exists and commits are ahead", () => {
const quick = resolveQuickAction(
status({
branch: "main",
hasUpstream: false,
aheadCount: 1,
pr: null,
}),
false,
true,
);
assert.deepInclude(quick, {
kind: "run_action",
action: "commit_push",
label: "Push",
disabled: false,
});
});
it("buildMenuItems still disables push and create PR when branch is behind", () => {
const items = buildMenuItems(
status({
hasUpstream: false,
behindCount: 1,
aheadCount: 0,
pr: null,
}),
false,
);
assert.deepEqual(items, [
{
id: "commit",
label: "Commit",
disabled: true,
icon: "commit",
kind: "open_dialog",
dialogAction: "commit",
},
{
id: "push",
label: "Push",
disabled: true,
icon: "push",
kind: "open_dialog",
dialogAction: "push",
},
{
id: "pr",
label: "Create PR",
disabled: true,
icon: "pr",
kind: "open_dialog",
dialogAction: "create_pr",
},
]);
});
});
describe("requiresDefaultBranchConfirmation", () => {
@@ -616,6 +745,53 @@ describe("requiresDefaultBranchConfirmation", () => {
});
});
describe("resolveDefaultBranchActionDialogCopy", () => {
it("uses push-only copy when pushing without a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push",
branchName: "main",
includesCommit: false,
});
assert.deepEqual(copy, {
title: "Push to default branch?",
description:
'This action will push local commits on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Push to main",
});
});
it("uses push-and-pr copy when creating a PR without a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push_pr",
branchName: "main",
includesCommit: false,
});
assert.deepEqual(copy, {
title: "Push & create PR from default branch?",
description:
'This action will push local commits and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Push & create PR",
});
});
it("keeps commit copy when the action includes a commit", () => {
const copy = resolveDefaultBranchActionDialogCopy({
action: "commit_push_pr",
branchName: "main",
includesCommit: true,
});
assert.deepEqual(copy, {
title: "Commit, push & create PR from default branch?",
description:
'This action will commit, push, and create a PR on "main". You can continue on this branch or create a feature branch and run the same action there.',
continueLabel: "Commit, push & create PR",
});
});
});
describe("buildGitActionProgressStages", () => {
it("shows only push progress when push-only is forced", () => {
const stages = buildGitActionProgressStages({
@@ -732,3 +908,20 @@ describe("summarizeGitResult", () => {
});
});
});
describe("resolveAutoFeatureBranchName", () => {
const day = new Date("2026-03-01T12:00:00.000Z");
it("returns the base auto feature branch name when available", () => {
const branch = resolveAutoFeatureBranchName(["main", "feature/other"], day);
assert.equal(branch, "feature/stacked-20260301");
});
it("increments suffix when the base name already exists", () => {
const branch = resolveAutoFeatureBranchName(
["main", "feature/stacked-20260301", "feature/stacked-20260301-2"],
day,
);
assert.equal(branch, "feature/stacked-20260301-3");
});
});
@@ -25,8 +25,17 @@ export interface GitQuickAction {
hint?: string;
}
export interface DefaultBranchActionDialogCopy {
title: string;
description: string;
continueLabel: string;
}
export type DefaultBranchConfirmableAction = "commit_push" | "commit_push_pr";
const SHORT_SHA_LENGTH = 7;
const TOAST_DESCRIPTION_MAX = 72;
const AUTO_FEATURE_BRANCH_PREFIX = "feature/stacked";
function shortenSha(sha: string | undefined): string | null {
if (!sha) return null;
@@ -118,7 +127,6 @@ export function buildMenuItems(
!hasChanges &&
!hasOpenPr &&
gitStatus.aheadCount > 0 &&
gitStatus.hasUpstream &&
!isBehind;
const canOpenPr = !isBusy && hasOpenPr;
@@ -204,6 +212,29 @@ export function resolveQuickAction(
};
}
if (!gitStatus.hasUpstream) {
if (!isAhead) {
if (hasOpenPr) {
return { label: "Open PR", disabled: false, kind: "open_pr" };
}
return {
label: "Push",
disabled: true,
kind: "show_hint",
hint: "No local commits to push.",
};
}
if (hasOpenPr || isDefaultBranch) {
return { label: "Push", disabled: false, kind: "run_action", action: "commit_push" };
}
return {
label: "Push & create PR",
disabled: false,
kind: "run_action",
action: "commit_push_pr",
};
}
if (isDiverged) {
return {
label: "Sync branch",
@@ -252,3 +283,67 @@ export function requiresDefaultBranchConfirmation(
if (!isDefaultBranch) return false;
return action === "commit_push" || action === "commit_push_pr";
}
export function resolveDefaultBranchActionDialogCopy(input: {
action: DefaultBranchConfirmableAction;
branchName: string;
includesCommit: boolean;
}): DefaultBranchActionDialogCopy {
const branchLabel = input.branchName;
const suffix = ` on "${branchLabel}". You can continue on this branch or create a feature branch and run the same action there.`;
if (input.action === "commit_push") {
if (input.includesCommit) {
return {
title: "Commit & push to default branch?",
description: `This action will commit and push changes${suffix}`,
continueLabel: `Commit & push to ${branchLabel}`,
};
}
return {
title: "Push to default branch?",
description: `This action will push local commits${suffix}`,
continueLabel: `Push to ${branchLabel}`,
};
}
if (input.includesCommit) {
return {
title: "Commit, push & create PR from default branch?",
description: `This action will commit, push, and create a PR${suffix}`,
continueLabel: `Commit, push & create PR`,
};
}
return {
title: "Push & create PR from default branch?",
description: `This action will push local commits and create a PR${suffix}`,
continueLabel: "Push & create PR",
};
}
function formatDateForBranch(now: Date): string {
const year = now.getUTCFullYear();
const month = String(now.getUTCMonth() + 1).padStart(2, "0");
const day = String(now.getUTCDate()).padStart(2, "0");
return `${year}${month}${day}`;
}
export function resolveAutoFeatureBranchName(
existingBranchNames: readonly string[],
now = new Date(),
): string {
const daySlug = formatDateForBranch(now);
const base = `${AUTO_FEATURE_BRANCH_PREFIX}-${daySlug}`;
const existingNames = new Set(existingBranchNames);
if (!existingNames.has(base)) {
return base;
}
let suffix = 2;
while (existingNames.has(`${base}-${suffix}`)) {
suffix += 1;
}
return `${base}-${suffix}`;
}
+271 -141
View File
@@ -8,9 +8,11 @@ import {
buildMenuItems,
type GitActionIconName,
type GitActionMenuItem,
type GitDialogAction,
type GitQuickAction,
type DefaultBranchConfirmableAction,
requiresDefaultBranchConfirmation,
resolveAutoFeatureBranchName,
resolveDefaultBranchActionDialogCopy,
resolveQuickAction,
summarizeGitResult,
} from "./GitActionsControl.logic";
@@ -32,6 +34,7 @@ import { Textarea } from "~/components/ui/textarea";
import { toastManager } from "~/components/ui/toast";
import {
gitBranchesQueryOptions,
gitCreateBranchAndCheckoutMutationOptions,
gitInitMutationOptions,
gitMutationKeys,
gitPullMutationOptions,
@@ -47,6 +50,17 @@ interface GitActionsControlProps {
activeThreadId: ThreadId | null;
}
interface PendingDefaultBranchAction {
action: DefaultBranchConfirmableAction;
branchName: string;
includesCommit: boolean;
commitMessage?: string;
forcePushOnlyProgress: boolean;
onConfirmed?: () => void;
}
type GitActionToastId = ReturnType<typeof toastManager.add>;
function getMenuActionDisabledReason(
item: GitActionMenuItem,
gitStatus: GitStatusResult | null,
@@ -97,26 +111,15 @@ function getMenuActionDisabledReason(
if (!isAhead) {
return "No local commits to include in a PR.";
}
if (!gitStatus.hasUpstream) {
return "Set an upstream branch before creating a PR.";
}
if (isBehind) {
return "Branch is behind upstream. Pull/rebase before creating a PR.";
}
return "Create PR is currently unavailable.";
}
const DIALOG_TITLE_BY_ACTION = {
commit: "Commit changes",
push: "Push branch",
create_pr: "Create pull request",
};
const DIALOG_DESCRIPTION_BY_ACTION = {
commit: "Review and confirm your commit. Leave the message blank to auto-generate one.",
push: "Push this branch now.",
create_pr: "Create a pull request using generated title/body content.",
};
const COMMIT_DIALOG_TITLE = "Commit changes";
const COMMIT_DIALOG_DESCRIPTION =
"Review and confirm your commit. Leave the message blank to auto-generate one.";
function GitActionItemIcon({ icon }: { icon: GitActionIconName }) {
if (icon === "commit") return <GitCommitIcon />;
@@ -143,8 +146,10 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
[activeThreadId],
);
const queryClient = useQueryClient();
const [activeDialogAction, setActiveDialogAction] = useState<GitDialogAction | null>(null);
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
useState<PendingDefaultBranchAction | null>(null);
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
@@ -167,12 +172,18 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const runImmediateGitActionMutation = useMutation(
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
);
const createBranchAndCheckoutMutation = useMutation(
gitCreateBranchAndCheckoutMutationOptions({ cwd: gitCwd, queryClient }),
);
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
const isRunStackedActionRunning =
useIsMutating({ mutationKey: gitMutationKeys.runStackedAction(gitCwd) }) > 0;
const isCreateBranchAndCheckoutRunning =
useIsMutating({ mutationKey: gitMutationKeys.createBranchAndCheckout(gitCwd) }) > 0;
const isPullRunning = useIsMutating({ mutationKey: gitMutationKeys.pull(gitCwd) }) > 0;
const isGitActionRunning = isRunStackedActionRunning || isPullRunning;
const isGitActionRunning =
isRunStackedActionRunning || isCreateBranchAndCheckoutRunning || isPullRunning;
const isDefaultBranch = useMemo(() => {
const branchName = gitStatusForActions?.branch;
if (!branchName) return false;
@@ -191,23 +202,13 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
const quickActionDisabledReason = quickAction.disabled
? (quickAction.hint ?? "This action is currently unavailable.")
: null;
const maybeConfirmPushToDefaultBranch = useCallback(
async (action: GitStackedAction): Promise<boolean> => {
const api = readNativeApi();
if (!api) return false;
if (
!requiresDefaultBranchConfirmation(action, isDefaultBranch) ||
!gitStatusForActions?.branch
) {
return true;
}
return api.dialogs.confirm(
`You're about to push to the default branch "${gitStatusForActions.branch}". Continue?`,
);
},
[gitStatusForActions?.branch, isDefaultBranch],
);
const pendingDefaultBranchActionCopy = pendingDefaultBranchAction
? resolveDefaultBranchActionDialogCopy({
action: pendingDefaultBranchAction.action,
branchName: pendingDefaultBranchAction.branchName,
includesCommit: pendingDefaultBranchAction.includesCommit,
})
: null;
const openExistingPr = useCallback(async () => {
const api = readNativeApi();
@@ -237,43 +238,82 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
});
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
const runGitActionWithToast = useCallback(
async ({
action,
commitMessage,
forcePushOnlyProgress = false,
onConfirmed,
skipDefaultBranchPrompt = false,
statusOverride,
isDefaultBranchOverride,
progressToastId,
}: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
skipDefaultBranchPrompt?: boolean;
statusOverride?: GitStatusResult | null;
isDefaultBranchOverride?: boolean;
progressToastId?: GitActionToastId;
}) => {
const confirmed = await maybeConfirmPushToDefaultBranch(action);
if (!confirmed) return;
const actionStatus = statusOverride ?? gitStatusForActions;
const actionIsDefaultBranch = isDefaultBranchOverride ?? isDefaultBranch;
const actionBranch = actionStatus?.branch ?? null;
const includesCommit =
!forcePushOnlyProgress && (action === "commit" || !!actionStatus?.hasWorkingTreeChanges);
if (
!skipDefaultBranchPrompt &&
requiresDefaultBranchConfirmation(action, actionIsDefaultBranch) &&
actionBranch
) {
if (action !== "commit_push" && action !== "commit_push_pr") {
return;
}
setPendingDefaultBranchAction({
action,
branchName: actionBranch,
includesCommit,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
});
return;
}
onConfirmed?.();
const pushTarget = gitStatusForActions?.branch
? `origin/${gitStatusForActions.branch}`
: undefined;
const pushTarget = actionBranch ? `origin/${actionBranch}` : undefined;
const progressStages = buildGitActionProgressStages({
action,
hasCustomCommitMessage: !!commitMessage?.trim(),
hasWorkingTreeChanges: !!gitStatusForActions?.hasWorkingTreeChanges,
hasWorkingTreeChanges: !!actionStatus?.hasWorkingTreeChanges,
forcePushOnly: forcePushOnlyProgress,
...(pushTarget ? { pushTarget } : {}),
});
const progressToastId = toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
const resolvedProgressToastId =
progressToastId ??
toastManager.add({
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
if (progressToastId) {
toastManager.update(progressToastId, {
type: "loading",
title: progressStages[0] ?? "Running git action...",
timeout: 0,
data: threadToastData,
});
}
let stageIndex = 0;
const stageInterval = setInterval(() => {
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
toastManager.update(progressToastId, {
toastManager.update(resolvedProgressToastId, {
title: progressStages[stageIndex] ?? "Running git action...",
type: "loading",
timeout: 0,
@@ -295,19 +335,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
stopProgressUpdates();
const resultToast = summarizeGitResult(result);
const existingOpenPrUrl =
gitStatusForActions?.pr?.state === "open" ? gitStatusForActions.pr.url : undefined;
const existingOpenPrUrl = actionStatus?.pr?.state === "open" ? actionStatus.pr.url : undefined;
const prUrl = result.pr.url ?? existingOpenPrUrl;
const shouldOfferPushCta = action === "commit" && result.commit.status === "created";
const shouldOfferOpenPrCta =
(action === "commit_push" || action === "commit_push_pr") && !!prUrl && !isDefaultBranch;
(action === "commit_push" || action === "commit_push_pr") &&
!!prUrl &&
!actionIsDefaultBranch;
const shouldOfferCreatePrCta =
action === "commit_push" && !prUrl && result.push.status === "pushed" && !isDefaultBranch;
action === "commit_push" &&
!prUrl &&
result.push.status === "pushed" &&
!actionIsDefaultBranch;
const closeResultToast = () => {
toastManager.close(progressToastId);
toastManager.close(resolvedProgressToastId);
};
toastManager.update(progressToastId, {
toastManager.update(resolvedProgressToastId, {
type: "success",
title: resultToast.title,
description: resultToast.description,
@@ -325,6 +369,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
action: "commit_push",
forcePushOnlyProgress: true,
onConfirmed: closeResultToast,
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
@@ -347,7 +393,11 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
children: "Create PR",
onClick: () => {
closeResultToast();
setActiveDialogAction("create_pr");
void runGitActionWithToast({
action: "commit_push_pr",
statusOverride: actionStatus,
isDefaultBranchOverride: actionIsDefaultBranch,
});
},
},
}
@@ -355,7 +405,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
});
} catch (err) {
stopProgressUpdates();
toastManager.update(progressToastId, {
toastManager.update(resolvedProgressToastId, {
type: "error",
title: "Action failed",
description: err instanceof Error ? err.message : "An error occurred.",
@@ -365,17 +415,109 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
},
[
gitStatusForActions?.branch,
gitStatusForActions?.hasWorkingTreeChanges,
gitStatusForActions?.pr,
isDefaultBranch,
maybeConfirmPushToDefaultBranch,
runImmediateGitActionMutation,
setActiveDialogAction,
setPendingDefaultBranchAction,
threadToastData,
gitStatusForActions,
],
);
const continuePendingDefaultBranchAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
void runGitActionWithToast({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
skipDefaultBranchPrompt: true,
});
}, [pendingDefaultBranchAction, runGitActionWithToast]);
const checkoutNewBranchAndRunAction = useCallback(
(actionParams: {
action: GitStackedAction;
commitMessage?: string;
forcePushOnlyProgress?: boolean;
onConfirmed?: () => void;
}) => {
const branchName = resolveAutoFeatureBranchName(
branchList?.branches.map((branch) => branch.name) ?? [],
);
const checkoutPromise = createBranchAndCheckoutMutation.mutateAsync(branchName);
const checkoutToastId = toastManager.add({
type: "loading",
title: `Creating ${branchName}...`,
timeout: 0,
data: threadToastData,
});
void checkoutPromise
.then(() => {
const statusOverride = gitStatusForActions
? {
...gitStatusForActions,
branch: branchName,
pr: null,
hasUpstream: false,
aheadCount: 0,
behindCount: 0,
}
: null;
return runGitActionWithToast({
...actionParams,
skipDefaultBranchPrompt: true,
statusOverride,
isDefaultBranchOverride: false,
progressToastId: checkoutToastId,
});
})
.catch((error) => {
toastManager.update(checkoutToastId, {
type: "error",
title: "Failed to checkout feature branch",
description: error instanceof Error ? error.message : "An error occurred.",
data: threadToastData,
});
});
},
[
branchList?.branches,
createBranchAndCheckoutMutation,
gitStatusForActions,
runGitActionWithToast,
threadToastData,
],
);
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
if (!pendingDefaultBranchAction) return;
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } = pendingDefaultBranchAction;
setPendingDefaultBranchAction(null);
checkoutNewBranchAndRunAction({
action,
...(commitMessage ? { commitMessage } : {}),
forcePushOnlyProgress,
...(onConfirmed ? { onConfirmed } : {}),
});
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
const runDialogActionOnNewBranch = useCallback(() => {
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
checkoutNewBranchAndRunAction({
action: "commit",
...(commitMessage ? { commitMessage } : {}),
});
}, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
const runQuickAction = useCallback(() => {
if (quickAction.kind === "open_pr") {
void openExistingPr();
@@ -427,30 +569,31 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
void runGitActionWithToast({ action: "commit_push", forcePushOnlyProgress: true });
return;
}
if (item.dialogAction) {
setActiveDialogAction(item.dialogAction);
if (item.dialogAction === "create_pr") {
void runGitActionWithToast({ action: "commit_push_pr" });
return;
}
setIsCommitDialogOpen(true);
},
[openExistingPr, runGitActionWithToast],
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
);
const runDialogAction = useCallback(() => {
if (!activeDialogAction) return;
const action: GitStackedAction =
activeDialogAction === "commit"
? "commit"
: activeDialogAction === "push"
? "commit_push"
: "commit_push_pr";
const commitMessage = activeDialogAction === "commit" ? dialogCommitMessage.trim() : "";
const forcePushOnlyProgress = activeDialogAction === "push";
setActiveDialogAction(null);
if (!isCommitDialogOpen) return;
const commitMessage = dialogCommitMessage.trim();
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
void runGitActionWithToast({
action,
action: "commit",
...(commitMessage ? { commitMessage } : {}),
...(forcePushOnlyProgress ? { forcePushOnlyProgress } : {}),
});
}, [activeDialogAction, dialogCommitMessage, runGitActionWithToast]);
}, [
dialogCommitMessage,
isCommitDialogOpen,
runGitActionWithToast,
setDialogCommitMessage,
setIsCommitDialogOpen,
]);
const openChangedFileInEditor = useCallback(
(filePath: string) => {
@@ -606,68 +749,29 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
)}
<Dialog
open={activeDialogAction !== null}
open={isCommitDialogOpen}
onOpenChange={(open) => {
if (!open) {
setActiveDialogAction(null);
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
}
}}
>
<DialogPopup>
<DialogHeader>
<DialogTitle>{DIALOG_TITLE_BY_ACTION[activeDialogAction ?? "commit"]}</DialogTitle>
<DialogDescription>
{DIALOG_DESCRIPTION_BY_ACTION[activeDialogAction ?? "commit"]}
</DialogDescription>
<DialogTitle>{COMMIT_DIALOG_TITLE}</DialogTitle>
<DialogDescription>{COMMIT_DIALOG_DESCRIPTION}</DialogDescription>
</DialogHeader>
<DialogPanel className="space-y-4">
<div className="space-y-3 rounded-lg border border-input bg-muted/40 p-3 text-xs">
<div className="grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1">
<span className="text-muted-foreground">Branch</span>
<span className="font-medium">
{gitStatusForActions?.branch ?? "(detached HEAD)"}
<span className="flex items-center justify-between gap-2">
<span className="font-medium">{gitStatusForActions?.branch ?? "(detached HEAD)"}</span>
{isDefaultBranch && (
<span className="text-right text-warning text-xs">Warning: default branch</span>
)}
</span>
{activeDialogAction !== "commit" && (
<>
<span className="text-muted-foreground">Upstream</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasUpstream
? "No upstream configured"
: gitStatusForActions.aheadCount === 0 &&
gitStatusForActions.behindCount === 0
? "Up to date"
: gitStatusForActions.aheadCount > 0 &&
gitStatusForActions.behindCount > 0
? `Diverged (+${gitStatusForActions.aheadCount} / -${gitStatusForActions.behindCount})`
: gitStatusForActions.aheadCount > 0
? `Ahead by ${gitStatusForActions.aheadCount}`
: `Behind by ${gitStatusForActions.behindCount}`}
</span>
<span className="text-muted-foreground">Working tree</span>
<span className="font-medium">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges
? "Clean"
: `${gitStatusForActions.workingTree.files.length} file(s)`}
</span>
<span className="text-muted-foreground">Diff</span>
<span className="font-mono">
{!gitStatusForActions || !gitStatusForActions.hasWorkingTreeChanges ? (
"none"
) : (
<>
<span className="text-success">
+{gitStatusForActions.workingTree.insertions}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
-{gitStatusForActions.workingTree.deletions}
</span>
</>
)}
</span>
</>
)}
</div>
<div className="space-y-1">
<p className="text-muted-foreground">Files</p>
@@ -707,35 +811,61 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
)}
</div>
</div>
{activeDialogAction === "commit" && (
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
)}
<div className="space-y-1">
<p className="text-xs font-medium">Commit message (optional)</p>
<Textarea
value={dialogCommitMessage}
onChange={(event) => setDialogCommitMessage(event.target.value)}
placeholder="Leave empty to auto-generate"
size="sm"
/>
</div>
</DialogPanel>
<DialogFooter>
<Button
variant="outline"
size="sm"
onClick={() => {
setActiveDialogAction(null);
setIsCommitDialogOpen(false);
setDialogCommitMessage("");
}}
>
Cancel
</Button>
<Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
Commit on new branch
</Button>
<Button size="sm" onClick={runDialogAction}>
{activeDialogAction === "commit"
? "Commit"
: activeDialogAction === "push"
? "Push"
: "Create PR"}
Commit
</Button>
</DialogFooter>
</DialogPopup>
</Dialog>
<Dialog
open={pendingDefaultBranchAction !== null}
onOpenChange={(open) => {
if (!open) {
setPendingDefaultBranchAction(null);
}
}}
>
<DialogPopup className="max-w-xl">
<DialogHeader>
<DialogTitle>
{pendingDefaultBranchActionCopy?.title ?? "Run action on default branch?"}
</DialogTitle>
<DialogDescription>{pendingDefaultBranchActionCopy?.description}</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" size="sm" onClick={() => setPendingDefaultBranchAction(null)}>
Abort
</Button>
<Button variant="outline" size="sm" onClick={continuePendingDefaultBranchAction}>
{pendingDefaultBranchActionCopy?.continueLabel ?? "Continue"}
</Button>
<Button size="sm" onClick={checkoutFeatureBranchAndContinuePendingAction}>
Checkout feature branch & continue
</Button>
</DialogFooter>
</DialogPopup>