fix(websearch): close review gaps in managed runtime

This commit is contained in:
Tam Nhu Tran committed 2026-03-30 23:02:20 -04:00
1 parent de7171d810
commit cae5b710b8
15 files changed
+299 -60

No files matched your search

+54 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'bun:test';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { spawnSync } from 'node:child_process';
@@ -267,4 +267,57 @@ describe('websearch-transformer hook helpers', () => {
rmSync(tempDir, { force: true, recursive: true });
}
});
it('falls back to the default trace file when CCS_WEBSEARCH_TRACE_FILE points outside safe paths', () => {
const tempDir = mkdtempSync(join(tmpdir(), 'websearch-hook-trace-safe-'));
const preloadPath = join(tempDir, 'mock-fetch.cjs');
const ccsHome = join(tempDir, 'home');
const fallbackTracePath = join(ccsHome, '.ccs', 'logs', 'websearch-trace.jsonl');
const disallowedTracePath = join(process.cwd(), '.tmp-websearch-trace-unsafe.jsonl');
const html = `
<a class="result__a" href="/l/?uddg=https%3A%2F%2Fexample.com%2Farticle">Example title</a>
<a class="result__snippet">Example snippet</a>
`.trim();
writeFileSync(
preloadPath,
`global.fetch = async () => ({ ok: true, text: async () => ${JSON.stringify(html)} });\n`,
'utf8'
);
try {
rmSync(disallowedTracePath, { force: true });
const result = spawnSync('node', ['-r', preloadPath, hookPath], {
encoding: 'utf8',
input: JSON.stringify({
tool_name: 'WebSearch',
tool_input: { query: 'btc price' },
}),
env: {
...process.env,
CCS_HOME: ccsHome,
CCS_WEBSEARCH_TRACE: '1',
CCS_WEBSEARCH_TRACE_FILE: disallowedTracePath,
CCS_WEBSEARCH_TRACE_LAUNCH_ID: 'hook-trace-safe-test',
CCS_WEBSEARCH_TRACE_LAUNCHER: 'unit-test',
CCS_WEBSEARCH_ENABLED: '1',
CCS_WEBSEARCH_SKIP: '0',
CCS_WEBSEARCH_BRAVE: '0',
CCS_WEBSEARCH_DUCKDUCKGO: '1',
CCS_WEBSEARCH_EXA: '0',
CCS_WEBSEARCH_GEMINI: '0',
CCS_WEBSEARCH_GROK: '0',
CCS_WEBSEARCH_OPENCODE: '0',
CCS_WEBSEARCH_TAVILY: '0',
},
});
expect(result.status).toBe(0);
expect(existsSync(disallowedTracePath)).toBe(false);
expect(existsSync(fallbackTracePath)).toBe(true);
} finally {
rmSync(disallowedTracePath, { force: true });
rmSync(tempDir, { recursive: true, force: true });
}
});
});
@@ -144,6 +144,53 @@ describe('InstanceManager MCP sync', () => {
});
});
it('repairs managed ccs-websearch entries from global config while preserving other instance MCP overrides', () => {
fs.writeFileSync(
path.join(tempRoot, '.claude.json'),
JSON.stringify(
{
mcpServers: {
'ccs-websearch': { command: 'node', args: ['/global/server.cjs'] },
shared: { command: 'global-shared' },
},
},
null,
2
),
'utf8'
);
const manager = new InstanceManager();
const instancePath = manager.getInstancePath('work');
fs.mkdirSync(instancePath, { recursive: true });
fs.writeFileSync(
path.join(instancePath, '.claude.json'),
JSON.stringify(
{
mcpServers: {
'ccs-websearch': { command: 'node', args: ['/old/server.cjs'] },
shared: { command: 'instance-shared' },
instanceOnly: { command: 'instance-only' },
},
},
null,
2
),
'utf8'
);
expect(manager.syncMcpServers(instancePath)).toBe(true);
const instanceContent = readJson(path.join(instancePath, '.claude.json')) as {
mcpServers: Record<string, unknown>;
};
expect(instanceContent.mcpServers).toEqual({
'ccs-websearch': { command: 'node', args: ['/global/server.cjs'] },
shared: { command: 'instance-shared' },
instanceOnly: { command: 'instance-only' },
});
});
it('logs warning when global MCP sync fails', () => {
fs.writeFileSync(path.join(tempRoot, '.claude.json'), '{invalid-json', 'utf8');
const warnSpy = spyOn(console, 'warn').mockImplementation(() => {});
@@ -115,6 +115,18 @@ exit 0
expect(fs.existsSync(claudeArgsLogPath)).toBe(false);
});
it('fails before delegated headless launch when the local WebSearch tool runtime cannot be prepared', () => {
if (process.platform === 'win32') return;
fs.writeFileSync(path.join(ccsDir, 'hooks'), 'not-a-directory', 'utf8');
const result = runCcs(['glm', '-p', 'smoke'], baseEnv);
expect(result.status).toBe(1);
expect(result.stderr).toContain('could not prepare the local WebSearch tool');
expect(fs.existsSync(claudeArgsLogPath)).toBe(false);
});
it('keeps launch non-fatal when WebSearch is disabled', () => {
if (process.platform === 'win32') return;
@@ -336,9 +336,25 @@ describe('CLAUDECODE environment stripping', () => {
writeConfigWithAutoUpdatePreference(false);
const ccsDir = path.join(process.env.CCS_HOME as string, '.ccs');
fs.writeFileSync(path.join(ccsDir, 'glm.settings.json'), '{}\n', 'utf8');
const projectDir = path.join(ccsDir, 'project');
fs.mkdirSync(path.join(projectDir, '.claude'), { recursive: true });
fs.writeFileSync(
path.join(projectDir, '.claude', 'settings.local.json'),
JSON.stringify(
{
permissions: {
deny: ['Bash', 'WebFetch'],
},
},
null,
2
) + '\n',
'utf8'
);
process.env.CCS_CLAUDE_PATH = 'claude';
const result = await HeadlessExecutor.execute('glm', 'latest AI chip news', {
cwd: projectDir,
permissionMode: 'default',
timeout: 1000,
});
@@ -347,12 +363,23 @@ describe('CLAUDECODE environment stripping', () => {
expect(spawnCalls.length).toBeGreaterThan(0);
const launch = spawnCalls[0];
expect(launch.args).toContain('--disallowedTools');
expect(launch.args).toContain('WebSearch');
const disallowedToolsIndex = launch.args.indexOf('--disallowedTools');
expect(disallowedToolsIndex).toBeGreaterThan(-1);
expect(launch.args[disallowedToolsIndex + 1]).toBe('Bash,WebFetch,WebSearch');
expect(launch.args).toContain('--append-system-prompt');
expect(launch.args.join(' ')).toContain(STEERING_PROMPT_SNIPPET);
const env = launch.options?.env as NodeJS.ProcessEnv;
expect(env.CCS_PROFILE_TYPE).toBe('settings');
expect(env.CCS_WEBSEARCH_ENABLED || env.CCS_WEBSEARCH_SKIP).toBeDefined();
const claudeUserConfig = JSON.parse(
fs.readFileSync(path.join(process.env.CCS_HOME as string, '.claude.json'), 'utf8')
) as {
mcpServers?: Record<string, { command: string; args: string[] }>;
};
expect(claudeUserConfig.mcpServers?.['ccs-websearch']).toEqual({
command: 'node',
args: [path.join(ccsDir, 'mcp', 'ccs-websearch-server.cjs')],
});
});
it('headless executor propagates a WebSearch trace launch id when tracing is enabled', async () => {
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { afterEach, describe, expect, it, mock, spyOn } from 'bun:test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
@@ -39,6 +39,8 @@ describe('ensureWebSearchMcp', () => {
}
afterEach(() => {
mock.restore();
if (originalCcsHome !== undefined) {
process.env.CCS_HOME = originalCcsHome;
} else {
@@ -158,4 +160,23 @@ describe('ensureWebSearchMcp', () => {
existing: { command: 'uvx', args: ['instance-server'] },
});
});
it('falls back to copy-overwrite when rename is blocked during MCP server install', () => {
setupTempHome();
writeEnabledConfig();
const realRenameSync = fs.renameSync;
const renameSpy = spyOn(fs, 'renameSync').mockImplementation((oldPath, newPath) => {
if (String(newPath) === getWebSearchMcpServerPath()) {
const error = new Error('busy') as NodeJS.ErrnoException;
error.code = 'EPERM';
throw error;
}
return realRenameSync(oldPath, newPath);
});
expect(ensureWebSearchMcp()).toBe(true);
expect(renameSpy).toHaveBeenCalled();
expect(fs.existsSync(getWebSearchMcpServerPath())).toBe(true);
});
});