diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7722692d..f2ef5f7c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -100,6 +100,7 @@ jobs: npm run build:release npm run package:release npm run package:claude -- --release + npm run package:antigravity -- --release - name: Validate the extracted release ZIP env: @@ -119,6 +120,14 @@ jobs: unzip -q "release/mobile-dev-$RELEASE_VERSION-claude-plugin-darwin-arm64.zip" -d "$RUNNER_TEMP/mobile-dev-claude" npm run test:claude -- "$RUNNER_TEMP/mobile-dev-claude" + - name: Validate the extracted Antigravity package + env: + RELEASE_VERSION: ${{ steps.release.outputs.version }} + run: | + mkdir "$RUNNER_TEMP/mobile-dev-antigravity" + unzip -q "release/mobile-dev-$RELEASE_VERSION-antigravity-plugin-darwin-arm64.zip" -d "$RUNNER_TEMP/mobile-dev-antigravity" + npm run test:antigravity -- "$RUNNER_TEMP/mobile-dev-antigravity" + - name: Upload Sentry source maps and native symbols env: SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }} @@ -251,6 +260,10 @@ jobs: branch: claude package: claude-plugin-darwin-arm64.zip script: apps/claude/tooling/publish-release.mjs + - host: antigravity + branch: antigravity + package: antigravity-plugin-darwin-arm64.zip + script: apps/antigravity/tooling/publish-release.mjs concurrency: group: release-${{ matrix.branch }} cancel-in-progress: false diff --git a/README.md b/README.md index f87d2268..325590f9 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,20 @@ It sends plugin errors and aggregate measurements to Sentry, as described under [Privacy and support](#privacy-and-support), and nothing else to Callstack; profiles go only to the TraceSift service on your Mac. +### Antigravity + +On an Apple Silicon Mac with Node.js 22.19 or later, install the Antigravity extension +from this repository's `release/antigravity` branch with the `agy` CLI: + +```sh +agy plugin install https://github.com/callstackincubator/mobile-dev/tree/release/antigravity/mobile-dev +``` + +Mobile Dev renders its live device panel, logs, storage, App Intelligence, and +performance tools directly inside the Antigravity Auxiliary Pane beside the chat, and +downloads the pinned panel runtime once on first open. Ask the agent to open Mobile Dev +or click the **Mobile Dev** icon in the Auxiliary Pane. + ### T3 Code [T3 Code](https://github.com/pingdotgg/t3code) runs Claude Code and Codex, so it loads @@ -254,6 +268,7 @@ product in `apps/`: | `packages/native`, `packages/runtimes` | Native helpers and bundled Node runtimes | | `apps/codex-plugin` | The Codex plugin: manifest, updater, and update banner | | `apps/claude` | Claude: its server, which downloads the panel's runtime, skill, and the Claude Desktop extension and Claude Code plugin manifests | +| `apps/antigravity` | Antigravity: its server, Auxiliary Pane sidecar proxy, skill, and extension manifest | | `apps/cursor` | Cursor: the Cursor plugin manifest | | `apps/mac` | The Mac app: SwiftUI window and its page | diff --git a/apps/antigravity/.antigravity-plugin/plugin.json b/apps/antigravity/.antigravity-plugin/plugin.json new file mode 100644 index 00000000..a0eef594 --- /dev/null +++ b/apps/antigravity/.antigravity-plugin/plugin.json @@ -0,0 +1,31 @@ +{ + "name": "mobile-dev", + "displayName": "Mobile Dev", + "description": "Stream iOS and Android devices beside your chat while building, running, or debugging mobile apps. Includes device control (agent-device), native and Metro logs, app storage inspection, and CPU, memory, and FPS performance profiling.", + "logo": "assets/icon.png", + "suggestedPrompts": [ + "Open the iOS simulator or Android emulator beside this chat", + "Read the mobile app logs and help me fix the current error", + "Record CPU, memory, and FPS while I interact with the app" + ], + "author": { + "name": "Callstack", + "email": "hello@callstack.com", + "url": "https://www.callstack.com/" + }, + "homepage": "https://github.com/callstackincubator/codex-mobile-dev-plugin", + "repository": "https://github.com/callstackincubator/codex-mobile-dev-plugin", + "license": "MIT", + "keywords": [ + "mobile", + "ios", + "android", + "react-native", + "expo", + "simulator", + "emulator", + "profiling", + "performance", + "logs" + ] +} diff --git a/apps/antigravity/README.md b/apps/antigravity/README.md new file mode 100644 index 00000000..12bd26a2 --- /dev/null +++ b/apps/antigravity/README.md @@ -0,0 +1,98 @@ +# Mobile Dev for Antigravity + +Build, run, and debug iOS and Android apps without leaving Antigravity. Mobile Dev +streams your simulators, emulators, and devices into an Antigravity Auxiliary Pane +(`sidecar://mobile-dev/device-panel/`) beside the chat, and gives Antigravity the tools +to control them, read their logs, inspect your app, and measure its performance. It +works with Expo, React Native, SwiftUI, and other native mobile projects. + +- **Auxiliary Pane device panel:** a live, interactive iOS simulator, Android + emulator, or connected device in the Antigravity side pane, with logs, storage, App + Intelligence, and performance tools beside it. Antigravity reads the devices you + select there and the logs, screenshots, and notes you add to chat. +- **Device control and inspection:** Antigravity taps, types, scrolls, reads the + accessibility tree, and takes screenshots through the bundled + [agent-device](https://agent-device.dev/) runtime. +- **App control:** install, launch, and stop apps, open deep links, send test pushes, + and set permissions and languages. +- **App Flow:** a visual map of your app's screens and the navigation between them, + read from your Expo Router or React Navigation source and optionally captured by + walking the app on an iOS simulator. +- **App Intelligence:** static screen-to-dependency graphs for Expo Router and React + Navigation projects, tracing each screen through its source files, assets, and + packages without building or running the app. +- **Testing Studio:** record deterministic e2e tests against a booted iOS simulator or Android emulator, with live TypeScript preview and editable steps beside the mirror. +- **Logs:** iOS unified logs, Android logcat, physical iPhone logs, and Metro console + messages. +- **Performance:** CPU, memory, and FPS recordings shown as interactive charts, which + Antigravity can analyze and compare. +- **App storage:** read what your app saved, such as UserDefaults, SharedPreferences, + AsyncStorage, MMKV, and SQLite, without adding code to it. +- **Profile analysis:** TraceSift findings for local CPU and React profiles. + +## Install + +Install directly from the `release/antigravity` branch with the `agy` CLI: + +```sh +agy plugin install https://github.com/callstackincubator/mobile-dev/tree/release/antigravity/mobile-dev +``` + +Or package and install from a local checkout: + +```sh +npm run build +npm run package:antigravity +agy plugin install ./release/antigravity-plugin/mobile-dev +``` + +Open the **Mobile Dev** icon in the Antigravity Auxiliary Pane or ask Antigravity to +open your app on a simulator. + +## Requirements + +- An Apple Silicon Mac. +- **Node.js 22.19 or later.** Mobile Dev looks for it on `PATH` and in the usual + Homebrew, nvm, fnm, Nix, Volta, mise, and asdf locations. +- **iOS:** Xcode 26 or later with an installed simulator runtime. Physical iPhone + logs need Xcode 27 or later. +- **Android:** Android SDK platform-tools and emulator, and an AVD or a device with + USB or wireless debugging authorized. + +## What it runs on your Mac + +The plugin bundles most of its runtimes and native helpers, so no `npm install`, +account, or hosted service is needed. Your project's own tools build the app. Besides +its Node.js server and Auxiliary Pane sidecar proxy, it runs: + +- **The device panel's runtime, downloaded once.** The first time you open the panel, + Mobile Dev downloads one archive from this project's GitHub release for the + installed version (`mobile-dev--panel-runtime-darwin-arm64.tar.gz`). The + plugin pins the archive's size and SHA-256 checksum and refuses any other file. It + is unpacked into Antigravity's plugin data folder (`PLUGIN_DATA`), or + `~/Library/Caches/mobile-dev` elsewhere, and kept across sessions. +- **A loopback page and sidecar proxy for the panel:** while the panel is open, the + server serves it on `127.0.0.1` at a random port behind a private link, and + `sidecars/launch.mjs` proxies it into the Antigravity Auxiliary Pane authenticated + with `ANTIGRAVITY_SIDECAR_UI_TOKEN`. +- **agent-device**, its bundled Node.js runtime, for device control. +- **Native helpers** for physical iPhone logs, iOS FPS, and Android CPU/FPS + collection. +- **Developer tools** already on your Mac: `xcrun simctl`, `devicectl`, `adb`, and the + Android emulator, and TraceSift when you analyze a profile. + +## Privacy and support + +Mobile Dev reports plugin errors, crashes, usage counters, sampled traces, and +aggregate plugin performance measurements to Sentry by default. App logs, +screenshots, input content, tool payloads, app storage contents, profiles, and device +performance recordings are excluded from that telemetry. Set `MOBILE_DEV_TELEMETRY=off` +in the environment Antigravity starts from, then restart Antigravity, to turn reporting +off. Read the [Privacy Policy](PRIVACY.md) and [Terms of Service](TERMS.md). + +For help, email [hello@callstack.com](mailto:hello@callstack.com) or see +[Support](SUPPORT.md). + +## License + +MIT. See [LICENSE](LICENSE) and [third-party notices](THIRD_PARTY_NOTICES.md). diff --git a/apps/antigravity/assets/icon.png b/apps/antigravity/assets/icon.png new file mode 100644 index 00000000..ba1d10de Binary files /dev/null and b/apps/antigravity/assets/icon.png differ diff --git a/apps/antigravity/hooks.json b/apps/antigravity/hooks.json new file mode 100644 index 00000000..e10db8bb --- /dev/null +++ b/apps/antigravity/hooks.json @@ -0,0 +1,11 @@ +{ + "mobile-dev-node-check": { + "SessionStart": [ + { + "type": "command", + "command": "/bin/sh ./scripts/launch-node.sh --check", + "timeout": 10 + } + ] + } +} diff --git a/apps/antigravity/mcp_config.json b/apps/antigravity/mcp_config.json new file mode 100644 index 00000000..b8d47d22 --- /dev/null +++ b/apps/antigravity/mcp_config.json @@ -0,0 +1,11 @@ +{ + "mcpServers": { + "mobile-dev": { + "command": "/bin/sh", + "args": [ + "${PLUGIN_ROOT}/scripts/launch-node.sh", + "${PLUGIN_ROOT}/dist/server.mjs" + ] + } + } +} diff --git a/apps/antigravity/package.json b/apps/antigravity/package.json new file mode 100644 index 00000000..b113e3d2 --- /dev/null +++ b/apps/antigravity/package.json @@ -0,0 +1,7 @@ +{ + "name": "@mobile-dev/antigravity", + "version": "0.0.0", + "private": true, + "type": "module", + "description": "Antigravity: the Antigravity extension manifest and Auxiliary Pane sidecar for the shared server and MCP Apps panel." +} diff --git a/apps/antigravity/plugin-host.json b/apps/antigravity/plugin-host.json new file mode 100644 index 00000000..86e981c8 --- /dev/null +++ b/apps/antigravity/plugin-host.json @@ -0,0 +1,32 @@ +{ + "label": "Antigravity", + "manifest": ".antigravity-plugin", + "mcpConfig": "mcp_config.json", + "hooks": "hooks.json", + "root": "PLUGIN_ROOT", + "data": "PLUGIN_DATA", + "config": { + "file": "antigravity-mcp-config.json", + "server": {}, + "target": "~/.gemini/antigravity/mcp_config.json" + }, + "marketplace": { + "name": "mobile-dev-local", + "manifest": ".antigravity-plugin/marketplace.json" + }, + "panelRuntime": "download", + "build": "tooling/build.mjs", + "skills": [ + "skills/mobile-dev", + "../../packages/skills/mobile-dev-testing", + "../../packages/skills/agent-device" + ], + "folders": [ + "scripts", + "sidecars", + "mcp_config.json", + "hooks.json" + ], + "readme": "README.md", + "maxFileBytes": 5242880 +} diff --git a/apps/antigravity/scripts/launch-node.sh b/apps/antigravity/scripts/launch-node.sh new file mode 100755 index 00000000..62b819ce --- /dev/null +++ b/apps/antigravity/scripts/launch-node.sh @@ -0,0 +1,44 @@ +#!/bin/sh +# Runs Mobile Dev with Node.js 22.19 or later. +# launch-node.sh + +`); +} + +function clearStandaloneChild() { + if (standaloneChild && !standaloneChild.killed) { + try { standaloneChild.kill("SIGTERM"); } catch {} + } + standaloneChild = null; +} + +function proxyHttpRequest(req, res, body, state, urlObj, setCookie, canRetry = true) { + const panelUrl = new URL(state.url); + let targetPath = panelUrl.pathname; + if (urlObj.pathname === "/mcp") { + targetPath = `${panelUrl.pathname}mcp`; + } else if (urlObj.pathname === "/context") { + targetPath = `${panelUrl.pathname}context`; + } else if (urlObj.pathname === "/" || urlObj.pathname === "/index.html") { + targetPath = `${panelUrl.pathname}${panelUrl.search}`; + } else { + res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); + res.end("Not Found"); + return; + } + + const headers = { ...req.headers }; + headers.host = panelUrl.host; + headers.origin = panelUrl.origin; + delete headers.referer; + + const reqSessionId = typeof req.headers["mcp-session-id"] === "string" ? req.headers["mcp-session-id"] : null; + if (req.method === "DELETE" && reqSessionId) { + activeSessions.delete(reqSessionId); + } + + const isHeadRoot = req.method === "HEAD" && (urlObj.pathname === "/" || urlObj.pathname === "/index.html"); + const proxyReq = http.request( + { + hostname: panelUrl.hostname, + port: Number(panelUrl.port), + path: targetPath, + method: isHeadRoot ? "GET" : req.method, + headers, + }, + proxyRes => { + const resSessionId = typeof proxyRes.headers["mcp-session-id"] === "string" ? proxyRes.headers["mcp-session-id"] : reqSessionId; + if (req.method !== "DELETE" && resSessionId && (proxyRes.statusCode === 200 || proxyRes.statusCode === 202)) { + if (!reqSessionId && !activeSessions.has(resSessionId) && activeSessions.size >= MAX_CONCURRENT_SESSIONS) { + let oldestId = null; + let oldestSeen = Infinity; + for (const [id, entry] of activeSessions) { + if (entry.lastBrowserSeen < oldestSeen) { + oldestSeen = entry.lastBrowserSeen; + oldestId = id; + } + } + if (oldestId) { + const oldestEntry = activeSessions.get(oldestId); + closeBackendSession(oldestId, oldestEntry?.backendUrl); + } + } + activeSessions.set(resSessionId, { backendUrl: state.url, lastBrowserSeen: Date.now() }); + } else if (resSessionId && proxyRes.statusCode === 404) { + activeSessions.delete(resSessionId); + } + const resHeaders = { ...proxyRes.headers }; + if (typeof resHeaders["content-security-policy"] === "string") { + resHeaders["content-security-policy"] = resHeaders["content-security-policy"].replace(/frame-ancestors\s+'none';?\s*/i, ""); + } + if (setCookie && TOKEN) { + resHeaders["set-cookie"] = `antigravity_sidecar_token=${encodeURIComponent(TOKEN)}; Path=/; HttpOnly; SameSite=Lax`; + } + if (isHeadRoot) { + res.writeHead(proxyRes.statusCode || 200, resHeaders); + proxyRes.resume(); + res.end(); + return; + } + const isRootGet = !isHeadRoot && req.method === "GET" && (urlObj.pathname === "/" || urlObj.pathname === "/index.html"); + if (isRootGet && TOKEN && (proxyRes.statusCode || 200) === 200) { + const chunks = []; + proxyRes.on("data", chunk => chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk)); + proxyRes.on("end", () => { + const rawHtml = Buffer.concat(chunks).toString("utf8"); + const escapedToken = TOKEN.replace(/[&"<>]/g, c => ({ "&": "&", "\"": """, "<": "<", ">": ">" })[c]); + const html = rawHtml.replace("", `\n `); + delete resHeaders["content-length"]; + delete resHeaders["transfer-encoding"]; + res.writeHead(200, resHeaders); + res.end(html); + }); + proxyRes.on("error", () => { + if (!res.headersSent) res.writeHead(502); + res.end(); + }); + return; + } + res.writeHead(proxyRes.statusCode || 200, resHeaders); + proxyRes.pipe(res); + }, + ); + + let clientAborted = false; + res.on("close", () => { + if (!res.writableEnded) { + clientAborted = true; + proxyReq.destroy(); + } + }); + + proxyReq.on("error", async err => { + if (clientAborted || res.destroyed) return; + const isTrulyDead = err?.code === "ECONNREFUSED" || !isPidAlive(state.pid); + if (isTrulyDead) { + deadUrls.add(state.url); + if (state.filePath) { + await unlink(state.filePath).catch(() => {}); + if (state.filePath === STANDALONE_STATE_FILE) { + clearStandaloneChild(); + } + } + } + if (!res.headersSent) { + const hasSession = Boolean(req.headers["mcp-session-id"]); + if (canRetry && !hasSession) { + const nextState = await ensureBackend(); + if (nextState) { + proxyHttpRequest(req, res, body, nextState, urlObj, setCookie, false); + return; + } + } + if (urlObj.pathname === "/mcp" || urlObj.pathname === "/context") { + void ensureBackend().catch(() => {}); + res.writeHead(404, { "Cache-Control": "no-store" }); + res.end(); + return; + } + if (req.method === "GET" || req.method === "HEAD") { + void ensureBackend().catch(() => {}); + sendWaitingHtml(res, "Reconnecting Mobile Dev...", setCookie, req.method); + return; + } + res.writeHead(502, { "Content-Type": "text/plain; charset=utf-8" }); + } + res.end(`Mobile Dev sidecar proxy error: ${err.message}`); + }); + + if (body.length > 0) proxyReq.write(body); + proxyReq.end(); +} + +const server = http.createServer(async (req, res) => { + try { + const urlObj = new URL(req.url || "/", `http://${req.headers.host || "127.0.0.1"}`); + const auth = verifyRequestToken(req, urlObj); + if (req.method !== "GET" && req.method !== "HEAD" && !auth.valid) { + res.writeHead(403, { "Content-Type": "text/plain; charset=utf-8" }); + res.end("Forbidden: Invalid or missing Antigravity sidecar token."); + return; + } + + if (urlObj.pathname === "/api/status") { + const now = Date.now(); + for (const entry of activeSessions.values()) { + entry.lastBrowserSeen = now; + } + const state = await getActiveBackend(); + const stateUrl = state ? new URL(state.url) : null; + const target = {}; + if (stateUrl) { + for (const key of ["platform", "kind", "deviceId", "workspaceTool", "appIntelScreen"]) { + const value = stateUrl.searchParams.get(key); + if (value !== null) target[key] = value; + } + } + const tool = stateUrl?.searchParams.get("tool") || "mobile_open_simulator"; + res.writeHead(200, { + "Content-Type": "application/json; charset=utf-8", + "Cache-Control": "no-store", + }); + res.end(JSON.stringify({ + status: state ? "ok" : "starting", + pid: state?.pid ?? null, + updatedAt: state?.updatedAt ?? null, + tool, + target, + })); + return; + } + + if (urlObj.pathname === "/api/close-session" && req.method === "POST") { + const rawBody = await readRequestBuffer(req); + let sessionId = null; + try { + const parsed = JSON.parse(rawBody.toString("utf8")); + if (typeof parsed?.sessionId === "string") sessionId = parsed.sessionId; + } catch {} + if (sessionId) { + const entry = activeSessions.get(sessionId); + const backendUrl = entry?.backendUrl ?? (await getActiveBackend())?.url; + closeBackendSession(sessionId, backendUrl); + } + res.writeHead(204, { "Cache-Control": "no-store" }); + res.end(); + return; + } + + const body = await readRequestBuffer(req); + let state = await getActiveBackend(); + if (!state) { + if (urlObj.pathname === "/" || urlObj.pathname === "/index.html") { + const pending = ensureBackend(); + state = await Promise.race([pending, new Promise(r => setTimeout(() => r(null), 1500))]); + } else { + state = await ensureBackend(); + } + } + if (!state) { + if (urlObj.pathname === "/mcp" || urlObj.pathname === "/context") { + res.writeHead(404, { "Cache-Control": "no-store" }); + res.end(); + return; + } + sendWaitingHtml(res, "Starting Mobile Dev backend...", auth.fromQuery, req.method); + return; + } + + proxyHttpRequest(req, res, body, state, urlObj, auth.fromQuery); + } catch (err) { + if (!res.headersSent) { + res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" }); + } + res.end(`Internal Server Error: ${err.message}`); + } +}); + +const keepAliveTimer = setInterval(async () => { + if (activeSessions.size === 0) return; + const state = await getActiveBackend(); + if (!state) return; + const now = Date.now(); + const panelUrl = new URL(state.url); + const payload = JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }); + for (const [sessionId, entry] of activeSessions) { + if (entry.backendUrl !== state.url) { + activeSessions.delete(sessionId); + continue; + } + if (now - entry.lastBrowserSeen > MAX_BROWSER_UNSEEN_MS) { + closeBackendSession(sessionId, entry.backendUrl); + continue; + } + const req = http.request( + { + hostname: panelUrl.hostname, + port: Number(panelUrl.port), + path: `${panelUrl.pathname}mcp`, + method: "POST", + headers: { + host: panelUrl.host, + origin: panelUrl.origin, + "content-type": "application/json", + accept: "application/json, text/event-stream", + "mcp-session-id": sessionId, + "content-length": Buffer.byteLength(payload), + }, + }, + res => { + if (res.statusCode === 404) activeSessions.delete(sessionId); + res.resume(); + }, + ); + req.on("error", () => {}); + req.end(payload); + } +}, 60_000); +keepAliveTimer.unref(); + +server.listen(PORT, "127.0.0.1", () => { + const addr = server.address(); + const actualPort = typeof addr === "object" && addr ? addr.port : PORT; + console.error(`[mobile-dev-sidecar] Listening on http://127.0.0.1:${actualPort}`); +}); + +function shutdown() { + if (standaloneChild && !standaloneChild.killed) { + try { standaloneChild.kill("SIGTERM"); } catch {} + } + server.close(() => process.exit(0)); + setTimeout(() => process.exit(0), 1000).unref(); +} + +process.on("SIGTERM", shutdown); +process.on("SIGINT", shutdown); diff --git a/apps/antigravity/skills/mobile-dev/SKILL.md b/apps/antigravity/skills/mobile-dev/SKILL.md new file mode 100644 index 00000000..1995b669 --- /dev/null +++ b/apps/antigravity/skills/mobile-dev/SKILL.md @@ -0,0 +1,44 @@ +--- +name: mobile-dev +description: Use when building, running, changing, or debugging local iOS, Android, Expo, React Native, or SwiftUI apps in Antigravity. Renders Mobile Dev's device panel in the Antigravity Auxiliary Pane beside the chat, controls devices with Mobile Dev's device_* tools, reads native and Metro logs, and records CPU, memory, and FPS into interactive charts in chat. Skip web-only apps and tasks limited to planning, docs, or code review. +--- + +# Mobile Dev + +Mobile Dev shows the user's simulator, emulator, or physical iPhone in the Antigravity Auxiliary Pane (`[Mobile Dev](sidecar://mobile-dev/device-panel/)`) beside the chat, and gives you the tools to control apps on it, read its logs, inspect app architecture, and record its performance. + +Before calling a Mobile Dev tool that is not yet in your tool list, load it through your tool-search tool if your session uses deferred tools. If none of the `mobile_*` or `device_*` tools exist at all, read `references/missing-tools.md` to diagnose the plugin's Node.js startup. + +## Read the panel's context first + +The Auxiliary Pane does not push its selection into the chat on its own. Call `mobile_read_panel_context` before device work and whenever the user refers to "this screen", "these logs", a screenshot, or a device they selected: + +- It returns the active and visible device IDs from every open Mobile Dev panel, and any logs, screenshots, and screen notes the user clicked **Add to chat** on. +- Pass the active device ID to your `mobile_*` and `device_*` calls so you act on the device the user is looking at. + +## Show the device panel when the user wants to see the app + +When the user asks to open a simulator, emulator, or device, run the app, or see a UI change: + +1. Call `mobile_open_simulator` with the platform (`ios` or `android`), `mobile_open_workspace` when both platforms or a workspace tool (`logs`, `performance`, `storage`, `app-intel`, `tracesift`) is wanted, or `mobile_open_app_intel` to visualize the React Native screen/dependency graph. Pass `deviceId` when one is already known. +2. In Antigravity, the Mobile Dev Auxiliary Pane updates automatically to the requested view and target. Include the clickable pill `[Mobile Dev](sidecar://mobile-dev/device-panel/)` in your reply so the user can toggle the Auxiliary Pane with one click. Never open an external Chrome browser or launch a browser subagent for the loopback URL. + +Never open the simulator backend's `baseUrl` (`127.0.0.1:46672`) or the `ui://mobile-dev/app.html` resource URI in a browser; neither is a standalone page. + +## App Intelligence + +App Intelligence statically discovers Expo Router and React Navigation screens and combines their source dependencies for iOS and Android; it does not require App Flow or a running device. When the user asks to see the app map, call `mobile_open_app_intel` and include `[Mobile Dev](sidecar://mobile-dev/device-panel/)`. Generate or refresh with `mobile_generate_app_intel`, passing `projectPath` when no project is remembered. For a screen or file dependency question, call `mobile_app_intel` with `operation: "screen"` or `"file"`, start with depth 1, and paginate only when `nextOffset` is present. + +## Drive the app and verify UI changes + +Use the `agent-device` skill for `device_*` commands: `device_open`, `device_snapshot`, `device_click`, `device_fill`, `device_scroll`, `device_wait`, `device_screenshot`, and the rest. Use `mobile_install_app`, `mobile_launch_app`, `mobile_stop_app`, `mobile_open_url`, `mobile_set_app_permission`, `mobile_set_app_language`, and `mobile_send_push` for app lifecycle and system state. + +Use the `mobile-dev-testing` skill when the user asks to record or capture an end-to-end test in Mobile Dev's Testing tab. + +After a code change the user can see on screen, check it on the device and leave the app on the affected screen so they can see it in the panel. + +## Logs, storage, and performance + +- **Logs:** start `mobile_logs_session` with sources (`ios_Sim`, `android`, `ios_physical`, or `metro`), read with `mobile_read_logs`, and close with `mobile_logs_close` when done. +- **App storage:** inspect UserDefaults, SharedPreferences, AsyncStorage, MMKV, Keychain, and SQLite with `mobile_app_storage`, `mobile_app_storage_table`, and `mobile_app_storage_file`. +- **Performance:** record CPU, memory, and FPS with `mobile_record_performance`, finish with `mobile_finish_performance_recording`, and render or compare in chat with `mobile_render_performance_recording` and `mobile_compare_performance_recordings`. The chart renders in the chat; the device panel stays in the Auxiliary Pane. diff --git a/apps/antigravity/skills/mobile-dev/references/missing-tools.md b/apps/antigravity/skills/mobile-dev/references/missing-tools.md new file mode 100644 index 00000000..69a077b0 --- /dev/null +++ b/apps/antigravity/skills/mobile-dev/references/missing-tools.md @@ -0,0 +1,27 @@ +# Recover missing Mobile Dev tools + +Use this when the installed plugin's tools are unavailable. Diagnose and explain the +setup problem in chat from the actual startup failure. + +Find the installed plugin root from the absolute path of the loaded `SKILL.md`: the +skill is under `/skills/mobile-dev/SKILL.md`. Inspect its +`.antigravity-plugin/plugin.json` and `mcp_config.json`, and check whether the plugin +is enabled in Antigravity. Use that installed copy rather than a source checkout or a +guessed cache version. + +The server starts through `scripts/launch-node.sh`, which needs Node.js 22.19 or +later and looks for it on `PATH` and in the usual Homebrew, nvm, fnm, Nix, Volta, mise and +asdf locations. Run `/bin/sh "/scripts/launch-node.sh" -p process.version` +to see which Node it finds. If it reports that none was found, explain that Mobile +Dev needs Node.js 22.19 or later and offer to install it: with `brew install node` +when `brew` is available, otherwise from https://nodejs.org. Do not install it +without the user's agreement. After the install, check the launcher again. + +Report the actual failure, or say what remains unknown. A generic timeout does not +justify increasing the timeout. Keep diagnostics local; startup failures occur before +the server's Sentry SDK starts. + +After resolving the startup failure, refresh MCP servers in Antigravity (or ask the +user to restart Antigravity) so it can rediscover the server, then confirm the tools +are available before resuming device work. Keep the original app task, and explain +what remains blocked. diff --git a/apps/antigravity/test/crypto-polyfill.test.ts b/apps/antigravity/test/crypto-polyfill.test.ts new file mode 100644 index 00000000..b7718a8b --- /dev/null +++ b/apps/antigravity/test/crypto-polyfill.test.ts @@ -0,0 +1,22 @@ +import assert from "node:assert/strict"; +import { webcrypto } from "node:crypto"; +import test from "node:test"; +import { installRandomUUIDPolyfill } from "../../../packages/mcp-app/src/crypto-polyfill.ts"; + +test("installRandomUUIDPolyfill provides valid v4 UUIDs when crypto.randomUUID is absent", () => { + const target: { getRandomValues: (array: Uint8Array) => Uint8Array; randomUUID?: () => string } = { + getRandomValues: buf => webcrypto.getRandomValues(buf), + }; + + installRandomUUIDPolyfill(target); + assert.equal(typeof target.randomUUID, "function"); + + const seen = new Set(); + const uuidV4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/; + for (let i = 0; i < 32; i++) { + const id = target.randomUUID!(); + assert.match(id, uuidV4); + assert.equal(seen.has(id), false); + seen.add(id); + } +}); diff --git a/apps/antigravity/test/hot-reload.test.ts b/apps/antigravity/test/hot-reload.test.ts new file mode 100644 index 00000000..c9bdf1c8 --- /dev/null +++ b/apps/antigravity/test/hot-reload.test.ts @@ -0,0 +1,76 @@ +import assert from "node:assert/strict"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import test from "node:test"; +import { pathToFileURL } from "node:url"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; +import { ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js"; + +test("hot-reload supervisor swaps worker when dist entry changes and notifies client", async t => { + const dir = await mkdtemp(join(tmpdir(), "mobile-dev-hot-reload-")); + t.after(() => rm(dir, { recursive: true, force: true })); + + const supervisorUrl = pathToFileURL(resolve("apps/antigravity/server/supervisor.ts")).href; + const mcpServerUrl = import.meta.resolve("@modelcontextprotocol/sdk/server/mcp.js"); + const stdioTransportUrl = import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"); + + const entryPath = join(dir, "server.ts"); + const renderEntry = (toolName: string) => ` +if (process.env.MOBILE_DEV_SERVER_WORKER === "1") { + const { McpServer } = await import(${JSON.stringify(mcpServerUrl)}); + const { StdioServerTransport } = await import(${JSON.stringify(stdioTransportUrl)}); + const server = new McpServer({ name: "hot-reload-test", version: "1.0.0" }); + server.registerTool(${JSON.stringify(toolName)}, { inputSchema: {} }, async () => ({ + content: [{ type: "text", text: ${JSON.stringify(toolName)} }], + })); + await server.connect(new StdioServerTransport()); +} else { + const { runHotReloadSupervisor } = await import(${JSON.stringify(supervisorUrl)}); + await runHotReloadSupervisor(import.meta.url); +} +`; + + await writeFile(entryPath, renderEntry("version_v1")); + + const client = new Client({ name: "hot-reload-client", version: "1.0.0" }); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [entryPath], + cwd: dir, + stderr: "pipe", + }); + + let resolveListChanged!: () => void; + const listChanged = new Promise(resolvePromise => { + resolveListChanged = resolvePromise; + }); + client.setNotificationHandler(ToolListChangedNotificationSchema, () => { + resolveListChanged(); + }); + + t.after(async () => { + await client.close(); + await transport.close(); + }); + + await client.connect(transport); + + const before = await client.listTools(); + assert.deepEqual(before.tools.map(tool => tool.name), ["version_v1"]); + + // Ensure mtime granularity ticks forward cleanly, then overwrite entry script. + await new Promise(r => setTimeout(r, 50)); + await writeFile(entryPath, renderEntry("version_v2")); + + await Promise.race([ + listChanged, + new Promise((_, reject) => + setTimeout(() => reject(new Error("Timed out waiting for tools/list_changed notification")), 12_000), + ), + ]); + + const after = await client.listTools(); + assert.deepEqual(after.tools.map(tool => tool.name), ["version_v2"]); +}); diff --git a/apps/antigravity/test/publish-release.test.ts b/apps/antigravity/test/publish-release.test.ts new file mode 100644 index 00000000..9c658008 --- /dev/null +++ b/apps/antigravity/test/publish-release.test.ts @@ -0,0 +1,63 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { test, type TestContext } from "node:test"; +import { publishRelease } from "../tooling/publish-release.mjs"; + +function git(directory: string, args: string[]) { + return execFileSync("git", args, { cwd: directory, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); +} + +async function fixture(t: TestContext) { + const directory = await mkdtemp(join(tmpdir(), "mobile-dev-antigravity-publish-test-")); + t.after(() => rm(directory, { recursive: true, force: true })); + const remote = join(directory, "remote.git"); + const plugin = join(directory, "plugin"); + git(directory, ["init", "--bare", remote]); + await mkdir(`${plugin}/.antigravity-plugin`, { recursive: true }); + await mkdir(`${plugin}/sidecars/device-panel`, { recursive: true }); + await mkdir(`${plugin}/dist/ios-fps`, { recursive: true }); + await writeFile(`${plugin}/mcp_config.json`, '{"mcpServers":{}}'); + await writeFile(`${plugin}/hooks.json`, '{"hooks":{}}'); + await writeFile(`${plugin}/sidecars/device-panel/sidecar.json`, '{"id":"mobile-dev.device-panel"}'); + await writeFile(`${plugin}/sidecars/launch.mjs`, "console.log('sidecar');\n"); + await writeFile(`${plugin}/dist/server.mjs`, "console.log('server');\n"); + await writeFile(`${plugin}/dist/ios-fps/mobile-dev-ios-fps`, "#!/bin/sh\n", { mode: 0o755 }); + await writeFile(`${plugin}/dist/telemetry-environment.json`, '{"environment":"release"}'); + await writeFile(`${plugin}/dist/app.html`, ''); + async function version(value: string, environment = "release") { + await writeFile(`${plugin}/dist/telemetry-environment.json`, JSON.stringify({ environment })); + await writeFile(`${plugin}/.antigravity-plugin/plugin.json`, JSON.stringify({ + name: "mobile-dev", version: value, description: "Release fixture", author: { name: "Callstack", email: "hello@callstack.com" }, + })); + } + async function checkout() { + const clone = join(directory, `clone-${Math.random().toString(36).slice(2)}`); + git(directory, ["clone", "--branch", "release/antigravity", remote, clone]); + return clone; + } + return { remote, plugin, version, checkout }; +} + +test("publishing puts the Antigravity extension beside its marketplace on release/antigravity", async t => { + const { remote, plugin, version, checkout } = await fixture(t); + await version("1.2.3"); + assert.deepEqual(await publishRelease(plugin, "v1.2.3", remote), { published: true, version: "1.2.3", latest: "1.2.3" }); + const clone = await checkout(); + const catalog = JSON.parse(await readFile(join(clone, ".antigravity-plugin/marketplace.json"), "utf8")); + assert.equal(catalog.name, "mobile-dev"); + assert.equal(JSON.parse(await readFile(join(clone, "mobile-dev/.antigravity-plugin/plugin.json"), "utf8")).version, "1.2.3"); + assert.equal(JSON.parse(await readFile(join(clone, "mobile-dev/sidecars/device-panel/sidecar.json"), "utf8")).id, "mobile-dev.device-panel"); + assert.equal((await stat(join(clone, "mobile-dev/dist/ios-fps/mobile-dev-ios-fps"))).mode & 0o111, 0o111); + assert.equal(git(clone, ["log", "-1", "--format=%s"]).trim(), "chore(release): release mobile-dev 1.2.3"); +}); + +test("only a release build matching its tag is published", async t => { + const { remote, plugin, version } = await fixture(t); + await version("1.3.0"); + await assert.rejects(publishRelease(plugin, "v1.2.9", remote), /must match the release tag/); + await version("1.3.0", "development"); + await assert.rejects(publishRelease(plugin, "v1.3.0", remote), /requires a release build/); +}); diff --git a/apps/antigravity/test/sidecar-launch.test.ts b/apps/antigravity/test/sidecar-launch.test.ts new file mode 100644 index 00000000..8060fec4 --- /dev/null +++ b/apps/antigravity/test/sidecar-launch.test.ts @@ -0,0 +1,190 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import test from "node:test"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { browserPanel } from "../../../packages/core/src/browser-panel.ts"; +import { SharedTransport } from "../../../packages/core/src/shared-transport.ts"; +import type { PanelOpen } from "../../../packages/core/src/server-feature.ts"; + +test("sidecar proxy replaces superseded sessions and closes sessions on beacon", async t => { + const fakeHome = await mkdtemp(join(tmpdir(), "mobile-dev-sidecar-test-")); + t.after(() => rm(fakeHome, { recursive: true, force: true })); + const cacheDir = join(fakeHome, "Library", "Caches", "mobile-dev"); + await mkdir(cacheDir, { recursive: true }); + const statePath = join(cacheDir, "antigravity-panel.json"); + + const server = new McpServer({ name: "mobile-dev-test", version: "1.0.0" }); + const [hostSide, serverSide] = InMemoryTransport.createLinkedPair(); + const connections = new SharedTransport(serverSide); + const openers: PanelOpen[] = []; + const template = new URL("../../../packages/mcp-app/src/browser-panel.html", import.meta.url); + let writeQueue: Promise = Promise.resolve(); + const stopPanel = browserPanel({ + always: true, + template, + onPage: url => { + const run = async () => { + const tmpPath = `${statePath}.${process.pid}.tmp`; + await writeFile(tmpPath, JSON.stringify({ pid: process.pid, url, updatedAt: Date.now() }) + "\n"); + await rename(tmpPath, statePath); + }; + writeQueue = writeQueue.then(run, run); + return writeQueue; + }, + })(server, { + connections, + onPanelOpen: opener => { openers.push(opener); }, + }); + t.after(async () => { + await stopPanel?.(); + await server.close(); + }); + + server.registerTool("mobile_open_simulator", { inputSchema: {} }, async () => { + for (const open of openers) await open({ tool: "mobile_open_simulator", target: { platform: "android" } }); + return { content: [{ type: "text", text: "opened" }] }; + }); + server.registerTool("slow_ping", { inputSchema: {} }, async () => { + await new Promise(r => setTimeout(r, 250)); + return { content: [{ type: "text", text: "pong" }] }; + }); + + await server.connect(connections); + const hostClient = new Client({ name: "antigravity-test", version: "1.0.0" }); + await hostClient.connect(hostSide); + t.after(() => hostClient.close()); + await hostClient.callTool({ name: "mobile_open_simulator", arguments: {} }); + + const token = "test-sidecar-secret"; + const sidecar = spawn(process.execPath, [resolve("apps/antigravity/sidecars/launch.mjs")], { + env: { + ...process.env, + HOME: fakeHome, + ANTIGRAVITY_SIDECAR_WEB_PORT: "0", + ANTIGRAVITY_SIDECAR_UI_TOKEN: token, + }, + stdio: ["ignore", "pipe", "pipe"], + }); + t.after(() => { sidecar.kill("SIGTERM"); }); + + const port = await new Promise((resolvePort, reject) => { + let stderr = ""; + sidecar.stderr.on("data", chunk => { + stderr += chunk.toString(); + const match = stderr.match(/Listening on http:\/\/127\.0\.0\.1:(\d+)/); + if (match) resolvePort(Number(match[1])); + }); + sidecar.once("exit", code => reject(new Error(`Sidecar exited early: ${code}\n${stderr}`))); + }); + + const baseUrl = `http://127.0.0.1:${port}`; + const headRes = await fetch(`${baseUrl}/?token=${token}`, { method: "HEAD" }); + assert.equal(headRes.status, 200); + + const statusRes = await fetch(`${baseUrl}/api/status`, { headers: { "x-sidecar-token": token } }); + assert.equal(statusRes.status, 200); + const statusJson = await statusRes.json() as { status: string; tool: string; target: Record }; + assert.equal(statusJson.status, "ok"); + assert.equal(statusJson.tool, "mobile_open_simulator"); + assert.deepEqual(statusJson.target, { platform: "android" }); + + const openBrowserSession = async (note: string) => { + const transport = new StreamableHTTPClientTransport(new URL(`${baseUrl}/mcp`), { + requestInit: { headers: { "x-sidecar-token": token } }, + }); + const client = new Client({ name: "browser-tab", version: "1.0.0" }); + await client.connect(transport); + const putRes = await fetch(`${baseUrl}/context`, { + method: "PUT", + headers: { + "content-type": "application/json", + "mcp-session-id": transport.sessionId!, + "x-sidecar-token": token, + }, + body: JSON.stringify({ content: [{ type: "text", text: note }] }), + }); + assert.equal(putRes.status, 204); + return { client, transport }; + }; + + const tab1 = await openBrowserSession("First tab context"); + t.after(() => tab1.client.close()); + const tab2 = await openBrowserSession("Second tab context"); + t.after(() => tab2.client.close()); + + await new Promise(r => setTimeout(r, 100)); + + const bothTabs = await hostClient.callTool({ name: "mobile_read_panel_context", arguments: {} }); + const bothText = JSON.stringify(bothTabs.content); + assert.match(bothText, /First tab context/, "Concurrent sidecar tabs must stay open."); + assert.match(bothText, /Second tab context/, "Second concurrent sidecar tab must also remain active."); + + const closeTab1 = await fetch(`${baseUrl}/api/close-session?token=${token}`, { + method: "POST", + body: JSON.stringify({ sessionId: tab1.transport.sessionId }), + }); + assert.equal(closeTab1.status, 204); + const closeTab2 = await fetch(`${baseUrl}/api/close-session?token=${token}`, { + method: "POST", + body: JSON.stringify({ sessionId: tab2.transport.sessionId }), + }); + assert.equal(closeTab2.status, 204); + await new Promise(r => setTimeout(r, 100)); + + const afterClose = await hostClient.callTool({ name: "mobile_read_panel_context", arguments: {} }); + assert.match(JSON.stringify(afterClose.content), /No Mobile Dev browser panel/); + + // Aborting an in-flight proxied request must not poison deadUrls or remove state file. + const tab3 = await openBrowserSession("Third tab context"); + t.after(() => tab3.client.close()); + const ac = new AbortController(); + setTimeout(() => ac.abort(), 30); + await assert.rejects( + fetch(`${baseUrl}/mcp`, { + method: "POST", + signal: ac.signal, + headers: { + "content-type": "application/json", + accept: "application/json, text/event-stream", + "mcp-session-id": tab3.transport.sessionId!, + "x-sidecar-token": token, + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 99, + method: "tools/call", + params: { name: "slow_ping", arguments: {} }, + }), + }), + ); + await new Promise(r => setTimeout(r, 50)); + + const rootAfterAbort = await fetch(`${baseUrl}/?token=${token}`); + assert.equal(rootAfterAbort.status, 200); + const rootHtml = await rootAfterAbort.text(); + assert.match(rootHtml, /Mobile Dev/); + assert.doesNotMatch(rootHtml, /Starting Mobile Dev backend/); + + const statusAfterAbort = await fetch(`${baseUrl}/api/status`, { headers: { "x-sidecar-token": token } }); + const statusAfterJson = await statusAfterAbort.json() as { status: string }; + assert.equal(statusAfterJson.status, "ok"); + + // GET / without ?token= succeeds and injects sidecar token meta, while POST /mcp without token stays 403. + const tokenlessRoot = await fetch(`${baseUrl}/`); + assert.equal(tokenlessRoot.status, 200); + const tokenlessHtml = await tokenlessRoot.text(); + assert.match(tokenlessHtml, new RegExp(``)); + + const tokenlessPost = await fetch(`${baseUrl}/mcp`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: "{}", + }); + assert.equal(tokenlessPost.status, 403); +}); diff --git a/apps/antigravity/tooling/build.mjs b/apps/antigravity/tooling/build.mjs new file mode 100644 index 00000000..5c41fbf5 --- /dev/null +++ b/apps/antigravity/tooling/build.mjs @@ -0,0 +1,17 @@ +import { rm } from "node:fs/promises"; +import { buildServerBundles } from "../../../tooling/server-bundle.mjs"; +import { telemetryBuildEnvironment } from "../../../tooling/telemetry-build.mjs"; +import { buildHostPage, buildUIPage } from "../../../tooling/ui-page.mjs"; + +export async function buildHost(outdir, { sentryDirectory = ".sentry/server/antigravity", includeUIPage = false } = {}) { + await rm(sentryDirectory, { recursive: true, force: true }); + if (includeUIPage) { + await buildUIPage({ + name: "ui/mcp-app", entry: "packages/mcp-app/src/main.tsx", template: "packages/mcp-app/src/index.html", + sources: ["packages/ui/src", "packages/mcp-app/src"], output: `${outdir}/app.html`, + environment: telemetryBuildEnvironment(), sourceURL: "app:///mobile-dev-ui.js", + }); + } + await buildHostPage({ entry: "packages/mcp-app/src/browser-panel.ts", template: "packages/mcp-app/src/browser-panel.html", output: `${outdir}/browser-panel.html` }); + await buildServerBundles({ entryPoints: { server: "apps/antigravity/server/index.ts" }, outdir, sentryDirectory, splitting: true }); +} diff --git a/apps/antigravity/tooling/publish-release.mjs b/apps/antigravity/tooling/publish-release.mjs new file mode 100644 index 00000000..d19d96cb --- /dev/null +++ b/apps/antigravity/tooling/publish-release.mjs @@ -0,0 +1,17 @@ +import { pluginMarketplace } from "../../../tooling/plugin-marketplace.mjs"; +import { publishFromCommandLine, publishPluginRelease } from "../../../tooling/release-branch.mjs"; + +const release = { + manifestPath: ".antigravity-plugin/plugin.json", + requiredFiles: ["dist/server.mjs", "mcp_config.json", "hooks.json", "sidecars/device-panel/sidecar.json", "sidecars/launch.mjs"], + branch: "release/antigravity", + pluginPath: "mobile-dev", + catalogPath: ".antigravity-plugin/marketplace.json", + catalog: manifest => pluginMarketplace("mobile-dev", "Mobile Dev for Antigravity: iOS and Android device panel, control, logs, and performance charts.", manifest), +}; + +export function publishRelease(pluginDirectory, tag, remote, token) { + return publishPluginRelease(release, { pluginDirectory, tag, remote, token }); +} + +await publishFromCommandLine(import.meta.url, ({ pluginDirectory, tag, remote, token }) => publishRelease(pluginDirectory, tag, remote, token)); diff --git a/package-lock.json b/package-lock.json index 01916660..805ebb8b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "packages/mcp-app", "packages/test-support", "apps/codex-plugin", + "apps/antigravity", "apps/claude", "apps/cursor", "apps/mac" @@ -72,6 +73,10 @@ "node": ">=22.19.0" } }, + "apps/antigravity": { + "name": "@mobile-dev/antigravity", + "version": "0.0.0" + }, "apps/claude": { "name": "@mobile-dev/claude", "version": "0.0.0" @@ -2080,6 +2085,10 @@ } } }, + "node_modules/@mobile-dev/antigravity": { + "resolved": "apps/antigravity", + "link": true + }, "node_modules/@mobile-dev/claude": { "resolved": "apps/claude", "link": true diff --git a/package.json b/package.json index fa09f15e..c510cb22 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "packages/mcp-app", "packages/test-support", "apps/codex-plugin", + "apps/antigravity", "apps/claude", "apps/cursor", "apps/mac" @@ -48,6 +49,9 @@ "test:ios-cpu": "node tooling/smoke-ios-cpu.mjs", "package": "node apps/codex-plugin/tooling/package.mjs", "package:release": "node apps/codex-plugin/tooling/package.mjs --release", + "antigravity:config": "node tooling/plugin-config.mjs antigravity", + "package:antigravity": "node tooling/package-plugin.mjs antigravity", + "test:antigravity": "node tooling/smoke-plugin.mjs antigravity", "claude:config": "node tooling/plugin-config.mjs claude", "package:claude": "node tooling/package-plugin.mjs claude", "test:claude": "node tooling/smoke-plugin.mjs claude", diff --git a/packages/core/src/browser-panel.ts b/packages/core/src/browser-panel.ts index a1253b49..05d96965 100644 --- a/packages/core/src/browser-panel.ts +++ b/packages/core/src/browser-panel.ts @@ -38,12 +38,20 @@ export type BrowserPanelOptions = { * server whose panel does not render inline (see createPanel's `inline`). */ always?: boolean; + /** Called with the panel page URL when the server starts or opens the panel. */ + onPage?: (url: string) => void | Promise; + /** Customizes the instructions returned when a tool opens the panel page. */ + instructions?: (url: string) => string; }; /** Hosts without MCP Apps, or every host with `always`, can show the shared panel on a session-owned loopback page. */ -export function browserPanel({ template = PAGE, always = false }: BrowserPanelOptions = {}): ServerFeature { +export function browserPanel({ template = PAGE, always = false, onPage, instructions: formatInstructions }: BrowserPanelOptions = {}): ServerFeature { return (server, { connections, onPanelOpen }) => { let page: Promise | undefined; + if (onPage !== undefined && connections !== undefined) { + page = startPanelPage(connections, "other", template); + void page.then(opened => onPage(opened.url("mobile_open_simulator", {}))).catch(() => {}); + } onPanelOpen(async ({ tool, target }) => { const capabilities = server.server.getClientCapabilities(); if (connections === undefined || (always === false && getUiCapability(capabilities))) return; @@ -52,7 +60,8 @@ export function browserPanel({ template = PAGE, always = false }: BrowserPanelOp page ??= startPanelPage(connections, host, template); const opened = await page; const url = opened.url(tool, target); - const instructions = `Mobile Dev's panel is a page to show beside the chat, not in it, and it is not open yet. Show it to the user now: open ${url} in your in-app browser or side panel, in the foreground, so the page is visible without another click. This page is how Mobile Dev shows its panel, so opening it is part of opening the panel. Use your host's own browser or preview tool, and load it first if it is deferred. Never open the page with a computer-use tool that drives the screen. Opening a page can leave the browser pane hidden: when your host has a tool that brings its browser or preview pane into view, such as a show_pane tool for its preview pane, load it if needed and call it right after. A host can also show the page as a floating preview and report it as not visible. That still counts as shown, so do not open it again. Leave the tab open after you reply. Reuse a tab that already shows Mobile Dev. Open no other address for it, such as the backend's baseUrl. If you cannot open pages, give the user the link. The page shares the user's devices and what they add to chat through mobile_read_panel_context; read it before device work.`; + await onPage?.(url); + const instructions = formatInstructions?.(url) ?? `Mobile Dev's panel is a page to show beside the chat, not in it, and it is not open yet. Show it to the user now: open ${url} in your in-app browser or side panel, in the foreground, so the page is visible without another click. This page is how Mobile Dev shows its panel, so opening it is part of opening the panel. Use your host's own browser or preview tool, and load it first if it is deferred. Never open the page with a computer-use tool that drives the screen. Opening a page can leave the browser pane hidden: when your host has a tool that brings its browser or preview pane into view, such as a show_pane tool for its preview pane, load it if needed and call it right after. A host can also show the page as a floating preview and report it as not visible. That still counts as shown, so do not open it again. Leave the tab open after you reply. Reuse a tab that already shows Mobile Dev. Open no other address for it, such as the backend's baseUrl. If you cannot open pages, give the user the link. The page shares the user's devices and what they add to chat through mobile_read_panel_context; read it before device work.`; return { url, instructions }; }); // A browser has no model context of its own, so the agent asks the server for it. diff --git a/packages/core/src/panel-runtime.ts b/packages/core/src/panel-runtime.ts index e3b3f070..739dab51 100644 --- a/packages/core/src/panel-runtime.ts +++ b/packages/core/src/panel-runtime.ts @@ -55,9 +55,10 @@ const STALE_MS = 60 * 60_000; const installed = /^\d+\.\d+\.\d+(?:-[\da-zA-Z.-]+)?-[0-9a-f]{12}$/; const run = promisify(execFile); -/** The persistent folder for downloaded runtimes: the plugin's data folder in Claude Code, else the user's cache. */ +/** The persistent folder for downloaded runtimes: the plugin's data folder in the host, else the user's cache. */ export function panelRuntimeDirectory(env: NodeJS.ProcessEnv = process.env) { - return env.CLAUDE_PLUGIN_DATA ? join(env.CLAUDE_PLUGIN_DATA, "panel-runtime") : join(homedir(), "Library", "Caches", "mobile-dev", "panel-runtime"); + const data = env.CLAUDE_PLUGIN_DATA || env.PLUGIN_DATA; + return data ? join(data, "panel-runtime") : join(homedir(), "Library", "Caches", "mobile-dev", "panel-runtime"); } /** diff --git a/packages/core/src/physical-ios-bezel.ts b/packages/core/src/physical-ios-bezel.ts index 48604cc2..60acc38e 100644 --- a/packages/core/src/physical-ios-bezel.ts +++ b/packages/core/src/physical-ios-bezel.ts @@ -10,6 +10,7 @@ import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts"; import type { Bezel } from "@mobile-dev/shared/bezel.ts"; import type { PhysicalIosDevice } from "@mobile-dev/shared/ios-devices.ts"; import { baguetteEnvironment } from "./baguette-runtime.ts"; +import { panelRuntimePath } from "./panel-runtime.ts"; import { captureServerError } from "./telemetry.ts"; const execute = promisify(execFile); @@ -81,10 +82,10 @@ async function renderBezel(device: PhysicalIosDevice, run: BezelCommand, runtime // Without an installed device type the screen mirrors without a frame. if (selected === undefined) throw new ExpectedOperationError("unsupported_platform", "Xcode has no Apple device frame for this model."); const { type, profile } = selected; - // Bundles, and the chunks they split into, sit in dist/ beside the helpers. - const root = import.meta.url.endsWith(".mjs") ? "./baguette/" : "../../native/vendor/baguette/"; - const url = new URL(`${root}Baguette`, import.meta.url); - const executable = fileURLToPath(url); + // Bundles, and the chunks they split into, sit in dist/ beside the helpers or in the downloaded panel runtime. + const executable = import.meta.url.endsWith(".mjs") + ? await panelRuntimePath("baguette/Baguette") + : fileURLToPath(new URL("../../native/vendor/baguette/Baguette", import.meta.url)); const signal = AbortSignal.timeout(commandOptions.timeout); const environment = await runtime(executable, signal); const renderOptions = { ...commandOptions, env: environment }; diff --git a/packages/core/test/browser-panel.test.ts b/packages/core/test/browser-panel.test.ts index 3dd27c2b..0226f8ad 100644 --- a/packages/core/test/browser-panel.test.ts +++ b/packages/core/test/browser-panel.test.ts @@ -374,3 +374,33 @@ test("an oversized browser context update is refused without storing it", async assert.deepEqual(page.context(), []); await transport.terminateSession(); }); + +test("browserPanel notifies onPage on startup and when a panel tool runs, with custom instructions", async t => { + const directory = await mkdtemp(join(tmpdir(), "browser-panel-")); + const page = join(directory, "browser-panel.html"); + await writeFile(page, ""); + const fake = await fakeBaguette(); + const [hostSide, serverSide] = InMemoryTransport.createLinkedPair(); + const shared = new SharedTransport(serverSide); + const seen: string[] = []; + const panel = createPanel({ baguette: new Baguette(fake.url), simulatorInput: fakeSimulatorInput(), inline: false }); + const feature = browserPanel({ + template: pathToFileURL(page), + always: true, + onPage: url => { seen.push(url); }, + instructions: url => `Auxiliary Pane renders ${url} automatically.`, + }); + const plugin = await createTestPlugin("", { panel, features: [feature], connections: shared }); + const host = new Client({ name: "antigravity-client", version: "1" }); + await plugin.server.connect(shared); + await host.connect(hostSide); + t.after(async () => { await host.close(); await plugin.close(); await fake.close(); await rm(directory, { recursive: true, force: true }); }); + + await t.waitFor(() => assert.equal(seen.length, 1)); + assert.equal(new URL(seen[0]).searchParams.get("tool"), "mobile_open_simulator"); + const result = await host.callTool({ name: "mobile_open_workspace", arguments: {} }); + assert.equal(seen.length, 2); + assert.equal(new URL(seen[1]).searchParams.get("tool"), "mobile_open_workspace"); + const { browserPanel: opening } = result.structuredContent as { browserPanel: { url: string; instructions: string } }; + assert.equal(opening.instructions, `Auxiliary Pane renders ${opening.url} automatically.`); +}); diff --git a/packages/core/test/mobile-dev-skill.test.ts b/packages/core/test/mobile-dev-skill.test.ts index 0f221c39..024c8c44 100644 --- a/packages/core/test/mobile-dev-skill.test.ts +++ b/packages/core/test/mobile-dev-skill.test.ts @@ -57,4 +57,6 @@ test("the testing skill ships from every plugin that has the panel", async () => assert.ok(sharedSkills.includes("packages/skills/mobile-dev-testing"), "Codex and Cursor"); const claude = JSON.parse(await readFile(new URL("../../../apps/claude/plugin-host.json", import.meta.url), "utf8")); assert.ok(claude.skills.includes("../../packages/skills/mobile-dev-testing"), "Claude Code"); + const antigravity = JSON.parse(await readFile(new URL("../../../apps/antigravity/plugin-host.json", import.meta.url), "utf8")); + assert.ok(antigravity.skills.includes("../../packages/skills/mobile-dev-testing"), "Antigravity"); }); diff --git a/packages/core/test/panel-runtime.test.ts b/packages/core/test/panel-runtime.test.ts index 265834f6..38e60b73 100644 --- a/packages/core/test/panel-runtime.test.ts +++ b/packages/core/test/panel-runtime.test.ts @@ -137,7 +137,8 @@ test("a prerelease pins and installs its runtime like a release", async t => { assert.equal((await readdir(data)).length, 2); }); -test("Claude Code's plugin data folder holds the runtime when it provides one", () => { +test("the host's plugin data folder holds the runtime when it provides one", () => { assert.equal(panelRuntimeDirectory({ CLAUDE_PLUGIN_DATA: "/data/mobile-dev" }), "/data/mobile-dev/panel-runtime"); + assert.equal(panelRuntimeDirectory({ PLUGIN_DATA: "/data/antigravity" }), "/data/antigravity/panel-runtime"); assert.match(panelRuntimeDirectory({}), /Library\/Caches\/mobile-dev\/panel-runtime$/); }); diff --git a/packages/mcp-app/src/browser-panel.ts b/packages/mcp-app/src/browser-panel.ts index 73a55e8d..16878580 100644 --- a/packages/mcp-app/src/browser-panel.ts +++ b/packages/mcp-app/src/browser-panel.ts @@ -1,3 +1,4 @@ +import "./crypto-polyfill.ts"; import { AppBridge, getToolUiResourceUri, PostMessageTransport, type McpUiHostContext } from "@modelcontextprotocol/ext-apps/app-bridge"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; @@ -8,52 +9,125 @@ import { PANEL_PAGE_META } from "@mobile-dev/shared/panel-target.ts"; const dark = matchMedia("(prefers-color-scheme: dark)"); const DISCONNECTED = "Mobile Dev disconnected from its chat session. Ask the agent to open Mobile Dev again."; const EXPIRED = "Mobile Dev's browser connection expired. Reload this page to reconnect."; +let fallbackLastReload = 0; -function notice(text: string) { +function readLastReload(): number { + try { + return Number(sessionStorage.getItem("mobile-dev-sidecar-reload") ?? String(fallbackLastReload)); + } catch { + return fallbackLastReload; + } +} + +function writeLastReload(timestamp: number): void { + fallbackLastReload = timestamp; + try { + sessionStorage.setItem("mobile-dev-sidecar-reload", String(timestamp)); + } catch {} +} + +function notice(text: string, reloadable = false) { const alert = document.createElement("p"); alert.setAttribute("role", "alert"); alert.textContent = text; + if (reloadable) { + const button = document.createElement("button"); + button.type = "button"; + button.textContent = "Reload"; + button.style.cssText = "margin-left:12px;padding:4px 10px;border:1px solid currentColor;border-radius:6px;background:transparent;color:inherit;cursor:pointer;font:inherit"; + button.onclick = () => location.reload(); + alert.append(button); + } document.body.replaceChildren(alert); } /** A small MCP Apps host for the same shared panel the chat would otherwise render. */ async function open() { const query = new URLSearchParams(location.search); - const toolName = query.get("tool") ?? "mobile_open_simulator"; - if (toolName !== "mobile_open_simulator" && toolName !== "mobile_open_workspace" && toolName !== "mobile_open_app_intel") { - throw new Error("This link does not open a Mobile Dev panel."); - } + const sidecarToken = query.get("token") ?? document.querySelector('meta[name="mobile-dev-sidecar-token"]')?.getAttribute("content") ?? null; + const isSidecar = sidecarToken !== null || location.protocol === "plugin:" || location.pathname === "/" || location.pathname === "/index.html"; + const sidecarHeaders: Record = sidecarToken ? { "x-sidecar-token": sidecarToken } : {}; + let toolName = query.get("tool") ?? "mobile_open_simulator"; const target: Record = {}; for (const key of ["platform", "kind", "deviceId", "workspaceTool", "appIntelScreen"]) { const value = query.get(key); if (value !== null) target[key] = value; } + let lastPanelUpdate = 0; + if (isSidecar && !query.has("tool")) { + try { + const res = await fetch(new URL("api/status", location.href), { headers: sidecarHeaders }); + if (res.ok) { + const status = await res.json() as { updatedAt?: number; tool?: string; target?: Record }; + if (typeof status.updatedAt === "number") lastPanelUpdate = status.updatedAt; + if (typeof status.tool === "string") toolName = status.tool; + if (status.target && typeof status.target === "object") Object.assign(target, status.target); + } + } catch {} + } + if (toolName !== "mobile_open_simulator" && toolName !== "mobile_open_workspace" && toolName !== "mobile_open_app_intel") { + throw new Error("This link does not open a Mobile Dev panel."); + } const client = new Client({ name: "mobile-dev-browser-panel", version: PLUGIN_VERSION }); const endpoint = new URL("mcp", location.href); const transport = new StreamableHTTPClientTransport(endpoint, { - fetch: (url, options) => fetch(url, { ...options, keepalive: options?.method === "DELETE" }), + fetch: (url, options) => fetch(url, { + ...options, + headers: sidecarToken ? { ...Object.fromEntries(new Headers(options?.headers).entries()), ...sidecarHeaders } : options?.headers, + keepalive: options?.method === "DELETE", + }), }); let bridge: AppBridge | undefined; let heartbeat: ReturnType | undefined; + let sidecarSync: ReturnType | undefined; let startup: ReturnType | undefined; let disposed = false; let checking = false; + let syncing = false; let contextChanged = () => {}; + const onVisible = () => { + if (document.visibilityState === "visible") void check(); + }; function dispose() { if (disposed) return; disposed = true; clearInterval(heartbeat); + clearInterval(sidecarSync); clearTimeout(startup); dark.removeEventListener("change", contextChanged); removeEventListener("pagehide", hide); + removeEventListener("focus", onVisible); + document.removeEventListener("visibilitychange", onVisible); const teardown = bridge?.teardownResource({}, { timeout: 1000, maxTotalTimeout: 1000 }); void teardown?.catch(() => {}).finally(() => bridge?.close()); + if (isSidecar && transport.sessionId) { + try { + const closeUrl = new URL("api/close-session", location.href); + if (sidecarToken) closeUrl.searchParams.set("token", sidecarToken); + const payload = JSON.stringify({ sessionId: transport.sessionId }); + if ((closeUrl.protocol === "http:" || closeUrl.protocol === "https:") && typeof navigator.sendBeacon === "function") { + navigator.sendBeacon(closeUrl, payload); + } else { + void fetch(closeUrl, { method: "POST", headers: sidecarHeaders, body: payload, keepalive: true }).catch(() => {}); + } + } catch {} + } void transport.terminateSession().catch(() => {}).finally(() => client.close()); } function stopped(message: string) { if (disposed) return; - notice(message); + if (isSidecar) { + const lastReload = readLastReload(); + if (Date.now() - lastReload > 3000) { + writeLastReload(Date.now()); + dispose(); + location.reload(); + return; + } + setTimeout(() => location.reload(), 3000); + } + notice(message, isSidecar); dispose(); } function hide(event: PageTransitionEvent) { @@ -75,6 +149,8 @@ async function open() { if (error instanceof StreamableHTTPError && error.code === 404) stopped(EXPIRED); }; addEventListener("pagehide", hide); + addEventListener("focus", onVisible); + document.addEventListener("visibilitychange", onVisible); try { await client.connect(transport); @@ -108,7 +184,7 @@ async function open() { const sessionId = transport.sessionId; if (sessionId === undefined) throw new Error("Mobile Dev's browser connection is not ready."); const response = await fetch(new URL("context", location.href), { - method: "PUT", headers: { "content-type": "application/json", "mcp-session-id": sessionId }, + method: "PUT", headers: { "content-type": "application/json", "mcp-session-id": sessionId, ...sidecarHeaders }, body: JSON.stringify({ content: content ?? [] }), }); if (response.status === 404) stopped(EXPIRED); @@ -143,7 +219,37 @@ async function open() { await initialized; await bridge.sendToolInput({ arguments: target }); const result = await client.callTool({ name: toolName, arguments: target }); + lastPanelUpdate = Date.now(); await bridge.sendToolResult(result as CallToolResult); + if (isSidecar && !query.has("tool")) { + let currentSig = JSON.stringify({ tool: toolName, target }); + sidecarSync = setInterval(async () => { + if (disposed || syncing || !bridge) return; + syncing = true; + try { + const res = await fetch(new URL("api/status", location.href), { headers: sidecarHeaders }); + if (!res.ok) return; + const status = await res.json() as { updatedAt?: number; tool?: string; target?: Record }; + if (typeof status.updatedAt !== "number" || status.updatedAt <= lastPanelUpdate) return; + lastPanelUpdate = status.updatedAt; + const nextTool = status.tool ?? "mobile_open_simulator"; + const nextTarget = status.target ?? {}; + const nextSig = JSON.stringify({ tool: nextTool, target: nextTarget }); + if (nextSig === currentSig) return; + currentSig = nextSig; + if (nextTool !== toolName) { + dispose(); + location.reload(); + return; + } + await bridge.sendToolInput({ arguments: nextTarget }); + const nextResult = await client.callTool({ name: nextTool, arguments: nextTarget }); + lastPanelUpdate = Date.now(); + await bridge.sendToolResult(nextResult as CallToolResult); + } catch {} + finally { syncing = false; } + }, 2000); + } } catch (error) { if (disposed === false) { dispose(); @@ -154,5 +260,11 @@ async function open() { open().catch(error => { const message = error instanceof Error ? error.message : String(error); - notice(`Mobile Dev could not open: ${message}`); + const isSidecar = new URLSearchParams(location.search).has("token") + || document.querySelector('meta[name="mobile-dev-sidecar-token"]') !== null + || location.protocol === "plugin:" + || location.pathname === "/" + || location.pathname === "/index.html"; + notice(`Mobile Dev could not open: ${message}`, isSidecar); + if (isSidecar) setTimeout(() => location.reload(), 3000); }); diff --git a/packages/mcp-app/src/crypto-polyfill.ts b/packages/mcp-app/src/crypto-polyfill.ts new file mode 100644 index 00000000..972c27cc --- /dev/null +++ b/packages/mcp-app/src/crypto-polyfill.ts @@ -0,0 +1,25 @@ +// Nested http://127.0.0.1 and about:srcdoc iframes inside custom-scheme IDE webviews +// (such as vscode-webview://) run with isSecureContext === false in Chromium, where +// crypto.randomUUID is omitted while crypto.getRandomValues remains available. +export function installRandomUUIDPolyfill( + target: { getRandomValues?: (array: Uint8Array) => Uint8Array; randomUUID?: () => string } | undefined = globalThis.crypto, +) { + if (!target || typeof target.getRandomValues !== "function" || typeof target.randomUUID === "function") return; + const hex = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); + const randomUUID = (): `${string}-${string}-${string}-${string}-${string}` => { + const bytes = new Uint8Array(16); + target.getRandomValues!(bytes); + bytes[6] = (bytes[6]! & 0x0f) | 0x40; + bytes[8] = (bytes[8]! & 0x3f) | 0x80; + return `${hex[bytes[0]!]!}${hex[bytes[1]!]!}${hex[bytes[2]!]!}${hex[bytes[3]!]!}-${hex[bytes[4]!]!}${hex[bytes[5]!]!}-${hex[bytes[6]!]!}${hex[bytes[7]!]!}-${hex[bytes[8]!]!}${hex[bytes[9]!]!}-${hex[bytes[10]!]!}${hex[bytes[11]!]!}${hex[bytes[12]!]!}${hex[bytes[13]!]!}${hex[bytes[14]!]!}${hex[bytes[15]!]!}`; + }; + try { + Object.defineProperty(target, "randomUUID", { configurable: true, writable: true, value: randomUUID }); + } catch { + try { + Object.defineProperty(Object.getPrototypeOf(target), "randomUUID", { configurable: true, writable: true, value: randomUUID }); + } catch {} + } +} + +installRandomUUIDPolyfill(); diff --git a/packages/mcp-app/src/main.tsx b/packages/mcp-app/src/main.tsx index be29f927..bca29a9c 100644 --- a/packages/mcp-app/src/main.tsx +++ b/packages/mcp-app/src/main.tsx @@ -1,3 +1,4 @@ +import "./crypto-polyfill.ts"; import { startMcpApp } from "./app.tsx"; // The panel as MCP Apps hosts without their own chrome load it, such as Claude Desktop. diff --git a/tooling/smoke-plugin.mjs b/tooling/smoke-plugin.mjs index d1efc64f..f7ee5048 100644 --- a/tooling/smoke-plugin.mjs +++ b/tooling/smoke-plugin.mjs @@ -90,7 +90,7 @@ async function smokePanelRuntime(plugin, launch) { // The published release may not exist yet, so the copy pins this archive by its file. await writeFile(join(plugin, "dist/panel-runtime.json"), JSON.stringify({ ...pin, url: pathToFileURL(archive).href })); const data = join(temporary, "plugin data"); - await launch({ CLAUDE_PLUGIN_DATA: data }, async client => { + await launch({ [host.data ?? "CLAUDE_PLUGIN_DATA"]: data }, async client => { const started = await client.callTool({ name: "mobile_start_baguette", arguments: {} }); assert.notEqual(started.isError, true, JSON.stringify(started.content)); const installed = await readdir(join(data, "panel-runtime")); @@ -157,7 +157,8 @@ try { assert.equal(manifest.version, version); assert.equal(manifest.license, "MIT"); await access(join(plugin, manifest.logo ?? manifest.icon)); - const server = manifest.mcpServers["mobile-dev"]; + const mcpConfig = host.mcpConfig ? JSON.parse(await readFile(join(plugin, host.mcpConfig), "utf8")) : manifest; + const server = mcpConfig.mcpServers["mobile-dev"]; // The server runs with Node from PATH, or through the host's launcher, which also // finds Node where version managers install it. const launcher = server.command !== "node"; @@ -181,9 +182,10 @@ try { const PATH = `${dirname(process.execPath)}:/usr/bin:/bin:/usr/sbin:/sbin`; if (launcher) { // Its session check stays silent when Node is usable. - const hooks = JSON.parse(await readFile(join(plugin, "hooks/hooks.json"), "utf8")); - const [check] = hooks.hooks.SessionStart[0].hooks; - assert.equal(execFileSync("/bin/sh", ["-c", check.command], { env: { PATH, HOME: home, [host.root]: plugin }, encoding: "utf8" }), ""); + const hooksPath = host.hooks ?? "hooks/hooks.json"; + const hooks = JSON.parse(await readFile(join(plugin, hooksPath), "utf8")); + const [check] = hooks.hooks ? hooks.hooks.SessionStart[0].hooks : Object.values(hooks)[0].SessionStart; + assert.equal(execFileSync("/bin/sh", ["-c", check.command], { cwd: plugin, env: { PATH, HOME: home, [host.root]: plugin }, encoding: "utf8" }), ""); } for (const environment of ["development", "release"]) { const env = { MOBILE_DEV_ENVIRONMENT: environment, [host.root]: plugin, ...launcher ? { PATH } : {} };