From 8338e77f46d61e668c9545dd3afecb96a7edd65a Mon Sep 17 00:00:00 2001 From: Mohamed Boudra Date: Wed, 25 Nov 2026 11:03:05 +0100 Subject: [PATCH] fix(plugins): keep empty launcher arguments on Windows and stop lifecycle hooks at the deadline A `.cmd` or `.bat` launch dropped an empty argument because cmd.exe saw only whitespace; it is now quoted as `""` and keeps its position. Teardown waited for a pending command.run.before hook past its deadline and then started the command. Hook preparation now races the teardown deadline and setup's cancel signal, and an aborted preparation never starts the command. --- .../process-internal/windows-command.ts | 3 +- packages/plugin/src/server/process.test.ts | 3 +- .../src/utils/spawn.launch-regression.test.ts | 15 ++++- packages/server/src/utils/worktree.test.ts | 39 +++++++++++ packages/server/src/utils/worktree.ts | 65 ++++++++++++++----- 5 files changed, 104 insertions(+), 21 deletions(-) diff --git a/packages/plugin/src/server/process-internal/windows-command.ts b/packages/plugin/src/server/process-internal/windows-command.ts index 188209437e..8ff201cfec 100644 --- a/packages/plugin/src/server/process-internal/windows-command.ts +++ b/packages/plugin/src/server/process-internal/windows-command.ts @@ -19,7 +19,8 @@ function escapeWindowsCmdValue(value: string, platform: NodeJS.Platform): string // escape for a literal `%`, so the format atoms become literals). const escaped = unquoted.replace(/([&|^<>()!])/g, "^$1"); - if (isQuoted || /[\s"]/u.test(unquoted)) { + // An empty argument is quoted so cmd.exe keeps it in its position instead of dropping it. + if (isQuoted || unquoted === "" || /[\s"]/u.test(unquoted)) { const quoted = escaped .replace(/(\\*)"/g, (_match, slashes: string) => `${slashes}${slashes}\\"`) .replace(/\\+$/u, (slashes) => `${slashes}${slashes}`); diff --git a/packages/plugin/src/server/process.test.ts b/packages/plugin/src/server/process.test.ts index 9e7eeb707a..de3ea276d9 100644 --- a/packages/plugin/src/server/process.test.ts +++ b/packages/plugin/src/server/process.test.ts @@ -60,12 +60,13 @@ test("a Windows script launch wrap starts through cmd.exe with each argument quo "C:\\Program Files\\Sandbox\\run.cmd", "--profile", "work profile", + "", "C:\\tools\\agy.cmd", "acp", ]; expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "win32")).toEqual({ command: '"C:\\Program Files\\Sandbox\\run.cmd"', - args: ["--profile", '"work profile"', "C:\\tools\\agy.cmd", "acp"], + args: ["--profile", '"work profile"', '""', "C:\\tools\\agy.cmd", "acp"], shell: true, }); expect(resolveSpawnInvocation(wrapped[0]!, wrapped.slice(1), undefined, "linux")).toEqual({ diff --git a/packages/server/src/utils/spawn.launch-regression.test.ts b/packages/server/src/utils/spawn.launch-regression.test.ts index 4943e68990..2ffe92f88c 100644 --- a/packages/server/src/utils/spawn.launch-regression.test.ts +++ b/packages/server/src/utils/spawn.launch-regression.test.ts @@ -127,6 +127,7 @@ async function runFixture(params: { args: string[]; shell?: boolean; env?: NodeJS.ProcessEnv; + expectedArgs?: string[]; }): Promise { const child = spawnProcess(params.command, params.args, { env: { @@ -135,7 +136,7 @@ async function runFixture(params: { // Terminal color settings must not add Node warnings to the argv fixture's stderr. NO_COLOR: undefined, FORCE_COLOR: undefined, - PASEO_EXPECTED_ARGV_JSON: JSON.stringify(["--config", JSON_ARG]), + PASEO_EXPECTED_ARGV_JSON: JSON.stringify(params.expectedArgs ?? ["--config", JSON_ARG]), }, stdio: ["ignore", "pipe", "pipe"], ...(params.shell === undefined ? {} : { shell: params.shell }), @@ -278,6 +279,18 @@ describe.runIf(isPlatform("win32"))("Windows spawn launch regression", () => { expect(result.stdout.trim()).toBe("ARGV_OK"); }); + // A plugin launch wrap can pass an empty argument to a .cmd launcher; cmd.exe must keep its slot. + test("launches a cmd shim with an empty argument in its position", async () => { + const fixture = makeFixture(); + const args = ["--profile", "", "--config", JSON_ARG]; + + const result = await runFixture({ command: fixture.shim, args, expectedArgs: args }); + + expect(result.stderr).toBe(""); + expect(result.stdout.trim()).toBe("ARGV_OK"); + expect(result.code).toBe(0); + }); + test("direct launch with a space-containing executable preserves JSON args", async () => { const fixture = makeFixture(); diff --git a/packages/server/src/utils/worktree.test.ts b/packages/server/src/utils/worktree.test.ts index a3ce36d170..58bd50cbb1 100644 --- a/packages/server/src/utils/worktree.test.ts +++ b/packages/server/src/utils/worktree.test.ts @@ -223,6 +223,45 @@ describe("paseo worktree manager", () => { }).toEqual({ exitCode: 0, stdoutLength: limit, stderrLength: limit }); }); + it("stops teardown at its deadline while a plugin hook is pending, without starting the command", async () => { + writeFileSync( + join(repoDir, "paseo.json"), + JSON.stringify({ + worktree: { + teardown: `node -e "require('fs').writeFileSync('ran.txt', 'ran')"`, + teardownTimeoutMs: 100, + }, + }), + ); + let hookDone!: () => void; + const hookSettled = new Promise((resolve) => { + hookDone = resolve; + }); + + const startedAt = Date.now(); + await expect( + runWorktreeTeardownCommands({ + worktreePath: repoDir, + repoRootPath: repoDir, + branchName: "main", + prepareCommand: async ({ env }) => { + await new Promise((resolve) => setTimeout(resolve, 1000)); + hookDone(); + return { env }; + }, + }), + ).rejects.toMatchObject({ + name: "WorktreeTeardownError", + message: `Worktree teardown command failed: node -e "require('fs').writeFileSync('ran.txt', 'ran')"\nTimed out after 0.1s`, + results: [], + }); + expect(Date.now() - startedAt).toBeLessThan(900); + // The hook answering after the deadline does not start the command. + await hookSettled; + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(existsSync(join(repoDir, "ran.txt"))).toBe(false); + }); + it("rejects paths that are not under the paseo worktrees root", async () => { const outsidePath = join(tempDir, "outside-paseo-home"); mkdirSync(outsidePath, { recursive: true }); diff --git a/packages/server/src/utils/worktree.ts b/packages/server/src/utils/worktree.ts index 3a8cd3a041..134499243d 100644 --- a/packages/server/src/utils/worktree.ts +++ b/packages/server/src/utils/worktree.ts @@ -157,16 +157,34 @@ export type PrepareWorktreeLifecycleCommand = ( command: WorktreeLifecycleCommand, ) => Promise; -async function prepareLifecycleCommand( - prepare: PrepareWorktreeLifecycleCommand | undefined, - command: WorktreeLifecycleCommand, - fail: (message: string) => Error, -): Promise { +/** + * Asks the hooks how to run `command`. Resolves to `null` when `signal` aborts first, such as at the + * teardown deadline or when archive cancels setup; the command must then not start. + */ +async function prepareLifecycleCommand(options: { + prepare: PrepareWorktreeLifecycleCommand | undefined; + command: WorktreeLifecycleCommand; + signal: AbortSignal | undefined; + fail: (message: string) => Error; +}): Promise { + const { prepare, command, signal } = options; + if (signal?.aborted) return null; if (!prepare) return { env: command.env }; + let stopWaiting = () => {}; + const aborted = new Promise((settle) => { + const onAbort = () => settle(null); + signal?.addEventListener("abort", onAbort, { once: true }); + stopWaiting = () => signal?.removeEventListener("abort", onAbort); + }); + const prepared = prepare(command).catch((error: unknown) => { + throw options.fail(error instanceof Error ? error.message : String(error)); + }); + // A hook that settles after the abort no longer matters; keep its rejection handled. + prepared.catch(() => {}); try { - return await prepare(command); - } catch (error) { - throw fail(error instanceof Error ? error.message : String(error)); + return await Promise.race([prepared, aborted]); + } finally { + stopWaiting(); } } @@ -740,12 +758,16 @@ export async function runWorktreeSetupCommands(options: { const results: WorktreeSetupCommandResult[] = []; for (const [index, cmd] of setupCommands.entries()) { - const prepared = await prepareLifecycleCommand( - options.prepareCommand, - { command: cmd, env: { ...runtimeEnv } }, - (message) => + const prepared = await prepareLifecycleCommand({ + prepare: options.prepareCommand, + command: { command: cmd, env: { ...runtimeEnv } }, + signal: options.signal, + fail: (message) => new WorktreeSetupError(`Worktree setup command refused: ${cmd}\n${message}`, results), - ); + }); + if (!prepared) { + throw new WorktreeSetupError(`Worktree setup canceled before: ${cmd}`, results); + } const setupEnv = createStringCommandShellEnv( createExternalProcessEnv(process.env, prepared.env), ); @@ -868,12 +890,19 @@ export async function runWorktreeTeardownCommands(options: { const deadline = AbortSignal.timeout(timeoutMs); const results: WorktreeTeardownCommandResult[] = []; for (const [index, cmd] of teardownCommands.entries()) { - const prepared = await prepareLifecycleCommand( - options.prepareCommand, - { command: cmd, env: { ...runtimeEnv } }, - (message) => + const prepared = await prepareLifecycleCommand({ + prepare: options.prepareCommand, + command: { command: cmd, env: { ...runtimeEnv } }, + signal: deadline, + fail: (message) => new WorktreeTeardownError(`Worktree teardown command refused: ${cmd}\n${message}`, results), - ); + }); + if (!prepared) { + throw new WorktreeTeardownError( + `Worktree teardown command failed: ${cmd}\nTimed out after ${timeoutMs / 1000}s`, + results, + ); + } const result = await execSetupCommandStreamed({ command: cmd, wrap: prepared.wrap,