diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 00e942f1e6df5..3ddf6579bb87c 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -1086,6 +1086,9 @@ it.effect.each([ detail: "The device hub did not answer within 40 seconds.", incompletePlatforms, }); + expect( + yield* service.locateDevice({ deviceId: DeviceId.make("emulator-5562") }).pipe(Effect.flip), + ).toMatchObject({ _tag: "DeviceListFailedError", hosts: [{ id: LOCAL_DEVICE_HOST_ID }] }); }), ); @@ -2177,12 +2180,14 @@ describe("locating a device id across hosts", () => { const macMini = { id: "mac-mini", label: "Mac Mini" }; const listingHost = ( host: { readonly id: string; readonly label: string }, - ids: ReadonlyArray, + ids: ReadonlyArray, ): DeviceHost.DeviceHost["Service"] => { - const devices = ids.map((id) => ({ - id, - name: id, - platform: id.startsWith("Pixel") ? ("android" as const) : ("ios" as const), + const devices = ids.map((entry) => ({ + ...(typeof entry === "string" ? { id: entry, name: entry } : entry), + platform: + typeof entry !== "string" || entry.startsWith("Pixel") + ? ("android" as const) + : ("ios" as const), version: "test", booted: true, physical: false, @@ -2294,6 +2299,129 @@ describe("locating a device id across hosts", () => { ), ); + it.effect("finds a running emulator by the AVD name it was opened with", () => + Effect.gen(function* () { + // A booted AVD is listed by its adb serial; its AVD name is only its name. + const service = yield* DeviceService.makeWithHosts( + new Map([ + [ + thisMachine.id, + listingHost(thisMachine, [{ id: "emulator-5554", name: "Medium_Phone" }]), + ], + ]), + ).pipe(Effect.provide(NodeCrypto.layer)); + yield* service.list; + const located = yield* service.locateDevice({ deviceId: DeviceId.make("Medium_Phone") }); + expect(Option.getOrUndefined(located)).toMatchObject({ + hostId: LOCAL_DEVICE_HOST_ID, + id: "emulator-5554", + }); + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped), + ); + + it.effect("does not guess between two emulators running the same AVD", () => + Effect.gen(function* () { + const service = yield* DeviceService.makeWithHosts( + new Map([ + [ + thisMachine.id, + listingHost(thisMachine, [ + { id: "emulator-5554", name: "Medium_Phone" }, + { id: "emulator-5556", name: "Medium_Phone" }, + ]), + ], + [macMini.id, listingHost(macMini, [{ id: "emulator-5554", name: "Medium_Phone" }])], + ]), + ).pipe(Effect.provide(NodeCrypto.layer)); + yield* service.list; + const deviceId = DeviceId.make("Medium_Phone"); + expect(yield* service.locateDevice({ deviceId }).pipe(Effect.flip)).toMatchObject({ + _tag: "DeviceHostAmbiguousError", + }); + expect(yield* service.locateDevice({ deviceId, hostId: LOCAL_DEVICE_HOST_ID })).toEqual( + Option.none(), + ); + expect( + Option.getOrUndefined(yield* service.locateDevice({ deviceId, hostId: "mac-mini" })), + ).toMatchObject({ hostId: "mac-mini", id: "emulator-5554" }); + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped), + ); + + it.effect("prefers a listed id to another host's emulator running that AVD", () => + Effect.gen(function* () { + const service = yield* DeviceService.makeWithHosts( + new Map([ + [ + thisMachine.id, + listingHost(thisMachine, [{ id: "Medium_Phone", name: "Medium_Phone" }]), + ], + [macMini.id, listingHost(macMini, [{ id: "emulator-5554", name: "Medium_Phone" }])], + ]), + ).pipe(Effect.provide(NodeCrypto.layer)); + yield* service.list; + const deviceId = DeviceId.make("Medium_Phone"); + expect(Option.getOrUndefined(yield* service.locateDevice({ deviceId }))).toMatchObject({ + hostId: LOCAL_DEVICE_HOST_ID, + id: "Medium_Phone", + }); + expect( + Option.getOrUndefined(yield* service.locateDevice({ deviceId, hostId: "mac-mini" })), + ).toMatchObject({ hostId: "mac-mini", id: "emulator-5554" }); + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped), + ); + + it.effect("reports a failed device list before matching another host or an AVD name", () => + Effect.gen(function* () { + const local = listingHost(thisMachine, [{ id: "emulator-5554", name: "Medium_Phone" }]); + let listed = false; + const failingOnRelist: DeviceHost.DeviceHost["Service"] = { + ...local, + ensureReady: (...args) => + local.ensureReady(...args).pipe( + Effect.map((ready): DeviceHost.DeviceHostReady => ({ + ...ready, + devices: { + ...ready.devices, + list: Effect.suspend(() => { + if (!listed) { + listed = true; + return ready.devices.list; + } + return Effect.fail( + new DeviceOperationError({ + operation: "list devices", + reason: "request_failed", + cause: null, + }), + ); + }), + }, + })), + ), + }; + const service = yield* DeviceService.makeWithHosts( + new Map([ + [thisMachine.id, failingOnRelist], + [ + macMini.id, + listingHost(macMini, ["MAC-UDID", { id: "emulator-5554", name: "Medium_Phone" }]), + ], + ]), + ).pipe(Effect.provide(NodeCrypto.layer)); + yield* service.list; + yield* service.list; + for (const input of [ + { deviceId: DeviceId.make("MAC-UDID"), hostId: LOCAL_DEVICE_HOST_ID }, + { deviceId: DeviceId.make("Medium_Phone") }, + ]) { + expect(yield* service.locateDevice(input).pipe(Effect.flip)).toMatchObject({ + _tag: "DeviceListFailedError", + hosts: [{ id: LOCAL_DEVICE_HOST_ID }], + }); + } + }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped), + ); + it.effect("finds nothing for a device id that no host lists", () => withTwoHosts((service) => Effect.gen(function* () { diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index cf8aece6745e0..44f25c0415d04 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -158,6 +158,18 @@ export class DeviceOnOtherHostError extends Schema.TaggedError()( + "DeviceListFailedError", + { + deviceId: DeviceId, + hosts: Schema.Array(Schema.Struct({ ...DeviceHostName.fields, detail: Schema.String })), + }, +) { + override get message(): string { + return `Device ${this.deviceId} is not in the last device list, and listing devices failed on ${this.hosts.map((host) => `${hostName(host)} (${host.detail})`).join(", ")}.`; + } +} + export class DeviceService extends Context.Service< DeviceService, { @@ -223,14 +235,15 @@ export class DeviceService extends Context.Service< /** * The device an id names in the last listing. Ids are unique per host, not across hosts (an * Android AVD name can exist on two), so a hostId decides, and without one the id has to be - * on a single host. + * on a single host. When no device in scope has the id, the one emulator running the AVD of + * that name on a host stands in for it, unless listing devices failed on a host in scope. */ readonly locateDevice: (input: { readonly hostId?: DeviceHostId | undefined; readonly deviceId: DeviceId; }) => Effect.Effect< Option.Option, - DeviceHostAmbiguousError | DeviceOnOtherHostError + DeviceHostAmbiguousError | DeviceOnOtherHostError | DeviceListFailedError >; /** As `locateDevice`, among the devices a thread has open. */ readonly locateSession: (input: { @@ -1048,15 +1061,17 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* Effect.map(({ state }) => state.sessions.filter((session) => session.threadId === threadId)), ); + const namedHost = (state: DeviceServiceState, id: DeviceHostId) => ({ + id, + label: state.hosts.find((host) => host.id === id)?.label, + }); + const locate = ( state: DeviceServiceState, input: { readonly hostId?: DeviceHostId | undefined; readonly deviceId: DeviceId }, matches: ReadonlyArray, ): Effect.Effect, DeviceHostAmbiguousError | DeviceOnOtherHostError> => { - const named = (id: DeviceHostId) => ({ - id, - label: state.hosts.find((host) => host.id === id)?.label, - }); + const named = (id: DeviceHostId) => namedHost(state, id); const onHost = matches.filter( (match) => input.hostId === undefined || match.hostId === input.hostId, ); @@ -1083,10 +1098,35 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* "DeviceService.locateDevice", )(function* (input) { const { state } = yield* SynchronizedRef.get(stateRef); - return yield* locate( - state, - input, - state.devices.filter((device) => device.id === input.deviceId), + const byId = state.devices.filter((device) => device.id === input.deviceId); + if (byId.some((device) => input.hostId === undefined || device.hostId === input.hostId)) { + return yield* locate(state, input, byId); + } + // A failed or incomplete refresh keeps the previous devices, so the device may be there unlisted. + const failed = ( + input.hostId === undefined ? state.hosts.map((host) => host.id) : [input.hostId] + ).flatMap((id) => { + const status = state.hostStatuses[id]; + return (status?.status === "failed" || status?.incompletePlatforms?.length) && status.detail + ? [{ ...namedHost(state, id), detail: status.detail }] + : []; + }); + if (failed.length > 0) { + return yield* new DeviceListFailedError({ deviceId: input.deviceId, hosts: failed }); + } + // A shut-down AVD is listed by its name and a running one by its adb serial. + const byAvdName = state.devices.filter( + (device) => + device.platform === "android" && + !device.physical && + device.booted && + device.name === input.deviceId, + ); + const located = yield* locate(state, input, [...byId, ...byAvdName]); + // Several emulators running one AVD: its name picks none of them. + return Option.filter( + located, + (device) => byAvdName.filter((other) => other.hostId === device.hostId).length === 1, ); }); diff --git a/apps/server/src/mcp/toolkits/device/handlers.ts b/apps/server/src/mcp/toolkits/device/handlers.ts index 099a9bae9e2d3..9893240e09dad 100644 --- a/apps/server/src/mcp/toolkits/device/handlers.ts +++ b/apps/server/src/mcp/toolkits/device/handlers.ts @@ -123,7 +123,9 @@ const hostName = (host: { readonly id: DeviceHostId; readonly label?: string | u const mapLocateErrors = ( effect: Effect.Effect< A, - DeviceService.DeviceHostAmbiguousError | DeviceService.DeviceOnOtherHostError, + | DeviceService.DeviceHostAmbiguousError + | DeviceService.DeviceOnOtherHostError + | DeviceService.DeviceListFailedError, R >, ) => @@ -135,6 +137,12 @@ const mapLocateErrors = ( reason: `Device ${error.deviceId} is on more than one host: ${error.hosts.map(hostName).join(", ")}. Pass hostId.`, }), ), + DeviceListFailedError: (error) => + Effect.fail( + new DeviceToolUnavailableError({ + reason: `${error.message} Call device_list to retry.`, + }), + ), DeviceOnOtherHostError: (error) => Effect.fail( new DeviceToolUnavailableError({