Skip to content
Merged
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
11 changes: 7 additions & 4 deletions packages/core/src/agent-device-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { RequestOptions } from "@modelcontextprotocol/sdk/shared/protocol.j
import { CallToolResultSchema, type CallToolRequest, type CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import * as Sentry from "@sentry/node";
import { execFile } from "node:child_process";
import { mkdtemp } from "node:fs/promises";
import { mkdir, mkdtemp } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
Expand Down Expand Up @@ -51,7 +51,7 @@ export async function claimAgentDeviceStateDirectory(
export class AgentDeviceRuntime {
private readonly cli: string;
private readonly config: string;
private state?: Promise<State>;
private state?: State;
private starting?: Promise<Client>;
/** The connected client; only its unexpected exit restarts the runtime. */
private client?: Client;
Expand Down Expand Up @@ -93,14 +93,16 @@ export class AgentDeviceRuntime {

private async createState(): Promise<State> {
const directory = await claimAgentDeviceStateDirectory();
// App Flow and Testing can pin this as the daemon's working directory before it exists.
await mkdir(directory, { recursive: true, mode: 0o700 });
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 };
}

private async start() {
const startedAt = performance.now();
const { directory } = await (this.state ??= this.createState());
const { directory } = this.state ??= await this.createState();
const client = new Client({ name: "mobile-dev-agent-device", version: "1" });
const transport = new StdioClientTransport({ command: process.execPath, args: [this.cli, "mcp"], cwd: directory, env: this.environment(directory), stderr: "inherit" });
// A start that fails closes its client too; connect reports that instead.
Expand All @@ -119,7 +121,8 @@ export class AgentDeviceRuntime {
async close() {
if (this.closing) return;
this.closing = true;
const [client, state] = await Promise.all([this.starting?.catch(() => undefined), this.state?.catch(() => undefined)]);
const client = await this.starting?.catch(() => undefined);
const state = this.state;
try { await client?.close(); }
finally {
state?.stopStorageMetrics();
Expand Down
35 changes: 35 additions & 0 deletions packages/core/test/agent-device-runtime.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import assert from "node:assert/strict";
import { mkdtemp, rm, stat, unlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { AgentDeviceRuntime } from "../src/agent-device-runtime.ts";

test("the runtime can retry and start in a newly configured state directory", async t => {
const root = await mkdtemp(join(tmpdir(), "mobile-dev-state-test-"));
const parent = join(root, "App Flow");
const directory = join(parent, "agent-device");
const previous = process.env.AGENT_DEVICE_STATE_DIR;
process.env.AGENT_DEVICE_STATE_DIR = directory;
const runtime = new AgentDeviceRuntime(new URL("../../runtimes/agent-device/", import.meta.url));
t.after(async () => {
try { await runtime.close(); }
finally {
if (previous === undefined) delete process.env.AGENT_DEVICE_STATE_DIR;
else process.env.AGENT_DEVICE_STATE_DIR = previous;
await rm(root, { recursive: true, force: true });
}
});

await writeFile(parent, "temporarily blocks directory creation");
await assert.rejects(runtime.connect());
await unlink(parent);

const client = await runtime.connect();
const state = await client.callTool({ name: "session", arguments: { action: "state-dir" } }, {});
assert.equal(state.isError, false);
assert.equal(state.structuredContent?.stateDir, directory);
assert.equal(process.env.AGENT_DEVICE_STATE_DIR, directory);
await runtime.close();
assert.ok((await stat(directory)).isDirectory(), "Closing the runtime keeps the configured state directory");
});
Loading