@devries-cameron20 / t3code Mirror · read-only / commits / 30d0138540
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

fix(devices): retain inventory when AVD enumeration fails (#19974)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Luís Miguel committed Oct 20, 2026 at 05:59 UTC 30d0138540bfd03cbca1570d6136eb1ab4ffaab3
8 files changed +171 -23
apps/server/src/device/DeviceService.test.ts
+77
@@ -842,6 +842,83 @@ it.effect.each([
842 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
843 );
844
845 +it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
846 + "retains hub inventory on %s when AVD enumeration fails and recovers on retry",
847 + (hostId) =>
848 + Effect.gen(function* () {
849 + let enumeration = { code: 1, stdout: "private stdout", stderr: "private stderr" };
850 + const ready: DeviceHost.DeviceHostReady = {
851 + nodePath: process.execPath,
852 + hub: { origin: "http://device.test" },
853 + helpers: { serveSimAxSettings: null, serveSimCli: null },
854 + run: () => Effect.sync(() => enumeration),
855 + };
856 + const host: DeviceHost.DeviceHost["Service"] = {
857 + id: hostId,
858 + summary: Effect.succeed({
859 + id: hostId,
860 + kind: hostId === LOCAL_DEVICE_HOST_ID ? "local" : "ssh",
861 + label: "Test device host",
862 + platforms: [{ platform: "android", available: true }],
863 + hubInstalled: true,
864 + agentDeviceInstalled: false,
865 + }),
866 + platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
867 + ensureReady: () => Effect.succeed(ready),
868 + ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
869 + current: Effect.succeed(ready),
870 + stop: Effect.void,
871 + stopAgent: Effect.void,
872 + };
873 + const hubDevices = [
874 + { id: "iphone", name: "iPhone", platform: "ios", physical: false },
875 + { id: "phone", name: "Pixel", platform: "android", physical: true },
876 + { id: "emulator-5554", name: "Running_AVD", platform: "android", physical: false },
877 + ].map((device) => ({ ...device, booted: true, version: "test" }));
878 + const http = HttpClient.make((request) =>
879 + Effect.succeed(
880 + HttpClientResponse.fromWeb(
881 + request,
882 + Response.json({ simulators: hubDevices.slice(0, 1), emulators: hubDevices.slice(1) }),
883 + ),
884 + ),
885 + );
886 + const service = yield* DeviceService.makeWithHosts(new Map([[hostId, host]])).pipe(
887 + Effect.provide(NodeCrypto.layer),
888 + Effect.provideService(HttpClient.HttpClient, http),
889 + );
890 +
891 + const incomplete = yield* service.list;
892 + expect(incomplete.devices).toEqual(hubDevices.map((device) => ({ ...device, hostId })));
893 + expect(incomplete.hostStatuses[hostId]).toEqual({
894 + status: "ready",
895 + androidDiscoveryIncomplete: true,
896 + detail:
897 + "Could not list Android virtual devices (emulator -list-avds, exit code 1). Discovered devices remain available.",
898 + });
899 + if (hostId === LOCAL_DEVICE_HOST_ID) {
900 + expect(incomplete.hostStatusDetail).toBe(incomplete.hostStatuses[hostId]?.detail);
901 + }
902 +
903 + enumeration = { code: 0, stdout: "Running_AVD\r\nStopped_AVD\nStopped_AVD\n", stderr: "" };
904 + const recovered = yield* service.retryHost(hostId);
905 + expect(recovered.devices).toEqual([
906 + ...hubDevices.map((device) => ({ ...device, hostId })),
907 + {
908 + hostId,
909 + id: "Stopped_AVD",
910 + name: "Stopped_AVD",
911 + platform: "android",
912 + version: "Android",
913 + booted: false,
914 + physical: false,
915 + },
916 + ]);
917 + expect(recovered.hostStatuses[hostId]).toEqual({ status: "ready" });
918 + if (hostId === LOCAL_DEVICE_HOST_ID) expect(recovered.hostStatusDetail).toBeUndefined();
919 + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
920 +);
921 +
922 it.effect("retry keeps device and agent consent unchanged", () =>
923 Effect.gen(function* () {
924 const { service, starts, agentStarts } = yield* fixture();
apps/server/src/device/DeviceService.ts
+32 -20
@@ -259,7 +259,15 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
259 ...(hostId === LOCAL_DEVICE_HOST_ID
260 ? { hostStatus: status.status, hostStatusDetail: status.detail }
261 : {}),
262 - hostStatuses: { ...state.hostStatuses, [hostId]: status },
262 + hostStatuses: {
263 + ...state.hostStatuses,
264 + [hostId]: {
265 + ...(state.hostStatuses[hostId]?.androidDiscoveryIncomplete
266 + ? { androidDiscoveryIncomplete: true }
267 + : {}),
268 + ...status,
269 + },
270 + },
271 })),
272 );
273
@@ -417,18 +425,27 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
425 physical: device.physical,
426 });
427 const devices = [...list.simulators, ...list.emulators].map(toSummary);
428 + const warnings = list.errors?.filter(
429 + (error) =>
430 + // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
431 + !(
432 + error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
433 + /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
434 + /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
435 + ),
436 + );
437 + const details = warnings?.map((error) => error.message) ?? [];
438 + let androidDiscoveryIncomplete = false;
439 const host = yield* resolveHost(ready.hostId);
440 if ((yield* host.platformAvailability("android")).available) {
441 const avds = yield* ready.run("emulator", ["-list-avds"]);
442 if (avds.code !== 0) {
424 - return yield* new DeviceOperationError({
425 - operation: "list",
426 - reason: "command_failed",
427 - exitCode: avds.code,
428 - cause: avds,
429 - });
443 + androidDiscoveryIncomplete = true;
444 + details.push(
445 + `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
446 + );
447 }
431 - for (const name of avds.stdout
448 + for (const name of (avds.code === 0 ? avds.stdout : "")
449 .split(/\r?\n/)
450 .map((line) => line.trim())
451 .filter(Boolean)) {
@@ -445,21 +462,12 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
462 }
463 }
464 }
448 - const warnings = list.errors?.filter(
449 - (error) =>
450 - // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
451 - !(
452 - error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
453 - /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
454 - /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
455 - ),
456 - );
457 - return { devices, detail: warnings?.map((error) => error.message).join("\n") || undefined };
465 + return { devices, detail: details.join("\n") || undefined, androidDiscoveryIncomplete };
466 });
467
468 const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
469 const host = hosts.get(ready.hostId);
462 - const { devices, detail } = yield* fetchDevices(ready);
470 + const { devices, detail, androidDiscoveryIncomplete } = yield* fetchDevices(ready);
471 const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
472 return yield* lifecycleLock.withPermit(
473 Effect.gen(function* () {
@@ -475,7 +483,11 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
483 ],
484 hostStatuses: {
485 ...state.hostStatuses,
478 - [ready.hostId]: { status: "ready", ...(detail ? { detail } : {}) },
486 + [ready.hostId]: {
487 + status: "ready",
488 + ...(detail ? { detail } : {}),
489 + ...(androidDiscoveryIncomplete ? { androidDiscoveryIncomplete } : {}),
490 + },
491 },
492 }));
493 }),
apps/server/src/device/LocalDeviceHost.test.ts
+20 -1
@@ -37,6 +37,7 @@ const agentFixture = Effect.fn("agentFixture")(function* (
37 startup: (
38 stateDir: string,
39 ) => Effect.Effect<ProcessRunner.ProcessRunOutput, ProcessRunner.ProcessRunError>,
40 + avdOutput: ProcessRunner.ProcessRunOutput = processOutput(0),
41 ) {
42 const fs = yield* FileSystem.FileSystem;
43 const path = yield* Path.Path;
@@ -79,7 +80,9 @@ const agentFixture = Effect.fn("agentFixture")(function* (
80 ),
81 Effect.provideService(ProcessRunner.ProcessRunner, {
82 run: (input) =>
82 - input.args.includes("devices") ? startup(stateDir) : Effect.succeed(processOutput(0)),
83 + input.args.includes("devices")
84 + ? startup(stateDir)
85 + : Effect.succeed(input.args.includes("-list-avds") ? avdOutput : processOutput(0)),
86 }),
87 Effect.provideService(
88 HttpClient.HttpClient,
@@ -398,6 +401,22 @@ describe("Android SDK availability", () => {
401 );
402 });
403
404 +it.effect.each([
405 + { reason: "timeout", timedOut: true },
406 + { reason: "signal termination", timedOut: false },
407 +])("reports AVD enumeration $reason as a failed command", ({ timedOut }) =>
408 + Effect.gen(function* () {
409 + const { host } = yield* agentFixture(() => Effect.succeed(processOutput(0)), {
410 + ...processOutput(0),
411 + code: null,
412 + timedOut,
413 + });
414 + const ready = yield* host.ensureReady(() => Effect.void);
415 + const result = yield* ready.run("emulator", ["-list-avds"]);
416 + expect(result.code).not.toBe(0);
417 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
418 +);
419 +
420 it.effect("puts detected Android tools on the helper PATH without losing existing commands", () =>
421 Effect.gen(function* () {
422 const path = yield* Path.Path;
apps/web/src/components/device/DevicePanel.tsx
+2 -1
@@ -20,7 +20,7 @@ import { deviceEnvironment, useDeviceState } from "~/state/device";
20 import { formatEnvironmentQueryError } from "~/state/query";
21 import { useAtomCommand } from "~/state/use-atom-command";
22 import { DeviceLoadingView } from "./DeviceLoadingView";
23 -import { DeviceSetup, deviceHubReadiness } from "./DeviceSetup";
23 +import { DeviceSetup, deviceHubReadiness, isAndroidDiscoveryUncertain } from "./DeviceSetup";
24 import { DeviceWorkspace } from "./DeviceWorkspace";
25 import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell";
26
@@ -316,6 +316,7 @@ export function DevicePanel(props: {
316 </div>
317 ) : null}
318 {hostReady &&
319 + !isAndroidDiscoveryUncertain(state) &&
320 !state.devices.some((device) => device.platform === "android") &&
321 !unavailablePlatforms.some((platform) => platform.platform === "android") ? (
322 <p className="max-w-sm text-xs">
apps/web/src/components/device/DeviceSetup.test.ts
+14
@@ -34,6 +34,20 @@ describe("device setup guidance", () => {
34 expect(platformSetupStatus(deviceState(), "android").message).toContain("Device Manager");
35 });
36
37 + it("waits for complete Android discovery before advising creation of an AVD", () => {
38 + const state = deviceState({
39 + hostStatus: "idle",
40 + hosts: [{ ...deviceState().hosts[0]!, id: "remote", kind: "ssh" }],
41 + hostStatuses: { remote: { status: "ready", androidDiscoveryIncomplete: true } },
42 + });
43 + expect(platformSetupStatus(state, "android").message).toContain("may be incomplete");
44 + expect(platformSetupStatus(state, "ios").message).toContain("Xcode Settings");
45 + expect(
46 + platformSetupStatus({ ...state, hostStatuses: { remote: { status: "ready" } } }, "android")
47 + .message,
48 + ).toContain("Device Manager");
49 + });
50 +
51 it("preserves a specific missing-tool explanation from the server", () => {
52 const state = deviceState({
53 hosts: [
apps/web/src/components/device/DeviceSetup.tsx
+13 -1
@@ -23,6 +23,11 @@ export const deviceHubDescription =
23 export const agentDeviceDescription =
24 "Allow new agent sessions in this environment to start and control local and remote devices, with required tools set up automatically.";
25
26 +export const isAndroidDiscoveryUncertain = (state: DeviceServiceState) =>
27 + Object.values(state.hostStatuses).some(
28 + (status) => status.status === "ready" && status.androidDiscoveryIncomplete,
29 + );
30 +
31 /**
32 * `hostStatus` only tracks this machine. A machine without simulator tooling never
33 * starts its own hub, so setup and the panel must also count remote device hosts.
@@ -39,6 +44,13 @@ export function deviceHubReadiness(state: DeviceServiceState) {
44 }
45
46 export function platformSetupStatus(state: DeviceServiceState, platform: DevicePlatform) {
47 + const hasDevices = state.devices.some((device) => device.platform === platform);
48 + if (platform === "android" && !hasDevices && isAndroidDiscoveryUncertain(state)) {
49 + return {
50 + ready: false,
51 + message: "The Android device list may be incomplete. Check the device host and try again.",
52 + };
53 + }
54 const availabilities = state.hosts.flatMap((host) =>
55 host.platforms
56 .filter((candidate) => candidate.platform === platform)
@@ -58,7 +70,7 @@ export function platformSetupStatus(state: DeviceServiceState, platform: DeviceP
70 state.hostStatuses[host.id]?.status === "ready" ||
71 (host.kind === "local" && state.hostStatus === "ready"),
72 );
61 - if (readyHosts.length > 0 && !state.devices.some((device) => device.platform === platform)) {
73 + if (readyHosts.length > 0 && !hasDevices) {
74 return {
75 ready: false,
76 message:
apps/web/src/components/settings/DeviceHostsSettings.tsx
+12
@@ -431,6 +431,18 @@ function DeviceHostList({
431 ))}
432 </div>
433 <p className="truncate text-xs text-muted-foreground">{host.target}</p>
434 + {results
435 + .filter(
436 + (result) =>
437 + result.status?.status === "ready" && result.status.androidDiscoveryIncomplete,
438 + )
439 + .map((result) => (
440 + <p key={result.environmentId} role="status" className="mt-1 text-xs text-warning">
441 + {compact ? `${result.label}: ` : ""}
442 + {result.status?.detail ??
443 + "The Android device list may be incomplete. Refresh devices to try again."}
444 + </p>
445 + ))}
446 {compact ? (
447 <Collapsible>
448 <div className="min-w-0 text-xs [--inline-button-white-space:normal]">
packages/contracts/src/device.ts
+1
@@ -107,6 +107,7 @@ export const DeviceServiceState = Schema.Struct({
107 Schema.Struct({
108 status: DeviceHostStatus,
109 detail: Schema.optional(Schema.String),
110 + androidDiscoveryIncomplete: Schema.optional(Schema.Boolean),
111 }),
112 ),
113 devices: Schema.Array(DeviceSummary),