Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
203 changes: 203 additions & 0 deletions src/cli/commands/connect.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { Command } from 'commander';
import { mkdtempSync, rmSync, statSync } from 'node:fs';
import { readFile } from 'node:fs/promises';
import os from 'node:os';
import path from 'node:path';

import { describe, expect, it, vi } from 'vitest';

import { registerConnectCommands } from './connect.js';
import { CliDetectError } from '../lib/detect-cli.js';

class ExitSignal extends Error {
constructor(public readonly code: number) {
super(`exit:${code}`);
}
}

interface Harness {
program: Command;
logs: string[];
errors: string[];
exitCode: number | undefined;
connect: ReturnType<typeof vi.fn>;
}

function createHarness(connectImpl?: (cli: string) => Promise<{ cli: string; version: string; binPath: string; manifestPath: string }>): Harness {
const logs: string[] = [];
const errors: string[] = [];
let exitCode: number | undefined;
const exit = (code: number): never => {
exitCode = code;
throw new ExitSignal(code);
};
const connect = vi.fn(
connectImpl ??
(async (cli: string) => ({
cli,
version: '1.2.3',
binPath: `/usr/local/bin/${cli}`,
manifestPath: '/tmp/agent-relay/connections.json',
})),
);

const program = new Command();
program.exitOverride();
registerConnectCommands(program, {
connect: connect as any,
log: (msg) => logs.push(msg),
error: (msg) => errors.push(msg),
exit,
});
return {
program,
logs,
errors,
get exitCode() {
return exitCode;
},
connect,
} as Harness;
}

async function run(program: Command, args: string[]): Promise<number | undefined> {
try {
await program.parseAsync(args, { from: 'user' });
return undefined;
} catch (err) {
if (err instanceof ExitSignal) {
return err.code;
}
throw err;
}
}

describe('registerConnectCommands', () => {
it('runs the happy path for claude', async () => {
const h = createHarness();
const code = await run(h.program, ['connect', 'claude']);
expect(code).toBeUndefined();
expect(h.connect).toHaveBeenCalledWith('claude', undefined);
expect(h.logs.join('\n')).toContain('Connected claude 1.2.3');
expect(h.logs.join('\n')).toContain('Manifest:');
});

it('runs the happy path for codex', async () => {
const h = createHarness();
await run(h.program, ['connect', 'codex']);
expect(h.connect).toHaveBeenCalledWith('codex', undefined);
});

it('runs the happy path for gemini', async () => {
const h = createHarness();
await run(h.program, ['connect', 'gemini']);
expect(h.connect).toHaveBeenCalledWith('gemini', undefined);
});

it('prints the deprecation banner for unknown providers and exits 1', async () => {
const h = createHarness();
const code = await run(h.program, ['connect', 'anthropic']);
expect(code).toBe(1);
expect(h.errors.join('\n')).toContain('[DEPRECATED]');
expect(h.errors.join('\n')).toContain('agent-relay cloud connect anthropic');
expect(h.connect).not.toHaveBeenCalled();
});

it('still accepts legacy cloud-connect options before printing the deprecation banner', async () => {
const h = createHarness();
const code = await run(h.program, [
'connect',
'anthropic',
'--timeout',
'300',
'--language',
'typescript',
'--cloud-url',
'https://cloud.example.test',
]);
expect(code).toBe(1);
expect(h.errors.join('\n')).toContain('agent-relay cloud connect anthropic');
expect(h.connect).not.toHaveBeenCalled();
});

it('accepts arbitrary legacy unknown options without crashing before the deprecation banner', async () => {
// commander rejects unknown options at parse time by default. Scripted
// callers may still pass forgotten legacy flags beyond --timeout /
// --language / --cloud-url; allowUnknownOption(true) lets the action
// run, then the unknown-cli check below fires the deprecation banner.
const h = createHarness();
const code = await run(h.program, [
'connect',
'anthropic',
'--region',
'us-east-1',
'--really-old-flag',
]);
expect(code).toBe(1);
expect(h.errors.join('\n')).toContain('[DEPRECATED]');
expect(h.errors.join('\n')).toContain('agent-relay cloud connect anthropic');
expect(h.connect).not.toHaveBeenCalled();
});

it('surfaces NEEDS_CLI_INSTALL via stderr and exits 2', async () => {
const h = createHarness(async () => {
throw new CliDetectError(
'NEEDS_CLI_INSTALL',
2,
'NEEDS_CLI_INSTALL: claude not found on PATH. Install: https://docs.anthropic.com/claude-code/install',
);
});
const code = await run(h.program, ['connect', 'claude']);
expect(code).toBe(2);
expect(h.errors.join('\n')).toContain('NEEDS_CLI_INSTALL');
expect(h.errors.join('\n')).toContain('claude not found on PATH');
expect(h.errors.join('\n')).toContain('https://docs.anthropic.com/claude-code/install');
});

it('surfaces CLI_VERSION_FAILED via stderr and exits 3', async () => {
const h = createHarness(async () => {
throw new CliDetectError('CLI_VERSION_FAILED', 3, 'claude found but --version failed');
});
const code = await run(h.program, ['connect', 'claude']);
expect(code).toBe(3);
expect(h.errors.join('\n')).toContain('--version failed');
});

it('exits 4 for unexpected errors', async () => {
const h = createHarness(async () => {
throw new Error('boom');
});
const code = await run(h.program, ['connect', 'claude']);
expect(code).toBe(4);
expect(h.errors.join('\n')).toContain('boom');
});

it('end-to-end writes a manifest entry through the real connections-file helper', async () => {
const tmp = mkdtempSync(path.join(os.tmpdir(), 'connect-cmd-'));
try {
const { upsertConnectionsManifest } = await import('../lib/connections-file.js');
const harness = createHarness(async (cli) => {
const { manifestPath } = await upsertConnectionsManifest(
{
cli: cli as 'claude',
binPath: `/usr/local/bin/${cli}`,
version: '9.9.9',
rawVersionOutput: `${cli} 9.9.9`,
connectedAt: '2026-05-16T00:00:00.000Z',
},
{ xdgConfigHome: tmp },
);
return { cli, version: '9.9.9', binPath: `/usr/local/bin/${cli}`, manifestPath };
});
await run(harness.program, ['connect', 'claude']);
const manifestPath = path.join(tmp, 'agent-relay', 'connections.json');
const body = JSON.parse(await readFile(manifestPath, 'utf8'));
expect(body.clis.claude.version).toBe('9.9.9');
if (process.platform !== 'win32') {
expect(statSync(manifestPath).mode & 0o777).toBe(0o600);
}
} finally {
rmSync(tmp, { recursive: true, force: true });
}
});
});
82 changes: 70 additions & 12 deletions src/cli/commands/connect.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,75 @@
import { Command } from 'commander';

