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
1 change: 1 addition & 0 deletions docs/features.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ Everything beyond the core loop (create a task, review its diff, merge or discar
- **Worktree setup** (optional, per project) — under Project settings → Tasks → **Worktree setup**. A project with nothing set here behaves exactly as before: a new worktree gets symlinks to the git-ignored root entries ticked in the New Task dialog (`node_modules`, `.env` and agent folders by default), with no extra step and no delay.
- **Setup script** runs in its own shell terminal in each new worktree task as soon as the task opens, including sub-tasks an agent creates (except those of a Docker task, where it would run outside the container). The agent starts at the same time; nothing waits for the script. The terminal shows the output live, the script stops at its first failing command, and a failure is marked on that terminal and announced in a notification. The script runs once, at creation: restarting the app does not run it again.
- **Teardown script** runs headless on the host, in the worktree, before the app removes it, when a task closes or merges with cleanup. The task's agents and shells are stopped first and the task shows that it is closing. It gets up to 2 minutes. If it fails or times out, a notification quotes the last lines of output and the worktree is still removed. It only runs in a folder git lists as one of the repository's worktrees. It also runs for sub-tasks that an agent closes or that land themselves, and for a task that created sub-tasks. It does not run for imported worktrees or tasks on the current branch.
- **Suspend script** and **Resume script** release what a task's worktree started while the task is set aside, such as a docker compose stack per worktree. The suspend script runs when a task is minimized, or snoozed with its agents stopped, after the agents stop; snoozing a task that keeps its agents running does not run it. The resume script runs when that task is restored, including after a restart, and only for tasks the suspend script ran for, so a task minimized before the scripts were set up is left alone. Both run headless on the host, in the worktree, without holding up the minimize or restore, with up to 2 minutes each; a failure is announced in a notification quoting the last lines of output. Scripts on one worktree run one at a time, so a quick restore resumes after the suspend finished. They run for every task with a worktree, imported ones included, and for sub-tasks an agent archives, but not for tasks on the current branch.
- Scripts run in your shell (`sh`, `bash` or `zsh` with stop-on-error; other shells fall back to `/bin/sh`). On Windows they run in `cmd.exe`, one command per line joined with `&&`, so keep each line a complete command (no `rem` lines or multi-line blocks), or in PowerShell 7.3 or later if that is your shell (older PowerShell does not stop on a failing program). A Docker task's setup script runs in the container with `/bin/sh`, where the main checkout is not mounted. Scripts get `PARALLEL_CODE_ROOT_PATH` (the main checkout), `PARALLEL_CODE_WORKTREE` and `PARALLEL_CODE_BRANCH` (`%PARALLEL_CODE_ROOT_PATH%` in `cmd.exe`), plus the project's environment variables except inside Docker. Like the verify command they live in app state, not in the repository, so opening a clone never runs its commands.
- **Save which ignored files new tasks bring in** stores the selection so it isn't picked again for every task, with a choice per entry: **Symlink** shares the main checkout's copy (fast; writes reach the main checkout and other tasks), **Copy** gives the worktree its own copy (isolated, but takes as long as the copy does; an entry that is itself a symlink is copied from what it points to). The New Task dialog and tasks created from the phone then start from this list, marking copies with `copy`; you can still untick an entry for one task. Sub-tasks an agent creates use the list as saved; without one they link `node_modules`. Symlinks inside a copied folder are copied as links, and removing the worktree never follows them into the main checkout.

Expand Down
1 change: 1 addition & 0 deletions electron/ipc/channel-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@
"SetMinimaxApiKey": "set_minimax_api_key",
"SetProjectAgentEnv": "set_project_agent_env",
"SetProjectWorktreeSettings": "set_project_worktree_settings",
"RunWorktreeLifecycleScript": "run_worktree_lifecycle_script",
"ListCodexModels": "list_codex_models",
"CheckDockerAvailable": "check_docker_available",
"CheckDockerImageExists": "check_docker_image_exists",
Expand Down
75 changes: 75 additions & 0 deletions electron/ipc/register-worktree-scripts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,81 @@ it('keeps the merge-time cleanup path unchanged without a teardown script', asyn
expect(remove).not.toHaveBeenCalled();
});

