Skip to content

Commit 7447e39

Browse files
fix(devices): a saved Simlock token only goes to its own gateway, and a platform whose workers are reconnecting is not cached
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 9868287 commit 7447e39

3 files changed

Lines changed: 58 additions & 33 deletions

File tree

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

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1513,18 +1513,20 @@ export const make = Effect.gen(function* () {
15131513
return yield* new DeviceSimlockIdentityError({
15141514
reason: "This machine's agent-device does not point at a Simlock gateway.",
15151515
});
1516-
const saved =
1516+
const savedHost =
15171517
input.hostId === undefined
1518-
? ""
1519-
: ((yield* settings.getSettings).simlockDeviceHosts.find(
1518+
? undefined
1519+
: (yield* settings.getSettings).simlockDeviceHosts.find(
15201520
(host) => host.id === input.hostId,
1521-
)?.agentToken ?? "");
1521+
);
15221522
const token = input.agentToken
15231523
? { agentToken: input.agentToken, source: "entered" as const }
1524-
: SimlockDeviceHost.resolveSimlockToken(gatewayUrl, saved, environment);
1524+
: SimlockDeviceHost.resolveSimlockToken(gatewayUrl, savedHost, environment);
15251525
if (!token)
15261526
return yield* new DeviceSimlockIdentityError({
1527-
reason: "No agent token for this gateway on this machine.",
1527+
reason: savedHost?.agentToken
1528+
? "The saved token is for another gateway. Enter one for this gateway."
1529+
: "No agent token for this gateway on this machine.",
15281530
});
15291531
const identity = yield* SimlockDeviceHost.simlockIdentity(gatewayUrl, token.agentToken).pipe(
15301532
Effect.mapError(

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

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -271,15 +271,14 @@ describe("Simlock device host", () => {
271271
expect(yield* host.platformAvailability("ios")).toEqual({
272272
platform: "ios",
273273
available: false,
274-
reason:
275-
"The Simlock gateway refused the agent token for Device pool. Check it in Settings.",
274+
reason: "The Simlock gateway refused the agent token for Device pool.",
276275
});
277276
expect((yield* host.summary).platforms.every((platform) => !platform.available)).toBe(true);
278277
yield* Scope.close(scope, Exit.void);
279278
}).pipe(Effect.scoped, Effect.provide(layer)),
280279
);
281280

282-
it.effect("uses this machine's agent-device token only for the gateway it targets", () =>
281+
it.effect("sends saved and machine tokens only to the gateway each belongs to", () =>
283282
Effect.gen(function* () {
284283
const pool = yield* fakePool();
285284
const availability = (baseUrl: string) =>
@@ -296,6 +295,14 @@ describe("Simlock device host", () => {
296295
return result;
297296
});
298297

298+
expect(
299+
SimlockDeviceHost.resolveSimlockToken(
300+
"https://elsewhere.example:4700",
301+
config({ agentToken: "saved-token" }),
302+
{},
303+
),
304+
).toBeNull();
305+
299306
expect(yield* availability(`${GATEWAY}/v1/agent-device`)).toEqual({
300307
platform: "ios",
301308
available: true,
@@ -310,19 +317,24 @@ describe("Simlock device host", () => {
310317
}).pipe(Effect.scoped, Effect.provide(layer)),
311318
);
312319

313-
it.effect("lists the pool again as soon as its workers return", () =>
320+
it.effect("lists a platform again as soon as its workers return", () =>
314321
Effect.gen(function* () {
315322
const pool = yield* fakePool();
316323
const scope = yield* Scope.make();
317324
const host = yield* makeHost(pool, config(), scope);
318325
const ready = yield* host.ensureReady(() => Effect.void);
319-
// Mid-reconnect, the gateway knows the models but no worker that makes them.
326+
// Mid-reconnect, the gateway knows the Android models but no worker that makes them.
320327
pool.setCatalog({
321-
platforms: [{ ...CATALOG.platforms[1]!, modelWorkers: { "Pixel 9": [], "Pixel 8": [] } }],
328+
platforms: [
329+
CATALOG.platforms[0]!,
330+
{ ...CATALOG.platforms[1]!, modelWorkers: { "Pixel 9": [], "Pixel 8": [] } },
331+
],
322332
});
323-
expect((yield* ready.devices.list).devices).toEqual([]);
333+
const during = (yield* ready.devices.list).devices;
334+
expect(during.some((device) => device.platform === "android")).toBe(false);
324335
pool.setCatalog(CATALOG);
325-
expect((yield* ready.devices.list).devices.length).toBeGreaterThan(0);
336+
const after = (yield* ready.devices.list).devices;
337+
expect(after.some((device) => device.platform === "android")).toBe(true);
326338
yield* Scope.close(scope, Exit.void);
327339
}).pipe(Effect.scoped, Effect.provide(layer)),
328340
);

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

Lines changed: 30 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
type DevicePlatformAvailability,
1414
type SimlockDeviceHostConfig,
1515
} from "@t3tools/contracts";
16+
import * as Cause from "effect/Cause";
1617
import * as Clock from "effect/Clock";
1718
import * as Duration from "effect/Duration";
1819
import * as Effect from "effect/Effect";
@@ -105,13 +106,17 @@ export const machineSimlockToken = (environment: NodeJS.ProcessEnv) => {
105106
return URL.canParse(gatewayUrl) ? { gatewayUrl, agentToken } : null;
106107
};
107108

108-
/** The saved token, else this machine's agent-device token, but only for the gateway it targets. */
109+
/**
110+
* The saved token, else this machine's agent-device token; each only for the gateway it belongs to,
111+
* so a URL being edited never receives either.
112+
*/
109113
export const resolveSimlockToken = (
110114
gatewayUrl: string,
111-
saved: string,
115+
saved: { readonly gatewayUrl: string; readonly agentToken: string } | undefined,
112116
environment: NodeJS.ProcessEnv,
113117
) => {
114-
if (saved) return { agentToken: saved, source: "settings" as const };
118+
if (saved?.agentToken && sameOrigin(saved.gatewayUrl, gatewayUrl))
119+
return { agentToken: saved.agentToken, source: "settings" as const };
115120
const machine = machineSimlockToken(environment);
116121
return machine && sameOrigin(machine.gatewayUrl, gatewayUrl)
117122
? { agentToken: machine.agentToken, source: "env" as const }
@@ -120,12 +125,18 @@ export const resolveSimlockToken = (
120125

121126
/** What went wrong talking to a gateway, without the gateway's own text. */
122127
export const describeGatewayFailure = (cause: unknown, gatewayUrl: string, tokenOwner: string) => {
123-
const status = HttpClientError.isHttpClientError(cause) ? cause.response?.status : undefined;
124-
return status === 401 || status === 403
125-
? `The Simlock gateway refused the agent token for ${tokenOwner}.`
126-
: status !== undefined
127-
? `The Simlock gateway at ${gatewayUrl} answered HTTP ${status}.`
128-
: `Could not reach the Simlock gateway at ${gatewayUrl}.`;
128+
if (Cause.isTimeoutError(cause)) return `Could not reach the Simlock gateway at ${gatewayUrl}.`;
129+
if (!HttpClientError.isHttpClientError(cause))
130+
return `The Simlock gateway at ${gatewayUrl} sent an answer T3 could not read.`;
131+
if (cause.reason._tag === "StatusCodeError") {
132+
const status = cause.reason.response.status;
133+
return status === 401 || status === 403
134+
? `The Simlock gateway refused the agent token for ${tokenOwner}.`
135+
: `The Simlock gateway at ${gatewayUrl} answered HTTP ${status}.`;
136+
}
137+
return cause.reason._tag === "TransportError"
138+
? `Could not reach the Simlock gateway at ${gatewayUrl}.`
139+
: `The Simlock gateway at ${gatewayUrl} sent an answer T3 could not read.`;
129140
};
130141

131142
const decodeIdentity = Schema.decodeUnknownEffect(
@@ -172,8 +183,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
172183
const environment = yield* HostProcess.Environment;
173184
const hostId = config.id;
174185
const gateway = config.gatewayUrl.replace(/\/$/, "");
175-
const agentToken =
176-
resolveSimlockToken(config.gatewayUrl, config.agentToken, environment)?.agentToken ?? "";
186+
const agentToken = resolveSimlockToken(config.gatewayUrl, config, environment)?.agentToken ?? "";
177187
const agentDeviceUrl = `${gateway}/v1/agent-device`;
178188
const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
179189
const leases = new Map<string, Lease>();
@@ -280,14 +290,11 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
280290
const decoded = yield* request("GET", "/v1/catalog").pipe(
281291
Effect.flatMap(decodeCatalog),
282292
Effect.mapError((cause) =>
283-
unavailable(
284-
`${describeGatewayFailure(cause, gateway, config.label)} Check it in Settings.`,
285-
cause,
286-
),
293+
unavailable(describeGatewayFailure(cause, gateway, config.label), cause),
287294
),
288295
);
289-
const devices = decoded.platforms.flatMap((entry) => {
290-
if (entry.platform !== "ios" && entry.platform !== "android") return [];
296+
const byPlatform = decoded.platforms.map((entry) => {
297+
if (entry.platform !== "ios" && entry.platform !== "android") return null;
291298
const platform: DevicePlatform = entry.platform;
292299
return Object.entries(entry.modelRuntimes).flatMap(([model, runtimes]) => {
293300
const kind = entry.modelClasses?.[model];
@@ -306,8 +313,12 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
306313
];
307314
});
308315
});
309-
// An empty catalog is usually workers reconnecting; caching it would hide the pool for the TTL.
310-
catalog = devices.length > 0 ? { at: now, devices } : null;
316+
const devices = byPlatform.flatMap((entry) => entry ?? []);
317+
// A platform with nothing to offer is usually its workers reconnecting; caching that would
318+
// hide it for the TTL, so only a catalog with devices on every platform is kept.
319+
catalog = byPlatform.every((entry) => entry === null || entry.length > 0)
320+
? { at: now, devices }
321+
: null;
311322
return devices;
312323
});
313324

0 commit comments

Comments
 (0)