Skip to content

Commit 5cb70ee

Browse files
committed
fix(server): configure cameras for older Android emulators
1 parent 3feaf42 commit 5cb70ee

6 files changed

Lines changed: 129 additions & 5 deletions

File tree

‎.macroscope/check-run-agents/effect-service-conventions.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ Review changed TypeScript for the conventions below. They apply when a pull requ
5757
- Define service failures with `Schema.TaggedError` and structured attributes: operation or stage, resource path or entity identifier, normalized category or status. Derive `message` from those attributes only. Never derive it from `cause`, `cause.message`, or a stringified defect, and do not add a `detail` field that copies `cause.message`.
5858
- When wrapping a real failure, keep the immediate underlying error as `cause` so the chain and stack survive. Make `cause` required if every construction wraps a failure. Pure validation or domain errors created without an underlying failure need no cause.
5959
- Keep attributes and log annotations safe and bounded: no raw wire payloads, command arguments or output, signed URLs, credentials, query strings, or arbitrary defect text. Preserve the exact value only as `cause`; expose normalized categories, lengths, counts, and safe URL protocol or hostname where useful.
60+
The documented exception is `DeviceBootError.diagnostics`: device hub launch commands and failure text are intentionally exposed to authorized device users and agents, capped at 2,000 characters and included in the error message. Do not apply this exception to other service errors.
6061
- At a translation boundary, pass through an already structured domain error when it is part of the target error channel; wrap only unknown or lower-level failures. Map failures where the context is known instead of wrapping a whole multi-step pipeline in one generic error.
6162
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Split into separate error classes when a discriminator drives caller control flow or the user-facing message; a discriminator used only for diagnostics may stay a field. Caller-visible messages exposed through HTTP, RPC, persisted state, or UI are behavior and must survive a structural refactor.
6263
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`. Construct the error at the failure boundary. Keep a mapper only when it performs real normalization, passes through domain errors, or adds reusable context; when such a mapper belongs to the target error type, prefer a static factory on that class.

‎apps/server/src/device/LocalDeviceHost.test.ts‎

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,73 @@ it.effect(
458458
Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
459459
);
460460
expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
461-
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
461+
}).pipe(
462+
Effect.scoped,
463+
Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
464+
),
465+
);
466+
467+
it.effect.each([
468+
{
469+
name: "old SDK",
470+
front: "emulated webcam<N> none",
471+
back: "emulated virtualscene none",
472+
code: 0,
473+
extra: undefined,
474+
expected: "-camera-front emulated -camera-back emulated",
475+
},
476+
{
477+
name: "imagefile-capable SDK",
478+
front: "emulated imagefile:<path> none",
479+
back: "emulated imagefile:<path> none",
480+
code: 0,
481+
extra: undefined,
482+
expected: undefined,
483+
},
484+
{
485+
name: "user overrides",
486+
front: "emulated none",
487+
back: "emulated none",
488+
code: 0,
489+
extra: "-memory 4096 -camera-front none",
490+
expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
491+
},
492+
{
493+
name: "different camera capabilities",
494+
front: "emulated none",
495+
back: "emulated imagefile:<path> none",
496+
code: 0,
497+
extra: undefined,
498+
expected: "-camera-front emulated",
499+
},
500+
{
501+
name: "failed help probe",
502+
front: "emulated none",
503+
back: "emulated none",
504+
code: 1,
505+
extra: undefined,
506+
expected: undefined,
507+
},
508+
])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
509+
Effect.gen(function* () {
510+
const result = yield* LocalDeviceHost.__testing
511+
.hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
512+
.pipe(
513+
Effect.provideService(HostProcess.Platform, "darwin"),
514+
Effect.provideService(HostProcess.UserId, 1000),
515+
Effect.provideService(ProcessRunner.ProcessRunner, {
516+
run: (input) => {
517+
expect(input.command).toBe("/sdk/emulator/emulator");
518+
expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
519+
return Effect.succeed(
520+
processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
521+
);
522+
},
523+
}),
524+
Effect.provide(NodeServices.layer),
525+
);
526+
expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
527+
}),
462528
);
463529

464530
it.live("limits hub discovery to Android unless the host is a Mac", () =>

‎apps/server/src/device/LocalDeviceHost.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,40 @@ const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
208208
const env: NodeJS.ProcessEnv = { ...environment, FORCE_COLOR: "0", NO_COLOR: "1" };
209209
const platform = yield* HostProcess.Platform;
210210
const uid = yield* HostProcess.UserId;
211+
if (env.ANDROID_HOME) {
212+
const path = yield* Path.Path;
213+
const runner = yield* ProcessRunner.ProcessRunner;
214+
const emulator = path.join(
215+
env.ANDROID_HOME,
216+
"emulator",
217+
platform === "win32" ? "emulator.exe" : "emulator",
218+
);
219+
const cameraArgs = yield* Effect.forEach(["front", "back"], (facing) =>
220+
runner
221+
.run({
222+
command: emulator,
223+
args: [`-help-camera-${facing}`],
224+
env,
225+
timeout: Duration.seconds(5),
226+
})
227+
.pipe(
228+
Effect.map((result) => {
229+
const help = `${result.stdout}\n${result.stderr}`;
230+
// The hub wires imagefile cameras unconditionally; older SDK emulators reject that mode.
231+
return result.code === 0 && /\bemulated\b/.test(help) && !/\bimagefile\b/.test(help)
232+
? `-camera-${facing} emulated`
233+
: "";
234+
}),
235+
Effect.orElseSucceed(() => ""),
236+
),
237+
);
238+
const overrides = cameraArgs.filter(Boolean).join(" ");
239+
if (overrides) {
240+
env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS = [overrides, env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS]
241+
.filter(Boolean)
242+
.join(" ");
243+
}
244+
}
211245
if (platform === "linux" && env.XDG_RUNTIME_DIR === undefined && uid !== undefined) {
212246
// SSH sessions may omit the directory where the emulator publishes its gRPC token.
213247
const runtimeDir = `/run/user/${uid}`;
@@ -409,6 +443,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
409443
stderr: "pipe",
410444
env: yield* hubEnvironment(hostEnvironment).pipe(
411445
Effect.provideService(FileSystem.FileSystem, fs),
446+
Effect.provideService(Path.Path, path),
447+
Effect.provideService(ProcessRunner.ProcessRunner, runner),
412448
Effect.provideService(HostProcess.Platform, hostPlatform),
413449
),
414450
},

‎apps/server/src/device/sshDeviceScript.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,11 @@ describe("remote helper lifecycle", () => {
5656
const bin = NodePath.join(home, "bin");
5757
await NodeFSP.mkdir(bin);
5858
await NodeFSP.writeFile(NodePath.join(bin, "adb"), "#!/bin/sh\nexit 0\n", { mode: 0o755 });
59+
await NodeFSP.writeFile(
60+
NodePath.join(bin, "emulator"),
61+
"#!/bin/sh\nprintf 'emulated webcam<N> none\\n' >&2\n",
62+
{ mode: 0o755 },
63+
);
5964
const root = NodePath.join(home, ".t3/device");
6065
const hubDir = NodePath.join(root, `tools/expo-device-hub@${DEVICE_HUB_VERSION}`);
6166
const agentDir = NodePath.join(root, `tools/agent-device@${AGENT_DEVICE_VERSION}`);
@@ -73,7 +78,7 @@ describe("remote helper lifecycle", () => {
7378
hub,
7479
`import http from 'node:http'; import fs from 'node:fs';
7580
if(fs.existsSync('fail-start-once')) {fs.unlinkSync('fail-start-once');process.exit(1);}
76-
const args=process.argv.slice(2); fs.writeFileSync('hub-args.json',JSON.stringify(args)); http.createServer((req,res)=>{res.statusCode=fs.existsSync('unhealthy-'+process.pid)?503:200;res.end('ok');}).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
81+
const args=process.argv.slice(2); fs.writeFileSync('hub-args.json',JSON.stringify(args)); fs.writeFileSync('hub-camera-args',process.env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS || ''); http.createServer((req,res)=>{res.statusCode=fs.existsSync('unhealthy-'+process.pid)?503:200;res.end('ok');}).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
7782
);
7883
await NodeFSP.writeFile(
7984
agent,
@@ -116,6 +121,8 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
116121
HOME: home,
117122
PATH: `${bin}:${process.env.PATH}`,
118123
SERVE_EMU_FFMPEG: NodePath.join(home, "missing-ffmpeg"),
124+
ANDROID_HOME: "",
125+
EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: "-memory 4096",
119126
},
120127
});
121128
return result.stdout ? JSON.parse(result.stdout) : null;
@@ -147,6 +154,9 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
147154
expect(concurrent.hubPort).toBe(manual.hubPort);
148155
expect(manual.daemonPort).toBeUndefined();
149156
expect((await hubArgs("one")).slice(-2)).toEqual(["--platform", "android"]);
157+
expect(
158+
await NodeFSP.readFile(NodePath.join(root, "hosts/one/hub-camera-args"), "utf8"),
159+
).toBe("-camera-front emulated -camera-back emulated -memory 4096");
150160
// A hub started before discovery was filtered has no recorded platform.
151161
const hubFile = NodePath.join(root, "hosts/one/hub.json");
152162
const { platform: _platform, ...unfilteredHub } = JSON.parse(

‎apps/server/src/device/sshDeviceScript.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -166,19 +166,27 @@ async function install(name, version, entry) {
166166
const hubEntry = await install('expo-device-hub', hubVersion, 'dist/server/cli.mjs');
167167
// Only a Mac can list Apple simulators. Recording the filter replaces hubs started without it.
168168
const hubPlatform = process.platform === 'darwin' ? undefined : 'android';
169+
const cameraArgs = android ? ['front', 'back'].flatMap(facing => {
170+
const emulator = process.env.ANDROID_HOME ? path.join(process.env.ANDROID_HOME, 'emulator', 'emulator') : 'emulator';
171+
const help = run(emulator, ['-help-camera-' + facing], { timeout: 5000 });
172+
const text = (help.stdout || '') + '\n' + (help.stderr || '');
173+
// The hub's imagefile camera mode is not supported by every installed SDK emulator.
174+
return help.status === 0 && /\bemulated\b/.test(text) && !/\bimagefile\b/.test(text) ? ['-camera-' + facing, 'emulated'] : [];
175+
}) : [];
176+
const emulatorExtraArgs = [cameraArgs.join(' '), process.env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS].filter(Boolean).join(' ');
169177
let hub = read(hubFile);
170-
if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || !await healthy(hub.port, '/readyz')) {
178+
if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || hub.emulatorExtraArgs !== emulatorExtraArgs || !await healthy(hub.port, '/readyz')) {
171179
stopHub(hub);
172180
for (let attempt = 0; attempt < 5; attempt++) {
173181
const hubPort = await port();
174182
const log = fs.openSync(path.join(state, 'hub.log'), 'a');
175183
const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], {
176-
cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },
184+
cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: emulatorExtraArgs, FORCE_COLOR: '0', NO_COLOR: '1' },
177185
});
178186
try { await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); }
179187
finally { fs.closeSync(log); }
180188
child.unref();
181-
hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry, platform: hubPlatform };
189+
hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry, platform: hubPlatform, emulatorExtraArgs };
182190
write(hubFile, hub);
183191
const deadline = Date.now() + 30000;
184192
let listening = false;

‎docs/internals/effect-services.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,9 @@ optional-service layer. Don't route around the layer with an imperative runtime.
114114
- **Safe values.** Attributes and log annotations stay bounded: no raw payloads, command arguments
115115
or output, signed URLs, credentials, query strings, or arbitrary defect text. The exact value
116116
lives only in `cause`. Expose a category, length, count, or a URL's protocol and host instead.
117+
`DeviceBootError.diagnostics` is a deliberate exception: authorized device users and agents
118+
need the device hub's launch command and failure text to diagnose host setup. It is capped at
119+
2,000 characters and included in the error message; other service errors keep the rule above.
117120
- **Translation.** Construct the error where the failure happens, and map it to a transport error
118121
only in the transport. A translation boundary passes through domain errors already in the target
119122
channel and wraps only unknown or lower-level failures. Map each failure where its context is

0 commit comments

Comments
 (0)