it.skipIf(process.platform === 'win32')(
'runs suspend and then resume in the worktree with the script variables and project env',
async () => {
const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'parallel-code-suspend-'));
tempDirs.push(projectRoot);
const worktreePath = path.join(projectRoot, '.worktrees', 'task', 'x');
const gitCmd = (args: string[]) =>
execFileSync('git', args, { cwd: projectRoot, stdio: 'ignore' });
gitCmd(['init', '--quiet', '--initial-branch=main']);
gitCmd(['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '--allow-empty', '-m', 'init']);
gitCmd(['worktree', 'add', '-b', 'task/x', worktreePath]);
await handlers.get(IPC.SetProjectAgentEnv)?.(undefined, {
projectId: 'p1',
env: { STACK: 'web' },
});
const run = (kind: string, script: string) =>
handlers.get(IPC.RunWorktreeLifecycleScript)?.(undefined, {
kind,
projectId: 'p1',
projectRoot,
worktreePath,
branchName: 'task/x',
script,
});
const log = 'echo "$0 $STACK $PARALLEL_CODE_BRANCH" >> lifecycle.log';

// Sent back to back, as a quick minimize and restore would: resume waits.
const [suspended, resumed] = await Promise.all([
run('suspend', `sleep 0.3\n${log.replace('$0', 'suspend')}`),
run('resume', log.replace('$0', 'resume')),
]);

expect(suspended).toEqual({});
expect(resumed).toEqual({});
expect(fs.readFileSync(path.join(worktreePath, 'lifecycle.log'), 'utf8')).toBe(
'suspend web task/x\nresume web task/x\n',
);
},
);

it.skipIf(process.platform === 'win32')(
'reports a failed suspend as a warning instead of an error',
async () => {
const projectRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'parallel-code-suspend-'));
tempDirs.push(projectRoot);
const worktreePath = path.join(projectRoot, '.worktrees', 'task', 'x');
const gitCmd = (args: string[]) =>
execFileSync('git', args, { cwd: projectRoot, stdio: 'ignore' });
gitCmd(['init', '--quiet', '--initial-branch=main']);
gitCmd(['-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '--allow-empty', '-m', 'init']);
gitCmd(['worktree', 'add', '-b', 'task/x', worktreePath]);

const result = await handlers.get(IPC.RunWorktreeLifecycleScript)?.(undefined, {
kind: 'suspend',
projectRoot,
worktreePath,
branchName: 'task/x',
script: 'echo no such service\nexit 2',
});

expect((result as { warning?: string }).warning).toMatch(
/^Suspend script exited with code 2\.\nno such service$/,
);
},
);

it('validates a suspend or resume request before running anything', async () => {
const base = { projectRoot: '/repo', worktreePath: '/repo/.worktrees/x', script: 'true' };
const run = (args: Record<string, unknown>) =>
handlers.get(IPC.RunWorktreeLifecycleScript)?.(undefined, { ...base, ...args });
await expect(run({ kind: 'teardown' })).rejects.toThrow('kind');
await expect(run({ kind: 'suspend', script: ' ' })).rejects.toThrow('script');
await expect(run({ kind: 'resume', worktreePath: 'relative' })).rejects.toThrow('worktreePath');
});

