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
5 changes: 5 additions & 0 deletions .fallowrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,11 @@
"maxCrap": 80,
"reason": "The supervisor's test arranges a process table, a clock, a filesystem and a scripted runner in one helper so each of its cases reads as one claim; the helper is branching setup, not logic under test."
},
{
"files": ["src/drivers/android/screen/session.test.ts"],
"maxCrap": 45,
"reason": "The capture's `setup` builds both devices' worlds — two targets, a scripted runner, an adb server, a clock, a filesystem, an optional scripted screen answer — in one helper so each case reads as one claim; the branches are optional arrangement, not logic under test."
},
{
"files": ["e2e/fake-driver/fake-driver.ts"],
"maxCrap": 45,
Expand Down
11 changes: 7 additions & 4 deletions docs/CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -607,10 +607,13 @@ sends almost nothing. `capabilities.stream.fps` is a ceiling rather than a rate
reason. On a Mac an iOS capture costs about 50-80 MB of memory per device being
watched.

An iOS simulator's screen and an Android emulator's screen can be streamed. A
lease on a physical iPhone or Android phone is refused with
`STREAM_NOT_SUPPORTED`, naming that as the reason rather than failing for one
the reader has to guess.
An iOS simulator's screen, an Android emulator's screen and a physical
Android phone's screen can be streamed. A lease on a physical iPhone is
refused with `STREAM_NOT_SUPPORTED`, naming that as the reason rather than
failing for one the reader has to guess. A phone whose screen is off is
woken first; one that does not wake is refused with `STREAM_UNAVAILABLE` saying
to turn it on. While a phone streams, its stay-awake setting is raised so the
screen stays on as long as it charges, and put back when the stream ends.

- **iOS** needs the capture program `pnpm build` builds on a Mac with Xcode
selected. Without it an iOS stream is refused with
Expand Down
15 changes: 9 additions & 6 deletions docs/CONSOLE.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,12 +263,15 @@ The panel is on every lease's page, and streams wherever the worker the lease
runs on has screen streaming turned on (see [`capabilities.stream.enabled`](CONFIGURATION.md)).
Where it is off, the panel says so before you press anything, and the button
cannot be pressed; where the lease is on a device a screen cannot be
captured from — a physical iPhone or Android phone — it says that a live screen
comes only from a simulator or an emulator. Either way it starts nothing.

The first picture can take a while on a slow emulator. The panel waits up to 90
seconds for it, longer than a worker takes to give up, so a capture that cannot
start shows the worker's reason rather than a timeout.
captured from — a physical iPhone — it says that a live screen comes only from a
simulator, an emulator or a physical Android phone. Either way it starts nothing.

The first picture can take a while — on a slow emulator, or on a physical
Android phone, whose screen state and shared adb server are read before the
capture starts. The panel waits up to 200 seconds for it, longer than a worker
takes to give up, so a capture that cannot start shows the worker's reason
rather than a timeout. A phone whose screen is off is woken first; one that does
not wake is refused with a message that says so.

### Who holds a lease

Expand Down
6 changes: 4 additions & 2 deletions docs/HTTP-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -942,8 +942,10 @@ worth asking for twice rather than holding open in advance.
Authorization is the same as every other lease route: a token sees its own
leases, an operator sees any, and anything else is a `404`. `STREAM_NOT_SUPPORTED`
(415) means the device behind the lease can never produce a picture here — a
physical phone. `STREAM_UNAVAILABLE` (503) means it could but cannot now: a
capture program that is not installed, or a device that painted nothing within
physical iPhone. `STREAM_UNAVAILABLE` (503) means it could but cannot now: a
capture program that is not installed, a physical Android phone whose screen is
off and did not turn on when woken (a phone whose screen is off is woken first),
or a device that painted nothing within
30 seconds; asking again is the right move. A stream that stops receiving frames
for 30 seconds ends with an error rather than freezing on its last picture. `WORKER_UNREACHABLE` on
a gateway means the worker that holds the lease is gone.
Expand Down
199 changes: 196 additions & 3 deletions e2e/slow-android-physical.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ const APK = process.env["SIMLOCK_PHYSICAL_ANDROID_APK"];
const PROBE_INTERVAL_MS = 2_000;
const EXEC_TIMEOUT_MS = 5_000;
const MINUTE = 60_000;
const STREAM_OPEN_BOUND = 4 * MINUTE;
const KEY_FRAME_BOUND = 2 * MINUTE;
const AGENT = "phone-lane-android";
const TAG = { alive: 0x06, description: 0x01, keyframe: 0x02, delta: 0x03, meta: 0x05 } as const;

const missing =
SERIAL === undefined || SERIAL === ""
Expand All @@ -21,6 +24,11 @@ const missing =
? "SIMLOCK_PHYSICAL_ANDROID_APK"
: undefined;

interface Frame {
readonly tag: number;
readonly payload: Uint8Array;
}

interface Grant {
readonly device: { readonly driverDeviceId: string };
readonly environment: Record<string, string>;
Expand Down Expand Up @@ -69,12 +77,17 @@ async function serverPid(): Promise<string> {
return stdout.trim().split("\n")[0] ?? "";
}

async function rig(execTimeoutMs?: number): Promise<Rig> {
async function rig(options: { readonly execTimeoutMs?: number } = {}): Promise<Rig> {
const { env, port } = await withHttpDaemon((port) => ({
configOverrides: {
...(execTimeoutMs === undefined ? {} : { exec: { timeoutMs: execTimeoutMs } }),
...(options.execTimeoutMs === undefined
? {}
: { exec: { timeoutMs: options.execTimeoutMs } }),
health: { probeIntervalMs: PROBE_INTERVAL_MS, stableObservations: 2 },
http: { enabled: true, host: "127.0.0.1", port },
capabilities: {
stream: { bitrateKbps: 1500, enabled: true, fps: 30, maxDimension: 720 },
},
},
driver: "real",
}));
Expand Down Expand Up @@ -125,6 +138,66 @@ async function exec(daemon: Rig, leaseId: string, args: readonly string[]): Prom
return response.text();
}

async function within<T>(work: Promise<T>, bound: number, what: string): Promise<T> {
let timer: NodeJS.Timeout | undefined;
const stalled = new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error(`timed out after ${bound} ms waiting for ${what}`)),
bound,
);
});
try {
return await Promise.race([work, stalled]);
} finally {
clearTimeout(timer);
}
}

