diff --git a/apps/cli/__tests__/preview/missing-imports-bundle-health.test.ts b/apps/cli/__tests__/preview/missing-imports-bundle-health.test.ts new file mode 100644 index 00000000..e9efd6e9 --- /dev/null +++ b/apps/cli/__tests__/preview/missing-imports-bundle-health.test.ts @@ -0,0 +1,170 @@ +/** + * Owner's codespace, 2026-11-23: a Remix export imported `expo-clipboard` / `expo-sqlite` without + * declaring them (the players supply them), Metro answered the bundle with a 500 and the Preview + * was a white page announced as ready. The CLI now installs what the app imports, and a build + * error is a `preview_error` with Metro's text. + */ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import * as http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { + aliasPrefixes, + expoInstallCommand, + findMissingImports, + importSpecifiers, + packageOf, +} from '../../src/services/preview/missing-imports'; +import { + addPreviewGitExcludes, + bundleErrorText, + checkAppBundle, + entryScriptOf, +} from '../../src/services/preview/bundle-health'; + +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(), 'missing-imports-')); +}); +afterEach(() => rmSync(dir, { recursive: true, force: true })); + +describe('import scan', () => { + it('finds static, side-effect, dynamic and require imports, not commented ones', () => { + const src = [ + "import * as Clipboard from 'expo-clipboard';", + "import { Storage } from 'expo-sqlite/kv-store';", + "import 'react-native-gesture-handler';", + "export { x } from './local';", + "const m = await import('@scope/pkg/sub');", + "const r = require('lodash');", + "// import nope from 'commented-out';", + "/* import alsoNope from 'block-commented'; */", + "const url = 'https://example.com/x';", + ].join('\n'); + expect(importSpecifiers(src).sort()).toEqual( + ['./local', '@scope/pkg/sub', 'expo-clipboard', 'expo-sqlite/kv-store', 'lodash', 'react-native-gesture-handler'].sort(), + ); + }); + it('maps a specifier to its package, skipping relative, built-ins, aliases and invalid names', () => { + expect(packageOf('expo-sqlite/kv-store', [])).toBe('expo-sqlite'); + expect(packageOf('@react-navigation/native/lib', [])).toBe('@react-navigation/native'); + expect(packageOf('./x', [])).toBeNull(); + expect(packageOf('fs', [])).toBeNull(); + expect(packageOf('node:path', [])).toBeNull(); + expect(packageOf('@/components/Button', ['@'])).toBeNull(); + expect(packageOf('~/lib', [])).toBeNull(); // not an npm name + expect(packageOf('components/Button', ['components'])).toBeNull(); + }); + it('reads aliases from tsconfig paths (with comments) and babel module-resolver', () => { + write('tsconfig.json', '{ // comment\n "compilerOptions": { "paths": { "@app/*": ["src/*"], "ui": ["src/ui"] } }, }'); + write('babel.config.js', "module.exports = { plugins: [['module-resolver', { alias: { 'components': './src/components', '@lib': './lib' } }]] };"); + expect(aliasPrefixes(dir).sort()).toEqual(['@app', '@lib', 'components', 'ui'].sort()); + }); + it('lists packages neither declared nor installed, outside server/ and node_modules', () => { + write('package.json', { dependencies: { expo: '~54.0.0', react: '19.1.0' } }); + write('App.tsx', "import React from 'react';\nimport { Text } from 'react-native';\nimport * as C from 'expo-clipboard';"); + write('src/db.ts', "import { Storage } from 'expo-sqlite/kv-store';\nimport x from '@app/thing';"); + write('tsconfig.json', { compilerOptions: { paths: { '@app/*': ['src/*'] } } }); + write('server/index.ts', "import { Hono } from 'hono';"); + write('node_modules/react-native/package.json', { name: 'react-native' }); + write('node_modules/some-dep/index.js', "require('not-mine');"); + expect(findMissingImports(dir)).toEqual(['expo-clipboard', 'expo-sqlite']); + }); + it('installs through the project expo binary with --legacy-peer-deps', () => { + expect(expoInstallCommand(dir, ['expo-clipboard']).args).toEqual([ + '--yes', 'expo', 'install', 'expo-clipboard', '--', '--legacy-peer-deps', + ]); + write('node_modules/.bin/expo', '#!/bin/sh'); + expect(expoInstallCommand(dir, ['a', 'b'])).toEqual({ + cmd: path.join(dir, 'node_modules', '.bin', 'expo'), + args: ['install', 'a', 'b', '--', '--legacy-peer-deps'], + }); + }); +}); + +describe('bundle health', () => { + it('finds Metro bundles and Vite module entries in the page', () => { + expect(entryScriptOf('')).toBe( + '/index.bundle?platform=web&dev=true', + ); + expect( + entryScriptOf(''), + ).toBe('./src/main.tsx'); + expect(entryScriptOf('')).toBeNull(); + }); + it("reads Metro's JSON error message", () => { + const body = JSON.stringify({ + type: 'UnableToResolveError', + message: '\u001b[31mUnable to resolve module expo-clipboard from src/screens/parent/FamilyScreen.tsx\u001b[39m', + }); + expect(bundleErrorText(body)).toBe('Unable to resolve module expo-clipboard from src/screens/parent/FamilyScreen.tsx'); + }); + + const serve = (handler: http.RequestListener): Promise => + new Promise((resolve) => { + const s = http.createServer(handler); + s.listen(0, '127.0.0.1', () => resolve(s)); + }); + const portOf = (s: http.Server): number => (s.address() as AddressInfo).port; + + it('a bundle 500 is a failure with the build text; a 200 is ok', async () => { + let broken = true; + const metro = await serve((req, res) => { + if (req.url === '/') { + res.writeHead(200, { 'content-type': 'text/html' }); + res.end(''); + } else if (broken) { + res.writeHead(500, { 'content-type': 'application/json' }); + res.end(JSON.stringify({ message: 'Unable to resolve module expo-clipboard' })); + } else { + res.writeHead(200, { 'content-type': 'application/javascript' }); + res.end('var a=1'); + } + }); + try { + expect(await checkAppBundle(portOf(metro))).toEqual({ + ok: false, + status: 500, + error: 'Unable to resolve module expo-clipboard', + }); + broken = false; + expect(await checkAppBundle(portOf(metro))).toEqual({ ok: true }); + } finally { + metro.close(); + } + }); + it('a slow bundle is inconclusive, never a failure', async () => { + const metro = await serve((req, res) => { + if (req.url === '/') { + res.writeHead(200, { 'content-type': 'text/html' }); + res.end(''); + } else setTimeout(() => res.end('late'), 2_000); + }); + try { + expect((await checkAppBundle(portOf(metro), { bundleTimeoutMs: 100 })).ok).toBe('unknown'); + } finally { + metro.closeAllConnections(); + metro.close(); + } + }); +}); + +describe('git exclude', () => { + it('adds our runtime paths once, keeping what the file had', () => { + const file = path.join(dir, '.git', 'info', 'exclude'); + write('.git/info/exclude', '# git ls-files --others --exclude-from=.git/info/exclude\n*.local'); + expect(addPreviewGitExcludes(file)).toBe(true); + expect(addPreviewGitExcludes(file)).toBe(false); + expect(readFileSync(file, 'utf8')).toBe( + '# git ls-files --others --exclude-from=.git/info/exclude\n*.local\n' + + '# CodeAgent preview runtime files\n/.wrangler/\n/.codeam/*\n!/.codeam/preview.json\n', + ); + }); +}); diff --git a/apps/cli/src/services/preview/bundle-health.ts b/apps/cli/src/services/preview/bundle-health.ts new file mode 100644 index 00000000..28e26fe8 --- /dev/null +++ b/apps/cli/src/services/preview/bundle-health.ts @@ -0,0 +1,123 @@ +import { execFile } from 'child_process'; +import * as fs from 'fs'; +import * as path from 'path'; + +/** + * Does the app actually BUILD? A dev server can answer `/` with 200 while the app's own code + * can't be bundled: Metro serves the HTML shell and then answers the bundle with a 500 + * ("Unable to resolve module expo-clipboard", owner's codespace 2026-11-23), and the Preview + * showed a white page with nothing in the panel. This asks for the page the way a browser does, + * then for its entry script (Metro's `*.bundle`, Vite's module entry), and returns the build + * error's own text when there is one. + */ + +export type BundleHealth = + | { ok: true } + | { ok: false; status: number | null; error: string } + | { ok: 'unknown'; reason: string }; + +/** The app's entry script in a served HTML page: Metro's bundle, else Vite's module entry. */ +export function entryScriptOf(html: string): string | null { + const scripts = [...html.matchAll(/]*\bsrc=["']([^"']+)["'][^>]*>/gi)].map((m) => ({ + src: m[1], + tag: m[0], + })); + const bundle = scripts.find((s) => /\.bundle(?:\?|$)/.test(s.src)); + if (bundle) return bundle.src; + const mod = scripts.find((s) => /type=["']module["']/i.test(s.tag) && !s.src.includes('/@vite/client')); + return mod ? mod.src : null; +} + +const ANSI_RE = /\u001b\[[0-9;]*[A-Za-z]/g; + +/** The readable error in a failed bundle response: Metro's JSON `message`, else the text. */ +export function bundleErrorText(body: string): string { + let text = body; + try { + const parsed = JSON.parse(body) as { message?: unknown; type?: unknown }; + if (typeof parsed.message === 'string') text = parsed.message; + } catch { + /* not JSON: plain text / HTML */ + } + return text.replace(ANSI_RE, '').replace(/<[^>]+>/g, ' ').replace(/\n{3,}/g, '\n\n').trim().slice(0, 1_500); +} + +async function get( + url: string, + timeoutMs: number, + headers: Record = {}, +): Promise<{ status: number; body: string } | 'timeout' | 'error'> { + const ac = new AbortController(); + const timer = setTimeout(() => ac.abort(), timeoutMs); + try { + const res = await fetch(url, { headers, signal: ac.signal, redirect: 'follow' }); + return { status: res.status, body: await res.text() }; + } catch { + return ac.signal.aborted ? 'timeout' : 'error'; + } finally { + clearTimeout(timer); + } +} + +/** + * Page, then its entry script, on the local dev server. A first Metro build of a big app takes a + * while, so the bundle gets `bundleTimeoutMs`; running out of time is `unknown`, never a failure. + */ +export async function checkAppBundle( + port: number, + opts: { bundleTimeoutMs?: number; host?: string } = {}, +): Promise { + const origin = `http://${opts.host ?? '127.0.0.1'}:${port}`; + const page = await get(`${origin}/`, 30_000, { Accept: 'text/html' }); + if (page === 'timeout' || page === 'error') return { ok: 'unknown', reason: `page ${page}` }; + if (page.status >= 500) return { ok: false, status: page.status, error: bundleErrorText(page.body) }; + const entry = entryScriptOf(page.body); + if (!entry) return { ok: 'unknown', reason: 'no entry script in the page' }; + const url = new URL(entry, `${origin}/`); + if (url.origin !== origin) return { ok: 'unknown', reason: 'entry script on another origin' }; + const bundle = await get(url.toString(), opts.bundleTimeoutMs ?? 240_000); + if (bundle === 'timeout' || bundle === 'error') return { ok: 'unknown', reason: `bundle ${bundle}` }; + if (bundle.status >= 400) { + return { ok: false, status: bundle.status, error: bundleErrorText(bundle.body) }; + } + return { ok: true }; +} + +/** + * Keep the preview's runtime files out of the user's `git status` (the change card counted 21 + * files / +8788 lines of `.wrangler/` + `.codeam/`). Written to `.git/info/exclude` — never the + * user's `.gitignore` — and only once. A committed `.codeam/preview.json` stays visible. + */ +export const GIT_EXCLUDE_LINES = [ + '# CodeAgent preview runtime files', + '/.wrangler/', + '/.codeam/*', + '!/.codeam/preview.json', +]; + +export function addPreviewGitExcludes(excludeFile: string): boolean { + let current = ''; + try { + current = fs.readFileSync(excludeFile, 'utf8'); + } catch { + /* no exclude file yet */ + } + const have = new Set(current.split('\n').map((l) => l.trim())); + const missing = GIT_EXCLUDE_LINES.filter((l) => !have.has(l)); + if (missing.length === 0 || (missing.length === 1 && missing[0].startsWith('#'))) return false; + fs.mkdirSync(path.dirname(excludeFile), { recursive: true }); + const sep = current.length === 0 || current.endsWith('\n') ? '' : '\n'; + fs.appendFileSync(excludeFile, `${sep}${missing.join('\n')}\n`); + return true; +} + +/** `git rev-parse --git-path info/exclude` for `cwd`; null outside a git repo. */ +export function gitExcludePath(cwd: string): Promise { + return new Promise((resolve) => { + execFile('git', ['rev-parse', '--git-path', 'info/exclude'], { cwd, timeout: 5_000 }, (err, out) => { + if (err) return resolve(null); + const p = out.trim(); + resolve(p ? path.resolve(cwd, p) : null); + }); + }); +} diff --git a/apps/cli/src/services/preview/index.ts b/apps/cli/src/services/preview/index.ts index 54c9d736..8c6a30e9 100644 --- a/apps/cli/src/services/preview/index.ts +++ b/apps/cli/src/services/preview/index.ts @@ -17,6 +17,8 @@ export * from './setup-deps'; export * from './script-candidates'; export * from './known-project'; export * from './remix-app-server'; +export * from './missing-imports'; +export * from './bundle-health'; export * from './prewarm-deps'; export * from './tunnel-bringup'; export * from './port-registry'; diff --git a/apps/cli/src/services/preview/missing-imports.ts b/apps/cli/src/services/preview/missing-imports.ts new file mode 100644 index 00000000..3acd9864 --- /dev/null +++ b/apps/cli/src/services/preview/missing-imports.ts @@ -0,0 +1,177 @@ +import { execFile } from 'child_process'; +import * as fs from 'fs'; +import { builtinModules } from 'module'; +import * as path from 'path'; + +/** + * Packages an Expo app imports but neither declares nor has installed. + * + * ⚠️ WHY (2026-11-23, the owner's codespace): the Remix players SUPPLY the platform modules + * (`expo-clipboard`, `expo-sqlite`, …), so an exported repo's package.json did not declare every + * module the app imports. Metro then answered 500 "Unable to resolve module expo-clipboard" and + * the Preview showed a white page. The CLI finds them before Expo starts and installs them with + * `expo install` (SDK-compatible versions). Path aliases (tsconfig `paths`, babel + * `module-resolver`), Node built-ins and the app's own server are never installed. + */ + +const CODE_EXT = /\.(?:[cm]?[jt]sx?)$/; +const SKIP_DIRS = new Set([ + 'node_modules', + 'server', + '.git', + '.expo', + '.wrangler', + '.codeam', + '.beads', + 'dist', + 'build', + 'web-build', + 'ios', + 'android', +]); +const MAX_FILES = 5_000; +const MAX_FILE_BYTES = 1_000_000; + +const IMPORT_RES = [ + /\b(?:import|export)\s[^'"`;]*?\bfrom\s*['"]([^'"\n]+)['"]/g, + /\bimport\s*['"]([^'"\n]+)['"]/g, + /\bimport\(\s*['"]([^'"\n]+)['"]\s*\)/g, + /\brequire\(\s*['"]([^'"\n]+)['"]\s*\)/g, +]; + +/** npm's package-name rules (lowercase, optional scope). */ +const NPM_NAME_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/; + +/** Every import specifier in a source text. */ +export function importSpecifiers(source: string): string[] { + const out = new Set(); + // Drop comments so a commented-out import is not installed. + const code = source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:'"`])\/\/[^\n]*/g, '$1'); + for (const re of IMPORT_RES) for (const m of code.matchAll(re)) out.add(m[1]); + return [...out]; +} + +/** The npm package a bare specifier belongs to (`expo-sqlite/kv-store` → `expo-sqlite`), or null. */ +export function packageOf(spec: string, aliases: readonly string[]): string | null { + if (spec.startsWith('.') || spec.startsWith('/') || spec.startsWith('node:')) return null; + if (aliases.some((a) => spec === a || spec.startsWith(`${a}/`))) return null; + const parts = spec.split('/'); + const name = spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]; + if (builtinModules.includes(name)) return null; + return NPM_NAME_RE.test(name) ? name : null; +} + +function readJsonLoose(file: string): unknown { + try { + const raw = fs.readFileSync(file, 'utf8'); + try { + return JSON.parse(raw); + } catch { + // tsconfig allows comments and trailing commas. + return JSON.parse(raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:"'])\/\/.*$/gm, '$1').replace(/,(\s*[}\]])/g, '$1')); + } + } catch { + return null; + } +} + +/** Import prefixes that are aliases, not packages: tsconfig/jsconfig `paths` and babel `alias`. */ +export function aliasPrefixes(cwd: string): string[] { + const out = new Set(); + for (const f of ['tsconfig.json', 'jsconfig.json']) { + const cfg = readJsonLoose(path.join(cwd, f)) as { compilerOptions?: { paths?: Record } } | null; + for (const key of Object.keys(cfg?.compilerOptions?.paths ?? {})) { + const prefix = key.replace(/\/?\*$/, ''); + if (prefix) out.add(prefix); + } + } + for (const f of ['babel.config.js', 'babel.config.cjs', '.babelrc', '.babelrc.js', 'babel.config.json']) { + let text = ''; + try { + text = fs.readFileSync(path.join(cwd, f), 'utf8'); + } catch { + continue; + } + for (const block of text.matchAll(/alias\s*["']?\s*:\s*\{([^}]*)\}/g)) { + for (const k of block[1].matchAll(/["']?([@\w~#$./-]+)["']?\s*:/g)) { + out.add(k[1].replace(/\/?\*$/, '')); + } + } + } + return [...out]; +} + +function sourceFiles(cwd: string): string[] { + const out: string[] = []; + const walk = (dir: string): void => { + if (out.length >= MAX_FILES) return; + let entries: fs.Dirent[]; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + return; + } + for (const e of entries) { + if (out.length >= MAX_FILES) return; + const p = path.join(dir, e.name); + if (e.isDirectory()) { + if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) walk(p); + } else if (e.isFile() && CODE_EXT.test(e.name) && !e.name.endsWith('.d.ts')) { + out.push(p); + } + } + }; + walk(cwd); + return out; +} + +function declared(cwd: string): Set { + const pkg = readJsonLoose(path.join(cwd, 'package.json')) as Record | null; + const names = new Set(); + for (const k of ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies']) { + const deps = pkg?.[k]; + if (deps && typeof deps === 'object') for (const n of Object.keys(deps)) names.add(n); + } + if (typeof pkg?.name === 'string') names.add(pkg.name); + return names; +} + +/** Packages the app imports that are neither declared in package.json nor installed. */ +export function findMissingImports(cwd: string): string[] { + const aliases = aliasPrefixes(cwd); + const known = declared(cwd); + const missing = new Set(); + for (const file of sourceFiles(cwd)) { + let text: string; + try { + if (fs.statSync(file).size > MAX_FILE_BYTES) continue; + text = fs.readFileSync(file, 'utf8'); + } catch { + continue; + } + for (const spec of importSpecifiers(text)) { + const name = packageOf(spec, aliases); + if (!name || known.has(name) || missing.has(name)) continue; + if (fs.existsSync(path.join(cwd, 'node_modules', name, 'package.json'))) continue; + missing.add(name); + } + } + return [...missing].sort(); +} + +/** `expo install -- --legacy-peer-deps` through the project's own expo binary. */ +export function expoInstallCommand(cwd: string, pkgs: readonly string[]): { cmd: string; args: string[] } { + const local = path.join(cwd, 'node_modules', '.bin', 'expo'); + return fs.existsSync(local) + ? { cmd: local, args: ['install', ...pkgs, '--', '--legacy-peer-deps'] } + : { cmd: 'npx', args: ['--yes', 'expo', 'install', ...pkgs, '--', '--legacy-peer-deps'] }; +} + +/** Is `name` a real npm package? (`npm view`, bounded). An unreachable registry counts as no. */ +export function npmPackageExists(name: string, timeoutMs = 20_000): Promise { + return new Promise((resolve) => { + execFile('npm', ['view', name, 'name'], { timeout: timeoutMs }, (err, out) => { + resolve(!err && out.trim() === name); + }); + }); +} diff --git a/apps/cli/src/services/preview/start-orchestrator.ts b/apps/cli/src/services/preview/start-orchestrator.ts index d4517bb2..f3a17890 100644 --- a/apps/cli/src/services/preview/start-orchestrator.ts +++ b/apps/cli/src/services/preview/start-orchestrator.ts @@ -363,6 +363,12 @@ export async function runPreviewStart(args: PreviewStartArgs): Promise { } ctx.cwd = appDir.dir; + // Keep our runtime files (.wrangler/, .codeam/) out of the user's git status. Best-effort. + void previewSvc + .gitExcludePath(ctx.rootCwd) + .then((file) => file && previewSvc.addPreviewGitExcludes(file)) + .catch(() => undefined); + emit(USER_EVENTS.PREVIEW_STARTING, { framework: detection.framework, port: detection.port, @@ -391,6 +397,11 @@ export async function runPreviewStart(args: PreviewStartArgs): Promise { const dev = await startDevServer(ctx); if (!dev) return; + // Vite only: its entry module is a sure signal (other frameworks keep the old readiness). + if (/vite/i.test(detection.framework) && !(await appBuilds(ctx, dev.served.port, dev.served.host))) { + if (dev.devServer) previewSvc.killProcessTree(dev.devServer, 'SIGTERM'); + return; + } const fronted = await frontWithAppServer(ctx, dev); if (!fronted) return; @@ -405,6 +416,58 @@ export async function runPreviewStart(args: PreviewStartArgs): Promise { } } +/** + * Packages the app imports but neither declares nor has installed (a Remix export: the players + * supply platform modules, so its package.json may miss `expo-clipboard` & co.). Installed with + * `expo install` — SDK-compatible versions — which also records them in package.json: that is + * what makes the repo runnable. Only names that exist on npm; aliases and built-ins never. + * Best-effort: a failure leaves Metro to name the module. + */ +async function installMissingImports(ctx: StageCtx): Promise { + let missing: string[]; + try { + missing = previewSvc.findMissingImports(ctx.cwd); + } catch (err) { + log.info('preview', `import scan failed (non-fatal): ${String(err)}`); + return; + } + if (missing.length === 0) return; + const exists = await Promise.all(missing.map((n) => previewSvc.npmPackageExists(n))); + const real = missing.filter((_, i) => exists[i]); + const skipped = missing.filter((_, i) => !exists[i]); + if (skipped.length > 0) log.info('preview', `imports not on npm, not installed: ${skipped.join(', ')}`); + if (real.length === 0) return; + log.info( + 'preview', + `the app imports ${real.join(', ')} but package.json doesn't declare them — ` + + 'installing with `expo install` (this adds them to package.json)', + ); + const install = previewSvc.expoInstallCommand(ctx.cwd, real); + ctx.emitProgress('SETUP_RUN', `expo install ${real.join(' ')} (modules the app imports)`); + const r = await previewSvc.runSetupCommand(install.cmd, install.args, ctx.cwd, ctx.detection.env, { + timeoutMs: INSTALL_TIMEOUT_MS, + }); + if (r.status !== 'ok') log.info('preview', `expo install ${real.join(' ')} → ${r.status} (non-fatal)`); +} + +/** + * The page AND its entry script answer (Metro's bundle / Vite's module entry): a build error is a + * `preview_error` with the build's own text, never a white page announced as ready. Running out of + * time is not a failure (a first Metro build can be slow): the preview goes on. + */ +async function appBuilds(ctx: StageCtx, port: number, host?: string): Promise { + ctx.emitProgress('WAITING_FOR_READY', 'building the app'); + const health = await previewSvc.checkAppBundle(port, { host }); + if (health.ok === 'unknown') log.info('preview', `bundle check inconclusive: ${health.reason}`); + if (health.ok !== false) return true; + log.info('preview', `the app does not build (${health.status ?? '-'}):\n${health.error}`); + ctx.emit(USER_EVENTS.PREVIEW_ERROR, { + stage: 'spawn', + message: `Your app didn't build:\n${health.error}`, + }); + return false; +} + /** How long `wrangler dev` gets to bind its port (workerd's first start included). */ const APP_SERVER_READY_TIMEOUT_MS = 90_000; @@ -523,6 +586,8 @@ async function frontWithAppServer(ctx: StageCtx, dev: DevServerUp): Promise { const { detection, emit, emitProgress } = ctx; + await installMissingImports(ctx); + // The WEB preview (owner 2026-10-31): Metro serves the app to a browser once `react-dom` // resolves from the project, so the web packages are installed first (`--no-save`, the // project's package.json is the user's). Best-effort: without them the preview is the Expo Go @@ -583,6 +648,12 @@ async function runExpoBringUp(ctx: StageCtx): Promise { return; } + if (web && !(await appBuilds(ctx, detection.port))) { + if (dev.devServer) previewSvc.killProcessTree(dev.devServer, 'SIGTERM'); + killQuiet(pub.tunnel); + return; + } + const expoGoUrl = previewSvc.expoGoDeepLink(pub.url); announceReady(ctx, dev, { // The web build in the frame + Expo Go beside it; an SDK without web deps keeps the QR alone. diff --git a/apps/cli/src/services/turn-files/review-ignore.ts b/apps/cli/src/services/turn-files/review-ignore.ts index 5c420c86..147f2c98 100644 --- a/apps/cli/src/services/turn-files/review-ignore.ts +++ b/apps/cli/src/services/turn-files/review-ignore.ts @@ -56,6 +56,8 @@ const CURATED_REVIEW_IGNORE: readonly string[] = [ // CodeAgent's own runtime prefixes (never a user change). '.codeam/', 'codeam-node20/', + // A Remix app server's local runtime state (wrangler dev / miniflare D1). + '.wrangler/', // Beads (issue tracker + agent memory) and its Dolt store — our tooling's // state, written on every bd op; it showed up as `.beads/issues.jsonl` in // the user's review (break-it 2026-09-26).