Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
74 changes: 74 additions & 0 deletions packages/core/src/hooks/hook-runner.process.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,80 @@ const isRunning = (pid: number): boolean => {
return !result.stdout.trim().startsWith('Z');
};

describe.runIf(process.platform === 'win32')(
'HookRunner Windows project directory expansion',
() => {
it.each(['QWEN_PROJECT_DIR', 'GEMINI_PROJECT_DIR', 'CLAUDE_PROJECT_DIR'])(
'expands $%s for cmd.exe',
async (variable) => {
const tempDir = await mkdtemp(
join(tmpdir(), "qwen hook (project) & 'quoted' "),
);

try {
const runner = new HookRunner();
const input: HookInput = {
session_id: 'project-dir-test',
transcript_path: join(tempDir, 'transcript.jsonl'),
cwd: tempDir,
hook_event_name: HookEventName.PreToolUse,
timestamp: new Date().toISOString(),
};

const result = await runner.executeHook(
{
type: HookType.Command,
command: `if exist $${variable} (echo FOUND) else (echo MISSING)`,
source: HooksConfigSource.Project,
},
HookEventName.PreToolUse,
input,
);

expect(result.success).toBe(true);
expect(result.stdout?.trim()).toBe('FOUND');
} finally {
await rm(tempDir, { recursive: true, force: true });
}
},
);

it('expands QWEN_PROJECT_DIR for PowerShell', async () => {
const tempDir = await mkdtemp(
join(tmpdir(), "qwen hook (project) & 'quoted' "),
);

try {
const runner = new HookRunner();
const input: HookInput = {
session_id: 'project-dir-test',
transcript_path: join(tempDir, 'transcript.jsonl'),
cwd: tempDir,
hook_event_name: HookEventName.PreToolUse,
timestamp: new Date().toISOString(),
};

const result = await runner.executeHook(
{
type: HookType.Command,
command:
"if (Test-Path $QWEN_PROJECT_DIR) { Write-Output 'FOUND' } else { Write-Output 'MISSING' }",
source: HooksConfigSource.Project,
shell: 'powershell',
},
HookEventName.PreToolUse,
input,
);

expect(result.success).toBe(true);
expect(result.stdout?.trim()).toBe('FOUND');
} finally {
await rm(tempDir, { recursive: true, force: true });
}
});
},
);

