Skip to content
Open
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
138 changes: 133 additions & 5 deletions apps/server/src/device/DeviceService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }] });
}),
);

Expand Down Expand Up @@ -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<string>,
ids: ReadonlyArray<string | { readonly id: string; readonly name: string }>,
): 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,
Expand Down Expand Up @@ -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* () {
Expand Down
60 changes: 50 additions & 10 deletions apps/server/src/device/DeviceService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,18 @@ export class DeviceOnOtherHostError extends Schema.TaggedError<DeviceOnOtherHost
}
}

export class DeviceListFailedError extends Schema.TaggedError<DeviceListFailedError>()(
"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,
{
Expand Down Expand Up @@ -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<DeviceSummary>,
DeviceHostAmbiguousError | DeviceOnOtherHostError
DeviceHostAmbiguousError | DeviceOnOtherHostError | DeviceListFailedError
>;
/** As `locateDevice`, among the devices a thread has open. */
readonly locateSession: (input: {
Expand Down Expand Up @@ -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 = <T extends { readonly hostId: DeviceHostId }>(
state: DeviceServiceState,
input: { readonly hostId?: DeviceHostId | undefined; readonly deviceId: DeviceId },
matches: ReadonlyArray<T>,
): Effect.Effect<Option.Option<T>, 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,
);
Expand All @@ -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,
);
});

Expand Down
10 changes: 9 additions & 1 deletion apps/server/src/mcp/toolkits/device/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,9 @@ const hostName = (host: { readonly id: DeviceHostId; readonly label?: string | u
const mapLocateErrors = <A, R>(
effect: Effect.Effect<
A,
DeviceService.DeviceHostAmbiguousError | DeviceService.DeviceOnOtherHostError,
| DeviceService.DeviceHostAmbiguousError
| DeviceService.DeviceOnOtherHostError
| DeviceService.DeviceListFailedError,
R
>,
) =>
Expand All @@ -135,6 +137,12 @@ const mapLocateErrors = <A, R>(
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({
Expand Down
Loading