The best way to control Claude Code, Codex and more from any computer or phone
fix(device): launch older Android emulators and report boot failures (#22012)
Yash Singh committed
Oct 19, 2026 at 19:03 UTC
d3dca44c2b5528f3f762ce988a7fdccfff9c8977
12 files changed
+574
-159
.macroscope/check-run-agents/effect-service-conventions.md
+1
@@ -57,6 +57,7 @@ Review changed TypeScript for the conventions below. They apply when a pull requ
57
- 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`.
58
- 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.
59
- 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.
61
- 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.
62
- 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.
63
- 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/DeviceService.test.ts
+107
-5
@@ -1,6 +1,7 @@
1
import { describe, expect, it } from "@effect/vitest";
2
import {
3
DEFAULT_SERVER_SETTINGS,
4
+ DeviceBootError,
5
DeviceId,
6
DeviceOperationError,
7
LOCAL_DEVICE_HOST_ID,
@@ -37,6 +38,8 @@ import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
38
import * as DeviceService from "./DeviceService.ts";
39
40
const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
41
+const decodeBootError = Schema.decodeUnknownSync(Schema.fromJsonString(DeviceBootError));
42
+const encodeBootError = Schema.encodeSync(Schema.fromJsonString(DeviceBootError));
43
44
const baseState: DeviceServiceState = {
45
hosts: [],
@@ -77,7 +80,7 @@ describe("DeviceService.stateStream", () => {
80
81
const fixture = Effect.fn("fixture")(function* (
82
onBoot: Effect.Effect<void> = Effect.void,
80
- bootError?: string,
83
+ bootError?: string | { error?: string; errors?: Array<{ message: string; error?: string }> },
84
failListAfterShutdown = false,
85
runtimeFailure?:
86
| NodeRuntimeUnavailableError
@@ -92,6 +95,7 @@ const fixture = Effect.fn("fixture")(function* (
95
const agentStops: string[] = [];
96
const requests: string[] = [];
97
const devices: Array<Omit<DeviceSummary, "hostId">> = [];
98
+ const discoveryErrors = yield* Ref.make<Array<{ message: string; error?: string }>>([]);
99
const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
100
let booted = false;
101
let shutDown = false;
@@ -212,7 +216,12 @@ const fixture = Effect.fn("fixture")(function* (
216
return HttpClientResponse.fromWeb(
217
request,
218
Response.json(
215
- bootError ? { ok: false, error: bootError } : { ok: true, serial: "emulator-5554" },
219
+ bootError
220
+ ? {
221
+ ok: false,
222
+ ...(typeof bootError === "string" ? { error: bootError } : bootError),
223
+ }
224
+ : { ok: true, serial: "emulator-5554" },
225
),
226
);
227
}
@@ -222,6 +231,7 @@ const fixture = Effect.fn("fixture")(function* (
231
return HttpClientResponse.fromWeb(
232
request,
233
Response.json({
234
+ errors: yield* Ref.get(discoveryErrors),
235
simulators: devices.filter((device) => device.platform === "ios"),
236
emulators: [
237
...devices.filter((device) => device.platform === "android"),
@@ -244,7 +254,17 @@ const fixture = Effect.fn("fixture")(function* (
254
),
255
),
256
);
247
- return { service, starts, agentStarts, agentStops, requests, settings, devices, encoderResult };
257
+ return {
258
+ service,
259
+ starts,
260
+ agentStarts,
261
+ agentStops,
262
+ requests,
263
+ settings,
264
+ devices,
265
+ encoderResult,
266
+ discoveryErrors,
267
+ };
268
});
269
270
describe("device setup consent", () => {
@@ -506,6 +526,60 @@ describe("device discovery after server restart", () => {
526
);
527
});
528
529
+const missingPlistMessage =
530
+ "[apple-utils] Failed to read CoreSimulator plist at /Users/test/Library/Developer/CoreSimulator/Devices/deleted-simulator/device.plist:";
531
+
532
+it.effect.each([
533
+ {
534
+ message: missingPlistMessage,
535
+ error: "Error: ENOENT: no such file or directory, open 'device.plist'",
536
+ ignored: true,
537
+ },
538
+ {
539
+ message: missingPlistMessage,
540
+ error: "Error: EACCES: permission denied, open 'device.plist'",
541
+ ignored: false,
542
+ },
543
+ { message: missingPlistMessage, error: undefined, ignored: false },
544
+ {
545
+ message: "[apple-utils] Failed to parse CoreSimulator device.plist:",
546
+ error: "Invalid XML",
547
+ ignored: false,
548
+ },
549
+ {
550
+ message: "[apple-utils] Failed to list devices:",
551
+ error: "Error: ENOENT: simctl missing",
552
+ ignored: false,
553
+ },
554
+])("handles discovery diagnostic: $error", ({ message, error, ignored }) =>
555
+ Effect.gen(function* () {
556
+ const { service, discoveryErrors } = yield* fixture();
557
+ yield* Ref.set(discoveryErrors, [{ message, ...(error ? { error } : {}) }]);
558
+ const state = yield* service.configure({ enabled: true });
559
+ expect(state.hostStatus).toBe("ready");
560
+ expect(state.devices.map((device) => device.id)).toEqual(["Pixel_API_35"]);
561
+ expect(state.hostStatusDetail).toBe(ignored ? undefined : message);
562
+ expect(state.hostStatuses.local?.detail).toBe(ignored ? undefined : message);
563
+ }).pipe(Effect.scoped),
564
+);
565
+
566
+it.effect("keeps other discovery warnings and clears them when only a deleted plist remains", () =>
567
+ Effect.gen(function* () {
568
+ const { service, discoveryErrors } = yield* fixture();
569
+ const missing = {
570
+ message: missingPlistMessage,
571
+ error: "Error: ENOENT: no such file or directory",
572
+ };
573
+ yield* Ref.set(discoveryErrors, [missing, { message: "Android discovery failed." }]);
574
+ const initial = yield* service.configure({ enabled: true });
575
+ expect(initial.hostStatusDetail).toBe("Android discovery failed.");
576
+ yield* Ref.set(discoveryErrors, [missing]);
577
+ const refreshed = yield* service.list;
578
+ expect(refreshed.hostStatusDetail).toBeUndefined();
579
+ expect(refreshed.hostStatuses.local?.detail).toBeUndefined();
580
+ }).pipe(Effect.scoped),
581
+);
582
+
583
it.effect.each([
584
{
585
diagnostic: "Insufficient disk space at /private/user/path",
@@ -518,7 +592,8 @@ it.effect.each([
592
message: "did not become ready in time",
593
},
594
{
521
- diagnostic: "Unexpected failure: secret-token",
595
+ diagnostic:
596
+ "The emulator process exited with code 1.\nTry manually: emulator -avd Pixel_API_35",
597
reason: "launch_failed",
598
message: "could not start",
599
},
@@ -535,7 +610,34 @@ it.effect.each([
610
.pipe(Effect.flip);
611
expect(error._tag).toBe("DeviceBootError");
612
expect(error.message).toContain(message);
538
- expect(error.message).not.toContain(diagnostic);
613
+ expect(error.message).toContain(diagnostic);
614
+ expect((yield* service.state).bootingDevices).toEqual([]);
615
+ }).pipe(Effect.scoped),
616
+);
617
+
618
+it.effect("includes nested hub boot diagnostics and bounds them to 2,000 characters", () =>
619
+ Effect.gen(function* () {
620
+ const diagnostic = "Error: emulator binary missing\n" + "diagnostic output\n".repeat(200);
621
+ const { service } = yield* fixture(Effect.void, {
622
+ error: "Failed to spawn emulator",
623
+ errors: [{ message: "Failed to launch emulator binary", error: diagnostic }],
624
+ });
625
+ yield* service.configure({ enabled: true });
626
+ const error = yield* service
627
+ .open({
628
+ threadId: ThreadId.make("nested-boot-failure"),
629
+ deviceId: "Pixel_API_35",
630
+ platform: "android",
631
+ })
632
+ .pipe(Effect.flip);
633
+ expect(error._tag).toBe("DeviceBootError");
634
+ if (error._tag !== "DeviceBootError") return;
635
+ const expected = `Failed to spawn emulator\n\nFailed to launch emulator binary\n\n${diagnostic}`;
636
+ expect(error.diagnostics).toBe(`${expected.slice(0, 1_999)}…`);
637
+ expect(error.diagnostics).toHaveLength(2_000);
638
+ expect(error.message).toContain(error.diagnostics);
639
+ const roundTrip = decodeBootError(encodeBootError(error));
640
+ expect(roundTrip.message).toBe(error.message);
641
expect((yield* service.state).bootingDevices).toEqual([]);
642
}).pipe(Effect.scoped),
643
);
apps/server/src/device/DeviceService.ts
+31
-4
@@ -96,13 +96,18 @@ const HubDevice = Schema.Struct({
96
const HubDeviceList = Schema.Struct({
97
simulators: Schema.Array(HubDevice),
98
emulators: Schema.Array(HubDevice),
99
- errors: Schema.optional(Schema.Array(Schema.Struct({ message: Schema.String }))),
99
+ errors: Schema.optional(
100
+ Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
101
+ ),
102
});
103
const HubActionResult = Schema.Struct({
104
ok: Schema.Boolean,
105
id: Schema.optional(Schema.String),
106
serial: Schema.optional(Schema.String),
107
error: Schema.optional(Schema.String),
108
+ errors: Schema.optional(
109
+ Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
110
+ ),
111
});
112
113
export interface DeviceScreenshot {
@@ -439,7 +444,16 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
444
}
445
}
446
}
442
- return { devices, detail: list.errors?.map((error) => error.message).join("\n") || undefined };
447
+ const warnings = list.errors?.filter(
448
+ (error) =>
449
+ // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
450
+ !(
451
+ error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
452
+ /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
453
+ /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
454
+ ),
455
+ );
456
+ return { devices, detail: warnings?.map((error) => error.message).join("\n") || undefined };
457
});
458
459
const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
@@ -630,16 +644,29 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
644
Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)),
645
);
646
if (!result.ok) {
647
+ // Keep the hub's launch command and nested failure available to agents for recovery.
648
+ const diagnostics = [
649
+ result.error,
650
+ ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
651
+ ]
652
+ .filter((text) => text?.trim())
653
+ .join("\n\n");
654
return yield* new DeviceBootError({
655
hostId: ready.hostId,
656
deviceId: device.id,
657
reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
637
- result.error ?? "",
658
+ diagnostics,
659
)
660
? "disk_space"
640
- : /timed? out|timeout/i.test(result.error ?? "")
661
+ : /timed? out|timeout/i.test(diagnostics)
662
? "timeout"
663
: "launch_failed",
664
+ ...(diagnostics
665
+ ? {
666
+ diagnostics:
667
+ diagnostics.length > 2_000 ? `${diagnostics.slice(0, 1_999)}…` : diagnostics,
668
+ }
669
+ : {}),
670
cause: result,
671
});
672
}
apps/server/src/device/LocalDeviceHost.test.ts
+67
-1
@@ -458,7 +458,73 @@ it.effect(
458
Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
459
);
460
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
+ }),
528
);
529
530
it.live("limits hub discovery to Android unless the host is a Mac", () =>
apps/server/src/device/LocalDeviceHost.ts
+36
@@ -208,6 +208,40 @@ const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
208
const env: NodeJS.ProcessEnv = { ...environment, FORCE_COLOR: "0", NO_COLOR: "1" };
209
const platform = yield* HostProcess.Platform;
210
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
+ }
245
if (platform === "linux" && env.XDG_RUNTIME_DIR === undefined && uid !== undefined) {
246
// SSH sessions may omit the directory where the emulator publishes its gRPC token.
247
const runtimeDir = `/run/user/${uid}`;
@@ -409,6 +443,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
443
stderr: "pipe",
444
env: yield* hubEnvironment(hostEnvironment).pipe(
445
Effect.provideService(FileSystem.FileSystem, fs),
446
+ Effect.provideService(Path.Path, path),
447
+ Effect.provideService(ProcessRunner.ProcessRunner, runner),
448
Effect.provideService(HostProcess.Platform, hostPlatform),
449
),
450
},
apps/server/src/device/sshDeviceScript.test.ts
+11
-1
@@ -56,6 +56,11 @@ describe("remote helper lifecycle", () => {
56
const bin = NodePath.join(home, "bin");
57
await NodeFSP.mkdir(bin);
58
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
+ );
64
const root = NodePath.join(home, ".t3/device");
65
const hubDir = NodePath.join(root, `tools/expo-device-hub@${DEVICE_HUB_VERSION}`);
66
const agentDir = NodePath.join(root, `tools/agent-device@${AGENT_DEVICE_VERSION}`);
@@ -73,7 +78,7 @@ describe("remote helper lifecycle", () => {
78
hub,
79
`import http from 'node:http'; import fs from 'node:fs';
80
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');`,
82
);
83
await NodeFSP.writeFile(
84
agent,
@@ -116,6 +121,8 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
121
HOME: home,
122
PATH: `${bin}:${process.env.PATH}`,
123
SERVE_EMU_FFMPEG: NodePath.join(home, "missing-ffmpeg"),
124
+ ANDROID_HOME: "",
125
+ EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: "-memory 4096",
126
},
127
});
128
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
154
expect(concurrent.hubPort).toBe(manual.hubPort);
155
expect(manual.daemonPort).toBeUndefined();
156
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");
160
// A hub started before discovery was filtered has no recorded platform.
161
const hubFile = NodePath.join(root, "hosts/one/hub.json");
162
const { platform: _platform, ...unfilteredHub } = JSON.parse(
apps/server/src/device/sshDeviceScript.ts
+11
-3
@@ -166,19 +166,27 @@ async function install(name, version, entry) {
166
const hubEntry = await install('expo-device-hub', hubVersion, 'dist/server/cli.mjs');
167
// Only a Mac can list Apple simulators. Recording the filter replaces hubs started without it.
168
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(' ');
177
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')) {
179
stopHub(hub);
180
for (let attempt = 0; attempt < 5; attempt++) {
181
const hubPort = await port();
182
const log = fs.openSync(path.join(state, 'hub.log'), 'a');
183
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' },
185
});
186
try { await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); }
187
finally { fs.closeSync(log); }
188
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 };
190
write(hubFile, hub);
191
const deadline = Date.now() + 30000;
192
let listening = false;
apps/server/src/mcp/McpDeviceToolkit.test.ts
+40
@@ -1,6 +1,7 @@
1
import { expect, it } from "@effect/vitest";
2
import * as NodeServices from "@effect/platform-node/NodeServices";
3
import {
4
+ DeviceBootError,
5
DeviceHostUnavailableError,
6
DeviceId,
7
EnvironmentId,
@@ -124,6 +125,45 @@ const layerTest = McpHttpServer.layerDeviceToolkit.pipe(
125
Layer.provide(NodeServices.layer),
126
);
127
128
+it.effect("returns the complete bounded launch diagnostics to the agent", () => {
129
+ const diagnostics =
130
+ "Emulator exited with code 1.\nTry manually: emulator -avd TestPhone\n" + "x".repeat(1_930);
131
+ const failure = new DeviceBootError({
132
+ hostId: "local",
133
+ deviceId: "UDID-1",
134
+ reason: "launch_failed",
135
+ diagnostics: diagnostics.slice(0, 2_000),
136
+ cause: { ok: false, error: diagnostics },
137
+ });
138
+ const failedDevices = Layer.mock(DeviceService.DeviceService)({
139
+ list: Effect.succeed(state),
140
+ agentTarget: () => Effect.succeed([]),
141
+ open: () => Effect.fail(failure),
142
+ });
143
+ return Effect.gen(function* () {
144
+ const server = yield* McpServer.McpServer;
145
+ const result = yield* server
146
+ .callTool({ name: "device_open", arguments: { platform: "ios" } })
147
+ .pipe(
148
+ Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
149
+ Effect.provideService(McpSchema.McpServerClient, client),
150
+ );
151
+ expect(result.isError).toBe(true);
152
+ expect(result.content).toEqual([{ type: "text", text: failure.message }]);
153
+ }).pipe(
154
+ Effect.scoped,
155
+ Effect.provide(
156
+ McpHttpServer.layerDeviceToolkit.pipe(
157
+ Layer.provideMerge(McpServer.McpServer.layer),
158
+ Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
159
+ Layer.provide(failedDevices),
160
+ Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-boot-error-test-" })),
161
+ Layer.provide(NodeServices.layer),
162
+ ),
163
+ ),
164
+ );
165
+});
166
+
167
it.effect("registers the device tools and returns the screenshot as image content", () =>
168
Effect.scoped(
169
Effect.gen(function* () {
apps/web/src/components/device/DevicePanel.browser.test.tsx
+60
-3
@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"
11
import type { RightPanelSurface } from "~/rightPanelStore";
12
13
import { DevicePanel } from "./DevicePanel";
14
+import "~/index.css";
15
16
type CommandResult =
17
| { _tag: "Success"; value: { hostId: string; deviceId: string } }
@@ -58,9 +59,10 @@ const deviceState: DeviceServiceState = {
59
hubBasePath: "/api/device-hub",
60
revision: 1,
61
};
62
+let currentState = deviceState;
63
vi.mock("~/state/device", () => ({
64
deviceEnvironment: { list: "list", open: "open", close: "close" },
63
- useDeviceState: () => ({ state: deviceState, loaded: true }),
65
+ useDeviceState: () => ({ state: currentState, loaded: true }),
66
}));
67
vi.mock("~/state/use-atom-command", () => ({
68
useAtomCommand: (command: string) =>
@@ -77,14 +79,15 @@ vi.mock("~/rightPanelStore", () => ({
79
},
80
}));
81
vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
80
-vi.mock("~/components/device/DeviceLoadingView", () => ({ DeviceLoadingView: () => null }));
82
vi.mock("~/components/device/DeviceWorkspace", () => ({
83
DeviceWorkspace: ({ onPowerOff }: { onPowerOff: () => void }) => (
84
<button onClick={onPowerOff}>Power off</button>
85
),
86
}));
87
vi.mock("~/components/preview/PreviewPanelShell", () => ({
87
- PreviewPanelShell: ({ children }: { children: ReactNode }) => children,
88
+ PreviewPanelShell: ({ children }: { children: ReactNode }) => (
89
+ <div className="flex h-full min-h-0 flex-col">{children}</div>
90
+ ),
91
}));
92
93
const threadA = {
@@ -142,8 +145,11 @@ const errors = () => container.querySelectorAll('[role="alert"]');
145
146
beforeEach(() => {
147
vi.resetAllMocks();
148
+ currentState = deviceState;
149
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
150
container = document.createElement("div");
151
+ container.style.width = "480px";
152
+ container.style.height = "800px";
153
document.body.append(container);
154
root = createRoot(container);
155
});
@@ -153,6 +159,57 @@ afterEach(async () => {
159
vi.unstubAllGlobals();
160
});
161
162
+describe("DevicePanel notices", () => {
163
+ it("keeps discovery warnings dismissed until the diagnostic or environment changes", async () => {
164
+ currentState = {
165
+ ...deviceState,
166
+ hostStatusDetail: "Could not read simulator usage timestamps.",
167
+ };
168
+ await show(threadA);
169
+ expect(errors()).toHaveLength(1);
170
+ expect(startButton()?.disabled).toBe(false);
171
+ await click(container.querySelector('[aria-label="Dismiss device warning"]'));
172
+ expect(errors()).toHaveLength(0);
173
+ await show(threadA);
174
+ expect(errors()).toHaveLength(0);
175
+
176
+ currentState = { ...currentState, hostStatusDetail: "A different discovery warning." };
177
+ await show(threadA);
178
+ expect(errors()).toHaveLength(1);
179
+ await click(container.querySelector('[aria-label="Dismiss device warning"]'));
180
+ await show(otherEnvironment);
181
+ expect(errors()).toHaveLength(1);
182
+ });
183
+
184
+ it("keeps the loading content centered when discovery and boot notices arrive or are dismissed", async () => {
185
+ const pick = deferred();
186
+ mocks.open.mockReturnValue(pick.promise);
187
+ await show(threadA);
188
+ await click(startButton());
189
+ const loadingBounds = () =>
190
+ container
191
+ .querySelector('[aria-label="Step 1 of 2: open device"]')!
192
+ .parentElement!.getBoundingClientRect();
193
+ const before = loadingBounds();
194
+ const panel = container.getBoundingClientRect();
195
+ expect(before.height).toBeGreaterThan(0);
196
+ expect(before.top + before.height / 2).toBeCloseTo(panel.top + panel.height / 2, 0);
197
+
198
+ currentState = {
199
+ ...deviceState,
200
+ hostStatusDetail: "Could not read CoreSimulator plist.\n".repeat(8),
201
+ bootingDevices: [{ ...phone, threadId: threadA.threadId }],
202
+ };
203
+ await show(threadA);
204
+ expect(loadingBounds().top).toBe(before.top);
205
+ expect(loadingBounds().left).toBe(before.left);
206
+ await click(container.querySelector('[aria-label="Dismiss device warning"]'));
207
+ expect(loadingBounds().top).toBe(before.top);
208
+ expect(loadingBounds().left).toBe(before.left);
209
+ await act(async () => pick.settle(failed));
210
+ });
211
+});
212
+
213
describe("DevicePanel thread switches", () => {
214
it.each(switches)("does not carry a pending or failed pick to %s", async (_, target) => {
215
const pick = deferred();
apps/web/src/components/device/DevicePanel.tsx
+204
-141
@@ -5,13 +5,13 @@ import type {
5
DeviceSummary,
6
ScopedThreadRef,
7
} from "@t3tools/contracts";
8
-import { Smartphone, X } from "lucide-react";
9
-import { useEffect, useState } from "react";
8
+import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react";
9
+import { type ReactNode, useEffect, useState } from "react";
10
11
import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
12
import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";
13
import { Button } from "~/components/ui/button";
14
-import { DiscoveryList, DiscoveryListRow } from "~/components/ui/discovery-list";
14
+import { DiscoveryList } from "~/components/ui/discovery-list";
15
import { Dialog } from "~/components/ui/dialog";
16
import { WizardPopup } from "~/components/ui/wizard";
17
import { Spinner } from "~/components/ui/spinner";
@@ -150,6 +150,14 @@ export function DevicePanel(props: {
150
const bootingDevices =
151
state.bootingDevices?.filter((device) => device.threadId === threadId) ?? [];
152
const { ready: hostReady, busy: hostBusy } = deviceHubReadiness(state);
153
+ const loading = !activeDevice && (pendingDevice !== null || hostBusy || !loaded);
154
+ const diagnostics = state.hosts.flatMap((host) => {
155
+ const status = state.hostStatuses[host.id];
156
+ const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined);
157
+ return detail && (status?.status ?? state.hostStatus) === "ready"
158
+ ? [{ hostId: host.id, label: host.label, detail }]
159
+ : [];
160
+ });
161
const unavailablePlatforms = state.hosts.flatMap((host) =>
162
host.platforms
163
.filter((platform) => !platform.available)
@@ -173,157 +181,212 @@ export function DevicePanel(props: {
181
182
return (
183
<PreviewPanelShell mode={props.mode}>
176
- {hostReady && !activeDevice && state.hostStatusDetail ? (
184
+ <div className="relative flex min-h-0 flex-1 flex-col">
185
<div
178
- role="status"
179
- aria-label="Device host diagnostics"
180
- tabIndex={0}
181
- className="max-h-32 shrink-0 overflow-y-auto whitespace-pre-line break-words border-b px-3 py-2 text-xs text-muted-foreground"
186
+ className={cn(
187
+ "shrink-0 bg-background",
188
+ loading && "absolute inset-x-0 top-0 z-10 max-h-[40%] overflow-y-auto",
189
+ )}
190
>
183
- {state.hostStatusDetail}
184
- </div>
185
- ) : null}
186
- <DeviceHostUpdates state={state} environmentId={environmentId} />
187
- {bootingDevices.length > 0 ? (
188
- <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
189
- Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a minute.
190
- </div>
191
- ) : null}
192
- {operationError ? (
193
- <div
194
- role="alert"
195
- className="flex items-start gap-2 border-b bg-destructive/5 px-3 py-2 text-xs text-destructive"
196
- >
197
- <p className="min-w-0 flex-1 whitespace-pre-wrap break-words">{operationError}</p>
198
- <Button
199
- size="icon-xs"
200
- variant="ghost"
201
- aria-label="Dismiss device error"
202
- onClick={() => setOperation(null)}
203
- >
204
- <X className="size-3" />
205
- </Button>
191
+ <div hidden={!!activeDevice}>
192
+ {diagnostics.map((diagnostic) => (
193
+ <DeviceDiscoveryWarning
194
+ key={`${environmentId}\u0000${diagnostic.hostId}\u0000${diagnostic.detail}`}
195
+ label={diagnostic.label}
196
+ detail={diagnostic.detail}
197
+ />
198
+ ))}
199
+ </div>
200
+ <DeviceHostUpdates state={state} environmentId={environmentId} />
201
+ {bootingDevices.length > 0 ? (
202
+ <div role="status" className="border-b px-3 py-2 text-xs text-muted-foreground">
203
+ Starting {bootingDevices.map((device) => device.name).join(", ")}… This can take a
204
+ minute.
205
+ </div>
206
+ ) : null}
207
+ {operationError ? (
208
+ <DeviceNotice tone="error" onDismiss={() => setOperation(null)}>
209
+ {operationError}
210
+ </DeviceNotice>
211
+ ) : null}
212
</div>
207
- ) : null}
208
- <div className="@container relative flex min-h-0 flex-1">
209
- {activeDevice && activeSession ? (
210
- <DeviceWorkspace
211
- key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
212
- environmentId={environmentId}
213
- device={activeDevice}
214
- hostLabel={
215
- state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"
216
- }
217
- hostDiagnostics={state.hostStatusDetail}
218
- visible={props.visible}
219
- onFloat={floatActive}
220
- onClose={() => closeActive(false)}
221
- onPowerOff={() => closeActive(true)}
222
- />
223
- ) : pendingDevice || hostBusy || !loaded ? (
224
- <DeviceLoadingView
225
- name={pendingDevice?.name ?? "Devices"}
226
- description={
227
- pendingDevice
228
- ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
229
- : ""
230
- }
231
- stage="opening"
232
- message={
233
- pendingDevice
234
- ? pendingDevice.booted
235
- ? "Opening device…"
236
- : "Starting device…"
237
- : state.hostStatus === "installing"
238
- ? (state.hostStatusDetail ?? "Installing device support…")
239
- : "Finding devices…"
240
- }
241
- />
242
- ) : (
243
- <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
244
- <div
245
- className={cn(
246
- "mx-auto flex w-full max-w-xl flex-col gap-6",
247
- grouped.length === 0 && "my-auto items-center text-center",
248
- )}
249
- >
250
- {grouped.length === 0 ? (
251
- <>
252
- <Smartphone className="size-6 opacity-60" />
253
- <p
254
- className="max-h-32 w-full max-w-sm overflow-y-auto whitespace-pre-line break-words"
255
- tabIndex={state.hostStatus === "failed" ? 0 : undefined}
256
- >
257
- {state.hostStatus === "failed"
258
- ? (state.hostStatusDetail ?? "The device hub failed to start.")
259
- : "No simulators or emulators were found on this environment."}
260
- </p>
261
- </>
262
- ) : null}
263
- {hostReady && grouped.length > 0 ? (
264
- <div className="w-full space-y-6 text-left">
265
- {grouped.map((group) => (
266
- <section key={group.platform} className="space-y-3">
267
- <div className="flex items-center gap-2 text-sm text-muted-foreground">
268
- <Smartphone className="size-4 shrink-0" />
269
- <h3 className="font-medium">{platformLabel(group.platform)}</h3>
270
- </div>
271
- <DiscoveryList>
272
- {group.devices.map((device) => (
273
- <DiscoveryListRow
274
- key={deviceKey(device)}
275
- icon={
213
+ <div className="@container relative flex min-h-0 flex-1">
214
+ {activeDevice && activeSession ? (
215
+ <DeviceWorkspace
216
+ key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
217
+ environmentId={environmentId}
218
+ device={activeDevice}
219
+ hostLabel={
220
+ state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"
221
+ }
222
+ hostDiagnostics={
223
+ diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail
224
+ }
225
+ visible={props.visible}
226
+ onFloat={floatActive}
227
+ onClose={() => closeActive(false)}
228
+ onPowerOff={() => closeActive(true)}
229
+ />
230
+ ) : loading ? (
231
+ <DeviceLoadingView
232
+ name={pendingDevice?.name ?? "Devices"}
233
+ description={
234
+ pendingDevice
235
+ ? `${state.hosts.find((host) => host.id === pendingDevice.hostId)?.label ?? "Device host"} · ${pendingDevice.version}`
236
+ : ""
237
+ }
238
+ stage="opening"
239
+ message={
240
+ pendingDevice
241
+ ? pendingDevice.booted
242
+ ? "Opening device…"
243
+ : "Starting device…"
244
+ : state.hostStatus === "installing"
245
+ ? (state.hostStatusDetail ?? "Installing device support…")
246
+ : "Finding devices…"
247
+ }
248
+ />
249
+ ) : (
250
+ <div className="scrollbar-gutter-both flex size-full flex-col overflow-y-auto px-5 py-8 text-sm text-muted-foreground">
251
+ <div
252
+ className={cn(
253
+ "mx-auto flex w-full max-w-xl flex-col gap-6",
254
+ grouped.length === 0 && "my-auto items-center text-center",
255
+ )}
256
+ >
257
+ {grouped.length === 0 ? (
258
+ <>
259
+ <Smartphone className="size-6 opacity-60" />
260
+ <p
261
+ className="max-h-32 w-full max-w-sm overflow-y-auto whitespace-pre-line break-words"
262
+ tabIndex={state.hostStatus === "failed" ? 0 : undefined}
263
+ >
264
+ {state.hostStatus === "failed"
265
+ ? (state.hostStatusDetail ?? "The device hub failed to start.")
266
+ : "No simulators or emulators were found on this environment."}
267
+ </p>
268
+ </>
269
+ ) : null}
270
+ {hostReady && grouped.length > 0 ? (
271
+ <div className="w-full space-y-6 text-left">
272
+ {grouped.map((group) => (
273
+ <section key={group.platform} className="space-y-3">
274
+ <div className="flex items-center gap-2 text-sm text-muted-foreground">
275
+ <Smartphone className="size-4 shrink-0" />
276
+ <h3 className="font-medium">{platformLabel(group.platform)}</h3>
277
+ </div>
278
+ <DiscoveryList>
279
+ {group.devices.map((device) => (
280
+ <div
281
+ key={deviceKey(device)}
282
+ className="flex items-center gap-3 px-3 py-3"
283
+ >
284
<span className="grid size-8 shrink-0 place-items-center rounded-md border border-border/60">
285
<Smartphone className="size-4" />
286
</span>
279
- }
280
- title={device.name}
281
- description={`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
282
- disabled={pendingDeviceKey !== null}
283
- aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
284
- onClick={() => void selectDevice(deviceKey(device))}
285
- action={
286
- pendingDeviceKey === deviceKey(device) ? (
287
- <Spinner size="xs" />
288
- ) : (
289
- <span className="text-xs text-muted-foreground">
290
- {device.booted ? "Open" : "Start"}
287
+ <div className="flex min-w-0 flex-1 flex-col">
288
+ <span className="truncate text-sm font-medium text-foreground">
289
+ {device.name}
290
+ </span>
291
+ <span className="truncate text-xs text-muted-foreground">
292
+ {`${state.hosts.find((host) => host.id === device.hostId)?.label} · ${device.version} · ${device.booted ? "Running" : "Stopped"}`}
293
</span>
292
- )
293
- }
294
- />
295
- ))}
296
- </DiscoveryList>
297
- </section>
298
- ))}
299
- </div>
300
- ) : null}
301
- {hostReady &&
302
- !state.devices.some((device) => device.platform === "android") &&
303
- !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
304
- <p className="max-w-sm text-xs">
305
- No Android virtual devices found. Create one in Android Studio's Device Manager,
306
- then refresh.
307
- </p>
308
- ) : null}
309
- {loaded && !hostBusy ? (
310
- <Button
311
- className={grouped.length > 0 ? "self-start" : "self-center"}
312
- variant={grouped.length > 0 ? "ghost" : "outline"}
313
- size="sm"
314
- onClick={() => void list({ environmentId, input: {} })}
315
- >
316
- Refresh devices
317
- </Button>
318
- ) : null}
294
+ </div>
295
+ <Button
296
+ variant="outline"
297
+ size="sm"
298
+ disabled={pendingDeviceKey !== null}
299
+ aria-label={`${device.booted ? "Open" : "Start"} ${device.name}`}
300
+ onClick={() => void selectDevice(deviceKey(device))}
301
+ >
302
+ {pendingDeviceKey === deviceKey(device) ? (
303
+ <Spinner size="xs" />
304
+ ) : device.booted ? (
305
+ <ArrowUpRight />
306
+ ) : (
307
+ <Play />
308
+ )}
309
+ {device.booted ? "Open" : "Start"}
310
+ </Button>
311
+ </div>
312
+ ))}
313
+ </DiscoveryList>
314
+ </section>
315
+ ))}
316
+ </div>
317
+ ) : null}
318
+ {hostReady &&
319
+ !state.devices.some((device) => device.platform === "android") &&
320
+ !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
321
+ <p className="max-w-sm text-xs">
322
+ No Android virtual devices found. Create one in Android Studio's Device Manager,
323
+ then refresh.
324
+ </p>
325
+ ) : null}
326
+ {loaded && !hostBusy ? (
327
+ <Button
328
+ className={grouped.length > 0 ? "self-start" : "self-center"}
329
+ variant="outline"
330
+ size="sm"
331
+ onClick={() => void list({ environmentId, input: {} })}
332
+ >
333
+ Refresh devices
334
+ </Button>
335
+ ) : null}
336
+ </div>
337
</div>
320
- </div>
321
- )}
338
+ )}
339
+ </div>
340
</div>
341
</PreviewPanelShell>
342
);
343
}
344
345
+function DeviceNotice(props: {
346
+ readonly tone: "warning" | "error";
347
+ readonly onDismiss: () => void;
348
+ readonly children: ReactNode;
349
+}) {
350
+ return (
351
+ <div
352
+ role="alert"
353
+ className={cn(
354
+ "flex items-start gap-2 border-b px-3 py-2 text-xs",
355
+ props.tone === "warning"
356
+ ? "bg-warning-surface text-warning-foreground"
357
+ : "bg-destructive/5 text-destructive",
358
+ )}
359
+ >
360
+ <CircleAlert className="mt-1 size-3.5 shrink-0" />
361
+ <div
362
+ className="max-h-32 min-w-0 flex-1 overflow-y-auto whitespace-pre-wrap break-words"
363
+ tabIndex={0}
364
+ >
365
+ {props.children}
366
+ </div>
367
+ <Button
368
+ size="icon-xs"
369
+ variant="ghost"
370
+ aria-label={props.tone === "warning" ? "Dismiss device warning" : "Dismiss device error"}
371
+ onClick={props.onDismiss}
372
+ >
373
+ <X />
374
+ </Button>
375
+ </div>
376
+ );
377
+}
378
+
379
+function DeviceDiscoveryWarning(props: { readonly label: string; readonly detail: string }) {
380
+ const [dismissed, setDismissed] = useState(false);
381
+ if (dismissed) return null;
382
+ return (
383
+ <DeviceNotice tone="warning" onDismiss={() => setDismissed(true)}>
384
+ <p className="font-medium">Device discovery warning · {props.label}</p>
385
+ {props.detail}
386
+ </DeviceNotice>
387
+ );
388
+}
389
+
390
function groupDevices(state: DeviceServiceState) {
391
const groups: Array<{ platform: DevicePlatform; devices: DeviceSummary[] }> = [];
392
for (const platform of ["ios", "android"] as const) {
docs/internals/effect-services.md
+3
@@ -114,6 +114,9 @@ optional-service layer. Don't route around the layer with an imperative runtime.
114
- **Safe values.** Attributes and log annotations stay bounded: no raw payloads, command arguments
115
or output, signed URLs, credentials, query strings, or arbitrary defect text. The exact value
116
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.
120
- **Translation.** Construct the error where the failure happens, and map it to a transport error
121
only in the transport. A translation boundary passes through domain errors already in the target
122
channel and wraps only unknown or lower-level failures. Map each failure where its context is
packages/contracts/src/device.ts
+3
-1
@@ -354,6 +354,7 @@ export class DeviceBootError extends Schema.TaggedError<DeviceBootError>()("Devi
354
hostId: DeviceHostId,
355
deviceId: DeviceId,
356
reason: Schema.Literals(["disk_space", "timeout", "launch_failed"]),
357
+ diagnostics: Schema.optional(Schema.String.check(Schema.isMaxLength(2_000))),
358
cause: Schema.Defect(),
359
}) {
360
override get message(): string {
@@ -363,7 +364,8 @@ export class DeviceBootError extends Schema.TaggedError<DeviceBootError>()("Devi
364
launch_failed:
365
"The simulator or emulator could not start. Check its configuration on the environment server.",
366
}[this.reason];
366
- return `Device ${this.deviceId} failed to boot: ${explanation}`;
367
+ const summary = `Device ${this.deviceId} failed to boot: ${explanation}`;
368
+ return this.diagnostics ? `${summary}\n\n${this.diagnostics}` : summary;
369
}
370
}
371