From b0d9bc89db844fc3a3b5cd22cf00a0041af2ad99 Mon Sep 17 00:00:00 2001 From: hurali97 Date: Tue, 24 Nov 2026 13:22:55 +0500 Subject: [PATCH] fix(agent-device): clarify session release without closing the app --- apps/claude/skills/mobile-dev/SKILL.md | 7 +- packages/core/src/agent-device-catalog.ts | 9 ++- packages/runtimes/agent-device/tools.json | 2 +- packages/skills/agent-device/SKILL.md | 4 +- packages/skills/mobile-dev/SKILL.md | 4 +- tooling/smoke-agent-device-release.mjs | 94 +++++++++++++++++++++++ 6 files changed, 112 insertions(+), 8 deletions(-) create mode 100644 tooling/smoke-agent-device-release.mjs diff --git a/apps/claude/skills/mobile-dev/SKILL.md b/apps/claude/skills/mobile-dev/SKILL.md index 260398e7..db86f036 100644 --- a/apps/claude/skills/mobile-dev/SKILL.md +++ b/apps/claude/skills/mobile-dev/SKILL.md @@ -92,8 +92,11 @@ The `device_*` tools are the bundled agent-device runtime's commands; follow the agent-device skill to drive the app. In short: call `device_open` with the app, the device's `platform` and `udid` (iOS) or `serial` (Android), a short `session` name, and `foreground: true`; act on refs from the latest snapshot with `settle: true`; verify -the requested result with a named expectation; and call `device_close` without -`shutdown` to leave the device running. Claude Code's simulator `control` tool can +the requested result with a named expectation; and call `device_close` with only +the `session` to release control while keeping the app running in its current +foreground state and the device booted. Omit both `app` and `shutdown` for that +handoff. Pass `app` only to intentionally close it, or `shutdown: true` to also stop +the simulator or emulator. Claude Code's simulator `control` tool can also tap and read the screen it shows; use one of the two for a flow rather than mixing them. diff --git a/packages/core/src/agent-device-catalog.ts b/packages/core/src/agent-device-catalog.ts index 1d11d63c..f383d638 100644 --- a/packages/core/src/agent-device-catalog.ts +++ b/packages/core/src/agent-device-catalog.ts @@ -78,6 +78,13 @@ const commandAnnotations: Record = { doctor: { ...write, openWorldHint: true }, metro: { ...write, openWorldHint: true }, }; +// The pinned runtime's close metadata says an omitted app closes the active app, +// but its native session teardown only closes an explicitly supplied app target. +// Keep the served contract aligned with that behavior across catalog regeneration. +const commandDescriptions: Record = { + close: "End the named local iOS or Android session and release its device claim. Omit app and shutdown to keep the app running in its current foreground state and leave the device booted, so another session can acquire it. Pass app only to intentionally close that app; set shutdown only to stop the simulator or emulator too. If cleanup fails, the session and claim may remain; retry close with the same options. Times out after 90s.", +}; + /** * The agent-device commands Mobile Dev serves, with compact schemas, our annotations, * and without output schemas, since the tools return agent-device's own results. @@ -89,7 +96,7 @@ export function agentDeviceCatalog(tools: Tool[]): Tool[] { .map(({ name, title, description, inputSchema }) => { const annotations = commandAnnotations[name]; if (annotations === undefined) throw new Error(`Classify agent-device's ${name} command in commandAnnotations before serving it.`); - return { name, title, description, inputSchema, annotations }; + return { name, title, description: commandDescriptions[name] ?? description, inputSchema, annotations }; }); } diff --git a/packages/runtimes/agent-device/tools.json b/packages/runtimes/agent-device/tools.json index c55552fb..1f9f65f1 100644 --- a/packages/runtimes/agent-device/tools.json +++ b/packages/runtimes/agent-device/tools.json @@ -666,7 +666,7 @@ }, { "name": "close", - "description": "Close the named app, or close the active session app when app is omitted. If the session booted a local simulator or emulator, add shutdown when you finish, unless the user asks to keep it running; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s, a killed process does not exit within 10s, or a new process runs past 2s. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay; run close again with the same options to retry the cleanup, leaving out save-script once the script is published. Times out after 90s.", + "description": "End the named local iOS or Android session and release its device claim. Omit app and shutdown to keep the app running in its current foreground state and leave the device booted, so another session can acquire it. Pass app only to intentionally close that app; set shutdown only to stop the simulator or emulator too. If cleanup fails, the session and claim may remain; retry close with the same options. Times out after 90s.", "inputSchema": { "type": "object", "properties": { diff --git a/packages/skills/agent-device/SKILL.md b/packages/skills/agent-device/SKILL.md index 75d9da80..fedb5595 100644 --- a/packages/skills/agent-device/SKILL.md +++ b/packages/skills/agent-device/SKILL.md @@ -5,7 +5,7 @@ description: Drive apps on a local iOS simulator or Android device with Mobile D # agent-device -Mobile Dev bundles agent-device 0.20.9 and serves each of its commands as a `device_` tool: `device_open` is its `open` command, and so on. No global CLI install, npx download, or separate server is needed. Follow the Mobile Dev skill to choose the device and to build, install, and launch the app; this skill covers driving it. +Mobile Dev bundles agent-device 0.21.37 and serves each of its commands as a `device_` tool: `device_open` is its `open` command, and so on. No global CLI install, npx download, or separate server is needed. Follow the Mobile Dev skill to choose the device and to build, install, and launch the app; this skill covers driving it. Read [the workflow guide](references/workflow.md) before the first task. It is this agent-device version's own `help workflow`, written for its CLI. With the tools: @@ -18,7 +18,7 @@ Read [the workflow guide](references/workflow.md) before the first task. It is t 2. Read the refs `device_open` returns, or call `device_snapshot` with `interactiveOnly: true`. Use actual refs from the latest result, or a known selector; prefer them to coordinates. 3. Call `device_press`, `device_fill`, or `device_scroll` with `settle: true`, and continue from the settled diff. `device_fill` replaces text; `device_type` appends to the focused field and has no settle option. Run stateful commands in order within one session. 4. Verify the requested result with a named expectation through `device_wait`, `device_is`, `device_get`, or `device_find`. Give `device_find` a read-only `action` such as `exists` or `getText`; without one it taps the match. A screenshot or snapshot alone is not verification, and an accepted input does not prove the app changed. `device_screenshot` returns the image when you need to look at the screen. -5. Call `device_close` when finished. Leave `shutdown` unset to keep the device running. Closing can close the active app; skip it if the user wants that app left open. +5. Release control when finished with `device_close({ session: "" })`, omitting both `app` and `shutdown`. On local iOS and Android devices, this ends the session and releases its device claim while keeping the app running in its current foreground state and the device booted, so another session can acquire it. Pass `app` only when intentionally closing that app; set `shutdown: true` only when the simulator or emulator should also stop. If cleanup fails, retry closing the same session; do not force-release another session's claim. A selector that matches several elements fails with `AMBIGUOUS_MATCH` and lists the candidates: retry with one of their refs or a narrower selector. diff --git a/packages/skills/mobile-dev/SKILL.md b/packages/skills/mobile-dev/SKILL.md index 43acda87..120746cd 100644 --- a/packages/skills/mobile-dev/SKILL.md +++ b/packages/skills/mobile-dev/SKILL.md @@ -35,7 +35,7 @@ device tools. 2. Use the task and app project to choose the platform. Follow the user's device choice; otherwise reuse a compatible device shared by the panel, then a suitable running simulator or emulator. If no suitable device runs, choose a compatible installed simulator or AVD. Pick among equivalent devices yourself for routine app development. When the intended target is ambiguous (for example, the app is open on several devices for a performance run), ask the user with `mobile_choose_devices`, or in chat when the host has no form. Read device IDs from tool results or panel context; never invent them. When `mobile_read_panel_context` is available, call it to read the active device in this chat before using the panel’s selection. Read it again after the user switches devices. 3. Boot a chosen stopped iOS simulator with `mobile_boot_simulator`, or an Android AVD with `mobile_boot_android_emulator`. A mobile app development request permits choosing and booting a suitable installed simulator without a separate device-choice question. Reuse running devices without rebooting them. Follow the Android section below for device discovery and serials. Opening the panel alone does not boot a device. 4. Build the app with the app project's own tools and the chosen device ID; the project's run command may also install and launch it. To restart an already installed app, use `mobile_launch_app` instead of rebuilding. Follow the project's framework skills where available. Before starting an app dev server, check for an existing server from that project and reuse it. Keep the same device for the panel, build target, and agent control; read the panel's shared IDs before acting and follow later user selections. Leave the panel and app available while continuing app work. Do not launch the app when the user asks only for compilation. -5. Control the app with the `device_*` tools, the bundled agent-device runtime's commands, and follow [the agent-device skill](../agent-device/SKILL.md) to drive it. In short: open the panel's device with `device_open` and a named session, act on refs from the latest snapshot with `settle: true`, verify the requested result with a named expectation, and close the session without `shutdown` so the device keeps running in the panel. Boot, launch, and app settings stay with the `mobile_*` tools above and below. +5. Control the app with the `device_*` tools, the bundled agent-device runtime's commands, and follow [the agent-device skill](../agent-device/SKILL.md) to drive it. In short: open the panel's device with `device_open` and a named session, act on refs from the latest snapshot with `settle: true`, verify the requested result with a named expectation, and release control with `device_close` using only the `session`. Omitting both `app` and `shutdown` keeps the app running in its current foreground state and the device booted in the panel while another session can acquire it. Pass `app` only to intentionally close it, or `shutdown: true` to also stop the simulator or emulator. Boot, launch, and app settings stay with the `mobile_*` tools above and below. ### Screen annotations @@ -44,7 +44,7 @@ A message that starts with "Apply these annotations." or "Apply these notes." ca 1. Edit the code directly. Open the Source first. When a note has no source, search the project for its Target text, then its testID or identifier, then the React owner names. Do not open an agent-device session, take a snapshot, or call `mobile_inspect_ui` to find or confirm a target before editing, unless a note has neither a source nor any text or identifier to search for. 2. Make every note's edit before checking anything. When Grouped notes say several notes select every matching element from one source with the same Edit, make that change once at the source. 3. JavaScript and style changes in a running React Native or Expo app arrive through Fast Refresh. Do not rebuild, reinstall, relaunch the app, or start another dev server for them. Native changes (Swift, Kotlin, native modules, app config) still need the project's build. -4. Check once, after all edits: open the panel's device with `device_open` and a named session without relaunching the app, take one `device_screenshot`, and close the session without `shutdown`. Do not verify each note separately or add named expectations unless the user asks. If the screenshot does not show the change, read the Metro or app logs before editing again. +4. Check once, after all edits: open the panel's device with `device_open` and a named session without relaunching the app, take one `device_screenshot`, and release the session with `device_close`, omitting both `app` and `shutdown` to leave the app open. Do not verify each note separately or add named expectations unless the user asks. If the screenshot does not show the change, read the Metro or app logs before editing again. ### App Intelligence diff --git a/tooling/smoke-agent-device-release.mjs b/tooling/smoke-agent-device-release.mjs new file mode 100644 index 00000000..20c77a11 --- /dev/null +++ b/tooling/smoke-agent-device-release.mjs @@ -0,0 +1,94 @@ +import assert from "node:assert/strict"; +import { execFile } from "node:child_process"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { AgentDeviceRuntime } from "../packages/core/src/agent-device-runtime.ts"; +import { agentDeviceTools, readAgentDeviceCatalog } from "../packages/core/src/agent-device-tools.ts"; +import { foregroundSimulatorPid } from "../packages/core/src/device-apps/foreground.ts"; +import { parseRunningApps } from "../packages/core/src/device-apps/apps.ts"; +import { usePanelRuntime } from "../packages/core/src/panel-runtime.ts"; + +// Run against an already booted simulator and an installed app. No shutdown, relaunch, +// or forced claim recovery: a failure must preserve the evidence of the broken handoff. +// node tooling/smoke-agent-device-release.mjs +const [udid, app] = process.argv.slice(2); +assert.ok(udid && app, "Pass an already booted simulator UDID and an installed app bundle ID."); +const root = new URL("../packages/runtimes/agent-device/", import.meta.url); +const pin = JSON.parse(await readFile(new URL("package.json", root), "utf8")); +const installed = JSON.parse(await readFile(new URL("node_modules/agent-device/package.json", root), "utf8")); +assert.equal(installed.version, pin.dependencies["agent-device"], "Install the pinned runtime before testing."); +const run = promisify(execFile); +const simctl = async (...args) => (await run("xcrun", ["simctl", ...args], { timeout: 20000, maxBuffer: 4 * 1024 * 1024 })).stdout; +const devices = JSON.parse(await simctl("list", "devices", "--json")); +assert.ok(Object.values(devices.devices).flat().some(device => device.udid === udid && device.state === "Booted"), "Boot the selected simulator through Mobile Dev first."); +usePanelRuntime(async () => fileURLToPath(new URL("../dist/", import.meta.url))); +const stateDir = await mkdtemp(join(tmpdir(), "mobile-dev-release-smoke-")); +process.env.AGENT_DEVICE_STATE_DIR = stateDir; +const runtime = new AgentDeviceRuntime(root); +const server = new McpServer({ name: "mobile-dev-release-smoke", version: "1" }); +const cleanup = agentDeviceTools(readAgentDeviceCatalog(new URL("tools.json", root)), runtime)(server); +const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); +const client = new Client({ name: "mobile-dev-release-smoke", version: "1" }); +const active = new Set(); +const evidence = { runtime: installed.version, app, observations: [] }; + +async function call(name, args) { + const result = await client.callTool({ name: `device_${name}`, arguments: args }, undefined, { timeout: 180000 }); + assert.notEqual(result.isError, true, JSON.stringify(result)); + return result; +} + +async function observe(phase, expectedPid) { + const running = parseRunningApps(await simctl("spawn", udid, "launchctl", "list"), true); + const process = running.find(candidate => candidate.bundleId === app); + assert.ok(process, `${phase}: the app must still be running`); + const foregroundPid = await foregroundSimulatorPid(udid); + assert.equal(foregroundPid, process.pid, `${phase}: the app must remain foreground`); + if (expectedPid !== undefined) assert.equal(process.pid, expectedPid, `${phase}: the app must not restart`); + evidence.observations.push({ phase, pid: process.pid, foregroundPid }); + console.log(`${phase}: app PID ${process.pid}, foreground PID ${foregroundPid}`); + return process.pid; +} + +try { + await server.connect(serverTransport); + await client.connect(clientTransport); + // Start outside agent-device, matching an agent attaching to an already-running app. + await simctl("launch", udid, app); + const pid = await observe("before opening a session"); + const first = "release-smoke-first"; + const second = "release-smoke-second"; + active.add(first); + await call("open", { session: first, platform: "ios", udid, app, foreground: true }); + await observe("first session owns device", pid); + const blocked = await client.callTool({ name: "device_open", arguments: { session: second, platform: "ios", udid, app } }); + assert.equal(blocked.isError, true, "The first session must keep exclusive ownership until released."); + assert.match(JSON.stringify(blocked), /DEVICE_IN_USE/); + await call("close", { session: first }); + active.delete(first); + await observe("after releasing first session", pid); + const sessions = await call("session", { action: "list" }); + assert.doesNotMatch(JSON.stringify(sessions), new RegExp(first), "The released session must be retired."); + active.add(second); + await call("open", { session: second, platform: "ios", udid, app, foreground: true }); + await observe("second session acquired device", pid); + await call("close", { session: second }); + active.delete(second); + await observe("after releasing second session", pid); + await cleanup(); + await observe("after stopping test runtime", pid); + console.log(JSON.stringify(evidence, null, 2)); +} finally { + for (const session of active) await call("close", { session }).catch(error => console.error(error)); + await client.close(); + await server.close(); + await cleanup(); + // Keep the isolated state directory and diagnostics for investigating failures. + console.log(`Runtime diagnostics: ${stateDir}`); +}