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
34 changes: 34 additions & 0 deletions .agents/reviews/pr-733.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"findings": [
{
"id": "R1",
"role": "code",
"class": "testing 2",
"outcome": "fixed",
"path": "src/drivers/android/index.test.ts:1587",
"fix": "9d1bc4ed77e549dcae9c87ee9042f09282d1331c"
},
{
"id": "R2",
"role": "claims",
"class": "manual claims path proof for durable marks",
"outcome": "fixed",
"path": "src/drivers/android/AGENTS.md:79",
"fix": "9d1bc4ed77e549dcae9c87ee9042f09282d1331c"
},
{
"id": "R3",
"role": "code",
"class": "lease loss on failed AVD path query",
"outcome": "intentional",
"path": "src/drivers/android/index.ts"
},
{
"id": "R4",
"role": "code",
"class": "style long manual line",
"outcome": "nonblocking",
"path": "src/drivers/android/AGENTS.md:79"
}
]
}
35 changes: 17 additions & 18 deletions src/drivers/android/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,37 +112,36 @@ No slim: `resolveSpec` ignores `mode` and returns a full spec. `fresh` is core's

Screen — `screenCapture`, only when `create` got `scrcpyServerPath` and `tcpStreamConnector`: [screen](screen/AGENTS.md).

Plain facts: `avdmanager list device` runs on every `listCatalog`, every resolve of a model the library
lacks, and every library provision (seed); nothing is cached. The sdkmanager catalog is never read.
Existing devices are not re-checked against the fit rule.
Plain facts: `avdmanager list device` runs on every `listCatalog`, resolve of a model the library lacks,
and library provision (seed); nothing is cached. The sdkmanager catalog is never read. Existing devices are not re-checked for fit.

## State and timers

| What | Default | Key |
| ------------------------------ | --------------------------------------- | --------------------------------------------------------------- |
| Device root | `$SIMLOCK_HOME/devices/android` | `drivers.android.deviceRoot` |
| adb server port | 5038 (never 5037) | `drivers.android.adbServerPort` |
| Emulator flags | window, auto GPU, audio, boot animation | `android.emulator.headless`, `.gpu`, `.audio`, `.bootAnimation` |
| Readiness timeout | 180 s, poll 2 s | none |
| adb server start / stop | 10 s / SIGTERM, 5 s, SIGKILL | none |
| `adb devices` in `listManaged` | 30 s | none |
| Physical read / uninstall | 30 s / 60 s | none |

Writes: `<root>/<avd>.avd/` (`config.ini`, `boot.prop`, snapshots,
`simlock-clean-baseline.json`), `$SIMLOCK_HOME/adb-server.json` (`pid`, `port`, `startedAt`).
| What | Default | Key |
| ------------------------------- | --------------------------------------- | --------------------------------------------------------------- |
| Device root | `$SIMLOCK_HOME/devices/android` | `drivers.android.deviceRoot` |
| adb server port | 5038 (never 5037) | `drivers.android.adbServerPort` |
| Emulator flags | window, auto GPU, audio, boot animation | `android.emulator.headless`, `.gpu`, `.audio`, `.bootAnimation` |
| Readiness timeout | 180 s, poll 2 s | none |
| adb server start / stop | 10 s / SIGTERM, 5 s, SIGKILL | none |
| `adb devices` in `listManaged` | 30 s | none |
| AVD path query (listing / boot) | 5 s | none |
| Physical read / uninstall | 30 s / 60 s | none |

Writes: `<root>/<avd>.avd/` (config, boot properties, snapshots, baseline marker); `$SIMLOCK_HOME/adb-server.json` (`pid`, `port`, `startedAt`).
Reads only: the user's AVD home, devices.xml, the SDK.

## Rules

- Ownership is root membership, proven again at boot by `emu avd path`. An AVD name proves nothing.
- Ownership is root membership, proven at boot and in running observations by `emu avd path`, never a name.
- The 5037 server is never started, stopped or adopted on purpose; physical commands pass the gate first.
- A recovery boot never wipes and never captures a baseline.
- A stored port is not trusted after a restart (#52); pinned by `two-instances.test.ts`.

## Known gaps

- **Simlock's adb server is stopped by pid only.** `ADB_REJECT_KILL_SERVER=1` refuses its `kill-server`. A
server with no record is `occupied`: find it with `lsof`, or move `drivers.android.adbServerPort` (one per instance).
- **Simlock's adb server is stopped by pid only.** `ADB_REJECT_KILL_SERVER=1` refuses its `kill-server`.
No record → `occupied`: find it with `lsof`, or move `drivers.android.adbServerPort` (one per instance).
- **A physical command can restart a 5037 server of another protocol (ADR 0022 §5).** One started
between the gate and the command is restarted by adb's client. Run every adb on the host from one platform-tools.
- **Port checks are partial.** A port handed out but not yet booted reads free to another instance.
Expand Down
142 changes: 141 additions & 1 deletion src/drivers/android/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1594,7 +1594,7 @@ describe("AndroidDriver", () => {
expect(runner.calls.some((call) => call.command === binaries.sdkmanager)).toBe(false);
});

it("joins adb devices with getprop to compute runState per AVD: running, stopped, transitioning", async () => {
it("reports one running root AVD, one stopped root AVD and the running AVD's process", async () => {
const filesystem = await androidFilesystem();
await filesystem.mkdirp(`${avdDirectory}/simlock_running.avd`);
await filesystem.mkdirp(`${avdDirectory}/simlock_stopped.avd`);
Expand All @@ -1610,6 +1610,7 @@ describe("AndroidDriver", () => {
],
"simlock_running\n",
),
avdPathExpectation("emulator-5586", "simlock_running"),
]);
const driver = await createDriver(filesystem, runner);

Expand Down Expand Up @@ -1873,6 +1874,7 @@ describe("AndroidDriver", () => {
],
'simlock_one\n{"token":"tok-123"}',
),
avdPathExpectation("emulator-5586"),
]);
const driver = await createDriver(filesystem, runner);

Expand Down Expand Up @@ -1902,6 +1904,7 @@ describe("AndroidDriver", () => {
],
"simlock_one\n",
),
avdPathExpectation("emulator-5586"),
]);
const driver = await createDriver(filesystem, runner);

