Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 4 additions & 1 deletion electron/ipc/channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export enum IPC {
GetAllFileDiffsFromBranch = 'get_all_file_diffs_from_branch',
GetFileDiff = 'get_file_diff',
GetFileDiffFromBranch = 'get_file_diff_from_branch',
GetGitignoredDirs = 'get_gitignored_dirs',
ListProjectEntries = 'list_project_entries',
GetWorktreeStatus = 'get_worktree_status',
CheckMergeStatus = 'check_merge_status',
MergeTask = 'merge_task',
Expand Down Expand Up @@ -82,6 +82,9 @@ export enum IPC {
PlanContent = 'plan_content',
ReadPlanContent = 'read_plan_content',

// Setup
RunSetupCommands = 'run_setup_commands',

// Ask about code
AskAboutCode = 'ask_about_code',
CancelAskAboutCode = 'cancel_ask_about_code',
Expand Down
93 changes: 24 additions & 69 deletions electron/ipc/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,23 +64,6 @@ function withWorktreeLock<T>(key: string, fn: () => Promise<T>): Promise<T> {
return next;
}

// --- Symlink candidates ---

const SYMLINK_CANDIDATES = [
'.claude',
'.cursor',
'.aider',
'.copilot',
'.codeium',
'.continue',
'.windsurf',
'.env',
'node_modules',
];

/** Entries inside `.claude` that must NOT be symlinked (kept per-worktree). */
const CLAUDE_DIR_EXCLUDE = new Set(['plans', 'settings.local.json']);

// --- Internal helpers ---

async function detectMainBranch(repoRoot: string): Promise<string> {
Expand Down Expand Up @@ -303,33 +286,6 @@ async function computeBranchDiffStats(
return { linesAdded, linesRemoved };
}

/**
* "Shallow-symlink" a directory: create a real directory at `target` and
* symlink each entry from `source` into it, EXCEPT entries in `exclude`.
*/
function shallowSymlinkDir(source: string, target: string, exclude: Set<string>): void {
fs.mkdirSync(target, { recursive: true });
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(source, { withFileTypes: true });
} catch (err) {
console.warn(`Failed to read directory ${source} for shallow-symlink:`, err);
return;
}
for (const entry of entries) {
if (exclude.has(entry.name)) continue;
const src = path.join(source, entry.name);
const dst = path.join(target, entry.name);
try {
if (!fs.existsSync(dst)) {
fs.symlinkSync(src, dst);
}
} catch {
/* ignore */
}
}
}

// --- Public functions (used by tasks.ts and register.ts) ---

export async function createWorktree(
Expand Down Expand Up @@ -365,21 +321,19 @@ export async function createWorktree(
await exec('git', ['worktree', 'add', '-b', branchName, worktreePath], { cwd: repoRoot });

// Symlink selected directories
const resolvedRoot = path.resolve(repoRoot) + path.sep;
const resolvedWorktree = path.resolve(worktreePath) + path.sep;
for (const name of symlinkDirs) {
// Reject names that could escape the worktree directory
if (name.includes('/') || name.includes('\\') || name.includes('..') || name === '.') continue;
if (name.includes('..')) continue;
const source = path.join(repoRoot, name);
const target = path.join(worktreePath, name);
if (!path.resolve(source).startsWith(resolvedRoot)) continue;
if (!path.resolve(target).startsWith(resolvedWorktree)) continue;
try {
if (!fs.existsSync(source)) continue;
if (fs.existsSync(target)) continue;

if (name === '.claude') {
// Shallow-symlink: real dir with per-entry symlinks, excluding per-worktree entries
shallowSymlinkDir(source, target, CLAUDE_DIR_EXCLUDE);
} else {
fs.symlinkSync(source, target);
}
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.symlinkSync(source, target);
} catch {
/* ignore */
}
Expand Down Expand Up @@ -425,23 +379,24 @@ export async function removeWorktree(

// --- IPC command functions ---

export async function getGitIgnoredDirs(projectRoot: string): Promise<string[]> {
const results: string[] = [];
for (const name of SYMLINK_CANDIDATES) {
const dirPath = path.join(projectRoot, name);
try {
fs.statSync(dirPath); // throws if entry doesn't exist
} catch {
continue;
}
try {
await exec('git', ['check-ignore', '-q', name], { cwd: projectRoot });
results.push(name);
} catch {
/* not ignored */
}
export function listProjectEntries(
projectRoot: string,
subpath?: string,
): { name: string; isDir: boolean }[] {
const HIDDEN = new Set(['.git', '.worktrees']);
const dir = subpath ? path.join(projectRoot, subpath) : projectRoot;
// Prevent traversal outside project root
const resolvedDir = path.resolve(dir);
const resolvedRoot = path.resolve(projectRoot);
if (resolvedDir !== resolvedRoot && !resolvedDir.startsWith(resolvedRoot + path.sep)) return [];
try {
return fs
.readdirSync(dir, { withFileTypes: true })
.filter((e) => !HIDDEN.has(e.name))
.map((e) => ({ name: e.name, isDir: e.isDirectory() }));
} catch {
return [];
}
return results;
}

export async function getMainBranch(projectRoot: string): Promise<string> {
Expand Down
21 changes: 18 additions & 3 deletions electron/ipc/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
import { ensurePlansDirectory, startPlanWatcher, readPlanForWorktree } from './plans.js';
import { startRemoteServer } from '../remote/server.js';
import {
getGitIgnoredDirs,
listProjectEntries,
getMainBranch,
getCurrentBranch,
getChangedFiles,
Expand All @@ -41,6 +41,7 @@ import { listAgents } from './agents.js';
import { saveAppState, loadAppState } from './persistence.js';
import { spawn } from 'child_process';
import { askAboutCode, cancelAskAboutCode } from './ask-code.js';
import { runSetupCommands } from './setup.js';
import path from 'path';
import {
assertString,
Expand Down Expand Up @@ -173,9 +174,9 @@ export function registerAllHandlers(win: BrowserWindow): void {
validateRelativePath(args.filePath, 'filePath');
return getFileDiffFromBranch(args.projectRoot, args.branchName, args.filePath);
});
ipcMain.handle(IPC.GetGitignoredDirs, (_e, args) => {
ipcMain.handle(IPC.ListProjectEntries, (_e, args) => {
validatePath(args.projectRoot, 'projectRoot');
return getGitIgnoredDirs(args.projectRoot);
return listProjectEntries(args.projectRoot, args.subpath);
});
ipcMain.handle(IPC.GetWorktreeStatus, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
Expand Down Expand Up @@ -304,6 +305,20 @@ export function registerAllHandlers(win: BrowserWindow): void {
return readPlanForWorktree(args.worktreePath, fileName);
});

// --- Setup commands ---
ipcMain.handle(IPC.RunSetupCommands, (_e, args) => {
validatePath(args.worktreePath, 'worktreePath');
validatePath(args.projectRoot, 'projectRoot');
assertStringArray(args.commands, 'commands');
assertString(args.onOutput?.__CHANNEL_ID__, 'channelId');
return runSetupCommands(win, {
worktreePath: args.worktreePath,
projectRoot: args.projectRoot,
commands: args.commands,
channelId: args.onOutput.__CHANNEL_ID__,
});
});

// --- Ask about code ---
ipcMain.handle(IPC.AskAboutCode, (_e, args) => {
assertString(args.requestId, 'requestId');
Expand Down
56 changes: 56 additions & 0 deletions electron/ipc/setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { spawn } from 'child_process';
import type { BrowserWindow } from 'electron';

export async function runSetupCommands(
win: BrowserWindow,
args: { worktreePath: string; projectRoot: string; commands: string[]; channelId: string },
): Promise<void> {
const { worktreePath, projectRoot, commands, channelId } = args;

const expandVars = (cmd: string): string =>
cmd
.replace(/\$\{PROJECT_ROOT\}|\$PROJECT_ROOT\b/g, () => projectRoot)
.replace(/\$\{WORKTREE\}|\$WORKTREE\b/g, () => worktreePath);

const send = (msg: string) => {
if (!win.isDestroyed()) {
win.webContents.send(`channel:${channelId}`, msg);
}
};

for (const raw of commands) {
const cmd = expandVars(raw);
send(`$ ${cmd}\n`);
await new Promise<void>((resolve, reject) => {
const proc = spawn(cmd, {
shell: true,
cwd: worktreePath,
stdio: ['ignore', 'pipe', 'pipe'],
});

proc.stdout?.on('data', (chunk: Buffer) => {
send(chunk.toString('utf8'));
});

proc.stderr?.on('data', (chunk: Buffer) => {
send(chunk.toString('utf8'));
});

let settled = false;
proc.on('close', (code) => {
if (settled) return;
settled = true;
if (code !== 0) {
reject(new Error(`Command "${cmd}" exited with code ${code}`));
} else {
resolve();
}
});
proc.on('error', (err) => {
if (settled) return;
settled = true;
reject(new Error(`Failed to run "${cmd}": ${err.message}`));
});
});
}
}
4 changes: 3 additions & 1 deletion electron/preload.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const ALLOWED_CHANNELS = new Set([
'get_file_diff_from_branch',
'get_all_file_diffs',
'get_all_file_diffs_from_branch',
'get_gitignored_dirs',
'list_project_entries',
'get_worktree_status',
'commit_all',
'discard_uncommitted',
Expand Down Expand Up @@ -76,6 +76,8 @@ const ALLOWED_CHANNELS = new Set([
'get_remote_status',
// Plan
'plan_content',
// Setup
'run_setup_commands',
// Ask about code
'ask_about_code',
'cancel_ask_about_code',
Expand Down
Loading