export function registerConnectCommands(program: Command): void {
import {
CliDetectError,
SUPPORTED_CLIS,
type SupportedCli,
connectCli,
type DetectCliDeps,
type ConnectCliResult,
} from '../lib/detect-cli.js';

export interface ConnectCommandDeps {
connect?: (cli: SupportedCli, deps?: DetectCliDeps) => Promise<ConnectCliResult>;
log?: (message: string) => void;
error?: (message: string) => void;
exit?: (code: number) => never;
detectDeps?: DetectCliDeps;
}

const DEPRECATION_BANNER = (providerArg: string): string =>
'\x1b[33m[DEPRECATED]\x1b[0m `agent-relay connect <provider>` has moved. Use:\n\n' +
` agent-relay cloud connect ${providerArg}\n`;

export function registerConnectCommands(
program: Command,
deps: ConnectCommandDeps = {},
): void {
const connect = deps.connect ?? connectCli;
const log = deps.log ?? ((m: string) => process.stdout.write(`${m}\n`));
const error = deps.error ?? ((m: string) => process.stderr.write(`${m}\n`));
const exit = deps.exit ?? ((code: number) => process.exit(code) as never);

program
.command('connect <provider>')
.description('[DEPRECATED] Use `agent-relay cloud connect <provider>` instead')
.option('--timeout <seconds>', 'Timeout in seconds (default: 300)', '300')
.option('--language <lang>', 'Sandbox language/image (default: typescript)', 'typescript')
.option('--cloud-url <url>', 'Cloud API URL')
.action(async (providerArg: string) => {
console.error(
'\x1b[33m[DEPRECATED]\x1b[0m `agent-relay connect` has moved. Use:\n\n' +
` agent-relay cloud connect ${providerArg}\n`
);
process.exit(1);
.command('connect <cli>')
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
.description(
`Connect a local AI CLI (${SUPPORTED_CLIS.join(' | ')}). Detects on PATH, version-checks, and writes ~/.config/agent-relay/connections.json. ` +
'Other provider arguments still print the legacy deprecation banner.',
)
.option('--timeout <seconds>', 'Deprecated cloud connect timeout option')
.option('--language <lang>', 'Deprecated cloud connect language/image option')
.option('--cloud-url <url>', 'Deprecated cloud connect API URL option')
// commander rejects unknown options before `.action` runs by default, so
// scripted callers passing any other legacy `agent-relay cloud connect`
// flag (beyond the three we explicitly handle above) would crash with
// "error: unknown option ..." instead of seeing the deprecation banner.
// Accept unknown options at parse time and surface them through the
// existing `<cli>` validation path so the banner can fire.
.allowUnknownOption(true)
.action(async (cliArg: string) => {
const normalized = cliArg.toLowerCase().trim();
if (!isSupportedCli(normalized)) {
error(DEPRECATION_BANNER(cliArg));
exit(1);
return;
}
try {
const result = await connect(normalized, deps.detectDeps);
log(`\x1b[32m✓\x1b[0m Connected ${result.cli} ${result.version} (${result.binPath})`);
log(` Manifest: ${result.manifestPath}`);
} catch (err) {
if (err instanceof CliDetectError) {
error(err.message);
exit(err.exitCode);
return;
}
const message = err instanceof Error ? err.message : String(err);
error(message);
exit(4);
}
});
}

function isSupportedCli(value: string): value is SupportedCli {
return (SUPPORTED_CLIS as readonly string[]).includes(value);
}
Loading
Loading