describe.skipIf(process.platform === 'win32')(
'HookRunner process tree cancellation',
() => {
Expand Down
94 changes: 94 additions & 0 deletions packages/core/src/hooks/hookRunner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ describe('HookRunner', () => {
// Benign inherited env and the hook's own vars are still present.
expect(spawnOptions.env['PATH']).toBeDefined();
expect(spawnOptions.env['QWEN_PROJECT_DIR']).toBe('/test');
expect(spawnOptions.env['GEMINI_PROJECT_DIR']).toBe('/test');
expect(spawnOptions.env['CLAUDE_PROJECT_DIR']).toBe('/test');
} finally {
if (originalServerToken === undefined) {
delete process.env['QWEN_SERVER_TOKEN'];
Expand Down Expand Up @@ -924,6 +926,96 @@ describe('HookRunner', () => {
});

describe('expandCommand', () => {
it('should expand QWEN_PROJECT_DIR placeholder', async () => {
const mockProcess = createMockProcess(0, 'result');
mockSpawn.mockImplementation(() => mockProcess);

const hookConfig: HookConfig = {
type: HookType.Command,
command: 'echo $QWEN_PROJECT_DIR',
source: HooksConfigSource.Project,
shell: 'powershell',
};
const input = createMockInput({ cwd: '/test/project' });

await hookRunner.executeHook(hookConfig, HookEventName.PreToolUse, input);

const spawnCall = mockSpawn.mock.calls[0];
const command = spawnCall[1][spawnCall[1].length - 1];
expect(command).toContain('/test/project');
expect(command).not.toContain('$QWEN_PROJECT_DIR');
});

it('leaves bash placeholders to the child environment', async () => {
const mockProcess = createMockProcess(0, 'result');
mockSpawn.mockImplementation(() => mockProcess);

const hookConfig: HookConfig = {
type: HookType.Command,
command: '# note $QWEN_PROJECT_DIR\necho $QWEN_PROJECT_DIRS',
source: HooksConfigSource.Project,
shell: 'bash',
};

await hookRunner.executeHook(
hookConfig,
HookEventName.PreToolUse,
createMockInput({ cwd: '/test/project' }),
);

const spawnCall = mockSpawn.mock.calls[0];
expect(spawnCall[1][spawnCall[1].length - 1]).toBe(
'# note $QWEN_PROJECT_DIR\necho $QWEN_PROJECT_DIRS',
);
});

it('expands all supported placeholders without rescanning the path', async () => {
const mockProcess = createMockProcess(0, 'result');
mockSpawn.mockImplementation(() => mockProcess);

const hookConfig: HookConfig = {
type: HookType.Command,
command:
'echo $QWEN_PROJECT_DIR $GEMINI_PROJECT_DIR $CLAUDE_PROJECT_DIR $QWEN_PROJECT_DIRS',
source: HooksConfigSource.Project,
shell: 'powershell',
};

await hookRunner.executeHook(
hookConfig,
HookEventName.PreToolUse,
createMockInput({ cwd: 'C:/test/$CLAUDE_PROJECT_DIR' }),
);

const spawnCall = mockSpawn.mock.calls[0];
const command = spawnCall[1][spawnCall[1].length - 1];
expect(command).toContain('C:/test/$CLAUDE_PROJECT_DIR');
expect(command.match(/C:\/test\/\$CLAUDE_PROJECT_DIR/g)).toHaveLength(3);
expect(command).toContain('$QWEN_PROJECT_DIRS');
});

it('preserves PowerShell quoting and Unicode variable boundaries', async () => {
const mockProcess = createMockProcess(0, 'result');
mockSpawn.mockImplementation(() => mockProcess);

const hookConfig: HookConfig = {
type: HookType.Command,
command: 'echo $QWEN_PROJECT_DIR $QWEN_PROJECT_DIRé',
source: HooksConfigSource.Project,
shell: 'powershell',
};

await hookRunner.executeHook(
hookConfig,
HookEventName.PreToolUse,
createMockInput({ cwd: 'C:/test/my project' }),
);

const spawnCall = mockSpawn.mock.calls[0];
const command = spawnCall[1][spawnCall[1].length - 1];
expect(command).toBe("echo 'C:/test/my project' $QWEN_PROJECT_DIRé");
});

it('should expand GEMINI_PROJECT_DIR placeholder', async () => {
const mockProcess = createMockProcess(0, 'result');
mockSpawn.mockImplementation(() => mockProcess);
Expand All @@ -932,6 +1024,7 @@ describe('HookRunner', () => {
type: HookType.Command,
command: 'echo $GEMINI_PROJECT_DIR',
source: HooksConfigSource.Project,
shell: 'powershell',
};
const input = createMockInput({ cwd: '/test/project' });

Expand All @@ -951,6 +1044,7 @@ describe('HookRunner', () => {
type: HookType.Command,
command: 'echo $CLAUDE_PROJECT_DIR',
source: HooksConfigSource.Project,
shell: 'powershell',
};
const input = createMockInput({ cwd: '/test/project' });

Expand Down
15 changes: 12 additions & 3 deletions packages/core/src/hooks/hookRunner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -809,6 +809,8 @@ export class HookRunner {
cwd: input.cwd,
stdio: ['pipe', 'pipe', 'pipe'],
shell: false,
windowsVerbatimArguments:
process.platform === 'win32' && shellConfig.shell === 'cmd',
// Own a process group so cancellation can signal the entire tree.
detached: process.platform !== 'win32',
},
Expand Down Expand Up @@ -1054,10 +1056,17 @@ export class HookRunner {
shellType: ShellType,
): string {
debugLogger.debug(`Expanding hook command: ${command} (cwd: ${input.cwd})`);
// Bash already expands QWEN/GEMINI/CLAUDE_PROJECT_DIR from the child
// environment. Leave its command text untouched so placeholders in
// comments, quoted strings, and shell assignments retain native semantics.
if (shellType === 'bash') {
return command;
}
const escapedCwd = escapeShellArg(input.cwd, shellType);
return command
.replace(/\$GEMINI_PROJECT_DIR/g, () => escapedCwd)
.replace(/\$CLAUDE_PROJECT_DIR/g, () => escapedCwd); // For compatibility
return command.replace(
/\$(?:QWEN|GEMINI|CLAUDE)_PROJECT_DIR(?![0-9A-Za-z_\p{L}\p{N}])/gu,
() => escapedCwd,
);
}

/**
Expand Down
Loading