Files
waggle-os/packages/agent/tests/tool-launcher.test.ts
shumeiko.it 25f95c584b refactor: launch external tools without Room credentials or hook settings
A Launcher launch still opens the tool in the active workspace's folder,
tracks its process, streams observed output and stops it. What it no
longer does:

- set WAGGLE_SIGNAL_EMIT, WAGGLE_SIDECAR_URL, HIVE_MIND_DATA_DIR or the
  Room identity variables (WAGGLE_RUN_ID, WAGGLE_ROOM_ID,
  WAGGLE_DANCE_TEAM_ID, WAGGLE_SENDER_ID, WAGGLE_RUN_TOKEN). Only the
  removed coding-agent hooks and the WaggleDance CLI read them. The
  external-process allowlist now admits WAGGLE_WORKSPACE_ID alone;
- issue a run credential. Run tokens existed for Room workers (the dance
  CLI and OpenClaw's model calls), so the registry's credential store,
  the middleware's run-token bearer on /v1/chat/completions and the
  proxy's per-run model scope go. While an agent run with a model is
  active, the proxy still serves only the session bearer.

The run record that a launch creates in the agent-run registry stays: it
backs cancel from the Room canvas, which this change does not remove.
2026-11-01 11:12:31 +01:00

374 lines
13 KiB
TypeScript

/**
* AI-OS Phase 2A — tool launcher tests.
*
* TDD coverage for launchTool(). All process
* spawns are injected so the test never actually executes a binary.
*/
import { execFileSync, type ChildProcess } from 'node:child_process';
import { EventEmitter } from 'node:events';
import { describe, it, expect, vi } from 'vitest';
import { join } from 'node:path';
import {
launchTool,
createObservedHandle,
defaultSpawnObserved,
resolveSpawnInvocation,
type ToolLauncherDeps,
type ObservedHandle,
} from '../src/tool-launcher.js';
import type { ToolId, ToolManifest } from '@waggle/shared';
function captureSpawn() {
const calls: Array<{
binary: string;
args: string[];
options: { cwd?: string; env?: NodeJS.ProcessEnv };
}> = [];
const spawnDetached: NonNullable<ToolLauncherDeps['spawnDetached']> = (
binary,
args,
options,
) => {
calls.push({ binary, args, options });
return { pid: 12345 };
};
return { calls, spawnDetached };
}
// ── launchTool ──────────────────────────────────────────────────────
describe('launchTool', () => {
it('spawns claude-code with the supplied installedPath and returns pid', () => {
const { calls, spawnDetached } = captureSpawn();
const result = launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
deps: { spawnDetached },
});
expect(result.ok).toBe(true);
expect(result.pid).toBe(12345);
expect(calls).toHaveLength(1);
expect(calls[0].binary).toBe('/usr/local/bin/claude');
});
it('injects WAGGLE_WORKSPACE_ID env when provided', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'codex-desktop',
installedPath: '/Applications/Codex.app/Contents/MacOS/Codex',
workspaceId: 'ws-kvark',
deps: { spawnDetached },
});
expect(calls[0].options.env?.WAGGLE_WORKSPACE_ID).toBe('ws-kvark');
});
it('fails closed against ambient provider and infrastructure secrets', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: 'C:\\tools\\claude.exe',
workspaceId: 'ws-isolated',
deps: {
platform: 'win32',
baseEnv: {
PATH: 'C:\\Windows\\System32',
PATHEXT: '.COM;.EXE;.CMD',
USERPROFILE: 'C:\\Users\\tester',
APPDATA: 'C:\\Users\\tester\\AppData\\Roaming',
LOCALAPPDATA: 'C:\\Redirected\\Local',
HERMES_HOME: 'D:\\Hermes Data',
TERM: 'xterm-256color',
ANTHROPIC_API_KEY: 'anthropic-secret',
OPENAI_API_KEY: 'openai-secret',
OPENROUTER_API_KEY: 'openrouter-secret',
GEMINI_API_KEY: 'gemini-secret',
STRIPE_SECRET_KEY: 'stripe-secret',
AWS_SECRET_ACCESS_KEY: 'aws-secret',
DATABASE_URL: 'database-secret',
SSH_AUTH_SOCK: 'credential-socket',
GIT_ASKPASS: 'credential-helper',
HTTPS_PROXY: 'https://user:secret@proxy.invalid',
NODE_OPTIONS: '--require C:\\malicious.js',
WAGGLE_RUN_TOKEN: 'stale-ambient-token',
},
spawnDetached,
},
});
expect(calls[0].options.env).toMatchObject({
PATH: 'C:\\Windows\\System32',
PATHEXT: '.COM;.EXE;.CMD',
USERPROFILE: 'C:\\Users\\tester',
APPDATA: 'C:\\Users\\tester\\AppData\\Roaming',
LOCALAPPDATA: 'C:\\Redirected\\Local',
HERMES_HOME: 'D:\\Hermes Data',
TERM: 'xterm-256color',
WAGGLE_WORKSPACE_ID: 'ws-isolated',
});
for (const name of [
'ANTHROPIC_API_KEY', 'OPENAI_API_KEY', 'OPENROUTER_API_KEY',
'GEMINI_API_KEY', 'STRIPE_SECRET_KEY', 'AWS_SECRET_ACCESS_KEY',
'DATABASE_URL', 'SSH_AUTH_SOCK', 'GIT_ASKPASS', 'HTTPS_PROXY',
'NODE_OPTIONS', 'WAGGLE_RUN_TOKEN',
]) {
expect(calls[0].options.env?.[name], name).toBeUndefined();
}
});
it('does not inject env when workspaceId is absent', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'codex-desktop',
installedPath: '/Applications/Codex.app/Contents/MacOS/Codex',
deps: { spawnDetached },
});
expect(calls[0].options.env?.WAGGLE_WORKSPACE_ID).toBeUndefined();
});
it('forwards cwd and args', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
cwd: '/home/user/project',
args: ['--continue'],
deps: { spawnDetached },
});
expect(calls[0].args).toEqual(['--continue']);
expect(calls[0].options.cwd).toBe('/home/user/project');
});
it('reports ok=false when the spawn returns no pid', () => {
const spawnDetached: NonNullable<ToolLauncherDeps['spawnDetached']> = () => ({
pid: null,
error: 'ENOENT',
});
const result = launchTool({
id: 'claude-code',
installedPath: '/missing/path/claude',
deps: { spawnDetached },
});
expect(result.ok).toBe(false);
expect(result.error).toBe('ENOENT');
});
it.each<ToolId>([
'claude-code', 'claude-desktop', 'codex', 'codex-desktop', 'hermes', 'hermes-desktop',
])('accepts every release-supported launch cohort tool (%s)', (id) => {
const { spawnDetached } = captureSpawn();
const result = launchTool({
id,
installedPath: `/somewhere/${id}`,
deps: { spawnDetached },
});
expect(result.ok).toBe(true);
expect(result.pid).toBe(12345);
});
it.each<ToolId>(['cursor', 'openclaw'])(
'rejects roadmap tool %s without spawning it',
(id) => {
const { calls, spawnDetached } = captureSpawn();
const result = launchTool({
id,
installedPath: `/somewhere/${id}`,
deps: { spawnDetached },
});
expect(result.ok).toBe(false);
expect(result.error).toContain('not launchable');
expect(calls).toHaveLength(0);
},
);
it('rejects empty installedPath', () => {
const { spawnDetached } = captureSpawn();
const result = launchTool({
id: 'claude-code',
installedPath: '',
deps: { spawnDetached },
});
expect(result.ok).toBe(false);
expect(result.error).toContain('installedPath is required');
});
it('accepts a launchable third-party adapter from the supplied registry', () => {
const { calls, spawnDetached } = captureSpawn();
const thirdParty: ToolManifest = {
id: 'foo-cli',
displayName: 'Foo CLI',
launchable: true,
detect: { kind: 'path', binaryName: 'foo' },
builtin: false,
};
const result = launchTool({
id: 'foo-cli',
installedPath: '/usr/local/bin/foo',
toolRegistry: [thirdParty],
deps: { spawnDetached },
});
expect(result.ok).toBe(true);
expect(result.pid).toBe(12345);
expect(calls[0].binary).toBe('/usr/local/bin/foo');
});
it('refuses a registered adapter that is not launchable', () => {
const { calls, spawnDetached } = captureSpawn();
const thirdParty: ToolManifest = {
id: 'foo-cli',
displayName: 'Foo CLI',
launchable: false,
detect: { kind: 'path', binaryName: 'foo' },
builtin: false,
};
const result = launchTool({
id: 'foo-cli',
installedPath: '/usr/local/bin/foo',
toolRegistry: [thirdParty],
deps: { spawnDetached },
});
expect(result.ok).toBe(false);
expect(result.error).toContain('not launchable');
expect(calls).toHaveLength(0);
});
});
// ── launchTool — no hook or Room env ─────────────────────────────────
// The coding-agent hooks and Waggle Room are not part of the community
// edition, so a launch sets only the workspace id.
describe('launchTool env', () => {
it('sets only WAGGLE_WORKSPACE_ID among Waggle variables', () => {
const { calls, spawnDetached } = captureSpawn();
launchTool({
id: 'claude-code',
installedPath: '/usr/local/bin/claude',
workspaceId: 'ws-1',
deps: { spawnDetached, baseEnv: { PATH: '/usr/bin' } },
});
const waggleVars = Object.keys(calls[0].options.env ?? {})
.filter((name) => name.startsWith('WAGGLE_') || name.startsWith('HIVE_MIND_'));
expect(waggleVars).toEqual(['WAGGLE_WORKSPACE_ID']);
});
});
describe('launchTool observe mode', () => {
it('preserves a target signal receipt instead of exposing the supervisor exit code', () => {
const child = new EventEmitter() as ChildProcess;
const handle = createObservedHandle(child);
const onExit = vi.fn();
handle.onExit(onExit);
child.emit('message', {
type: 'waggle-sidecar-owned-process-exit',
code: null,
signal: 'SIGTERM',
});
child.emit('exit', 1, null);
expect(onExit).toHaveBeenCalledOnce();
expect(onExit).toHaveBeenCalledWith(null);
});
it.runIf(process.platform === 'win32')(
'keeps the production observed target under a sidecar-owned supervisor',
async () => {
const result = defaultSpawnObserved(process.execPath, [
'-e',
"setTimeout(() => console.log(JSON.stringify({ pid: process.pid, ppid: process.ppid })), 100); setInterval(() => {}, 1000)",
], { env: process.env });
expect(result.pid).toBeTypeOf('number');
expect(result.handle).toBeDefined();
const supervisorPid = result.pid!;
try {
const payload = await new Promise<{ pid: number; ppid: number }>((resolvePayload, reject) => {
const timer = setTimeout(() => reject(new Error('Observed target produced no ownership receipt')), 5_000);
let output = '';
result.handle!.onData((chunk) => {
output += chunk;
const line = output.split(/\r?\n/, 1)[0];
try {
const parsed = JSON.parse(line) as { pid: number; ppid: number };
clearTimeout(timer);
resolvePayload(parsed);
} catch { /* wait for a complete JSON line */ }
});
});
expect(payload.pid).not.toBe(supervisorPid);
expect(payload.ppid).toBe(supervisorPid);
} finally {
const windowsRoot = process.env.SystemRoot ?? process.env.WINDIR ?? 'C:\\Windows';
try {
execFileSync(join(windowsRoot, 'System32', 'taskkill.exe'), [
'/PID', String(supervisorPid), '/T', '/F',
], { stdio: 'ignore', windowsHide: true });
} catch { /* best-effort fixture cleanup */ }
}
},
15_000,
);
it('uses spawnObserved and returns its handle when observe:true', () => {
const handle: ObservedHandle = { onData: () => {}, onExit: () => {} };
const spawnObserved = vi.fn(() => ({ pid: 4242, handle }));
const spawnDetached = vi.fn(() => ({ pid: 1 }));
const res = launchTool({
id: 'claude-code',
installedPath: '/usr/bin/claude',
observe: true,
deps: { spawnObserved, spawnDetached },
});
expect(spawnObserved).toHaveBeenCalledTimes(1);
expect(spawnDetached).not.toHaveBeenCalled();
expect(res.ok).toBe(true);
expect(res.pid).toBe(4242);
expect(res.output).toBe(handle);
});
it('uses spawnDetached and omits output when observe is absent', () => {
const spawnObserved = vi.fn(() => ({ pid: 9, handle: { onData() {}, onExit() {} } }));
const spawnDetached = vi.fn(() => ({ pid: 7 }));
const res = launchTool({
id: 'claude-code',
installedPath: '/usr/bin/claude',
deps: { spawnObserved, spawnDetached },
});
expect(spawnDetached).toHaveBeenCalledTimes(1);
expect(spawnObserved).not.toHaveBeenCalled();
expect(res.output).toBeUndefined();
});
it('reports observe spawn failure as ok:false', () => {
const res = launchTool({
id: 'claude-code',
installedPath: '/usr/bin/claude',
observe: true,
deps: { spawnObserved: () => ({ pid: null, error: 'boom' }) },
});
expect(res.ok).toBe(false);
expect(res.error).toBe('boom');
expect(res.output).toBeUndefined();
});
});
describe('resolveSpawnInvocation', () => {
it('rejects unrecognized Windows batch shims instead of invoking cmd.exe', () => {
expect(() => resolveSpawnInvocation(
'C:\\Users\\test\\AppData\\Roaming\\npm\\openclaw.cmd',
['safe" & echo injected & rem'],
'win32',
)).toThrow(/UNSAFE_WINDOWS_BATCH_SHIM/);
});
it('leaves Windows exe launches untouched', () => {
const invocation = resolveSpawnInvocation(
'C:\\Users\\test\\.local\\bin\\claude.exe',
['--version'],
'win32',
);
expect(invocation.binary).toBe('C:\\Users\\test\\.local\\bin\\claude.exe');
expect(invocation.args).toEqual(['--version']);
});
});