From 190f6517a0e4b982bfb8efdcff98f8cdffdf6f2d Mon Sep 17 00:00:00 2001 From: Dorian Villet Date: Sun, 15 Nov 2026 19:03:27 +0100 Subject: [PATCH] feat(worktrees): suspend and resume scripts for minimized tasks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Minimizing a task stops its agents but leaves running whatever its worktree started, such as a docker compose stack per worktree. With many tasks set aside, those stacks hold memory until each task is closed, and only closing runs the teardown script, which also removes the worktree. Two optional per-project scripts sit next to Setup and Teardown under Project settings → Tasks → Worktree setup: - Suspend script: runs in the worktree when a task is minimized, or snoozed with its agents stopped, after the agents stop. Snoozing with agents running does not run it. - Resume script: runs when that task is restored. A task is marked suspended when the script runs, and the mark is persisted, so a restore after a restart resumes only tasks that were suspended. Both run headless like teardown, with the same variables, project env and two-minute limit, and only in a folder git lists as a worktree of the repository. Neither holds up the minimize or restore; a failure is announced in a notification naming the task. Scripts on one worktree now run one at a time in the order asked, so a quick restore resumes after the suspend finished, and a close right after a minimize tears down after it. The headless runner is renamed from runTeardownScript to runWorktreeScript, and its failure notice takes the script's label. Co-Authored-By: Claude Opus 5.5 --- docs/features.md | 1 + electron/ipc/channel-manifest.json | 1 + .../ipc/register-worktree-scripts.test.ts | 75 ++++++++ electron/ipc/register.ts | 36 +++- electron/ipc/tasks.ts | 8 +- electron/ipc/worktree-scripts.test.ts | 59 ++++-- electron/ipc/worktree-scripts.ts | 96 +++++++--- electron/preload.cjs | 1 + .../EditProjectDialog.client.test.tsx | 17 ++ .../ProjectWorktreeSetupSection.tsx | 44 ++++- src/components/project-settings-form.ts | 10 + src/store/background-tasks.client.test.tsx | 41 ++++- src/store/persistence.test.ts | 55 ++++++ src/store/persistence.ts | 4 + src/store/projects.test.ts | 22 +++ src/store/projects.ts | 8 + src/store/tasks.test.ts | 172 ++++++++++++++++++ src/store/tasks.ts | 13 ++ src/store/types.ts | 11 ++ src/store/worktree-setup.ts | 60 +++++- 20 files changed, 673 insertions(+), 61 deletions(-) diff --git a/docs/features.md b/docs/features.md index a733ade3e..6c538312a 100644 --- a/docs/features.md +++ b/docs/features.md @@ -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. diff --git a/electron/ipc/channel-manifest.json b/electron/ipc/channel-manifest.json index fe08e335a..afd5104e7 100644 --- a/electron/ipc/channel-manifest.json +++ b/electron/ipc/channel-manifest.json @@ -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", diff --git a/electron/ipc/register-worktree-scripts.test.ts b/electron/ipc/register-worktree-scripts.test.ts index 161521c12..06ee3188a 100644 --- a/electron/ipc/register-worktree-scripts.test.ts +++ b/electron/ipc/register-worktree-scripts.test.ts @@ -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) => + 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 }]; diff --git a/electron/ipc/register.ts b/electron/ipc/register.ts index 605e7b3c0..644253403 100644 --- a/electron/ipc/register.ts +++ b/electron/ipc/register.ts @@ -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 { @@ -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, @@ -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, @@ -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); diff --git a/electron/ipc/tasks.ts b/electron/ipc/tasks.ts index c48fad0fa..1e5c26892 100644 --- a/electron/ipc/tasks.ts +++ b/electron/ipc/tasks.ts @@ -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'; @@ -145,7 +145,7 @@ export async function deleteTask(opts: DeleteTaskOpts): Promise { }); }); -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; @@ -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, @@ -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, @@ -134,7 +134,7 @@ 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'); }); @@ -142,30 +142,30 @@ describe.skipIf(process.platform === 'win32')('runTeardownScript', () => { 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, @@ -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, ); @@ -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(); }); }); diff --git a/electron/ipc/worktree-scripts.ts b/electron/ipc/worktree-scripts.ts index 8fbef1756..80800a74e 100644 --- a/electron/ipc/worktree-scripts.ts +++ b/electron/ipc/worktree-scripts.ts @@ -6,17 +6,18 @@ import { resolveUserShell } from '../user-shell.js'; import { stripAnsi } from '../shared/prompt-detect.js'; /** - * Per-project worktree setup and teardown scripts. + * Per-project worktree scripts: setup, teardown, suspend and resume. * - * Both live in app state, never in a repo file, for the same reason as the + * All live in app state, never in a repo file, for the same reason as the * verify command: opening a hostile clone must not run commands on the host. - * Setup runs in a visible task terminal (the PTY path in `pty.ts`); teardown - * runs here, headless, while the task shows its closing state. + * Setup runs in a visible task terminal (the PTY path in `pty.ts`); the others + * run here, headless: teardown while the task shows its closing state, suspend + * and resume in the background when a task is minimized and restored. */ export const WORKTREE_SCRIPT_MAX_LENGTH = 16 * 1024; -export const TEARDOWN_TIMEOUT_MS = 2 * 60_000; -export const TEARDOWN_OUTPUT_TAIL_CHARS = 8 * 1024; +export const WORKTREE_SCRIPT_TIMEOUT_MS = 2 * 60_000; +export const WORKTREE_SCRIPT_OUTPUT_TAIL_CHARS = 8 * 1024; /** Lines of output quoted in the failure notice; the rest is in the log tail. */ const FAILURE_EXCERPT_LINES = 6; const KILL_GRACE_MS = 3_000; @@ -117,7 +118,7 @@ export function buildScriptInvocation( } /** - * Variables setup and teardown scripts can use, e.g. to copy from the main + * Variables worktree scripts can use, e.g. to copy from the main * checkout. No task id: `PARALLEL_CODE_TASK_ID` is the agent-hook identity, * which the PTY layer strips and child processes must not inherit. */ @@ -147,29 +148,31 @@ export async function listLinkedWorktrees(projectRoot: string): Promise; timeoutMs?: number; } -export interface TeardownDeps { +export interface WorktreeScriptDeps { spawnImpl?: typeof spawn; platform?: NodeJS.Platform; shell?: string; - /** Defaults to `git worktree list`; teardown only runs in a listed worktree. */ + /** Defaults to `git worktree list`; scripts only run in a listed worktree. */ listWorktrees?: (projectRoot: string) => Promise; } @@ -190,15 +193,42 @@ function realpathOrResolve(p: string): string { function appendTail(tail: string, chunk: string): string { const next = tail + chunk; - return next.length > TEARDOWN_OUTPUT_TAIL_CHARS ? next.slice(-TEARDOWN_OUTPUT_TAIL_CHARS) : next; + return next.length > WORKTREE_SCRIPT_OUTPUT_TAIL_CHARS + ? next.slice(-WORKTREE_SCRIPT_OUTPUT_TAIL_CHARS) + : next; +} + +// Scripts on one worktree run one at a time, in the order they were asked for: +// a resume sent while the suspend is still stopping services waits for it, and +// so does the teardown of a task closed right after it was minimized. +const worktreeQueues = new Map>(); + +function inWorktreeQueue(key: string, run: () => Promise): Promise { + const next = (worktreeQueues.get(key) ?? Promise.resolve()).then(run, run); + const tail = next.catch(() => undefined); + worktreeQueues.set(key, tail); + void tail.then(() => { + if (worktreeQueues.get(key) === tail) worktreeQueues.delete(key); + }); + return next; +} + +/** Runs a worktree script (teardown, suspend or resume) in the worktree, after + * any other script still running there, and reports how it ended. Never throws. */ +export function runWorktreeScript( + request: WorktreeScriptRequest, + deps: WorktreeScriptDeps = {}, +): Promise { + return inWorktreeQueue(realpathOrResolve(request.worktreePath), () => + checkAndRunWorktreeScript(request, deps), + ); } -/** Runs the teardown script in the worktree and reports how it ended. Never throws. */ -export async function runTeardownScript( - request: TeardownRequest, - deps: TeardownDeps = {}, -): Promise { - const skipped = (message: string): TeardownResult => ({ +async function checkAndRunWorktreeScript( + request: WorktreeScriptRequest, + deps: WorktreeScriptDeps, +): Promise { + const skipped = (message: string): WorktreeScriptResult => ({ status: 'skipped', exitCode: null, outputTail: '', @@ -207,7 +237,7 @@ export async function runTeardownScript( if (!fs.existsSync(request.worktreePath)) return skipped('The worktree no longer exists.'); const target = realpathOrResolve(request.worktreePath); if (target === realpathOrResolve(request.projectRoot)) { - return skipped('Teardown never runs in the main checkout.'); + return skipped('Worktree scripts never run in the main checkout.'); } // A path the renderer sent is only trusted once git confirms it is one of // this repository's linked worktrees, so a stale or mistaken path can never @@ -231,14 +261,17 @@ export async function runTeardownScript( message: `${request.worktreePath} is not a worktree of this repository, so it was not run`, }; } - return spawnTeardown(request, deps); + return spawnWorktreeScript(request, deps); } -function spawnTeardown(request: TeardownRequest, deps: TeardownDeps): Promise { +function spawnWorktreeScript( + request: WorktreeScriptRequest, + deps: WorktreeScriptDeps, +): Promise { const platform = deps.platform ?? process.platform; const invocation = buildScriptInvocation(request.script, { platform, shell: deps.shell }); const spawnImpl = deps.spawnImpl ?? spawn; - const timeoutMs = request.timeoutMs ?? TEARDOWN_TIMEOUT_MS; + const timeoutMs = request.timeoutMs ?? WORKTREE_SCRIPT_TIMEOUT_MS; return new Promise((resolve) => { let child: ReturnType; @@ -284,7 +317,7 @@ function spawnTeardown(request: TeardownRequest, deps: TeardownDeps): Promise { + const finish = (result: WorktreeScriptResult) => { if (settled) return; settled = true; for (const t of timers) clearTimeout(t); @@ -293,7 +326,7 @@ function spawnTeardown(request: TeardownRequest, deps: TeardownDeps): Promise { + const outcome = (code: number | null, signal: NodeJS.Signals | null): WorktreeScriptResult => { if (timedOut) return { status: 'timed_out', @@ -333,10 +366,13 @@ function spawnTeardown(request: TeardownRequest, deps: TeardownDeps): Promise line.length > 0) .slice(-FAILURE_EXCERPT_LINES) .join('\n'); - return `Teardown script ${how}.${excerpt ? `\n${excerpt}` : ''}`; + return `${label} script ${how}.${excerpt ? `\n${excerpt}` : ''}`; } diff --git a/electron/preload.cjs b/electron/preload.cjs index c278fd472..54044f345 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -134,6 +134,7 @@ const ALLOWED_CHANNELS = new Set([ 'set_minimax_api_key', 'set_project_agent_env', 'set_project_worktree_settings', + 'run_worktree_lifecycle_script', 'list_codex_models', 'check_docker_available', 'check_docker_image_exists', diff --git a/src/components/EditProjectDialog.client.test.tsx b/src/components/EditProjectDialog.client.test.tsx index 791f527a8..7891780a0 100644 --- a/src/components/EditProjectDialog.client.test.tsx +++ b/src/components/EditProjectDialog.client.test.tsx @@ -289,6 +289,23 @@ describe('worktree setup settings', () => { expect(store.projects[0].worktreeSetupScript).toBeUndefined(); }); + it('saves suspend and resume scripts', async () => { + vi.mocked(invoke).mockResolvedValue(undefined); + const dialog = open(); + for (const [label, value] of [ + ['Suspend script', 'docker compose stop'], + ['Resume script', 'docker compose start'], + ]) { + const input = field(label); + input.value = value; + input.dispatchEvent(new Event('input', { bubbles: true })); + } + dialog.save(); + await vi.waitFor(() => expect(dialog.onClose).toHaveBeenCalled()); + expect(store.projects[0].worktreeSuspendScript).toBe('docker compose stop'); + expect(store.projects[0].worktreeResumeScript).toBe('docker compose start'); + }); + it('seeds a saved include list from the defaults and stores per-entry modes', async () => { vi.mocked(invoke).mockImplementation(async (channel) => channel === IPC.GetGitignoredDirs diff --git a/src/components/ProjectWorktreeSetupSection.tsx b/src/components/ProjectWorktreeSetupSection.tsx index 67deb29c7..e1d71e75d 100644 --- a/src/components/ProjectWorktreeSetupSection.tsx +++ b/src/components/ProjectWorktreeSetupSection.tsx @@ -35,8 +35,8 @@ const SCRIPT_VARIABLES = '$PARALLEL_CODE_ROOT_PATH, $PARALLEL_CODE_WORKTREE, $PA /** * Opt-in worktree preparation for a Git project: what runs after a worktree - * is created and before it is removed, and a saved choice of ignored files to - * bring in. Everything empty keeps today's behaviour exactly. + * is created, before it is removed, and when its task is minimized and + * restored, and a saved choice of ignored files to bring in. Everything empty keeps today's behaviour exactly. */ export function ProjectWorktreeSetupSection(props: ProjectWorktreeSetupSectionProps) { const form = () => props.form; @@ -132,6 +132,46 @@ export function ProjectWorktreeSetupSection(props: ProjectWorktreeSetupSectionPr )} + + {(id) => ( +