// why: the body is an endless stream, so this reads frames until it has what it came for and then
// lets go, rather than reading to an end that never comes.
async function readFrames(
body: ReadableStream<Uint8Array>,
enough: (frames: readonly Frame[]) => boolean,
whileOpen?: () => Promise<void>,
): Promise<Frame[]> {
const reader = body.getReader();
const frames: Frame[] = [];
let buffer = new Uint8Array(0);
try {
while (!enough(frames)) {
const step = await within(reader.read(), KEY_FRAME_BOUND, "the stream's frames");
if (step.done) break;
const joined = new Uint8Array(buffer.length + step.value.length);
joined.set(buffer);
joined.set(step.value, buffer.length);
buffer = joined;
while (buffer.length >= 5) {
const length = new DataView(buffer.buffer, buffer.byteOffset).getUint32(0);
if (buffer.length < 4 + length) break;
frames.push({ payload: buffer.slice(5, 4 + length), tag: buffer[4]! });
buffer = buffer.slice(4 + length);
}
}
// why: runs once the frames are in and before the stream is let go, so it sees the stream open.
await whileOpen?.();
} finally {
await reader.cancel().catch(() => undefined);
}
return frames;
}

async function streamOf(daemon: Rig, leaseId: string): Promise<Response> {
const response = await fetch(`${daemon.base}/v1/stream/leases/${encodeURIComponent(leaseId)}`, {
headers: daemon.auth,
// why: covers the ~185 s worst case of opening the stream, so a stall fails here naming its step.
signal: AbortSignal.timeout(STREAM_OPEN_BOUND),
});
// why: a 200 body is an endless stream, so its text is read only for a failure, never as an argument evaluated up front.
const detail = response.status === 200 ? "" : await response.text().catch(() => "");
expect(response.status, detail).toBe(200);
return response;
}

describe.skipIf(missing !== undefined)(
missing === undefined
? "Android physical phone (real adb)"
Expand Down Expand Up @@ -223,11 +296,131 @@ describe.skipIf(missing !== undefined)(
},
);

