Skip to content
Merged
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
56 changes: 55 additions & 1 deletion apps/cli/__tests__/agents/acp/internal-paths.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,31 @@ describe('internal-paths — CodeAgent internals guard predicates', () => {
it('flags references to ~/.codeam and house-claude', () => {
expect(textReferencesInternal('cat ~/.codeam/host-agent.json')).toBe(true);
expect(textReferencesInternal('cat ~/.codeam/house-claude/x/.claude.json')).toBe(true);
expect(textReferencesInternal('cat .codeam-host.log')).toBe(true);
// Relative mentions resolve against the session cwd: the host log is internal when the
// session runs AT home, and a same-named file in a project is the project's.
expect(textReferencesInternal('cat .codeam-host.log', HOME, HOME)).toBe(true);
expect(textReferencesInternal('cat .codeam-host.log', HOME, '/workspaces/app')).toBe(false);
expect(textReferencesInternal('cat $HOME/.codeam/host-agent.json', HOME, '/workspaces/app')).toBe(true);
expect(textReferencesInternal('cat ${HOME}/.codeam/config.json', HOME, '/workspaces/app')).toBe(true);
});
// 2026-11-23 (Antigravity on a Box): writing the PROJECT's documented Preview override was
// auto-blocked as "CodeAgent's own runtime files (~/.codeam)" — a bare ".codeam" substring match.
it("does NOT flag the project's own .codeam/ (preview override, provision)", () => {
const cwd = '/home/box/workspace/pasito';
expect(textReferencesInternal('File .codeam/preview.json', HOME, cwd)).toBe(false);
expect(textReferencesInternal('mkdir -p .codeam && cat > .codeam/preview.json', HOME, cwd)).toBe(false);
expect(textReferencesInternal(`${cwd}/.codeam/preview.json`, HOME, cwd)).toBe(false);
expect(textReferencesInternal('ls .codeam/provision/', HOME, cwd)).toBe(false);
// …while the HOME dir stays off-limits from the same cwd.
expect(textReferencesInternal('cat ~/.codeam/config.json', HOME, cwd)).toBe(true);
expect(textReferencesInternal('cat ../../.codeam/host-agent.json', HOME, cwd)).toBe(true);
});
it('a repo cloned AT home: only the documented project files under .codeam/ pass', () => {
expect(textReferencesInternal('File .codeam/preview.json', HOME, HOME)).toBe(false);
expect(textReferencesInternal('cat .codeam/provision/compose.generated.yaml', HOME, HOME)).toBe(false);
expect(textReferencesInternal('cat .codeam/config.json', HOME, HOME)).toBe(true);
expect(textReferencesInternal('cat .codeam/preview-ports.json', HOME, HOME)).toBe(true);
expect(textReferencesInternal('ls .codeam', HOME, HOME)).toBe(true);
});
it('does NOT flag the self-hosted workspace subtree (the user\'s cloned project)', () => {
// Rafael 2026-08-05: warm-codespace/self-hosted repos live at
Expand Down Expand Up @@ -59,6 +83,21 @@ describe('internal-paths — CodeAgent internals guard predicates', () => {
expect(pathIsInternal(`${HOME}/.codeam/host-agent.json`, HOME)).toBe(true);
expect(pathIsInternal(`${HOME}/.codeam/house-claude/dep/x`, HOME)).toBe(true);
});
it("does NOT flag the project's .codeam/preview.json, relative or absolute", () => {
const cwd = '/workspaces/pasito';
expect(pathIsInternal('.codeam/preview.json', HOME, cwd)).toBe(false);
expect(pathIsInternal(`${cwd}/.codeam/preview.json`, HOME, cwd)).toBe(false);
expect(pathIsInternal(`${HOME}/.codeam/config.json`, HOME, cwd)).toBe(true);
});
it('a repo cloned AT home: preview.json + provision/ pass, every other ~/.codeam file stays internal', () => {
expect(pathIsInternal('.codeam/preview.json', HOME, HOME)).toBe(false);
expect(pathIsInternal(`${HOME}/.codeam/preview.json`, HOME, HOME)).toBe(false);
expect(pathIsInternal(`${HOME}/.codeam/provision/compose.generated.yaml`, HOME, HOME)).toBe(false);
expect(pathIsInternal(`${HOME}/.codeam/preview-ports.json`, HOME, HOME)).toBe(true);
expect(pathIsInternal(`${HOME}/.codeam/host-agent.json`, HOME, HOME)).toBe(true);
// The exemption is the SESSION's project, not any repo's: from another cwd, home stays internal.
expect(pathIsInternal(`${HOME}/.codeam/preview.json`, HOME, '/workspaces/app')).toBe(true);
});
it('is not fooled by a sibling prefix (.codeam-extra)', () => {
expect(pathIsInternal(`${HOME}/.codeam-extra/x`, HOME)).toBe(false);
});
Expand All @@ -73,6 +112,21 @@ describe('internal-paths — CodeAgent internals guard predicates', () => {
it('flags via the title too', () => {
expect(toolCallReferencesInternal({ title: 'Read ~/.codeam/host-agent.json' })).toBe(true);
});
it("does not flag a write of the project's .codeam/preview.json (the 2026-11-23 Antigravity block)", () => {
const cwd = '/home/box/workspace/pasito';
expect(
toolCallReferencesInternal(
{
title: 'File .codeam/preview.json',
kind: 'edit',
rawInput: { path: '.codeam/preview.json', content: '{"framework":"Expo"}' },
locations: [{ path: `${cwd}/.codeam/preview.json` }],
},
HOME,
cwd,
),
).toBe(false);
});
it('does not flag a normal tool call', () => {
expect(
toolCallReferencesInternal({ title: 'Bash', rawInput: { command: 'npm run build' } }),
Expand Down
4 changes: 2 additions & 2 deletions apps/cli/__tests__/agents/antigravity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,13 +120,13 @@ describe.skipIf(process.platform === 'win32')('AntigravityRuntimeStrategy.genera
buildLaunch: (cmd: string, args: string[]) => ({ cmd, args }),
}) as unknown as OsStrategy;

it('runs `agy -p <prompt> --print-timeout <n>s` and returns its stdout', async () => {
it('runs `agy -p <prompt> --print-timeout <n>s` and returns its stdout (print timeout 10 s under the budget)', async () => {
// Echo argv back, one arg per line, so the test sees exactly what agy got.
const bin = fakeAgy('for a in "$@"; do echo "$a"; done');
const out = await new AntigravityRuntimeStrategy(osWith(bin)).generateOneShot('detect it', {
timeoutMs: 30_000,
});
expect(out?.split('\n')).toEqual(['-p', 'detect it', '--print-timeout', '30s']);
expect(out?.split('\n')).toEqual(['-p', 'detect it', '--print-timeout', '20s']);
});

it('returns null when agy hangs (signed out, waiting for a pasted code)', async () => {
Expand Down
210 changes: 210 additions & 0 deletions apps/cli/__tests__/preview/known-project.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/**
* Deterministic Preview detection (2026-11-23): a Remix export (Pasito, Expo SDK
* 54 + server/ + remix.json) failed on Antigravity because the agent's detect
* one-shot never answered. Projects whose start command is certain skip the
* agent; everything else (monorepos above all) keeps it.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { detectKnownProject } from '../../src/services/preview/known-project';

let dir: string;
const write = (rel: string, content: unknown): void => {
const file = path.join(dir, rel);
mkdirSync(path.dirname(file), { recursive: true });
writeFileSync(file, typeof content === 'string' ? content : JSON.stringify(content));
};

beforeEach(() => {
dir = mkdtempSync(path.join(tmpdir(), 'known-project-'));
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));

/** The package.json api-v2's `expoProjectPackageJson` exports for a MOBILE project. */
const PASITO_PKG = {
name: 'pasito',
private: true,
main: 'index.js',
scripts: { start: 'expo start', android: 'expo start --android', ios: 'expo start --ios', web: 'expo start --web' },
dependencies: { expo: '~54.0.0', react: '19.1.0', 'react-native': '0.81.4', 'react-dom': '19.1.0' },
};

describe('detectKnownProject — Remix exports', () => {
it('a MOBILE export with a server → the Expo detection the agent returns, with a server note', () => {
write('package.json', PASITO_PKG);
write('remix.json', { kind: 'MOBILE', template: 'expo-app', server: { db: true }, env: [] });
write('index.js', "import { registerRootComponent } from 'expo';");
write('server/index.ts', 'export default app;');
const got = detectKnownProject(dir);
expect(got?.kind).toBe('remix-mobile');
expect(got?.detection).toMatchObject({
framework: 'Expo',
command: 'npx',
args: ['expo', 'start'],
port: 8081,
setup_commands: [],
});
// Never --tunnel: the Expo bring-up runs our own cloudflared.
expect(got?.detection.args).not.toContain('--tunnel');
expect(got?.detection.notes).toMatch(/server/);
});

it('a MOBILE export without a server has no note', () => {
write('package.json', PASITO_PKG);
write('remix.json', { kind: 'MOBILE', template: 'expo-app' });
expect(detectKnownProject(dir)?.detection.notes).toBeUndefined();
});

it('an old MOBILE export without an expo dependency is still Expo (registerRootComponent entry)', () => {
write('package.json', { main: 'index.js', dependencies: { 'expo-status-bar': '~3.0.0' } });
write('remix.json', { template: 'unknown' });
write('index.js', "import { registerRootComponent } from 'expo';\nregisterRootComponent(App);");
expect(detectKnownProject(dir)?.kind).toBe('remix-mobile');
});

it('a WEB export (only a build script) → the vite binary on 0.0.0.0:5173', () => {
write('package.json', { scripts: { build: 'vite build' }, devDependencies: { vite: '7.1.12' } });
write('remix.json', { kind: 'WEB', template: 'vite-react' });
expect(detectKnownProject(dir)).toEqual({
kind: 'remix-web',
detection: {
framework: 'Vite',
command: 'npx',
args: ['vite', '--host', '0.0.0.0', '--port', '5173'],
port: 5173,
ready_pattern: 'Local:.*http',
env: {},
setup_commands: [],
},
});
});

it('a WEB export with a `vite` dev script runs it, keeping its port', () => {
write('package.json', { scripts: { dev: 'vite --port 3001' }, devDependencies: { vite: '7' } });
write('remix.json', { kind: 'WEB_DATA', template: 'vite-vanilla' });
const got = detectKnownProject(dir);
expect(got?.detection).toMatchObject({
command: 'npm',
args: ['run', 'dev', '--', '--host', '0.0.0.0'],
port: 3001,
});
});

it('a WEB export with no vite at all → agent', () => {
write('package.json', { scripts: { build: 'tsc' } });
write('remix.json', { kind: 'WEB' });
expect(detectKnownProject(dir)).toBeNull();
});
});

describe('detectKnownProject — plain projects', () => {
it('a plain Expo app (expo dep + app.json) → Expo', () => {
write('package.json', { scripts: { start: 'expo start' }, dependencies: { expo: '~54.0.0' } });
write('app.json', { expo: { name: 'x' } });
expect(detectKnownProject(dir)?.kind).toBe('expo');
});

it('expo without an app config → agent', () => {
write('package.json', { dependencies: { expo: '~54.0.0' } });
expect(detectKnownProject(dir)).toBeNull();
});

it('a plain Vite app with `dev: vite` → npm run dev on 0.0.0.0', () => {
write('package.json', { scripts: { dev: 'vite' }, devDependencies: { vite: '7' } });
expect(detectKnownProject(dir)).toEqual({
kind: 'vite',
detection: expect.objectContaining({
framework: 'Vite',
command: 'npm',
args: ['run', 'dev', '--', '--host', '0.0.0.0'],
port: 5173,
}),
});
});

it('keeps an explicit --host in the dev script', () => {
write('package.json', { scripts: { dev: 'vite --host' }, devDependencies: { vite: '7' } });
expect(detectKnownProject(dir)?.detection.args).toEqual(['run', 'dev']);
});

it('a dev script that is not plain vite (concurrently, next, …) → agent', () => {
write('package.json', { scripts: { dev: 'concurrently "vite" "node server.js"' }, devDependencies: { vite: '7' } });
expect(detectKnownProject(dir)).toBeNull();
write('package.json', { scripts: { dev: 'next dev' }, dependencies: { next: '15' } });
expect(detectKnownProject(dir)).toBeNull();
});

it('vite without a dev script → agent (outside a Remix export)', () => {
write('package.json', { devDependencies: { vite: '7' } });
expect(detectKnownProject(dir)).toBeNull();
});

it('no package.json, or unreadable JSON → agent', () => {
expect(detectKnownProject(dir)).toBeNull();
write('package.json', '{ not json');
expect(detectKnownProject(dir)).toBeNull();
});
});

describe('detectKnownProject — monorepos keep the agent path', () => {
it.each([
['package.json workspaces', () => write('package.json', { workspaces: ['apps/*'], scripts: { dev: 'vite' } })],
['pnpm-workspace.yaml', () => {
write('package.json', { scripts: { dev: 'vite' } });
write('pnpm-workspace.yaml', 'packages:\n - apps/*\n');
}],
['nx.json', () => {
write('package.json', { dependencies: { expo: '~54.0.0' } });
write('app.json', {});
write('nx.json', {});
}],
['turbo.json + remix.json', () => {
write('package.json', PASITO_PKG);
write('remix.json', { kind: 'MOBILE' });
write('turbo.json', {});
}],
])('%s → null', (_label, setup) => {
setup();
expect(detectKnownProject(dir)).toBeNull();
});
});

describe('resolvePreviewDetection uses it before the agent', () => {
it('returns the Expo detection without invoking the one-shot (and works on a runtime without one)', async () => {
vi.resetModules();
vi.doMock('../../src/services/pairing.service', () => ({
postLinkCredential: vi.fn().mockResolvedValue(undefined),
postAiResult: vi.fn().mockResolvedValue(undefined),
postPreviewEvent: vi.fn().mockResolvedValue({ ok: true }),
postBeadsEvent: vi.fn().mockResolvedValue(undefined),
postCliUpdateEvent: vi.fn().mockResolvedValue(undefined),
postCoderabbitEvent: vi.fn().mockResolvedValue(undefined),
postAgentReviewReport: vi.fn().mockResolvedValue(undefined),
fetchProvisionCredential: vi.fn().mockResolvedValue(undefined),
}));
const { resolvePreviewDetection } = await import('../../src/commands/start/handlers');
write('package.json', PASITO_PKG);
write('remix.json', { kind: 'MOBILE', template: 'expo-app' });
write('App.tsx', 'export default function App() { return null; }');
const cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(dir);
try {
type Runtime = Parameters<typeof resolvePreviewDetection>[0]['runtime'];
const generateOneShot = vi.fn();
for (const runtime of [{ id: 'antigravity', generateOneShot }, { id: 'aider' }]) {
const got = await resolvePreviewDetection({
ctx: { sessionId: 's', pluginId: 'p' },
runtime: runtime as unknown as Runtime,
pluginAuthToken: 't',
origin: 'agent',
});
expect(got?.framework).toBe('Expo');
}
expect(generateOneShot).not.toHaveBeenCalled();
} finally {
cwdSpy.mockRestore();
vi.doUnmock('../../src/services/pairing.service');
}
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,12 @@ describe('preview_error — el fallback de variable de entorno', () => {

await handlers.request_preview_detect!(makeCtx(), cmd, {} as never);

expect(lastErrorPayload().missingServices).toEqual([
{ service: 'postgres', envVar: 'DATABASE_URL' },
]);
// The detect runs off the dispatch loop (it reads .codeam/preview.json first): wait for it.
await vi.waitFor(() =>
expect(lastErrorPayload().missingServices).toEqual([
{ service: 'postgres', envVar: 'DATABASE_URL' },
]),
);
});

it('no adjunta nada cuando las dependencias SI estan servidas', async () => {
Expand All @@ -97,6 +100,7 @@ describe('preview_error — el fallback de variable de entorno', () => {

await handlers.request_preview_detect!(makeCtx(), cmd, {} as never);

await vi.waitFor(() => expect(lastErrorPayload()).toBeDefined());
expect(lastErrorPayload().missingServices).toBeUndefined();
});
});
Loading
Loading