Expand Down Expand Up @@ -3639,6 +3642,143 @@ describe("AndroidDriver.create", () => {
});

describe("AndroidDriver ownership", () => {
it.each([
{
reported: "a trailing slash",
answer: ok(`${avdDirectory}/simlock_one.avd/\r\nOK\r\n`),
runState: "running",
},
{
reported: "a canonical alias",
answer: ok(`/private${avdDirectory}/simlock_one.avd\r\nOK\r\n`),
runState: "running",
},
{ reported: "a blank path", answer: ok("\r\nOK\r\n"), runState: "stopped" },
{ reported: "a console error", answer: ok("KO: unknown command\r\n"), runState: "stopped" },
{ reported: "a relative path", answer: ok("simlock_one.avd\r\nOK\r\n"), runState: "stopped" },
{
reported: "a missing directory",
answer: ok("/missing/simlock_one.avd\r\nOK\r\n"),
runState: "stopped",
},
{
reported: "an unreadable alias",
answer: ok(`/unreadable/simlock_one.avd\r\nOK\r\n`),
runState: "stopped",
},
{
reported: "a sibling AVD",
answer: ok(`${avdDirectory}/simlock_two.avd\r\nOK\r\n`),
runState: "stopped",
},
{
reported: "a vanished serial",
answer: { code: 1, stderr: "device 'emulator-5586' not found", stdout: "" },
runState: "transitioning",
},
])(
"gates running state, processes and erasable marks on path proof while retaining durable marks: $reported",
async ({ answer, runState }) => {
const filesystem = await androidFilesystem(
{ config: "simlock.mark=tok-123\n" },
new WorkingDirectoryFilesystem(avdDirectory),
);
filesystem.defineSymlink("/private/home", "/home");
filesystem.defineSymlink("/unreadable", avdDirectory);
filesystem.defineFailure("/unreadable/simlock_one.avd", "EACCES");
await filesystem.mkdirp(`${avdDirectory}/simlock_two.avd`);

for (const result of [ok(`${avdDirectory}/simlock_one.avd\r\nOK\r\n`), answer]) {
const runner = new ScriptedProcessRunner([
processResult(
binaries.adb,
["devices"],
"List of devices attached\nemulator-5586\tdevice\n",
),
processResult(
binaries.adb,
["-s", "emulator-5586", "shell", /getprop ro\.boot\.qemu\.avd_name/],
'simlock_one\n{"token":"tok-123"}',
),
{
match: { command: binaries.adb, args: ["-s", "emulator-5586", "emu", "avd", "path"] },
result,
},
]);
const driver = await createDriver(filesystem, runner);
const reality = await driver.listManaged();
const expectedState = result === answer ? runState : "running";
const running = expectedState === "running";

expect(reality.processes).toEqual(
running
? [expect.objectContaining({ address: "emulator-5586", deviceId: "simlock_one" })]
: [],
);
expect(reality.devices.find((device) => device.deviceId === "simlock_one")).toMatchObject({
runState: expectedState,
mark: {
durable: "tok-123",
erasable: running ? "tok-123" : undefined,
erasableReadable: running,
},
});
expect(
runner.calls.find((call) => call.args.slice(2).join(" ") === "emu avd path")?.options,
).toEqual({ env: scopedEnv, timeoutMs: 5_000 });
}
},
);

it("does not attribute an outside-root emulator to a root AVD with the same name (#261)", async () => {
const filesystem = await androidFilesystem();
const ownedPath = `${avdDirectory}/simlock_mine.avd`;
const foreignPath = `${home}/.android/avd/simlock_mine.avd`;
await filesystem.mkdirp(ownedPath);
await filesystem.writeFileAtomic(`${ownedPath}/config.ini`, "simlock.mark=owned-token\n");
await filesystem.mkdirp(foreignPath);

for (const path of [ownedPath, foreignPath]) {
const runner = answeringAvdPath(
new ScriptedProcessRunner([
processResult(
binaries.adb,
["devices"],
"List of devices attached\nemulator-5586\tdevice\n",
),
processResult(
binaries.adb,
["-s", "emulator-5586", "shell", /getprop ro\.boot\.qemu\.avd_name/],
'simlock_mine\n{"token":"owned-token"}',
),
]),
ok(`${path}\r\nOK\r\n`),
);
const driver = await createDriver(filesystem, runner);

const reality = await driver.listManaged();

expect
.soft(reality.processes, path)
.toEqual(
path === ownedPath
? [expect.objectContaining({ address: "emulator-5586", deviceId: "simlock_mine" })]
: [],
);
expect.soft(reality.devices, path).toEqual([
expect.objectContaining({
deviceId: "simlock_mine",
runState: path === ownedPath ? "running" : "stopped",
mark: {
durable: "owned-token",
erasable: path === ownedPath ? "owned-token" : undefined,
erasableReadable: path === ownedPath,
},
}),
]);
}
});

it("manages every AVD in its root, whatever the AVD is called", async () => {
const filesystem = await androidFilesystem();
await filesystem.mkdirp(`${avdDirectory}/a-name-nobody-prefixed.avd`);
Expand Down
32 changes: 20 additions & 12 deletions src/drivers/android/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ const PORT_POLL_INTERVAL_MS = 2_000;
* first and the read reports the platform's failure rather than its own timeout.
*/
const ADB_DEVICES_TIMEOUT_MS = 30_000;
const AVD_PATH_TIMEOUT_MS = 5_000;
const DEFAULT_ADB_SERVER_PORT = 5038;
// why: After this long without an answer from a serial, the emulator's own registration is
// assumed lost and Simlock re-sends it. Long enough that a normally-booting emulator has
Expand Down Expand Up @@ -1204,12 +1205,6 @@ export class AndroidDriver implements Driver {
return avdNames;
}

/**
* why: Serials attached in a settled `device` state can answer `getprop`, so they can be
* attributed to an AVD by name. A serial in any other adb state (offline, unauthorized,
* booting, ...) cannot answer `getprop` yet, so it cannot be attributed to an AVD name --
* `unattributableTransitionalSerial` records that this tick saw at least one such serial.
*/
async #scanAdbSerials(): Promise<{
readonly settledSerials: readonly string[];
readonly unattributableTransitionalSerial: boolean;
Expand Down Expand Up @@ -1265,11 +1260,17 @@ export class AndroidDriver implements Driver {
}
const [nameLine = "", ...markLines] = output.stdout.split(/\r?\n/);
const avdName = nameLine.trim();
// why: Root membership, never the name and never "our server can see it". `ADB_EMU=0`
// should mean this server only holds transports Simlock registered itself, but a
// device is Simlock's because of where its AVD lives -- ownership is proven, not
// inferred from who happens to be looking at it (safety rule 8).
if (!avdNamesInRoot.has(avdName)) continue;
let answered: string;
try {
answered = await this.#readAvdPath(candidate);
} catch {
// why: A serial can disappear after its shell answered; keep the observation
// inconclusive just as when it disappears before that shell call.
unreadableSerial = true;
continue;
}
if (!(await this.#sameDirectory(answered, `${this.#deviceRoot}/${avdName}.avd`))) continue;
runningByAvdName.add(avdName);
erasableMarkByAvdName.set(avdName, parseErasableMark(markLines.join("\n")));
const port = Number(candidate.slice("emulator-".length));
Expand Down Expand Up @@ -1930,8 +1931,7 @@ export class AndroidDriver implements Driver {
*/
async #confirmAvdAnswers(data: AndroidDriverData): Promise<void> {
const expected = `${this.#deviceRoot}/${data.avdName}.avd`;
const result = await this.#runOrThrow(this.#sdk.adb, ["-s", data.serial, "emu", "avd", "path"]);
const answered = answeredAvdPath(result.stdout);
const answered = await this.#readAvdPath(data.serial);
if (await this.#isOwnAvdPath(answered, expected)) {
return;
}
Expand All @@ -1940,6 +1940,13 @@ export class AndroidDriver implements Driver {
);
}

async #readAvdPath(serial: string): Promise<string> {
const result = await this.#runOrThrow(this.#sdk.adb, ["-s", serial, "emu", "avd", "path"], {
timeoutMs: AVD_PATH_TIMEOUT_MS,
});
return answeredAvdPath(result.stdout);
}

/**
* why: The gate before any emulator mutation (`emu kill`, snapshot load): asks the emulator on the
* serial for its AVD path, bounded by a timeout, on every call -- the answer is never kept,
Expand Down Expand Up @@ -1968,6 +1975,7 @@ export class AndroidDriver implements Driver {
}

async #sameDirectory(left: string, right: string): Promise<boolean> {
if (left === right) return true;
if (!isAbsolute(left)) return false;
try {
const [realLeft, realRight] = await Promise.all([
Expand Down
Loading