From e6f00cbf88b93805e7699336f6fcfb23ed603a1c Mon Sep 17 00:00:00 2001 From: Edgar Durand Date: Mon, 23 Nov 2026 16:40:08 -0300 Subject: [PATCH] fix(cli): open Remix/Expo/Vite previews without the agent, unblock project .codeam/ - Preview detection: after .codeam/preview.json and BEFORE the agent one-shot (and before the generateOneShot availability check), detectKnownProject answers projects whose start command is certain: a Remix export (root remix.json; MOBILE -> the Expo detection, WEB -> Vite), a plain single-package Expo app or a Vite app whose dev script is `vite`. Monorepos keep the agent. The debug log names the path (preview.json | deterministic | agent) and a timed-out one-shot now logs the agent's stderr tail. The prewarm no longer bills a one-shot for these projects. (2026-11-23: a Remix Expo export on a Box with Antigravity never got an answer from `agy -p` in 120 s.) - Antigravity one-shot: --print-timeout ends 10 s before the caller's budget so agy's own timeout (partial answer + reason) lands before the Preview deadline. - ACP internals guard: a `.codeam` mention is resolved against the session cwd and blocked only under the HOME ~/.codeam; a repo cloned AT home still gets .codeam/preview.json and .codeam/provision/. Writing the project's own .codeam/preview.json was auto-blocked as "CodeAgent's own runtime files". Co-Authored-By: Claude Opus 5.5 --- .../agents/acp/internal-paths.test.ts | 56 ++++- apps/cli/__tests__/agents/antigravity.test.ts | 4 +- .../__tests__/preview/known-project.test.ts | 210 ++++++++++++++++++ .../preview-error-missing-services.test.ts | 10 +- apps/cli/src/agents/acp/internal-paths.ts | 132 +++++++---- apps/cli/src/agents/antigravity/runtime.ts | 12 +- apps/cli/src/commands/start/handlers.ts | 47 +++- apps/cli/src/services/preview/index.ts | 1 + .../cli/src/services/preview/known-project.ts | 174 +++++++++++++++ 9 files changed, 587 insertions(+), 59 deletions(-) create mode 100644 apps/cli/__tests__/preview/known-project.test.ts create mode 100644 apps/cli/src/services/preview/known-project.ts diff --git a/apps/cli/__tests__/agents/acp/internal-paths.test.ts b/apps/cli/__tests__/agents/acp/internal-paths.test.ts index 40c1fb19..36435962 100644 --- a/apps/cli/__tests__/agents/acp/internal-paths.test.ts +++ b/apps/cli/__tests__/agents/acp/internal-paths.test.ts @@ -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 @@ -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); }); @@ -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' } }), diff --git a/apps/cli/__tests__/agents/antigravity.test.ts b/apps/cli/__tests__/agents/antigravity.test.ts index 9ff82514..9f6972cd 100644 --- a/apps/cli/__tests__/agents/antigravity.test.ts +++ b/apps/cli/__tests__/agents/antigravity.test.ts @@ -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 --print-timeout s` and returns its stdout', async () => { + it('runs `agy -p --print-timeout 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 () => { diff --git a/apps/cli/__tests__/preview/known-project.test.ts b/apps/cli/__tests__/preview/known-project.test.ts new file mode 100644 index 00000000..b431fc99 --- /dev/null +++ b/apps/cli/__tests__/preview/known-project.test.ts @@ -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[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'); + } + }); +}); diff --git a/apps/cli/__tests__/preview/preview-error-missing-services.test.ts b/apps/cli/__tests__/preview/preview-error-missing-services.test.ts index 359d8ff6..5639a4fb 100644 --- a/apps/cli/__tests__/preview/preview-error-missing-services.test.ts +++ b/apps/cli/__tests__/preview/preview-error-missing-services.test.ts @@ -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 () => { @@ -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(); }); }); diff --git a/apps/cli/src/agents/acp/internal-paths.ts b/apps/cli/src/agents/acp/internal-paths.ts index b10293d7..3dd0e3bf 100644 --- a/apps/cli/src/agents/acp/internal-paths.ts +++ b/apps/cli/src/agents/acp/internal-paths.ts @@ -36,15 +36,36 @@ import * as os from 'node:os'; */ /** - * Substring tokens that unambiguously denote CodeAgent platform internals, for - * matching against arbitrary tool input (a bash command string, a Read path, - * a glob). `.codeam` matches `~/.codeam/**` and `.codeam-host.log` but NOT - * `/tmp/codeam-node20` (no leading dot); `bd` commands (`bd ready`, - * `bd remember …`) never contain `.codeam`, so beads keeps working. We - * deliberately do NOT match a bare `.beads` here — a project's own `./.beads` - * is legitimate; the home `~/.beads` is caught by {@link pathIsInternal}. + * `house-claude` never names a user's file, so any mention of it is internal. + * `.codeam` is different: it is BOTH our home runtime dir (`~/.codeam`) AND the + * documented PROJECT override dir (`/.codeam/preview.json`, + * `/.codeam/provision/`). A bare substring match blocked an agent writing + * its own project's `.codeam/preview.json` (Antigravity, 2026-11-23), so every + * `.codeam` mention is resolved to a path (against the session cwd) and judged + * by {@link pathIsInternal}, which is anchored at the HOME dir. We deliberately + * do NOT match a bare `.beads` here — a project's own `./.beads` is legitimate; + * the home `~/.beads` is caught by {@link pathIsInternal}. */ -const INTERNAL_TOKENS = ['.codeam', 'house-claude']; +const ALWAYS_INTERNAL_TOKEN = 'house-claude'; + +/** Characters that end a path inside a shell command / tool title. */ +const PATH_DELIMS = /[\s'"`;|&<>()=,\[\]]/; + +/** The path-like token around `text[index]`. */ +function tokenAt(text: string, index: number): string { + let a = index; + while (a > 0 && !PATH_DELIMS.test(text[a - 1])) a--; + let b = index; + while (b < text.length && !PATH_DELIMS.test(text[b])) b++; + return text.slice(a, b); +} + +/** A token as an absolute path: `~`/`$HOME` → home, relative → the session cwd. */ +function resolveToken(token: string, homeDir: string, cwd: string): string { + const home = token.match(/^(?:~|\$HOME|\$\{HOME\})(?=$|[/\\])/); + if (home) return path.join(homeDir, token.slice(home[0].length)); + return path.resolve(cwd, token); +} /** * ACP ToolKinds whose `rawInput`/`title` carry free-form PROSE ABOUT the work — @@ -66,38 +87,74 @@ export function isProseOnlyToolKind(kind: string | null | undefined): boolean { } /** - * The per-deploy WORKSPACE lives at `~/.codeam/self-hosted//` — that - * subtree is the USER's cloned project (a warm codespace / self-hosted box - * clones repos there), NOT a CodeAgent internal. Its path literally contains - * `.codeam`, so the naive `.codeam` substring token would false-flag EVERY tool - * call whose cwd/paths sit inside the workspace. ⚠️ Rafael, 2026-08-05: in a warm - * codespace, every `git commit` / edit / read was denied in MANUAL permission - * mode (in AUTO the agent uses `bypassPermissions` and never asks the client, so - * the guard never ran — hence "manual denies, auto works"). Neutralize the - * self-hosted workspace prefix before the internal-token scan. + * True if arbitrary text (bash command, tool title, a tool-input string) + * references an internal path. Each `.codeam` occurrence is resolved to the + * path it sits in — `~/…` and `$HOME/…` against the home dir, a relative one + * against the session cwd — so `cat ~/.codeam/host-agent.json` is internal and + * `.codeam/preview.json` in a project is not. The per-deploy workspace at + * `~/.codeam/self-hosted//` is the USER's cloned repo (⚠️ Rafael, + * 2026-08-05: every git commit/edit there was denied in MANUAL mode); it is + * exempted by {@link pathIsInternal}. */ -const SELF_HOSTED_WORKSPACE_RE = /\.codeam[/\\]self-hosted/gi; - -/** True if arbitrary text (bash command, serialized tool input) references an internal path. */ -export function textReferencesInternal(text: string | null | undefined): boolean { +export function textReferencesInternal( + text: string | null | undefined, + homeDir: string = os.homedir(), + cwd: string = process.cwd(), +): boolean { if (!text) return false; - const scrubbed = text.replace(SELF_HOSTED_WORKSPACE_RE, ' '); - return INTERNAL_TOKENS.some((t) => scrubbed.includes(t)); + if (text.includes(ALWAYS_INTERNAL_TOKEN)) return true; + for (let i = text.indexOf('.codeam'); i !== -1; i = text.indexOf('.codeam', i + 1)) { + if (pathIsInternal(resolveToken(tokenAt(text, i), homeDir, cwd), homeDir, cwd)) return true; + } + return false; +} + +/** Every string inside a tool's `rawInput`, so paths are scanned as written (not JSON-escaped). */ +function stringsIn(v: unknown, out: string[] = [], depth = 0): string[] { + if (depth > 8) return out; + if (typeof v === 'string') out.push(v); + else if (Array.isArray(v)) for (const x of v) stringsIn(x, out, depth + 1); + else if (v && typeof v === 'object') for (const x of Object.values(v)) stringsIn(x, out, depth + 1); + return out; } /** - * Precise absolute-path check for the fs read/write seam: within `~/.codeam`, - * `~/.beads`, `~/.codeam-host.log`, or any `house-claude` directory. + * The project files under `/.codeam/` the docs tell an agent (and a team) + * to write: the Preview override and the generated service compose. Only these + * matter when the repo IS the home dir (`/.codeam` === `~/.codeam`); + * anywhere else a project's `.codeam/` is outside `~/.codeam` anyway. */ -export function pathIsInternal(p: string | null | undefined, homeDir: string = os.homedir()): boolean { +function isProjectOverride(abs: string, cwd: string): boolean { + const dir = path.join(path.resolve(cwd), '.codeam'); + const provision = path.join(dir, 'provision'); + return ( + abs === path.join(dir, 'preview.json') || + abs === provision || + abs.startsWith(provision + path.sep) + ); +} + +/** + * Precise path check for the fs read/write seam: within `~/.codeam`, + * `~/.beads`, `~/.codeam-host.log`, or any `house-claude` directory. A + * relative path resolves against the session cwd; the project's own + * `.codeam/preview.json` / `.codeam/provision/` never count, even in a repo + * cloned AT the home dir. + */ +export function pathIsInternal( + p: string | null | undefined, + homeDir: string = os.homedir(), + cwd: string = process.cwd(), +): boolean { if (!p) return false; - const abs = path.resolve(p); + const abs = path.resolve(cwd, p); const home = path.resolve(homeDir); const within = (root: string) => abs === root || abs.startsWith(root + path.sep); // The user's cloned project lives under ~/.codeam/self-hosted// — it - // is NOT an internal (see SELF_HOSTED_WORKSPACE_RE). Must be checked BEFORE the + // is NOT an internal (see textReferencesInternal). Must be checked BEFORE the // ~/.codeam catch-all below, which would otherwise swallow the whole workspace. if (within(path.join(home, '.codeam', 'self-hosted'))) return false; + if (isProjectOverride(abs, cwd)) return false; return ( within(path.join(home, '.codeam')) || within(path.join(home, '.beads')) || @@ -124,21 +181,15 @@ export function toolCallReferencesInternal( rawInput?: unknown; locations?: ReadonlyArray<{ path: string }> | null; }, - homeDir?: string, + homeDir: string = os.homedir(), + cwd: string = process.cwd(), ): boolean { // Structured path field — authoritative for EVERY kind, prose ones included. - if (call.locations?.some((l) => pathIsInternal(l.path, homeDir))) return true; + if (call.locations?.some((l) => pathIsInternal(l.path, homeDir, cwd))) return true; // Free-text scan only for kinds whose input IS a path/command. if (isProseOnlyToolKind(call.kind)) return false; - if (textReferencesInternal(call.title)) return true; - if (call.rawInput != null) { - try { - return textReferencesInternal(JSON.stringify(call.rawInput)); - } catch { - return false; - } - } - return false; + if (textReferencesInternal(call.title, homeDir, cwd)) return true; + return stringsIn(call.rawInput).some((t) => textReferencesInternal(t, homeDir, cwd)); } /** @@ -160,10 +211,11 @@ export function internalPathPermissionOutcome( options: ReadonlyArray<{ optionId: string; kind: string }>; }, homeDir?: string, + cwd?: string, ): | { outcome: { outcome: 'selected'; optionId: string } | { outcome: 'cancelled' } } | null { - if (!toolCallReferencesInternal(request.toolCall, homeDir)) return null; + if (!toolCallReferencesInternal(request.toolCall, homeDir, cwd)) return null; // Prefer reject_ONCE: the guard re-evaluates every call anyway, and a // `reject_always` permanently poisons the tool for the whole session (the // 2026-08-19 plan-mode wedge). One blocked call must never disable a tool. diff --git a/apps/cli/src/agents/antigravity/runtime.ts b/apps/cli/src/agents/antigravity/runtime.ts index 5d5fefa0..d3d83913 100644 --- a/apps/cli/src/agents/antigravity/runtime.ts +++ b/apps/cli/src/agents/antigravity/runtime.ts @@ -46,6 +46,14 @@ import { ANTIGRAVITY_INSTALL_URL, ensureAntigravityInstalled } from './installer const DEFAULT_ONE_SHOT_TIMEOUT_MS = 120_000; /** Kill grace past agy's own `--print-timeout`, so agy normally exits on its own. */ const ONE_SHOT_KILL_GRACE_MS = 5_000; +/** + * agy's `--print-timeout` ends this much BEFORE the caller's budget. Preview + * detection races the one-shot against the SAME 120 s it passes as + * `timeoutMs`, so with `--print-timeout` equal to it agy's own timeout (which + * prints the partial answer and why) could never land before the caller gave + * up — the 2026-11-23 "agent did not answer" showed nothing of what agy did. + */ +const PRINT_TIMEOUT_HEADROOM_MS = 10_000; export class AntigravityRuntimeStrategy implements RuntimeStrategy { readonly id: AgentId = 'antigravity'; @@ -144,7 +152,9 @@ export class AntigravityRuntimeStrategy implements RuntimeStrategy { const binary = this.os.findInPath('agy'); if (!binary) return null; const timeoutMs = opts?.timeoutMs ?? DEFAULT_ONE_SHOT_TIMEOUT_MS; - const printTimeoutSec = Math.max(1, Math.floor(timeoutMs / 1000)); + const printBudgetMs = + timeoutMs > PRINT_TIMEOUT_HEADROOM_MS * 2 ? timeoutMs - PRINT_TIMEOUT_HEADROOM_MS : timeoutMs; + const printTimeoutSec = Math.max(1, Math.floor(printBudgetMs / 1000)); const launch = this.os.buildLaunch(binary, [ '-p', prompt, diff --git a/apps/cli/src/commands/start/handlers.ts b/apps/cli/src/commands/start/handlers.ts index 20fbc6bc..1482c816 100644 --- a/apps/cli/src/commands/start/handlers.ts +++ b/apps/cli/src/commands/start/handlers.ts @@ -100,6 +100,7 @@ import { isUnsupportedDetection, describeDetectionFailure, listScriptCandidates, + detectKnownProject, prewarmNodeDeps, describeOneShotAgentError, looksLikeManagedCreditsExhausted, @@ -1963,7 +1964,9 @@ export function originPayload( export type PreviewCtx = Pick; /** - * Resolve HOW to start this project: `.codeam/preview.json` first, else the + * Resolve HOW to start this project: `.codeam/preview.json` first, then a + * deterministic detection for projects whose command is certain + * (`detectKnownProject`: Remix exports, plain Expo / Vite apps), else the * agent's headless one-shot. Emits `preview_detection_pending` and every * `preview_error` itself; returns the detection (never `unsupported`) or null * once the error has been reported. The caller decides what a success means — @@ -2013,6 +2016,28 @@ export async function resolvePreviewDetection(args: { }); return null; } + // `.codeam/preview.json` short-circuits the agent step entirely + // when a repo has been pinned. Saves the user 30-90 s + the LLM + // tokens, and lets a team commit the override so every dev gets + // an instant preview on first try. + const fromFile = await readPreviewConfig(process.cwd()); + if (fromFile) { + log.info('preview', `detect: path=preview.json (${fromFile.framework})`); + return fromFile; + } + // A project whose start command is certain (a Remix export, a plain Expo or + // Vite app) needs no LLM — and works on agents without a one-shot too. The + // Antigravity one-shot that never answered for a Remix Expo export + // (2026-11-23) is why this runs BEFORE the agent. Not persisted: it is + // instant, and a pinned copy would stop tracking the project's own scripts. + const known = detectKnownProject(process.cwd()); + if (known) { + log.info( + 'preview', + `detect: path=deterministic kind=${known.kind} (${known.detection.framework} on :${known.detection.port})`, + ); + return known.detection; + } if (typeof runtime.generateOneShot !== 'function') { log.info('preview', `runtime ${runtime.id} has no generateOneShot — emitting unsupported`); emitError({ @@ -2023,23 +2048,20 @@ export async function resolvePreviewDetection(args: { return null; } const generateOneShot = runtime.generateOneShot.bind(runtime); - // `.codeam/preview.json` short-circuits the agent step entirely - // when a repo has been pinned. Saves the user 30-90 s + the LLM - // tokens, and lets a team commit the override so every dev gets - // an instant preview on first try. - const fromFile = await readPreviewConfig(process.cwd()); - if (fromFile) { - log.info('preview', `detect: using .codeam/preview.json (${fromFile.framework})`); - return fromFile; - } emit(USER_EVENTS.PREVIEW_DETECTION_PENDING); - log.info('preview', 'detect: invoking generateOneShot'); + log.info('preview', `detect: path=agent (${runtime.id} one-shot)`); const startedAt = Date.now(); const { raw, timedOut, stderr } = await runDetectOneShot(generateOneShot); const tookMs = Date.now() - startedAt; if (timedOut) { - log.info('preview', `detect: timed out after ${tookMs}ms — emitting preview_error`); + // What the agent said before the deadline is the only clue to WHY it never + // answered (Antigravity, 2026-11-23: nothing was logged). Bounded tail. + log.info( + 'preview', + `detect: timed out after ${tookMs}ms — emitting preview_error` + + (stderr.trim() ? `\n--- agent stderr (tail) ---\n${stderr.slice(-1_500)}` : ' (agent printed nothing)'), + ); emitError({ stage: 'detection', reason: 'timeout', @@ -2252,6 +2274,7 @@ export function prewarmPreviewDetection(runtime: RuntimeStrategy): void { try { const cwd = process.cwd(); if (await readPreviewConfig(cwd)) return; // already pinned/cached — nothing to do + if (detectKnownProject(cwd)) return; // certain without the agent — never bill a one-shot // Same gate as the on-demand detect: an untouched scratch project has // nothing to serve. The prewarm fires 20 s after pairing, when a scratch // workspace is ALWAYS still empty, and the one-shot bills a credits user's diff --git a/apps/cli/src/services/preview/index.ts b/apps/cli/src/services/preview/index.ts index 1316d562..d38b00af 100644 --- a/apps/cli/src/services/preview/index.ts +++ b/apps/cli/src/services/preview/index.ts @@ -15,6 +15,7 @@ export * from './provision-deps'; export * from './run-setup'; export * from './setup-deps'; export * from './script-candidates'; +export * from './known-project'; export * from './prewarm-deps'; export * from './tunnel-bringup'; export * from './port-registry'; diff --git a/apps/cli/src/services/preview/known-project.ts b/apps/cli/src/services/preview/known-project.ts new file mode 100644 index 00000000..ee4d1ec5 --- /dev/null +++ b/apps/cli/src/services/preview/known-project.ts @@ -0,0 +1,174 @@ +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import type { PreviewDetection } from '@codeam/shared'; + +/** + * Projects whose start command is CERTAIN without asking the agent — the + * Preview's deterministic detection, tried after `.codeam/preview.json` and + * before the agent's headless one-shot. + * + * ⚠️ WHY (2026-11-23): the owner's Remix export "Pasito" (Expo SDK 54 + a + * `server/` + a root `remix.json`), opened on a Box with Antigravity: the + * agent's detect one-shot never answered in 120 s, so the Preview failed and the + * agent ran `npx expo start --web` in its own bash, which the Preview pane never + * sees. A Remix export is OUR file layout (`remix-export-files.ts` in api-v2): + * nothing about how to start it needs an LLM, and every agent (including one + * without `generateOneShot`) gets the same instant answer. + * + * Covered: + * - a Remix export (root `remix.json`): MOBILE → Expo, WEB/WEB_DATA → Vite; + * - a plain single-package Expo app (an `expo` dependency + `app.json` / + * `app.config.*`); + * - a plain single-package Vite app whose `dev` script is `vite …`. + * Anything else — monorepos above all — keeps the agent path. + */ + +export type KnownProjectKind = 'remix-mobile' | 'remix-web' | 'expo' | 'vite'; + +export interface KnownProjectDetection { + kind: KnownProjectKind; + detection: PreviewDetection; +} + +type Pkg = { + main?: unknown; + scripts?: Record; + dependencies?: Record; + devDependencies?: Record; + workspaces?: unknown; +}; + +type RemixConfig = { kind?: unknown; template?: unknown; server?: unknown }; + +/** The detect prompt's Expo shape, minus `--tunnel` (the Expo bring-up runs OUR tunnel). */ +const EXPO_DETECTION: Omit = { + framework: 'Expo', + command: 'npx', + args: ['expo', 'start'], + port: 8081, + ready_pattern: 'Waiting on http|Metro waiting|Logs for your project', + env: {}, + setup_commands: [], +}; + +const VITE_PORT = 5173; +const VITE_READY = 'Local:.*http'; + +/** Monorepo markers: a workspace root needs the agent to pick the app. */ +const MONOREPO_FILES = ['pnpm-workspace.yaml', 'lerna.json', 'nx.json', 'turbo.json', 'rush.json']; + +function readJson(file: string): T | null { + try { + const v: unknown = JSON.parse(fs.readFileSync(file, 'utf8')); + return v && typeof v === 'object' && !Array.isArray(v) ? (v as T) : null; + } catch { + return null; + } +} + +function deps(pkg: Pkg): Record { + return { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) }; +} + +function script(pkg: Pkg, name: string): string | null { + const s = pkg.scripts?.[name]; + return typeof s === 'string' && s.trim() ? s.trim() : null; +} + +function isMonorepo(cwd: string, pkg: Pkg): boolean { + if (pkg.workspaces !== undefined) return true; + return MONOREPO_FILES.some((f) => fs.existsSync(path.join(cwd, f))); +} + +/** An Expo app: an `expo` dependency, or the Remix entry (`main` → a file that calls `registerRootComponent`). */ +function isExpoApp(cwd: string, pkg: Pkg): boolean { + if ('expo' in deps(pkg)) return true; + if (typeof pkg.main !== 'string') return false; + try { + const entry = path.resolve(cwd, pkg.main); + if (!entry.startsWith(path.resolve(cwd) + path.sep)) return false; + return /\bregisterRootComponent\s*\(/.test(fs.readFileSync(entry, 'utf8')); + } catch { + return false; + } +} + +/** `--port N` / `--port=N` in a script body, else the default. */ +function portIn(body: string, fallback: number): number { + const m = /--port(?:=|\s+)(\d{2,5})\b/.exec(body); + const n = m ? Number(m[1]) : NaN; + return Number.isInteger(n) && n > 0 && n < 65536 ? n : fallback; +} + +/** + * Vite from its `dev` script when it is a bare `vite …` call (args after `--` + * reach Vite: bind every interface so the tunnel reaches it whatever + * `localhost` resolves to), else the `vite` binary directly. `null` when the + * project has neither. + */ +function viteDetection(pkg: Pkg): PreviewDetection | null { + const dev = script(pkg, 'dev'); + if (dev && /^vite(\s|$)/.test(dev)) { + const extra = /(^|\s)--host\b/.test(dev) ? [] : ['--', '--host', '0.0.0.0']; + return { + framework: 'Vite', + command: 'npm', + args: ['run', 'dev', ...extra], + port: portIn(dev, VITE_PORT), + ready_pattern: VITE_READY, + env: {}, + setup_commands: [], + }; + } + if (dev) return null; // a dev script that isn't plain vite: the agent knows better + if (!('vite' in deps(pkg))) return null; + // Remix WEB templates declare only `build: vite build` — no dev script. + return { + framework: 'Vite', + command: 'npx', + args: ['vite', '--host', '0.0.0.0', '--port', String(VITE_PORT)], + port: VITE_PORT, + ready_pattern: VITE_READY, + env: {}, + setup_commands: [], + }; +} + +/** + * The app's own server (`server/`, remix.json "server") is a Hono app for + * Cloudflare Workers + D1 that the Remix platform deploys; the client reaches + * it through `__REMIX_SERVER_BASE__`, which only the Remix players inject. The + * Preview brings up the CLIENT; say so instead of letting calls fail silently. + */ +const REMIX_SERVER_NOTE = + "The app's server (server/) runs on Cloudflare Workers once the app is published on Remix; " + + "the preview doesn't start it, so screens that call it show their error state here."; + +function remixDetection(cwd: string, pkg: Pkg, remix: RemixConfig): KnownProjectDetection | null { + const hasServer = + (remix.server !== undefined && remix.server !== null) || + fs.existsSync(path.join(cwd, 'server', 'index.ts')); + const notes = hasServer ? { notes: REMIX_SERVER_NOTE } : {}; + const mobile = remix.kind === 'MOBILE' || remix.template === 'expo-app' || isExpoApp(cwd, pkg); + if (mobile) return { kind: 'remix-mobile', detection: { ...EXPO_DETECTION, ...notes } }; + const vite = viteDetection(pkg); + return vite ? { kind: 'remix-web', detection: { ...vite, ...notes } } : null; +} + +/** The deterministic detection for `cwd`, or `null` when the agent should decide. */ +export function detectKnownProject(cwd: string): KnownProjectDetection | null { + const pkg = readJson(path.join(cwd, 'package.json')); + if (!pkg || isMonorepo(cwd, pkg)) return null; + const remix = readJson(path.join(cwd, 'remix.json')); + if (remix) return remixDetection(cwd, pkg, remix); + if ('expo' in deps(pkg)) { + const hasConfig = ['app.json', 'app.config.js', 'app.config.ts'].some((f) => + fs.existsSync(path.join(cwd, f)), + ); + return hasConfig ? { kind: 'expo', detection: { ...EXPO_DETECTION } } : null; + } + // A plain Vite app only when `dev` is unambiguous (`vite …`); no dev script → agent. + if (!script(pkg, 'dev')) return null; + const vite = viteDetection(pkg); + return vite ? { kind: 'vite', detection: vite } : null; +}