From d86b7556a04a51aa15003881ea13809e9db08c3c Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:57:19 -0500 Subject: [PATCH 1/2] fix(server): harden device channels, session cleanup, and agent tools Lands the missing server review fixes from feat/device-panel-server alongside security and reliability fixes found in the live nightly audit: - DeviceChannels: reject control characters and whitespace in device paths, tighten helper IDs to [A-Za-z0-9._-]+, verify canonical URL pathname, validate WS subprotocols, register WS channels before dialing the hub, stay inside the 2 MiB window, fail slow before enqueuing oversized messages, allow the draining nextSeq at the 64-message buffer limit, cap outbound bufferedAmount, keep UTF-16 surrogate pairs whole, and clean up handshake listeners. - DeviceService & LocalDeviceHost: persist pendingReleases before updating in-memory claims, check daemon PID liveness before refusing session close, withdraw launchers and agent-device.json when agent access turns off (and re-check agent access before recording/binding), keep retrying failed hub restarts with backoff, verify hub liveness in currentHub, reap stale hubs on start and stop, read the hub token from stdout only with Bearer on /readyz, reserve own tool ports before spawn and clear agent port only after stop, and guard the settings watcher per change. - AgentDeviceShim: refuse agent override flags (--session, -s, device/daemon flags), strip --serial for Android cdp/connection, stop matching positional -h on fill/type, write launchers atomically, hash non-plain IDs, forward SIGTERM/SIGINT, and escape % in Windows .cmd scripts. - DeviceActions, DeviceHubOperations, Codex, Guide: implement iOS shake via notifyutil, reject Android permission reset instead of revoking, capture Xcode 26 fallback screenshots with a scoped temp file, set Codex device MCP tool_timeout_sec=300, drop redundant device listing on device_open, and update the device-tab guide topic. --- .../server/src/device/AgentDeviceShim.test.ts | 168 +++++++----- apps/server/src/device/AgentDeviceShim.ts | 51 +++- apps/server/src/device/DeviceActions.test.ts | 30 +++ apps/server/src/device/DeviceActions.ts | 15 ++ apps/server/src/device/DeviceChannels.test.ts | 88 ++++++- apps/server/src/device/DeviceChannels.ts | 216 +++++++++++----- apps/server/src/device/DeviceHost.ts | 7 +- .../src/device/DeviceHubOperations.test.ts | 49 ++++ apps/server/src/device/DeviceHubOperations.ts | 77 ++++-- apps/server/src/device/DeviceService.test.ts | 165 +++++++++++- apps/server/src/device/DeviceService.ts | 243 ++++++++++++++---- apps/server/src/device/LocalDeviceHost.ts | 236 +++++++++++------ apps/server/src/guide/topics.ts | 10 +- apps/server/src/mcp/deviceToolHandlers.ts | 1 + .../provider/Layers/CodexSessionRuntime.ts | 2 +- .../src/provider/codexAppServerArgs.test.ts | 17 +- .../server/src/provider/codexAppServerArgs.ts | 20 +- docs/design/devices.md | 15 +- 18 files changed, 1115 insertions(+), 295 deletions(-) diff --git a/apps/server/src/device/AgentDeviceShim.test.ts b/apps/server/src/device/AgentDeviceShim.test.ts index 0e81ef677..f16c64cbe 100644 --- a/apps/server/src/device/AgentDeviceShim.test.ts +++ b/apps/server/src/device/AgentDeviceShim.test.ts @@ -32,72 +32,110 @@ const listeningPort = Effect.acquireRelease( ).pipe(Effect.map((server) => (server.address() as NodeNet.AddressInfo).port)); describe.skipIf(process.platform === "win32")("agent-device launcher", () => { - it.live("binds one device's flags, lets the agent's own flags win, and leaves help alone", () => - Effect.gen(function* () { - const fs = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const dir = yield* fs.makeTempDirectoryScoped({ prefix: "tl-device-launcher-" }); - const port = yield* listeningPort; - const entryPath = path.join(dir, "cli.mjs"); - yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));"); - const config = agentDeviceConfigPath(path, dir); - yield* writeAgentDeviceConfig(config, { baseUrl: `http://127.0.0.1:${port}`, token: "t" }); - const target = [ - "--platform", - "ios", - "--udid", - "UDID-1", - "--config", - config, - "--session", - "tl-a", - ]; - const command = yield* bindAgentDeviceLauncher({ - stateDir: dir, - threadId: "thread-1", - deviceId: "UDID-1", - node: process.execPath, - entryPath, - targetArgs: target, - }); - expect(command).toBe( - path.join(agentDeviceLaunchersDir(path, dir), "thread-1", "UDID-1", "agent-device"), - ); - const launch = (args: ReadonlyArray) => - exec(command, [...args]).then((result) => JSON.parse(result.stdout)); + it.live( + "binds one device's flags, refuses override flags, strips Android --serial on cdp, and leaves help alone", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fs.makeTempDirectoryScoped({ prefix: "tl-device-launcher-" }); + const port = yield* listeningPort; + const entryPath = path.join(dir, "cli.mjs"); + yield* fs.writeFileString(entryPath, "console.log(JSON.stringify(process.argv.slice(2)));"); + const config = agentDeviceConfigPath(path, dir); + yield* writeAgentDeviceConfig(config, { baseUrl: `http://127.0.0.1:${port}`, token: "t" }); + const target = [ + "--platform", + "ios", + "--udid", + "UDID-1", + "--config", + config, + "--session", + "tl-a", + ]; + const command = yield* bindAgentDeviceLauncher({ + stateDir: dir, + threadId: "thread-1", + deviceId: "UDID-1", + node: process.execPath, + entryPath, + targetArgs: target, + }); + expect(command).toBe( + path.join(agentDeviceLaunchersDir(path, dir), "thread-1", "UDID-1", "agent-device"), + ); + const launch = (args: ReadonlyArray) => + exec(command, [...args]).then((result) => JSON.parse(result.stdout)); - expect(yield* Effect.promise(() => launch(["snapshot", "-i"]))).toEqual([ - "snapshot", - "-i", - ...target, - ]); - expect(yield* Effect.promise(() => launch(["open", "--session", "mine"]))).toEqual([ - "open", - "--session", - "mine", - ...target.slice(0, 6), - ]); - // After `--` everything is text, and bound flags go before it. - expect(yield* Effect.promise(() => launch(["fill", "@e5", "--", "--help"]))).toEqual([ - "fill", - "@e5", - ...target, - "--", - "--help", - ]); - for (const args of [["help", "gesture"], ["open", "--help"], []]) { - expect(yield* Effect.promise(() => launch(args))).toEqual(args); - } - // Commands that would replace Threadlines' connection are refused. - yield* Effect.promise(() => - expect(launch(["daemon", "stop"])).rejects.toThrow("Threadlines manages this command"), - ); - // A runtime that moved since device_open names the fix. - yield* fs.remove(entryPath); - yield* Effect.promise(() => - expect(launch(["snapshot"])).rejects.toThrow("Call device_open again"), - ); - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + expect(yield* Effect.promise(() => launch(["snapshot", "-i"]))).toEqual([ + "snapshot", + "-i", + ...target, + ]); + // Override flags are refused so every session stays one Threadlines ends. + for (const args of [ + ["open", "--session", "mine"], + ["open", "-s", "mine"], + ["snapshot", "--udid=OTHER"], + ["snapshot", "--daemon-base-url", "http://127.0.0.1:9999"], + ]) { + yield* Effect.promise(() => + expect(launch(args)).rejects.toThrow("bound to one device and its session"), + ); + } + // Positional `-h` on text commands is text, not help. + expect(yield* Effect.promise(() => launch(["fill", "@e5", "-h"]))).toEqual([ + "fill", + "@e5", + "-h", + ...target, + ]); + // Android `cdp` strips `--serial` as well as `--platform`/`--config`/`--session`. + const androidCommand = yield* bindAgentDeviceLauncher({ + stateDir: dir, + threadId: "thread-1", + deviceId: "emulator-5554", + node: process.execPath, + entryPath, + targetArgs: [ + "--platform", + "android", + "--serial", + "emulator-5554", + "--config", + config, + "--session", + "tl-b", + ], + }); + const launchAndroid = (args: ReadonlyArray) => + exec(androidCommand, [...args]).then((result) => JSON.parse(result.stdout)); + expect(yield* Effect.promise(() => launchAndroid(["cdp", "list"]))).toEqual([ + "cdp", + "list", + ]); + // After `--` everything is text, and bound flags go before it. + expect(yield* Effect.promise(() => launch(["fill", "@e5", "--", "--help"]))).toEqual([ + "fill", + "@e5", + ...target, + "--", + "--help", + ]); + for (const args of [["help", "gesture"], ["open", "--help"], []]) { + expect(yield* Effect.promise(() => launch(args))).toEqual(args); + } + // Commands that would replace Threadlines' connection are refused. + yield* Effect.promise(() => + expect(launch(["daemon", "stop"])).rejects.toThrow("Threadlines manages this command"), + ); + // A runtime that moved since device_open names the fix. + yield* fs.remove(entryPath); + yield* Effect.promise(() => + expect(launch(["snapshot"])).rejects.toThrow("Call device_open again"), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); it.live("says the device connection is down before running agent-device", () => diff --git a/apps/server/src/device/AgentDeviceShim.ts b/apps/server/src/device/AgentDeviceShim.ts index d6624183c..b234b3e2b 100644 --- a/apps/server/src/device/AgentDeviceShim.ts +++ b/apps/server/src/device/AgentDeviceShim.ts @@ -1,4 +1,5 @@ // @effect-diagnostics globalJsonInEffect:off - JSON string literals embed paths safely into generated JavaScript. +// @effect-diagnostics nodeBuiltinImport:off - sha256 digest for non-plain device ids. /** * The `agent-device` launcher `device_open` hands an agent * (docs/design/devices.md). One per thread and device, at @@ -9,10 +10,13 @@ * would replace Threadlines' connection, and checks the connection first so a * sandboxed shell and a dead daemon get different messages. */ +import { createHash } from "node:crypto"; + import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; +import { writeFileStringAtomically } from "../atomicWrite.ts"; import { deviceStateDir } from "./DeviceToolchain.ts"; const STALE_RUNTIME = @@ -169,7 +173,7 @@ import { existsSync, readFileSync } from "node:fs"; import { connect } from "node:net"; const entry = ${JSON.stringify(entryPath)}; const bound = ${JSON.stringify(boundArgs)}; -const refused = new Map([["cdp", ["--platform", "--udid", "--config", "--session"]], ["connection", ["--platform", "--udid"]]]); +const refused = new Map([["cdp", ["--platform", "--udid", "--serial", "--config", "--session"]], ["connection", ["--platform", "--udid", "--serial"]]]); const managed = ["connect", "disconnect", "auth", "daemon"]; const args = process.argv.slice(2); const end = args.indexOf("--"); @@ -182,7 +186,14 @@ for (let index = 0; index < args.length; index++) { if (!arg.startsWith("-")) { name = arg; break; } if (!arg.includes("=") && valued.has(arg)) index++; } -const informational = args.length === 0 || ["help", "--help", "-h", "--version", "version"].includes(args[0]) || options.includes("--help") || options.includes("-h"); +const textCommands = new Set(["fill", "type"]); +let hasHelpFlag = false; +for (let index = 0; index < options.length; index++) { + const arg = options[index]; + if (arg === "--help" || (arg === "-h" && !textCommands.has(name))) { hasHelpFlag = true; break; } + if (!arg.includes("=") && valued.has(arg)) index++; +} +const informational = args.length === 0 || ["help", "--help", "-h", "--version", "version"].includes(args[0]) || hasHelpFlag; if (!informational && managed.includes(name)) { console.error("Threadlines manages this command's connection to the device, so \`" + name + "\` is not available through it."); process.exit(1); @@ -192,6 +203,22 @@ if (!informational && name === "device") { process.exit(1); } const skip = refused.get(name) ?? []; +// Its device, session and daemon are bound: an agent's own would open a session Threadlines cannot end. +const locked = new Set([...bound.filter((_, index) => index % 2 === 0), "--device", "-d", "--serial", "--udid", "--platform", "--session", "-s", "--config", "--daemon-base-url", "--daemon-auth-token", "--state-dir"]); +let overridden; +if (bound.length > 0 && !informational) { + for (let index = 0; index < options.length; index++) { + const arg = options[index]; + const eq = arg.indexOf("="); + const flag = eq > 0 ? arg.slice(0, eq) : arg; + if (locked.has(flag)) { overridden = flag; break; } + if (eq < 0 && valued.has(arg)) index++; + } +} +if (overridden) { + console.error("This command is bound to one device and its session, so it takes no " + overridden + ". Leave it out, or call device_open for another device."); + process.exit(1); +} if (!informational) for (let index = 0; index + 1 < bound.length; index += 2) if (!skip.includes(bound[index]) && !options.some(arg => arg === bound[index] || arg.startsWith(bound[index] + "="))) options.push(bound[index], bound[index + 1]); const command = end < 0 ? options : [...options, ...args.slice(end)]; const hasValue = flag => { const index = options.indexOf(flag); return options.some(arg => arg.startsWith(flag + "=") && arg.length > flag.length + 1) || (index >= 0 && !!options[index + 1] && !options[index + 1].startsWith("--")); }; @@ -227,10 +254,13 @@ delete env.AGENT_DEVICE_DAEMON_BASE_URL; delete env.AGENT_DEVICE_DAEMON_AUTH_TOKEN; delete env.AGENT_DEVICE_CONFIG; const child = spawn(${JSON.stringify(node)}, [entry, ...command], { stdio: "inherit", env }); +for (const signal of ["SIGTERM", "SIGINT"]) process.on(signal, () => { if (!child.killed) child.kill(signal); }); child.on("error", error => { console.error(error.message); process.exitCode = 1; }); child.on("exit", code => { process.exitCode = code ?? 1; }); `; +const escapeCmd = (value: string) => value.replaceAll("%", "%%"); + /** Writes a launcher into `dir` and returns the executable agents run. */ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (input: { readonly dir: string; @@ -243,27 +273,32 @@ const writeLauncher = Effect.fn("AgentDeviceShim.writeLauncher")(function* (inpu const node = input.node; yield* fs.makeDirectory(input.dir, { recursive: true }); const launcherPath = path.join(input.dir, "agent-device-launcher.mjs"); - yield* fs.writeFileString(launcherPath, launcherSource(node, input.entryPath, input.boundArgs)); + yield* writeFileStringAtomically({ + filePath: launcherPath, + contents: launcherSource(node, input.entryPath, input.boundArgs), + }); if (process.platform === "win32") { - const script = `@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\nif not exist "${node}" (echo ${STALE_RUNTIME} 1>&2 & exit /b 1)\r\n"${node}" "${launcherPath}" %*\r\n`; + const safeNode = escapeCmd(node); + const safeLauncher = escapeCmd(launcherPath); + const script = `@echo off\r\nsetlocal EnableExtensions DisableDelayedExpansion\r\nif not exist "${safeNode}" (echo ${STALE_RUNTIME} 1>&2 & exit /b 1)\r\n"${safeNode}" "${safeLauncher}" %*\r\n`; const scriptPath = path.join(input.dir, "agent-device.cmd"); - yield* fs.writeFileString(scriptPath, script); + yield* writeFileStringAtomically({ filePath: scriptPath, contents: script }); return scriptPath; } const script = `#!/bin/sh\n[ -x ${quoteShell(node)} ] || { echo ${quoteShell(STALE_RUNTIME)} >&2; exit 1; }\nexec ${quoteShell(node)} ${quoteShell(launcherPath)} "$@"\n`; const scriptPath = path.join(input.dir, "agent-device"); - yield* fs.writeFileString(scriptPath, script); + yield* writeFileStringAtomically({ filePath: scriptPath, contents: script }); yield* fs.chmod(scriptPath, 0o755); return scriptPath; }); const SAFE_SEGMENT = /^[A-Za-z0-9._-]{1,128}$/; -/** A path segment for an id: the id itself when it is plain, else a digest of it. */ +/** A path segment for an id: the id itself when it is plain, else a sha256 digest of it. */ const segment = (id: string) => SAFE_SEGMENT.test(id) && id !== "." && id !== ".." ? id - : `x-${Buffer.from(id).toString("base64url").slice(0, 96)}`; + : `x-${createHash("sha256").update(id).digest("hex").slice(0, 24)}`; /** `/device/bin`. */ export const agentDeviceLaunchersDir = (path: Path.Path, stateDir: string) => diff --git a/apps/server/src/device/DeviceActions.test.ts b/apps/server/src/device/DeviceActions.test.ts index ae7088a94..0eeb300b0 100644 --- a/apps/server/src/device/DeviceActions.test.ts +++ b/apps/server/src/device/DeviceActions.test.ts @@ -151,6 +151,36 @@ describe("runDeviceAction", () => { expect(calls.map((call) => call.args.at(-1))).toEqual(permissions); }), ); + + it.effect("shakes an iOS simulator via notifyutil", () => + Effect.gen(function* () { + const { ready, calls } = makeReady(); + yield* runDeviceAction(ready, "ios", { type: "shake", deviceId: udid }); + expect(calls).toEqual([ + { + command: "xcrun", + args: ["simctl", "spawn", udid, "notifyutil", "-p", "com.apple.UIKit.simulatorShake"], + }, + ]); + }), + ); + + it.effect("rejects Android permission reset as unsupported instead of revoking", () => + Effect.gen(function* () { + const { ready, calls } = makeReady(); + const error = yield* Effect.flip( + runDeviceAction(ready, "android", { + type: "setPermission", + deviceId: "emulator-5554", + appId: "com.example.app", + permission: "camera", + decision: "reset", + }), + ); + expect(error._tag).toBe("DeviceActionUnavailableError"); + expect(calls).toEqual([]); + }), + ); }); describe("readDeviceDetail", () => { diff --git a/apps/server/src/device/DeviceActions.ts b/apps/server/src/device/DeviceActions.ts index 2333671cf..1744b89ce 100644 --- a/apps/server/src/device/DeviceActions.ts +++ b/apps/server/src/device/DeviceActions.ts @@ -43,6 +43,7 @@ const IOS_ACTIONS: ReadonlySet = new Set([ "openUrl", "launchApp", "terminateApp", + "shake", "sendPush", ]); @@ -315,6 +316,13 @@ const runIos = Effect.fn("DeviceActions.runIos")(function* ( return; } case "shake": + yield* simctl( + run, + udid, + ["spawn", "notifyutil", "-p", "com.apple.UIKit.simulatorShake"], + "shake", + ); + return; case "setOrientation": return yield* new DeviceActionUnavailableError({ operation: input.type, @@ -433,6 +441,13 @@ const runAndroid = Effect.fn("DeviceActions.runAndroid")(function* ( // The emulator cannot clear location; keep the fix and refresh the reading. return; case "setPermission": { + if (input.decision === "reset") { + return yield* new DeviceActionUnavailableError({ + operation: "permission", + platform: "android", + reason: "unsupported", + }); + } const permissions = ANDROID_PERMISSIONS[input.permission]; if (!permissions) { return yield* new DeviceActionUnavailableError({ diff --git a/apps/server/src/device/DeviceChannels.test.ts b/apps/server/src/device/DeviceChannels.test.ts index f9040ed29..a4f686a65 100644 --- a/apps/server/src/device/DeviceChannels.test.ts +++ b/apps/server/src/device/DeviceChannels.test.ts @@ -102,6 +102,15 @@ describe("isAllowedDevicePath", () => { expect( DeviceChannels.isAllowedDevicePath("GET", "/vendor/serve-sim/helper/%2e%2e/stream.avcc"), ).toBe(false); + expect(DeviceChannels.isAllowedDevicePath("GET", "/vendor/serve-sim/helper/.\t./config")).toBe( + false, + ); + expect(DeviceChannels.isAllowedDevicePath("GET", "/vendor/serve-sim/helper/.\n./config")).toBe( + false, + ); + expect( + DeviceChannels.isAllowedDevicePath("GET", "/vendor/serve-sim/helper/SIM-1/config?x=1"), + ).toBe(false); }); it("allows the viewer's stream and input routes", () => { @@ -164,11 +173,11 @@ describe("DeviceChannels", () => { return event; }); expect((yield* take)._tag).toBe("opened"); - // Uncredited, the channel stops at the window instead of reading the whole body. + // Uncredited, the channel holds strictly inside the window instead of overshooting it. yield* Effect.sleep("300 millis"); while ((yield* Queue.size(received)) > 0) yield* take; - expect(delivered).toBeGreaterThanOrEqual(DEVICE_CHANNEL_WINDOW_BYTES); - expect(delivered).toBeLessThan(DEVICE_CHANNEL_WINDOW_BYTES + DEVICE_CHANNEL_CHUNK_BYTES); + expect(delivered).toBeGreaterThan(0); + expect(delivered).toBeLessThanOrEqual(DEVICE_CHANNEL_WINDOW_BYTES); // Crediting lets the rest through. let ended = false; while (!ended) { @@ -236,4 +245,77 @@ describe("DeviceChannels", () => { }), ), ); + + it.live("refuses duplicate ws ids and invalid protocols without dialing the hub", () => + Effect.scoped( + Effect.gen(function* () { + const hub = yield* startFakeHub; + const channels = yield* channelsFor(hub.origin); + const invalid = yield* channels + .open("connection", { + _tag: "ws", + channelId: "bad-proto", + path: "/vendor/serve-sim/helper/ws", + protocols: ["dup", "dup"], + }) + .pipe(Effect.flip); + expect(invalid.reason).toBe("forbidden"); + yield* channels + .open("connection", { + _tag: "ws", + channelId: "w1", + path: "/vendor/serve-sim/helper/ws", + }) + .pipe(Effect.asVoid); + const dup = yield* channels + .open("connection", { + _tag: "ws", + channelId: "w1", + path: "/vendor/serve-sim/helper/ws", + }) + .pipe(Effect.flip); + expect(dup.reason).toBe("limit"); + expect(hub.seen).toEqual([`WS /vendor/serve-sim/helper/ws Bearer ${TOKEN}`]); + }), + ), + ); + + it.live("drains 64 queued out-of-order sends when nextSeq arrives", () => + Effect.scoped( + Effect.gen(function* () { + const hub = yield* startFakeHub; + const channels = yield* channelsFor(hub.origin); + const events = yield* channels.open("connection", { + _tag: "ws", + channelId: "w-drain", + path: "/vendor/serve-sim/helper/ws", + }); + const received = yield* Queue.unbounded(); + yield* events.pipe( + Stream.runForEach((event) => Queue.offer(received, event)), + Effect.forkScoped, + ); + expect((yield* Queue.take(received))._tag).toBe("opened"); + const queued = Array.from({ length: 64 }, (_, index) => + channels.send("connection", { + channelId: "w-drain", + seq: index + 1, + data: `m${index + 1}`, + binary: false, + }), + ); + const fibers = yield* Effect.forEach(queued, (effect) => Effect.forkScoped(effect)); + yield* Effect.sleep("20 millis"); + yield* channels.send("connection", { + channelId: "w-drain", + seq: 0, + data: "m0", + binary: false, + }); + yield* Effect.forEach(fibers, (fiber) => Fiber.join(fiber)); + const first = yield* Queue.take(received); + expect(first).toEqual({ _tag: "message", data: "m0", binary: false, final: true }); + }), + ), + ); }); diff --git a/apps/server/src/device/DeviceChannels.ts b/apps/server/src/device/DeviceChannels.ts index 5199ff5fc..98ced4f8f 100644 --- a/apps/server/src/device/DeviceChannels.ts +++ b/apps/server/src/device/DeviceChannels.ts @@ -54,8 +54,8 @@ const GET_PATHS: ReadonlyArray = [ /^\/api\/devices$/, /^\/vendor\/serve-sim\/api\/screenshot$/, /^\/vendor\/serve-sim\/api\/event-log(\/events)?$/, - /^\/vendor\/serve-sim\/helper\/[^/]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/, - /^\/vendor\/serve-sim\/helper\/[^/]+\/panel\/(1|3)\/stream\.avcc$/, + /^\/vendor\/serve-sim\/helper\/[A-Za-z0-9._-]+\/(stream\.mjpeg|stream\.avcc|config|health|ax|foreground)$/, + /^\/vendor\/serve-sim\/helper\/[A-Za-z0-9._-]+\/panel\/(1|3)\/stream\.avcc$/, /^\/vendor\/serve-sim\/appstate$/, /^\/vendor\/serve-emu\/api\/(devices|screenshot|stream-mode|stream-settings|accessibility|fold)$/, /^\/vendor\/serve-emu\/health$/, @@ -79,12 +79,27 @@ const SCREENSHOT_PATHS = new Set([ "/vendor/serve-emu/api/screenshot", ]); +/** RFC 6455 subprotocol token: ASCII visible non-separator characters. */ +const WS_PROTOCOL_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; + +const areValidProtocols = (protocols: ReadonlyArray | undefined): boolean => { + if (protocols === undefined || protocols.length === 0) return true; + const seen = new Set(); + for (const protocol of protocols) { + if (!WS_PROTOCOL_TOKEN.test(protocol) || seen.has(protocol)) return false; + seen.add(protocol); + } + return true; +}; + /** - * Whether a client may open `path` this way. Segments that a URL parser - * would rewrite (`.`, `..`, escapes, backslashes, empty) are refused outright, - * so what is checked is what reaches the hub. + * Whether a client may open `path` this way. Control characters, whitespace, + * query/fragment markers, and segments a URL parser would rewrite (`.`, `..`, + * escapes, backslashes, empty) are refused outright, so what is checked is + * what reaches the hub. */ export const isAllowedDevicePath = (kind: "GET" | "POST" | "ws", path: string): boolean => { + if (!path.startsWith("/") || /[\x00-\x1f\x7f?#\s]/.test(path)) return false; const segments = path.split("/").slice(1); if ( segments.some( @@ -113,18 +128,44 @@ const upstreamSearch = (query: Readonly> | undefined) => return text === "" ? "" : `?${text}`; }; +/** Builds a hub URL and verifies WHATWG URL normalization left `path` unchanged. */ +const canonicalHubUrl = ( + origin: string, + path: string, + query: Readonly> | undefined, +): Effect.Effect => + Effect.try({ + try: () => { + const url = `${origin}${path}${upstreamSearch(query)}`; + const parsed = new URL(url); + if (parsed.pathname !== path) { + throw new Error("Path changed under URL normalization."); + } + return url; + }, + catch: () => failure("forbidden", "That device path is not available."), + }); + const oneEvent = (event: DeviceChannelEvent): Stream.Stream => Stream.succeed(event); const failure = (reason: DeviceChannelError["reason"], detail: string) => new DeviceChannelError({ reason, detail }); +interface Chunk { + /** base64 */ + readonly data: string; + /** Exact decoded byte count: what the client credits back. */ + readonly bytes: number; +} + /** Slices of at most DEVICE_CHANNEL_CHUNK_BYTES, base64. */ -const toChunks = (bytes: Uint8Array): ReadonlyArray => { +const toChunks = (bytes: Uint8Array): ReadonlyArray => { const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength); - const chunks: Array = []; + const chunks: Array = []; for (let offset = 0; offset < buffer.length; offset += DEVICE_CHANNEL_CHUNK_BYTES) { - chunks.push(buffer.subarray(offset, offset + DEVICE_CHANNEL_CHUNK_BYTES).toString("base64")); + const slice = buffer.subarray(offset, offset + DEVICE_CHANNEL_CHUNK_BYTES); + chunks.push({ data: slice.toString("base64"), bytes: slice.length }); } return chunks; }; @@ -139,8 +180,8 @@ interface Channel { unacknowledged: number; /** Credit arrived: let a waiting http body continue, or resume a paused socket. */ readonly onCredit: () => void; - /** Set for a ws channel. */ - readonly socket: WebSocket | null; + /** Set for a ws channel once the upstream socket is created. */ + socket: WebSocket | null; nextSeq: number; readonly waiting: Map; } @@ -225,9 +266,8 @@ export const make = Effect.gen(function* () { const credited = yield* Latch.make(true); const channel: Channel = { unacknowledged: 0, - onCredit: () => { - if (channel.unacknowledged < DEVICE_CHANNEL_WINDOW_BYTES) Latch.openUnsafe(credited); - }, + // The sender checks again whether its slice fits; a credit only wakes it. + onCredit: () => Latch.openUnsafe(credited), socket: null, nextSeq: 0, waiting: new Map(), @@ -235,15 +275,20 @@ export const make = Effect.gen(function* () { yield* register(connectionId, input.channelId, channel, () => Latch.openUnsafe(credited)); // Waits for credit before each slice goes out: the body is pulled only as fast as the client takes it. - const paced = (slices: Stream.Stream) => + // A slice goes out only when it fits in the window whole (or nothing is outstanding). + const paced = (slices: Stream.Stream) => slices.pipe( - Stream.mapEffect((data) => + Stream.mapEffect((chunk) => Effect.gen(function* () { - yield* credited.await; - // Exact decoded size: the client credits decoded bytes, so an estimate would drift. - channel.unacknowledged += Buffer.byteLength(data, "base64"); - if (channel.unacknowledged >= DEVICE_CHANNEL_WINDOW_BYTES) Latch.closeUnsafe(credited); - return { _tag: "data", data } as const; + while ( + channel.unacknowledged > 0 && + channel.unacknowledged + chunk.bytes > DEVICE_CHANNEL_WINDOW_BYTES + ) { + Latch.closeUnsafe(credited); + yield* credited.await; + } + channel.unacknowledged += chunk.bytes; + return { _tag: "data", data: chunk.data } as const; }), ), ); @@ -261,7 +306,7 @@ export const make = Effect.gen(function* () { } const hub = yield* hubOrUnavailable; - const url = `${hub.origin}${input.path}${upstreamSearch(input.query)}`; + const url = yield* canonicalHubUrl(hub.origin, input.path, input.query); const request = ( input.method === "POST" ? HttpClientRequest.post(url) : HttpClientRequest.get(url) ).pipe( @@ -301,51 +346,63 @@ export const make = Effect.gen(function* () { connectionId: string, input: Extract, ) { - if (!isAllowedDevicePath("ws", input.path)) { + if (!isAllowedDevicePath("ws", input.path) || !areValidProtocols(input.protocols)) { return yield* failure("forbidden", "That device path is not available."); } const hub = yield* hubOrUnavailable; - const url = `${hub.origin.replace(/^http/, "ws")}${input.path}${upstreamSearch(input.query)}`; + const url = yield* canonicalHubUrl(hub.origin.replace(/^http/, "ws"), input.path, input.query); const queue = yield* Queue.unbounded(); let paused = false; - // An `error` with no listener would take the server down: one is on from the start. - const socket = new WebSocket(url, input.protocols ? [...input.protocols] : [], { - headers: { authorization: `Bearer ${hub.token}` }, - handshakeTimeout: OPEN_TIMEOUT_MS, - perMessageDeflate: false, - }); - socket.binaryType = "nodebuffer"; const channel: Channel = { unacknowledged: 0, onCredit: () => { if (paused && channel.unacknowledged < DEVICE_CHANNEL_WINDOW_BYTES / 2) { paused = false; - socket.resume(); + channel.socket?.resume(); } }, - socket, + socket: null, nextSeq: 0, waiting: new Map(), }; + // The slot first: a channel refused for the limit or a reused id never reaches the hub. + yield* register(connectionId, input.channelId, channel, () => channel.socket?.terminate()); + // An `error` with no listener would take the server down: one is on from the start. + const socket = yield* Effect.try({ + try: () => + new WebSocket(url, input.protocols ? [...input.protocols] : [], { + headers: { authorization: `Bearer ${hub.token}` }, + handshakeTimeout: OPEN_TIMEOUT_MS, + perMessageDeflate: false, + }), + catch: (error) => + failure("forbidden", error instanceof Error ? error.message : "Invalid device socket."), + }); + socket.binaryType = "nodebuffer"; + channel.socket = socket; const fail = (error: DeviceChannelError) => { settleWaiting(channel, error); Queue.failCauseUnsafe(queue, Cause.fail(error)); socket.terminate(); }; socket.on("error", (error) => fail(failure("broken", error.message))); - // A refused open (a duplicate id, or the connection's limit) must not leave the socket up. - yield* register(connectionId, input.channelId, channel, () => socket.terminate()).pipe( - Effect.onError(() => Effect.sync(() => socket.terminate())), - ); socket.on("message", (data: Buffer | ArrayBuffer | Array, isBinary: boolean) => { const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data as Buffer); + // Paused, the socket may still hand over what it had read: past the cap, the client is gone. + if ( + channel.unacknowledged + bytes.length > + DEVICE_CHANNEL_WINDOW_BYTES + DEVICE_CHANNEL_SLOW_BYTES + ) { + fail(failure("slow", "The device stream got too far ahead of this client.")); + return; + } if (isBinary) { const parts = toChunks(bytes); parts.forEach((part, index) => Queue.offerUnsafe(queue, { _tag: "message", - data: part, + data: part.data, binary: true, final: index === parts.length - 1, }), @@ -355,20 +412,27 @@ export const make = Effect.gen(function* () { } else { const text = bytes.toString("utf8"); const step = DEVICE_CHANNEL_CHUNK_BYTES / 4; - for (let offset = 0; offset < Math.max(text.length, 1); offset += step) { - Queue.offerUnsafe(queue, { - _tag: "message", - data: text.slice(offset, offset + step), - binary: false, - final: offset + step >= text.length, - }); + if (text.length === 0) { + Queue.offerUnsafe(queue, { _tag: "message", data: "", binary: false, final: true }); + } else { + for (let offset = 0; offset < text.length;) { + let end = Math.min(offset + step, text.length); + // Keep UTF-16 surrogate pairs together so JSON chunks stay valid UTF-8 and credit stays exact. + if (end < text.length) { + const last = text.charCodeAt(end - 1); + if (last >= 0xd800 && last <= 0xdbff && end - offset > 1) end -= 1; + } + Queue.offerUnsafe(queue, { + _tag: "message", + data: text.slice(offset, end), + binary: false, + final: end >= text.length, + }); + offset = end; + } } } channel.unacknowledged += bytes.length; - if (channel.unacknowledged > DEVICE_CHANNEL_WINDOW_BYTES + DEVICE_CHANNEL_SLOW_BYTES) { - fail(failure("slow", "The device stream got too far ahead of this client.")); - return; - } if (!paused && channel.unacknowledged >= DEVICE_CHANNEL_WINDOW_BYTES) { paused = true; socket.pause(); @@ -387,20 +451,46 @@ export const make = Effect.gen(function* () { }); }); yield* Effect.callback((resume) => { - if (socket.readyState === WebSocket.OPEN) return resume(Effect.void); - socket.once("open", () => resume(Effect.void)); - socket.once("unexpected-response", (_request, response) => { + if (socket.readyState === WebSocket.OPEN) { + resume(Effect.void); + return; + } + if (socket.readyState === WebSocket.CLOSING || socket.readyState === WebSocket.CLOSED) { + resume(Effect.fail(failure("unreachable", "The device hub closed the socket."))); + return; + } + const cleanup = () => { + socket.off("open", onOpen); + socket.off("unexpected-response", onUnexpected); + socket.off("close", onClose); + socket.off("error", onError); + }; + const onOpen = () => { + cleanup(); + resume(Effect.void); + }; + const onUnexpected = (_request: unknown, response: { readonly statusCode?: number }) => { + cleanup(); resume( Effect.fail( failure("unreachable", `The device hub refused the socket (${response.statusCode}).`), ), ); socket.terminate(); - }); - socket.once("close", () => - resume(Effect.fail(failure("unreachable", "The device hub closed the socket."))), - ); - socket.once("error", (error) => resume(Effect.fail(failure("unreachable", error.message)))); + }; + const onClose = () => { + cleanup(); + resume(Effect.fail(failure("unreachable", "The device hub closed the socket."))); + }; + const onError = (error: Error) => { + cleanup(); + resume(Effect.fail(failure("unreachable", error.message))); + }; + socket.once("open", onOpen); + socket.once("unexpected-response", onUnexpected); + socket.once("close", onClose); + socket.once("error", onError); + return Effect.sync(cleanup); }); return Stream.fromQueue(queue); }); @@ -411,20 +501,30 @@ export const make = Effect.gen(function* () { const send: DeviceChannelsShape["send"] = (connectionId, input) => Effect.gen(function* () { const channel = channels.get(keyOf(connectionId, input.channelId)); - if (channel === undefined || channel.socket === null) { + if ( + channel === undefined || + channel.socket === null || + channel.socket.readyState === WebSocket.CONNECTING + ) { return yield* failure("unknownChannel", "That device channel is not open."); } const socket = channel.socket; if ( input.seq < channel.nextSeq || channel.waiting.has(input.seq) || - channel.waiting.size >= MAX_SENDS_OUT_OF_ORDER + (input.seq !== channel.nextSeq && channel.waiting.size >= MAX_SENDS_OUT_OF_ORDER) ) { const error = failure("limit", "The channel's messages arrived out of all order."); settleWaiting(channel, error); socket.terminate(); return yield* error; } + if (socket.bufferedAmount > DEVICE_CHANNEL_WINDOW_BYTES) { + const error = failure("slow", "The device hub stopped accepting input."); + settleWaiting(channel, error); + socket.terminate(); + return yield* error; + } const done = yield* Deferred.make(); channel.waiting.set(input.seq, { data: input.binary ? Buffer.from(input.data, "base64") : input.data, diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.ts index 1f18f6002..015b56a71 100644 --- a/apps/server/src/device/DeviceHost.ts +++ b/apps/server/src/device/DeviceHost.ts @@ -146,8 +146,11 @@ export class DeviceHost extends Context.Service< * and can try again. */ readonly releaseAgentSession: (session: string) => Effect.Effect; - /** Stops the agent-device daemon through its own CLI. */ - readonly stopAgent: Effect.Effect; + /** + * Stops the agent-device daemon through its own CLI. True once no daemon + * runs for this state folder; false when one may still be running. + */ + readonly stopAgent: Effect.Effect; /** Stops the hub and the daemon. Simulators and emulators keep running; the user owns those. */ readonly stop: Effect.Effect; } diff --git a/apps/server/src/device/DeviceHubOperations.test.ts b/apps/server/src/device/DeviceHubOperations.test.ts index 5965b0ec6..c4a0c4809 100644 --- a/apps/server/src/device/DeviceHubOperations.test.ts +++ b/apps/server/src/device/DeviceHubOperations.test.ts @@ -1,8 +1,11 @@ import * as Http from "node:http"; import type { AddressInfo } from "node:net"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; import { FetchHttpClient, HttpClient } from "effect/http"; import { @@ -171,4 +174,50 @@ describe("DeviceHubOperations list", () => { expect(commands.filter((command) => command.includes("getprop"))).toHaveLength(1); }).pipe(Effect.scoped, Effect.provide(FetchHttpClient.layer)), ); + + it.live("captures Xcode 26 fallback screenshots via scoped temp file and cleans it up", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const scratchDir = yield* fs.makeTempDirectoryScoped({ prefix: "tl-device-shot-" }); + const hub = yield* startFakeHub({}); + const payload = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]); + let capturedFile = ""; + const operations = makeDeviceHubOperations({ + origin: hub.origin, + token: "t", + modelCache: makeDeviceModelCache(), + http: yield* HttpClient.HttpClient, + fs, + scratchDir, + platformAvailable: () => Effect.succeed(true), + run: (command, args) => + Effect.gen(function* () { + expect(command).toBe("xcrun"); + expect(args.slice(0, 5)).toEqual([ + "simctl", + "io", + "SIM-26", + "screenshot", + "--type=png", + ]); + capturedFile = args[5]!; + yield* fs.writeFile(capturedFile, payload); + return { code: 0, stdout: "", stderr: "" }; + }).pipe(Effect.orDie), + }); + const bytes = yield* operations.screenshot({ + id: "SIM-26", + name: "iPhone 16", + version: "iOS 26.1", + platform: "ios", + booted: true, + physical: false, + }); + expect(bytes).toEqual(payload); + expect(yield* fs.exists(capturedFile)).toBe(false); + }).pipe( + Effect.scoped, + Effect.provide(Layer.mergeAll(FetchHttpClient.layer, NodeServices.layer)), + ), + ); }); diff --git a/apps/server/src/device/DeviceHubOperations.ts b/apps/server/src/device/DeviceHubOperations.ts index 07aec9791..911b88793 100644 --- a/apps/server/src/device/DeviceHubOperations.ts +++ b/apps/server/src/device/DeviceHubOperations.ts @@ -11,6 +11,7 @@ import { } from "@threadlines/contracts"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import type * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; @@ -33,12 +34,6 @@ const GETPROP_LINE = /^\[([^\]]+)\]: \[(.*)\]$/; // An AVD name as `emulator -list-avds` prints it; anything else is never joined into a path. const AVD_NAME = /^[A-Za-z0-9._-]+$/; const runsOnXcode26Runtime = (version: string) => Number(/^iOS (\d+)/.exec(version)?.[1]) <= 26; -// simctl needs a real file (it writes "-" or /dev/stdout as a file of that -// name), so the PNG passes through one in Threadlines' own state folder ($2), -// removed on exit, never the user's temp folder. -const DEFAULT_DISPLAY_SCREENSHOT = `mkdir -p "$2" && f=$(mktemp "$2/screenshot.XXXXXX") || exit 1 -trap 'rm -f "$f"' 0 -xcrun simctl io "$1" screenshot --type=png "$f" >/dev/null && base64 -i "$f"`; const HubDevice = Schema.Struct({ id: Schema.String, @@ -173,6 +168,8 @@ export interface DeviceHubOperationsOptions { readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect; /** A folder in the server's state dir for files a command must write (screenshots). */ readonly scratchDir: string; + /** Filesystem for scoped temp screenshot files (avoids sh/mktemp leaks on timeout). */ + readonly fs?: FileSystem.FileSystem; /** Kept by the host across hub starts, so a refresh does not ask simctl or adb again. */ readonly modelCache: DeviceModelCache; /** @@ -556,25 +553,69 @@ export const makeDeviceHubOperations = (options: DeviceHubOperationsOptions): De }, ); + // simctl needs a real file (it writes "-" or /dev/stdout as a file of that + // name), so the PNG passes through a scoped temp file in Threadlines' own + // state folder, removed even if the command times out or is interrupted. const defaultDisplayScreenshot = Effect.fn("DeviceHubOperations.defaultDisplayScreenshot")( function* (udid: string) { - const capture = yield* run( - "sh", - ["-c", DEFAULT_DISPLAY_SCREENSHOT, "sh", udid, options.scratchDir], - { - timeoutMs: Duration.toMillis(SCREENSHOT_TIMEOUT), - maxOutputBytes: 64 * 1024 * 1024, - }, - ); - if (capture.code !== 0) { + const fs = options.fs; + if (!fs) { return yield* new DeviceOperationError({ operation: "screenshot", reason: "command_failed", - exitCode: capture.code, - detail: boundDiagnostics(capture.stderr.trim()), + detail: "No filesystem available for fallback screenshot capture.", }); } - return new Uint8Array(Buffer.from(capture.stdout, "base64")); + return yield* Effect.scoped( + Effect.gen(function* () { + yield* fs.makeDirectory(options.scratchDir, { recursive: true }).pipe( + Effect.mapError( + () => + new DeviceOperationError({ + operation: "screenshot", + reason: "command_failed", + detail: "Could not prepare the temporary screenshot folder.", + }), + ), + ); + const file = yield* fs + .makeTempFileScoped({ directory: options.scratchDir, prefix: "screenshot-" }) + .pipe( + Effect.mapError( + () => + new DeviceOperationError({ + operation: "screenshot", + reason: "command_failed", + detail: "Could not create a temporary screenshot file.", + }), + ), + ); + const capture = yield* run( + "xcrun", + ["simctl", "io", udid, "screenshot", "--type=png", file], + { timeoutMs: Duration.toMillis(SCREENSHOT_TIMEOUT) }, + ); + if (capture.code !== 0) { + return yield* new DeviceOperationError({ + operation: "screenshot", + reason: "command_failed", + exitCode: capture.code, + detail: boundDiagnostics(capture.stderr.trim()), + }); + } + return yield* fs.readFile(file).pipe( + Effect.map((bytes) => new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)), + Effect.mapError( + () => + new DeviceOperationError({ + operation: "screenshot", + reason: "command_failed", + detail: "Could not read the captured screenshot file.", + }), + ), + ); + }), + ); }, ); diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 329e1116a..87148a558 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -7,6 +7,7 @@ import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import { ServerConfig } from "../config.ts"; @@ -83,7 +84,7 @@ const fakeHost = ( current: Effect.succeed(ready), releaseAgentSession: (session) => Effect.sync(() => released.push(session) > 0), stop: Effect.void, - stopAgent: Effect.void, + stopAgent: Effect.succeed(true), }); }; @@ -133,6 +134,168 @@ describe("DeviceService claims", () => { expect(yield* fs.readFileString(claimsPath)).not.toContain("SIM-1"); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); + + it.live("keeps unconfirmed daemon releases on pendingReleases and retries on next startup", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const base = yield* fs.makeTempDirectoryScoped({ prefix: "tl-device-pending-" }); + const claimsPath = path.join(base, "userdata", "device", "claims.json"); + let confirmRelease = false; + const attempts: Array = []; + const host = Layer.mock(DeviceHost.DeviceHost)({ + summary: Effect.succeed({ + platforms: [{ platform: "ios", available: true }], + hubInstalled: true, + agentDeviceInstalled: false, + tools: undefined, + toolInspectionError: undefined, + }), + platformAvailability: (platform) => Effect.succeed({ platform, available: true }), + ensureReady: () => + Effect.succeed({ + nodePath: process.execPath, + hub: { origin: "http://127.0.0.1:1", token: "token" }, + devices: { + list: Effect.succeed({ + devices: [ + { + id: "SIM-1", + platform: "ios", + name: "iPhone", + version: "iOS 27.2", + booted: true, + physical: false, + }, + ], + detail: undefined, + incompletePlatforms: [], + }), + boot: () => unused, + attach: () => Effect.void, + shutdown: () => unused, + screenshot: () => unused, + }, + run: () => Effect.succeed({ stdout: "", stderr: "", code: 0 }), + helpers: { serveSimAxSettings: null, serveSimCli: null }, + }), + current: Effect.succeed(null), + releaseAgentSession: (session) => + Effect.sync(() => { + attempts.push(session); + return confirmRelease; + }), + stop: Effect.void, + stopAgent: Effect.succeed(true), + }); + const layer = Layer.mergeAll( + host, + settingsLayer, + ServerConfig.layerTest(process.cwd(), base), + ); + + yield* Effect.scoped( + Effect.gen(function* () { + const service = yield* DeviceService.make; + yield* service.open({ threadId, deviceId: "SIM-1", platform: "ios" }, "user"); + yield* service.close({ threadId, deviceId: "SIM-1" }); + expect((yield* service.state).sessions).toEqual([]); + }), + ).pipe(Effect.provide(layer)); + + const expectedSession = agentDeviceSession(threadId, "SIM-1"); + expect(attempts).toEqual([expectedSession]); + expect(JSON.parse(yield* fs.readFileString(claimsPath))).toEqual({ + version: 1, + claims: [], + pendingReleases: [expectedSession], + }); + + confirmRelease = true; + yield* Effect.scoped( + Effect.gen(function* () { + yield* DeviceService.make; + yield* Effect.promise(() => + expect + .poll(() => + Effect.runPromise( + fs.readFileString(claimsPath).pipe(Effect.map((s) => JSON.parse(s))), + ), + ) + .toEqual({ version: 1, claims: [], pendingReleases: [] }), + ); + }), + ).pipe(Effect.provide(layer)); + expect(attempts).toEqual([expectedSession, expectedSession]); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.live( + "turning agent access off removes launchers and config and warns if daemon stays up", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const base = yield* fs.makeTempDirectoryScoped({ prefix: "tl-device-withdraw-" }); + const stateDir = path.join(base, "userdata"); + const configPath = path.join(stateDir, "device", "agent-device.json"); + const launcherDir = path.join(stateDir, "device", "bin", "thread-devices", "SIM-1"); + yield* fs.makeDirectory(launcherDir, { recursive: true }); + yield* fs.writeFileString(path.join(launcherDir, "agent-device"), "#!/bin/sh\n"); + yield* fs.writeFileString( + configPath, + '{"daemonBaseUrl":"http://127.0.0.1:1","daemonAuthToken":"t"}', + ); + + let currentSettings = { enableDevices: true, agentDeviceAccess: true }; + const settingsQueue = yield* Queue.unbounded(); + const pushSettings = (next: typeof currentSettings) => + Effect.sync(() => { + currentSettings = next; + }).pipe(Effect.andThen(Queue.offer(settingsQueue, next))); + const dynamicSettings = Layer.mock(ServerSettingsService)({ + getSettings: Effect.sync(() => currentSettings as never), + streamChanges: Stream.fromQueue(settingsQueue) as never, + }); + const host = Layer.mock(DeviceHost.DeviceHost)({ + summary: Effect.succeed({ + platforms: [{ platform: "ios", available: true }], + hubInstalled: true, + agentDeviceInstalled: true, + tools: undefined, + toolInspectionError: undefined, + }), + platformAvailability: (platform) => Effect.succeed({ platform, available: true }), + ensureReady: () => unused, + current: Effect.succeed(null), + releaseAgentSession: () => Effect.succeed(true), + stop: Effect.void, + stopAgent: Effect.succeed(false), + }); + const layer = Layer.mergeAll( + host, + dynamicSettings, + ServerConfig.layerTest(process.cwd(), base), + ); + + yield* Effect.scoped( + Effect.gen(function* () { + const service = yield* DeviceService.make; + yield* Effect.sleep("20 millis"); + yield* pushSettings({ enableDevices: true, agentDeviceAccess: false }); + yield* Effect.promise(() => + expect + .poll(() => + Effect.runPromise(service.state.pipe(Effect.map((s) => s.hostStatusDetail))), + ) + .toContain("Agent tools did not stop"), + ); + expect(yield* fs.exists(configPath)).toBe(false); + expect(yield* fs.exists(launcherDir)).toBe(false); + }), + ).pipe(Effect.provide(layer)); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); }); describe("DeviceService release during an open", () => { diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index ddb7202ac..7aebdf076 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -88,7 +88,14 @@ const DeviceClaim = Schema.Struct({ agentSession: Schema.String, }); type DeviceClaim = typeof DeviceClaim.Type; -const ClaimsFile = Schema.Struct({ version: Schema.Literal(1), claims: Schema.Array(DeviceClaim) }); +const ClaimsFile = Schema.Struct({ + version: Schema.Literal(1), + claims: Schema.Array(DeviceClaim), + /** agent-device sessions whose close the daemon did not confirm: tried again later. */ + pendingReleases: Schema.Array(Schema.String).pipe( + Schema.withDecodingDefault(Effect.succeed([] as ReadonlyArray)), + ), +}); const decodeClaimsFile = Schema.decodeUnknownEffect(Schema.fromJsonString(ClaimsFile)); const encodeClaimsFile = Schema.encodeUnknownEffect(Schema.fromJsonString(ClaimsFile)); @@ -118,6 +125,8 @@ export interface DeviceServiceShape { readonly threadId: ThreadId; readonly deviceId: DeviceId; readonly platform: DevicePlatform; + /** Skip the initial listing when the caller just refreshed devices. */ + readonly alreadyListed?: boolean; }) => Effect.Effect; /** Every session a thread holds, oldest first. */ readonly sessionsForThread: (threadId: ThreadId) => Effect.Effect>; @@ -191,24 +200,78 @@ export const make = Effect.gen(function* () { ); // Claims a previous run left. A file that can't be read is kept as it is and treated as none. - const loadedClaims = yield* fs.readFileString(claimsPath).pipe( + const loaded = yield* fs.readFileString(claimsPath).pipe( Effect.flatMap(decodeClaimsFile), - Effect.map((file) => file.claims), - Effect.catch(() => Effect.succeed([] as ReadonlyArray)), + Effect.catch(() => + Effect.succeed({ + claims: [] as ReadonlyArray, + pendingReleases: [] as ReadonlyArray, + }), + ), ); - const claims = new Map( - loadedClaims.map((claim) => [claim.agentSession, claim]), + // What claims.json holds. Changed only once the file says the same, so a + // failed write never leaves memory and disk telling different stories. + let claims: ReadonlyMap = new Map( + loaded.claims.map((claim) => [claim.agentSession, claim]), ); + let pendingReleases: ReadonlySet = new Set(loaded.pendingReleases); const claimsLock = yield* Semaphore.make(1); - const persistClaims = claimsLock.withPermit( - Effect.suspend(() => encodeClaimsFile({ version: 1, claims: [...claims.values()] })).pipe( - Effect.flatMap((contents) => writeFileStringAtomically({ filePath: claimsPath, contents })), - services, + const saveClaims = (update: { + readonly claims?: ReadonlyMap; + readonly pendingReleases?: ReadonlySet; + }) => + Effect.gen(function* () { + const nextClaims = update.claims ?? claims; + const nextPending = update.pendingReleases ?? pendingReleases; + const contents = yield* encodeClaimsFile({ + version: 1, + claims: [...nextClaims.values()], + pendingReleases: [...nextPending], + }); + yield* writeFileStringAtomically({ filePath: claimsPath, contents }).pipe(services); + claims = nextClaims; + pendingReleases = nextPending; + }).pipe( Effect.mapError( () => new DeviceOperationError({ operation: "save claim", reason: "settings_failed" }), ), - ), - ); + ); + /** Changes the claims under their lock, from the latest ones. */ + const changeClaims = ( + change: (current: { + readonly claims: ReadonlyMap; + readonly pendingReleases: ReadonlySet; + }) => { + readonly claims?: ReadonlyMap; + readonly pendingReleases?: ReadonlySet; + }, + ) => claimsLock.withPermit(Effect.suspend(() => saveClaims(change({ claims, pendingReleases })))); + + /** + * Ends every agent-device session on the pending list that the daemon now + * confirms. A session the daemon would not close stays listed, so the next + * close, agent tools starting, or the next server tries again. + */ + const retryPendingReleases = Effect.suspend(() => { + const names = [...pendingReleases]; + if (names.length === 0) return Effect.void; + return Effect.forEach( + names, + (name) => host.releaseAgentSession(name).pipe(Effect.map((done) => (done ? name : null))), + { concurrency: 4 }, + ).pipe( + Effect.flatMap((results) => { + const done = new Set(results.filter((name): name is string => name !== null)); + if (done.size === 0) return Effect.void; + return changeClaims((current) => ({ + pendingReleases: new Set([...current.pendingReleases].filter((name) => !done.has(name))), + })); + }), + Effect.catch((error) => + Effect.logWarning("Could not save device claims", { detail: error.message }), + ), + ); + }); const toSession = ({ agentSession: _agentSession, ...session }: DeviceClaim): DeviceSession => session; @@ -325,14 +388,24 @@ export const make = Effect.gen(function* () { "Agents can't use devices on this computer. Ask the user to turn on Use devices and Agents can use devices in Settings → Devices.", }); } + const wasReady = (yield* currentState).hostStatus === "ready"; const ready = yield* host .ensureAgentReady((phase, detail) => setHostStatus(phase, detail).pipe(Effect.asVoid)) .pipe( - Effect.tapError((error) => setHostStatus("failed", error.message)), + Effect.tapError((error) => + wasReady + ? host.current.pipe( + Effect.flatMap((hub) => + hub !== null ? setHostStatus("ready") : setHostStatus("failed", error.message), + ), + ) + : setHostStatus("failed", error.message), + ), Effect.mapError(hostUnavailable), ); yield* setHostStatus("ready"); yield* publishSummary; + yield* retryPendingReleases; return ready; }).pipe(lifecycleLock.withPermit, Effect.withSpan("DeviceService.agentReadiness")), ); @@ -430,19 +503,26 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, const recordSession = (session: DeviceSession, releasesAtStart: number) => Effect.gen(function* () { - if (!(yield* readDeviceSettings).enabled) { + const deviceSettings = yield* readDeviceSettings; + if (!deviceSettings.enabled) { return yield* new DeviceHostUnavailableError({ reason: "Devices were turned off while the device was opening.", }); } + if (session.openedBy === "agent" && !deviceSettings.agentAccessEnabled) { + return yield* new DeviceHostUnavailableError({ + reason: "Agent device access was turned off while the device was opening.", + }); + } if ((releaseCounts.get(session.threadId) ?? 0) !== releasesAtStart) { return yield* new DeviceHostUnavailableError({ reason: "The thread was put away while the device was opening.", }); } const agentSession = agentDeviceSession(session.threadId, session.deviceId); - claims.set(agentSession, { ...session, agentSession }); - yield* persistClaims; + yield* changeClaims((current) => ({ + claims: new Map([...current.claims, [agentSession, { ...session, agentSession }]]), + })); yield* publish((state) => ({ ...state, sessions: [ @@ -452,13 +532,21 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, })); }).pipe(lifecycleLock.withPermit); - const open: DeviceServiceShape["open"] = (input, openedBy = "user") => + const openInternal = ( + input: DeviceOpenInput, + openedBy: "user" | "agent", + skipInitialRefresh = false, + ) => Effect.gen(function* () { const releasesAtStart = releaseCounts.get(input.threadId) ?? 0; yield* ensurePlatform(input.platform); const ready = yield* readiness; - let state = yield* refresh(ready); - let device = findDevice(state, input.deviceId); + let state = yield* currentState; + let device = skipInitialRefresh ? findDevice(state, input.deviceId) : undefined; + if (!device) { + state = yield* refresh(ready); + device = findDevice(state, input.deviceId); + } if (!device) return yield* new DeviceNotFoundError({ deviceId: input.deviceId }); if (device.platform === "android" && !device.physical) yield* requireAndroidVideo(ready); let bootedNow = false; @@ -505,6 +593,9 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, return session; }).pipe(Effect.withSpan("DeviceService.open")); + const open: DeviceServiceShape["open"] = (input, openedBy = "user") => + openInternal(input, openedBy, false); + /** Removes launchers whose session is gone. Under the launcher lock, so binding never races it. */ const pruneLaunchers = launcherLock.withPermit( Effect.gen(function* () { @@ -517,30 +608,20 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, ); /** - * Ends sessions: their agent-device sessions first (which quits the app the - * agent opened and frees the device for others), then the claims, then the - * state and launchers. + * Ends sessions: drops their claims and queues their agent-device sessions on + * `pendingReleases` in one disk write, then updates state, prunes launchers, + * and tries to release them on the daemon. */ - const endSessions = (requested: ReadonlyArray) => + const endSessions = (ending: ReadonlyArray) => Effect.gen(function* () { - let ending = requested; if (ending.length === 0) return; - const released = yield* Effect.forEach( - ending, - (session) => - host.releaseAgentSession(agentDeviceSession(session.threadId, session.deviceId)), - { concurrency: 4 }, - ); - // A session whose close the daemon did not confirm stays claimed and open, - // so closing again (or the next startup's sweep) retries it. - ending = ending.filter((_, index) => released[index]); - if (ending.length === 0) return; - for (const session of ending) { - claims.delete(agentDeviceSession(session.threadId, session.deviceId)); - } - yield* persistClaims.pipe( - Effect.catch((error) => Effect.logWarning("Could not save device claims", { error })), - ); + const names = ending.map((session) => agentDeviceSession(session.threadId, session.deviceId)); + // The claims go first, and as one write: a session reported closed is closed on disk too. + // Their agent-device sessions wait on the pending list until the daemon confirms them. + yield* changeClaims((current) => ({ + claims: new Map([...current.claims].filter(([name]) => !names.includes(name))), + pendingReleases: new Set([...current.pendingReleases, ...names]), + })); yield* publish((state) => ({ ...state, sessions: state.sessions.filter( @@ -548,6 +629,7 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, ), })); yield* pruneLaunchers; + yield* retryPendingReleases; }); const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* ( @@ -653,17 +735,10 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, Effect.gen(function* () { // Consent and agent tools first, before anything boots or a session is recorded. const agentReady = yield* agentReadiness; - const session = yield* open(input, "agent"); + const session = yield* openInternal(input, "agent", input.alreadyListed === true); const device = findDevice(yield* currentState, session.deviceId); if (!device) return yield* new DeviceNotFoundError({ deviceId: session.deviceId }); const configPath = agentDeviceConfigPath(path, stateDir); - yield* writeAgentDeviceConfig(configPath, agentReady.agentDevice).pipe( - services, - Effect.mapError( - () => - new DeviceOperationError({ operation: "configure agent", reason: "settings_failed" }), - ), - ); const agentSession = agentDeviceSession(session.threadId, session.deviceId); const targetArgs = [ ...agentTargetArgs(device), @@ -674,9 +749,23 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, ]; const command = yield* launcherLock.withPermit( Effect.gen(function* () { + const deviceSettings = yield* readDeviceSettings; + if (!deviceSettings.enabled || !deviceSettings.agentAccessEnabled) { + return Option.none(); + } const { sessions } = yield* currentState; // Closed while it opened: no launcher for a session that is gone. if (!sessions.some((live) => sameSession(live, session))) return Option.none(); + yield* writeAgentDeviceConfig(configPath, agentReady.agentDevice).pipe( + services, + Effect.mapError( + () => + new DeviceOperationError({ + operation: "configure agent", + reason: "settings_failed", + }), + ), + ); return Option.some( yield* bindAgentDeviceLauncher({ stateDir, @@ -701,7 +790,7 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, if (Option.isNone(command)) { return yield* new DeviceHostUnavailableError({ reason: - "The device was closed while it was opening. Call device_open again only if you still need it.", + "The device was closed or agent access was turned off while it was opening. Call device_open again only if you still need it.", }); } return { device, session, command: command.value, agentSession }; @@ -743,6 +832,35 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, return yield* publishSummary; }).pipe(lifecycleLock.withPermit, Effect.withSpan("DeviceService.updateTool")); + /** + * Agent access off: every agent-device session is ended, every launcher and + * the daemon config they read are removed, then the daemon stops. A daemon + * that would not stop is reported, never assumed gone. + */ + const withdrawAgentAccess = Effect.gen(function* () { + yield* changeClaims((current) => ({ + pendingReleases: new Set([...current.pendingReleases, ...current.claims.keys()]), + })).pipe(Effect.ignore); + yield* retryPendingReleases; + yield* launcherLock.withPermit( + Effect.gen(function* () { + yield* pruneAgentDeviceLaunchers({ stateDir, live: new Set() }).pipe(services); + yield* fs + .remove(agentDeviceConfigPath(path, stateDir), { force: true }) + .pipe(Effect.ignore); + }), + ); + const stopped = yield* host.stopAgent; + if (stopped) { + yield* retryPendingReleases; + } else { + yield* setHostStatus( + (yield* currentState).hostStatus, + `Agent tools did not stop. Their logs are in ${path.join(deviceStateDir(path, stateDir), "agent-device")}; restarting Threadlines stops them.`, + ); + } + }); + /** "Use devices" off stops the hub and daemon (devices keep running); agent access off stops the daemon. */ const applySettings = (next: { readonly enabled: boolean; @@ -781,12 +899,22 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, if (!next.enabled) { yield* lifecycleLock.withPermit( Effect.gen(function* () { - yield* endSessions(previous.sessions); + const activeClaims = [...claims.values()].map(toSession); + yield* endSessions(activeClaims).pipe(Effect.ignore); + yield* launcherLock.withPermit( + Effect.gen(function* () { + yield* pruneAgentDeviceLaunchers({ stateDir, live: new Set() }).pipe(services); + yield* fs + .remove(agentDeviceConfigPath(path, stateDir), { force: true }) + .pipe(Effect.ignore); + }), + ); yield* host.stop; + yield* retryPendingReleases; }), ); } else if (!next.agentAccessEnabled && previous.agentAccessEnabled) { - yield* host.stopAgent; + yield* lifecycleLock.withPermit(withdrawAgentAccess); } // Agent access turned on: fetch agent-device now, in the background, so the // first device_open is quick. Nothing starts until an agent asks. @@ -806,13 +934,22 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`, enabled: value.enableDevices, agentAccessEnabled: value.agentDeviceAccess, })), - Stream.runForEach(applySettings), + // One change that fails (a claims write, say) must not end the watcher. + Stream.runForEach((next) => + applySettings(next).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Could not apply device settings", { cause }), + ), + ), + ), Effect.catchCause((cause) => Effect.logWarning("Device settings watcher stopped", { cause })), Effect.forkIn(scope), ); - // Launchers for sessions that no longer exist (the claims file is the record). + // Launchers for sessions that no longer exist (the claims file is the record), + // and agent-device sessions an earlier run could not end. yield* pruneLaunchers.pipe(Effect.ignore); + yield* retryPendingReleases.pipe(Effect.forkIn(scope)); // Stop the hub and daemon with the server. Devices keep running. yield* Effect.addFinalizer(() => host.stop); diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index 42ed656f5..48f63d1e3 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -438,13 +438,13 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { Effect.ignore, ); - const waitForReady = (origin: string) => + const waitForReady = (origin: string, token: string) => Effect.gen(function* () { const deadline = (yield* Clock.currentTimeMillis) + HUB_READY_TIMEOUT_MS; while (true) { const ok = yield* httpClient .pipe(HttpClient.withScope) - .get(`${origin}/readyz`) + .get(`${origin}/readyz`, { headers: { authorization: `Bearer ${token}` } }) .pipe( Effect.flatMap((response) => response.arrayBuffer.pipe(Effect.as(response.status === 200)), @@ -483,6 +483,12 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { const scope = yield* Scope.make("sequential"); // Not recorded yet: stop it on failure or interruption from the spawn on. return yield* Effect.gen(function* () { + // Refuse this port in the preview tunnel before the hub binds it, on every platform. + setOwnDeviceToolPort("hub", reserved); + yield* Scope.addFinalizer( + scope, + Effect.sync(() => setOwnDeviceToolPort("hub", null, reserved)), + ); const node = yield* leaseDeviceNode(stateDir).pipe( Effect.provideService(Scope.Scope, scope), services, @@ -516,8 +522,15 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { detail: "The device hub did not print its startup line. Update it in Settings → Devices.", }); } + if (announced.value.port !== reserved) { + setOwnDeviceToolPort("hub", announced.value.port); + yield* Scope.addFinalizer( + scope, + Effect.sync(() => setOwnDeviceToolPort("hub", null, announced.value.port)), + ); + } const origin = `http://127.0.0.1:${announced.value.port}`; - yield* waitForReady(origin); + yield* waitForReady(origin, announced.value.token); const hub: HubProcess = { child, scope, @@ -527,12 +540,6 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { nodePath: node.node, }; yield* recordHub(hub, hubTool); - // The preview tunnel refuses this port while the hub has it, on every platform. - setOwnDeviceToolPort("hub", announced.value.port); - yield* Scope.addFinalizer( - scope, - Effect.sync(() => setOwnDeviceToolPort("hub", null, announced.value.port)), - ); yield* Effect.logInfo("Device hub started", { pid: Number(child.pid), port: announced.value.port, @@ -541,31 +548,42 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { }).pipe(Effect.onError(() => Scope.close(scope, Exit.void).pipe(Effect.ignore))); }); + const lines = ( + stream: Stream.Stream, + onLine: (line: string) => Effect.Effect, + ) => stream.pipe(Stream.decodeText(), Stream.splitLines, Stream.runForEach(onLine)); + + const logHubLine = (child: ChildProcessSpawner.ChildProcessHandle, line: string) => { + const text = line.trim(); + return text.length === 0 + ? Effect.void + : Effect.logDebug("Device hub output", { + pid: Number(child.pid), + output: redactHubLine(text), + }); + }; + const observeHubOutput = ( child: ChildProcessSpawner.ChildProcessHandle, started: Deferred.Deferred<{ readonly port: number; readonly token: string }>, ) => - child.all.pipe( - Stream.decodeText(), - Stream.splitLines, - Stream.runForEach((line) => - Effect.gen(function* () { - const startup = parseHubStartupLine(line); - if (startup) { - yield* Deferred.succeed(started, startup); - return; - } - const text = line.trim(); - if (text.length > 0) { - yield* Effect.logDebug("Device hub output", { - pid: Number(child.pid), - output: redactHubLine(text), - }); - } - }), - ), - Effect.ignoreCause, - ); + Effect.all( + [ + // The token is taken only from stdout, where the hub prints its startup line. + lines(child.stdout, (line) => + Effect.gen(function* () { + const startup = parseHubStartupLine(line); + if (startup) { + yield* Deferred.succeed(started, startup); + return; + } + yield* logHubLine(child, line); + }), + ), + lines(child.stderr, (line) => logHubLine(child, line)), + ], + { concurrency: "unbounded", discard: true }, + ).pipe(Effect.ignoreCause); // Waits for the hub's lifetime and starts a replacement with backoff; a span would nest across restarts. const superviseHub: (hub: HubProcess, hubTool: DeviceToolPaths) => Effect.Effect = @@ -585,16 +603,29 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { delayMs: delay, }); yield* stopHub(hub); - yield* Effect.sleep(Duration.millis(delay)); - yield* startLock.withPermits(1)( - Effect.gen(function* () { - const current = yield* Ref.get(runningRef); - if (current?.hub.child.pid !== hub.child.pid) return; - const replacement = yield* spawnHub(hubTool); - yield* Ref.set(runningRef, { ...current, hub: replacement }); - yield* Effect.forkDetach(superviseHub(replacement, hubTool)); - }), - ); + // Tries again with backoff until a replacement starts, or the hub is stopped or replaced. + let wait = delay; + while (true) { + yield* Effect.sleep(Duration.millis(wait)); + const outcome = yield* startLock.withPermits(1)( + Effect.gen(function* () { + const current = yield* Ref.get(runningRef); + if (current?.hub.child.pid !== hub.child.pid) return "done" as const; + const replacement = yield* spawnHub(hubTool); + yield* Ref.set(runningRef, { ...current, hub: replacement }); + yield* Effect.forkDetach(superviseHub(replacement, hubTool)); + return "done" as const; + }).pipe( + Effect.catch((error) => + Effect.logWarning("Device hub restart failed; trying again", { + detail: error.message, + }).pipe(Effect.as("retry" as const)), + ), + ), + ); + if (outcome === "done") return; + wait = Math.min(Math.max(wait * 2, 1_000), HUB_RESTART_MAX_DELAY_MS); + } }, Effect.catchCause((cause) => Effect.logWarning("Device hub supervisor failed", { cause })), ); @@ -710,28 +741,34 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { } }); - // The daemon may predate this process (an earlier server was killed, possibly on an - // older pin), so it is stopped with the CLI of its recorded version when that is installed. - const stopAgentDeviceDaemon = Effect.gen(function* () { - setOwnDeviceToolPort("agent", null); - if (!(yield* fs.exists(daemonFilePath).pipe(Effect.orElseSucceed(() => false)))) return; + /** + * Stops the daemon with the CLI of its recorded version when that is + * installed: it may predate this process (an earlier server was killed, + * possibly on an older pin). True once no daemon runs for this state + * folder; false when one may still be running. + */ + const stopAgentDeviceDaemon: Effect.Effect = Effect.gen(function* () { const recorded = yield* readDaemonFile; - if ( - Option.isSome(recorded) && - recorded.value.pid && - !(yield* isProcessAlive(recorded.value.pid)) - ) { - return yield* fs.remove(daemonFilePath, { force: true }); + if (Option.isNone(recorded)) { + setOwnDeviceToolPort("agent", null); + return true; } + const pid = recorded.value.pid; + const forget = Effect.gen(function* () { + setOwnDeviceToolPort("agent", null, recorded.value.httpPort); + yield* fs.remove(daemonFilePath, { force: true }).pipe(Effect.ignore); + return true; + }); + if (pid !== undefined && !(yield* isProcessAlive(pid))) return yield* forget; const entryPath = yield* installedAgentDeviceEntry(stateDir, [ - ...(Option.isSome(recorded) && recorded.value.version ? [recorded.value.version] : []), + ...(recorded.value.version ? [recorded.value.version] : []), AGENT_DEVICE_VERSION, ]).pipe(withPath, services); - if (!entryPath) return; - yield* Effect.scoped( + if (!entryPath) return false; + const result = yield* Effect.scoped( Effect.gen(function* () { const node = yield* leaseDeviceNode(stateDir).pipe(services, withPath); - yield* runner.run({ + return yield* runner.run({ command: node.node, args: [entryPath, "daemon", "stop", "--state-dir", agentDeviceStateDir(path, stateDir)], env: { ...(yield* currentHostEnvironment), AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1" }, @@ -739,8 +776,25 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { timeoutBehavior: "timedOutResult", }); }), - ); - }).pipe(Effect.ignore); + ).pipe(Effect.option); + // The CLI's word is not enough: the daemon is stopped once its pid is gone. + if (pid === undefined) { + if (Option.isNone(result) || result.value.code !== 0) return false; + } else { + const deadline = (yield* Clock.currentTimeMillis) + 5_000; + while (yield* isProcessAlive(pid)) { + if ((yield* Clock.currentTimeMillis) > deadline) { + yield* Effect.logWarning("agent-device daemon did not stop", { + pid, + exitCode: Option.isSome(result) ? result.value.code : null, + }); + return false; + } + yield* Effect.sleep(Duration.millis(100)); + } + } + return yield* forget; + }).pipe(Effect.orElseSucceed(() => false)); const serveSimHelpers = Effect.fn("LocalDeviceHost.serveSimHelpers")(function* ( hubTool: DeviceToolPaths, @@ -842,6 +896,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { platformAvailable: (platform) => platformAvailability(platform).pipe(Effect.map((availability) => availability.available)), scratchDir: path.join(deviceStateDir(path, stateDir), "tmp"), + fs, androidAvds: { home: androidAvdHome(environment, path), readTextFile: (file) => @@ -891,39 +946,56 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { }), ); + // Only a hub that is running: a dead one's address may belong to something else by now. const current: DeviceHost.DeviceHost["Service"]["current"] = Ref.get(runningRef).pipe( - Effect.map((running) => (running ? toReady(running) : null)), + Effect.flatMap((running) => + running + ? running.hub.child.isRunning.pipe( + Effect.orElseSucceed(() => false), + Effect.map((alive) => (alive ? toReady(running) : null)), + ) + : Effect.succeed(null), + ), ); const releaseAgentSession: DeviceHost.DeviceHost["Service"]["releaseAgentSession"] = (session) => Effect.gen(function* () { + const file = yield* readDaemonFile; + // No daemon for this state folder, or its process is gone: its sessions went with it. + if (Option.isNone(file)) return true; + if (file.value.pid !== undefined && !(yield* isProcessAlive(file.value.pid))) { + setOwnDeviceToolPort("agent", null, file.value.httpPort); + yield* fs.remove(daemonFilePath, { force: true }).pipe(Effect.ignore); + yield* Ref.update(runningRef, (running) => + running ? { ...running, agentDevice: null } : running, + ); + return true; + } const running = yield* Ref.get(runningRef); - const endpoint = - running?.agentDevice ?? - (yield* readDaemonFile.pipe( - Effect.map((file) => - Option.isSome(file) - ? { baseUrl: `http://127.0.0.1:${file.value.httpPort}`, token: file.value.token } - : null, + const endpoint = running?.agentDevice ?? { + baseUrl: `http://127.0.0.1:${file.value.httpPort}`, + token: file.value.token, + }; + return yield* releaseAgentDeviceSession( + httpClient, + endpoint, + )(session).pipe( + Effect.as(true), + Effect.catch((cause) => + Effect.logWarning("Could not end the agent-device session", { session, cause }).pipe( + Effect.as(false), ), - )); - if (!endpoint) return true; - yield* releaseAgentDeviceSession(httpClient, endpoint)(session); - return true; - }).pipe( - Effect.catch((cause) => - Effect.logWarning("Could not end the agent-device session", { session, cause }).pipe( - Effect.as(false), ), - ), - ); + ); + }); const stopAgent: DeviceHost.DeviceHost["Service"]["stopAgent"] = startLock.withPermits(1)( Effect.gen(function* () { - yield* stopAgentDeviceDaemon; + const stopped = yield* stopAgentDeviceDaemon; yield* Ref.update(runningRef, (running) => running ? { ...running, agentDevice: null } : running, ); + return stopped; }), ); @@ -933,9 +1005,13 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { // Hub cleanup waits for its exit; it must not strand the detached agent daemon. yield* Effect.all( [ - stopHub(running?.hub).pipe( - Effect.andThen(fs.remove(hubStatePath, { force: true }).pipe(Effect.ignore)), - ), + // No hub of ours: one an earlier run left may still be recorded, so reap it + // rather than forget its pid. + running + ? stopHub(running.hub).pipe( + Effect.andThen(fs.remove(hubStatePath, { force: true }).pipe(Effect.ignore)), + ) + : reapStaleHub, stopAgentDeviceDaemon, ], { concurrency: "unbounded", discard: true }, @@ -969,6 +1045,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { }); yield* Effect.addFinalizer(() => stop); + // A hub an earlier run left behind holds a token nobody has any more: stop it now. + yield* reapStaleHub.pipe(Effect.forkDetach); return DeviceHost.DeviceHost.of({ summary, diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 5aae2bc98..f5b6762ee 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -443,8 +443,16 @@ Every computer has its own set: the menu groups projects under each computer's n "iphone duo", "foldable", "accessibility frames", + "record", + "recording", + "float", + "floating", + "chips", + "event log", ], - body: `The Device tab in the right panel shows a live iOS Simulator or Android Emulator running on the thread's computer. You tap, swipe and type on its screen as on a phone. The screen sits in a drawing of the device's model (an unknown model gets a plain frame). The toolbar above it has Home, the app switcher, Back and Recents on Android, rotate, screenshot, accessibility frames and power off. Accessibility frames outline each element on screen and show its label on hover; their Inspect button makes a tap show the label instead of touching the device. An iPhone Duo shows its stance buttons beside the screen (closed, book, open, laptop, tent, and table mode where offered), and an Android foldable shows fold and unfold. The Tools drawer sets appearance, text size, accessibility options, location and permissions, opens a URL, launches or quits an app, shakes the device, sends a test push, and on Android sets the network. + body: `The Device tab in the right panel shows a live iOS Simulator or Android Emulator running on the thread's computer. You tap, swipe and type on its screen as on a phone (touch screens also get a Keyboard button). The screen sits in a drawing of the device's model (an unknown model gets a plain frame). You can open several devices at once in a thread: each open device is a chip across the top (rename from its menu or by double-clicking, + opens the picker), and only the visible one streams. The Float button moves a device into a small draggable, resizable window over the chat while the right panel shows something else; Open in right panel brings it back (floating is hidden in the phone layout). + +The toolbar above the screen has Home, the app switcher, Back and Recents on Android, rotate, save screenshot, record a flow, float, accessibility frames, Tools, and a More menu with Close device and Power off. Record a flow captures taps, buttons, Tools actions, key screenshots and a video of the screen (up to 3 minutes or 10 MB) and appends them to the thread's unsent draft; any file the draft cannot save stays available to download in the Device tab. Accessibility frames outline each element on screen and show its label on hover; their Inspect button makes a tap show the label instead of touching the device. An iPhone Duo shows its stance buttons beside the screen (closed, book, open, laptop, tent, and table mode where offered), and an Android foldable shows fold and unfold. The Tools drawer sets appearance, text size, accessibility options, location and permissions, opens a URL, launches or quits an app, shakes an iOS simulator, sends a test push and streams the event log on iOS, and sets the network on Android. Open it from the right panel's + menu or its launcher, or with Open device in the command palette. It shows in project threads, not General Chats. diff --git a/apps/server/src/mcp/deviceToolHandlers.ts b/apps/server/src/mcp/deviceToolHandlers.ts index 461c55254..e04631da9 100644 --- a/apps/server/src/mcp/deviceToolHandlers.ts +++ b/apps/server/src/mcp/deviceToolHandlers.ts @@ -162,6 +162,7 @@ export const deviceOpen = (caller: McpInvocationScope, input: DeviceToolOpenInpu threadId: caller.threadId, deviceId: target.id, platform: target.platform, + alreadyListed: true, }); return { device: opened.device, diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 237e2f35d..4c2a07cd4 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -855,7 +855,7 @@ export function buildTurnStartParams(input: { ? { agentPageAssetsDir: input.agentPageAssetsDir } : {}), ...(input.commandRequests ? { commandRequests: true } : {}), - ...(input.deviceTools ? { deviceTools: true } : {}), + ...(input.deviceTools && !input.lockdown ? { deviceTools: true } : {}), ...(input.scheduleTools && !input.lockdown ? { scheduleTools: true } : {}), ...(input.guide && !input.lockdown ? { guide: true } : {}), }); diff --git a/apps/server/src/provider/codexAppServerArgs.test.ts b/apps/server/src/provider/codexAppServerArgs.test.ts index 0b7a62659..3ae6e0ed0 100644 --- a/apps/server/src/provider/codexAppServerArgs.test.ts +++ b/apps/server/src/provider/codexAppServerArgs.test.ts @@ -1,6 +1,10 @@ import { assert, it } from "@effect/vitest"; -import { CODEX_APP_SERVER_ARGS, codexAppServerArgs } from "./codexAppServerArgs.ts"; +import { + CODEX_APP_SERVER_ARGS, + CODEX_DEVICE_TOOL_TIMEOUT_SEC, + codexAppServerArgs, +} from "./codexAppServerArgs.ts"; it("suppresses the warning for Threadlines' intentional unstable Codex features", () => { assert.deepStrictEqual(CODEX_APP_SERVER_ARGS, [ @@ -22,3 +26,14 @@ it("approves the page tools without asking, and only them", () => { assert.include(args, 'mcp_servers.threadlines_pages.default_tools_approval_mode="approve"'); assert.notInclude(args, 'mcp_servers.threadlines_browser.default_tools_approval_mode="approve"'); }); + +it("gives the device server a longer tool timeout for installs and cold boots", () => { + const args = codexAppServerArgs({ + device: { url: "http://127.0.0.1:1/mcp/device", serverName: "threadlines_device" }, + }); + assert.include(args, 'mcp_servers.threadlines_device.default_tools_approval_mode="approve"'); + assert.include( + args, + `mcp_servers.threadlines_device.tool_timeout_sec=${CODEX_DEVICE_TOOL_TIMEOUT_SEC}`, + ); +}); diff --git a/apps/server/src/provider/codexAppServerArgs.ts b/apps/server/src/provider/codexAppServerArgs.ts index c39db102f..4b9985e08 100644 --- a/apps/server/src/provider/codexAppServerArgs.ts +++ b/apps/server/src/provider/codexAppServerArgs.ts @@ -70,6 +70,13 @@ export const CODEX_BROWSER_TOKEN_ENV_VAR = "THREADLINES_MCP_BEARER_TOKEN"; */ export const CODEX_ROOM_TOOL_TIMEOUT_SEC = Duration.toSeconds(ROOM_TOOL_CALL_TIMEOUT); +/** + * How long Codex waits on one device tool call (its own default is 60s). + * A first `device_open` can install expo-device-hub / agent-device and cold-boot + * a simulator or emulator (up to 3 min boot timeout). + */ +export const CODEX_DEVICE_TOOL_TIMEOUT_SEC = 300; + /** An MCP server over streamable HTTP, its credential from the environment. */ const httpMcpServerArgs = (serverName: string, url: string): ReadonlyArray => [ "-c", @@ -132,7 +139,18 @@ export function codexAppServerArgs(servers?: { ...(servers?.room !== undefined ? codexRoomServerArgs(servers.room) : []), ...(servers?.pages !== undefined ? codexPagesServerArgs(servers.pages) : []), ...(servers?.commands !== undefined ? codexPagesServerArgs(servers.commands) : []), - ...(servers?.device !== undefined ? codexPagesServerArgs(servers.device) : []), + ...(servers?.device !== undefined ? codexDeviceServerArgs(servers.device) : []), + ]; +} + +function codexDeviceServerArgs(device: { + readonly url: string; + readonly serverName: string; +}): ReadonlyArray { + return [ + ...codexPagesServerArgs(device), + "-c", + `mcp_servers.${device.serverName}.tool_timeout_sec=${CODEX_DEVICE_TOOL_TIMEOUT_SEC}`, ]; } diff --git a/docs/design/devices.md b/docs/design/devices.md index de4e86326..b0722d2e2 100644 --- a/docs/design/devices.md +++ b/docs/design/devices.md @@ -455,11 +455,18 @@ user-only (`widensAgents`). Windows and without `pgrep`, where the process scan cannot run. - `device_open` never picks a physical phone by default; an agent gets one only by naming its id. -- A session whose close the daemon did not confirm stays claimed and open, so - a second close or the next startup sweep retries it. An open that finishes - after its thread was put away records nothing (a release count per thread). +- A session whose close the daemon did not confirm moves to `pendingReleases` + in `claims.json` (and drops from active claims right away), so the next + close, agent tools starting, or the next server retries it. A dead daemon + is checked by PID so a stale `daemon.json` never wedges closing. An open + that finishes after its thread was put away or agent access turned off + records nothing. +- The bound `agent-device` launcher refuses an agent's own `--session`, + `-s`, device, or daemon flags so every session it opens is one Threadlines + ends, and strips `--serial` alongside `--udid` for `cdp` / `connection`. - Turning a switch off publishes the new state before stopping anything, so - the agent tools refuse from that moment. + the agent tools refuse from that moment; turning agent access off removes + every launcher and `agent-device.json` and verifies the daemon PID exited. - The state stream slides: a subscriber that stops reading keeps only the newest two snapshots. - The iOS screenshot fallback writes through a temp file in From e730c3c4b7afd96280b5d6e91bbe29f014f56724 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:19:38 -0500 Subject: [PATCH 2/2] test(web): wait for highlight note focus before typing in AgentPageFrame TranscriptSelectionPopover focuses its note textarea inside requestAnimationFrame after Add note is clicked. On busy CI runners, userEvent.keyboard started typing before that frame ran, dropping characters or leaving the note empty so toggling Source dismissed it. Wait for the note input to have focus before typing. --- apps/web/src/components/chat/AgentPageFrame.browser.tsx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/chat/AgentPageFrame.browser.tsx b/apps/web/src/components/chat/AgentPageFrame.browser.tsx index 4d19d463f..bf4fdb431 100644 --- a/apps/web/src/components/chat/AgentPageFrame.browser.tsx +++ b/apps/web/src/components/chat/AgentPageFrame.browser.tsx @@ -366,6 +366,7 @@ describe("AgentPageRow", () => { await expect.element(addNote).toBeVisible(); await addNote.click(); + await expect.element(page.getByPlaceholder("Add context for this highlight")).toHaveFocus(); await userEvent.keyboard("This one failed"); await page.getByRole("button", { name: "Add", exact: true }).click(); expect(onAddHighlight).toHaveBeenCalledWith({ @@ -427,7 +428,9 @@ describe("AgentPageRow", () => { await expect.poll(actionsBelowFrameTop).toBeGreaterThan(265); // Escape in the note, even on its buttons, closes the note, not the full-size view. + const noteInput = dialog.getByPlaceholder("Add context for this highlight"); await addNote.click(); + await expect.element(noteInput).toHaveFocus(); await userEvent.keyboard("Discontinued"); await userEvent.keyboard("{Tab}"); await expect.element(dialog.getByRole("button", { name: "Cancel" })).toHaveFocus(); @@ -440,15 +443,15 @@ describe("AgentPageRow", () => { await dialog.getByRole("button", { name: /^Zoom 125%/ }).click(); await pastTypingWindow(); await line.tripleClick(); + await expect.element(addNote).toBeVisible(); await addNote.click(); + await expect.element(noteInput).toHaveFocus(); await userEvent.keyboard("Discontinued"); // A look at the source keeps the note being written. const source = dialog.getByRole("button", { name: "Source" }); await source.click(); await source.click(); - await expect - .element(dialog.getByPlaceholder("Add context for this highlight")) - .toHaveValue("Discontinued"); + await expect.element(noteInput).toHaveValue("Discontinued"); await dialog.getByRole("button", { name: "Add", exact: true }).click(); expect(onAddHighlight).toHaveBeenCalledWith({ sourceMessageId: version.pageId,