@devries-cameron20 / t3code Mirror · read-only / commits / be7d86fa66
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, 13:15 UTC

feat(devices): Simlock setup uses each machine's agent-device token, checks tokens, and lists the pool through worker reconnects (#26706)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 28, 2026 at 18:04 UTC be7d86fa666780aaf815bd515fb1ab6ecf4826de
13 files changed +444 -39
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -193,6 +193,7 @@ export const RPC_REQUIRED_SCOPES = {
193 [WS_METHODS.deviceConfigure]: AuthSettingsWriteScope,
194 [WS_METHODS.deviceTestHost]: AuthSettingsWriteScope,
195 [WS_METHODS.deviceEasAccount]: AuthSettingsWriteScope,
196 + [WS_METHODS.deviceSimlockIdentity]: AuthSettingsWriteScope,
197 [WS_METHODS.deviceList]: AuthOrchestrationReadScope,
198 [WS_METHODS.deviceOpen]: AuthOrchestrationOperateScope,
199 [WS_METHODS.deviceClose]: AuthOrchestrationOperateScope,
apps/server/src/device/DeviceService.ts
+76
@@ -20,6 +20,9 @@ import {
20 type DeviceEasAccount,
21 DeviceEasAccountError,
22 type DeviceEasAccountInput,
23 + type DeviceSimlockIdentity,
24 + DeviceSimlockIdentityError,
25 + type DeviceSimlockIdentityInput,
26 type DeviceHostConfig,
27 type EasDeviceHostConfig,
28 type SimlockDeviceHostConfig,
@@ -69,6 +72,7 @@ import * as DeviceHost from "./DeviceHost.ts";
72 import * as SshDeviceHost from "./SshDeviceHost.ts";
73 import * as EasDeviceHost from "./EasDeviceHost.ts";
74 import * as SimlockDeviceHost from "./SimlockDeviceHost.ts";
75 +import * as HostProcess from "@t3tools/shared/HostProcess";
76 import { makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";
77 import * as Exit from "effect/Exit";
78 import * as LocalDeviceHost from "./LocalDeviceHost.ts";
@@ -142,6 +146,10 @@ export class DeviceService extends Context.Service<
146 readonly easAccount: (
147 input: DeviceEasAccountInput,
148 ) => Effect.Effect<DeviceEasAccount, DeviceEasAccountError>;
149 + /** Who a Simlock agent token is; without a gateway or token, this machine's agent-device's. */
150 + readonly simlockIdentity: (
151 + input: DeviceSimlockIdentityInput,
152 + ) => Effect.Effect<DeviceSimlockIdentity, DeviceSimlockIdentityError>;
153 /**
154 * The agent-device flags that reach the device: its config and session,
155 * and the id agent-device selects it by, which can differ from its id here.
@@ -1012,6 +1020,13 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
1020 }),
1021 );
1022 }),
1023 + simlockIdentity: Effect.fn("DeviceService.simlockIdentity")(function () {
1024 + return Effect.fail(
1025 + new DeviceSimlockIdentityError({
1026 + reason: "Simlock hosts are unavailable in this device service.",
1027 + }),
1028 + );
1029 + }),
1030 agentTarget: Effect.fn("DeviceService.agentTarget")(function* (input) {
1031 const host = yield* resolveHost(input.hostId);
1032 const ready = yield* agentReadinessIfSupported(input.hostId);
@@ -1379,6 +1394,14 @@ export const make = Effect.gen(function* () {
1394 );
1395 hosts.set(host.id, instance);
1396 configured.set(host.id, { config: host, scope: hostScope });
1397 + // Ask the gateway now, so a refused token shows in Settings before anyone opens a device.
1398 + if ((yield* settings.getSettings).enableDeviceSupport)
1399 + yield* instance
1400 + .platformAvailability("ios")
1401 + .pipe(
1402 + Effect.andThen(service.withLifecycleLock(service.refreshHosts)),
1403 + Effect.forkIn(hostScope),
1404 + );
1405 continue;
1406 }
1407 if (host.kind === "eas") {
@@ -1478,9 +1501,62 @@ export const make = Effect.gen(function* () {
1501 ),
1502 );
1503
1504 + const simlockIdentity: DeviceService["Service"]["simlockIdentity"] = Effect.fn(
1505 + "DeviceService.simlockIdentity",
1506 + )(
1507 + function* (input) {
1508 + const environment = yield* HostProcess.Environment;
1509 + const gatewayUrl = (
1510 + input.gatewayUrl || SimlockDeviceHost.machineSimlockToken(environment)?.gatewayUrl
1511 + )?.replace(/\/$/, "");
1512 + if (!gatewayUrl)
1513 + return yield* new DeviceSimlockIdentityError({
1514 + reason: "This machine's agent-device does not point at a Simlock gateway.",
1515 + });
1516 + const savedHost =
1517 + input.hostId === undefined
1518 + ? undefined
1519 + : (yield* settings.getSettings).simlockDeviceHosts.find(
1520 + (host) => host.id === input.hostId,
1521 + );
1522 + const token = input.agentToken
1523 + ? { agentToken: input.agentToken, source: "entered" as const }
1524 + : SimlockDeviceHost.resolveSimlockToken(gatewayUrl, savedHost, environment);
1525 + if (!token)
1526 + return yield* new DeviceSimlockIdentityError({
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.",
1530 + });
1531 + const identity = yield* SimlockDeviceHost.simlockIdentity(gatewayUrl, token.agentToken).pipe(
1532 + Effect.mapError(
1533 + (cause) =>
1534 + new DeviceSimlockIdentityError({
1535 + reason: SimlockDeviceHost.describeGatewayFailure(
1536 + cause,
1537 + gatewayUrl,
1538 + token.source === "env" ? "this machine" : "this environment",
1539 + ),
1540 + }),
1541 + ),
1542 + );
1543 + if (identity.role !== "agent")
1544 + return yield* new DeviceSimlockIdentityError({
1545 + reason: `That is a ${identity.role} token. Create one with --role agent.`,
1546 + });
1547 + return { gatewayUrl, signedInAs: identity.name, tokenSource: token.source };
1548 + },
1549 + Effect.catchTags({
1550 + ServerSettingsError: () =>
1551 + Effect.fail(new DeviceSimlockIdentityError({ reason: "Could not read the saved token." })),
1552 + }),
1553 + Effect.provide(simlockContext),
1554 + );
1555 +
1556 return {
1557 ...service,
1558 easAccount,
1559 + simlockIdentity,
1560 };
1561 });
1562
apps/server/src/device/SimlockDeviceHost.test.ts
+86 -2
@@ -1,6 +1,7 @@
1 import { describe, expect, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import type { SimlockDeviceHostConfig } from "@t3tools/contracts";
4 +import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Effect from "effect/Effect";
6 import * as Fiber from "effect/Fiber";
7 import * as Deferred from "effect/Deferred";
@@ -62,14 +63,16 @@ const fakePool = (
63 const commands: Array<{ readonly args: ReadonlyArray<string>; readonly cwd?: string }> = [];
64 let leases = 0;
65 let renewStatus = 200;
66 + let catalog: unknown = CATALOG;
67 const http = HttpClient.make((request) =>
68 Effect.sync(() => {
69 const url = new URL(request.url);
70 requests.push(`${request.method} ${url.pathname}`);
69 - expect(request.headers.authorization).toBe("Bearer agent-token");
71 const json = (body: unknown, status = 200) =>
72 HttpClientResponse.fromWeb(request, Response.json(body, { status }));
72 - if (url.pathname === "/v1/catalog") return json(CATALOG);
73 + if (request.headers.authorization !== "Bearer agent-token")
74 + return json({ error: { code: "UNAUTHENTICATED", message: "Unknown bearer token" } }, 401);
75 + if (url.pathname === "/v1/catalog") return json(catalog);
76 if (url.pathname.endsWith("/renew")) return json({}, renewStatus);
77 if (request.method === "DELETE") return json({}, 202);
78 return json({}, 404);
@@ -134,6 +137,9 @@ const fakePool = (
137 endLeases: () => {
138 renewStatus = 404;
139 },
140 + setCatalog: (next: unknown) => {
141 + catalog = next;
142 + },
143 };
144 });
145
@@ -257,6 +263,84 @@ describe("Simlock device host", () => {
263 }).pipe(Effect.scoped, Effect.provide(layer)),
264 );
265
266 + it.effect("reports its platforms unavailable when the gateway refuses the agent token", () =>
267 + Effect.gen(function* () {
268 + const pool = yield* fakePool();
269 + const scope = yield* Scope.make();
270 + const host = yield* makeHost(pool, config({ agentToken: "revoked" }), scope);
271 + expect(yield* host.platformAvailability("ios")).toEqual({
272 + platform: "ios",
273 + available: false,
274 + reason: "The Simlock gateway refused the agent token for Device pool.",
275 + });
276 + expect((yield* host.summary).platforms.every((platform) => !platform.available)).toBe(true);
277 + yield* Scope.close(scope, Exit.void);
278 + }).pipe(Effect.scoped, Effect.provide(layer)),
279 + );
280 +
281 + it.effect("sends saved and machine tokens only to the gateway each belongs to", () =>
282 + Effect.gen(function* () {
283 + const pool = yield* fakePool();
284 + const availability = (baseUrl: string) =>
285 + Effect.gen(function* () {
286 + const scope = yield* Scope.make();
287 + const host = yield* makeHost(pool, config({ agentToken: "" }), scope).pipe(
288 + Effect.provideService(HostProcess.Environment, {
289 + AGENT_DEVICE_DAEMON_BASE_URL: baseUrl,
290 + AGENT_DEVICE_DAEMON_AUTH_TOKEN: "agent-token",
291 + }),
292 + );
293 + const result = yield* host.platformAvailability("ios");
294 + yield* Scope.close(scope, Exit.void);
295 + return result;
296 + });
297 +
298 + expect(
299 + SimlockDeviceHost.resolveSimlockToken(
300 + "https://elsewhere.example:4700",
301 + config({ agentToken: "saved-token" }),
302 + {},
303 + ),
304 + ).toBeNull();
305 +
306 + expect(yield* availability(`${GATEWAY}/v1/agent-device`)).toEqual({
307 + platform: "ios",
308 + available: true,
309 + });
310 + const requests = pool.requests.length;
311 + expect(yield* availability("https://elsewhere.example:4700/v1/agent-device")).toEqual({
312 + platform: "ios",
313 + available: false,
314 + reason: "Add an agent token for Device pool in Settings.",
315 + });
316 + expect(pool.requests).toHaveLength(requests);
317 + }).pipe(Effect.scoped, Effect.provide(layer)),
318 + );
319 +
320 + it.effect("lists a platform again as soon as its workers return", () =>
321 + Effect.gen(function* () {
322 + const pool = yield* fakePool();
323 + const scope = yield* Scope.make();
324 + const host = yield* makeHost(pool, config(), scope);
325 + const ready = yield* host.ensureReady(() => Effect.void);
326 + pool.setCatalog({ platforms: [] });
327 + expect((yield* ready.devices.list).devices).toEqual([]);
328 + // Mid-reconnect, the gateway knows the Android models but no worker that makes them.
329 + pool.setCatalog({
330 + platforms: [
331 + CATALOG.platforms[0]!,
332 + { ...CATALOG.platforms[1]!, modelWorkers: { "Pixel 9": [], "Pixel 8": [] } },
333 + ],
334 + });
335 + const during = (yield* ready.devices.list).devices;
336 + expect(during.some((device) => device.platform === "android")).toBe(false);
337 + pool.setCatalog(CATALOG);
338 + const after = (yield* ready.devices.list).devices;
339 + expect(after.some((device) => device.platform === "android")).toBe(true);
340 + yield* Scope.close(scope, Exit.void);
341 + }).pipe(Effect.scoped, Effect.provide(layer)),
342 + );
343 +
344 it.effect("closes the session of a failed open so no lease is left behind", () =>
345 Effect.gen(function* () {
346 const pool = yield* fakePool({ failOpen: true });
apps/server/src/device/SimlockDeviceHost.ts
+139 -21
@@ -10,8 +10,10 @@ import {
10 DeviceHostUnavailableError,
11 DeviceOperationError,
12 type DevicePlatform,
13 + type DevicePlatformAvailability,
14 type SimlockDeviceHostConfig,
15 } from "@t3tools/contracts";
16 +import * as Cause from "effect/Cause";
17 import * as Clock from "effect/Clock";
18 import * as Duration from "effect/Duration";
19 import * as Effect from "effect/Effect";
@@ -22,7 +24,7 @@ import * as Path from "effect/Path";
24 import * as Random from "effect/Random";
25 import * as Schema from "effect/Schema";
26 import * as Semaphore from "effect/Semaphore";
25 -import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
27 +import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
28 import * as HostProcess from "@t3tools/shared/HostProcess";
29 import type { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
30
@@ -83,6 +85,85 @@ const parseCatalogId = (id: string) => {
85 const platformVersion = (platform: DevicePlatform, runtime: string | undefined) =>
86 `${platform === "ios" ? "iOS" : "Android"}${runtime ? ` ${runtime}` : ""}`;
87
88 +const AGENT_DEVICE_PATH = "/v1/agent-device";
89 +const sameOrigin = (left: string, right: string) => {
90 + try {
91 + return new URL(left).origin === new URL(right).origin;
92 + } catch {
93 + return false;
94 + }
95 +};
96 +
97 +/**
98 + * The gateway and token this machine's agent-device uses, from agent-device's own remote-daemon
99 + * variables, which Simlock tells its clients to set. Null unless they point at a Simlock gateway.
100 + */
101 +export const machineSimlockToken = (environment: NodeJS.ProcessEnv) => {
102 + const base = environment.AGENT_DEVICE_DAEMON_BASE_URL?.trim().replace(/\/+$/, "");
103 + const agentToken = environment.AGENT_DEVICE_DAEMON_AUTH_TOKEN?.trim();
104 + if (!base?.endsWith(AGENT_DEVICE_PATH) || !agentToken) return null;
105 + const gatewayUrl = base.slice(0, -AGENT_DEVICE_PATH.length);
106 + return URL.canParse(gatewayUrl) ? { gatewayUrl, agentToken } : null;
107 +};
108 +
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 + */
113 +export const resolveSimlockToken = (
114 + gatewayUrl: string,
115 + saved: { readonly gatewayUrl: string; readonly agentToken: string } | undefined,
116 + environment: NodeJS.ProcessEnv,
117 +) => {
118 + if (saved?.agentToken && sameOrigin(saved.gatewayUrl, gatewayUrl))
119 + return { agentToken: saved.agentToken, source: "settings" as const };
120 + const machine = machineSimlockToken(environment);
121 + return machine && sameOrigin(machine.gatewayUrl, gatewayUrl)
122 + ? { agentToken: machine.agentToken, source: "env" as const }
123 + : null;
124 +};
125 +
126 +/** What went wrong talking to a gateway, without the gateway's own text. */
127 +export const describeGatewayFailure = (cause: unknown, gatewayUrl: string, tokenOwner: string) => {
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.`;
140 +};
141 +
142 +const decodeIdentity = Schema.decodeUnknownEffect(
143 + Schema.Struct({ name: Schema.String, role: Schema.String }),
144 +);
145 +
146 +/** Who the gateway says a token is, via GET /v1/identity. */
147 +export const simlockIdentity = Effect.fn("SimlockDeviceHost.identity")(function* (
148 + gatewayUrl: string,
149 + agentToken: string,
150 +) {
151 + const http = yield* HttpClient.HttpClient;
152 + return yield* http
153 + .execute(
154 + HttpClientRequest.get(`${gatewayUrl.replace(/\/$/, "")}/v1/identity`).pipe(
155 + HttpClientRequest.bearerToken(agentToken),
156 + ),
157 + )
158 + .pipe(
159 + Effect.flatMap(HttpClientResponse.filterStatusOk),
160 + Effect.flatMap((response) => response.json),
161 + Effect.flatMap(decodeIdentity),
162 + Effect.scoped,
163 + Effect.timeout(REQUEST_TIMEOUT),
164 + );
165 +});
166 +
167 /** T3's own agent-device CLI, installed on first use. */
168 export type AgentDeviceCli = Effect.Effect<
169 { readonly nodePath: string; readonly entryPath: string },
@@ -102,6 +183,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
183 const environment = yield* HostProcess.Environment;
184 const hostId = config.id;
185 const gateway = config.gatewayUrl.replace(/\/$/, "");
186 + const agentToken = resolveSimlockToken(config.gatewayUrl, config, environment)?.agentToken ?? "";
187 const agentDeviceUrl = `${gateway}/v1/agent-device`;
188 const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
189 const leases = new Map<string, Lease>();
@@ -114,6 +196,8 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
196 readonly at: number;
197 readonly devices: ReadonlyArray<DeviceHost.HostDevice>;
198 } | null = null;
199 + // The last answer from the gateway; empty until it gives one.
200 + let platforms: ReadonlyArray<DevicePlatformAvailability> = [];
201 let ready: DeviceHost.DeviceHostReady | null = null;
202 let cli: { readonly nodePath: string; readonly entryPath: string } | null = null;
203
@@ -139,7 +223,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
223 HttpClientRequest.bodyJsonUnsafe(body ?? {}),
224 )
225 : HttpClientRequest.delete(`${gateway}${route}`)
142 - ).pipe(HttpClientRequest.bearerToken(config.agentToken)),
226 + ).pipe(HttpClientRequest.bearerToken(agentToken)),
227 )
228 .pipe(
229 Effect.flatMap(HttpClientResponse.filterStatusOk),
@@ -197,23 +281,20 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
281 return result.stdout;
282 });
283
200 - const loadCatalog = Effect.gen(function* () {
284 + const fetchCatalog = Effect.gen(function* () {
285 const now = yield* Clock.currentTimeMillis;
286 if (catalog && now - catalog.at < CATALOG_TTL_MS) return catalog.devices;
203 - if (!config.agentToken) {
287 + if (!agentToken) {
288 return yield* unavailable(`Add an agent token for ${config.label} in Settings.`);
289 }
290 const decoded = yield* request("GET", "/v1/catalog").pipe(
291 Effect.flatMap(decodeCatalog),
292 Effect.mapError((cause) =>
209 - unavailable(
210 - `Could not reach the Simlock gateway at ${gateway}, or it refused the agent token.`,
211 - cause,
212 - ),
293 + unavailable(describeGatewayFailure(cause, gateway, config.label), cause),
294 ),
295 );
215 - const devices = decoded.platforms.flatMap((entry) => {
216 - 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;
298 const platform: DevicePlatform = entry.platform;
299 return Object.entries(entry.modelRuntimes).flatMap(([model, runtimes]) => {
300 const kind = entry.modelClasses?.[model];
@@ -232,10 +313,41 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
313 ];
314 });
315 });
235 - catalog = { at: now, devices };
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 =
320 + devices.length > 0 && byPlatform.every((entry) => entry === null || entry.length > 0)
321 + ? { at: now, devices }
322 + : null;
323 return devices;
324 });
325
326 + const loadCatalog = fetchCatalog.pipe(
327 + Effect.tap((devices) =>
328 + Effect.sync(() => {
329 + platforms = (["ios", "android"] as const).map((platform) =>
330 + devices.some((device) => device.platform === platform)
331 + ? { platform, available: true }
332 + : {
333 + platform,
334 + available: false,
335 + reason: `The pool has no ${platform === "ios" ? "iOS" : "Android"} devices.`,
336 + },
337 + );
338 + }),
339 + ),
340 + Effect.tapError((error) =>
341 + Effect.sync(() => {
342 + platforms = (["ios", "android"] as const).map((platform) => ({
343 + platform,
344 + available: false,
345 + reason: error.reason,
346 + }));
347 + }),
348 + ),
349 + );
350 +
351 const forget = (lease: Lease) =>
352 Effect.suspend(() => {
353 leases.delete(lease.leaseId);
@@ -319,7 +431,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
431 const configPath = path.join(dir, "agent-device.json");
432 yield* writeAgentDeviceConfig(configPath, {
433 baseUrl: agentDeviceUrl,
322 - token: config.agentToken,
434 + token: agentToken,
435 stateDir: dir,
436 }).pipe(
437 Effect.provide(services),
@@ -445,7 +557,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
557 onSome: (lease) =>
558 Effect.succeed({
559 baseUrl: agentDeviceUrl,
448 - token: config.agentToken,
560 + token: agentToken,
561 agentDeviceId: null,
562 session: lease.session,
563 stateDir: lease.dir,
@@ -476,7 +588,7 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
588 if (!lease) return null;
589 return {
590 url: `${gateway}/v1/leases/${encodeURIComponent(lease.leaseId)}/${stream ? "stream" : "input"}`,
479 - headers: { authorization: `Bearer ${config.agentToken}` },
591 + headers: { authorization: `Bearer ${agentToken}` },
592 protocols: [],
593 };
594 });
@@ -515,19 +627,25 @@ export const make = Effect.fn("SimlockDeviceHost.make")(function* (
627 yield* Effect.addFinalizer(() => stopAll);
628
629 const platformAvailability = (platform: DevicePlatform) =>
518 - Effect.succeed({ platform, available: true });
630 + loadCatalog.pipe(
631 + Effect.ignore,
632 + Effect.map(
633 + (): DevicePlatformAvailability =>
634 + platforms.find((candidate) => candidate.platform === platform) ?? {
635 + platform,
636 + available: false,
637 + },
638 + ),
639 + );
640
520 - const summary: Effect.Effect<DeviceHostSummary> = Effect.succeed({
641 + const summary: Effect.Effect<DeviceHostSummary> = Effect.sync(() => ({
642 id: hostId,
643 label: config.label,
644 kind: "simlock" as const,
524 - platforms: [
525 - { platform: "ios" as const, available: true },
526 - { platform: "android" as const, available: true },
527 - ],
645 + platforms,
646 hubInstalled: true,
647 agentDeviceInstalled: true,
530 - });
648 + }));
649
650 return DeviceHost.DeviceHost.of({
651 id: hostId,
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -203,6 +203,7 @@ const RPC_AGGREGATES = {
203 [WS_METHODS.deviceConfigure]: "device",
204 [WS_METHODS.deviceTestHost]: "device",
205 [WS_METHODS.deviceEasAccount]: "device",
206 + [WS_METHODS.deviceSimlockIdentity]: "device",
207 [WS_METHODS.deviceList]: "device",
208 [WS_METHODS.deviceOpen]: "device",
209 [WS_METHODS.deviceClose]: "device",
apps/server/src/ws.ts
+1
@@ -3020,6 +3020,7 @@ export const layerWsRpc = (
3020 [WS_METHODS.deviceConfigure]: (input) => deviceService.configure(input),
3021 [WS_METHODS.deviceTestHost]: (input) => deviceService.testHost(input),
3022 [WS_METHODS.deviceEasAccount]: (input) => deviceService.easAccount(input),
3023 + [WS_METHODS.deviceSimlockIdentity]: (input) => deviceService.simlockIdentity(input),
3024 [WS_METHODS.deviceList]: (input) =>
3025 input.inspectOnly && !input.updateTool
3026 ? deviceService.inspect
apps/web/src/components/settings/DeviceSourcesSettings.tsx
+2 -8
@@ -507,14 +507,8 @@ export function DeviceSourcesSettings(props: {
507 label: member.label,
508 added: true,
509 platforms: hostPlatforms(member.state, host.id),
510 - status:
511 - held.agentToken === ""
512 - ? ({
513 - tone: "warning",
514 - label: "No agent token",
515 - ...(disabled ? {} : { action: { label: "Add token", run: edit } }),
516 - } as const)
517 - : hostStatus(member.state, host.id),
510 + // A blank token can still resolve to the machine's own, so the host's answer decides.
511 + status: hostStatus(member.state, host.id),
512 };
513 }),
514 actions: rowActions(edit, () => removeSimlock(host)),
apps/web/src/components/settings/SimlockDeviceHostEditor.tsx
+83 -4
@@ -1,7 +1,14 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 import { useId, useState, type ReactNode } from "react";
3 import type { EnvironmentId, SimlockDeviceHostConfig } from "@t3tools/contracts";
4 +import * as Cause from "effect/Cause";
5 +import * as Option from "effect/Option";
6 +import { AsyncResult, Atom } from "effect/reactivity";
7 import { XIcon } from "lucide-react";
8
9 +import { deviceSimlockIdentityCheck } from "../../state/device";
10 +import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
11 +
12 import { Button } from "../ui/button";
13 import {
14 Dialog,
@@ -17,10 +24,23 @@ import { Spinner } from "../ui/spinner";
24 import { SecretInput } from "./SecretInput";
25 import {
26 planSimlockDeviceHostSave,
27 + simlockDeviceHostProblem,
28 type SimlockHostEnvironment,
29 type SimlockTokenEntry,
30 } from "./simlockDeviceHostsSettings.logic";
31
32 +const failureMessage = (cause: Cause.Cause<unknown>) => {
33 + const error = Cause.squash(cause);
34 + return error instanceof Error ? error.message : String(error);
35 +};
36 +
37 +/** The gateway each environment's own agent-device points at, if any. */
38 +const machineGatewaysAtom = environmentAtomList("web-simlock-machine-gateways", (environmentId) =>
39 + deviceSimlockIdentityCheck({ environmentId, input: {} }),
40 +);
41 +
42 +const NO_CHECK = Atom.make(AsyncResult.initial()).pipe(Atom.withLabel("simlock-identity:none"));
43 +
44 /** Shared fields once, then one agent token per environment: Simlock counts leases per token. */
45 export function SimlockDeviceHostEditor(props: {
46 host: SimlockDeviceHostConfig;
@@ -34,6 +54,19 @@ export function SimlockDeviceHostEditor(props: {
54 onClose: () => void;
55 }) {
56 const [draft, setDraft] = useState(props.host);
57 + const [urlEdited, setUrlEdited] = useState(false);
58 + const machineGateways = useAtomValue(
59 + machineGatewaysAtom(
60 + environmentIdsKey(
61 + props.isNew ? props.environments.map((environment) => environment.environmentId) : [],
62 + ),
63 + ),
64 + );
65 + // A new host starts at the gateway an environment's agent-device already uses.
66 + const detectedUrl = machineGateways
67 + .map((result) => Option.getOrUndefined(AsyncResult.value(result))?.gatewayUrl)
68 + .find(Boolean);
69 + const gatewayUrl = urlEdited || draft.gatewayUrl ? draft.gatewayUrl : (detectedUrl ?? "");
70 const savedToken = (environment: SimlockHostEnvironment) =>
71 environment.hosts.some((host) => host.id === props.host.id && host.agentToken !== "");
72 const [tokens, setTokens] = useState<ReadonlyMap<EnvironmentId, SimlockTokenEntry>>(
@@ -48,8 +81,9 @@ export function SimlockDeviceHostEditor(props: {
81 const next: SimlockDeviceHostConfig = {
82 ...draft,
83 label: draft.label.trim(),
51 - gatewayUrl: draft.gatewayUrl.trim(),
84 + gatewayUrl: gatewayUrl.trim(),
85 };
86 + const checkUrl = simlockDeviceHostProblem(next) === null ? next.gatewayUrl : null;
87 const plan = planSimlockDeviceHostSave(props.environments, next, tokens);
88 const problem = "problem" in plan ? plan.problem : null;
89 const several = props.environments.length > 1;
@@ -119,10 +153,11 @@ export function SimlockDeviceHostEditor(props: {
153 required
154 type="url"
155 placeholder="https://gateway.example.ts.net:4700"
122 - value={draft.gatewayUrl}
156 + value={gatewayUrl}
157 disabled={props.busy}
158 onChange={(event) => {
159 const gatewayUrl = event.target.value;
160 + setUrlEdited(true);
161 setDraft((current) => ({ ...current, gatewayUrl }));
162 }}
163 />
@@ -131,6 +166,9 @@ export function SimlockDeviceHostEditor(props: {
166 {props.environments.map((environment) => (
167 <SimlockTokenField
168 key={environment.environmentId}
169 + environmentId={environment.environmentId}
170 + hostId={props.isNew ? null : props.host.id}
171 + gatewayUrl={checkUrl}
172 label={several ? `Agent token · ${environment.label}` : "Agent token"}
173 token={tokens.get(environment.environmentId) ?? { kind: "cleared" }}
174 hasSaved={savedToken(environment)}
@@ -142,7 +180,10 @@ export function SimlockDeviceHostEditor(props: {
180 ))}
181 <p className="text-xs text-muted-foreground">
182 Leases, drives, and streams devices. Create one{several ? " per environment" : ""}{" "}
145 - with <code>simlock --gateway token create --role agent</code>.
183 + with <code>simlock --gateway token create --role agent</code>, or leave it blank to
184 + add it later. A blank token uses the machine's{" "}
185 + <code>AGENT_DEVICE_DAEMON_AUTH_TOKEN</code> when its{" "}
186 + <code>AGENT_DEVICE_DAEMON_BASE_URL</code> is this gateway.
187 </p>
188 </div>
189 <div className="grid grid-cols-2 gap-3 text-sm">
@@ -153,7 +194,7 @@ export function SimlockDeviceHostEditor(props: {
194 A lease ends after the lease minutes even while in use.
195 {props.isNew ? null : " Saving restarts this host, which releases its devices."}
196 </p>
156 - {problem === null || !draft.gatewayUrl ? null : (
197 + {problem === null || !gatewayUrl ? null : (
198 <p className="text-xs text-destructive" role="alert">
199 {problem}
200 </p>
@@ -174,6 +215,9 @@ export function SimlockDeviceHostEditor(props: {
215 }
216
217 function SimlockTokenField(props: {
218 + environmentId: EnvironmentId;
219 + hostId: string | null;
220 + gatewayUrl: string | null;
221 label: ReactNode;
222 token: SimlockTokenEntry;
223 hasSaved: boolean;
@@ -181,6 +225,40 @@ function SimlockTokenField(props: {
225 onChange: (token: SimlockTokenEntry) => void;
226 }) {
227 const id = useId();
228 + const entered = props.token.kind === "new" ? props.token.value.trim() : "";
229 + // A cleared field asks about the machine's own token, which a blank one falls back to.
230 + const check = useAtomValue(
231 + props.gatewayUrl === null
232 + ? NO_CHECK
233 + : deviceSimlockIdentityCheck({
234 + environmentId: props.environmentId,
235 + input: {
236 + gatewayUrl: props.gatewayUrl,
237 + ...(entered
238 + ? { agentToken: entered }
239 + : props.token.kind === "saved" && props.hostId !== null
240 + ? { hostId: props.hostId }
241 + : {}),
242 + },
243 + }),
244 + );
245 + const identity = AsyncResult.isSuccess(check) ? check.value : null;
246 + const status =
247 + props.gatewayUrl === null ? null : check._tag === "Initial" || check.waiting ? (
248 + <span className="text-muted-foreground">Checking…</span>
249 + ) : identity ? (
250 + <span className="text-muted-foreground">
251 + {identity.tokenSource === "env"
252 + ? `Using this machine's agent-device token (${identity.signedInAs}).`
253 + : `Accepted as ${identity.signedInAs}.`}
254 + </span>
255 + ) : AsyncResult.isFailure(check) ? (
256 + <span
257 + className={props.token.kind === "cleared" ? "text-muted-foreground" : "text-destructive"}
258 + >
259 + {failureMessage(check.cause)}
260 + </span>
261 + ) : null;
262 return (
263 <div className="space-y-1.5 text-sm">
264 <label htmlFor={id} className="block">
@@ -219,6 +297,7 @@ function SimlockTokenField(props: {
297 </Button>
298 ) : null}
299 </div>
300 + {status ? <p className="text-xs">{status}</p> : null}
301 </div>
302 );
303 }
apps/web/src/components/settings/simlockDeviceHostsSettings.logic.test.ts
+5 -2
@@ -36,7 +36,7 @@ describe("Simlock device host settings", () => {
36 expect(updateSimlockDeviceHosts(renamed, host, true)).toEqual([other]);
37 });
38
39 - it("saves the shared fields everywhere and each environment's own token", () => {
39 + it("saves the shared fields everywhere and each environment's own token, if it has one", () => {
40 const mbp = "mbp" as EnvironmentId;
41 const cups = "cups" as EnvironmentId;
42 const environments = [
@@ -48,7 +48,10 @@ describe("Simlock device host settings", () => {
48 expect(
49 planSimlockDeviceHostSave(environments, draft, new Map([[mbp, { kind: "saved" }]])),
50 ).toEqual({
51 - problem: "Add an agent token for cups.",
51 + patches: [
52 + { environmentId: mbp, hosts: [{ ...draft, agentToken: "<redacted>" }] },
53 + { environmentId: cups, hosts: [{ ...draft, agentToken: "" }] },
54 + ],
55 });
56 expect(
57 planSimlockDeviceHostSave(
apps/web/src/components/settings/simlockDeviceHostsSettings.logic.ts
+1 -2
@@ -62,7 +62,7 @@ export type SimlockTokenEntry =
62
63 /**
64 * The host list each environment saves: the shared fields everywhere, and each environment's own
65 - * token. Saved tokens arrive redacted, and sending the redacted value back keeps them.
65 + * token, which may stay blank until later. Saved tokens arrive redacted; sending one back keeps it.
66 */
67 export function planSimlockDeviceHostSave(
68 environments: ReadonlyArray<SimlockHostEnvironment>,
@@ -84,7 +84,6 @@ export function planSimlockDeviceHostSave(
84 const entry = tokens.get(environment.environmentId) ?? { kind: "cleared" };
85 const agentToken =
86 entry.kind === "saved" ? saved : entry.kind === "new" ? entry.value.trim() : "";
87 - if (!agentToken) return { problem: `Add an agent token for ${environment.label}.` };
87 patches.push({
88 environmentId: environment.environmentId,
89 hosts: updateSimlockDeviceHosts(environment.hosts, { ...draft, agentToken }, false),
apps/web/src/state/device.ts
+11
@@ -171,3 +171,14 @@ export const deviceEasAccountCheck = createEnvironmentRpcQueryAtomFamily(connect
171 staleTimeMs: 0,
172 idleTtlMs: 0,
173 });
174 +
175 +/** Who a Simlock token is, checked as the host editor's URL and token fields change. */
176 +export const deviceSimlockIdentityCheck = createEnvironmentRpcQueryAtomFamily(
177 + connectionAtomRuntime,
178 + {
179 + label: "environment-data:device:simlock-identity-check",
180 + tag: WS_METHODS.deviceSimlockIdentity,
181 + staleTimeMs: 0,
182 + idleTtlMs: 0,
183 + },
184 +);
packages/contracts/src/device.ts
+27
@@ -127,6 +127,33 @@ export const DeviceEasAccount = Schema.Struct({
127 });
128 export type DeviceEasAccount = typeof DeviceEasAccount.Type;
129
130 +export const DeviceSimlockIdentityInput = Schema.Struct({
131 + /** Without one, the gateway this machine's agent-device points at. */
132 + gatewayUrl: Schema.optional(TrimmedString),
133 + /** A saved Simlock host whose stored token is checked when no new token is given. */
134 + hostId: Schema.optional(DeviceHostId),
135 + agentToken: Schema.optional(TrimmedString),
136 +});
137 +export type DeviceSimlockIdentityInput = typeof DeviceSimlockIdentityInput.Type;
138 +
139 +export const DeviceSimlockIdentity = Schema.Struct({
140 + gatewayUrl: Schema.String,
141 + /** The label the gateway gave the token. */
142 + signedInAs: Schema.String,
143 + /** `env`: this machine's AGENT_DEVICE_DAEMON_AUTH_TOKEN, used because it targets this gateway. */
144 + tokenSource: Schema.Literals(["entered", "settings", "env"]),
145 +});
146 +export type DeviceSimlockIdentity = typeof DeviceSimlockIdentity.Type;
147 +
148 +export class DeviceSimlockIdentityError extends Schema.TaggedError<DeviceSimlockIdentityError>()(
149 + "DeviceSimlockIdentityError",
150 + { reason: Schema.String },
151 +) {
152 + override get message(): string {
153 + return this.reason;
154 + }
155 +}
156 +
157 /** Checking an Expo credential failed; no device host is involved yet. */
158 export class DeviceEasAccountError extends Schema.TaggedError<DeviceEasAccountError>()(
159 "DeviceEasAccountError",
packages/contracts/src/rpc.ts
+11
@@ -293,6 +293,9 @@ import {
293 DeviceEasAccount,
294 DeviceEasAccountError,
295 DeviceEasAccountInput,
296 + DeviceSimlockIdentity,
297 + DeviceSimlockIdentityError,
298 + DeviceSimlockIdentityInput,
299 DeviceHostSummary,
300 DeviceOpenInput,
301 DeviceServiceState,
@@ -473,6 +476,7 @@ export const WS_METHODS = {
476 deviceList: "device.list",
477 deviceTestHost: "device.testHost",
478 deviceEasAccount: "device.easAccount",
479 + deviceSimlockIdentity: "device.simlockIdentity",
480 deviceOpen: "device.open",
481 deviceClose: "device.close",
482 deviceShutdown: "device.shutdown",
@@ -1613,6 +1617,12 @@ const WsDeviceEasAccountRpc = Rpc.make(WS_METHODS.deviceEasAccount, {
1617 error: Schema.Union([DeviceEasAccountError, EnvironmentAuthorizationError]),
1618 });
1619
1620 +const WsDeviceSimlockIdentityRpc = Rpc.make(WS_METHODS.deviceSimlockIdentity, {
1621 + payload: DeviceSimlockIdentityInput,
1622 + success: DeviceSimlockIdentity,
1623 + error: Schema.Union([DeviceSimlockIdentityError, EnvironmentAuthorizationError]),
1624 +});
1625 +
1626 const WsDeviceListRpc = Rpc.make(WS_METHODS.deviceList, {
1627 payload: DeviceListInput,
1628 success: DeviceServiceState,
@@ -2088,6 +2098,7 @@ export const WsRpcGroup = RpcGroup.make(
2098 WsDeviceListRpc,
2099 WsDeviceTestHostRpc,
2100 WsDeviceEasAccountRpc,
2101 + WsDeviceSimlockIdentityRpc,
2102 WsDeviceOpenRpc,
2103 WsDeviceCloseRpc,
2104 WsDeviceShutdownRpc,