it(
"a lease on the phone streams a meta frame and a key frame over GET /v1/stream/leases/{leaseId}, and after the lease ends the phone holds no simlock-scrcpy jar and no scrcpy server process and the host keeps no capture shell, with the phone's screen off when the stream asks and its stay-awake setting put back within 10 s of the lease's end",
{ timeout: 10 * MINUTE },
async () => {
const stayOn = (
await adbOut(serial, ["shell", "settings", "get", "global", "stay_on_while_plugged_in"])
).trim();
const screenIsOff = async (): Promise<boolean> => {
const power = await adbOut(serial, ["shell", "dumpsys", "power"]);
const word = /^\s*mWakefulness=(\S+)\s*$/m.exec(power)?.[1];
return word === "Asleep" || word === "Dozing";
};
// why: the setting is put back whatever the case does, so a failure leaves the phone as it was found.
try {
// why: 2 is not scrcpy's 7, so a restore of the recorded value shows in the setting.
await adbOut(serial, [
"shell",
"settings",
"put",
"global",
"stay_on_while_plugged_in",
"2",
]);
await adbOut(serial, ["shell", "input", "keyevent", "KEYCODE_SLEEP"]);
await waitFor(screenIsOff, {
interval: 500,
label: "the phone's screen off before the stream asks",
timeout: 15_000,
});

const daemon = await rig();
await enroll(daemon.env, serial);
const grant = await leasePhysical(daemon.env);

const response = await streamOf(daemon, grant.lease.id);
if (response.body === null) throw new Error("the stream answered without a body");
const frames = await readFrames(
response.body,
(read) => read.some((frame) => frame.tag === TAG.keyframe),
async () => {
// why: 7 is scrcpy's stay_awake value; read while the stream body is still open, so the viewer's cancel cannot have put it back.
expect(
(
await adbOut(serial, [
"shell",
"settings",
"get",
"global",
"stay_on_while_plugged_in",
])
).trim(),
"stay_on_while_plugged_in while the stream is open",
).toBe("7");
// why: the lease ends with the stream still open, so the wait below cannot be met by the viewer's own cancel.
expect(await daemon.env.cli(["release", grant.lease.id])).toMatchObject({ code: 0 });
},
);

const tags = frames.map((frame) => frame.tag);
expect(tags).toContain(TAG.meta);
expect(tags).toContain(TAG.keyframe);
const meta = JSON.parse(new TextDecoder().decode(frames[0]!.payload)) as {
codec: string;
width: number;
height: number;
};
expect(meta.codec).toBe("h264");
expect(Math.max(meta.width, meta.height)).toBeGreaterThan(0);

await waitFor(
async () =>
(
await adbOut(serial, [
"shell",
"settings",
"get",
"global",
"stay_on_while_plugged_in",
])
).trim() === "2",
{
interval: 500,
label: "stay_on_while_plugged_in back at 2 after the lease ended",
timeout: 10_000,
},
);

await waitFor(
async () => {
const processes = await adbOut(serial, ["shell", "ps", "-A", "-o", "ARGS"]);
const files = await adbOut(serial, ["shell", "ls", "/data/local/tmp"]);
return (
!processes.includes("com.genymobile.scrcpy.Server") &&
!files.includes("simlock-scrcpy-")
);
},
{
interval: 500,
label: "no scrcpy server process and no pushed jar left on the phone",
timeout: 30_000,
},
);

const hostShells = await new Promise<string>((resolve) => {
execFile("pgrep", ["-fl", "[s]imlock-scrcpy-"], (_error, stdout) => resolve(stdout));
});
expect(hostShells, "a host adb shell for the capture outlived the lease").toBe("");
} finally {
await adbOut(serial, [
"shell",
"settings",
"put",
"global",
"stay_on_while_plugged_in",
stayOn,
]);
}
},
);

it(
"with a short exec.timeoutMs, a device.exec adb shell sleep 60 on the leased phone ends EXEC_TIMEOUT, and the adb server listening on 5037 still runs with the pid it had before the command",
{ timeout: 5 * MINUTE },
async () => {
const daemon = await rig(EXEC_TIMEOUT_MS);
const daemon = await rig({ execTimeoutMs: EXEC_TIMEOUT_MS });
await enroll(daemon.env, serial);
const grant = await leasePhysical(daemon.env);
const pidBefore = await serverPid();
Expand Down
Loading
Loading