Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions src/main/ipc/gitIpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2608,4 +2608,58 @@ current branch '${currentBranch}' ahead of base '${baseRef}'.`,
return { success: false, error: error instanceof Error ? error.message : String(error) };
}
});

ipcMain.handle(
'git:delete-remote-branch',
async (_, args: { projectPath: string; branch: string; remote?: string }) => {
try {
const { remoteBranchService } = await import('../services/RemoteBranchService');
const result = await remoteBranchService.deleteRemoteBranch(
args.projectPath,
args.branch,
args.remote
);
return { ...result };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
);

ipcMain.handle(
'git:evaluate-branch-cleanup',
async (
_,
args: {
projectPath: string;
branch: string;
mode: string;
daysThreshold: number;
}
) => {
try {
const { remoteBranchService } = await import('../services/RemoteBranchService');
const { isValidRemoteBranchCleanupMode } = await import('../../shared/remoteBranchCleanup');
if (!isValidRemoteBranchCleanupMode(args.mode)) {
return { success: true, action: 'skip' as const };
}
const action = await remoteBranchService.evaluateCleanupAction(
args.projectPath,
args.branch,
args.mode,
args.daysThreshold
);
return { success: true, action };
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : String(error),
action: 'skip' as const,
};
}
}
);
}
10 changes: 10 additions & 0 deletions src/main/preload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ contextBridge.exposeInMainWorld('electronAPI', {
worktreePath?: string;
branch?: string;
taskName?: string;
deleteRemoteBranch?: boolean;
}) => ipcRenderer.invoke('worktree:remove', args),
worktreeStatus: (args: { worktreePath: string }) => ipcRenderer.invoke('worktree:status', args),
worktreeMerge: (args: { projectPath: string; worktreeId: string }) =>
Expand Down Expand Up @@ -394,6 +395,14 @@ contextBridge.exposeInMainWorld('electronAPI', {
forceLarge?: boolean;
}) => ipcRenderer.invoke('git:get-commit-file-diff', args),
gitSoftReset: (args: { taskPath: string }) => ipcRenderer.invoke('git:soft-reset', args),
deleteRemoteBranch: (args: { projectPath: string; branch: string; remote?: string }) =>
ipcRenderer.invoke('git:delete-remote-branch', args),
evaluateBranchCleanup: (args: {
projectPath: string;
branch: string;
mode: string;
daysThreshold: number;
}) => ipcRenderer.invoke('git:evaluate-branch-cleanup', args),
gitCommitAndPush: (args: {
taskPath: string;
commitMessage?: string;
Expand Down Expand Up @@ -862,6 +871,7 @@ export interface ElectronAPI {
worktreePath?: string;
branch?: string;
taskName?: string;
deleteRemoteBranch?: boolean;
}) => Promise<{ success: boolean; error?: string }>;
worktreeStatus: (args: {
worktreePath: string;
Expand Down
213 changes: 213 additions & 0 deletions src/main/services/RemoteBranchService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,213 @@
import { execFile } from 'child_process';
import { promisify } from 'util';
import { log } from '../lib/logger';

const execFileAsync = promisify(execFile);

/**
* Result of a remote branch deletion attempt.
*/
export interface RemoteBranchDeletionResult {
/** Whether the deletion was executed (true even if the branch was already absent). */
success: boolean;
/** True if the branch did not exist on the remote (already deleted or never pushed). */
alreadyAbsent: boolean;
/** True if the remote ('origin' by default) is not configured for the repo. */
noRemote: boolean;
/** Human-readable detail message suitable for logs / UI toasts. */
message: string;
}

/** Patterns that indicate the remote branch was already gone. */
const ALREADY_ABSENT_PATTERNS = [
/remote ref does not exist/i,
/unknown revision/i,
/not found/i,
/error: unable to delete '[^']*': remote ref does not exist/i,
];
Comment on lines +25 to +26
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overly broad not found pattern can mask network errors

The pattern /not found/i is too generic. Git error messages for network failures (e.g., Could not resolve hostname 'github.com': Name or service not found, SSL_connect: Connection not found) also contain "not found". When this pattern matches a transient network error, the code returns { success: true, alreadyAbsent: true } — silently reporting success and masking what was actually a failed deletion.

Consider tightening the pattern to specifically match git branch-not-found output:

Suggested change
/error: unable to delete '[^']*': remote ref does not exist/i,
];
const ALREADY_ABSENT_PATTERNS = [
/remote ref does not exist/i,
/unknown revision/i,
/error: unable to delete '[^']*': remote ref does not exist/i,
];

The fourth pattern (error: unable to delete '...') is already a precise superset of the first for the branch-absent case; and unknown revision covers the remaining scenario, so dropping the broad /not found/i loses no real coverage while eliminating false positives.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Implemented!


/**
* Check whether a given remote alias exists for the repository.
*/
async function hasRemote(projectPath: string, remote: string): Promise<boolean> {
try {
const { stdout } = await execFileAsync('git', ['remote'], { cwd: projectPath });
return stdout
.split('\n')
.map((l) => l.trim())
.includes(remote);
} catch {
return false;
}
}

/**
* Determine the date (ISO string) of the most recent commit on a branch.
* Returns `null` if the branch doesn't exist locally.
*/
async function getLastCommitDate(projectPath: string, branch: string): Promise<string | null> {
try {
const { stdout } = await execFileAsync('git', ['log', '-1', '--format=%aI', branch, '--'], {
cwd: projectPath,
});
const trimmed = stdout.trim();
return trimmed || null;
} catch {
return null;
}
}

/**
* Dedicated service for managing remote branch lifecycle operations.
*
* This service encapsulates the logic for deleting remote branches
* with robust error handling and graceful degradation for common
* failure scenarios (branch already deleted, no remote configured,
* network timeouts, etc.).
*/
export class RemoteBranchService {
/**
* Delete a remote branch.
*
* @param projectPath — Absolute path to the local git repository (or worktree root).
* @param branch — Branch name to delete on the remote. May optionally include
* the `origin/` prefix, which is stripped automatically.
* @param remote — Remote alias (defaults to `'origin'`).
*
* @returns `RemoteBranchDeletionResult` describing the outcome. The method
* **never throws** — all errors are caught and returned as a failed result.
*/
async deleteRemoteBranch(
projectPath: string,
branch: string,
remote = 'origin'
): Promise<RemoteBranchDeletionResult> {
// -------------------------------------------------------------------
// Guard: no remote configured
// -------------------------------------------------------------------
try {
const remoteExists = await hasRemote(projectPath, remote);
if (!remoteExists) {
const msg = `Skipping remote branch deletion — no remote "${remote}" configured.`;
log.info(msg);
return { success: true, alreadyAbsent: false, noRemote: true, message: msg };
}
} catch (err) {
const msg = `Could not verify remote "${remote}" existence: ${String(err)}`;
log.warn(msg);
return { success: false, alreadyAbsent: false, noRemote: false, message: msg };
}

// Normalise: remove leading "origin/" if present
let remoteBranch = branch;
const prefixPattern = new RegExp(`^${remote}/`);
if (prefixPattern.test(remoteBranch)) {
remoteBranch = remoteBranch.replace(prefixPattern, '');
}

if (!remoteBranch) {
const msg = 'Cannot delete remote branch — empty branch name.';
log.warn(msg);
return { success: false, alreadyAbsent: false, noRemote: false, message: msg };
}

// -------------------------------------------------------------------
// Execute: git push <remote> --delete <branch>
// -------------------------------------------------------------------
try {
await execFileAsync('git', ['push', remote, '--delete', remoteBranch], {
cwd: projectPath,
timeout: 30_000, // 30 s network timeout
});
const msg = `Deleted remote branch ${remote}/${remoteBranch}.`;
log.info(msg);
return { success: true, alreadyAbsent: false, noRemote: false, message: msg };
} catch (error: unknown) {
const stderr = extractStderr(error);

// Known benign errors: branch was already absent
if (ALREADY_ABSENT_PATTERNS.some((pattern) => pattern.test(stderr))) {
const msg = `Remote branch ${remote}/${remoteBranch} already absent.`;
log.info(msg);
return { success: true, alreadyAbsent: true, noRemote: false, message: msg };
}

// Unknown / network error — log, but don't throw
const msg = `Failed to delete remote branch ${remote}/${remoteBranch}: ${stderr}`;
log.warn(msg);
return { success: false, alreadyAbsent: false, noRemote: false, message: msg };
}
}

/**
* Determine whether a branch qualifies as "stale" based on the configured
* days threshold and the date of its most recent commit.
*
* @returns `true` if the branch's last commit is older than `daysThreshold`
* days, or if the last commit date cannot be determined (conservative).
*/
async isBranchStale(
projectPath: string,
branch: string,
daysThreshold: number
): Promise<boolean> {
const dateStr = await getLastCommitDate(projectPath, branch);
if (!dateStr) {
// Cannot determine — treat as stale so users aren't surprised by
// branches that silently escape cleanup.
return true;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Treating unknown commit date as stale can silently delete live branches

When getLastCommitDate returns null (branch doesn't exist locally, git failed, etc.), isBranchStale returns true, which causes evaluateCleanupAction to return 'delete'. This means any branch that can't be resolved locally — even a branch pushed very recently from another machine — will be unconditionally deleted in auto mode.

The safer conservative choice is to return false (not stale) when the age cannot be determined, preventing silent deletions of branches that cannot be verified:

Suggested change
const dateStr = await getLastCommitDate(projectPath, branch);
if (!dateStr) {
// Cannot determine — treat as stale so users aren't surprised by
// branches that silently escape cleanup.
return true;
if (!dateStr) {
// Cannot determine age — skip deletion to avoid removing branches
// that may still be active but lack a local tracking ref.
return false;
}

The existing tests (returns true when date cannot be determined) explicitly assert the current "fail open" behaviour; those tests would need updating if this is changed.

}

const commitDate = new Date(dateStr);
if (isNaN(commitDate.getTime())) {
return true;
}

const now = new Date();
const diffMs = now.getTime() - commitDate.getTime();
const diffDays = diffMs / (1000 * 60 * 60 * 24);
return diffDays >= daysThreshold;
}

/**
* Evaluate the cleanup setting to decide whether a remote branch should be
* deleted right now. This does **not** perform the deletion — call
* `deleteRemoteBranch()` separately if the answer is `'delete'`.
*
* @returns `'delete'` | `'skip'` | `'ask'`
*/
async evaluateCleanupAction(
projectPath: string,
branch: string,
mode: import('@shared/remoteBranchCleanup').RemoteBranchCleanupMode,
daysThreshold: number
): Promise<'delete' | 'skip' | 'ask'> {
switch (mode) {
case 'always':
return 'delete';
case 'never':
return 'skip';
case 'ask':
return 'ask';
case 'auto': {
const stale = await this.isBranchStale(projectPath, branch, daysThreshold);
return stale ? 'delete' : 'skip';
}
default:
return 'skip';
}
}
}

/** Extract the stderr string from a child-process error. */
function extractStderr(error: unknown): string {
if (error && typeof error === 'object') {
const e = error as Record<string, unknown>;
if (typeof e.stderr === 'string' && e.stderr) return e.stderr;
if (typeof e.message === 'string' && e.message) return e.message;
}
return String(error);
}

/** Module-level singleton, following the project convention. */
export const remoteBranchService = new RemoteBranchService();
41 changes: 11 additions & 30 deletions src/main/services/WorktreeService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from 'path';
import fs from 'fs';
import crypto from 'crypto';
import { projectSettingsService } from './ProjectSettingsService';
import { remoteBranchService } from './RemoteBranchService';
import { minimatch } from 'minimatch';
import { errorTracking } from '../errorTracking';

Expand Down Expand Up @@ -405,7 +406,8 @@ export class WorktreeService {
projectPath: string,
worktreeId: string,
worktreePath?: string,
branch?: string
branch?: string,
options?: { deleteRemoteBranch?: boolean }
): Promise<void> {
try {
const worktree = this.worktrees.get(worktreeId);
Expand Down Expand Up @@ -516,36 +518,15 @@ export class WorktreeService {
}
}

// Only try to delete remote branch if a remote exists
const remoteAlias = 'origin';
const hasRemote = await this.hasRemote(projectPath, remoteAlias);
if (hasRemote) {
let remoteBranchName = branchToDelete;
if (branchToDelete.startsWith('origin/')) {
remoteBranchName = branchToDelete.replace(/^origin\//, '');
}
try {
await execFileAsync('git', ['push', remoteAlias, '--delete', remoteBranchName], {
cwd: projectPath,
});
log.info(`Deleted remote branch ${remoteAlias}/${remoteBranchName}`);
} catch (remoteError: any) {
const msg = String(remoteError?.stderr || remoteError?.message || remoteError);
if (
/remote ref does not exist/i.test(msg) ||
/unknown revision/i.test(msg) ||
/not found/i.test(msg)
) {
log.info(`Remote branch ${remoteAlias}/${remoteBranchName} already absent`);
} else {
log.warn(
`Failed to delete remote branch ${remoteAlias}/${remoteBranchName}:`,
remoteError
);
}
}
// Delete remote branch only when explicitly requested via the cleanup setting.
// The caller (worktreeIpc / task management) evaluates the user's preference
// and passes `deleteRemoteBranch: true` when appropriate.
if (options?.deleteRemoteBranch) {
await remoteBranchService.deleteRemoteBranch(projectPath, branchToDelete);
} else {
log.info(`Skipping remote branch deletion - no remote configured (local-only repo)`);
log.info(
`Skipping remote branch deletion for ${branchToDelete} (deleteRemoteBranch not requested)`
);
}
}

Expand Down
4 changes: 3 additions & 1 deletion src/main/services/worktreeIpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ export function registerWorktreeIpc(): void {
worktreeId: string;
worktreePath?: string;
branch?: string;
deleteRemoteBranch?: boolean;
}
) => {
try {
Expand Down Expand Up @@ -187,7 +188,8 @@ export function registerWorktreeIpc(): void {
args.projectPath,
args.worktreeId,
args.worktreePath,
args.branch
args.branch,
{ deleteRemoteBranch: args.deleteRemoteBranch }
);
return { success: true };
} catch (error) {
Expand Down
Loading
Loading