@devries-cameron20 / t3code Mirror · read-only / commits / be6ff17f51
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): lease simulators and emulators from a Simlock pool (alpha) (#25259)

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

Julius Marminge committed Oct 28, 2026 at 12:09 UTC be6ff17f5171c8a55969ec74af46ff1d86666c3a
41 files changed +2926 -1011
apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx
+1
@@ -411,6 +411,7 @@ function OpenDevicePreview({
411 access={access}
412 platform={session.platform}
413 deviceId={session.deviceId}
414 + serveSimOnly={preview.serveSimOnly}
415 colors={{
416 background: themeVariables["--color-sheet-solid"],
417 foreground: themeVariables["--color-foreground"],
apps/mobile/src/features/devices/DeviceStreamWebView.tsx
+1
@@ -45,6 +45,7 @@ export function DeviceStreamWebView({
45 access: props.access,
46 platform: props.platform,
47 deviceId: props.deviceId,
48 + ...(props.serveSimOnly ? { serveSimOnly: true } : {}),
49 colors: props.colors,
50 });
51 return (
apps/mobile/src/features/devices/device-stream-document.ts
+2
@@ -6,6 +6,8 @@ export interface DeviceStreamConfiguration {
6 readonly access: DeviceHubAccess;
7 readonly platform: DevicePlatform;
8 readonly deviceId: string;
9 + /** See `DeviceStreamTarget.serveSimOnly`. */
10 + readonly serveSimOnly?: boolean;
11 readonly colors: {
12 readonly background: string;
13 readonly foreground: string;
apps/mobile/src/features/devices/threadDevicePreviews.ts
+1
@@ -14,6 +14,7 @@ export function threadDevicePreviews(state: DeviceServiceState | null, threadId:
14 session,
15 name: device?.name ?? (session.platform === "ios" ? "iOS Simulator" : "Android Emulator"),
16 description: [device?.version, host?.label].filter(Boolean).join(" · "),
17 + serveSimOnly: host?.kind === "simlock",
18 };
19 });
20 }
apps/server/src/device/AgentDeviceTarget.ts
+7 -2
@@ -9,7 +9,11 @@ import type { AgentDaemonEndpoint } from "./DeviceHost.ts";
9
10 const encodeEndpoint = Schema.encodeEffect(
11 Schema.fromJsonString(
12 - Schema.Struct({ daemonBaseUrl: Schema.String, daemonAuthToken: Schema.String }),
12 + Schema.Struct({
13 + daemonBaseUrl: Schema.String,
14 + daemonAuthToken: Schema.String,
15 + stateDir: Schema.optionalKey(Schema.String),
16 + }),
17 ),
18 );
19
@@ -40,7 +44,7 @@ export const agentDeviceSession = (threadId: string, hostId: string, deviceId: s
44
45 export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")(function* (
46 file: string,
43 - endpoint: AgentDaemonEndpoint,
47 + endpoint: AgentDaemonEndpoint & { readonly stateDir?: string | undefined },
48 ) {
49 const fs = yield* FileSystem.FileSystem;
50 const path = yield* Path.Path;
@@ -48,6 +52,7 @@ export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")
52 const content = yield* encodeEndpoint({
53 daemonBaseUrl: endpoint.baseUrl,
54 daemonAuthToken: endpoint.token,
55 + ...(endpoint.stateDir === undefined ? {} : { stateDir: endpoint.stateDir }),
56 });
57 if ((yield* fs.readFileString(file).pipe(Effect.orElseSucceed(() => ""))) === content) return;
58 const temporary = yield* fs.makeTempFile({ directory: path.dirname(file), prefix: ".endpoint-" });
apps/server/src/device/DeviceHost.ts
+12 -4
@@ -84,6 +84,17 @@ export interface DeviceOpenContext {
84
85 export type AgentDaemonEndpoint = Pick<AgentDeviceEndpoint, "baseUrl" | "token">;
86
87 +export interface AgentDeviceBinding extends AgentDaemonEndpoint {
88 + /** Null when the session alone picks the device and selector flags would be refused. */
89 + readonly agentDeviceId: string | null;
90 + /** The one session the device is leased to, shared by every thread. */
91 + readonly session?: string;
92 + /** agent-device state holding that session's connection. */
93 + readonly stateDir?: string;
94 + /** agent-device accepts installs into the session only from the directory that opened it. */
95 + readonly installDirectory?: string;
96 +}
97 +
98 /** Where the proxy sends a device hub request, for hosts that serve several upstreams. */
99 export interface HubUpstream {
100 readonly url: string;
@@ -124,10 +135,7 @@ export interface DeviceOperations {
135 */
136 readonly agentEndpoint?: (
137 deviceId: string,
127 - ) => Effect.Effect<
128 - AgentDaemonEndpoint & { readonly agentDeviceId: string },
129 - DeviceHostUnavailableError
130 - >;
138 + ) => Effect.Effect<AgentDeviceBinding, DeviceHostUnavailableError>;
139 /**
140 * Set by hosts that end devices on their own (EAS stops sessions at their
141 * limits), so a session on a device the host stops listing is dropped.
apps/server/src/device/DeviceHubProxy.stream.test.ts
+34
@@ -1,9 +1,12 @@
1 import { expect, it } from "@effect/vitest";
2 import { NodeWS } from "@effect/platform-node/NodeSocket";
3 +import * as NodeNet from "node:net";
4 import * as Context from "effect/Context";
5 import * as Effect from "effect/Effect";
6 +import * as Fiber from "effect/Fiber";
7 import * as Layer from "effect/Layer";
8 import { HttpRouter, HttpServer } from "effect/http";
9 +import * as Socket from "effect/socket/Socket";
10 import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
11 import {
12 AuthOrchestrationOperateScope,
@@ -87,3 +90,34 @@ it.effect("preserves binary input and admission frames through the real socket p
90 expect(frames).toEqual([[0x83], [0x03, 1], [0x03, 2]]);
91 }),
92 );
93 +
94 +it.live("closes an upstream socket that is still connecting without an unhandled error", () =>
95 + Effect.gen(function* () {
96 + const dialed = Promise.withResolvers<NodeNet.Socket>();
97 + // Accepts the connection and never answers the WebSocket handshake.
98 + const hub = yield* Effect.acquireRelease(
99 + Effect.promise(
100 + () =>
101 + new Promise<NodeNet.Server>((resolve) => {
102 + const server = NodeNet.createServer((socket) => dialed.resolve(socket));
103 + server.listen(0, "127.0.0.1", () => resolve(server));
104 + }),
105 + ),
106 + (server) =>
107 + Effect.promise(() => new Promise<void>((resolve) => server.close(() => resolve()))),
108 + );
109 + const address = hub.address();
110 + if (typeof address !== "object" || !address) throw new Error("Missing hub port");
111 + // Handshake headers, as Simlock's routes send, select the `ws` package over the global WebSocket.
112 + const upstream = yield* Socket.makeWebSocket(`ws://127.0.0.1:${address.port}`, {
113 + headers: { authorization: "Bearer test" },
114 + }).pipe(Effect.provide(DeviceHubProxy.upstreamWebSocketConstructor));
115 + const reading = yield* Effect.forkChild(
116 + Effect.scoped(Effect.flatMap(upstream.reader, ({ pull }) => pull)),
117 + );
118 + const connection = yield* Effect.promise(() => dialed.promise);
119 + const abandoned = new Promise<void>((resolve) => connection.once("close", () => resolve()));
120 + yield* Fiber.interrupt(reading);
121 + yield* Effect.promise(() => abandoned);
122 + }),
123 +);
apps/server/src/device/DeviceHubProxy.ts
+24 -2
@@ -2,6 +2,7 @@
2 // Proxy with environment read scope for streams and operate scope for input and tuning.
3 import { AuthOrchestrationReadScope, AuthOrchestrationOperateScope } from "@t3tools/contracts";
4 import * as Effect from "effect/Effect";
5 +import * as Layer from "effect/Layer";
6 import * as Option from "effect/Option";
7 import {
8 HttpClient,
@@ -75,16 +76,32 @@ const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: st
76 return headers;
77 };
78
79 +// Effect drops its listeners before closing a socket that is still connecting, and `ws` then
80 +// emits an `error` nobody handles, which exits the server.
81 +export const upstreamWebSocketConstructor = Layer.effect(
82 + Socket.WebSocketConstructor,
83 + Effect.gen(function* () {
84 + const make = yield* Socket.WebSocketConstructor;
85 + return (url, options) => {
86 + const socket = make(url, options);
87 + socket.addEventListener("error", () => undefined);
88 + return socket;
89 + };
90 + }),
91 +).pipe(Layer.provide(NodeSocket.layerWebSocketConstructor));
92 +
93 const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
94 request: HttpServerRequest.HttpServerRequest,
95 upstreamUrl: string,
96 protocols: ReadonlyArray<string> = [],
97 + headers: Readonly<Record<string, string>> = {},
98 ) {
99 const client = yield* request.upgrade;
100 const upstream = yield* Socket.makeWebSocket(upstreamUrl, {
101 openTimeout: "10 seconds",
102 ...(protocols.length > 0 ? { protocols: [...protocols] } : {}),
87 - }).pipe(Effect.provide(NodeSocket.layerWebSocketConstructor));
103 + ...(Object.keys(headers).length > 0 ? { headers: { ...headers } } : {}),
104 + }).pipe(Effect.provide(upstreamWebSocketConstructor));
105 yield* Effect.scoped(
106 Effect.gen(function* () {
107 const writeToClient = yield* client.writer;
@@ -194,7 +211,12 @@ const handler = Effect.gen(function* () {
211 }
212 const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`;
213 if (upgrade) {
197 - return yield* proxyWebSocket(request, upstreamUrl.replace(/^http/, "ws"), routed?.protocols);
214 + return yield* proxyWebSocket(
215 + request,
216 + upstreamUrl.replace(/^http/, "ws"),
217 + routed?.protocols,
218 + routed?.headers,
219 + );
220 }
221 return yield* proxyHttp(request, upstreamUrl, routed?.headers);
222 });
apps/server/src/device/DeviceService.test.ts
+122 -1
@@ -52,7 +52,7 @@ const fixture = Effect.fn("fixture")(function* (
52 | DeviceHost.AgentDeviceStartError,
53 inspectError = false,
54 installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],
55 - options: { readonly endsDevices?: boolean } = {},
55 + options: { readonly endsDevices?: boolean; readonly routesStreams?: boolean } = {},
56 ) {
57 const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
58 const starts: string[] = [];
@@ -137,6 +137,7 @@ const fixture = Effect.fn("fixture")(function* (
137 },
138 helpers: { serveSimAxSettings: null, serveSimCli: null },
139 run,
140 + ...(options.routesStreams ? { upstream: () => Effect.succeed(null) } : {}),
141 };
142 const host: DeviceHost.DeviceHost["Service"] = {
143 ...(inspectError
@@ -401,6 +402,29 @@ describe("device setup consent", () => {
402 }).pipe(Effect.scoped),
403 );
404
405 + it.effect("opens emulators on hosts that route their own streams without ffmpeg", () =>
406 + Effect.gen(function* () {
407 + const { service, requests, encoderResult } = yield* fixture(
408 + Effect.void,
409 + undefined,
410 + false,
411 + undefined,
412 + false,
413 + undefined,
414 + { routesStreams: true },
415 + );
416 + yield* Ref.set(encoderResult, { code: 127, stdout: "", stderr: "host commands unavailable" });
417 + yield* service.configure({ enabled: true });
418 + const session = yield* service.open({
419 + threadId: ThreadId.make("pool-emulator"),
420 + deviceId: "Pixel_API_35",
421 + platform: "android",
422 + });
423 + expect(session.deviceId).toBe("emulator-5554");
424 + expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
425 + }).pipe(Effect.scoped),
426 + );
427 +
428 it.effect("installs agent support only after the separate agent permission", () =>
429 Effect.gen(function* () {
430 const { service, agentStarts, agentStops, settings } = yield* fixture();
@@ -787,6 +811,103 @@ it.effect.each(["shutdown", "close"] as const)(
811 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
812 );
813
814 +it.effect("leaves a session its host leases to every thread open when one thread closes", () =>
815 + Effect.gen(function* () {
816 + const deviceId = DeviceId.make("33333333-3333-3333-3333-333333333333");
817 + const http = HttpClient.make((request) =>
818 + Effect.sync(() =>
819 + new URL(request.url).pathname === "/api/devices"
820 + ? HttpClientResponse.fromWeb(
821 + request,
822 + Response.json({
823 + emulators: [],
824 + simulators: [
825 + {
826 + id: deviceId,
827 + name: "iPhone",
828 + platform: "ios",
829 + version: "26",
830 + physical: false,
831 + booted: true,
832 + },
833 + ],
834 + }),
835 + )
836 + : HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId })),
837 + ),
838 + );
839 + const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
840 + const ready: DeviceHost.DeviceHostAgentReady = {
841 + nodePath: process.execPath,
842 + hub: { origin: "http://device.test" },
843 + devices: {
844 + ...makeDeviceHubOperations({
845 + hostId: LOCAL_DEVICE_HOST_ID,
846 + origin: "http://device.test",
847 + http,
848 + run,
849 + androidAvailable: Effect.succeed(true),
850 + }),
851 + agentEndpoint: () =>
852 + Effect.succeed({
853 + baseUrl: "http://agent.test",
854 + token: "agent-token",
855 + agentDeviceId: null,
856 + session: "lease-session",
857 + }),
858 + },
859 + helpers: { serveSimAxSettings: null, serveSimCli: null },
860 + run,
861 + agentDevice: null,
862 + };
863 + const host: DeviceHost.DeviceHost["Service"] = {
864 + id: LOCAL_DEVICE_HOST_ID,
865 + label: "Pool",
866 + summary: Effect.succeed({
867 + id: LOCAL_DEVICE_HOST_ID,
868 + kind: "local",
869 + label: "Pool",
870 + platforms: [{ platform: "ios", available: true }],
871 + hubInstalled: true,
872 + agentDeviceInstalled: true,
873 + }),
874 + platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
875 + ensureReady: () => Effect.succeed(ready),
876 + ensureAgentReady: () => Effect.succeed(ready),
877 + current: Effect.succeed(ready),
878 + stopAgent: Effect.void,
879 + stop: Effect.void,
880 + };
881 + const released: string[] = [];
882 + const service = yield* DeviceService.makeWithHosts(
883 + new Map([[host.id, host]]),
884 + undefined,
885 + () => Effect.succeed("agent-device.json"),
886 + undefined,
887 + {
888 + bind: ({ session }) => Effect.succeed(session),
889 + prune: () => Effect.void,
890 + release: (launcher) => Effect.sync(() => void released.push(launcher)),
891 + },
892 + ).pipe(Effect.provide(NodeCrypto.layer));
893 + const threads = [ThreadId.make("pool-a"), ThreadId.make("pool-b")];
894 + for (const threadId of threads) {
895 + yield* service.open({ threadId, deviceId, platform: "ios" });
896 + const target = { threadId, hostId: LOCAL_DEVICE_HOST_ID, deviceId };
897 + const agent = yield* service.agentTarget(target);
898 + expect(agent.session).toBe("lease-session");
899 + yield* service.agentLauncher({ ...target, targetArgs: agent.args });
900 + }
901 + yield* service.close({ threadId: threads[0]! });
902 + expect(released).toEqual([]);
903 + }).pipe(
904 + Effect.provide(
905 + ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),
906 + ),
907 + Effect.scoped,
908 + ),
909 +);
910 +
911 it.effect.each([
912 { hubReports: "off", outcome: "succeeds" },
913 { hubReports: "booted", outcome: "fails" },
apps/server/src/device/DeviceService.ts
+92 -37
@@ -22,6 +22,7 @@ import {
22 type DeviceEasAccountInput,
23 type DeviceHostConfig,
24 type EasDeviceHostConfig,
25 + type SimlockDeviceHostConfig,
26 type SshDeviceHostConfig,
27 type DeviceHostSummary,
28 LOCAL_DEVICE_HOST_ID,
@@ -67,6 +68,7 @@ import * as ProcessRunner from "../processRunner.ts";
68 import * as DeviceHost from "./DeviceHost.ts";
69 import * as SshDeviceHost from "./SshDeviceHost.ts";
70 import * as EasDeviceHost from "./EasDeviceHost.ts";
71 +import * as SimlockDeviceHost from "./SimlockDeviceHost.ts";
72 import { makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";
73 import * as Exit from "effect/Exit";
74 import * as LocalDeviceHost from "./LocalDeviceHost.ts";
@@ -150,9 +152,10 @@ export class DeviceService extends Context.Service<
152 deviceId: DeviceId;
153 }) => Effect.Effect<
154 {
153 - readonly agentDeviceId: string;
155 + readonly agentDeviceId: string | null;
156 readonly session: string;
157 readonly args: ReadonlyArray<string>;
158 + readonly installDirectory?: string | undefined;
159 },
160 DeviceError
161 >;
@@ -247,7 +250,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
250 ),
251 configureAgent: (
252 hostId: DeviceHostId,
250 - endpoint: DeviceHost.AgentDaemonEndpoint,
253 + endpoint: DeviceHost.AgentDaemonEndpoint & { readonly stateDir?: string | undefined },
254 deviceId?: DeviceId,
255 ) => Effect.Effect<string, DeviceError> = (hostId) =>
256 Effect.fail(
@@ -284,6 +287,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
287 supportsToolUpdate: installTool !== undefined,
288 supportsToolInspection: true,
289 supportsEasHosts: true,
290 + supportsSimlockHosts: true,
291 hosts: initialHosts,
292 hostStatus: initialSettings.enabled ? "idle" : "disabled",
293 hostStatuses: {},
@@ -299,6 +303,8 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
303 const launcherLock = yield* Semaphore.make(1);
304 /** Launchers bound since startup, by agent-device session. */
305 const boundLaunchers = new Map<string, string>();
306 + /** Launchers on a session the host leases to every thread; the host ends it, not a retiring thread. */
307 + const hostSessionLaunchers = new Set<string>();
308 // Binding and pruning read sessions under the lock, so neither acts on a session list the other has outdated.
309 // A retired session's agent-device session ends before its launcher goes, and a reopen of the same
310 // device waits for the lock, so the close cannot end the reopened session.
@@ -313,9 +319,10 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
319 );
320 const retired = [...boundLaunchers].filter(([session]) => !live.has(session));
321 for (const [session] of retired) boundLaunchers.delete(session);
322 + const ending = retired.filter(([session]) => !hostSessionLaunchers.delete(session));
323 const release = launchers.release;
324 if (release)
318 - yield* Effect.forEach(retired, ([, launcher]) => release(launcher), {
325 + yield* Effect.forEach(ending, ([, launcher]) => release(launcher), {
326 concurrency: "unbounded",
327 discard: true,
328 });
@@ -703,7 +710,8 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
710 if (!device) {
711 return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });
712 }
706 - if (device.platform === "android" && !device.physical) {
713 + // Hosts that route their own streams never encode emulator video with serve-emu's ffmpeg.
714 + if (device.platform === "android" && !device.physical && !ready.upstream) {
715 // Resolve the override on the device host the way its hub does.
716 const encoders = yield* ready.run(ready.nodePath, [
717 "-e",
@@ -1014,39 +1022,51 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
1022 reason:
1023 "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
1024 });
1017 - const { configPath, agentDeviceId } = yield* lifecycleLock.withPermit(
1018 - Effect.gen(function* () {
1019 - if (hosts.get(host.id) !== host)
1020 - return yield* new DeviceHostUnavailableError({
1021 - hostId: host.id,
1022 - hostLabel: host.label,
1023 - reason: "Host configuration changed. Retry the operation.",
1024 - });
1025 - if (ready.devices.agentEndpoint) {
1026 - const endpoint = yield* ready.devices.agentEndpoint(input.deviceId);
1025 + const { configPath, agentDeviceId, boundSession, installDirectory } =
1026 + yield* lifecycleLock.withPermit(
1027 + Effect.gen(function* () {
1028 + if (hosts.get(host.id) !== host)
1029 + return yield* new DeviceHostUnavailableError({
1030 + hostId: host.id,
1031 + hostLabel: host.label,
1032 + reason: "Host configuration changed. Retry the operation.",
1033 + });
1034 + if (ready.devices.agentEndpoint) {
1035 + const endpoint = yield* ready.devices.agentEndpoint(input.deviceId);
1036 + return {
1037 + configPath: yield* configureAgent(input.hostId, endpoint, input.deviceId),
1038 + agentDeviceId: endpoint.agentDeviceId,
1039 + boundSession: endpoint.session,
1040 + installDirectory: endpoint.installDirectory,
1041 + };
1042 + }
1043 + if (!ready.agentDevice)
1044 + return yield* new DeviceHostUnavailableError({
1045 + hostId: host.id,
1046 + hostLabel: host.label,
1047 + reason: "This host has no agent-device daemon.",
1048 + });
1049 return {
1028 - configPath: yield* configureAgent(input.hostId, endpoint, input.deviceId),
1029 - agentDeviceId: endpoint.agentDeviceId,
1050 + configPath: yield* configureAgent(input.hostId, ready.agentDevice),
1051 + agentDeviceId: input.deviceId,
1052 + boundSession: undefined,
1053 + installDirectory: undefined,
1054 };
1031 - }
1032 - if (!ready.agentDevice)
1033 - return yield* new DeviceHostUnavailableError({
1034 - hostId: host.id,
1035 - hostLabel: host.label,
1036 - reason: "This host has no agent-device daemon.",
1037 - });
1038 - return {
1039 - configPath: yield* configureAgent(input.hostId, ready.agentDevice),
1040 - agentDeviceId: input.deviceId,
1041 - };
1042 - }),
1043 - );
1044 - const session = yield* agentDeviceSession(
1055 + }),
1056 + );
1057 + const ownSession = yield* agentDeviceSession(
1058 input.threadId,
1059 input.hostId,
1060 input.deviceId,
1061 ).pipe(Effect.provideService(Crypto.Crypto, crypto));
1049 - return { agentDeviceId, session, args: ["--config", configPath, "--session", session] };
1062 + if (boundSession) hostSessionLaunchers.add(ownSession);
1063 + const session = boundSession ?? ownSession;
1064 + return {
1065 + agentDeviceId,
1066 + session,
1067 + args: ["--config", configPath, "--session", session],
1068 + installDirectory,
1069 + };
1070 }),
1071 agentLauncher: Effect.fn("DeviceService.agentLauncher")(function* ({
1072 targetArgs,
@@ -1139,7 +1159,7 @@ export const make = Effect.gen(function* () {
1159 const configureAgent = Effect.fn("DeviceService.configureAgent")(
1160 function* (
1161 hostId: DeviceHostId,
1142 - endpoint: DeviceHost.AgentDaemonEndpoint,
1162 + endpoint: DeviceHost.AgentDaemonEndpoint & { readonly stateDir?: string | undefined },
1163 deviceId?: DeviceId,
1164 ) {
1165 const file = yield* configPath(hostId, deviceId);
@@ -1290,6 +1310,23 @@ export const make = Effect.gen(function* () {
1310 yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
1311 const easContext =
1312 yield* Effect.context<Effect.Services<ReturnType<typeof EasDeviceHost.make>>>();
1313 + const simlockContext =
1314 + yield* Effect.context<Effect.Services<ReturnType<typeof SimlockDeviceHost.make>>>();
1315 + const simlockAgentCli = Effect.fn("DeviceService.simlockAgentCli")(
1316 + function* (hostId: string) {
1317 + const nodePath = yield* resolveNodeExecutable("Device automation");
1318 + const tool = yield* ensureAgentDevice(config.baseDir).pipe(
1319 + Effect.mapError(
1320 + (cause) =>
1321 + new DeviceHost.DeviceHostError({ hostId, step: "installing agent tools", cause }),
1322 + ),
1323 + );
1324 + return { nodePath, entryPath: tool.entryPath };
1325 + },
1326 + Effect.provideService(FileSystem.FileSystem, fs),
1327 + Effect.provideService(Path.Path, path),
1328 + Effect.provideService(ProcessRunner.ProcessRunner, runner),
1329 + );
1330 const configured = new Map<string, { config: DeviceHostConfig; scope: Scope.Closeable }>();
1331 const unchanged = (current: DeviceHostConfig, previous: DeviceHostConfig) =>
1332 current.kind === "ssh" && previous.kind === "ssh"
@@ -1334,6 +1371,16 @@ export const make = Effect.gen(function* () {
1371 if (configured.has(host.id)) continue;
1372 added = true;
1373 const hostScope = yield* Scope.fork(scope);
1374 + if (host.kind === "simlock") {
1375 + // Closing this scope releases the host's leases back to the pool.
1376 + const instance = yield* SimlockDeviceHost.make(host, simlockAgentCli(host.id)).pipe(
1377 + Effect.provideService(Scope.Scope, hostScope),
1378 + Effect.provide(simlockContext),
1379 + );
1380 + hosts.set(host.id, instance);
1381 + configured.set(host.id, { config: host, scope: hostScope });
1382 + continue;
1383 + }
1384 if (host.kind === "eas") {
1385 // Closing this scope stops the host's running sessions, so a changed
1386 // limit or token never leaves a billed session behind.
@@ -1375,14 +1422,22 @@ export const make = Effect.gen(function* () {
1422 );
1423 });
1424 const changes = yield* settings.subscribeChanges;
1378 - // Settings keep EAS hosts apart from SSH hosts; an id both lists use stays the SSH host's.
1425 + // Each kind has its own settings list; an id two lists share stays the first one's.
1426 const configuredHosts = (value: {
1427 readonly deviceHosts: ReadonlyArray<SshDeviceHostConfig>;
1428 readonly easDeviceHosts: ReadonlyArray<EasDeviceHostConfig>;
1382 - }): ReadonlyArray<DeviceHostConfig> => [
1383 - ...value.deviceHosts,
1384 - ...value.easDeviceHosts.filter((host) => !value.deviceHosts.some((ssh) => ssh.id === host.id)),
1385 - ];
1429 + readonly simlockDeviceHosts: ReadonlyArray<SimlockDeviceHostConfig>;
1430 + readonly simlockDeviceHostsEnabled: boolean;
1431 + }): ReadonlyArray<DeviceHostConfig> => {
1432 + const hosts: Array<DeviceHostConfig> = [...value.deviceHosts];
1433 + for (const host of [
1434 + ...value.easDeviceHosts,
1435 + ...(value.simlockDeviceHostsEnabled ? value.simlockDeviceHosts : []),
1436 + ]) {
1437 + if (!hosts.some((existing) => existing.id === host.id)) hosts.push(host);
1438 + }
1439 + return hosts;
1440 + };
1441 yield* reconcile(configuredHosts(yield* settings.getSettings));
1442 yield* changes.pipe(
1443 Stream.runForEach((value) => reconcile(configuredHosts(value))),
apps/server/src/device/EasDeviceHost.test.ts
+19
@@ -1,6 +1,7 @@
1 import { describe, expect, it } from "@effect/vitest";
2 import * as NodeServices from "@effect/platform-node/NodeServices";
3 import type { EasDeviceHostConfig } from "@t3tools/contracts";
4 +import * as HostProcess from "@t3tools/shared/HostProcess";
5 import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 import * as Fiber from "effect/Fiber";
@@ -455,6 +456,24 @@ describe("EAS Simulator host", () => {
456 }).pipe(Effect.scoped, Effect.provide(layer)),
457 );
458
459 + it.effect("reports iOS unavailable on a server with no Expo credential", () =>
460 + Effect.gen(function* () {
461 + const fs = yield* FileSystem.FileSystem;
462 + const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-expo-home-" });
463 + const host = yield* makeHost(
464 + fakeExpo(),
465 + config({ accessToken: "" }),
466 + yield* Scope.make(),
467 + ).pipe(
468 + Effect.provideService(HostProcess.HomeDirectory, home),
469 + Effect.provideService(HostProcess.Environment, {}),
470 + );
471 + const [ios] = (yield* host.summary).platforms;
472 + expect(ios).toMatchObject({ platform: "ios", available: false });
473 + expect(ios?.reason).toContain("No Expo credential on the server");
474 + }).pipe(Effect.scoped, Effect.provide(layer)),
475 + );
476 +
477 it.effect("stops a session that is still starting when the host stops", () =>
478 Effect.gen(function* () {
479 const previewGate = yield* makeGate;
apps/server/src/device/EasDeviceHost.ts
+15 -9
@@ -830,16 +830,22 @@ export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDevice
830 ),
831 );
832
833 + // Each server signs in on its own, so one with no Expo credential answers for itself. Reading
834 + // the credential is local; whether Expo accepts it is only known once a session starts.
835 const platformAvailability = (platform: DevicePlatform) =>
834 - Effect.succeed(
835 - platform === "ios"
836 - ? { platform, available: true }
837 - : {
838 - platform,
839 - available: false,
840 - reason: "EAS Simulator Android emulators are not supported yet.",
841 - },
842 - );
836 + platform === "ios"
837 + ? resolveExpoCredential(config.accessToken).pipe(
838 + Effect.provide(services),
839 + Effect.as({ platform, available: true }),
840 + Effect.catch((error) =>
841 + Effect.succeed({ platform, available: false, reason: error.message }),
842 + ),
843 + )
844 + : Effect.succeed({
845 + platform,
846 + available: false,
847 + reason: "EAS Simulator Android emulators are not supported yet.",
848 + });
849
850 const summary: Effect.Effect<DeviceHostSummary> = Effect.all([
851 platformAvailability("ios"),
apps/server/src/device/SimlockDeviceHost.test.ts new
+335
@@ -0,0 +1,335 @@
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 Effect from "effect/Effect";
5 +import * as Fiber from "effect/Fiber";
6 +import * as Deferred from "effect/Deferred";
7 +import * as Exit from "effect/Exit";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Layer from "effect/Layer";
10 +import * as Path from "effect/Path";
11 +import * as Scope from "effect/Scope";
12 +import * as TestClock from "effect/testing/TestClock";
13 +import { HttpClient, HttpClientResponse } from "effect/http";
14 +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15 +
16 +import * as ServerConfig from "../config.ts";
17 +import * as ProcessRunner from "../processRunner.ts";
18 +import * as SimlockDeviceHost from "./SimlockDeviceHost.ts";
19 +
20 +const GATEWAY = "https://simlock.test:4700";
21 +
22 +const config = (overrides: Partial<SimlockDeviceHostConfig> = {}): SimlockDeviceHostConfig => ({
23 + kind: "simlock",
24 + id: "pool",
25 + label: "Device pool",
26 + gatewayUrl: `${GATEWAY}/`,
27 + agentToken: "agent-token",
28 + maxLeases: 2,
29 + maxLeaseMinutes: 60,
30 + ...overrides,
31 +});
32 +
33 +const CATALOG = {
34 + platforms: [
35 + {
36 + platform: "ios",
37 + modelRuntimes: { "iPhone 17 Pro": ["27.0"], "Apple TV 4K": ["27.0"], "iPhone 12": [] },
38 + modelClasses: { "iPhone 17 Pro": "phone", "Apple TV 4K": "tv", "iPhone 12": "phone" },
39 + },
40 + {
41 + platform: "android",
42 + modelRuntimes: { "Pixel 9": ["36"], "Pixel 8": ["36"] },
43 + modelWorkers: { "Pixel 9": ["worker-a"], "Pixel 8": [] },
44 + },
45 + ],
46 +};
47 +
48 +/** The gateway's HTTP API and T3's agent-device CLI, recording what was asked of them. */
49 +const fakePool = (
50 + options: {
51 + readonly failOpen?: boolean;
52 + readonly holdOpen?: {
53 + readonly entered: Deferred.Deferred<void>;
54 + readonly proceed: Deferred.Deferred<void>;
55 + };
56 + } = {},
57 +) =>
58 + Effect.gen(function* () {
59 + const fs = yield* FileSystem.FileSystem;
60 + const path = yield* Path.Path;
61 + const requests: Array<string> = [];
62 + const commands: Array<{ readonly args: ReadonlyArray<string>; readonly cwd?: string }> = [];
63 + let leases = 0;
64 + let renewStatus = 200;
65 + const http = HttpClient.make((request) =>
66 + Effect.sync(() => {
67 + const url = new URL(request.url);
68 + requests.push(`${request.method} ${url.pathname}`);
69 + expect(request.headers.authorization).toBe("Bearer agent-token");
70 + const json = (body: unknown, status = 200) =>
71 + HttpClientResponse.fromWeb(request, Response.json(body, { status }));
72 + if (url.pathname === "/v1/catalog") return json(CATALOG);
73 + if (url.pathname.endsWith("/renew")) return json({}, renewStatus);
74 + if (request.method === "DELETE") return json({}, 202);
75 + return json({}, 404);
76 + }),
77 + );
78 + const runner = ProcessRunner.ProcessRunner.of({
79 + run: (input) =>
80 + Effect.gen(function* () {
81 + const args = input.args.slice(1);
82 + commands.push({ args, ...(input.cwd ? { cwd: input.cwd } : {}) });
83 + const command = args[0];
84 + const session = args[args.indexOf("--session") + 1]!;
85 + const configFile = args[args.indexOf("--config") + 1]!;
86 + const stateDir = (
87 + JSON.parse(yield* fs.readFileString(configFile)) as { stateDir: string }
88 + ).stateDir;
89 + if (command === "open") {
90 + if (options.failOpen) {
91 + return {
92 + stdout: JSON.stringify({
93 + error: { message: "No device matches.", hint: "Retry." },
94 + }),
95 + stderr: "",
96 + code: ChildProcessSpawner.ExitCode(1),
97 + timedOut: false,
98 + stdoutTruncated: false,
99 + stderrTruncated: false,
100 + stdoutInvalidUtf8: false,
101 + stderrInvalidUtf8: false,
102 + };
103 + }
104 + if (options.holdOpen) {
105 + yield* Deferred.succeed(options.holdOpen.entered, undefined);
106 + yield* Deferred.await(options.holdOpen.proceed);
107 + }
108 + const dir = path.join(stateDir, "remote-connections");
109 + yield* fs.makeDirectory(dir, { recursive: true });
110 + yield* fs.writeFileString(
111 + path.join(dir, `${session}.json`),
112 + JSON.stringify({ leaseId: `lease-${++leases}` }),
113 + );
114 + }
115 + if (command === "screenshot") yield* fs.writeFile(args[1]!, new Uint8Array([1, 2, 3]));
116 + return {
117 + stdout: "{}",
118 + stderr: "",
119 + code: ChildProcessSpawner.ExitCode(0),
120 + timedOut: false,
121 + stdoutTruncated: false,
122 + stderrTruncated: false,
123 + stdoutInvalidUtf8: false,
124 + stderrInvalidUtf8: false,
125 + };
126 + }).pipe(Effect.orDie),
127 + });
128 + const ran = (command: string) => commands.filter(({ args }) => args[0] === command);
129 + return {
130 + http,
131 + runner,
132 + requests,
133 + ran,
134 + endLeases: () => {
135 + renewStatus = 404;
136 + },
137 + };
138 + });
139 +
140 +const layer = Layer.mergeAll(
141 + ServerConfig.layerTest(process.cwd(), { prefix: "t3-simlock-host-" }),
142 +).pipe(Layer.provideMerge(NodeServices.layer));
143 +
144 +const makeHost = (
145 + pool: Effect.Success<ReturnType<typeof fakePool>>,
146 + hostConfig: SimlockDeviceHostConfig,
147 + scope: Scope.Scope,
148 +) =>
149 + SimlockDeviceHost.make(
150 + hostConfig,
151 + Effect.succeed({ nodePath: "node", entryPath: "/tools/agent-device.mjs" }),
152 + ).pipe(
153 + Effect.provideService(HttpClient.HttpClient, pool.http),
154 + Effect.provideService(ProcessRunner.ProcessRunner, pool.runner),
155 + Effect.provideService(Scope.Scope, scope),
156 + );
157 +
158 +describe("Simlock device host", () => {
159 + it.effect("leases a pool device for agents and serves its screen and input to the panel", () =>
160 + Effect.gen(function* () {
161 + const pool = yield* fakePool();
162 + const fs = yield* FileSystem.FileSystem;
163 + const workspace = yield* fs.makeTempDirectoryScoped();
164 + const scope = yield* Scope.make();
165 + const host = yield* makeHost(pool, config(), scope);
166 + const ready = yield* host.ensureReady(() => Effect.void);
167 +
168 + const catalog = (yield* ready.devices.list).devices;
169 + // Only models a worker can make right now, and only phones and tablets.
170 + expect(catalog.map((device) => [device.id, device.version])).toEqual([
171 + ["simlock:ios:iPhone 17 Pro", "iOS 27.0"],
172 + ["simlock:android:Pixel 9", "Android 36"],
173 + ]);
174 +
175 + const leaseId = yield* ready.devices.boot(catalog[1]!, { workspaceRoot: workspace });
176 + expect(leaseId).toBe("lease-1");
177 + const [open] = pool.ran("open");
178 + expect(open?.args.slice(0, 5)).toEqual([
179 + "open",
180 + "--platform",
181 + "android",
182 + "--device",
183 + "Pixel 9",
184 + ]);
185 + expect(open?.cwd).toBe(yield* fs.realPath(workspace));
186 + expect(pool.ran("connect")[0]?.args).toContain(`${GATEWAY}/v1/agent-device`);
187 +
188 + const binding = yield* ready.devices.agentEndpoint!(leaseId);
189 + expect(binding).toMatchObject({
190 + baseUrl: `${GATEWAY}/v1/agent-device`,
191 + token: "agent-token",
192 + agentDeviceId: null,
193 + session: open?.args[open.args.indexOf("--session") + 1],
194 + installDirectory: yield* fs.realPath(workspace),
195 + });
196 + expect((yield* ready.devices.list).devices.at(-1)).toMatchObject({
197 + id: "lease-1",
198 + name: "Pixel 9",
199 + booted: true,
200 + });
201 +
202 + expect(
203 + yield* ready.upstream!(
204 + "/vendor/serve-sim/helper/lease-1/stream.avcc",
205 + new URLSearchParams(),
206 + ),
207 + ).toEqual({
208 + url: `${GATEWAY}/v1/leases/lease-1/stream`,
209 + headers: { authorization: "Bearer agent-token" },
210 + protocols: [],
211 + });
212 + expect(
213 + yield* ready.upstream!(
214 + "/vendor/serve-sim/helper/ws",
215 + new URLSearchParams({ device: "lease-1" }),
216 + ),
217 + ).toEqual({
218 + url: `${GATEWAY}/v1/leases/lease-1/input`,
219 + headers: { authorization: "Bearer agent-token" },
220 + protocols: [],
221 + });
222 + expect(
223 + yield* ready.upstream!("/vendor/serve-sim/helper/lease-1/config", new URLSearchParams()),
224 + ).toBeNull();
225 + expect(
226 + yield* ready.upstream!(
227 + "/vendor/serve-sim/helper/ws",
228 + new URLSearchParams({ device: "lease-2" }),
229 + ),
230 + ).toBeNull();
231 + expect([...(yield* ready.devices.screenshot({ ...catalog[1]!, id: leaseId }))]).toEqual([
232 + 1, 2, 3,
233 + ]);
234 +
235 + yield* ready.devices.shutdown({ id: leaseId, platform: "android" });
236 + expect(pool.ran("close")).toHaveLength(1);
237 + expect((yield* ready.devices.list).devices.some((device) => device.booted)).toBe(false);
238 + yield* Scope.close(scope, Exit.void);
239 + expect(pool.ran("close")).toHaveLength(1);
240 + }).pipe(Effect.scoped, Effect.provide(layer)),
241 + );
242 +
243 + it.effect("caps leases at the limit", () =>
244 + Effect.gen(function* () {
245 + const pool = yield* fakePool();
246 + const scope = yield* Scope.make();
247 + const host = yield* makeHost(pool, config({ maxLeases: 1 }), scope);
248 + const ready = yield* host.ensureReady(() => Effect.void);
249 + const [iphone] = (yield* ready.devices.list).devices;
250 + yield* ready.devices.boot(iphone!);
251 +
252 + const refused = yield* ready.devices.boot(iphone!).pipe(Effect.flip);
253 + expect(refused.message).toContain("limited to 1 device");
254 + expect(pool.ran("open")).toHaveLength(1);
255 + yield* Scope.close(scope, Exit.void);
256 + expect(pool.ran("close")).toHaveLength(1);
257 + }).pipe(Effect.scoped, Effect.provide(layer)),
258 + );
259 +
260 + it.effect("closes the session of a failed open so no lease is left behind", () =>
261 + Effect.gen(function* () {
262 + const pool = yield* fakePool({ failOpen: true });
263 + const scope = yield* Scope.make();
264 + const host = yield* makeHost(pool, config(), scope);
265 + const ready = yield* host.ensureReady(() => Effect.void);
266 + const [iphone] = (yield* ready.devices.list).devices;
267 + const failure = yield* ready.devices.boot(iphone!).pipe(Effect.flip);
268 + expect(String(failure.cause)).toContain("No device matches. Retry.");
269 + expect(pool.ran("close")).toHaveLength(1);
270 + // The failed open freed its slot.
271 + expect(yield* ready.devices.boot(iphone!).pipe(Effect.flip)).toBeDefined();
272 + yield* Scope.close(scope, Exit.void);
273 + }).pipe(Effect.scoped, Effect.provide(layer)),
274 + );
275 +
276 + it.effect("keeps a watched lease renewed and stops listing it once Simlock ends it", () =>
277 + Effect.gen(function* () {
278 + const pool = yield* fakePool();
279 + const scope = yield* Scope.make();
280 + const host = yield* makeHost(pool, config(), scope);
281 + const ready = yield* host.ensureReady(() => Effect.void);
282 + const [iphone] = (yield* ready.devices.list).devices;
283 + const leaseId = yield* ready.devices.boot(iphone!);
284 +
285 + yield* TestClock.adjust("2 minutes");
286 + expect(pool.requests).toContain(`POST /v1/leases/${leaseId}/renew`);
287 + expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe(
288 + true,
289 + );
290 +
291 + pool.endLeases();
292 + yield* TestClock.adjust("2 minutes");
293 + expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe(
294 + false,
295 + );
296 + yield* Scope.close(scope, Exit.void);
297 + expect(pool.ran("close")).toHaveLength(0);
298 + }).pipe(Effect.scoped, Effect.provide(layer)),
299 + );
300 +
301 + it.effect("returns a lease whose open finishes after the host stopped", () =>
302 + Effect.gen(function* () {
303 + const holdOpen = {
304 + entered: yield* Deferred.make<void>(),
305 + proceed: yield* Deferred.make<void>(),
306 + };
307 + const pool = yield* fakePool({ holdOpen });
308 + const host = yield* makeHost(pool, config(), yield* Scope.make());
309 + const ready = yield* host.ensureReady(() => Effect.void);
310 + const [iphone] = (yield* ready.devices.list).devices;
311 + const opening = yield* Effect.forkChild(ready.devices.boot(iphone!));
312 + yield* Deferred.await(holdOpen.entered);
313 + yield* host.stop;
314 + yield* Deferred.succeed(holdOpen.proceed, undefined);
315 + expect(Exit.isFailure(yield* Fiber.await(opening))).toBe(true);
316 + expect(pool.ran("close")).toHaveLength(1);
317 + expect((yield* ready.devices.list).devices.every((device) => !device.booted)).toBe(true);
318 + }).pipe(Effect.scoped, Effect.provide(layer)),
319 + );
320 +
321 + it.effect("holds a lease for its full maximum age, then returns it", () =>
322 + Effect.gen(function* () {
323 + const pool = yield* fakePool();
324 + const host = yield* makeHost(pool, config({ maxLeaseMinutes: 5 }), yield* Scope.make());
325 + const ready = yield* host.ensureReady(() => Effect.void);
326 + const [iphone] = (yield* ready.devices.list).devices;
327 + yield* ready.devices.boot(iphone!);
328 +
329 + yield* TestClock.adjust("299 seconds");
330 + expect(pool.ran("close")).toHaveLength(0);
331 + yield* TestClock.adjust("1 second");
332 + expect(pool.ran("close")).toHaveLength(1);
333 + }).pipe(Effect.scoped, Effect.provide(layer)),
334 + );
335 +});
apps/server/src/device/SimlockDeviceHost.ts new
+545
@@ -0,0 +1,545 @@
1 +/**
2 + * Alpha: devices leased from a Simlock gateway the user runs. Opening a device
3 + * takes a lease through the gateway's agent-device front, so agents drive it
4 + * with the same session; closing it returns the device to the pool, wiped.
5 + * A lease left by a server that crashed ends one TTL after its last renewal.
6 + */
7 +import {
8 + DeviceBootError,
9 + type DeviceHostSummary,
10 + DeviceHostUnavailableError,
11 + DeviceOperationError,
12 + type DevicePlatform,
13 + type SimlockDeviceHostConfig,
14 +} from "@t3tools/contracts";
15 +import * as Clock from "effect/Clock";
16 +import * as Duration from "effect/Duration";
17 +import * as Effect from "effect/Effect";
18 +import * as FiberMap from "effect/FiberMap";
19 +import * as FileSystem from "effect/FileSystem";
20 +import * as Option from "effect/Option";
21 +import * as Path from "effect/Path";
22 +import * as Random from "effect/Random";
23 +import * as Schema from "effect/Schema";
24 +import * as Semaphore from "effect/Semaphore";
25 +import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
26 +import * as HostProcess from "@t3tools/shared/HostProcess";
27 +import type { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
28 +
29 +import * as ServerConfig from "../config.ts";
30 +import * as ProcessRunner from "../processRunner.ts";
31 +import { writeAgentDeviceConfig } from "./AgentDeviceTarget.ts";
32 +import * as DeviceHost from "./DeviceHost.ts";
33 +
34 +const CATALOG_TTL_MS = 60_000;
35 +const REQUEST_TIMEOUT = Duration.seconds(15);
36 +// The gateway queues a lease request for up to five minutes when every device is busy.
37 +const OPEN_TIMEOUT = Duration.minutes(7);
38 +const COMMAND_TIMEOUT = Duration.minutes(2);
39 +// Renewal keeps a watched but idle device; a lease this server stops renewing ends after LEASE_TTL.
40 +const RENEW_INTERVAL = Duration.minutes(2);
41 +const LEASE_TTL_MS = 10 * 60_000;
42 +const STREAM_PATH = /^\/vendor\/serve-sim\/helper\/([^/]+)\/stream\.avcc$/;
43 +const INPUT_PATH = "/vendor/serve-sim/helper/ws";
44 +
45 +const Catalog = Schema.Struct({
46 + platforms: Schema.Array(
47 + Schema.Struct({
48 + platform: Schema.String,
49 + modelRuntimes: Schema.Record(Schema.String, Schema.Array(Schema.String)),
50 + modelClasses: Schema.optional(Schema.Record(Schema.String, Schema.String)),
51 + modelWorkers: Schema.optional(Schema.Record(Schema.String, Schema.Array(Schema.String))),
52 + }),
53 + ),
54 +});
55 +const decodeCatalog = Schema.decodeUnknownEffect(Catalog);
56 +const decodeSessionRecord = Schema.decodeUnknownEffect(
57 + Schema.fromJsonString(Schema.Struct({ leaseId: Schema.String })),
58 +);
59 +const decodeCliFailure = Schema.decodeUnknownOption(
60 + Schema.fromJsonString(
61 + Schema.Struct({
62 + error: Schema.Struct({ message: Schema.String, hint: Schema.optional(Schema.String) }),
63 + }),
64 + ),
65 +);
66 +
67 +interface Lease {
68 + readonly leaseId: string;
69 + readonly platform: DevicePlatform;
70 + readonly name: string;
71 + readonly version: string;
72 + readonly session: string;
73 + readonly dir: string;
74 + readonly configPath: string;
75 + readonly installDirectory: string;
76 +}
77 +
78 +const catalogId = (platform: DevicePlatform, model: string) => `simlock:${platform}:${model}`;
79 +const parseCatalogId = (id: string) => {
80 + const match = /^simlock:(ios|android):(.+)$/.exec(id);
81 + return match ? { platform: match[1] as DevicePlatform, model: match[2]! } : null;
82 +};
83 +const platformVersion = (platform: DevicePlatform, runtime: string | undefined) =>
84 + `${platform === "ios" ? "iOS" : "Android"}${runtime ? ` ${runtime}` : ""}`;
85 +
86 +/** T3's own agent-device CLI, installed on first use. */
87 +export type AgentDeviceCli = Effect.Effect<
88 + { readonly nodePath: string; readonly entryPath: string },
89 + DeviceHost.DeviceHostError | NodeRuntimeUnavailableError
90 +>;
91 +
92 +export const make = Effect.fn("SimlockDeviceHost.make")(function* (
93 + config: SimlockDeviceHostConfig,
94 + agentDeviceCli: AgentDeviceCli,
95 +) {
96 + const http = yield* HttpClient.HttpClient;
97 + const fs = yield* FileSystem.FileSystem;
98 + const path = yield* Path.Path;
99 + const runner = yield* ProcessRunner.ProcessRunner;
100 + const server = yield* ServerConfig.ServerConfig;
101 + const services = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
102 + const environment = yield* HostProcess.Environment;
103 + const hostId = config.id;
104 + const gateway = config.gatewayUrl.replace(/\/$/, "");
105 + const agentDeviceUrl = `${gateway}/v1/agent-device`;
106 + const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
107 + const leases = new Map<string, Lease>();
108 + let starting = 0;
109 + // Bumped by every stop, so an open that finishes after one returns its lease instead of keeping it.
110 + let stops = 0;
111 + const slotLock = yield* Semaphore.make(1);
112 + const keepAlive = yield* FiberMap.make<string>();
113 + let catalog: {
114 + readonly at: number;
115 + readonly devices: ReadonlyArray<DeviceHost.HostDevice>;
116 + } | null = null;
117 + let ready: DeviceHost.DeviceHostReady | null = null;
118 + let cli: { readonly nodePath: string; readonly entryPath: string } | null = null;
119 +
120 + const unavailable = (reason: string, cause?: unknown) =>
121 + new DeviceHostUnavailableError({
122 + hostId,
123 + hostLabel: config.label,
124 + reason,
125 + ...(cause === undefined ? {} : { cause }),
126 + });
127 +
128 + const request = (
129 + method: "GET" | "POST" | "DELETE",
130 + route: string,
131 + body?: Readonly<Record<string, unknown>>,
132 + ) =>
133 + http
134 + .execute(
135 + (method === "GET"
136 + ? HttpClientRequest.get(`${gateway}${route}`)
137 + : method === "POST"
138 + ? HttpClientRequest.post(`${gateway}${route}`).pipe(
139 + HttpClientRequest.bodyJsonUnsafe(body ?? {}),
140 + )
141 + : HttpClientRequest.delete(`${gateway}${route}`)
142 + ).pipe(HttpClientRequest.bearerToken(config.agentToken)),
143 + )
144 + .pipe(
145 + Effect.flatMap(HttpClientResponse.filterStatusOk),
146 + Effect.flatMap((response) => response.json),
147 + Effect.scoped,
148 + Effect.timeout(REQUEST_TIMEOUT),
149 + );
150 +
151 + const agentEnvironment: NodeJS.ProcessEnv = Object.fromEntries(
152 + Object.entries({
153 + ...environment,
154 + ELECTRON_RUN_AS_NODE: "1",
155 + AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
156 + NO_COLOR: "1",
157 + FORCE_COLOR: "0",
158 + }).filter(
159 + ([name]) =>
160 + !/^AGENT_DEVICE_(DAEMON_BASE_URL|DAEMON_AUTH_TOKEN|CONFIG|STATE_DIR|SESSION)$/.test(name),
161 + ),
162 + );
163 +
164 + /** Runs T3's own agent-device CLI against the lease's session; its failure message is the reason. */
165 + const agentDevice = Effect.fn("SimlockDeviceHost.agentDevice")(function* (
166 + lease: Pick<Lease, "session" | "configPath">,
167 + args: ReadonlyArray<string>,
168 + options: { readonly cwd?: string; readonly timeout?: Duration.Input } = {},
169 + ) {
170 + if (!cli) return yield* unavailable(`${config.label} is not ready.`);
171 + const result = yield* runner
172 + .run({
173 + command: cli.nodePath,
174 + args: [
175 + cli.entryPath,
176 + ...args,
177 + "--session",
178 + lease.session,
179 + "--config",
180 + lease.configPath,
181 + "--json",
182 + ],
183 + env: agentEnvironment,
184 + ...(options.cwd ? { cwd: options.cwd } : {}),
185 + timeout: options.timeout ?? COMMAND_TIMEOUT,
186 + })
187 + .pipe(Effect.mapError((cause) => unavailable("agent-device could not run.", cause)));
188 + if (result.code !== 0) {
189 + const failure = decodeCliFailure(result.stdout);
190 + return yield* unavailable(
191 + Option.match(failure, {
192 + onNone: () => `agent-device ${args[0]} failed (exit code ${result.code ?? "none"}).`,
193 + onSome: ({ error }) => (error.hint ? `${error.message} ${error.hint}` : error.message),
194 + }),
195 + );
196 + }
197 + return result.stdout;
198 + });
199 +
200 + const loadCatalog = Effect.gen(function* () {
201 + const now = yield* Clock.currentTimeMillis;
202 + if (catalog && now - catalog.at < CATALOG_TTL_MS) return catalog.devices;
203 + if (!config.agentToken) {
204 + return yield* unavailable(`Add an agent token for ${config.label} in Settings.`);
205 + }
206 + const decoded = yield* request("GET", "/v1/catalog").pipe(
207 + Effect.flatMap(decodeCatalog),
208 + Effect.mapError((cause) =>
209 + unavailable(
210 + `Could not reach the Simlock gateway at ${gateway}, or it refused the agent token.`,
211 + cause,
212 + ),
213 + ),
214 + );
215 + const devices = decoded.platforms.flatMap((entry) => {
216 + if (entry.platform !== "ios" && entry.platform !== "android") return [];
217 + const platform: DevicePlatform = entry.platform;
218 + return Object.entries(entry.modelRuntimes).flatMap(([model, runtimes]) => {
219 + const kind = entry.modelClasses?.[model];
220 + const workers = entry.modelWorkers?.[model];
221 + if (runtimes.length === 0 || (workers !== undefined && workers.length === 0)) return [];
222 + if (kind !== undefined && kind !== "phone" && kind !== "tablet") return [];
223 + return [
224 + {
225 + id: catalogId(platform, model),
226 + platform,
227 + name: model,
228 + version: platformVersion(platform, runtimes.at(-1)),
229 + booted: false,
230 + physical: false,
231 + } satisfies DeviceHost.HostDevice,
232 + ];
233 + });
234 + });
235 + catalog = { at: now, devices };
236 + return devices;
237 + });
238 +
239 + const forget = (lease: Lease) =>
240 + Effect.suspend(() => {
241 + leases.delete(lease.leaseId);
242 + return fs.remove(lease.dir, { recursive: true, force: true }).pipe(Effect.ignore);
243 + });
244 +
245 + /** Ends the lease through its session, or over HTTP when the session is gone. */
246 + const release = Effect.fn("SimlockDeviceHost.release")(function* (lease: Lease) {
247 + yield* agentDevice(lease, ["close"]).pipe(
248 + Effect.catch(() => request("DELETE", `/v1/leases/${encodeURIComponent(lease.leaseId)}`)),
249 + Effect.tapError((cause) =>
250 + Effect.logWarning("Could not release Simlock lease", { leaseId: lease.leaseId, cause }),
251 + ),
252 + Effect.ignore,
253 + );
254 + yield* forget(lease);
255 + });
256 +
257 + /** Renews until the lease ends on its own or reaches its maximum age, then releases it. */
258 + const renewLoop = Effect.fn("SimlockDeviceHost.renewLoop")(function* (lease: Lease) {
259 + const deadline =
260 + (yield* Clock.currentTimeMillis) +
261 + Duration.toMillis(Duration.minutes(config.maxLeaseMinutes));
262 + while (true) {
263 + const left = deadline - (yield* Clock.currentTimeMillis);
264 + yield* Effect.sleep(Duration.millis(Math.min(left, Duration.toMillis(RENEW_INTERVAL))));
265 + if ((yield* Clock.currentTimeMillis) >= deadline) break;
266 + const renewed = yield* request(
267 + "POST",
268 + `/v1/leases/${encodeURIComponent(lease.leaseId)}/renew`,
269 + { ttlMs: LEASE_TTL_MS },
270 + ).pipe(Effect.result);
271 + if (renewed._tag === "Success") continue;
272 + const error = renewed.failure;
273 + // Simlock ended it (lease_lost, an agent's close, or its TTL): stop listing it.
274 + if (
275 + error._tag === "HttpClientError" &&
276 + error.reason._tag === "StatusCodeError" &&
277 + error.reason.response.status === 404
278 + ) {
279 + return yield* forget(lease);
280 + }
281 + yield* Effect.logWarning("Could not renew Simlock lease", { leaseId: lease.leaseId, error });
282 + }
283 + yield* Effect.logInfo("Releasing Simlock lease at its maximum age", {
284 + leaseId: lease.leaseId,
285 + });
286 + yield* release(lease);
287 + });
288 +
289 + const reserveSlot = slotLock.withPermit(
290 + Effect.suspend(() => {
291 + if (leases.size + starting >= config.maxLeases) {
292 + return Effect.fail(
293 + unavailable(
294 + `${config.label} is limited to ${config.maxLeases} ${config.maxLeases === 1 ? "device" : "devices"} at once. Close one in the Device panel first.`,
295 + ),
296 + );
297 + }
298 + starting++;
299 + return Effect.void;
300 + }),
301 + );
302 +
303 + const openLease = Effect.fn("SimlockDeviceHost.openLease")(function* (
304 + device: DeviceHost.HostDevice,
305 + context: DeviceHost.DeviceOpenContext | undefined,
306 + ) {
307 + const target = parseCatalogId(device.id);
308 + if (!target) {
309 + return yield* new DeviceBootError({
310 + hostId,
311 + deviceId: device.id,
312 + reason: "launch_failed",
313 + cause: new Error("This Simlock device is no longer leased. Open it again from the list."),
314 + });
315 + }
316 + const suffix = (yield* Random.nextIntBetween(0, 0xffffff)).toString(16).padStart(6, "0");
317 + const session = `t3-${suffix}`;
318 + const dir = path.join(hostDir, suffix);
319 + const configPath = path.join(dir, "agent-device.json");
320 + yield* writeAgentDeviceConfig(configPath, {
321 + baseUrl: agentDeviceUrl,
322 + token: config.agentToken,
323 + stateDir: dir,
324 + }).pipe(
325 + Effect.provide(services),
326 + Effect.mapError((cause) => unavailable("Could not write the agent-device config.", cause)),
327 + );
328 + // agent-device ties installs to the directory that opened the session.
329 + const installDirectory = context?.workspaceRoot
330 + ? yield* fs.realPath(context.workspaceRoot).pipe(Effect.orElseSucceed(() => dir))
331 + : dir;
332 + const pending = { session, configPath };
333 + const stopsAtOpen = stops;
334 + return yield* Effect.gen(function* () {
335 + yield* agentDevice(pending, ["connect", "proxy", "--daemon-base-url", agentDeviceUrl]);
336 + yield* agentDevice(
337 + pending,
338 + ["open", "--platform", target.platform, "--device", target.model],
339 + { cwd: installDirectory, timeout: OPEN_TIMEOUT },
340 + );
341 + const record = yield* fs
342 + .readFileString(path.join(dir, "remote-connections", `${session}.json`))
343 + .pipe(
344 + Effect.flatMap(decodeSessionRecord),
345 + Effect.mapError((cause) => unavailable("agent-device recorded no Simlock lease.", cause)),
346 + );
347 + const opened: Lease = {
348 + leaseId: record.leaseId,
349 + platform: target.platform,
350 + name: target.model,
351 + version: device.version,
352 + session,
353 + dir,
354 + configPath,
355 + installDirectory,
356 + };
357 + if (stops !== stopsAtOpen)
358 + return yield* unavailable("Device support stopped while the device was opening.");
359 + leases.set(opened.leaseId, opened);
360 + yield* FiberMap.run(keepAlive, opened.leaseId, renewLoop(opened));
361 + return opened.leaseId;
362 + }).pipe(
363 + // A failed or interrupted open may still hold a lease: close the session either way.
364 + Effect.onExit((exit) =>
365 + exit._tag === "Success"
366 + ? Effect.void
367 + : agentDevice(pending, ["close"]).pipe(
368 + Effect.ignore,
369 + Effect.andThen(fs.remove(dir, { recursive: true, force: true }).pipe(Effect.ignore)),
370 + ),
371 + ),
372 + Effect.mapError((error) =>
373 + error._tag === "DeviceHostUnavailableError"
374 + ? new DeviceBootError({
375 + hostId,
376 + deviceId: device.id,
377 + reason: "launch_failed",
378 + cause: new Error(error.reason),
379 + })
380 + : error,
381 + ),
382 + );
383 + });
384 +
385 + const leaseFor = (deviceId: string) => Option.fromNullishOr(leases.get(deviceId));
386 + const operationError = (operation: string) => (cause: unknown) =>
387 + new DeviceOperationError({ operation, reason: "request_failed", cause });
388 +
389 + const screenshotLease = Effect.fn("SimlockDeviceHost.screenshot")(
390 + function* (lease: Lease) {
391 + const file = path.join(
392 + lease.dir,
393 + `screenshot-${(yield* Random.nextIntBetween(0, 0xffffff)).toString(16)}.png`,
394 + );
395 + yield* agentDevice(lease, ["screenshot", file]);
396 + return yield* fs
397 + .readFile(file)
398 + .pipe(Effect.ensuring(fs.remove(file, { force: true }).pipe(Effect.ignore)));
399 + },
400 + Effect.mapError(operationError("screenshot")),
401 + );
402 +
403 + const devices: DeviceHost.DeviceOperations = {
404 + list: loadCatalog.pipe(
405 + Effect.mapError(operationError("list")),
406 + Effect.map((available) => ({
407 + devices: [
408 + ...available,
409 + ...[...leases.values()].map((lease): DeviceHost.HostDevice => ({
410 + id: lease.leaseId,
411 + platform: lease.platform,
412 + name: lease.name,
413 + version: lease.version,
414 + booted: true,
415 + physical: false,
416 + })),
417 + ],
418 + detail: undefined,
419 + })),
420 + ),
421 + boot: (device, context) =>
422 + leases.has(device.id)
423 + ? Effect.succeed(device.id)
424 + : Effect.acquireUseRelease(
425 + reserveSlot,
426 + () => openLease(device, context),
427 + () => Effect.sync(() => void starting--),
428 + ),
429 + attach: () => Effect.void,
430 + shutdown: (device) =>
431 + Option.match(leaseFor(device.id), {
432 + onNone: () => Effect.void,
433 + onSome: (lease) =>
434 + FiberMap.remove(keepAlive, lease.leaseId).pipe(Effect.andThen(release(lease))),
435 + }),
436 + screenshot: (device) =>
437 + Option.match(leaseFor(device.id), {
438 + onNone: () =>
439 + Effect.fail(operationError("screenshot")(new Error("The Simlock lease has ended"))),
440 + onSome: screenshotLease,
441 + }),
442 + agentEndpoint: (deviceId) =>
443 + Option.match(leaseFor(deviceId), {
444 + onNone: () => Effect.fail(unavailable("This Simlock lease has ended.")),
445 + onSome: (lease) =>
446 + Effect.succeed({
447 + baseUrl: agentDeviceUrl,
448 + token: config.agentToken,
449 + agentDeviceId: null,
450 + session: lease.session,
451 + stateDir: lease.dir,
452 + installDirectory: lease.installDirectory,
453 + }),
454 + }),
455 + endsDevices: true,
456 + };
457 +
458 + /**
459 + * The client speaks serve-sim to every Simlock lease: its AVCC stream and its input
460 + * socket map to the lease's own stream and input routes, which take the agent token.
461 + */
462 + const upstream: NonNullable<DeviceHost.DeviceHostReady["upstream"]> = (hubPath, search) =>
463 + Effect.sync(() => {
464 + const stream = STREAM_PATH.exec(hubPath);
465 + let deviceId: string | null;
466 + try {
467 + deviceId = stream
468 + ? decodeURIComponent(stream[1]!)
469 + : hubPath === INPUT_PATH
470 + ? search.get("device")
471 + : null;
472 + } catch {
473 + return null;
474 + }
475 + const lease = deviceId === null ? undefined : leases.get(deviceId);
476 + if (!lease) return null;
477 + return {
478 + url: `${gateway}/v1/leases/${encodeURIComponent(lease.leaseId)}/${stream ? "stream" : "input"}`,
479 + headers: { authorization: `Bearer ${config.agentToken}` },
480 + protocols: [],
481 + };
482 + });
483 +
484 + const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = Effect.fn(
485 + "SimlockDeviceHost.ensureReady",
486 + )(function* (onPhase) {
487 + if (ready) return ready;
488 + // A missing token or unreachable gateway does not stop readiness: listing
489 + // and opening devices say what is wrong instead.
490 + yield* onPhase("installing");
491 + cli = yield* agentDeviceCli;
492 + const { nodePath } = cli;
493 + ready = {
494 + nodePath,
495 + hub: { origin: gateway },
496 + devices,
497 + upstream,
498 + // Simlock relays only simctl, adb, and devicectl, and only to a lease's owner.
499 + run: () =>
500 + Effect.succeed({
501 + stdout: "",
502 + stderr: "Simlock devices cannot run host commands.",
503 + code: 127,
504 + }),
505 + helpers: { serveSimAxSettings: null, serveSimCli: null },
506 + };
507 + return ready;
508 + });
509 +
510 + const stopAll = Effect.gen(function* () {
511 + stops++;
512 + yield* FiberMap.clear(keepAlive);
513 + yield* Effect.forEach([...leases.values()], release, { discard: true, concurrency: 4 });
514 + }).pipe(Effect.ignore);
515 + yield* Effect.addFinalizer(() => stopAll);
516 +
517 + const platformAvailability = (platform: DevicePlatform) =>
518 + Effect.succeed({ platform, available: true });
519 +
520 + const summary: Effect.Effect<DeviceHostSummary> = Effect.succeed({
521 + id: hostId,
522 + label: config.label,
523 + kind: "simlock" as const,
524 + platforms: [
525 + { platform: "ios" as const, available: true },
526 + { platform: "android" as const, available: true },
527 + ],
528 + hubInstalled: true,
529 + agentDeviceInstalled: true,
530 + });
531 +
532 + return DeviceHost.DeviceHost.of({
533 + id: hostId,
534 + label: config.label,
535 + summary,
536 + platformAvailability,
537 + ensureReady,
538 + ensureAgentReady: Effect.fn("SimlockDeviceHost.ensureAgentReady")(function* (onPhase) {
539 + return { ...(yield* ensureReady(onPhase)), agentDevice: null };
540 + }),
541 + current: Effect.sync(() => ready),
542 + stopAgent: Effect.void,
543 + stop: stopAll,
544 + });
545 +});
apps/server/src/mcp/toolkits/device/handlers.ts
+35 -9
@@ -30,16 +30,28 @@ export function agentDeviceQuickStart(
30 device: DeviceSummary,
31 targetArgs = agentDeviceTargetArgs(device),
32 command = "agent-device",
33 - cloud = false,
33 + host?:
34 + | { readonly kind: "eas" }
35 + | { readonly kind: "simlock"; readonly installDirectory?: string },
36 ): string {
37 const executable = shellWord(command);
38 const target = targetArgs.map(shellWord).join(" ");
39 const run = (args: string) => [executable, args, target].filter(Boolean).join(" ");
38 - const platformNotes = cloud
39 - ? "This is an EAS Simulator session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source <url> installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine."
40 - : device.platform === "ios"
41 - ? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast."
42 - : "The Android snapshot helper installs itself on first use.";
40 + const platformNotes =
41 + host?.kind === "simlock"
42 + ? [
43 + "This device is leased from a Simlock pool (alpha in T3 Code). The lease returns it to the pool, wiped, when it ends, so call device_close with shutdown: true when you are done. It starts with no apps installed.",
44 + host.installDirectory
45 + ? `agent-device accepts install for this lease only when run from ${host.installDirectory}.`
46 + : "",
47 + ]
48 + .filter(Boolean)
49 + .join(" ")
50 + : host?.kind === "eas"
51 + ? "This is an EAS Simulator session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source <url> installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine."
52 + : device.platform === "ios"
53 + ? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast."
54 + : "The Android snapshot helper installs itself on first use.";
55 return [
56 `The user is watching ${device.name} (${device.version}) in the Device panel.`,
57 target === ""
@@ -222,9 +234,11 @@ const handlers = {
234 deviceId: session.deviceId,
235 };
236 const agent = yield* devices.agentTarget(opened);
225 - const cloud = after.hosts.some((host) => host.id === device.hostId && host.kind === "eas");
237 + const hostKind = after.hosts.find((host) => host.id === device.hostId)?.kind;
238 const targetArgs = [
227 - ...agentDeviceTargetArgs({ ...device, id: agent.agentDeviceId }),
239 + ...(agent.agentDeviceId === null
240 + ? []
241 + : agentDeviceTargetArgs({ ...device, id: agent.agentDeviceId })),
242 ...agent.args,
243 ];
244 const launcher = yield* devices.agentLauncher({ ...opened, targetArgs });
@@ -238,7 +252,19 @@ const handlers = {
252 return {
253 device,
254 agentDevice: { command, targetArgs, session: agent.session },
241 - quickStart: agentDeviceQuickStart(device, [], command, cloud),
255 + quickStart: agentDeviceQuickStart(
256 + device,
257 + [],
258 + command,
259 + hostKind === "simlock"
260 + ? {
261 + kind: "simlock",
262 + ...(agent.installDirectory ? { installDirectory: agent.installDirectory } : {}),
263 + }
264 + : hostKind === "eas"
265 + ? { kind: "eas" }
266 + : undefined,
267 + ),
268 };
269 }).pipe(Effect.mapError(toolError)),
270 ),
apps/server/src/settingsSecrets.ts
+22 -1
@@ -4,6 +4,7 @@ import {
4 CodexSettings,
5 EasDeviceHostConfig,
6 type ServerSettings,
7 + SimlockDeviceHostConfig,
8 UsageLimitSourceConfig,
9 secretSettingsFields,
10 } from "@t3tools/contracts";
@@ -33,6 +34,7 @@ const providerSecretFields = new Map([
34 ]);
35 const usageLimitSecretFields = secretSettingsFields(UsageLimitSourceConfig);
36 const easDeviceHostSecretFields = secretSettingsFields(EasDeviceHostConfig);
37 +const simlockDeviceHostSecretFields = secretSettingsFields(SimlockDeviceHostConfig);
38 const encode = (value: string) => Buffer.from(value, "utf8").toString("base64url");
39
40 export interface SettingsSecret {
@@ -155,5 +157,24 @@ export function mapSettingsSecrets(
157 ) as EasDeviceHostConfig,
158 );
159
158 - return { ...settings, providerInstances, sourceControlHosts, usageLimitSources, easDeviceHosts };
160 + // Its own prefix: an EAS and a Simlock host may share an id.
161 + const simlockDeviceHosts = settings.simlockDeviceHosts.map(
162 + (host) =>
163 + mapFields(
164 + host,
165 + simlockDeviceHostSecretFields,
166 + (field, serverHost) =>
167 + `simlock-device-host-${encode(host.id)}-${encode(field)}` +
168 + (serverHost === null ? "" : `-${encode(serverHost)}`),
169 + ) as SimlockDeviceHostConfig,
170 + );
171 +
172 + return {
173 + ...settings,
174 + providerInstances,
175 + sourceControlHosts,
176 + usageLimitSources,
177 + easDeviceHosts,
178 + simlockDeviceHosts,
179 + };
180 }
apps/web/src/components/device/DeviceControlsRail.tsx
+101 -91
@@ -46,6 +46,8 @@ export function DeviceControlsRail(props: {
46 onFloat: () => void;
47 onClose: () => void;
48 onPowerOff: () => void;
49 + /** The host takes input but runs no device commands (Simlock): no rotation, settings, tools, or screenshots. */
50 + inputOnly?: boolean;
51 }) {
52 const { view, handle, controls } = props;
53 const popupSide = "left";
@@ -85,115 +87,123 @@ export function DeviceControlsRail(props: {
87 >
88 <Square />
89 </RailButton>
90 + {props.inputOnly ? null : (
91 + <Menu>
92 + <MenuTrigger
93 + render={
94 + <Button
95 + size="icon-sm"
96 + variant="ghost"
97 + aria-label="Rotate device"
98 + disabled={controls.disabled}
99 + />
100 + }
101 + >
102 + <RotateCcw />
103 + </MenuTrigger>
104 + <MenuPopup side={popupSide}>
105 + <MenuItem
106 + onClick={() => void controls.act({ type: "setOrientation", value: "portrait" })}
107 + >
108 + Portrait
109 + </MenuItem>
110 + <MenuItem
111 + onClick={() =>
112 + void controls.act({ type: "setOrientation", value: "landscape_left" })
113 + }
114 + >
115 + Landscape
116 + </MenuItem>
117 + </MenuPopup>
118 + </Menu>
119 + )}
120 + </>
121 + ) : props.inputOnly ? null : (
122 + <RailButton
123 + tooltipSide={popupSide}
124 + label="Rotate device"
125 + disabled={inputDisabled || !!view.keyboard?.attached}
126 + onClick={() => handle?.rotate()}
127 + >
128 + <RotateCcw />
129 + </RailButton>
130 + )}
131 + {props.inputOnly ? null : (
132 + <>
133 + <RailDivider />
134 + <RailButton
135 + tooltipSide={popupSide}
136 + label={`Switch device to ${nextAppearance} mode`}
137 + disabled={controls.disabled || !settings?.appearance}
138 + onClick={() => void controls.act({ type: "setAppearance", value: nextAppearance })}
139 + >
140 + <MorphIcon icon={settings?.appearance === "dark" ? Sun : Moon} />
141 + </RailButton>
142 <Menu>
143 <MenuTrigger
144 render={
145 <Button
146 size="icon-sm"
147 variant="ghost"
94 - aria-label="Rotate device"
95 - disabled={controls.disabled}
148 + aria-label="Device text size"
149 + title="Device text size"
150 + disabled={controls.disabled || !settings?.textSize}
151 />
152 }
153 >
99 - <RotateCcw />
154 + <Type />
155 </MenuTrigger>
101 - <MenuPopup side={popupSide}>
102 - <MenuItem
103 - onClick={() => void controls.act({ type: "setOrientation", value: "portrait" })}
156 + <MenuPopup side={popupSide} className="min-w-40">
157 + <MenuRadioGroup
158 + value={settings?.textSize ?? ""}
159 + onValueChange={(value) => {
160 + if (
161 + value === "small" ||
162 + value === "default" ||
163 + value === "large" ||
164 + value === "extra-large"
165 + )
166 + void controls.act({ type: "setTextSize", value });
167 + }}
168 >
105 - Portrait
106 - </MenuItem>
107 - <MenuItem
108 - onClick={() =>
109 - void controls.act({ type: "setOrientation", value: "landscape_left" })
110 - }
111 - >
112 - Landscape
113 - </MenuItem>
169 + {(
170 + [
171 + ["small", "Small"],
172 + ["default", "Default"],
173 + ["large", "Large"],
174 + ["extra-large", "Extra large"],
175 + ] as const
176 + ).map(([value, label]) => (
177 + <MenuRadioItem key={value} value={value}>
178 + <span className="flex items-center gap-2">
179 + <span className="flex-1">{label}</span>
180 + <MenuRadioItemIndicator />
181 + </span>
182 + </MenuRadioItem>
183 + ))}
184 + </MenuRadioGroup>
185 </MenuPopup>
186 </Menu>
187 + <RailButton
188 + tooltipSide={popupSide}
189 + label="Device tools"
190 + pressed={props.toolsOpen}
191 + onClick={props.onTools}
192 + >
193 + <SlidersHorizontal />
194 + </RailButton>
195 </>
117 - ) : (
196 + )}
197 + {props.inputOnly ? null : (
198 <RailButton
199 tooltipSide={popupSide}
120 - label="Rotate device"
121 - disabled={inputDisabled || !!view.keyboard?.attached}
122 - onClick={() => handle?.rotate()}
200 + label={props.screenshotPending ? "Capturing screenshot" : "Save screenshot"}
201 + disabled={!view.streaming || props.screenshotPending}
202 + onClick={props.onScreenshot}
203 >
124 - <RotateCcw />
204 + <Camera />
205 </RailButton>
206 )}
127 - <RailDivider />
128 - <RailButton
129 - tooltipSide={popupSide}
130 - label={`Switch device to ${nextAppearance} mode`}
131 - disabled={controls.disabled || !settings?.appearance}
132 - onClick={() => void controls.act({ type: "setAppearance", value: nextAppearance })}
133 - >
134 - <MorphIcon icon={settings?.appearance === "dark" ? Sun : Moon} />
135 - </RailButton>
136 - <Menu>
137 - <MenuTrigger
138 - render={
139 - <Button
140 - size="icon-sm"
141 - variant="ghost"
142 - aria-label="Device text size"
143 - title="Device text size"
144 - disabled={controls.disabled || !settings?.textSize}
145 - />
146 - }
147 - >
148 - <Type />
149 - </MenuTrigger>
150 - <MenuPopup side={popupSide} className="min-w-40">
151 - <MenuRadioGroup
152 - value={settings?.textSize ?? ""}
153 - onValueChange={(value) => {
154 - if (
155 - value === "small" ||
156 - value === "default" ||
157 - value === "large" ||
158 - value === "extra-large"
159 - )
160 - void controls.act({ type: "setTextSize", value });
161 - }}
162 - >
163 - {(
164 - [
165 - ["small", "Small"],
166 - ["default", "Default"],
167 - ["large", "Large"],
168 - ["extra-large", "Extra large"],
169 - ] as const
170 - ).map(([value, label]) => (
171 - <MenuRadioItem key={value} value={value}>
172 - <span className="flex items-center gap-2">
173 - <span className="flex-1">{label}</span>
174 - <MenuRadioItemIndicator />
175 - </span>
176 - </MenuRadioItem>
177 - ))}
178 - </MenuRadioGroup>
179 - </MenuPopup>
180 - </Menu>
181 - <RailButton
182 - tooltipSide={popupSide}
183 - label="Device tools"
184 - pressed={props.toolsOpen}
185 - onClick={props.onTools}
186 - >
187 - <SlidersHorizontal />
188 - </RailButton>
189 - <RailButton
190 - tooltipSide={popupSide}
191 - label={props.screenshotPending ? "Capturing screenshot" : "Save screenshot"}
192 - disabled={!view.streaming || props.screenshotPending}
193 - onClick={props.onScreenshot}
194 - >
195 - <Camera />
196 - </RailButton>
207 <Menu>
208 <MenuTrigger
209 render={
@@ -219,7 +229,7 @@ export function DeviceControlsRail(props: {
229 <MenuSeparator />
230 <MenuItem variant="destructive" onClick={props.onPowerOff}>
231 <Power />
222 - Power off device
232 + {props.inputOnly ? "Return device to the pool" : "Power off device"}
233 </MenuItem>
234 </MenuPopup>
235 </Menu>
apps/web/src/components/device/DevicePanel.tsx
+5 -3
@@ -86,6 +86,9 @@ export function DevicePanel(props: {
86 (device) => device.hostId === activeSession.hostId && device.id === activeSession.deviceId,
87 )
88 : undefined;
89 + const activeHost = activeDevice
90 + ? state.hosts.find((host) => host.id === activeDevice.hostId)
91 + : undefined;
92
93 const grouped = groupDevices(state);
94
@@ -234,9 +237,8 @@ export function DevicePanel(props: {
237 key={`${environmentId}\u0000${deviceKey(activeDevice)}`}
238 environmentId={environmentId}
239 device={activeDevice}
237 - hostLabel={
238 - state.hosts.find((host) => host.id === activeDevice.hostId)?.label ?? "Device host"
239 - }
240 + hostLabel={activeHost?.label ?? "Device host"}
241 + simlock={activeHost?.kind === "simlock"}
242 hostDiagnostics={
243 diagnostics.find(({ hostId }) => hostId === activeDevice.hostId)?.detail
244 }
apps/web/src/components/device/DeviceSetup.tsx
+4 -4
@@ -19,9 +19,9 @@ import { cn } from "~/lib/utils";
19
20 const platformName = (platform: DevicePlatform) => (platform === "ios" ? "iOS" : "Android");
21
22 -export const deviceHubDescription =
22 +const deviceHubDescription =
23 "Enable this environment to open simulators and emulators, whether they run here or on a remote device host.";
24 -export const agentDeviceDescription =
24 +const agentDeviceDescription =
25 "Allow new agent sessions in this environment to start and control local and remote devices, with required tools set up automatically.";
26
27 export const isAndroidDiscoveryUncertain = (state: DeviceServiceState) =>
@@ -57,7 +57,7 @@ function deviceHostDiagnostics(
57 });
58 }
59
60 -export function DeviceHostDiagnostics(props: {
60 +function DeviceHostDiagnostics(props: {
61 readonly hosts: ReadonlyArray<Pick<DeviceServiceState["hosts"][number], "id" | "label">>;
62 readonly hostStatuses: DeviceServiceState["hostStatuses"];
63 readonly className?: string;
@@ -360,7 +360,7 @@ export function AgentDeviceSetupStatus(props: {
360 return null;
361 }
362
363 -export function PlatformStatus(props: {
363 +function PlatformStatus(props: {
364 readonly platform: string;
365 readonly status: { readonly ready: boolean; readonly message: string };
366 readonly compact?: boolean;
apps/web/src/components/device/DeviceStreamView.tsx
+3
@@ -93,6 +93,8 @@ export function DeviceStreamView(props: {
93 readonly axOverlay?: boolean;
94 /** Lets a parent read this view's own stream state, such as its screen size. */
95 readonly viewId?: string;
96 + /** The host serves only serve-sim's stream and input socket (Simlock). */
97 + readonly serveSimOnly?: boolean;
98 }) {
99 const model = deviceModel(props.platform, props.deviceName ?? "");
100 const isDuo = model?.id === "iphone-duo";
@@ -118,6 +120,7 @@ export function DeviceStreamView(props: {
120 platform: props.platform,
121 deviceId: props.deviceId,
122 access,
123 + serveSimOnly: props.serveSimOnly === true,
124 viewId,
125 })
126 : NO_SESSION_ATOM,
apps/web/src/components/device/DeviceWorkspace.tsx
+4
@@ -16,6 +16,8 @@ export function DeviceWorkspace(props: {
16 environmentId: EnvironmentId;
17 device: DeviceSummary;
18 hostLabel: string;
19 + /** Leased from a Simlock pool: serve-sim input, no host commands. */
20 + simlock?: boolean;
21 hostDiagnostics: string | undefined;
22 visible: boolean;
23 onFloat: () => void;
@@ -80,6 +82,7 @@ export function DeviceWorkspace(props: {
82 deviceId={props.device.id}
83 hostId={props.device.hostId}
84 visible={props.visible}
85 + serveSimOnly={props.simlock === true}
86 axOverlay={axOverlay}
87 allowPhoneView
88 renderControls={(view) => (
@@ -95,6 +98,7 @@ export function DeviceWorkspace(props: {
98 onFloat={props.onFloat}
99 onClose={props.onClose}
100 onPowerOff={props.onPowerOff}
101 + inputOnly={props.simlock === true}
102 />
103 )}
104 />
apps/web/src/components/device/deviceStreamSession.ts
+8 -1
@@ -43,6 +43,8 @@ export interface DeviceStreamKey {
43 readonly platform: DevicePlatform;
44 readonly deviceId: string;
45 readonly access: DeviceHubAccess;
46 + /** See `DeviceStreamTarget.serveSimOnly`. */
47 + readonly serveSimOnly: boolean;
48 /** Each mounted view owns its own client: one canvas cannot be in two places. */
49 readonly viewId: string;
50 }
@@ -89,7 +91,12 @@ export const deviceStreamSessionAtom = Atom.family((key: DeviceStreamKey) =>
91 get.setSelf(session);
92 };
93 const client = createDeviceStreamClient(
92 - { platform: key.platform, deviceId: key.deviceId, access: key.access },
94 + {
95 + platform: key.platform,
96 + deviceId: key.deviceId,
97 + access: key.access,
98 + serveSimOnly: key.serveSimOnly,
99 + },
100 createCanvasFrameSink(canvas, () => frameListener?.()),
101 {
102 onDuoControl: (duoControl) => {
apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx
+3 -2
@@ -366,8 +366,8 @@ function DeviceMiniPlayer({
366 const device = deviceState.devices.find(
367 (entry) => entry.hostId === source.hostId && entry.id === source.deviceId,
368 );
369 - const hostLabel =
370 - deviceState.hosts.find((host) => host.id === source.hostId)?.label ?? "Device host";
369 + const host = deviceState.hosts.find((entry) => entry.id === source.hostId);
370 + const hostLabel = host?.label ?? "Device host";
371 const cornerRadius = (player: PreviewMiniPlayerSize) =>
372 resolveDeviceMiniPlayerCornerRadius(source.platform, player);
373
@@ -404,6 +404,7 @@ function DeviceMiniPlayer({
404 deviceDescription={`${hostLabel} · ${device?.version ?? source.platform}`}
405 visible
406 viewId={viewId}
407 + serveSimOnly={host?.kind === "simlock"}
408 />
409 </div>
410 )}
apps/web/src/components/settings/DeviceHostsSettings.tsx deleted
-593
@@ -1,593 +0,0 @@
1 -import { DeviceToolVersions } from "../device/DeviceToolVersions";
2 -import { DeviceHostAvailability } from "../device/DeviceHostAvailability";
3 -import { useAtomValue } from "@effect/atom-react";
4 -import * as Option from "effect/Option";
5 -import { AsyncResult } from "effect/reactivity";
6 -import { AuthSettingsWriteScope } from "@t3tools/contracts";
7 -import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
8 -import { Tooltip, TooltipTrigger, TooltipPopup } from "../ui/tooltip";
9 -import { AppleIcon, AndroidIcon } from "../Icons";
10 -import { Spinner } from "../ui/spinner";
11 -import type { EnvironmentId, SshDeviceHostConfig } from "@t3tools/contracts";
12 -import { randomUUID } from "../../lib/utils";
13 -import { useState } from "react";
14 -import { deviceEnvironment } from "../../state/device";
15 -import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
16 -import { serverEnvironment } from "../../state/server";
17 -import { useAtomCommand } from "../../state/use-atom-command";
18 -import { Button, InlineButton } from "../ui/button";
19 -import {
20 - CheckIcon,
21 - ChevronDownIcon,
22 - CircleIcon,
23 - MoreVertical,
24 - PlusIcon,
25 - TriangleAlertIcon,
26 -} from "lucide-react";
27 -import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
28 -import { Menu, MenuTrigger, MenuPopup, MenuItem } from "../ui/menu";
29 -import { SettingsRow } from "./settingsLayout";
30 -
31 -import { useSettingsScope } from "./SettingsScopeContext";
32 -import { toastManager } from "../ui/toast";
33 -import {
34 - groupDeviceHosts,
35 - updateDeviceHosts,
36 - type DeviceHostEnvironment,
37 - type DeviceHostGroup,
38 -} from "./deviceHostsSettings.logic";
39 -import { FoldedSettingsSection } from "./FoldedSettingsSection";
40 -import { DeviceHostEditor } from "./DeviceHostEditor";
41 -import { useHostConnectionChecks } from "./useHostConnectionChecks";
42 -import { deviceHostConnectionKey } from "./deviceHostConnectionChecks";
43 -import { settingsScopeEnvironmentLabel, settingsScopeEnvironmentLabels } from "./settingsScopeAxis";
44 -import { DeviceHostDiagnostics } from "../device/DeviceSetup";
45 -
46 -export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null }) {
47 - const { scope, environments, connectedEnvironments } = useSettingsScope();
48 - const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
49 - const projectScope = scope.kind === "project" || scope.kind === "checkout";
50 - const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
51 - const [editing, setEditing] = useState<SshDeviceHostConfig | null>(null);
52 - const [originalHost, setOriginalHost] = useState<SshDeviceHostConfig | null>(null);
53 - const [busy, setBusy] = useState(false);
54 - const targets = environments.map((environment) => ({
55 - environmentId: environment.environmentId,
56 - label: settingsScopeEnvironmentLabel(environment, environments),
57 - connected: environment.connection.phase === "connected",
58 - }));
59 - const { checks, testConnection } = useHostConnectionChecks(targets);
60 - const hostEnvironments = connectedEnvironments.map((environment) => ({
61 - environmentId: environment.environmentId,
62 - label: environment.label,
63 - labels: settingsScopeEnvironmentLabels(environment, connectedEnvironments),
64 - hosts: environment.serverConfig?.settings.deviceHosts ?? [],
65 - }));
66 - const groupedHosts = groupDeviceHosts(hostEnvironments);
67 - const save = async (host: SshDeviceHostConfig, remove = false, original = host) => {
68 - if (!props.environmentId || projectScope) return;
69 - setBusy(true);
70 - const results = await Promise.allSettled(
71 - environments.map(async (environment) => {
72 - if (environment.connection.phase !== "connected" || !environment.serverConfig) {
73 - throw new Error("Environment disconnected");
74 - }
75 - if (!readEnvironmentScope(environment.environmentId, AuthSettingsWriteScope)) {
76 - throw new Error("This connection cannot change device settings.");
77 - }
78 - return update({
79 - environmentId: environment.environmentId,
80 - input: {
81 - patch: {
82 - deviceHosts: updateDeviceHosts(
83 - environment.serverConfig.settings.deviceHosts,
84 - host,
85 - remove,
86 - original,
87 - ),
88 - },
89 - },
90 - });
91 - }),
92 - );
93 - setBusy(false);
94 - const failed = environments.filter((_, index) => {
95 - const result = results[index];
96 - return result?.status !== "fulfilled" || result.value._tag === "Failure";
97 - });
98 - if (failed.length === 0) {
99 - setEditing(null);
100 - } else {
101 - toastManager.add({
102 - type: "error",
103 - title: "Device hosts not saved on all environments",
104 - description: `Could not update ${failed.map((environment) => environment.label).join(", ")}.`,
105 - });
106 - }
107 - };
108 - const listActions = {
109 - busy: !canConfigure || projectScope || busy,
110 - checks,
111 - testConnection: async (host: SshDeviceHostConfig) => {
112 - const results = await testConnection(host);
113 - if (!results) return;
114 - const failed = targets.filter((target) => results[target.environmentId]?.status === "failed");
115 - toastManager.add({
116 - type: failed.length ? "error" : "success",
117 - title: failed.length
118 - ? `${host.label}: ${failed.length} of ${targets.length} environments failed`
119 - : `${host.label}: connection checks passed`,
120 - description: failed.length
121 - ? `Could not connect from ${failed.map((target) => target.label).join(", ")}.`
122 - : "Connected or already available locally on each selected environment.",
123 - });
124 - return results;
125 - },
126 - onEdit: (host: SshDeviceHostConfig) => {
127 - setOriginalHost(host);
128 - setEditing(host);
129 - },
130 - onRemove: (host: SshDeviceHostConfig) => void save(host, true),
131 - };
132 - return (
133 - <SettingsRow
134 - id="device-hosts"
135 - title="Device hosts"
136 - serverScoped
137 - settingKeys={["deviceHosts"]}
138 - description="Add remote machines with simulator or emulator runtimes installed, and the selected environments will connect over SSH and set up device tools automatically."
139 - control={
140 - <Button
141 - size="sm"
142 - variant="outline"
143 - disabled={
144 - !canConfigure || projectScope || busy || !props.environmentId || editing !== null
145 - }
146 - onClick={() => {
147 - setOriginalHost(null);
148 - setEditing({ kind: "ssh", id: randomUUID(), label: "", target: "" });
149 - }}
150 - >
151 - <PlusIcon className="size-3.5" /> Add host
152 - </Button>
153 - }
154 - >
155 - <div className="pt-3 pb-2">
156 - {!props.environmentId ? (
157 - <p className="text-sm text-muted-foreground">
158 - Connect a selected environment to manage device hosts.
159 - </p>
160 - ) : (
161 - <>
162 - {hostEnvironments.length > 1 && groupedHosts === null ? (
163 - <div className="space-y-2">
164 - {hostEnvironments.map((environment) => (
165 - <FoldedSettingsSection
166 - key={environment.environmentId}
167 - id={`device-hosts-${environment.environmentId}`}
168 - title={
169 - <>
170 - <span className="block max-w-64 truncate">
171 - {environment.labels.primary}
172 - </span>
173 - {environment.labels.secondary ? (
174 - <span className="block max-w-64 truncate text-xs font-normal text-muted-foreground">
175 - {environment.labels.secondary}
176 - </span>
177 - ) : null}
178 - </>
179 - }
180 - summary={
181 - summarizeLabels(environment.hosts.map((host) => host.label)) ||
182 - "No device hosts"
183 - }
184 - >
185 - <div className="px-3 sm:px-4 [&>div:first-child]:border-t-0">
186 - <DeviceHostList environments={[environment]} {...listActions} />
187 - </div>
188 - </FoldedSettingsSection>
189 - ))}
190 - </div>
191 - ) : (
192 - <DeviceHostList
193 - environments={hostEnvironments}
194 - groups={groupedHosts ?? undefined}
195 - compact={hostEnvironments.length > 1}
196 - {...listActions}
197 - />
198 - )}
199 - {editing ? (
200 - <DeviceHostEditor
201 - key={editing.id}
202 - host={editing}
203 - isNew={originalHost === null}
204 - targets={targets}
205 - busy={busy}
206 - onSave={(host) => void save(host, false, originalHost ?? host)}
207 - onClose={() => setEditing(null)}
208 - />
209 - ) : null}
210 - </>
211 - )}
212 - </div>
213 - </SettingsRow>
214 - );
215 -}
216 -
217 -const deviceHostStatesAtom = environmentAtomList("web-device-host-states", (environmentId) =>
218 - deviceEnvironment.state({ environmentId, input: {} }),
219 -);
220 -
221 -function DeviceHostList({
222 - environments,
223 - groups,
224 - compact = false,
225 - busy,
226 - onEdit,
227 - onRemove,
228 - checks,
229 - testConnection,
230 -}: {
231 - environments: ReadonlyArray<DeviceHostEnvironment>;
232 - groups?: ReadonlyArray<DeviceHostGroup> | undefined;
233 - compact?: boolean;
234 - busy: boolean;
235 - onEdit: (host: SshDeviceHostConfig) => void;
236 - onRemove: (host: SshDeviceHostConfig) => void;
237 - checks: ReturnType<typeof useHostConnectionChecks>["checks"];
238 - testConnection: ReturnType<typeof useHostConnectionChecks>["testConnection"];
239 -}) {
240 - const { environments: scopeEnvironments } = useSettingsScope();
241 - const environmentLabels = new Map(
242 - scopeEnvironments.map((environment) => [
243 - environment.environmentId,
244 - settingsScopeEnvironmentLabels(environment, scopeEnvironments),
245 - ]),
246 - );
247 - const environmentIds = environments.map(({ environmentId }) => environmentId);
248 - const results = useAtomValue(deviceHostStatesAtom(environmentIdsKey(environmentIds)));
249 - const states = new Map(
250 - environmentIds.map(
251 - (environmentId, index) =>
252 - [environmentId, Option.getOrUndefined(AsyncResult.value(results[index]!))] as const,
253 - ),
254 - );
255 - const retry = useAtomCommand(deviceEnvironment.list);
256 - const [retrying, setRetrying] = useState<string | null>(null);
257 - const retryHost = (environmentId: EnvironmentId, hostId: string, key = hostId) => {
258 - setRetrying(key);
259 - void retry({ environmentId, input: { retryHostId: hostId } }).finally(() => setRetrying(null));
260 - };
261 - const rows =
262 - groups ??
263 - environments.flatMap((environment) =>
264 - environment.hosts.map((host) => ({
265 - host,
266 - members: [{ environmentId: environment.environmentId, label: environment.label, host }],
267 - })),
268 - );
269 - return (
270 - <>
271 - {rows.length === 0 ? (
272 - <p className="py-2 text-sm text-muted-foreground">No device hosts.</p>
273 - ) : null}
274 - {rows.map(({ host, members }) => {
275 - const hostChecks = checks[deviceHostConnectionKey(host)];
276 - const checkedMembers = scopeEnvironments.flatMap((environment) =>
277 - hostChecks?.[environment.environmentId] &&
278 - !members.some((member) => member.environmentId === environment.environmentId)
279 - ? [{ environmentId: environment.environmentId, label: environment.label, host }]
280 - : [],
281 - );
282 - const results = [...members, ...checkedMembers].map((member) => {
283 - const state = states.get(member.environmentId);
284 - const status = state?.hostStatuses[member.host.id];
285 - const check = hostChecks?.[member.environmentId];
286 - const summary = state?.hosts.find((value) => value.id === member.host.id);
287 - const label = environmentLabels.get(member.environmentId)?.primary ?? member.label;
288 - const address = environmentLabels.get(member.environmentId)?.secondary;
289 - const error =
290 - check?.status === "failed"
291 - ? check.error
292 - : check?.status === "local"
293 - ? undefined
294 - : status?.status === "failed"
295 - ? status.detail
296 - : undefined;
297 - return {
298 - ...member,
299 - label,
300 - address,
301 - name: [label, address].filter(Boolean).join(" · "),
302 - state,
303 - status,
304 - check,
305 - summary,
306 - error,
307 - versions: (
308 - <DeviceToolVersions
309 - owner={label}
310 - error={summary?.toolInspectionError}
311 - tools={summary?.tools ?? (check?.status === "connected" ? check.tools : undefined)}
312 - />
313 - ),
314 - };
315 - });
316 - const first = results[0];
317 - if (!first) return null;
318 - const { environmentId, status, check, summary, error } = first;
319 - const platforms =
320 - (check?.status === "connected" ? check.platforms : undefined) ?? summary?.platforms ?? [];
321 - const progress =
322 - check?.status === "pending"
323 - ? "Checking connection…"
324 - : status?.status === "installing"
325 - ? "Installing device support…"
326 - : status?.status === "starting"
327 - ? "Connecting…"
328 - : null;
329 - const failed = results.filter(
330 - (result) =>
331 - result.check?.status === "failed" ||
332 - (result.check?.status !== "local" && result.status?.status === "failed"),
333 - );
334 - const pending = results.some(
335 - (result) =>
336 - result.check?.status === "pending" ||
337 - result.status?.status === "installing" ||
338 - result.status?.status === "starting",
339 - );
340 - const ready = results.every(
341 - (result) =>
342 - result.check?.status === "connected" ||
343 - result.check?.status === "local" ||
344 - result.status?.status === "ready",
345 - );
346 - const retryable = results.filter(
347 - (result) =>
348 - result.status?.status === "failed" &&
349 - result.state?.supportsHostRetry &&
350 - result.state.hostStatus !== "disabled",
351 - );
352 - const canRetry = !compact && retryable.includes(first);
353 - const indicators = compact
354 - ? [
355 - {
356 - key: "connection",
357 - label: failed.length
358 - ? "Connection failed"
359 - : pending
360 - ? "Checking connections"
361 - : ready
362 - ? "Connected"
363 - : "Connection not checked",
364 - warning: failed.length > 0,
365 - icon: failed.length ? (
366 - <TriangleAlertIcon className="size-3.5" />
367 - ) : pending ? (
368 - <Spinner size="xs" />
369 - ) : ready ? (
370 - <CheckIcon className="size-3.5" />
371 - ) : (
372 - <CircleIcon className="size-3.5" />
373 - ),
374 - detail: failed.length ? (
375 - <div className="space-y-1">
376 - {failed.map((result) => (
377 - <p key={result.environmentId}>
378 - {result.name}: {result.error || "Connection failed"}
379 - </p>
380 - ))}
381 - </div>
382 - ) : pending ? (
383 - "Checking connections…"
384 - ) : ready ? (
385 - "Connected or available locally on each listed machine"
386 - ) : (
387 - "Test the connection to check access from each machine"
388 - ),
389 - },
390 - ]
391 - : platforms
392 - .filter((platform) => platform.available)
393 - .map((platform) => ({
394 - key: platform.platform,
395 - label: platform.platform === "ios" ? "iOS available" : "Android available",
396 - warning: false,
397 - icon:
398 - platform.platform === "ios" ? (
399 - // The Apple mark is bottom-heavy; lift it so it does not dip under the label.
400 - <AppleIcon className="size-3.5 -translate-y-px" />
401 - ) : (
402 - <AndroidIcon className="size-3.5" />
403 - ),
404 - }));
405 - return (
406 - <div key={host.id} className="flex items-center gap-2 border-t border-border/50 py-2.5">
407 - <div className="min-w-0 flex-1">
408 - <div className="flex min-w-0 items-center gap-2">
409 - <p className="truncate text-sm font-medium">{host.label}</p>
410 - {indicators.map((indicator) => (
411 - <Tooltip key={indicator.key}>
412 - <TooltipTrigger
413 - render={
414 - <span
415 - tabIndex={0}
416 - role="img"
417 - aria-label={indicator.label}
418 - className={
419 - indicator.warning
420 - ? "shrink-0 text-warning"
421 - : "shrink-0 text-muted-foreground"
422 - }
423 - />
424 - }
425 - >
426 - {indicator.icon}
427 - </TooltipTrigger>
428 - <TooltipPopup>
429 - {"detail" in indicator ? indicator.detail : indicator.label}
430 - </TooltipPopup>
431 - </Tooltip>
432 - ))}
433 - </div>
434 - <p className="truncate text-xs text-muted-foreground">{host.target}</p>
435 - {results
436 - .filter(
437 - (result) =>
438 - result.status?.status === "ready" && result.status.androidDiscoveryIncomplete,
439 - )
440 - .map((result) => (
441 - <p key={result.environmentId} role="status" className="mt-1 text-xs text-warning">
442 - {compact ? `${result.label}: ` : ""}
443 - {result.status?.detail ??
444 - "The Android device list may be incomplete. Refresh devices to try again."}
445 - </p>
446 - ))}
447 - {compact ? (
448 - <Collapsible>
449 - <div className="min-w-0 text-xs [--inline-button-white-space:normal]">
450 - <CollapsibleTrigger
451 - aria-label={`${host.label} machine details`}
452 - render={<InlineButton tone="muted" />}
453 - >
454 - <span className="line-clamp-1 break-all text-left">
455 - {summarizeLabels(results.map((result) => result.name))}
456 - </span>
457 - <ChevronDownIcon className="size-3 shrink-0" />
458 - </CollapsibleTrigger>
459 - </div>
460 - <CollapsiblePanel>
461 - <div className="mt-2 space-y-2">
462 - {results.map((result) => (
463 - <div key={result.environmentId}>
464 - <p className="text-xs text-muted-foreground">{result.label}</p>
465 - {result.address ? (
466 - <p className="truncate text-xs text-muted-foreground">
467 - {result.address}
468 - </p>
469 - ) : null}
470 - {result.error ? (
471 - <p role="status" className="text-xs text-destructive">
472 - {result.error}
473 - </p>
474 - ) : null}
475 - {result.state ? (
476 - <DeviceHostDiagnostics
477 - hosts={[result.host]}
478 - hostStatuses={result.state.hostStatuses}
479 - />
480 - ) : null}
481 - {result.versions}
482 - {result.check?.status === "local" ? (
483 - <p className="text-xs text-muted-foreground">
484 - Already available locally
485 - </p>
486 - ) : (
487 - <DeviceHostAvailability
488 - platforms={
489 - (result.check?.status === "connected"
490 - ? result.check.platforms
491 - : result.summary?.platforms) ?? []
492 - }
493 - />
494 - )}
495 - </div>
496 - ))}
497 - </div>
498 - </CollapsiblePanel>
499 - </Collapsible>
500 - ) : (
501 - first.versions
502 - )}
503 - {!compact && check?.status === "local" ? (
504 - <p className="mt-1 text-xs text-muted-foreground">Already available locally</p>
505 - ) : null}
506 - {!compact && error ? (
507 - <div className="mt-1" role="status">
508 - <details className="text-xs text-destructive">
509 - <summary>Connection failed</summary>
510 - <p className="mt-1 whitespace-pre-wrap break-words">{error}</p>
511 - </details>
512 - </div>
513 - ) : null}
514 - {!compact
515 - ? results.map((result) =>
516 - result.state ? (
517 - <DeviceHostDiagnostics
518 - key={result.environmentId}
519 - className="mt-1"
520 - hosts={[result.host]}
521 - hostStatuses={result.state.hostStatuses}
522 - />
523 - ) : null,
524 - )
525 - : null}
526 - </div>
527 - {!compact && progress ? (
528 - <span
529 - role="status"
530 - className="inline-flex items-center gap-1.5 text-xs text-muted-foreground"
531 - >
532 - <Spinner size="xs" />
533 - {progress}
534 - </span>
535 - ) : null}
536 - <Menu>
537 - <MenuTrigger
538 - render={
539 - <Button
540 - size="icon-sm"
541 - variant="ghost-muted"
542 - disabled={busy}
543 - aria-label={host.label + " options"}
544 - />
545 - }
546 - >
547 - <MoreVertical />
548 - </MenuTrigger>
549 - <MenuPopup align="end">
550 - <MenuItem onClick={() => onEdit(host)}>Edit</MenuItem>
551 - <MenuItem variant="destructive" onClick={() => onRemove(host)}>
552 - Remove
553 - </MenuItem>
554 - {compact
555 - ? retryable.map((result) => (
556 - <MenuItem
557 - key={result.environmentId}
558 - disabled={retrying !== null}
559 - onClick={() =>
560 - retryHost(result.environmentId, result.host.id, result.environmentId)
561 - }
562 - >
563 - {retrying === result.environmentId ? "Retrying" : "Retry"} from{" "}
564 - {result.label}
565 - {result.address ? ` (${result.address})` : null}
566 - </MenuItem>
567 - ))
568 - : null}
569 - </MenuPopup>
570 - </Menu>
571 - <Button
572 - size="sm"
573 - variant="outline"
574 - disabled={
575 - busy || (canRetry ? retrying !== null : compact ? pending : progress !== null)
576 - }
577 - onClick={() => {
578 - if (canRetry) retryHost(environmentId, host.id);
579 - else void testConnection(host);
580 - }}
581 - >
582 - {canRetry ? (retrying === host.id ? "Retrying…" : "Retry") : "Test connection"}
583 - </Button>
584 - </div>
585 - );
586 - })}
587 - </>
588 - );
589 -}
590 -
591 -function summarizeLabels(labels: ReadonlyArray<string>) {
592 - return `${labels.slice(0, 2).join(", ")}${labels.length > 2 ? ` +${labels.length - 2}` : ""}`;
593 -}
apps/web/src/components/settings/DeviceSourcesSettings.tsx new
+808
@@ -0,0 +1,808 @@
1 +import { useAtomValue } from "@effect/atom-react";
2 +import { Fragment, useState, type ReactNode } from "react";
3 +import * as Cause from "effect/Cause";
4 +import * as Option from "effect/Option";
5 +import { AsyncResult } from "effect/reactivity";
6 +import {
7 + AuthSettingsWriteScope,
8 + type DevicePlatform,
9 + type DevicePlatformAvailability,
10 + type DeviceServiceState,
11 + type EasDeviceHostConfig,
12 + type EnvironmentId,
13 + type ServerSettingsPatch,
14 + type SimlockDeviceHostConfig,
15 + type SshDeviceHostConfig,
16 +} from "@t3tools/contracts";
17 +import { ChevronDownIcon, MoreVertical, PlusIcon } from "lucide-react";
18 +
19 +import { cn, randomUUID } from "../../lib/utils";
20 +import { deviceEnvironment } from "../../state/device";
21 +import { environmentAtomList, environmentIdsKey } from "../../state/environmentAtomList";
22 +import { serverEnvironment } from "../../state/server";
23 +import { readEnvironmentScope } from "../../state/session";
24 +import { useAtomCommand } from "../../state/use-atom-command";
25 +import { AndroidIcon, AppleIcon } from "../Icons";
26 +import { Button, InlineButton } from "../ui/button";
27 +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
28 +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
29 +import { Spinner } from "../ui/spinner";
30 +import { toastManager } from "../ui/toast";
31 +import { DeviceHostEditor } from "./DeviceHostEditor";
32 +import { updateDeviceHosts, groupDeviceHosts } from "./deviceHostsSettings.logic";
33 +import { EasDeviceHostEditor } from "./EasDeviceHostEditor";
34 +import {
35 + easSessionLimits,
36 + newEasDeviceHost,
37 + updateEasDeviceHosts,
38 +} from "./easDeviceHostsSettings.logic";
39 +import { useSettingsScope } from "./SettingsScopeContext";
40 +import { SettingsSection } from "./settingsLayout";
41 +import { settingsScopeEnvironmentLabel } from "./settingsScopeAxis";
42 +import { SimlockDeviceHostEditor } from "./SimlockDeviceHostEditor";
43 +import {
44 + newSimlockDeviceHost,
45 + planSimlockDeviceHostSave,
46 + simlockLeaseLimits,
47 + updateSimlockDeviceHosts,
48 + type SimlockTokenEntry,
49 +} from "./simlockDeviceHostsSettings.logic";
50 +import { useHostConnectionChecks } from "./useHostConnectionChecks";
51 +
52 +const deviceHostStatesAtom = environmentAtomList("web-device-host-states", (environmentId) =>
53 + deviceEnvironment.state({ environmentId, input: {} }),
54 +);
55 +
56 +const failureMessage = (cause: Cause.Cause<unknown>) => {
57 + const error = Cause.squash(cause);
58 + return error instanceof Error ? error.message : String(error);
59 +};
60 +
61 +/** Something on one environment that is in progress or needs a fix; a working source has none. */
62 +interface SourceStatus {
63 + readonly tone: "pending" | "warning" | "error";
64 + readonly label: string;
65 + readonly detail?: string | undefined;
66 + readonly action?: { readonly label: string; readonly run: () => void } | undefined;
67 +}
68 +
69 +/** A source on one environment whose devices are on. */
70 +interface SourceEnvironment {
71 + readonly environmentId: EnvironmentId;
72 + readonly label: string;
73 + readonly added: boolean;
74 + readonly status?: SourceStatus | undefined;
75 + /** Unknown until the environment's hub has reached the source. */
76 + readonly platforms?: ReadonlyArray<DevicePlatformAvailability> | undefined;
77 +}
78 +
79 +interface SourceRow {
80 + readonly key: string;
81 + readonly title: string;
82 + readonly kind?: string;
83 + readonly description: ReactNode;
84 + readonly environments: ReadonlyArray<SourceEnvironment>;
85 + /**
86 + * One machine or account every environment reaches the same way (an SSH host, EAS, a Simlock
87 + * pool), so its platforms are the same for all of them. Local simulators differ per machine.
88 + */
89 + readonly shared: boolean;
90 + readonly actions?: ReactNode;
91 +}
92 +
93 +type Editing =
94 + | {
95 + readonly kind: "ssh";
96 + readonly host: SshDeviceHostConfig;
97 + readonly original: SshDeviceHostConfig | null;
98 + /** Limits the save to these environments, for a host that differs between them. */
99 + readonly only?: ReadonlySet<EnvironmentId>;
100 + }
101 + | {
102 + readonly kind: "eas";
103 + readonly host: EasDeviceHostConfig;
104 + readonly isNew: boolean;
105 + /** Where the editor checks the Expo account: an environment that holds the host. */
106 + readonly environmentId: EnvironmentId;
107 + }
108 + | { readonly kind: "simlock"; readonly host: SimlockDeviceHostConfig; readonly isNew: boolean };
109 +
110 +/** What a configured host is doing on one environment, when it is not simply working. */
111 +function hostStatus(
112 + state: DeviceServiceState | undefined,
113 + hostId: string,
114 +): SourceStatus | undefined {
115 + if (!state) return { tone: "pending", label: "Loading" };
116 + const status = state.hostStatuses[hostId];
117 + switch (status?.status) {
118 + case "ready":
119 + return status.androidDiscoveryIncomplete
120 + ? { tone: "warning", label: "Android list may be incomplete", detail: status.detail }
121 + : undefined;
122 + case "installing":
123 + case "starting":
124 + return { tone: "pending", label: "Starting", detail: status.detail };
125 + case "failed":
126 + return { tone: "error", label: "Failed", detail: status.detail };
127 + default:
128 + return undefined;
129 + }
130 +}
131 +
132 +const hostPlatforms = (state: DeviceServiceState | undefined, hostId: string) =>
133 + state?.hosts.find((host) => host.id === hostId)?.platforms;
134 +
135 +/**
136 + * Every device source the selected environments can open, one row each. A source configured on
137 + * several environments is one row; how it stands on each lives in the row's breakdown.
138 + */
139 +export function DeviceSourcesSettings(props: {
140 + readonly supportsEas: boolean;
141 + readonly supportsSimlock: boolean;
142 +}) {
143 + const { scope, environments, connectedEnvironments, environment: primary } = useSettingsScope();
144 + const projectScope = scope.kind === "project" || scope.kind === "checkout";
145 + const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
146 + const list = useAtomCommand(deviceEnvironment.list, { reportFailure: false });
147 + const [editing, setEditing] = useState<Editing | null>(null);
148 + const [busy, setBusy] = useState(false);
149 + const label = (environment: (typeof environments)[number]) =>
150 + settingsScopeEnvironmentLabel(environment, environments);
151 + const targets = environments.map((environment) => ({
152 + environmentId: environment.environmentId,
153 + label: label(environment),
154 + connected: environment.connection.phase === "connected",
155 + }));
156 + const { testConnection } = useHostConnectionChecks(targets);
157 + const ids = connectedEnvironments.map((environment) => environment.environmentId);
158 + const results = useAtomValue(deviceHostStatesAtom(environmentIdsKey(ids)));
159 + const members = connectedEnvironments.map((environment, index) => {
160 + const result = results[index];
161 + return {
162 + environmentId: environment.environmentId,
163 + label: label(environment),
164 + settings: environment.serverConfig?.settings,
165 + state: result ? Option.getOrUndefined(AsyncResult.value(result)) : undefined,
166 + };
167 + });
168 + // Environments with devices off are left out: the switch above already says so.
169 + const active = members.filter((member) => member.settings?.enableDeviceSupport);
170 + const simlockEnabled = members.some((member) => member.settings?.simlockDeviceHostsEnabled);
171 + // Like every scoped setting, a change reaches the connected environments and skips the rest.
172 + const disabled = projectScope || busy || members.length === 0;
173 +
174 + /** Writes one settings patch per environment; reports the environments it could not change. */
175 + const write = async (
176 + patches: ReadonlyArray<{ environmentId: EnvironmentId; patch: ServerSettingsPatch }>,
177 + failedTitle: string,
178 + ) => {
179 + if (projectScope) return false;
180 + const name = (environmentId: EnvironmentId) =>
181 + members.find((member) => member.environmentId === environmentId)?.label ?? environmentId;
182 + const unwritable = patches.filter(
183 + (patch) => !readEnvironmentScope(patch.environmentId, AuthSettingsWriteScope),
184 + );
185 + if (unwritable.length > 0) {
186 + toastManager.add({
187 + type: "error",
188 + title: failedTitle,
189 + description: `This connection cannot change settings on ${unwritable.map((patch) => name(patch.environmentId)).join(", ")}.`,
190 + });
191 + return false;
192 + }
193 + setBusy(true);
194 + const outcomes = await Promise.all(
195 + patches.map((patch) =>
196 + update({ environmentId: patch.environmentId, input: { patch: patch.patch } }),
197 + ),
198 + );
199 + setBusy(false);
200 + const failed = patches.flatMap((patch, index) => {
201 + const outcome = outcomes[index];
202 + return outcome && outcome._tag === "Failure"
203 + ? [`${name(patch.environmentId)}: ${failureMessage(outcome.cause)}`]
204 + : [];
205 + });
206 + if (failed.length === 0) return true;
207 + toastManager.add({ type: "error", title: failedTitle, description: failed.join("\n") });
208 + return false;
209 + };
210 +
211 + const saveSsh = async (
212 + host: SshDeviceHostConfig,
213 + remove: boolean,
214 + original = host,
215 + only?: ReadonlySet<EnvironmentId>,
216 + ) => {
217 + try {
218 + const saved = await write(
219 + members
220 + .filter((member) => !only || only.has(member.environmentId))
221 + .map((member) => ({
222 + environmentId: member.environmentId,
223 + patch: {
224 + deviceHosts: updateDeviceHosts(
225 + member.settings?.deviceHosts ?? [],
226 + host,
227 + remove,
228 + original,
229 + ),
230 + },
231 + })),
232 + remove ? "Device host not removed everywhere" : "Device host not saved everywhere",
233 + );
234 + if (saved) setEditing(null);
235 + } catch (error) {
236 + toastManager.add({
237 + type: "error",
238 + title: "Device host not saved",
239 + description: error instanceof Error ? error.message : String(error),
240 + });
241 + }
242 + };
243 +
244 + const saveEas = async (
245 + host: EasDeviceHostConfig,
246 + remove: boolean,
247 + previous?: EasDeviceHostConfig,
248 + ) => {
249 + const keepToken = previous !== undefined && host.accessToken === previous.accessToken;
250 + const saved = await write(
251 + members.map((member) => ({
252 + environmentId: member.environmentId,
253 + patch: {
254 + easDeviceHosts: updateEasDeviceHosts(
255 + member.settings?.easDeviceHosts ?? [],
256 + host,
257 + remove,
258 + keepToken,
259 + ),
260 + },
261 + })),
262 + remove ? "EAS host not removed everywhere" : "EAS host not saved everywhere",
263 + );
264 + if (saved) setEditing(null);
265 + };
266 +
267 + const simlockEnvironments = members.map((member) => ({
268 + environmentId: member.environmentId,
269 + label: member.label,
270 + hosts: member.settings?.simlockDeviceHosts ?? [],
271 + }));
272 + const saveSimlock = async (
273 + host: SimlockDeviceHostConfig,
274 + tokens: ReadonlyMap<EnvironmentId, SimlockTokenEntry>,
275 + ) => {
276 + const plan = planSimlockDeviceHostSave(simlockEnvironments, host, tokens);
277 + if ("problem" in plan) return;
278 + const saved = await write(
279 + plan.patches.map((patch) => ({
280 + environmentId: patch.environmentId,
281 + patch: { simlockDeviceHosts: patch.hosts },
282 + })),
283 + "Simlock host not saved everywhere",
284 + );
285 + if (saved) setEditing(null);
286 + };
287 + const removeSimlock = (host: SimlockDeviceHostConfig) =>
288 + void write(
289 + simlockEnvironments
290 + .filter((environment) => environment.hosts.some((candidate) => candidate.id === host.id))
291 + .map((environment) => ({
292 + environmentId: environment.environmentId,
293 + patch: { simlockDeviceHosts: updateSimlockDeviceHosts(environment.hosts, host, true) },
294 + })),
295 + "Simlock host not removed everywhere",
296 + );
297 +
298 + const [testing, setTesting] = useState<ReadonlySet<string>>(new Set());
299 + const testSsh = async (host: SshDeviceHostConfig) => {
300 + setTesting((current) => new Set(current).add(host.id));
301 + const checked = await testConnection(host).finally(() =>
302 + setTesting((current) => {
303 + const next = new Set(current);
304 + next.delete(host.id);
305 + return next;
306 + }),
307 + );
308 + if (!checked) return;
309 + const failed = targets.filter((target) => checked[target.environmentId]?.status === "failed");
310 + toastManager.add({
311 + type: failed.length ? "error" : "success",
312 + title: failed.length
313 + ? `${host.label}: ${failed.length} of ${targets.length} environments failed`
314 + : `${host.label}: connection checks passed`,
315 + description: failed.length
316 + ? failed
317 + .map((target) => {
318 + const result = checked[target.environmentId];
319 + return `${target.label}: ${result?.status === "failed" ? result.error : "failed"}`;
320 + })
321 + .join("\n")
322 + : "Connected or already available locally on each selected environment.",
323 + });
324 + };
325 +
326 + const retry = (environmentId: EnvironmentId, hostId: string) =>
327 + void list({ environmentId, input: { retryHostId: hostId } });
328 +
329 + const rowActions = (onEdit: () => void, onRemove: () => void, extra?: ReactNode) => (
330 + <>
331 + <Button size="sm" variant="outline" disabled={disabled} onClick={onEdit}>
332 + Edit
333 + </Button>
334 + <Menu>
335 + <MenuTrigger
336 + render={
337 + <Button size="icon-sm" variant="ghost-muted" disabled={disabled} aria-label="More" />
338 + }
339 + >
340 + <MoreVertical />
341 + </MenuTrigger>
342 + <MenuPopup align="end">
343 + {extra}
344 + <MenuItem variant="destructive" onClick={onRemove}>
345 + Remove
346 + </MenuItem>
347 + </MenuPopup>
348 + </Menu>
349 + </>
350 + );
351 +
352 + const rows: SourceRow[] = [];
353 +
354 + rows.push({
355 + key: "local",
356 + shared: false,
357 + title: "Local simulators",
358 + description:
359 + members.length > 1
360 + ? "Simulators and emulators installed on each environment's own machine."
361 + : "Simulators and emulators installed on this environment's machine.",
362 + environments: active.map((member) => {
363 + const local = member.state?.hosts.find((host) => host.kind === "local");
364 + const status = local ? hostStatus(member.state, local.id) : hostStatus(member.state, "");
365 + return {
366 + environmentId: member.environmentId,
367 + label: member.label,
368 + added: true,
369 + platforms: local?.platforms,
370 + status:
371 + status?.tone === "error"
372 + ? {
373 + ...status,
374 + action: {
375 + label: "Refresh",
376 + run: () => void list({ environmentId: member.environmentId, input: {} }),
377 + },
378 + }
379 + : status,
380 + };
381 + }),
382 + });
383 +
384 + const grouped = groupDeviceHosts(
385 + members.map((member) => ({
386 + environmentId: member.environmentId,
387 + label: member.label,
388 + hosts: member.settings?.deviceHosts ?? [],
389 + })),
390 + );
391 + const sshGroups =
392 + grouped ??
393 + // Hosts that cannot be matched across environments stay one row per environment.
394 + members.flatMap((member) =>
395 + (member.settings?.deviceHosts ?? []).map((host) => ({
396 + host,
397 + members: [{ environmentId: member.environmentId, label: member.label, host }],
398 + })),
399 + );
400 + for (const group of sshGroups) {
401 + const host = group.host;
402 + const holders = new Set(group.members.map((member) => member.environmentId));
403 + rows.push({
404 + key: `ssh:${host.id}:${group.members.map((member) => member.environmentId).join(",")}`,
405 + shared: true,
406 + title: host.label,
407 + kind: "SSH",
408 + description: host.target,
409 + environments: active.map((member) => {
410 + const held = group.members.find(
411 + (candidate) => candidate.environmentId === member.environmentId,
412 + );
413 + if (!held)
414 + return { environmentId: member.environmentId, label: member.label, added: false };
415 + const status = testing.has(host.id)
416 + ? ({ tone: "pending", label: "Testing connection" } as const)
417 + : hostStatus(member.state, held.host.id);
418 + return {
419 + environmentId: member.environmentId,
420 + label: member.label,
421 + added: true,
422 + platforms: hostPlatforms(member.state, held.host.id),
423 + status:
424 + status?.tone === "error" && member.state?.supportsHostRetry
425 + ? {
426 + ...status,
427 + label: "Can't connect",
428 + action: { label: "Retry", run: () => retry(member.environmentId, held.host.id) },
429 + }
430 + : status,
431 + };
432 + }),
433 + actions: rowActions(
434 + () =>
435 + setEditing({ kind: "ssh", host, original: host, ...(grouped ? {} : { only: holders }) }),
436 + () => void saveSsh(host, true, host, holders),
437 + <MenuItem onClick={() => void testSsh(host)}>Test connection</MenuItem>,
438 + ),
439 + });
440 + }
441 +
442 + if (props.supportsEas) {
443 + const easHosts = new Map<string, EasDeviceHostConfig>();
444 + for (const member of members)
445 + for (const host of member.settings?.easDeviceHosts ?? [])
446 + if (!easHosts.has(host.id)) easHosts.set(host.id, host);
447 + for (const host of easHosts.values()) {
448 + const holders = members.filter((member) =>
449 + (member.settings?.easDeviceHosts ?? []).some((candidate) => candidate.id === host.id),
450 + );
451 + const [firstHolder] = holders;
452 + if (!firstHolder) continue;
453 + const checkOn = (
454 + holders.find((member) => member.environmentId === primary?.environmentId) ?? firstHolder
455 + ).environmentId;
456 + rows.push({
457 + key: `eas:${host.id}`,
458 + shared: true,
459 + title: host.label,
460 + kind: "EAS",
461 + description: easSessionLimits(host),
462 + environments: active.map((member) => {
463 + const added = (member.settings?.easDeviceHosts ?? []).some(
464 + (candidate) => candidate.id === host.id,
465 + );
466 + return {
467 + environmentId: member.environmentId,
468 + label: member.label,
469 + added,
470 + ...(added
471 + ? {
472 + status: hostStatus(member.state, host.id),
473 + platforms: hostPlatforms(member.state, host.id),
474 + }
475 + : {}),
476 + };
477 + }),
478 + actions: rowActions(
479 + () => setEditing({ kind: "eas", host, isNew: false, environmentId: checkOn }),
480 + () => void saveEas(host, true),
481 + ),
482 + });
483 + }
484 + }
485 +
486 + if (props.supportsSimlock && simlockEnabled) {
487 + const simlockHosts = new Map<string, SimlockDeviceHostConfig>();
488 + for (const environment of simlockEnvironments)
489 + for (const host of environment.hosts)
490 + if (!simlockHosts.has(host.id)) simlockHosts.set(host.id, host);
491 + for (const host of simlockHosts.values()) {
492 + const edit = () => setEditing({ kind: "simlock", host, isNew: false });
493 + rows.push({
494 + key: `simlock:${host.id}`,
495 + shared: true,
496 + title: host.label,
497 + kind: "Simlock",
498 + description: `${host.gatewayUrl.replace(/^https?:\/\//, "")} · ${simlockLeaseLimits(host)}`,
499 + environments: active.map((member) => {
500 + const held = (member.settings?.simlockDeviceHosts ?? []).find(
501 + (candidate) => candidate.id === host.id,
502 + );
503 + if (!held)
504 + return { environmentId: member.environmentId, label: member.label, added: false };
505 + return {
506 + environmentId: member.environmentId,
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),
518 + };
519 + }),
520 + actions: rowActions(edit, () => removeSimlock(host)),
521 + });
522 + }
523 + }
524 +
525 + const addMenu = (
526 + <Menu>
527 + <MenuTrigger
528 + render={<Button size="sm" variant="outline" disabled={disabled || editing !== null} />}
529 + >
530 + <PlusIcon className="size-3.5" /> Add source
531 + <ChevronDownIcon className="size-3.5" />
532 + </MenuTrigger>
533 + <MenuPopup align="end">
534 + <MenuItem
535 + onClick={() =>
536 + setEditing({
537 + kind: "ssh",
538 + host: { kind: "ssh", id: randomUUID(), label: "", target: "" },
539 + original: null,
540 + })
541 + }
542 + >
543 + Machine over SSH
544 + </MenuItem>
545 + {props.supportsEas ? (
546 + <MenuItem
547 + onClick={() =>
548 + primary &&
549 + setEditing({
550 + kind: "eas",
551 + host: newEasDeviceHost(randomUUID()),
552 + isNew: true,
553 + environmentId: primary.environmentId,
554 + })
555 + }
556 + >
557 + EAS Simulator
558 + </MenuItem>
559 + ) : null}
560 + {props.supportsSimlock && simlockEnabled ? (
561 + <MenuItem
562 + onClick={() =>
563 + setEditing({ kind: "simlock", host: newSimlockDeviceHost(randomUUID()), isNew: true })
564 + }
565 + >
566 + Simlock pool (alpha)
567 + </MenuItem>
568 + ) : null}
569 + </MenuPopup>
570 + </Menu>
571 + );
572 +
573 + return (
574 + <SettingsSection id="device-sources" title="Device sources" headerAction={addMenu}>
575 + {rows.map((row) => (
576 + <DeviceSourceRow key={row.key} row={row} />
577 + ))}
578 + {editing?.kind === "ssh" ? (
579 + <DeviceHostEditor
580 + key={editing.host.id}
581 + host={editing.host}
582 + isNew={editing.original === null}
583 + targets={targets}
584 + busy={busy}
585 + onSave={(host) => void saveSsh(host, false, editing.original ?? host, editing.only)}
586 + onClose={() => setEditing(null)}
587 + />
588 + ) : editing?.kind === "eas" ? (
589 + <EasDeviceHostEditor
590 + key={editing.host.id}
591 + environmentId={editing.environmentId}
592 + host={editing.host}
593 + isNew={editing.isNew}
594 + busy={busy}
595 + onSave={(host) => void saveEas(host, false, editing.isNew ? undefined : editing.host)}
596 + onClose={() => setEditing(null)}
597 + />
598 + ) : editing?.kind === "simlock" ? (
599 + <SimlockDeviceHostEditor
600 + key={editing.host.id}
601 + host={editing.host}
602 + isNew={editing.isNew}
603 + environments={simlockEnvironments}
604 + busy={busy}
605 + onSave={(host, tokens) => void saveSimlock(host, tokens)}
606 + onClose={() => setEditing(null)}
607 + />
608 + ) : null}
609 + </SettingsSection>
610 + );
611 +}
612 +
613 +const PLATFORMS = [
614 + { platform: "ios", label: "iOS", Icon: AppleIcon },
615 + { platform: "android", label: "Android", Icon: AndroidIcon },
616 +] as const satisfies ReadonlyArray<{ platform: DevicePlatform; label: string; Icon: unknown }>;
617 +
618 +/** The platforms a source offers: one icon each, solid where available, muted where not. */
619 +function SourcePlatforms(props: { row: SourceRow }) {
620 + const added = props.row.environments.filter((environment) => environment.added);
621 + const known = added.filter((environment) => environment.platforms !== undefined);
622 + return PLATFORMS.filter(({ platform }) =>
623 + known.some((environment) =>
624 + environment.platforms?.some((candidate) => candidate.platform === platform),
625 + ),
626 + ).map((entry) => <PlatformIcon key={entry.platform} {...entry} row={props.row} known={known} />);
627 +}
628 +
629 +function PlatformIcon(props: {
630 + platform: DevicePlatform;
631 + label: string;
632 + Icon: (typeof PLATFORMS)[number]["Icon"];
633 + row: SourceRow;
634 + known: ReadonlyArray<SourceEnvironment>;
635 +}) {
636 + const availability = (environment: SourceEnvironment) =>
637 + environment.platforms?.find((candidate) => candidate.platform === props.platform);
638 + const availableOn = props.known.filter((environment) => availability(environment)?.available);
639 + const several = props.row.environments.length > 1;
640 + const available = availableOn.length > 0;
641 + const partial = available && availableOn.length < props.known.length;
642 + // A shared source usually answers the same everywhere, so its answer is given once. Each
643 + // environment still signs in to it on its own, which is where they can differ.
644 + const sharedAnswer = props.known.map(availability).find(Boolean);
645 + const uniform = props.known.every(
646 + (environment) =>
647 + availability(environment)?.available === sharedAnswer?.available &&
648 + availability(environment)?.reason === sharedAnswer?.reason,
649 + );
650 + const unavailableOn = props.known.filter((environment) => !availability(environment)?.available);
651 + const connected = props.row.environments.filter((environment) => environment.added);
652 + const notAdded = props.row.environments.filter((environment) => !environment.added);
653 + return (
654 + <Popover>
655 + <PopoverTrigger
656 + openOnHover
657 + delay={150}
658 + closeDelay={100}
659 + render={
660 + <button
661 + type="button"
662 + aria-label={`${props.row.title}: ${props.label} ${available ? "available" : "not available"}`}
663 + className={cn(
664 + "relative grid size-6 shrink-0 place-items-center rounded-md outline-hidden hover:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
665 + available ? "text-foreground" : "text-muted-foreground/45",
666 + )}
667 + />
668 + }
669 + >
670 + <props.Icon className={cn("size-3.5", props.platform === "ios" && "-translate-y-px")} />
671 + {partial ? (
672 + <span
673 + aria-hidden
674 + className="absolute top-0.5 right-0.5 size-1.5 rounded-full bg-warning ring-2 ring-background"
675 + />
676 + ) : null}
677 + </PopoverTrigger>
678 + <PopoverPopup side="top" align="end" width="sm">
679 + <p className="text-sm font-medium">
680 + {props.label}{" "}
681 + {available ? (partial ? "available on some" : "available") : "not available"}
682 + </p>
683 + {props.row.shared ? (
684 + <>
685 + {uniform && !available && sharedAnswer?.reason ? (
686 + <p className="mt-1 text-xs text-muted-foreground">{sharedAnswer.reason}</p>
687 + ) : null}
688 + {several ? (
689 + <dl className="mt-2 space-y-1.5 text-xs">
690 + {(
691 + [
692 + ...(uniform
693 + ? ([["Connected", connected]] as const)
694 + : ([
695 + ["Available", availableOn],
696 + ["Not available", unavailableOn],
697 + ] as const)),
698 + ["Not added", notAdded],
699 + ] as const
700 + ).map(([heading, environments]) =>
701 + environments.length > 0 ? (
702 + <div key={heading}>
703 + <dt className="text-muted-foreground">{heading}</dt>
704 + {environments.map((environment) => {
705 + const reason =
706 + heading === "Not available"
707 + ? availability(environment)?.reason
708 + : undefined;
709 + return (
710 + <dd key={environment.environmentId}>
711 + <span className="block truncate">{environment.label}</span>
712 + {reason ? (
713 + <span className="block text-muted-foreground">{reason}</span>
714 + ) : null}
715 + </dd>
716 + );
717 + })}
718 + </div>
719 + ) : null,
720 + )}
721 + </dl>
722 + ) : null}
723 + </>
724 + ) : several ? (
725 + <dl className="mt-2 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-xs">
726 + {props.known.map((environment) => {
727 + const entry = availability(environment);
728 + return (
729 + <Fragment key={environment.environmentId}>
730 + <dt className="text-muted-foreground">{environment.label}</dt>
731 + <dd className={entry?.available ? "" : "text-muted-foreground"}>
732 + {entry?.available ? "Available" : (entry?.reason ?? "Not available")}
733 + </dd>
734 + </Fragment>
735 + );
736 + })}
737 + </dl>
738 + ) : !available ? (
739 + <p className="mt-1 text-xs text-muted-foreground">
740 + {availability(props.known[0]!)?.reason ?? "Not set up on this machine."}
741 + </p>
742 + ) : null}
743 + </PopoverPopup>
744 + </Popover>
745 + );
746 +}
747 +
748 +function DeviceSourceRow(props: { row: SourceRow }) {
749 + const { row } = props;
750 + const several = row.environments.length > 1;
751 + const issues = row.environments.filter(
752 + (environment): environment is SourceEnvironment & { status: SourceStatus } =>
753 + environment.status !== undefined,
754 + );
755 + const problems = issues.filter((environment) => environment.status.tone !== "pending");
756 + const pending = issues.find((environment) => environment.status.tone === "pending");
757 + return (
758 + <div className="flex items-center gap-3 border-t border-border/60 px-3 py-3 first:border-t-0 sm:px-4">
759 + <div className="min-w-0 flex-1">
760 + <div className="flex min-w-0 items-center gap-1.5">
761 + <p className="truncate text-sm font-medium">{row.title}</p>
762 + {row.kind ? (
763 + <span className="shrink-0 rounded border border-border px-1 text-3xs uppercase tracking-wide text-muted-foreground">
764 + {row.kind}
765 + </span>
766 + ) : null}
767 + </div>
768 + <p className="truncate text-xs text-muted-foreground">{row.description}</p>
769 + {problems.map((environment) => (
770 + <p
771 + key={environment.environmentId}
772 + role="status"
773 + className={cn(
774 + "mt-1 flex flex-wrap items-center gap-1.5 text-xs",
775 + environment.status.tone === "error" ? "text-destructive" : "text-warning",
776 + )}
777 + >
778 + <span className="min-w-0 break-words">
779 + {several ? `${environment.label}: ` : ""}
780 + {!several && environment.status.detail
781 + ? environment.status.detail
782 + : environment.status.label}
783 + </span>
784 + {environment.status.action ? (
785 + <InlineButton onClick={environment.status.action.run}>
786 + {environment.status.action.label}
787 + </InlineButton>
788 + ) : null}
789 + </p>
790 + ))}
791 + </div>
792 + {pending ? (
793 + <span
794 + role="status"
795 + className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground"
796 + >
797 + <Spinner size="xs" />
798 + {pending.status.label}
799 + </span>
800 + ) : (
801 + <div className="flex shrink-0 items-center gap-0.5">
802 + <SourcePlatforms row={row} />
803 + </div>
804 + )}
805 + {row.actions ? <div className="flex shrink-0 items-center gap-1">{row.actions}</div> : null}
806 + </div>
807 + );
808 +}
apps/web/src/components/settings/EasDeviceHostEditor.tsx renamed
+3 -118
@@ -3,17 +3,13 @@ import { useId, useRef, useState } from "react";
3 import * as Cause from "effect/Cause";
4 import * as Option from "effect/Option";
5 import {
6 - AuthSettingsWriteScope,
6 type DeviceEasAccount,
7 type EasDeviceHostConfig,
8 type EnvironmentId,
9 } from "@t3tools/contracts";
11 -import { CloudIcon, PlusIcon, XIcon } from "lucide-react";
10 +import { XIcon } from "lucide-react";
11
13 -import { randomUUID } from "../../lib/utils";
12 import { deviceEasAccountCheck, deviceEnvironment } from "../../state/device";
15 -import { serverEnvironment } from "../../state/server";
16 -import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
13 import { useAtomCommand } from "../../state/use-atom-command";
14 import { Button } from "../ui/button";
15 import {
@@ -28,16 +24,8 @@ import {
24 import { Input } from "../ui/input";
25 import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
26 import { Spinner } from "../ui/spinner";
31 -import { toastManager } from "../ui/toast";
32 -import {
33 - easSessionLimits,
34 - newEasDeviceHost,
35 - parseEasDeviceHostDraft,
36 - updateEasDeviceHosts,
37 -} from "./easDeviceHostsSettings.logic";
27 +import { parseEasDeviceHostDraft } from "./easDeviceHostsSettings.logic";
28 import { SecretInput } from "./SecretInput";
39 -import { useSettingsScope } from "./SettingsScopeContext";
40 -import { SettingsRow } from "./settingsLayout";
29
30 const FROM_THREAD_PROJECT = "thread-project";
31
@@ -52,116 +40,13 @@ const failureMessage = (cause: Cause.Cause<unknown>) => {
40 return error instanceof Error ? error.message : String(error);
41 };
42
55 -/** EAS hosts belong to one environment: its server holds the Expo credential and runs the sessions. */
56 -export function EasDeviceHostsSettings(props: { environmentId: EnvironmentId | null }) {
57 - const { scope, connectedEnvironments } = useSettingsScope();
58 - const canConfigure = useEnvironmentScope(props.environmentId, AuthSettingsWriteScope);
59 - const projectScope = scope.kind === "project" || scope.kind === "checkout";
60 - const update = useAtomCommand(serverEnvironment.updateSettings, { reportFailure: false });
61 - const environment = connectedEnvironments.find(
62 - (candidate) => candidate.environmentId === props.environmentId,
63 - );
64 - const hosts = environment?.serverConfig?.settings.easDeviceHosts ?? [];
65 - const [editing, setEditing] = useState<{ host: EasDeviceHostConfig; isNew: boolean } | null>(
66 - null,
67 - );
68 - const [busy, setBusy] = useState(false);
69 - const disabled = !canConfigure || projectScope || busy || !props.environmentId;
70 -
71 - const save = async (host: EasDeviceHostConfig, remove: boolean) => {
72 - if (!props.environmentId || !readEnvironmentScope(props.environmentId, AuthSettingsWriteScope))
73 - return;
74 - setBusy(true);
75 - const result = await update({
76 - environmentId: props.environmentId,
77 - input: { patch: { easDeviceHosts: updateEasDeviceHosts(hosts, host, remove) } },
78 - });
79 - setBusy(false);
80 - if (result._tag === "Success") setEditing(null);
81 - else
82 - toastManager.add({
83 - type: "error",
84 - title: remove ? "EAS host not removed" : "EAS host not saved",
85 - description: failureMessage(result.cause),
86 - });
87 - };
88 -
89 - return (
90 - <SettingsRow
91 - id="eas-device-hosts"
92 - title="EAS Simulator"
93 - serverScoped
94 - settingKeys={["easDeviceHosts"]}
95 - description="Run iOS Simulators in Expo's cloud from this environment. Sessions bill the Expo account until they stop, so each host limits how many run and for how long. Editing or removing a host stops its running sessions."
96 - control={
97 - <Button
98 - size="sm"
99 - variant="outline"
100 - disabled={disabled || editing !== null}
101 - onClick={() => setEditing({ host: newEasDeviceHost(randomUUID()), isNew: true })}
102 - >
103 - <PlusIcon className="size-3.5" /> Add EAS host
104 - </Button>
105 - }
106 - >
107 - <div className="pt-3 pb-2">
108 - {hosts.length === 0 ? (
109 - <p className="text-sm text-muted-foreground">No EAS hosts.</p>
110 - ) : (
111 - <ul className="divide-y divide-border/40">
112 - {hosts.map((host) => (
113 - <li key={host.id} className="flex items-center justify-between gap-3 py-2.5 text-sm">
114 - <div className="min-w-0">
115 - <p className="flex items-center gap-1.5 truncate font-medium">
116 - <CloudIcon className="size-3.5 shrink-0" /> {host.label}
117 - </p>
118 - <p className="truncate text-xs text-muted-foreground">{easSessionLimits(host)}</p>
119 - </div>
120 - <div className="flex shrink-0 gap-1">
121 - <Button
122 - size="sm"
123 - variant="ghost"
124 - disabled={disabled}
125 - onClick={() => setEditing({ host, isNew: false })}
126 - >
127 - Edit
128 - </Button>
129 - <Button
130 - size="sm"
131 - variant="ghost-destructive"
132 - disabled={disabled}
133 - onClick={() => void save(host, true)}
134 - >
135 - Remove
136 - </Button>
137 - </div>
138 - </li>
139 - ))}
140 - </ul>
141 - )}
142 - {editing && props.environmentId ? (
143 - <EasDeviceHostEditor
144 - key={editing.host.id}
145 - environmentId={props.environmentId}
146 - host={editing.host}
147 - isNew={editing.isNew}
148 - busy={busy}
149 - onSave={(host) => void save(host, false)}
150 - onClose={() => setEditing(null)}
151 - />
152 - ) : null}
153 - </div>
154 - </SettingsRow>
155 - );
156 -}
157 -
43 type AccountCheck =
44 | { status: "idle" }
45 | { status: "checking" }
46 | { status: "signed-in"; account: DeviceEasAccount }
47 | { status: "failed"; error: string };
48
164 -function EasDeviceHostEditor(props: {
49 +export function EasDeviceHostEditor(props: {
50 environmentId: EnvironmentId;
51 host: EasDeviceHostConfig;
52 isNew: boolean;
apps/web/src/components/settings/IntegrationsSettings.tsx
+29 -82
@@ -2,8 +2,7 @@ import { DeviceHostUpdates } from "../device/DeviceHostUpdates";
2 import { DeviceToolVersions } from "../device/DeviceToolVersions";
3 import { useScopedSettings, useUpdateScopedSettings } from "./useScopedSettings";
4 import { ScopedSwitch } from "./ScopedSwitch";
5 -import { DeviceHostsSettings } from "./DeviceHostsSettings";
6 -import { EasDeviceHostsSettings } from "./EasDeviceHostsSettings";
5 +import { DeviceSourcesSettings } from "./DeviceSourcesSettings";
6 import {
7 AuthSettingsWriteScope,
8 BrowserImportFailureReason,
@@ -42,7 +41,6 @@ import { MoreVertical, Plus as PlusIcon } from "lucide-react";
41 import { useRef, useState } from "react";
42
43 import { ScreenRotationIcon } from "~/browser/ScreenRotationIcon";
45 -import { AnimatedHeight } from "~/components/AnimatedHeight";
44 import { resolveEnvironmentOptionLabel } from "~/components/BranchToolbar.logic";
45 import { previewBridge } from "~/components/preview/previewBridge";
46 import { cn, randomUUID } from "~/lib/utils";
@@ -58,11 +56,6 @@ import {
56 AgentDeviceSetupStatus,
57 DeviceHubSetupStatus,
58 deviceHubReadiness,
61 - PlatformStatus,
62 - platformSetupStatus,
63 - deviceHubDescription,
64 - agentDeviceDescription,
65 - DeviceHostDiagnostics,
59 } from "~/components/device/DeviceSetup";
60 import { isElectron } from "../../env";
61
@@ -797,15 +790,23 @@ function DeviceIntegrationSettings() {
790 const connected = selected?.connection.phase === "connected" && selected.serverConfig !== null;
791 const environmentId = connected ? selected.environmentId : null;
792
793 + const { state } = useDeviceState(environmentId);
794 +
795 return (
801 - <SettingsSection id="devices" title="Devices">
802 - <DeviceIntegrationControls
803 - key={`${environmentId}:${JSON.stringify(search)}`}
804 - environmentId={environmentId}
805 - enabled={settings.enableDeviceSupport}
806 - agentAccessEnabled={settings.enableAgentDeviceAccess}
796 + <>
797 + <SettingsSection id="devices" title="Devices">
798 + <DeviceIntegrationControls
799 + key={`${environmentId}:${JSON.stringify(search)}`}
800 + environmentId={environmentId}
801 + enabled={settings.enableDeviceSupport}
802 + agentAccessEnabled={settings.enableAgentDeviceAccess}
803 + />
804 + </SettingsSection>
805 + <DeviceSourcesSettings
806 + supportsEas={state.supportsEasHosts === true}
807 + supportsSimlock={state.supportsSimlockHosts === true}
808 />
808 - </SettingsSection>
809 + </>
810 );
811 }
812
@@ -831,20 +832,7 @@ function DeviceIntegrationControls({
832 const [pending, setPending] = useState<
833 "hub" | "check" | "agent" | "update-hub" | "update-agent" | null
834 >(null);
834 - const { ready: hubReady, busy } = deviceHubReadiness(state);
835 - const localPlatformsUnavailable = state.hosts.some(
836 - (host) => host.kind === "local" && !host.platforms.some((platform) => platform.available),
837 - );
838 - const [platformsRevealed, setPlatformsRevealed] = useState(false);
839 - if (platformsRevealed && !enabled) setPlatformsRevealed(false);
840 - if (
841 - enabled &&
842 - !platformsRevealed &&
843 - (hubReady || localPlatformsUnavailable) &&
844 - pending !== "hub"
845 - ) {
846 - setPlatformsRevealed(true);
847 - }
835 + const { busy } = deviceHubReadiness(state);
836
837 const update = async (
838 kind: NonNullable<typeof pending>,
@@ -941,14 +929,18 @@ function DeviceIntegrationControls({
929 {...searchableSetting("device-hub")}
930 serverScoped
931 settingKeys={["enableDeviceSupport"]}
944 - description={deviceHubDescription}
945 - control={
932 + description={
933 <>
934 + Open simulators and emulators in the Device panel. Hub:{" "}
935 <DeviceToolVersions
936 action={versionActions("hub")}
937 kind="hub"
938 tools={state.hosts.find((host) => host.kind === "local")?.tools}
939 />
940 + </>
941 + }
942 + control={
943 + <>
944 {pending === "hub" ? <DeviceHubSetupStatus state={state} pending compact /> : null}
945 <ScopedSwitch
946 settingKeys={["enableDeviceSupport"]}
@@ -972,65 +964,22 @@ function DeviceIntegrationControls({
964 </>
965 }
966 />
975 - <AnimatedHeight>
976 - {platformsRevealed ? (
977 - <SettingsRow
978 - {...searchableSetting("device-platform-support")}
979 - description={
980 - connectedEnvironments.length > 1
981 - ? `Status for ${connectedEnvironments.find((environment) => environment.environmentId === environmentId)?.label}. Select an environment to inspect its simulator support.`
982 - : undefined
983 - }
984 - status={
985 - <div className="space-y-2">
986 - <div className="flex flex-wrap gap-x-5 gap-y-2">
987 - <PlatformStatus
988 - compact
989 - platform="iOS"
990 - status={platformSetupStatus(state, "ios")}
991 - />
992 - <PlatformStatus
993 - compact
994 - platform="Android"
995 - status={platformSetupStatus(state, "android")}
996 - />
997 - </div>
998 - {/* Remote hosts report their own warnings in the device host list below. */}
999 - <DeviceHostDiagnostics
1000 - hosts={state.hosts.filter((host) => host.kind === "local")}
1001 - hostStatuses={state.hostStatuses}
1002 - />
1003 - </div>
1004 - }
1005 - control={
1006 - <Button
1007 - size="sm"
1008 - variant="outline"
1009 - disabled={!environmentId || !enabled || busy || pending !== null}
1010 - onClick={() => {
1011 - if (!environmentId) return;
1012 - setPending("check");
1013 - void list({ environmentId, input: {} }).finally(() => setPending(null));
1014 - }}
1015 - >
1016 - {pending === "check" ? "Checking…" : "Refresh"}
1017 - </Button>
1018 - }
1019 - />
1020 - ) : null}
1021 - </AnimatedHeight>
967 <SettingsRow
968 {...searchableSetting("agent-device-access")}
969 serverScoped
970 settingKeys={["enableAgentDeviceAccess"]}
1026 - description={agentDeviceDescription}
1027 - control={
971 + description={
972 <>
973 + New agent sessions can open and drive these devices. agent-device:{" "}
974 <DeviceToolVersions
975 action={versionActions("agent")}
976 kind="agent"
977 tools={state.hosts.find((host) => host.kind === "local")?.tools}
978 />
979 + </>
980 + }
981 + control={
982 + <>
983 {pending === "agent" ? <AgentDeviceSetupStatus state={state} pending compact /> : null}
984 <ScopedSwitch
985 settingKeys={["enableAgentDeviceAccess"]}
@@ -1057,8 +1006,6 @@ function DeviceIntegrationControls({
1006 environmentId={environmentId}
1007 />
1008 ) : null}
1060 - <DeviceHostsSettings environmentId={environmentId} />
1061 - {state.supportsEasHosts ? <EasDeviceHostsSettings environmentId={environmentId} /> : null}
1009 </>
1010 );
1011 }
apps/web/src/components/settings/LabsSettingsPanel.tsx
+41
@@ -21,6 +21,7 @@ export function LabsSettingsPanel() {
21 {/* Clerk is only mounted when this build has T3 Connect. */}
22 {hasCloudPublicConfig() ? <GuestLinksRowWithSignIn /> : <GuestLinksRow />}
23 <LinkedEnvironmentsRow />
24 + <SimlockHostsRow />
25 </SettingsSection>
26 <LegacyFeaturesSection />
27 </SettingsPageContainer>
@@ -148,3 +149,43 @@ function LinkedEnvironmentsRow() {
149 />
150 );
151 }
152 +
153 +function SimlockHostsRow() {
154 + const settings = useScopedSettings();
155 + const updateSettings = useUpdateScopedSettings();
156 + return (
157 + <SettingsRow
158 + serverScoped
159 + {...searchableSetting("simlock-hosts")}
160 + settingKeys={["simlockDeviceHostsEnabled"]}
161 + description={
162 + <>
163 + Let the Device panel lease simulators and emulators from your own{" "}
164 + <a
165 + href="https://incubator.callstack.com/simlock/"
166 + target="_blank"
167 + rel="noreferrer"
168 + className="underline underline-offset-2"
169 + >
170 + Simlock
171 + </a>{" "}
172 + pool, added in{" "}
173 + <Link to="/settings/devices" className="underline underline-offset-2">
174 + Devices
175 + </Link>
176 + . An alpha that may change or break. T3 Code never installs Simlock.
177 + </>
178 + }
179 + control={
180 + <ScopedSwitch
181 + settingKeys={["simlockDeviceHostsEnabled"]}
182 + checked={settings.simlockDeviceHostsEnabled}
183 + onCheckedChange={(checked) =>
184 + updateSettings({ simlockDeviceHostsEnabled: Boolean(checked) })
185 + }
186 + aria-label="Simlock device hosts"
187 + />
188 + }
189 + />
190 + );
191 +}
apps/web/src/components/settings/SimlockDeviceHostEditor.tsx new
+224
@@ -0,0 +1,224 @@
1 +import { useId, useState, type ReactNode } from "react";
2 +import type { EnvironmentId, SimlockDeviceHostConfig } from "@t3tools/contracts";
3 +import { XIcon } from "lucide-react";
4 +
5 +import { Button } from "../ui/button";
6 +import {
7 + Dialog,
8 + DialogDescription,
9 + DialogFooter,
10 + DialogHeader,
11 + DialogPanel,
12 + DialogPopup,
13 + DialogTitle,
14 +} from "../ui/dialog";
15 +import { Input } from "../ui/input";
16 +import { Spinner } from "../ui/spinner";
17 +import { SecretInput } from "./SecretInput";
18 +import {
19 + planSimlockDeviceHostSave,
20 + type SimlockHostEnvironment,
21 + type SimlockTokenEntry,
22 +} from "./simlockDeviceHostsSettings.logic";
23 +
24 +/** Shared fields once, then one agent token per environment: Simlock counts leases per token. */
25 +export function SimlockDeviceHostEditor(props: {
26 + host: SimlockDeviceHostConfig;
27 + isNew: boolean;
28 + environments: ReadonlyArray<SimlockHostEnvironment>;
29 + busy: boolean;
30 + onSave: (
31 + host: SimlockDeviceHostConfig,
32 + tokens: ReadonlyMap<EnvironmentId, SimlockTokenEntry>,
33 + ) => void;
34 + onClose: () => void;
35 +}) {
36 + const [draft, setDraft] = useState(props.host);
37 + const savedToken = (environment: SimlockHostEnvironment) =>
38 + environment.hosts.some((host) => host.id === props.host.id && host.agentToken !== "");
39 + const [tokens, setTokens] = useState<ReadonlyMap<EnvironmentId, SimlockTokenEntry>>(
40 + () =>
41 + new Map(
42 + props.environments.map((environment) => [
43 + environment.environmentId,
44 + savedToken(environment) ? { kind: "saved" } : { kind: "cleared" },
45 + ]),
46 + ),
47 + );
48 + const next: SimlockDeviceHostConfig = {
49 + ...draft,
50 + label: draft.label.trim(),
51 + gatewayUrl: draft.gatewayUrl.trim(),
52 + };
53 + const plan = planSimlockDeviceHostSave(props.environments, next, tokens);
54 + const problem = "problem" in plan ? plan.problem : null;
55 + const several = props.environments.length > 1;
56 +
57 + const limit = (
58 + field: "maxLeases" | "maxLeaseMinutes",
59 + label: string,
60 + min: number,
61 + max: number,
62 + ) => (
63 + <label className="block space-y-1.5">
64 + <span>{label}</span>
65 + <Input
66 + type="number"
67 + min={min}
68 + max={max}
69 + value={draft[field]}
70 + disabled={props.busy}
71 + onChange={(event) => {
72 + const value = Number(event.target.value);
73 + setDraft((current) => ({ ...current, [field]: value }));
74 + }}
75 + />
76 + </label>
77 + );
78 +
79 + return (
80 + <Dialog
81 + open
82 + onOpenChange={(open) => {
83 + if (!open && !props.busy) props.onClose();
84 + }}
85 + >
86 + <DialogPopup showCloseButton={!props.busy}>
87 + <form
88 + className="flex min-h-0 flex-col"
89 + onSubmit={(event) => {
90 + event.preventDefault();
91 + if (problem === null && !props.busy) props.onSave(next, tokens);
92 + }}
93 + >
94 + <DialogHeader>
95 + <DialogTitle>{props.isNew ? "Add Simlock host" : "Edit Simlock host"}</DialogTitle>
96 + <DialogDescription>
97 + {several
98 + ? "Each selected environment's server leases devices from your Simlock gateway with its own agent token, and releases them when they close."
99 + : "The environment's server leases devices from your Simlock gateway and releases them when they close."}
100 + </DialogDescription>
101 + </DialogHeader>
102 + <DialogPanel>
103 + <label className="block space-y-1.5 text-sm">
104 + <span>Name</span>
105 + <Input
106 + autoFocus
107 + required
108 + value={draft.label}
109 + disabled={props.busy}
110 + onChange={(event) => {
111 + const label = event.target.value;
112 + setDraft((current) => ({ ...current, label }));
113 + }}
114 + />
115 + </label>
116 + <label className="block space-y-1.5 text-sm">
117 + <span>Gateway URL</span>
118 + <Input
119 + required
120 + type="url"
121 + placeholder="https://gateway.example.ts.net:4700"
122 + value={draft.gatewayUrl}
123 + disabled={props.busy}
124 + onChange={(event) => {
125 + const gatewayUrl = event.target.value;
126 + setDraft((current) => ({ ...current, gatewayUrl }));
127 + }}
128 + />
129 + </label>
130 + <div className="space-y-3">
131 + {props.environments.map((environment) => (
132 + <SimlockTokenField
133 + key={environment.environmentId}
134 + label={several ? `Agent token · ${environment.label}` : "Agent token"}
135 + token={tokens.get(environment.environmentId) ?? { kind: "cleared" }}
136 + hasSaved={savedToken(environment)}
137 + busy={props.busy}
138 + onChange={(token) =>
139 + setTokens((current) => new Map(current).set(environment.environmentId, token))
140 + }
141 + />
142 + ))}
143 + <p className="text-xs text-muted-foreground">
144 + Leases, drives, and streams devices. Create one{several ? " per environment" : ""}{" "}
145 + with <code>simlock --gateway token create --role agent</code>.
146 + </p>
147 + </div>
148 + <div className="grid grid-cols-2 gap-3 text-sm">
149 + {limit("maxLeases", "Devices at once", 1, 20)}
150 + {limit("maxLeaseMinutes", "Lease minutes", 5, 240)}
151 + </div>
152 + <p className="text-xs text-muted-foreground">
153 + A lease ends after the lease minutes even while in use.
154 + {props.isNew ? null : " Saving restarts this host, which releases its devices."}
155 + </p>
156 + {problem === null || !draft.gatewayUrl ? null : (
157 + <p className="text-xs text-destructive" role="alert">
158 + {problem}
159 + </p>
160 + )}
161 + </DialogPanel>
162 + <DialogFooter>
163 + <Button type="button" variant="ghost" disabled={props.busy} onClick={props.onClose}>
164 + Cancel
165 + </Button>
166 + <Button type="submit" disabled={props.busy || problem !== null}>
167 + {props.busy ? <Spinner size="xs" /> : null} Save host
168 + </Button>
169 + </DialogFooter>
170 + </form>
171 + </DialogPopup>
172 + </Dialog>
173 + );
174 +}
175 +
176 +function SimlockTokenField(props: {
177 + label: ReactNode;
178 + token: SimlockTokenEntry;
179 + hasSaved: boolean;
180 + busy: boolean;
181 + onChange: (token: SimlockTokenEntry) => void;
182 +}) {
183 + const id = useId();
184 + return (
185 + <div className="space-y-1.5 text-sm">
186 + <label htmlFor={id} className="block">
187 + {props.label}
188 + </label>
189 + <div className="flex items-center gap-2">
190 + <SecretInput
191 + id={id}
192 + className="min-w-0 flex-1"
193 + configured={props.token.kind === "saved"}
194 + value={props.token.kind === "new" ? props.token.value : ""}
195 + disabled={props.busy}
196 + onChange={(event) => {
197 + const value = event.target.value;
198 + // Emptying the field is not clearing the saved token; the Clear
199 + // button is, so a saved token comes back here.
200 + props.onChange(
201 + value
202 + ? { kind: "new", value }
203 + : props.hasSaved
204 + ? { kind: "saved" }
205 + : { kind: "cleared" },
206 + );
207 + }}
208 + />
209 + {props.token.kind !== "cleared" ? (
210 + <Button
211 + type="button"
212 + size="icon-sm"
213 + variant="ghost-destructive"
214 + aria-label="Clear agent token"
215 + disabled={props.busy}
216 + onClick={() => props.onChange({ kind: "cleared" })}
217 + >
218 + <XIcon className="size-3.5" />
219 + </Button>
220 + ) : null}
221 + </div>
222 + </div>
223 + );
224 +}
apps/web/src/components/settings/easDeviceHostsSettings.logic.test.ts
+16 -1
@@ -1,7 +1,11 @@
1 import { describe, expect, it } from "vite-plus/test";
2 import * as Option from "effect/Option";
3
4 -import { newEasDeviceHost, parseEasDeviceHostDraft } from "./easDeviceHostsSettings.logic";
4 +import {
5 + newEasDeviceHost,
6 + parseEasDeviceHostDraft,
7 + updateEasDeviceHosts,
8 +} from "./easDeviceHostsSettings.logic";
9
10 describe("EAS device host settings", () => {
11 it("rejects limits EAS does not allow", () => {
@@ -18,4 +22,15 @@ describe("EAS device host settings", () => {
22 true,
23 );
24 });
25 +
26 + it("keeps each environment's own token when a save leaves the token unchanged", () => {
27 + const edited = { ...newEasDeviceHost("eas"), label: "Renamed", accessToken: "" };
28 + const elsewhere = { ...newEasDeviceHost("eas"), accessToken: "••••••" };
29 + expect(updateEasDeviceHosts([elsewhere], edited, false, true)).toEqual([
30 + { ...edited, accessToken: "••••••" },
31 + ]);
32 + expect(updateEasDeviceHosts([], { ...edited, accessToken: "••••••" }, false, true)).toEqual([
33 + { ...edited, accessToken: "" },
34 + ]);
35 + });
36 });
apps/web/src/components/settings/easDeviceHostsSettings.logic.ts
+10 -3
@@ -17,15 +17,22 @@ export const newEasDeviceHost = (id: string): EasDeviceHostConfigType => ({
17 });
18
19 /** Adds, replaces, or removes one EAS host. */
20 +/**
21 + * With `keepToken`, the environment keeps the token it holds: a saved token arrives redacted, and
22 + * one environment's token says nothing about another's. One new to the host uses its own Expo login.
23 + */
24 export function updateEasDeviceHosts(
25 hosts: ReadonlyArray<EasDeviceHostConfigType>,
26 host: EasDeviceHostConfigType,
27 remove: boolean,
28 + keepToken = false,
29 ): ReadonlyArray<EasDeviceHostConfigType> {
30 if (remove) return hosts.filter((candidate) => candidate.id !== host.id);
26 - return hosts.some((candidate) => candidate.id === host.id)
27 - ? hosts.map((candidate) => (candidate.id === host.id ? host : candidate))
28 - : [...hosts, host];
31 + const existing = hosts.find((candidate) => candidate.id === host.id);
32 + const next = keepToken ? { ...host, accessToken: existing?.accessToken ?? "" } : host;
33 + return existing
34 + ? hosts.map((candidate) => (candidate.id === host.id ? next : candidate))
35 + : [...hosts, next];
36 }
37
38 export function easSessionLimits(host: EasDeviceHostConfigType) {
apps/web/src/components/settings/settingsSearch.ts
+18 -9
@@ -451,6 +451,13 @@ export const SETTINGS_SEARCH_ITEMS = [
451 scope: "environment",
452 searchTerms: ["beta link another machine vps peer agents work there delegate"],
453 },
454 + {
455 + id: "simlock-hosts",
456 + title: "Simlock device hosts (alpha)",
457 + to: "/settings/labs",
458 + scope: "environment",
459 + searchTerms: ["beta alpha simlock callstack simulator emulator ios android pool lease gateway"],
460 + },
461 {
462 id: "auto-settle-inactive-threads",
463 title: "Auto-settle inactive threads",
@@ -806,31 +813,33 @@ export const SETTINGS_SEARCH_ITEMS = [
813 searchTerms: ["allow disable enable open drive preview tools sessions project override"],
814 },
815 {
809 - id: "device-hosts",
810 - title: "Device hosts",
816 + id: "device-sources",
817 + title: "Device sources",
818 to: "/settings/devices",
812 - searchTerms: ["ssh remote simulator emulator ios android mac mini identity key connection"],
819 + searchTerms: [
820 + "device hosts ssh remote mac mini identity key connection eas expo cloud simlock pool gateway local simulators",
821 + ],
822 },
823 {
824 id: "agent-device-access",
816 - title: "Agent device access",
825 + title: "Agents can use devices",
826 to: "/settings/devices",
827 targetId: "devices",
828 searchTerms: ["allow simulator emulator ios android drive tools sessions"],
829 },
830 {
831 id: "device-hub",
823 - title: "Device hub",
832 + title: "Use devices",
833 to: "/settings/devices",
834 targetId: "devices",
826 - searchTerms: ["simulator emulator ios android install start"],
835 + searchTerms: ["device hub simulator emulator ios android install start version"],
836 },
837 {
838 id: "device-platform-support",
830 - title: "Simulator support",
839 + title: "Local simulators",
840 to: "/settings/devices",
832 - targetId: "devices",
833 - searchTerms: ["xcode android studio sdk avd runtime"],
841 + targetId: "device-sources",
842 + searchTerms: ["simulator support xcode android studio sdk avd runtime"],
843 },
844 {
845 id: "browser-profiles",
apps/web/src/components/settings/simlockDeviceHostsSettings.logic.test.ts new
+69
@@ -0,0 +1,69 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import type { EnvironmentId } from "@t3tools/contracts";
4 +
5 +import {
6 + newSimlockDeviceHost,
7 + planSimlockDeviceHostSave,
8 + simlockDeviceHostProblem,
9 + updateSimlockDeviceHosts,
10 +} from "./simlockDeviceHostsSettings.logic";
11 +
12 +const host = {
13 + ...newSimlockDeviceHost("simlock"),
14 + gatewayUrl: "https://gateway.example.ts.net:4700",
15 + agentToken: "agent",
16 +};
17 +
18 +describe("Simlock device host settings", () => {
19 + it("names what keeps a draft from saving", () => {
20 + expect(simlockDeviceHostProblem(host)).toBeNull();
21 + expect(simlockDeviceHostProblem({ ...host, label: " " })).toBe("Give the host a label.");
22 + expect(simlockDeviceHostProblem({ ...host, gatewayUrl: "gateway:4700" })).toMatch(/origin/);
23 + expect(
24 + simlockDeviceHostProblem({ ...host, gatewayUrl: "https://gateway.example/api" }),
25 + ).toMatch(/origin/);
26 + expect(simlockDeviceHostProblem({ ...host, maxLeases: 21 })).toMatch(/ranges/);
27 + expect(simlockDeviceHostProblem({ ...host, maxLeaseMinutes: 4 })).toMatch(/ranges/);
28 + });
29 +
30 + it("adds, replaces, and removes one host", () => {
31 + const other = { ...host, id: "other", label: "Other" };
32 + const added = updateSimlockDeviceHosts([other], host, false);
33 + expect(added.map((candidate) => candidate.id)).toEqual(["other", "simlock"]);
34 + const renamed = updateSimlockDeviceHosts(added, { ...host, label: "Renamed" }, false);
35 + expect(renamed.map((candidate) => candidate.label)).toEqual(["Other", "Renamed"]);
36 + expect(updateSimlockDeviceHosts(renamed, host, true)).toEqual([other]);
37 + });
38 +
39 + it("saves the shared fields everywhere and each environment's own token", () => {
40 + const mbp = "mbp" as EnvironmentId;
41 + const cups = "cups" as EnvironmentId;
42 + const environments = [
43 + { environmentId: mbp, label: "mbp", hosts: [{ ...host, agentToken: "<redacted>" }] },
44 + { environmentId: cups, label: "cups", hosts: [] },
45 + ];
46 + const draft = { ...host, label: "Pool", agentToken: "" };
47 +
48 + expect(
49 + planSimlockDeviceHostSave(environments, draft, new Map([[mbp, { kind: "saved" }]])),
50 + ).toEqual({
51 + problem: "Add an agent token for cups.",
52 + });
53 + expect(
54 + planSimlockDeviceHostSave(
55 + environments,
56 + draft,
57 + new Map([
58 + [mbp, { kind: "saved" }],
59 + [cups, { kind: "new", value: " cups-token " }],
60 + ]),
61 + ),
62 + ).toEqual({
63 + patches: [
64 + { environmentId: mbp, hosts: [{ ...draft, agentToken: "<redacted>" }] },
65 + { environmentId: cups, hosts: [{ ...draft, agentToken: "cups-token" }] },
66 + ],
67 + });
68 + });
69 +});
apps/web/src/components/settings/simlockDeviceHostsSettings.logic.ts new
+94
@@ -0,0 +1,94 @@
1 +import {
2 + SimlockDeviceHostConfig,
3 + type EnvironmentId,
4 + type SimlockDeviceHostConfig as SimlockDeviceHostConfigType,
5 +} from "@t3tools/contracts";
6 +import * as Option from "effect/Option";
7 +import * as Schema from "effect/Schema";
8 +
9 +const parseSimlockDeviceHostDraft = Schema.decodeUnknownOption(SimlockDeviceHostConfig);
10 +
11 +export const newSimlockDeviceHost = (id: string): SimlockDeviceHostConfigType => ({
12 + kind: "simlock",
13 + id,
14 + label: "Simlock",
15 + gatewayUrl: "",
16 + agentToken: "",
17 + maxLeases: 2,
18 + maxLeaseMinutes: 60,
19 +});
20 +
21 +/** Adds, replaces, or removes one Simlock host. */
22 +export function updateSimlockDeviceHosts(
23 + hosts: ReadonlyArray<SimlockDeviceHostConfigType>,
24 + host: SimlockDeviceHostConfigType,
25 + remove: boolean,
26 +): ReadonlyArray<SimlockDeviceHostConfigType> {
27 + if (remove) return hosts.filter((candidate) => candidate.id !== host.id);
28 + return hosts.some((candidate) => candidate.id === host.id)
29 + ? hosts.map((candidate) => (candidate.id === host.id ? host : candidate))
30 + : [...hosts, host];
31 +}
32 +
33 +/** Why the shared fields keep a draft from saving, or null; tokens are checked per environment. */
34 +export function simlockDeviceHostProblem(host: SimlockDeviceHostConfigType): string | null {
35 + const withToken = { ...host, agentToken: "token" };
36 + if (Option.isSome(parseSimlockDeviceHostDraft(withToken))) return null;
37 + if (!host.label.trim()) return "Give the host a label.";
38 + // With in-range limits, a draft that still fails has a bad gateway URL.
39 + return Option.isNone(
40 + parseSimlockDeviceHostDraft({ ...withToken, maxLeases: 1, maxLeaseMinutes: 60 }),
41 + )
42 + ? "Enter the gateway's origin, such as https://gateway.example.ts.net:4700."
43 + : "Keep the limits within the ranges shown.";
44 +}
45 +
46 +export function simlockLeaseLimits(host: SimlockDeviceHostConfigType) {
47 + const devices = host.maxLeases === 1 ? "1 device" : `${host.maxLeases} devices`;
48 + return `Up to ${devices} at once, each released after ${host.maxLeaseMinutes} min`;
49 +}
50 +
51 +export interface SimlockHostEnvironment {
52 + readonly environmentId: EnvironmentId;
53 + readonly label: string;
54 + readonly hosts: ReadonlyArray<SimlockDeviceHostConfigType>;
55 +}
56 +
57 +/** A token field: the environment's saved token, a replacement, or none. */
58 +export type SimlockTokenEntry =
59 + | { kind: "saved" }
60 + | { kind: "new"; value: string }
61 + | { kind: "cleared" };
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.
66 + */
67 +export function planSimlockDeviceHostSave(
68 + environments: ReadonlyArray<SimlockHostEnvironment>,
69 + draft: SimlockDeviceHostConfigType,
70 + tokens: ReadonlyMap<EnvironmentId, SimlockTokenEntry>,
71 +):
72 + | { readonly problem: string }
73 + | {
74 + readonly patches: ReadonlyArray<{
75 + environmentId: EnvironmentId;
76 + hosts: ReadonlyArray<SimlockDeviceHostConfigType>;
77 + }>;
78 + } {
79 + const shared = simlockDeviceHostProblem(draft);
80 + if (shared) return { problem: shared };
81 + const patches = [];
82 + for (const environment of environments) {
83 + const saved = environment.hosts.find((host) => host.id === draft.id)?.agentToken ?? "";
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}.` };
88 + patches.push({
89 + environmentId: environment.environmentId,
90 + hosts: updateSimlockDeviceHosts(environment.hosts, { ...draft, agentToken }, false),
91 + });
92 + }
93 + return { patches };
94 +}
docs/internals/devices.md
+21
@@ -44,6 +44,27 @@ clients never hold it. Agent config files are written per device
44 device before targeting it. Device settings run `simctl` on the simulator's
45 machine, which EAS does not expose, so they are unavailable there.
46
47 +## Simlock hosts lease through the agent-device front
48 +
49 +A [Simlock host](../../apps/server/src/device/SimlockDeviceHost.ts) (alpha) opens a
50 +device by running T3's own agent-device CLI against the gateway's agent-device
51 +front (`connect proxy`, then `open`), not with Simlock's lease HTTP API:
52 +agent-device cannot adopt a lease it did not allocate. The lease is bound to
53 +that one agent-device session and to the directory `open` ran in, so
54 +`agentEndpoint` hands every thread the same session, a `stateDir` holding its
55 +connection record, and no `--udid`/`--serial` (the gateway refuses selectors).
56 +Installs work only from that directory; `device_open` names it.
57 +
58 +Simlock serves a lease's screen and input to its holder in serve-sim's formats
59 +on both platforms: AVCC envelopes at `/v1/leases/<id>/stream` and serve-sim's
60 +input messages at `/v1/leases/<id>/input`, both with the agent token. Clients
61 +therefore treat a Simlock Android lease like iOS (`serveSimOnly` in the stream
62 +client), and `upstream` maps serve-sim's `stream.avcc` and `helper/ws` paths to
63 +those routes. Simlock has no MJPEG, screenshot, or host command routes, so the
64 +panel offers only input there.
65 +Leases are renewed while tracked and released at the host's age limit; one a
66 +crashed server left behind ends on its own one TTL later, so there is no ledger.
67 +
68 ## The hub is never exposed
69
70 serve-sim has a shell-exec route whose token is readable from its own
docs/user/devices.md
+43 -6
@@ -22,7 +22,7 @@ Choose **Float device over chat** in the toolbar to keep watching and tapping th
22 device in a small window while the right panel shows something else; drag the
23 window by its handle, resize it from any edge, and use **Open in right panel**
24 to bring it back.
25 -Turn off the device hub in **Settings → Devices** to stop the
25 +Turn off **Use devices** in **Settings → Devices** to stop the
26 helper processes; simulators and emulators keep running until you power them
27 off.
28
@@ -80,12 +80,12 @@ viewer stops streaming and leaves the device available to the agent. Device
80 activity also appears in the thread timeline.
81
82 Agents drive the device through the `agent-device` command line. T3
83 -Code installs and starts it only after **Agent device access** is enabled. iOS
83 +Code installs and starts it only after **Agents can use devices** is on. iOS
84 taps build a small test runner on first use, which takes a couple of minutes
85 once per server. Restart an existing agent session after granting access so it
86 receives the device CLI environment.
87
88 -To keep agents away from simulators, turn off **Agent device access** in
88 +To keep agents away from simulators, turn off **Agents can use devices** in
89 **Settings → Devices**. This hides the device tools from agents
90 started from then on; your own Device panel is unaffected.
91
@@ -99,12 +99,12 @@ still-image stream and Android cannot show video.
99 ## SSH device hosts
100
101 In Settings → Devices, choose the environments that should use
102 -the host and add it under **Device hosts**. Enter an SSH alias or `user@host`, with
102 +the host and choose **Add source → Machine over SSH**. Enter an SSH alias or `user@host`, with
103 an optional identity file and port. These resolve on the environment server,
104 so use the SSH configuration and keys available there. Password prompts are
105 not supported.
106
107 -**Test connection** checks SSH, Node, npm, and platform tools without installing
107 +**Test connection**, in the host's menu, checks SSH, Node, npm, and platform tools without installing
108 anything, with a result for each selected environment. Targets that resolve to
109 the environment’s own machine are skipped, since its devices are already local.
110 The first device listing installs pinned device tools on the host.
@@ -123,8 +123,45 @@ installation, and connectivity to development servers such as Metro separately.
123 A simulator on another machine cannot reach Metro through your environment's
124 localhost without forwarding or another reachable address.
125
126 +## Simlock hosts (alpha)
127 +
128 +[Simlock](https://incubator.callstack.com/simlock/) pools iOS simulators and
129 +Android emulators across machines. If you run a Simlock gateway, T3 can lease
130 +devices from it. Simlock is new and unreleased, so this integration is an
131 +alpha: it may change or stop working with a newer Simlock. T3 does not install
132 +or manage Simlock; set up the gateway and its workers yourself. It needs a
133 +gateway and workers built from Simlock's `main` at
134 +[6316e10](https://github.com/callstackincubator/simlock/commit/6316e10) or
135 +later, the first with a lease holder's screen and input.
136 +
137 +Turn on **Settings → Labs → Simlock device hosts (alpha)** and **Use devices**
138 +in Settings → Devices, then choose **Add source → Simlock pool** with an **agent token**
139 +(`simlock --gateway token create --role agent`). Give each T3 server its own
140 +token: Simlock counts every lease made with one token against the same
141 +requester, and allows one at a time unless the gateway's
142 +`lease.maxPerRequester` is raised to the host's **Devices at once**. The token
143 +leases devices and reaches only its own leases, but commands on a leased device
144 +run on its worker, so treat it like shell access to your workers. T3 sends it
145 +with every request, so use an HTTPS gateway URL, or plain HTTP only over an
146 +encrypted network such as Tailscale. The gateway
147 +and workers need `capabilities.stream.enabled` and `capabilities.input.enabled`
148 +for the live screen and for input.
149 +
150 +The picker lists the models your workers can make. Opening one takes a lease;
151 +closing it with **Return device to the pool**, or removing the host, returns it
152 +wiped. The panel keeps a watched device leased up to the host's lease limit.
153 +You can tap, swipe, type, and press Home, and Back and Recents on Android.
154 +Rotation, appearance, text size, device tools, and screenshots are not offered
155 +for Simlock devices; agents can still do them through `device_open`. On iOS 27
156 +simulators, typing on your keyboard does nothing; tap the on-screen keyboard
157 +instead. Workers must run the same agent-device
158 +version as T3 (see Device tool updates), and agent-device accepts app installs
159 +for a lease only from the folder it was opened from, which `device_open`
160 +names. A device cannot reach development servers on your machine through
161 +localhost; use an address its worker can reach.
162 +
163 ## Device tool updates
164
128 -The connected T3 server manages the device hub and agent tools on its own machine and configured SSH hosts. Required versions install automatically the next time those tools are used. Settings → Devices → Check versions reads installed versions without installing tools or starting devices.
165 +The connected T3 server manages the device hub and agent tools on its own machine and configured SSH hosts. Required versions install automatically the next time those tools are used. In Settings → Devices, select a version and choose **Check versions** to read installed versions without installing tools or starting devices.
166
167 To receive newer tool versions on a remote environment, update that environment's T3 server. Updating only the browser or mobile app does not update the remote server. An offline host keeps its installed files, but an update needs network access before device support can start; T3 does not fall back to an older version. Reconnect the host and use Retry if installation fails. Existing device and agent-access settings are preserved.
packages/client-runtime/src/device/stream.test.ts
+59 -2
@@ -199,7 +199,11 @@ class MjpegImage extends EventTarget {
199 }
200 }
201
202 -function recoveryFixture(platform: "ios" | "android" = "ios", preferMjpeg = true) {
202 +function recoveryFixture(
203 + platform: "ios" | "android" = "ios",
204 + preferMjpeg = true,
205 + serveSimOnly = false,
206 +) {
207 vi.useFakeTimers();
208 const sockets: Socket[] = [];
209 class Socket {
@@ -211,7 +215,9 @@ function recoveryFixture(platform: "ios" | "android" = "ios", preferMjpeg = true
215 onclose: ((event: { code: number; reason: string }) => void) | null = null;
216 send = vi.fn();
217 close = vi.fn();
214 - constructor() {
218 + readonly url: string;
219 + constructor(url: string) {
220 + this.url = url;
221 sockets.push(this);
222 }
223 }
@@ -273,6 +279,7 @@ function recoveryFixture(platform: "ios" | "android" = "ios", preferMjpeg = true
279 {
280 platform,
281 preferMjpeg,
282 + serveSimOnly,
283 deviceId: "test-device",
284 access: {
285 httpBase: "https://test/api/device-hub",
@@ -353,6 +360,56 @@ describe("shared device stream readiness and recovery", () => {
360 }
361 });
362
363 + it("streams and drives a serve-sim-only Android device over serve-sim's AVCC and input socket", async () => {
364 + const { client, events, fetch, sockets, videoBodies, decoders } = recoveryFixture(
365 + "android",
366 + false,
367 + true,
368 + );
369 + client.start();
370 + await vi.advanceTimersByTimeAsync(0);
371 + // No MJPEG priming: Simlock serves only the AVCC stream and the input socket.
372 + expect(fetch.mock.calls.map(([url]) => url)).toEqual([
373 + "https://test/api/device-hub/vendor/serve-sim/helper/test-device/stream.avcc",
374 + ]);
375 + expect(sockets.map((socket) => socket.url)).toEqual([
376 + "wss://test/api/device-hub/vendor/serve-sim/helper/ws?device=test-device",
377 + ]);
378 + // Simlock adds meta (5), keep-alive (6), and lease-end (7) frames to serve-sim's envelopes.
379 + videoBodies[0]!.enqueue(
380 + new Uint8Array([
381 + ...envelope(5, [0x7b, 0x7d]),
382 + ...envelope(1, [1, 0x64, 0, 0x1f]),
383 + ...envelope(6, []),
384 + ...envelope(2, [2]),
385 + ...envelope(7, [0x7b, 0x7d]),
386 + ]),
387 + );
388 + await vi.advanceTimersByTimeAsync(0);
389 + expect(decoders[0]!.decode).toHaveBeenCalledOnce();
390 +
391 + const input = sockets[0]!;
392 + input.onmessage?.({ data: Uint8Array.of(0x83).buffer });
393 + input.onmessage?.({
394 + data: new Uint8Array([
395 + 0x82,
396 + ...new TextEncoder().encode('{"width":1080,"height":2400,"orientation":"portrait"}'),
397 + ]).buffer,
398 + });
399 + expect(events.onInputConnected).toHaveBeenLastCalledWith(true, undefined);
400 + client.sendTouch("begin", 0.25, 0.5);
401 + client.pressButton("back");
402 + const sent = input.send.mock.calls.map(([payload]) => {
403 + const bytes = payload as Uint8Array;
404 + return [bytes[0], JSON.parse(new TextDecoder().decode(bytes.subarray(1)))];
405 + });
406 + expect(sent).toEqual([
407 + [0x03, { type: "begin", x: 0.25, y: 0.5 }],
408 + [0x04, { button: "back" }],
409 + ]);
410 + client.stop();
411 + });
412 +
413 it("does not repaint a delayed JPEG seed over newer decoded video", async () => {
414 const { client, videoBodies, drawImage, decodedFrame } = recoveryFixture("ios", false);
415 let resolveBitmap!: (bitmap: ImageBitmap) => void;
packages/client-runtime/src/device/stream.ts
+38 -24
@@ -120,6 +120,8 @@ export interface DeviceStreamTarget {
120 readonly preferMjpeg?: boolean;
121 readonly panelId?: 1 | 3;
122 readonly videoOnly?: boolean;
123 + /** The host speaks only serve-sim's AVCC stream and input socket, on both platforms (Simlock). */
124 + readonly serveSimOnly?: boolean;
125 }
126
127 export type DeviceHardwareButton = "home" | "back" | "recents" | "power" | "appSwitcher";
@@ -388,12 +390,16 @@ export function createDeviceStreamClient(
390 ): DeviceStreamClient {
391 const { access, platform, deviceId } = target;
392 const sink = "present" in output ? output : createCanvasFrameSink(output);
391 - const vendor = platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
393 + // Android normally streams over serve-emu's socket; a serve-sim-only host serves it like iOS.
394 + const serveSimOnly = target.serveSimOnly === true;
395 + const avcc = platform === "ios" || serveSimOnly;
396 + const vendor = avcc ? "/vendor/serve-sim" : "/vendor/serve-emu";
397 const device = encodeURIComponent(deviceId);
398 const httpUrl = (path: string) =>
399 withDeviceHubQuery(`${access.httpBase}${vendor}${path}`, access);
400 const wsUrl = (path: string) => withDeviceHubQuery(`${access.wsBase}${vendor}${path}`, access);
396 - const useWebCodecs = isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg);
401 + const useWebCodecs =
402 + isWebCodecsSupported() && !(platform === "ios" && target.preferMjpeg && !serveSimOnly);
403
404 let stopped = true;
405 let socket: WebSocket | null = null;
@@ -551,7 +557,7 @@ export function createDeviceStreamClient(
557
558 const paint = (source: CanvasImageSource, width: number, height: number) => {
559 if (stopped) return;
554 - if (platform === "android" && (screen?.width !== width || screen.height !== height)) {
560 + if (!avcc && (screen?.width !== width || screen.height !== height)) {
561 screen = { width, height, orientation: width > height ? "landscape_left" : "portrait" };
562 events.onScreen(screen);
563 }
@@ -572,7 +578,11 @@ export function createDeviceStreamClient(
578 };
579
580 const recoverDecoder = () => {
575 - if (platform === "ios") fallBackToMjpeg();
581 + if (serveSimOnly) {
582 + // A new AVCC request starts a fresh capture with a keyframe; there is no MJPEG.
583 + closeDecoder();
584 + controller?.abort();
585 + } else if (platform === "ios") fallBackToMjpeg();
586 else {
587 closeDecoder();
588 connecting("Video decoder restarted.");
@@ -585,10 +595,7 @@ export function createDeviceStreamClient(
595 const decoder = new VideoDecoder({
596 output: (frame) => {
597 try {
588 - if (
589 - videoDecoder === decoder &&
590 - (platform !== "ios" || feedGeneration === videoGeneration)
591 - ) {
598 + if (videoDecoder === decoder && (!avcc || feedGeneration === videoGeneration)) {
599 decodedVideoGeneration = feedGeneration;
600 paint(frame, frame.displayWidth, frame.displayHeight);
601 }
@@ -597,11 +604,7 @@ export function createDeviceStreamClient(
604 }
605 },
606 error: () => {
600 - if (
601 - stopped ||
602 - videoDecoder !== decoder ||
603 - (platform === "ios" && feedGeneration !== videoGeneration)
604 - )
607 + if (stopped || videoDecoder !== decoder || (avcc && feedGeneration !== videoGeneration))
608 return;
609 recoverDecoder();
610 },
@@ -638,7 +641,7 @@ export function createDeviceStreamClient(
641 awaitingKeyframe = false;
642 }
643 if (videoDecoder.decodeQueueSize > SOFT_DECODE_QUEUE) {
641 - if (platform !== "ios") {
644 + if (!avcc) {
645 recoverDecoder();
646 return;
647 }
@@ -769,7 +772,12 @@ export function createDeviceStreamClient(
772 if (!configured) {
773 await reader.cancel().catch(() => {});
774 if (!isCurrent()) return;
772 - if (target.videoOnly)
775 + if (serveSimOnly)
776 + setStatus(
777 + "error",
778 + `This browser cannot decode this device's ${avcCodecString(chunk.payload)} stream.`,
779 + );
780 + else if (target.videoOnly)
781 setStatus(
782 "error",
783 `This browser cannot decode the Duo panel's ${avcCodecString(chunk.payload)} stream.`,
@@ -1070,7 +1078,7 @@ export function createDeviceStreamClient(
1078 const connectIosInput = async () => {
1079 if (stopped) return;
1080 const session = generation;
1073 - await primeIosHelper(session);
1081 + if (!serveSimOnly) await primeIosHelper(session);
1082 if (stopped || generation !== session) return;
1083 const ws = new WebSocket(wsUrl(`/helper/ws?device=${device}`));
1084 ws.binaryType = "arraybuffer";
@@ -1231,7 +1239,11 @@ export function createDeviceStreamClient(
1239 iosInputAdmitted = false;
1240 iosInputUnavailable = false;
1241 connecting();
1234 - if (platform === "ios") {
1242 + if (serveSimOnly) {
1243 + if (!target.videoOnly) void connectIosInput();
1244 + if (useWebCodecs) void readIosVideo();
1245 + else fail("This browser cannot decode this device's stream (WebCodecs unavailable).");
1246 + } else if (platform === "ios") {
1247 if (!target.videoOnly) void connectIosInput();
1248 if (useWebCodecs) void readIosVideo();
1249 else fallBackToMjpeg();
@@ -1275,7 +1287,7 @@ export function createDeviceStreamClient(
1287 const send = (payload: Uint8Array<ArrayBuffer> | string) => {
1288 if (
1289 !stopped &&
1278 - (platform !== "ios" || (iosInputAdmitted && !iosInputUnavailable)) &&
1290 + (!avcc || (iosInputAdmitted && !iosInputUnavailable)) &&
1291 socket?.readyState === WebSocket.OPEN
1292 )
1293 socket.send(payload);
@@ -1326,7 +1338,7 @@ export function createDeviceStreamClient(
1338 startDuoVideo(panels);
1339 },
1340 sendTouch: (phase, x, y) => {
1329 - if (platform === "ios") {
1341 + if (avcc) {
1342 send(taggedJson(IOS_MSG_TOUCH, { type: phase, ...rawPoint(x, y) }));
1343 return;
1344 }
@@ -1334,7 +1346,7 @@ export function createDeviceStreamClient(
1346 send(JSON.stringify({ type: "touch", action, x, y }));
1347 },
1348 sendKey: (event, phase) => {
1337 - if (platform === "ios") {
1349 + if (avcc) {
1350 const usage = hidUsageForCode(event.code);
1351 if (usage !== null) send(taggedJson(IOS_MSG_KEY, { type: phase, usage }));
1352 return;
@@ -1348,7 +1360,7 @@ export function createDeviceStreamClient(
1360 }
1361 },
1362 sendText: (text) => {
1351 - if (platform !== "android") return;
1363 + if (avcc) return;
1364 let chunk = "";
1365 let chunkBytes = 0;
1366 let sentChunks = 0;
@@ -1366,15 +1378,17 @@ export function createDeviceStreamClient(
1378 if (chunk.length > 0) send(JSON.stringify({ type: "text", text: chunk }));
1379 },
1380 pressButton: (button) => {
1369 - if (platform === "ios") {
1381 + if (avcc) {
1382 const name =
1383 button === "home"
1384 ? "home"
1373 - : button === "appSwitcher"
1385 + : button === "appSwitcher" || button === "recents"
1386 ? "app_switcher"
1387 : button === "power"
1388 ? "lock"
1377 - : null;
1389 + : button === "back" && platform === "android"
1390 + ? "back"
1391 + : null;
1392 if (name) send(taggedJson(IOS_MSG_BUTTON, { button: name }));
1393 return;
1394 }
packages/contracts/src/device.test.ts
+4 -1
@@ -4,6 +4,7 @@ import {
4 DeviceBootError,
5 DeviceServiceState,
6 EasDeviceHostConfig,
7 + SimlockDeviceHostConfig,
8 EasDeviceHostConfigs,
9 SshDeviceHostConfigs,
10 } from "./device.ts";
@@ -49,6 +50,7 @@ describe("configured device hosts", () => {
50
51 it("marks the EAS access token as a secret setting", () => {
52 expect(secretSettingsFields(EasDeviceHostConfig)).toEqual(["accessToken"]);
53 + expect(secretSettingsFields(SimlockDeviceHostConfig)).toEqual(["agentToken"]);
54 });
55 });
56
@@ -63,6 +65,7 @@ describe("device state for clients from before EAS hosts", () => {
65 hosts: [
66 { ...summary, id: "local", kind: "local" as const },
67 { ...summary, id: "eas", kind: "eas" as const },
68 + { ...summary, id: "pool", kind: "simlock" as const },
69 ],
70 hostStatus: "ready" as const,
71 hostStatuses: {},
@@ -74,7 +77,7 @@ describe("device state for clients from before EAS hosts", () => {
77 revision: 1,
78 };
79
77 - it("sends EAS hosts where an older client does not look, and reads them back", () => {
80 + it("sends EAS and Simlock hosts where an older client does not look, and reads them back", () => {
81 const wire = encodeState(state);
82 expect(decodeOlderState(wire).hosts.map((host) => host.id)).toEqual(["local"]);
83 expect(decodeState(wire).hosts).toEqual(state.hosts);
packages/contracts/src/device.ts
+48 -5
@@ -68,7 +68,32 @@ export const EasDeviceHostConfig = Schema.Struct({
68 );
69 export type EasDeviceHostConfig = typeof EasDeviceHostConfig.Type;
70
71 -export type DeviceHostConfig = SshDeviceHostConfig | EasDeviceHostConfig;
71 +/**
72 + * Alpha: devices leased from a Simlock gateway (https://incubator.callstack.com/simlock).
73 + * T3 never installs Simlock; the gateway and its workers are the user's own.
74 + */
75 +export const SimlockDeviceHostConfig = Schema.Struct({
76 + kind: Schema.Literal("simlock"),
77 + id: ConfiguredDeviceHostId,
78 + label: TrimmedNonEmptyString,
79 + /** The gateway's origin, such as https://gateway.example.ts.net:4700. */
80 + gatewayUrl: TrimmedNonEmptyString.check(Schema.isPattern(/^https?:\/\/[^\s/]+\/?$/)),
81 + /** Leases, drives, watches, and takes input on its own leases. Kept in the secret store. */
82 + agentToken: TrimmedString.pipe(
83 + Schema.withDecodingDefaultKey(Effect.succeed("")),
84 + Schema.annotateKey({ settingsSecret: true }),
85 + ),
86 + maxLeases: Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 20 })).pipe(
87 + Schema.withDecodingDefaultKey(Effect.succeed(2)),
88 + ),
89 + /** A lease the Device panel keeps alive ends this long after it started. */
90 + maxLeaseMinutes: Schema.Int.check(Schema.isBetween({ minimum: 5, maximum: 240 })).pipe(
91 + Schema.withDecodingDefaultKey(Effect.succeed(60)),
92 + ),
93 +});
94 +export type SimlockDeviceHostConfig = typeof SimlockDeviceHostConfig.Type;
95 +
96 +export type DeviceHostConfig = SshDeviceHostConfig | EasDeviceHostConfig | SimlockDeviceHostConfig;
97
98 const uniqueHostIds = Schema.makeFilter(
99 (hosts: ReadonlyArray<{ readonly id: string }>) =>
@@ -85,6 +110,9 @@ export const SshDeviceHostConfigs = Schema.Array(SshDeviceHostConfig).check(uniq
110 */
111 export const EasDeviceHostConfigs = Schema.Array(EasDeviceHostConfig).check(uniqueHostIds);
112
113 +/** Kept apart from the other host lists for the same reason as EAS hosts. */
114 +export const SimlockDeviceHostConfigs = Schema.Array(SimlockDeviceHostConfig).check(uniqueHostIds);
115 +
116 export const DeviceEasAccountInput = Schema.Struct({
117 /** A saved EAS host whose stored token is checked when no new token is given. */
118 hostId: Schema.optional(DeviceHostId),
@@ -161,7 +189,15 @@ const EasDeviceHostSummary = Schema.Struct({
189 ...deviceHostSummaryFields,
190 kind: Schema.Literal("eas"),
191 });
164 -export const DeviceHostSummary = Schema.Union([MachineDeviceHostSummary, EasDeviceHostSummary]);
192 +const SimlockDeviceHostSummary = Schema.Struct({
193 + ...deviceHostSummaryFields,
194 + kind: Schema.Literal("simlock"),
195 +});
196 +export const DeviceHostSummary = Schema.Union([
197 + MachineDeviceHostSummary,
198 + EasDeviceHostSummary,
199 + SimlockDeviceHostSummary,
200 +]);
201 export type DeviceHostSummary = typeof DeviceHostSummary.Type;
202
203 export const DeviceHostStatus = Schema.Literals([
@@ -198,6 +234,8 @@ const deviceServiceStateFields = {
234 supportsToolInspection: Schema.optional(Schema.Boolean),
235 /** Servers from before EAS hosts ignore `easDeviceHosts`, so clients offer them only when set. */
236 supportsEasHosts: Schema.optional(Schema.Boolean),
237 + /** Servers from before Simlock hosts ignore `simlockDeviceHosts`. */
238 + supportsSimlockHosts: Schema.optional(Schema.Boolean),
239 hostStatus: DeviceHostStatus,
240 hostStatusDetail: Schema.optional(Schema.String),
241 hostStatuses: DeviceHostStatuses,
@@ -221,6 +259,7 @@ const DeviceServiceStateWire = Schema.Struct({
259 ...deviceServiceStateFields,
260 hosts: Schema.Array(MachineDeviceHostSummary),
261 easHosts: Schema.optional(Schema.Array(EasDeviceHostSummary)),
262 + simlockHosts: Schema.optional(Schema.Array(SimlockDeviceHostSummary)),
263 });
264 const DeviceServiceStateDecoded = Schema.Struct({
265 ...deviceServiceStateFields,
@@ -234,18 +273,22 @@ export const DeviceServiceState = DeviceServiceStateWire.pipe(
273 typeof DeviceServiceStateDecoded.Type,
274 typeof DeviceServiceStateWire.Type
275 >({
237 - decode: ({ easHosts, ...state }) => ({
276 + decode: ({ easHosts, simlockHosts, ...state }) => ({
277 ...state,
239 - hosts: [...state.hosts, ...(easHosts ?? [])],
278 + hosts: [...state.hosts, ...(easHosts ?? []), ...(simlockHosts ?? [])],
279 }),
280 encode: (state) => ({
281 ...state,
282 hosts: state.hosts.filter(
244 - (host): host is typeof MachineDeviceHostSummary.Type => host.kind !== "eas",
283 + (host): host is typeof MachineDeviceHostSummary.Type =>
284 + host.kind === "local" || host.kind === "ssh",
285 ),
286 easHosts: state.hosts.filter(
287 (host): host is typeof EasDeviceHostSummary.Type => host.kind === "eas",
288 ),
289 + simlockHosts: state.hosts.filter(
290 + (host): host is typeof SimlockDeviceHostSummary.Type => host.kind === "simlock",
291 + ),
292 }),
293 }),
294 ),
packages/contracts/src/settings.ts
+6 -1
@@ -1,4 +1,4 @@
1 -import { EasDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts";
1 +import { EasDeviceHostConfigs, SimlockDeviceHostConfigs, SshDeviceHostConfigs } from "./device.ts";
2 import {
3 AuthOrchestrationOperateScope,
4 AuthSettingsWriteScope,
@@ -1195,6 +1195,9 @@ export const ServerSettings = Schema.Struct({
1195 deviceOnboardingCompleted: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1196 deviceHosts: SshDeviceHostConfigs.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1197 easDeviceHosts: EasDeviceHostConfigs.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1198 + simlockDeviceHosts: SimlockDeviceHostConfigs.pipe(Schema.withDecodingDefault(Effect.succeed([]))),
1199 + /** Alpha: Simlock device hosts. Off, the server ignores `simlockDeviceHosts`. */
1200 + simlockDeviceHostsEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
1201 sidebarAutoSettleAfterDays: Schema.NullOr(SidebarAutoSettleAfterDays).pipe(
1202 Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_AUTO_SETTLE_AFTER_DAYS)),
1203 ),
@@ -1551,6 +1554,8 @@ export const ServerSettingsPatch = Schema.Struct({
1554 deviceOnboardingCompleted: Schema.optionalKey(Schema.Boolean),
1555 deviceHosts: Schema.optionalKey(SshDeviceHostConfigs),
1556 easDeviceHosts: Schema.optionalKey(EasDeviceHostConfigs),
1557 + simlockDeviceHosts: Schema.optionalKey(SimlockDeviceHostConfigs),
1558 + simlockDeviceHostsEnabled: Schema.optionalKey(Schema.Boolean),
1559 sidebarAutoSettleAfterDays: Schema.optionalKey(Schema.NullOr(SidebarAutoSettleAfterDays)),
1560 compactIdleThreads: Schema.optionalKey(LegacyCompactIdleThreads),
1561 idleCompaction: Schema.optionalKey(IdleCompactionMode),