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.
This commit is contained in:
Mohamed Boudra
2026-11-25 17:37:32 +01:00
parent e5d81304f7
commit 8338e77f46
5 changed files with 104 additions and 21 deletions
@@ -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}`);
+2 -1
View File
@@ -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({
@@ -127,6 +127,7 @@ async function runFixture(params: {
args: string[];
shell?: boolean;
env?: NodeJS.ProcessEnv;
expectedArgs?: string[];
}): Promise<SpawnResult> {
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();
@@ -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<void>((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 });
+47 -18
View File
@@ -157,16 +157,34 @@ export type PrepareWorktreeLifecycleCommand = (
command: WorktreeLifecycleCommand,
) => Promise<PreparedWorktreeLifecycleCommand>;
async function prepareLifecycleCommand(
prepare: PrepareWorktreeLifecycleCommand | undefined,
command: WorktreeLifecycleCommand,
fail: (message: string) => Error,
): Promise<PreparedWorktreeLifecycleCommand> {
/**
* 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<PreparedWorktreeLifecycleCommand | null> {
const { prepare, command, signal } = options;
if (signal?.aborted) return null;
if (!prepare) return { env: command.env };
let stopWaiting = () => {};
const aborted = new Promise<null>((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,