it('never takes the verbatim Windows command-line flag from the renderer', async () => {
await handlers.get(IPC.SpawnAgent)?.(undefined, shellSpawn({ windowsVerbatimArgs: true }));
const [, spawned] = spawnAgent.mock.lastCall as [unknown, { windowsVerbatimArgs?: boolean }];
Expand Down
36 changes: 32 additions & 4 deletions electron/ipc/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,10 @@ import { buildVerifyEnv, validateVerifyCommand, verificationRunner } from './ver
import {
buildScriptInvocation,
buildWorktreeScriptEnv,
describeTeardownFailure,
describeWorktreeScriptFailure,
optionalWorktreeScript,
runTeardownScript,
runWorktreeScript,
validateWorktreeScript,
} from './worktree-scripts.js';
import { scanChange } from './change-scan.js';
import {
Expand Down Expand Up @@ -1237,7 +1238,7 @@ export function registerAllHandlers(win: BrowserWindow): void {
}
}
const target = worktreePath ?? worktreePathFor(projectRoot, branchName);
const teardown = await runTeardownScript({
const teardown = await runWorktreeScript({
worktreePath: target,
projectRoot,
script: teardownScript,
Expand All @@ -1247,7 +1248,7 @@ export function registerAllHandlers(win: BrowserWindow): void {
},
});
await removeWorktreeLocked(projectRoot, branchName, true, worktreePath);
const teardownWarning = describeTeardownFailure(teardown);
const teardownWarning = describeWorktreeScriptFailure('Teardown', teardown);
if (teardownWarning) {
result = {
...result,
Expand Down Expand Up @@ -1610,6 +1611,33 @@ export function registerAllHandlers(win: BrowserWindow): void {
setProjectWorktreeSettings(args.projectId, args);
});

// A project's suspend or resume script, run headless in the worktree of a
// task being minimized or restored. The renderer does not wait on it to
// change the layout; a failure comes back as a warning to show.
ipcMain.handle(IPC.RunWorktreeLifecycleScript, async (_e, args) => {
if (args.kind !== 'suspend' && args.kind !== 'resume')
throw new Error('kind must be "suspend" or "resume"');
const projectRoot = projectRootArg(args);
const worktreePath = worktreePathArg(args);
const branchName = args.branchName ? branchNameArg(args) : undefined;
assertOptionalString(args.projectId, 'projectId');
validateWorktreeScript(args.script, 'script');
const result = await runWorktreeScript({
worktreePath,
projectRoot,
script: args.script,
env: {
...projectAgentEnv(args.projectId),
...buildWorktreeScriptEnv({ projectRoot, worktreePath, branchName }),
},
});
const warning = describeWorktreeScriptFailure(
args.kind === 'suspend' ? 'Suspend' : 'Resume',
result,
);
return warning ? { warning } : {};
});

ipcMain.handle(IPC.SetMinimaxApiKey, (_e, args) => {
assertString(args.key, 'key');
setMinimaxApiKey(args.key);
Expand Down
8 changes: 4 additions & 4 deletions electron/ipc/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { recordWorktreeIntent } from './worktree-intents.js';
import { localBranchExists, resolvePrCheckout } from '../github/pr-checkout.js';
import {
buildWorktreeScriptEnv,
describeTeardownFailure,
runTeardownScript,
describeWorktreeScriptFailure,
runWorktreeScript,
} from './worktree-scripts.js';
import type { CreatePrTaskResult, DeleteTaskResult } from './shared-types.js';

Expand Down Expand Up @@ -145,7 +145,7 @@ export async function deleteTask(opts: DeleteTaskOpts): Promise<DeleteTaskResult
let teardownWarning: string | undefined;
if (opts.teardownScript) {
const worktreePath = opts.worktreePath ?? worktreePathFor(opts.projectRoot, opts.branchName);
const result = await runTeardownScript({
const result = await runWorktreeScript({
worktreePath,
projectRoot: opts.projectRoot,
script: opts.teardownScript,
Expand All @@ -158,7 +158,7 @@ export async function deleteTask(opts: DeleteTaskOpts): Promise<DeleteTaskResult
}),
},
});
teardownWarning = describeTeardownFailure(result);
teardownWarning = describeWorktreeScriptFailure('Teardown', result);
}
await removeWorktree(opts.projectRoot, opts.branchName, opts.deleteBranch, opts.worktreePath);
notifyAgentListChanged();
Expand Down
59 changes: 42 additions & 17 deletions electron/ipc/worktree-scripts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import { afterEach, describe, expect, it } from 'vitest';
import {
WORKTREE_SCRIPT_MAX_LENGTH,
buildScriptInvocation,
describeTeardownFailure,
describeWorktreeScriptFailure,
listLinkedWorktrees,
optionalWorktreeScript,
runTeardownScript,
runWorktreeScript,
validateWorktreeScript,
} from './worktree-scripts.js';

Expand Down Expand Up @@ -92,7 +92,7 @@ describe('buildScriptInvocation', () => {
});
});

describe.skipIf(process.platform === 'win32')('runTeardownScript', () => {
describe.skipIf(process.platform === 'win32')('runWorktreeScript', () => {
// Each test's worktree is listed as a linked worktree of its root.
let listed: string[] = [];
const listWorktrees = async () => listed;
Expand All @@ -106,7 +106,7 @@ describe.skipIf(process.platform === 'win32')('runTeardownScript', () => {
it('runs in the worktree with the script variables and passes on exit 0', async () => {
const root = tempDir();
const worktree = worktreeDir();
const result = await runTeardownScript(
const result = await runWorktreeScript(
{
worktreePath: worktree,
projectRoot: root,
Expand All @@ -118,13 +118,13 @@ describe.skipIf(process.platform === 'win32')('runTeardownScript', () => {
expect(result.status).toBe('passed');
expect(result.outputTail).toContain(fs.realpathSync(worktree));
expect(result.outputTail).toContain(`root=${root}`);
expect(describeTeardownFailure(result)).toBeUndefined();
expect(describeWorktreeScriptFailure('Teardown', result)).toBeUndefined();
});

it('stops at the first failing line and reports the exit code with the output', async () => {
const root = tempDir();
const worktree = worktreeDir();
const result = await runTeardownScript(
const result = await runWorktreeScript(
{
worktreePath: worktree,
projectRoot: root,
Expand All @@ -134,38 +134,38 @@ describe.skipIf(process.platform === 'win32')('runTeardownScript', () => {
);
expect(result).toMatchObject({ status: 'failed', exitCode: 3 });
expect(fs.existsSync(path.join(worktree, 'after'))).toBe(false);
const notice = describeTeardownFailure(result);
const notice = describeWorktreeScriptFailure('Teardown', result);
expect(notice).toContain('exited with code 3');
expect(notice).toContain('stopping db');
});

it('kills a script that runs past its timeout', async () => {
const root = tempDir();
const worktree = worktreeDir();
const result = await runTeardownScript(
const result = await runWorktreeScript(
{ worktreePath: worktree, projectRoot: root, script: 'sleep 30', timeoutMs: 200 },
shellDeps,
);
expect(result.status).toBe('timed_out');
expect(describeTeardownFailure(result)).toContain('timed out');
expect(describeWorktreeScriptFailure('Teardown', result)).toContain('timed out');
});

it('reports a script killed by a signal as failed', async () => {
const root = tempDir();
const worktree = worktreeDir();
const result = await runTeardownScript(
const result = await runWorktreeScript(
{ worktreePath: worktree, projectRoot: root, script: 'kill -TERM $$' },
shellDeps,
);
expect(result.status).toBe('failed');
expect(describeTeardownFailure(result)).toContain('SIGTERM');
expect(describeWorktreeScriptFailure('Teardown', result)).toContain('SIGTERM');
});

it('settles when the script exits even if a background child keeps its output open', async () => {
const root = tempDir();
const worktree = worktreeDir();
const started = Date.now();
const result = await runTeardownScript(
const result = await runWorktreeScript(
{
worktreePath: worktree,
projectRoot: root,
Expand All @@ -179,22 +179,47 @@ describe.skipIf(process.platform === 'win32')('runTeardownScript', () => {
expect(Date.now() - started).toBeLessThan(5_000);
});

it('runs the scripts of one worktree one at a time, in the order asked', async () => {
const root = tempDir();
const worktree = worktreeDir();
const slow = runWorktreeScript(
{ worktreePath: worktree, projectRoot: root, script: 'sleep 0.3\necho first >> order' },
shellDeps,
);
const quick = runWorktreeScript(
{ worktreePath: worktree, projectRoot: root, script: 'echo second | tee -a order\nexit 1' },
shellDeps,
);
const after = runWorktreeScript(
{ worktreePath: worktree, projectRoot: root, script: 'echo third >> order' },
shellDeps,
);
const results = await Promise.all([slow, quick, after]);
expect(results.map((r) => r.status)).toEqual(['passed', 'failed', 'passed']);
expect(fs.readFileSync(path.join(worktree, 'order'), 'utf8')).toBe('first\nsecond\nthird\n');
expect(describeWorktreeScriptFailure('Resume', results[1])).toMatch(
/^Resume script exited with code 1\.\nsecond$/,
);
});

it('refuses a folder git does not list as a worktree of the repository', async () => {
const root = tempDir();
const elsewhere = tempDir();
listed = [];
const result = await runTeardownScript(
const result = await runWorktreeScript(
{ worktreePath: elsewhere, projectRoot: root, script: 'touch ran' },
shellDeps,
);
expect(result.status).toBe('error');
expect(describeTeardownFailure(result)).toContain('is not a worktree of this repository');
expect(describeWorktreeScriptFailure('Teardown', result)).toContain(
'is not a worktree of this repository',
);
expect(fs.existsSync(path.join(elsewhere, 'ran'))).toBe(false);
});

it('never runs in the main checkout', async () => {
const root = tempDir();
const result = await runTeardownScript(
const result = await runWorktreeScript(
{ worktreePath: root, projectRoot: root, script: 'touch ran' },
shellDeps,
);
Expand All @@ -204,12 +229,12 @@ describe.skipIf(process.platform === 'win32')('runTeardownScript', () => {

it('skips a worktree that is already gone', async () => {
const root = tempDir();
const result = await runTeardownScript(
const result = await runWorktreeScript(
{ worktreePath: path.join(root, 'missing'), projectRoot: root, script: 'true' },
shellDeps,
);
expect(result.status).toBe('skipped');
expect(describeTeardownFailure(result)).toBeUndefined();
expect(describeWorktreeScriptFailure('Teardown', result)).toBeUndefined();
});
});

Expand Down
Loading