Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 0 additions & 27 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 24 additions & 2 deletions packages/core/src/agent-device-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import * as Sentry from "@sentry/node";
import { execFile } from "node:child_process";
import { mkdtemp } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { startStorageMetrics } from "./storage-metrics.ts";
Expand All @@ -21,6 +21,28 @@ export type AgentDeviceBackend = {
/** The runtime's state directory for this server, and the storage measurement that watches it. */
type State = { directory: string; stopStorageMetrics: () => void };

/**
* Claims the one agent-device state directory every subsystem in this server process shares.
*
* App Flow also starts agent-device clients and CLI commands. Publishing a newly-created directory
* through the process environment lets those clients join this runtime's daemon instead of
* becoming a second owner of the same simulator. An operator-supplied directory still wins.
*/
export async function claimAgentDeviceStateDirectory(
env: NodeJS.ProcessEnv = process.env,
create: (prefix: string) => Promise<string> = mkdtemp,
): Promise<string> {
const configured = env.AGENT_DEVICE_STATE_DIR?.trim();
if (configured) return resolve(configured);
const directory = await create(join(tmpdir(), "mobile-dev-agent-device-"));
// App Flow may have pinned its directory while mkdtemp was in flight. Join that winner instead
// of overwriting it and splitting the two clients across daemons again.
const concurrentlyConfigured = env.AGENT_DEVICE_STATE_DIR?.trim();
if (concurrentlyConfigured) return resolve(concurrentlyConfigured);
env.AGENT_DEVICE_STATE_DIR = directory;
return directory;
}

/**
* The bundled agent-device runtime: its CLI's MCP server in a process of its own, with a
* state directory for this server. It starts on the first command and again after an
Expand Down Expand Up @@ -70,7 +92,7 @@ export class AgentDeviceRuntime {
}

private async createState(): Promise<State> {
const directory = await mkdtemp(join(tmpdir(), "mobile-dev-agent-device-"));
const directory = await claimAgentDeviceStateDirectory();
console.error(`[mobile-dev] agent-device state directory: ${directory}`);
const stopStorageMetrics = startStorageMetrics({ agent_device_state: directory, apple_runner_cache: join(homedir(), ".agent-device/apple-runner") });
return { directory, stopStorageMetrics };
Expand Down
32 changes: 32 additions & 0 deletions packages/core/src/app-flow/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { homedir } from 'node:os'
import { basename, isAbsolute, join } from 'node:path'
import type { AppFlowNode, AppFlowPressable, AppFlowStep, ExplorationMode } from '@mobile-dev/shared/app-flow.ts'
import { errorMessage } from '@mobile-dev/shared/protocol.ts'
import { ExpectedOperationError } from '@mobile-dev/shared/error-reporting.ts'
import {
acceptOpenInAppPrompt,
isUrlSchemePreapproved,
Expand Down Expand Up @@ -390,6 +391,36 @@ async function closeExistingSession(client: AgentDeviceClient): Promise<void> {
}
}

/**
* Transfers the selected device from an idle chat session to App Flow.
*
* The shared state directory makes both clients peers of the same daemon. Closing through that
* daemon waits behind work already using the session, releases its device claim, and leaves the
* healthy iOS runner warm for App Flow's same-state-dir takeover. Sessions on other devices are
* deliberately untouched.
*/
export async function handoffCaptureDevice(
client: AgentDeviceClient,
deviceId: string
): Promise<void> {
const sessions = await client.sessions.list()
const owners = sessions.filter((session: { device?: { id?: string } }) => session.device?.id === deviceId)
for (const owner of owners) {
const session = owner.address ?? owner.name
if (typeof session !== 'string' || !session.trim()) continue
log('sessions.close', `handoff device=${deviceId} owner=${owner.name ?? session}`)
try {
await client.sessions.close({ session })
} catch (error) {
throw new ExpectedOperationError(
'resource_limit',
`App Flow could not take the simulator from agent-device session "${owner.name ?? session}". ` +
`Wait for that session to finish its current command, then retry. (${errorMessage(error)})`
)
}
}
}

function detectPackageManager(projectPath: string): 'yarn' | 'pnpm' | 'bun' | 'npm' {
if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn'
if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm'
Expand Down Expand Up @@ -1374,6 +1405,7 @@ export async function bootDevice(ctx: CaptureContext): Promise<CaptureDevice> {

const bootResult = await bootPreferredDevice(client, ctx)
log('devices.boot', `device=${bootResult.device} id=${bootResult.id}`)
await handoffCaptureDevice(client, bootResult.id)

const setupCommands = [agentDeviceBootCommand()]
let expoGoTarget: string | undefined
Expand Down
26 changes: 26 additions & 0 deletions packages/core/test/agent-device-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,38 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { agentDeviceCatalogFile, agentDeviceClient } from "../../test-support/agent-device-fixtures.ts";
import { readAgentDeviceCatalog } from "../src/agent-device-tools.ts";
import { claimAgentDeviceStateDirectory } from "../src/agent-device-runtime.ts";
import { PNG } from "../../test-support/fixtures.ts";

function text(result: { content: unknown }) {
return (result.content as { text: string }[])[0].text;
}

test("the first agent-device runtime publishes one state directory for App Flow and later runtimes", async () => {
const env: NodeJS.ProcessEnv = {};
const created: string[] = [];
const create = async () => {
const directory = `/tmp/mobile-dev-agent-device-test-${created.length + 1}`;
created.push(directory);
return directory;
};
const first = await claimAgentDeviceStateDirectory(env, create);
const second = await claimAgentDeviceStateDirectory(env, create);
assert.equal(second, first);
assert.equal(env.AGENT_DEVICE_STATE_DIR, first);
assert.deepEqual(created, [first]);
});

test("App Flow's state directory wins when it is pinned during runtime setup", async () => {
const env: NodeJS.ProcessEnv = {};
const directory = await claimAgentDeviceStateDirectory(env, async () => {
env.AGENT_DEVICE_STATE_DIR = "/app-flow/agent-device";
return "/tmp/unused-agent-device-state";
});
assert.equal(directory, "/app-flow/agent-device");
assert.equal(env.AGENT_DEVICE_STATE_DIR, directory);
});

test("agent-device commands are device_ tools with their compact schemas, and listing them starts nothing", async t => {
const { client, counts } = await agentDeviceClient(t);
const { tools } = await client.listTools();
Expand Down
34 changes: 34 additions & 0 deletions packages/core/test/app-flow-device-handoff.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import assert from "node:assert/strict";
import test from "node:test";
import { handoffCaptureDevice } from "../src/app-flow/capture.ts";

test("App Flow releases only sessions that own its selected device", async () => {
const closed: string[] = [];
const client = {
sessions: {
list: async () => [
{ name: "experimenta", address: "cwd:chat:experimenta", device: { id: "ios-selected" } },
{ name: "android-task", address: "cwd:chat:android-task", device: { id: "android-other" } },
],
close: async ({ session }: { session: string }) => { closed.push(session); },
},
};

await handoffCaptureDevice(client, "ios-selected");

assert.deepEqual(closed, ["cwd:chat:experimenta"]);
});

test("App Flow names the owning session when a handoff cannot complete", async () => {
const client = {
sessions: {
list: async () => [{ name: "experimenta", device: { id: "ios-selected" } }],
close: async () => { throw new Error("session is busy"); },
},
};

await assert.rejects(
handoffCaptureDevice(client, "ios-selected"),
/session "experimenta".*finish its current command.*session is busy/i,
);
});
Binary file modified packages/native/vendor/android-cpu/arm64-v8a/mobile-dev-cpu
Binary file not shown.
Binary file modified packages/native/vendor/android-cpu/armeabi-v7a/mobile-dev-cpu
Binary file not shown.
Loading
Loading