diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 69dc53dc4393f..56e3f03525e01 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,7 +1,7 @@ # Security policy Report security vulnerabilities affecting T3 Code or T3 Tools-operated infrastructure to -[security@ping.gg](mailto:security@ping.gg). Please do not disclose them publicly until we have had +[security@t3.codes](mailto:security@t3.codes). Please do not disclose them publicly until we have had a reasonable opportunity to investigate and remediate them. See the [full security policy](https://t3.codes/security-policy) for reporting details, scope, diff --git a/.github/actions/setup-ci-deps/action.yml b/.github/actions/setup-ci-deps/action.yml index e9b7ae70a36ad..b4fe25fab83fd 100644 --- a/.github/actions/setup-ci-deps/action.yml +++ b/.github/actions/setup-ci-deps/action.yml @@ -123,10 +123,12 @@ runs: key: ${{ steps.pnpm_verified.outputs.cache-primary-key }} # A filtered install that started from the current full store adds nothing - # worth a second copy of it. + # worth a second copy of it. A stacked PR, based on a branch other than the + # default, saves a ~1 GB store only its own reruns can read, so it only restores. - name: Save pnpm store if: >- inputs.install == 'true' && + (github.event_name != 'pull_request' || github.base_ref == github.event.repository.default_branch) && steps.pnpm_cache.outputs.cache-hit != 'true' && (steps.pnpm_store.outputs.namespace == 'full' || steps.pnpm_cache.outputs.cache-matched-key != format('pnpm-full-v1-{0}-{1}-{2}', runner.os, runner.arch, hashFiles('pnpm-lock.yaml', 'pnpm-workspace.yaml', 'package.json'))) diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.yml index 11d43b37bc428..b7851bd836dce 100644 --- a/.github/workflows/release-desktop.yml +++ b/.github/workflows/release-desktop.yml @@ -538,6 +538,8 @@ jobs: name: cli-${{ inputs.platform }}-${{ inputs.arch }} path: release-cli/* if-no-files-found: error + # The archive is already gzip or zip; deflating it again saves under 2%. + compression-level: 0 - uses: ./.github/actions/setup-apt-mirrors if: inputs.platform == 'linux' @@ -924,6 +926,8 @@ jobs: name: desktop-${{ inputs.platform }}-${{ inputs.arch }} path: release-publish/* if-no-files-found: error + # Installers, zips and blockmaps are already compressed; deflating them again saves under 0.3%. + compression-level: 0 - name: Upload resource monitor uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index c995f261bd17d..10cc29e6d2ccf 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -25,6 +25,12 @@ export default defineConfig({ dependsOn: ["t3#build"], cache: false, }, + // CI bundle jobs skip the Linux browser secret helper; packaging stages one per arch. + "build:bundle": { + command: "node scripts/build-preview-annotation-css.mjs && vp pack", + dependsOn: ["t3#build"], + cache: false, + }, dev: { command: "node scripts/build-browser-secret.mjs && node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch", diff --git a/apps/marketing/astro.config.mjs b/apps/marketing/astro.config.mjs index 87f85c01c77db..29f6bc47f7ca0 100644 --- a/apps/marketing/astro.config.mjs +++ b/apps/marketing/astro.config.mjs @@ -11,6 +11,8 @@ export default defineConfig({ process.env.S2CODE_MARKETING_URL?.trim() || process.env.SHUV2CODE_MARKETING_URL?.trim() || undefined, + // Vercel 308s `/path/` to `/path` (see vercel.ts), so every internal link and canonical uses one form. + trailingSlash: "never", server: { port: Number(process.env.PORT ?? 4173), }, diff --git a/apps/marketing/src/pages/security-policy.astro b/apps/marketing/src/pages/security-policy.astro index 22ee02449123e..fda5c6f1ac9aa 100644 --- a/apps/marketing/src/pages/security-policy.astro +++ b/apps/marketing/src/pages/security-policy.astro @@ -17,8 +17,8 @@ const sections = [ description="How to report security issues in T3 Code and how T3 Tools approaches product security." heading="T3 Code Security Policy" lede="Security is a shared responsibility. This policy explains how to report a vulnerability, how we protect T3 Tools-operated services, and how you can secure the environments and providers you connect to T3 Code." - effectiveDate="2026-07-15" - lastUpdated="2026-07-15" + effectiveDate="2026-11-06" + lastUpdated="2026-11-06" sections={sections} >
@@ -46,7 +46,7 @@ const sections = [

Reporting Security Issues

If you believe you have found a security vulnerability affecting T3 Code or T3 Tools-operated - infrastructure, email{" "}security@ping.gg. Please do not + infrastructure, email{" "}security@t3.codes. Please do not disclose the issue publicly until we have had a reasonable opportunity to investigate and remediate it.

@@ -176,7 +176,7 @@ const sections = [

Contact Us

Report security issues or ask security-related questions at{" "}security@ping.ggsecurity@t3.codes.

diff --git a/apps/marketing/vercel.ts b/apps/marketing/vercel.ts index e785d6f6b99a4..4d9782ef3329d 100644 --- a/apps/marketing/vercel.ts +++ b/apps/marketing/vercel.ts @@ -7,6 +7,8 @@ export const config: VercelConfig = { installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing...'", buildCommand: "vp run --filter @t3tools/marketing build", outputDirectory: "dist", + // One URL per page: `/download/` and `/download` both served 200 before, which splits ranking signals. + trailingSlash: false, // curl | sh requires plain, uncompressed scripts with no cache across deploys. headers: [ { diff --git a/apps/server/scripts/cli.ts b/apps/server/scripts/cli.ts index b56a629cc34c1..178586c258c58 100644 --- a/apps/server/scripts/cli.ts +++ b/apps/server/scripts/cli.ts @@ -18,6 +18,7 @@ import rootPackageJson from "../../../package.json" with { type: "json" }; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { + ServerCliBootstrapTooLargeError, ServerCliBuildAssetMissingError, ServerCliCommandExitError, ServerCliDevelopmentIconSourceMissingError, @@ -138,30 +139,48 @@ const buildExeCmd = Command.make( (yield* HostProcess.Platform) === "linux" && (yield* HostProcess.Architecture) === "arm64"; const spawnCommand = yield* resolveSpawnCommand("vp", ["pack"]); - yield* runCommand( - ChildProcess.make(spawnCommand.command, spawnCommand.args, { - cwd: serverDir, - env: { - ...process.env, - T3CODE_PACK_EXE: linuxArm64 ? "bundle" : "1", - T3CODE_PACK_EXE_TARGET: target ?? "", - }, - stdout: config.verbose ? "inherit" : "ignore", - stderr: "inherit", - shell: spawnCommand.shell, - }), - ); + const cliAssetDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-asset-" }); + const pack = (packMode: "bundle" | "bootstrap" | "1") => + runCommand( + ChildProcess.make(spawnCommand.command, spawnCommand.args, { + cwd: serverDir, + env: { + ...process.env, + T3CODE_PACK_EXE: packMode, + T3CODE_CLI_ASSET_DIR: cliAssetDir, + T3CODE_PACK_EXE_TARGET: target ?? "", + }, + stdout: config.verbose ? "inherit" : "ignore", + stderr: "inherit", + shell: spawnCommand.shell, + }), + ); + + yield* pack("bundle"); + const cliMainPath = path.join(cliAssetDir, "binMain.mjs"); + yield* pack(linuxArm64 ? "bootstrap" : "1"); // Executables reject non-builtin imports even when bundling succeeds; inspect the emitted graph. - const bundlePath = path.join(serverDir, "dist-exe/bin.mjs"); - const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath)); - if (specifiers.length > 0) { - return yield* new ServerCliExecutableImportError({ bundlePath, specifiers }); + const bootstrapPath = path.join(serverDir, "dist-exe/bin.mjs"); + for (const bundlePath of [bootstrapPath, cliMainPath]) { + const specifiers = findEsmImportsOfExternalPackages(yield* fs.readFileString(bundlePath)); + if (specifiers.length > 0) { + return yield* new ServerCliExecutableImportError({ bundlePath, specifiers }); + } + } + // The service launcher's memory win depends on the CLI staying out of the bootstrap. + const bootstrapBytes = (yield* fs.stat(bootstrapPath)).size; + if (bootstrapBytes > 1024 * 1024) { + return yield* new ServerCliBootstrapTooLargeError({ + bootstrapPath, + bytes: Number(bootstrapBytes), + }); } // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048 if (linuxArm64) { yield* injectLinuxArm64Sea({ - bundlePath, + bundlePath: bootstrapPath, + cliAssetPath: cliMainPath, outputPath: path.join(serverDir, "dist-exe/t3"), nodeVersion: rootPackageJson.engines.node, verbose: config.verbose, diff --git a/apps/server/scripts/cliErrors.ts b/apps/server/scripts/cliErrors.ts index 1c9a9ff5ce197..fa3927f492a06 100644 --- a/apps/server/scripts/cliErrors.ts +++ b/apps/server/scripts/cliErrors.ts @@ -66,3 +66,15 @@ export class ServerCliExecutableImportError extends Schema.TaggedError()( + "ServerCliBootstrapTooLargeError", + { + bootstrapPath: Schema.String, + bytes: Schema.Number, + }, +) { + override get message(): string { + return `${this.bootstrapPath} is ${this.bytes} bytes. The CLI was bundled into the executable bootstrap; keep ./binMain.ts external.`; + } +} diff --git a/apps/server/src/bin.ts b/apps/server/src/bin.ts index 112add39ca0f2..2e29b8e0e22de 100644 --- a/apps/server/src/bin.ts +++ b/apps/server/src/bin.ts @@ -1,12 +1,35 @@ -/** - * Every ACP agent spawns `t3 acp-mcp-bridge` while opening its session, and terminal-fallback - * agents run `t3 acp-mcp-call` per tool call, so their startup sits on first-message latency. - * They and Codex's managed-token helper dispatch before the full CLI module graph (seconds - * of evaluation) loads; everything else defers to the real CLI in ./binCli.ts. - */ +// @effect-diagnostics nodeBuiltinImport:off -- The service launcher starts before the CLI runtime. +import * as NodeModule from "node:module"; +import * as NodeSea from "node:sea"; +import * as NodeURL from "node:url"; + import { isEntrypoint } from "./entrypoint.ts"; import { applyProductEnvironment } from "@t3tools/shared/productIdentity"; -import { enableCliCompileCache } from "./cliCompileCache.ts"; + +// Loads the CLI outside the launcher's module graph. Packaged builds embed it as a raw asset. +async function loadCliMain(): Promise { + if (!NodeSea.isSea()) return import("./binMain.ts"); + + // Keep the executable's module URL so the CLI finds the web client and native packages beside it. + const require = NodeModule.createRequire(import.meta.url); + // require() resolves links in the executable path, such as a Windows junction. + const cliUrl = NodeURL.pathToFileURL(require.resolve(process.execPath)).href; + const hook = NodeModule.registerHooks({ + load(url, context, next) { + if (url !== cliUrl) return next(url, context); + return { + format: "module", + source: new Uint8Array(NodeSea.getRawAsset("binMain.mjs")), + shortCircuit: true, + }; + }, + }); + try { + return require(process.execPath) as typeof import("./binMain.ts"); + } finally { + hook.deregister(); + } +} if ( isEntrypoint({ @@ -16,42 +39,13 @@ if ( }) ) { applyProductEnvironment(process.env); - const command = process.argv[2]; - // Guard sockets before either dispatch path can load outbound-capable modules. - const { ignoreMacosTypeOfServiceEinval } = await import("./outboundHttp.ts"); - ignoreMacosTypeOfServiceEinval(); - if (command === "__document-text") { - const { extractDocumentText } = await import("./provider/documentTextWorker.ts"); - try { - process.stdout.write(await extractDocumentText(process.argv[3]!, process.argv[4]!)); - } catch (error) { - if (error instanceof Error && "code" in error && /^E[A-Z0-9]+$/.test(String(error.code))) { - throw error; - } - // Exit 2 identifies document rejections; OS and process failures remain retryable. - process.exitCode = 2; - } - } else if (command === "__managed-chatgpt-token") { - const { runManagedChatGptTokenCli } = await import("./cli/managedChatGptToken.ts"); - await runManagedChatGptTokenCli(process.argv.slice(3)); - } else if (command === "acp-mcp-bridge" || command === "acp-mcp-call") { - const { runAcpMcpCliFastPath } = await import("./mcp/AcpMcpStdioBridge.ts"); - await runAcpMcpCliFastPath(command, process.argv.slice(3)); - } else if (command === "__speech-worker") { - const mode = process.argv[3]; - if (mode !== "discover" && mode !== "model") throw new Error("Unknown speech worker mode."); - const { runNativeSpeechWorker } = await import("./speech/native.ts"); - await runNativeSpeechWorker(mode, process.argv[4]); + // The launcher owns shutdown until its child exits, so it bypasses the Effect CLI runtime. + // The service unit passes no arguments; flags and help go through the full CLI. + if (process.argv[2] === "__service-launcher" && process.argv.length === 3) { + const { runServiceLauncherCli } = await import("./cli/serviceLauncher.ts"); + await runServiceLauncherCli(); } else { - enableCliCompileCache(); - // Windows desktop launches without stdin; attach before reading, except on fast paths using pipes. - const { attachConsoleStdin } = await import("./cli/consoleStdin.ts"); - attachConsoleStdin(); - const importStart = performance.now(); - const { runCli } = await import("./binCli.ts"); - if (process.env.T3CODE_STARTUP_PROFILE_DIR) { - performance.measure("server.import.binCli", { start: importStart }); - } - runCli(); + const { runCliCommand } = await loadCliMain(); + await runCliCommand(); } } diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index c4ea9907c2385..ef3293d97cbc8 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -26,7 +26,7 @@ import { threadCommand } from "./cli/thread.ts"; import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts"; import { updateCommand } from "./cli/update.ts"; import { uninstallCommand } from "./cli/uninstall.ts"; -import { serviceLauncherCommand } from "./cli/serviceLauncher.ts"; +import { runServiceLauncherCli } from "./cli/serviceLauncher.ts"; import { speechWorkerCommand } from "./cli/speechWorker.ts"; import { claudeHistoryCommand } from "./cli/claudeHistory.ts"; import { sshHelperCommand } from "./cli/sshHelper.ts"; @@ -92,7 +92,12 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => serviceCommand, updateCommand, uninstallCommand, - serviceLauncherCommand, + // bin.ts runs the bare service invocation; this keeps flags and help working like other commands. + Command.make("__service-launcher").pipe( + Command.unlisted, + // The launcher owns shutdown until its child exits; `runMain` would interrupt that shutdown. + Command.withHandler(() => Effect.sync(() => void runServiceLauncherCli())), + ), claudeHistoryCommand, speechWorkerCommand, sshHelperCommand, diff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts new file mode 100644 index 0000000000000..0dabd73873440 --- /dev/null +++ b/apps/server/src/binMain.ts @@ -0,0 +1,45 @@ +import { enableCliCompileCache } from "./cliCompileCache.ts"; + +// Packaged builds load this graph with require(esm): top-level await anywhere in it breaks them. +// ACP agents spawn `acp-mcp-bridge` per session and `acp-mcp-call` per tool call, so those fast +// paths dispatch before the full CLI module graph (seconds of evaluation) loads. +export async function runCliCommand() { + const command = process.argv[2]; + // Install the socket guard before importing code that can open outbound connections. + const { ignoreMacosTypeOfServiceEinval } = await import("./outboundHttp.ts"); + ignoreMacosTypeOfServiceEinval(); + if (command === "__document-text") { + const { extractDocumentText } = await import("./provider/documentTextWorker.ts"); + try { + process.stdout.write(await extractDocumentText(process.argv[3]!, process.argv[4]!)); + } catch (error) { + if (error instanceof Error && "code" in error && /^E[A-Z0-9]+$/.test(String(error.code))) { + throw error; + } + // Exit 2 identifies document rejections; OS and process failures remain retryable. + process.exitCode = 2; + } + } else if (command === "__managed-chatgpt-token") { + const { runManagedChatGptTokenCli } = await import("./cli/managedChatGptToken.ts"); + await runManagedChatGptTokenCli(process.argv.slice(3)); + } else if (command === "acp-mcp-bridge" || command === "acp-mcp-call") { + const { runAcpMcpCliFastPath } = await import("./mcp/AcpMcpStdioBridge.ts"); + await runAcpMcpCliFastPath(command, process.argv.slice(3)); + } else if (command === "__speech-worker") { + const mode = process.argv[3]; + if (mode !== "discover" && mode !== "model") throw new Error("Unknown speech worker mode."); + const { runNativeSpeechWorker } = await import("./speech/native.ts"); + await runNativeSpeechWorker(mode, process.argv[4]); + } else { + enableCliCompileCache(); + // Windows desktop launches without stdin; attach before reading, except on fast paths using pipes. + const { attachConsoleStdin } = await import("./cli/consoleStdin.ts"); + attachConsoleStdin(); + const importStart = performance.now(); + const { runCli } = await import("./binCli.ts"); + if (process.env.T3CODE_STARTUP_PROFILE_DIR) { + performance.measure("server.import.binCli", { start: importStart }); + } + runCli(); + } +} diff --git a/apps/server/src/cli/serviceLauncher.ts b/apps/server/src/cli/serviceLauncher.ts index a1af566d0c773..252659fd25489 100644 --- a/apps/server/src/cli/serviceLauncher.ts +++ b/apps/server/src/cli/serviceLauncher.ts @@ -1,18 +1,11 @@ -import * as Effect from "effect/Effect"; -import { Command } from "effect/cli"; - import { main as runServiceLauncher } from "../serviceLauncher.ts"; -/** The launcher must stop its child before exiting; `runMain` would interrupt that shutdown. */ -export const serviceLauncherCommand = Command.make("__service-launcher").pipe( - Command.unlisted, - Command.withHandler(() => - Effect.sync(() => { - runServiceLauncher().catch((cause: unknown) => { - const error = cause instanceof Error ? cause : new Error(String(cause)); - process.stderr.write(`[service-launcher] ${error.message}\n`); - process.exitCode = 1; - }); - }), - ), -); +export async function runServiceLauncherCli(): Promise { + try { + await runServiceLauncher(); + } catch (cause) { + const message = cause instanceof Error ? cause.message : String(cause); + process.stderr.write(`[service-launcher] ${message}\n`); + process.exitCode = 1; + } +} diff --git a/apps/server/src/cliCompileCache.test.ts b/apps/server/src/cliCompileCache.test.ts index 250ae444f094f..c88681b408937 100644 --- a/apps/server/src/cliCompileCache.test.ts +++ b/apps/server/src/cliCompileCache.test.ts @@ -8,13 +8,23 @@ import * as FileSystem from "effect/FileSystem"; import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; -it.live("enables CLI caching while respecting overrides and unavailable storage", () => +it.live("loads the CLI with its cache settings only when the command needs it", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-cache-test-" }); - const report = `import { getCompileCacheDir, registerHooks } from 'node:module'; registerHooks({ resolve(specifier, context, nextResolve) { if (specifier === './binCli.ts') console.error('CACHE=' + (getCompileCacheDir() ?? 'disabled')); return nextResolve(specifier, context); } });`; - const run = Effect.fn("cliCompileCache.test.run")(function* (env: Record) { + const report = ` + import { getCompileCacheDir, registerHooks } from 'node:module'; + registerHooks({ resolve(specifier, context, nextResolve) { + if (specifier === './binMain.ts') console.error('LOADED_CLI_MAIN'); + if (specifier === './binCli.ts') console.error('CACHE=' + (getCompileCacheDir() ?? 'disabled')); + return nextResolve(specifier, context); + } }); + `; + const run = Effect.fn("cliCompileCache.test.run")(function* ( + env: Record, + args: ReadonlyArray = ["--help"], + ) { const child = yield* spawner.spawn( ChildProcess.make( process.execPath, @@ -23,12 +33,15 @@ it.live("enables CLI caching while respecting overrides and unavailable storage" "--import", `data:text/javascript,${encodeURIComponent(report)}`, NodeURL.fileURLToPath(new URL("./bin.ts", import.meta.url)), - "--help", + ...args, ], { env: { XDG_CACHE_HOME: `${root}/cache`, S2CODE_HOME: `${root}/home`, + // Without a usable home the fork's launcher pauses; never fall back to a live one. + SHUV2CODE_HOME: undefined, + T3CODE_HOME: undefined, NODE_COMPILE_CACHE: undefined, NODE_DISABLE_COMPILE_CACHE: undefined, APPIMAGE: "", @@ -48,9 +61,22 @@ it.live("enables CLI caching while respecting overrides and unavailable storage" }, Effect.scoped); const normal = yield* run({}); expect(normal.exitCode).toBe(0); + expect(normal.stderr).toContain("LOADED_CLI_MAIN"); expect(normal.stderr.replaceAll("\\", "/")).toContain( `CACHE=${root}/cache/${PRODUCT_ID}/compile-cache`.replaceAll("\\", "/"), ); + const launcher = yield* run({}, ["__service-launcher"]); + expect(launcher.exitCode).toBe(1); + expect(launcher.stderr).toMatch(/\[service-launcher\] .*service-state\.json/); + expect(launcher.stderr).not.toMatch(/LOADED_CLI_MAIN|CACHE=/); + const launcherHelp = yield* run({}, ["__service-launcher", "--help"]); + expect(launcherHelp.exitCode).toBe(0); + expect(launcherHelp.stderr).toContain("LOADED_CLI_MAIN"); + expect(launcherHelp.stdout).toContain("s2code __service-launcher [flags]"); + const launcherFlags = yield* run({}, ["__service-launcher", "--log-level", "debug"]); + expect(launcherFlags.exitCode).toBe(1); + expect(launcherFlags.stderr).toContain("LOADED_CLI_MAIN"); + expect(launcherFlags.stderr).toMatch(/\[service-launcher\] .*service-state\.json/); const appImage = yield* run({ APPIMAGE: `${root}/T3Code.AppImage` }); expect(appImage.exitCode).toBe(0); expect(appImage.stderr).toContain("CACHE=disabled"); diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.ts index 7a0962e06f18b..ef0b48eefc80f 100644 --- a/apps/server/src/device/DeviceHost.ts +++ b/apps/server/src/device/DeviceHost.ts @@ -110,6 +110,8 @@ export interface DeviceOperations { readonly detail: string | undefined; /** Some Android virtual devices could not be listed; the rest are. */ readonly androidDiscoveryIncomplete?: boolean; + /** Platforms that could not be listed; their last known devices stay listed. */ + readonly incompletePlatforms?: ReadonlyArray; }, DeviceOperationError >; diff --git a/apps/server/src/device/DeviceHubOperations.ts b/apps/server/src/device/DeviceHubOperations.ts index 772b626619487..2725e7ac4fe29 100644 --- a/apps/server/src/device/DeviceHubOperations.ts +++ b/apps/server/src/device/DeviceHubOperations.ts @@ -6,6 +6,7 @@ import { } from "@t3tools/contracts"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; @@ -13,6 +14,11 @@ import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost const BOOT_TIMEOUT = Duration.minutes(3); const SCREENSHOT_TIMEOUT = Duration.seconds(20); +// Let the hub's 30 s simctl timeout report its cause first. +const LIST_TIMEOUT_SECONDS = 40; +// expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes. +const SIMULATOR_LIST_FAILED = + /^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/; const HubDevice = Schema.Struct({ id: Schema.String, @@ -63,30 +69,35 @@ export const makeDeviceHubOperations = (options: { readonly origin: string; readonly http: HttpClient.HttpClient; readonly run: DeviceHostReady["run"]; - /** Whether to list AVDs, which the hub does not report until they boot. */ - readonly androidAvailable: Effect.Effect; + /** Android gates listing AVDs, which the hub does not report until they boot. */ + readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect; }): DeviceOperations => { const { hostId, origin, run } = options; const httpClient = options.http.pipe(HttpClient.withScope); + const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* ( + request: HttpClientRequest.HttpClientRequest, + schema: Schema.Codec, + ) { + return yield* httpClient + .execute(request) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)), + Effect.scoped, + ); + }); + const hubJson = ( request: HttpClientRequest.HttpClientRequest, schema: Schema.Codec, operation: string, timeout: Duration.Input = Duration.seconds(15), ) => - httpClient.execute(request).pipe( - Effect.flatMap(HttpClientResponse.filterStatusOk), - Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)), - Effect.scoped, + fetchJson(request, schema).pipe( Effect.timeout(timeout), Effect.mapError( - (cause) => - new DeviceOperationError({ - operation, - reason: "request_failed", - cause, - }), + (cause) => new DeviceOperationError({ operation, reason: "request_failed", cause }), ), ); @@ -106,13 +117,27 @@ export const makeDeviceHubOperations = (options: { ); const list: DeviceOperations["list"] = Effect.gen(function* () { - const hubList = yield* hubJson( + const listed = yield* fetchJson( HttpClientRequest.get(`${origin}/api/devices`), HubDeviceList, - "list", + ).pipe( + Effect.mapError( + (cause) => new DeviceOperationError({ operation: "list", reason: "request_failed", cause }), + ), + Effect.timeoutOption(Duration.seconds(LIST_TIMEOUT_SECONDS)), ); + if (Option.isNone(listed)) { + return { + devices: [], + detail: `The device hub did not answer within ${LIST_TIMEOUT_SECONDS} seconds.`, + incompletePlatforms: yield* Effect.filter(["ios", "android"] as const, (platform) => + options.platformAvailable(platform), + ), + }; + } + const hubList = listed.value; const devices: Array = [...hubList.simulators, ...hubList.emulators]; - const androidAvailable = yield* options.androidAvailable; + const androidAvailable = yield* options.platformAvailable("android"); const warnings = hubList.errors?.filter( (error) => // The host summary already explains a missing Android SDK; the hub's failed probes are noise. @@ -155,10 +180,14 @@ export const makeDeviceHubOperations = (options: { } } } + const simulatorsUnlisted = + hubList.simulators.length === 0 && + (hubList.errors ?? []).some((error) => SIMULATOR_LIST_FAILED.test(error.message)); return { devices, detail: details.join("\n") || undefined, androidDiscoveryIncomplete, + ...(simulatorsUnlisted ? { incompletePlatforms: ["ios"] as const } : {}), }; }).pipe(Effect.withSpan("DeviceHubOperations.list")); diff --git a/apps/server/src/device/DeviceMultiHost.test.ts b/apps/server/src/device/DeviceMultiHost.test.ts index 44115303e7b8a..adf01a5cda5d6 100644 --- a/apps/server/src/device/DeviceMultiHost.test.ts +++ b/apps/server/src/device/DeviceMultiHost.test.ts @@ -52,7 +52,7 @@ it.effect("keeps hosts independent when serials collide and another host fails", origin: `http://${id}`, http, run, - androidAvailable: Effect.succeed(true), + platformAvailable: () => Effect.succeed(true), }), agentDevice: { baseUrl: `http://${id}`, token: "test", entryPath: "/agent-device" }, releaseAgentSession: releaseAgentDeviceSession(http, { diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 979de6f94bc55..24f13062f2b6a 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -29,6 +29,7 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as ServerConfig from "../config.ts"; @@ -59,7 +60,7 @@ it.effect.each([400, 500])( ), ), run: () => Effect.die("Screenshot does not run a command"), - androidAvailable: Effect.succeed(false), + platformAvailable: () => Effect.succeed(false), }); const result = yield* operations .screenshot({ @@ -103,7 +104,9 @@ const fixture = Effect.fn("fixture")(function* ( const devices: Array> = []; const discoveryErrors = yield* Ref.make>([]); const androidAvailable = yield* Ref.make(true); + const iosAvailable = yield* Ref.make(true); const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" }); + const listing = { hangs: false, requested: yield* Deferred.make() }; let booted = false; let shutDown = false; const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false }; @@ -168,6 +171,11 @@ const fixture = Effect.fn("fixture")(function* ( if (request.url.endsWith("/grid/api/start")) { return HttpClientResponse.fromWeb(request, Response.json({ ok: true })); } + if (listing.hangs) { + return yield* Deferred.succeed(listing.requested, undefined).pipe( + Effect.andThen(Effect.never), + ); + } return HttpClientResponse.fromWeb( request, Response.json({ @@ -205,7 +213,8 @@ const fixture = Effect.fn("fixture")(function* ( origin: "http://device.test", http, run, - androidAvailable: Ref.get(androidAvailable), + platformAvailable: (platform) => + Ref.get(platform === "ios" ? iosAvailable : androidAvailable), }), ...(options.endsDevices ? { endsDevices: true } : {}), }, @@ -331,6 +340,8 @@ const fixture = Effect.fn("fixture")(function* ( encoderResult, discoveryErrors, androidAvailable, + iosAvailable, + listing, endDevice, }; }); @@ -830,6 +841,101 @@ it.effect("keeps the cause from the hub's error in discovery warnings, without t }).pipe(Effect.scoped), ); +it.effect( + "keeps the last simulators while simctl cannot list them, and drops them once it can", + () => + Effect.gen(function* () { + const { service, devices, discoveryErrors } = yield* fixture(); + const simulator = { + id: DeviceId.make("iphone"), + name: "iPhone", + platform: "ios", + version: "iOS 26", + booted: true, + physical: false, + } as const; + devices.push(simulator, { ...simulator, id: DeviceId.make("pixel"), platform: "android" }); + yield* service.configure({ enabled: true, agentAccessEnabled: true }); + yield* service.agentReadinessIfSupported(); + devices.length = 0; + yield* Ref.set(discoveryErrors, [{ message: simctlMessage }]); + const failed = yield* service.list; + expect(failed.devices.map((device) => device.id)).toEqual(["iphone", "Pixel_API_35"]); + expect(failed.hostStatuses.local).toEqual({ + status: "ready", + detail: simctlMessage, + incompletePlatforms: ["ios"], + }); + yield* service.agentReadinessIfSupported(); + expect((yield* service.state).hostStatuses.local).toEqual(failed.hostStatuses.local); + yield* Ref.set(discoveryErrors, []); + const recovered = yield* service.list; + expect(recovered.devices.map((device) => device.id)).toEqual(["Pixel_API_35"]); + expect(recovered.hostStatuses.local).toEqual({ status: "ready" }); + }).pipe(Effect.scoped), +); + +it.effect.each([ + { + ios: true, + android: true, + incompletePlatforms: ["ios", "android"], + kept: ["iphone", "Pixel_API_35"], + }, + { ios: true, android: false, incompletePlatforms: ["ios"], kept: ["iphone"] }, + { ios: false, android: true, incompletePlatforms: ["android"], kept: ["Pixel_API_35"] }, +] as const)( + "keeps the devices of listable platforms when the hub does not answer within 40 seconds (iOS: $ios, Android SDK: $android)", + ({ ios, android, incompletePlatforms, kept }) => + Effect.gen(function* () { + const { service, devices, listing, androidAvailable, iosAvailable } = yield* fixture(); + yield* Ref.set(androidAvailable, android); + yield* Ref.set(iosAvailable, ios); + devices.push({ + id: DeviceId.make("iphone"), + name: "iPhone", + platform: "ios", + version: "iOS 26", + booted: true, + physical: false, + }); + yield* service.configure({ enabled: true }); + listing.hangs = true; + const listed = yield* service.list.pipe(Effect.forkScoped); + yield* Deferred.await(listing.requested); + yield* TestClock.adjust("40 seconds"); + const timedOut = yield* Fiber.join(listed); + expect(timedOut.devices.map((device) => device.id)).toEqual(kept); + expect(timedOut.hostStatuses.local).toEqual({ + status: "ready", + detail: "The device hub did not answer within 40 seconds.", + incompletePlatforms, + }); + }).pipe(Effect.scoped), +); + +it.effect("does not open a retained pre-boot entry when the post-boot listing is incomplete", () => + Effect.gen(function* () { + const afterBoot = { run: Effect.void as Effect.Effect }; + const android = yield* fixture(Effect.suspend(() => afterBoot.run)); + afterBoot.run = Effect.sync(() => { + android.listing.hangs = true; + }); + yield* android.service.configure({ enabled: true }); + const opening = yield* android.service + .open({ + threadId: ThreadId.make("boot-timeout"), + deviceId: "Pixel_API_35", + platform: "android", + }) + .pipe(Effect.flip, Effect.forkScoped); + yield* Deferred.await(android.listing.requested); + yield* TestClock.adjust("40 seconds"); + expect((yield* Fiber.join(opening))._tag).toBe("DeviceNotFoundError"); + expect((yield* android.service.state).sessions).toEqual([]); + }).pipe(Effect.scoped), +); + it.effect.each([ { diagnostic: "Insufficient disk space at /private/user/path", @@ -965,7 +1071,7 @@ it.effect.each(["shutdown", "close"] as const)( origin: "http://device.test", http, run, - androidAvailable: Effect.succeed(true), + platformAvailable: () => Effect.succeed(true), }), helpers: { serveSimAxSettings: null, serveSimCli: null }, run, @@ -1127,7 +1233,7 @@ it.effect("leaves a session its host leases to every thread open when one thread origin: "http://device.test", http, run, - androidAvailable: Effect.succeed(true), + platformAvailable: () => Effect.succeed(true), }), agentEndpoint: () => Effect.succeed({ @@ -1249,7 +1355,7 @@ it.effect.each([ origin: "http://device.test", http, run, - androidAvailable: Effect.succeed(true), + platformAvailable: () => Effect.succeed(true), }), helpers: { serveSimAxSettings: null, serveSimCli: null }, run, @@ -1321,7 +1427,7 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( origin: "http://device.test", http, run, - androidAvailable: Effect.succeed(true), + platformAvailable: () => Effect.succeed(true), }), helpers: { serveSimAxSettings: null, serveSimCli: null }, run, diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.ts index ffe652b6a7751..790daabe7a445 100644 --- a/apps/server/src/device/DeviceService.ts +++ b/apps/server/src/device/DeviceService.ts @@ -390,6 +390,9 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* return host; }); + // Readiness phases replace the shown detail; this restores an incomplete listing's cause once ready. + const discoveryDetails = new Map(); + const setHostStatus = ( hostId: DeviceHostId, status: DeviceServiceState["hostStatuses"][string], @@ -397,21 +400,34 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* Effect.suspend(() => !hosts.has(hostId) ? SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)) - : publish((state) => ({ - ...state, - ...(hostId === LOCAL_DEVICE_HOST_ID - ? { hostStatus: status.status, hostStatusDetail: status.detail } - : {}), - hostStatuses: { - ...state.hostStatuses, - [hostId]: { - ...(state.hostStatuses[hostId]?.androidDiscoveryIncomplete - ? { androidDiscoveryIncomplete: true } - : {}), - ...status, + : publish((state) => { + const previous = state.hostStatuses[hostId]; + const detail = + status.detail ?? + (status.status === "ready" && + (previous?.incompletePlatforms || previous?.androidDiscoveryIncomplete) + ? discoveryDetails.get(hostId) + : undefined); + return { + ...state, + ...(hostId === LOCAL_DEVICE_HOST_ID + ? { hostStatus: status.status, hostStatusDetail: detail } + : {}), + hostStatuses: { + ...state.hostStatuses, + [hostId]: { + ...(previous?.androidDiscoveryIncomplete + ? { androidDiscoveryIncomplete: true } + : {}), + ...(previous?.incompletePlatforms + ? { incompletePlatforms: previous.incompletePlatforms } + : {}), + ...status, + ...(detail ? { detail } : {}), + }, }, - }, - })), + }; + }), ); const readiness: DeviceService["Service"]["readiness"] = Effect.fn("DeviceService.readiness")( @@ -536,11 +552,13 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* ); const fetchDevices = Effect.fn("DeviceService.fetchDevices")(function* (ready: DeviceReadiness) { - const { devices, detail, androidDiscoveryIncomplete } = yield* ready.devices.list; + const { devices, detail, androidDiscoveryIncomplete, incompletePlatforms } = + yield* ready.devices.list; return { devices: devices.map((device): DeviceSummary => ({ ...device, hostId: ready.hostId })), detail, androidDiscoveryIncomplete, + incompletePlatforms: incompletePlatforms ?? [], }; }); @@ -551,19 +569,26 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* const sessionKey = (session: DeviceSession) => `${session.hostId}\u0000${session.deviceId}\u0000${session.threadId}\u0000${session.openedAt}`; const before = new Set((yield* SynchronizedRef.get(stateRef)).state.sessions.map(sessionKey)); - const { devices, detail, androidDiscoveryIncomplete } = yield* fetchDevices(ready); + const { devices, detail, androidDiscoveryIncomplete, incompletePlatforms } = + yield* fetchDevices(ready); const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary); return yield* lifecycleLock.withPermit( Effect.gen(function* () { if (!(yield* readDeviceSettings).enabled || !host || hosts.get(ready.hostId) !== host) return (yield* SynchronizedRef.get(stateRef)).state; + if (detail && (incompletePlatforms.length > 0 || androidDiscoveryIncomplete)) + discoveryDetails.set(ready.hostId, detail); + else discoveryDetails.delete(ready.hostId); return yield* publish((state) => ({ ...state, hosts: hostSummaries, ...(ready.hostId === LOCAL_DEVICE_HOST_ID ? { hostStatusDetail: detail } : {}), devices: [ - ...state.devices.filter((device) => device.hostId !== ready.hostId), - ...devices, + ...state.devices.filter( + (device) => + device.hostId !== ready.hostId || incompletePlatforms.includes(device.platform), + ), + ...devices.filter((device) => !incompletePlatforms.includes(device.platform)), ], // A host that ends devices itself (EAS stops sessions at their limits) // leaves sessions on devices it no longer lists with nothing to stream. @@ -582,6 +607,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* status: "ready", ...(detail ? { detail } : {}), ...(androidDiscoveryIncomplete ? { androidDiscoveryIncomplete } : {}), + ...(incompletePlatforms.length > 0 ? { incompletePlatforms } : {}), }, }, })); @@ -795,7 +821,10 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* ), ); state = yield* refresh(ready); - device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id); + // Retained entries predate the boot, so only a complete listing confirms the booted device. + device = state.hostStatuses[host.id]?.incompletePlatforms?.includes(device.platform) + ? undefined + : (findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id)); if (!device) { return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId }); } diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts index 13ad97fcec660..6643e689328d1 100644 --- a/apps/server/src/device/LocalDeviceHost.ts +++ b/apps/server/src/device/LocalDeviceHost.ts @@ -823,9 +823,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () { origin: running.hub.origin, http: httpClient, run, - androidAvailable: platformAvailability("android").pipe( - Effect.map((availability) => availability.available), - ), + platformAvailable: (platform) => + platformAvailability(platform).pipe(Effect.map((availability) => availability.available)), }), nodePath: running.hub.nodePath, run, diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.ts index a505a07166a8c..7a46a472d0732 100644 --- a/apps/server/src/device/SshDeviceHost.ts +++ b/apps/server/src/device/SshDeviceHost.ts @@ -379,14 +379,15 @@ export const make = Effect.fn("SshDeviceHost.make")(function* ( origin: hubOrigin, http, run, - // Keep probing negative reports so an SDK installed after connecting is still found. - androidAvailable: Effect.suspend(() => - summary.platforms.some((p) => p.platform === "android" && p.available) - ? Effect.succeed(true) - : platformAvailability("android").pipe( - Effect.map((availability) => availability.available), - ), - ), + // Keep probing negative reports so tooling installed after connecting is still found. + platformAvailable: (platform) => + Effect.suspend(() => + summary.platforms.some((p) => p.platform === platform && p.available) + ? Effect.succeed(true) + : platformAvailability(platform).pipe( + Effect.map((availability) => availability.available), + ), + ), }), ...(remote.daemonPort !== undefined && remote.token !== undefined && diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index f03a7874f8790..a89f1ab25b501 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -378,6 +378,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma tempDirectory: profileDirectory, }); const runtime = yield* makeAntigravityAcpRuntime({ + runtimeVersion: expectedVersion, spawn: buildAntigravityAcpSpawnInput({ installation: executable, profile, diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts index ea5efe230a234..3c3d90186066f 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.test.ts @@ -16,6 +16,7 @@ import type * as EffectAcpSchema from "effect-acp/compat"; import { resolveAttachmentPath } from "../../attachmentStore.ts"; import { applyAntigravityAcpModelSelection, + antigravityClientInfo, antigravitySessionMeta, buildAntigravityPrompt, isQualifiedAntigravityRelease, @@ -59,17 +60,19 @@ function makeModelRuntime( describe("Antigravity release gates", () => { it.each([ - { version: "1.4.1", filter: false, native: false }, - { version: "1.4.2", filter: true, native: false }, - { version: "1.4.4", filter: true, native: false }, - { version: "1.4.5", filter: true, native: true }, - { version: "1.4.6", filter: false, native: false }, - { version: "1.3.0", filter: false, native: false }, - { version: undefined, filter: false, native: false }, - { version: "unknown", filter: false, native: false }, + { version: "1.4.1", filter: false, native: false, ownName: false }, + { version: "1.4.2", filter: true, native: false, ownName: false }, + { version: "1.4.4", filter: true, native: false, ownName: false }, + { version: "1.4.5", filter: true, native: true, ownName: false }, + { version: "1.4.6", filter: false, native: false, ownName: false }, + { version: "1.5.0", filter: false, native: false, ownName: false }, + { version: "1.5.1", filter: false, native: false, ownName: true }, + { version: "1.3.0", filter: false, native: false, ownName: false }, + { version: undefined, filter: false, native: false, ownName: false }, + { version: "unknown", filter: false, native: false, ownName: false }, ])( - "$version: workflow filter $filter, native reads and system prompt $native", - ({ version, filter, native }) => { + "$version: workflow filter $filter, native reads and system prompt $native, own client name $ownName", + ({ version, filter, native, ownName }) => { const initialize = { protocolVersion: 1, ...(version === undefined ? {} : { agentInfo: { name: "antigravity-acp", version } }), @@ -86,6 +89,7 @@ describe("Antigravity release gates", () => { filter || native ? { antigravity } : undefined, ); expect(isQualifiedAntigravityRelease(version)).toBe(native); + expect(antigravityClientInfo(version).name).toBe(ownName ? "t3-code" : "zed"); }, ); }); diff --git a/apps/server/src/provider/acp/AntigravityAcpSupport.ts b/apps/server/src/provider/acp/AntigravityAcpSupport.ts index 52fbd6c6070fb..0834571785891 100644 --- a/apps/server/src/provider/acp/AntigravityAcpSupport.ts +++ b/apps/server/src/provider/acp/AntigravityAcpSupport.ts @@ -23,6 +23,7 @@ import { makeAntigravityStdoutTransform, } from "../antigravityAuthSupport.ts"; import * as AcpSessionRuntime from "@t3tools/provider-acp/server/AcpSessionRuntime"; +import packageJson from "../../../package.json" with { type: "json" }; import { normalizeAntigravitySessionUpdate } from "./AntigravityProtocol.ts"; export interface AntigravityAcpRuntimeInput extends Omit< @@ -42,7 +43,7 @@ export interface AntigravityAcpRuntimeInput extends Omit< readonly onAuthorizationUrl?: (url: string) => Effect.Effect; /** Serve `fs/read_text_file` for runtimes whose native reader is not qualified. */ readonly clientFileReads?: boolean; - /** The installed version, known before `initialize`; it picks the file reader. */ + /** The installed version, known before `initialize`; it picks the file reader and client name. */ readonly runtimeVersion?: string | null; /** Conversational sessions only; helpers and probes leave the system prompt untouched. */ readonly sessionSystemPromptAppend?: string; @@ -83,6 +84,9 @@ export function isQualifiedAntigravityRelease(version: string | null | undefined return version?.trim() === "1.4.5"; } +// `agy acp` 1.5.1 offers every model to every ACP client; older runtimes allowlist editors. +const OPEN_MODEL_ACCESS_RELEASE = [1, 5, 1] as const; + /** * 1.4.5 appends `systemPrompt.append` to its system instructions on new, load and resume, and * keeps none of it between processes, so every activation sends it again. @@ -106,6 +110,14 @@ export function antigravitySessionMeta( return Object.keys(antigravity).length === 0 ? undefined : { antigravity }; } +/** Older releases offer non-Gemini models only to allowlisted clients such as Zed. */ +export function antigravityClientInfo(version: string | null | undefined) { + const parsed = parseAntigravityVersion(version); + return parsed !== undefined && compareVersions(parsed, OPEN_MODEL_ACCESS_RELEASE) >= 0 + ? { name: "t3-code", title: "T3 Code", version: packageJson.version } + : { name: "zed", version: "0.0.0" }; +} + export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")(function* ( input: AntigravityAcpRuntimeInput, ): Effect.fn.Return< @@ -120,8 +132,7 @@ export const makeAntigravityAcpRuntime = Effect.fn("makeAntigravityAcpRuntime")( authenticateEagerly: true, resumeMethod: "resume", cancelBehavior: "wait-for-prompt", - // The agent offers non-Gemini models only to allowlisted clients such as Zed. - clientInfo: { name: "zed", version: "0.0.0" }, + clientInfo: antigravityClientInfo(input.runtimeVersion), sessionMeta: (initializeResult) => antigravitySessionMeta(initializeResult, input.sessionSystemPromptAppend), clientCapabilities: { diff --git a/apps/server/vite.config.ts b/apps/server/vite.config.ts index fa39e77aa4eb1..03b70853c044c 100644 --- a/apps/server/vite.config.ts +++ b/apps/server/vite.config.ts @@ -1,4 +1,6 @@ import "vite-plus/test/config"; +// @effect-diagnostics-next-line nodeBuiltinImport:off -- tsdown needs the asset path when it reads this config. +import * as NodePath from "node:path"; import { defineConfig, mergeConfig } from "vite-plus"; import baseConfig from "../../vite.config.ts"; @@ -29,10 +31,14 @@ if (!TELEMETRY_CHANNELS.includes(telemetryChannel)) { } // tsdown SEA needs one chunk (sourcemaps count) and Node >=25.7, so package separately. +// "bundle" emits the embedded CLI. "1" builds dist-exe/t3 from the bootstrap. // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048 -// "1" builds dist-exe/t3 here; "bundle" stops at bin.mjs for scripts/cli.ts to inject (linux-arm64). +// "bootstrap" stops at bin.mjs for scripts/cli.ts to inject (linux-arm64). const packMode = process.env.T3CODE_PACK_EXE; -const packExecutable = packMode === "1" || packMode === "bundle"; +const packBootstrap = packMode === "1" || packMode === "bootstrap"; +const packExecutable = packBootstrap || packMode === "bundle"; +const cliAssetDir = process.env.T3CODE_CLI_ASSET_DIR ?? ""; +if (packExecutable && !cliAssetDir) throw new Error("Build the executable with build:exe."); // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048 // No linux-arm64: --build-sea output cannot load on 16/64 KiB page kernels, so it builds natively. const SEA_TARGETS = { @@ -83,12 +89,15 @@ export default mergeConfig( }, pack: { // SEA embeds one entry; expose the history worker as a hidden subcommand. - entry: packExecutable ? ["src/bin.ts"] : ["src/bin.ts", "src/claude-history-worker.ts"], - outDir: packExecutable ? "dist-exe" : "dist", + entry: packBootstrap + ? ["src/bin.ts"] + : packExecutable + ? ["src/binMain.ts"] + : ["src/bin.ts", "src/claude-history-worker.ts"], + outDir: packBootstrap ? "dist-exe" : packExecutable ? cliAssetDir : "dist", sourcemap: !packExecutable, clean: true, - // TEMPORARY one-time Node fix. Remove when fixed: https://github.com/nodejs/node/issues/67048 - // SEA can only resolve built-ins; keep dynamic imports inside its one module. + // SEA can only resolve built-ins; keep dynamic imports inside each emitted module. ...(packExecutable ? { outputOptions: { codeSplitting: false } } : {}), ...(packMode === "1" ? { @@ -97,14 +106,20 @@ export default mergeConfig( outDir: "dist-exe", ...(packExecutableTargets ? { targets: packExecutableTargets } : {}), // Node SEA useCodeCache breaks import(), which the server needs. - seaConfig: { useCodeCache: false }, + seaConfig: { + useCodeCache: false, + // The bootstrap loads the embedded CLI with require(esm). + execArgv: ["--require-module"], + assets: { "binMain.mjs": NodePath.join(cliAssetDir, "binMain.mjs") }, + }, }, } : {}), deps: { // alwaysBundle=false has no opinion; neverBundle must retain transitive native acceleration. alwaysBundle: shouldBundleCliDependency, - neverBundle: (id: string) => isExternalCliDependency(id), + neverBundle: (id: string) => + (packBootstrap && id === "./binMain.ts") || isExternalCliDependency(id), onlyBundle: false, }, banner: { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 1ed3065a92c0d..d45ba6a3a3686 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -17,6 +17,7 @@ import { DndContext, useSensor, useSensors, + type AutoScrollOptions, type DragEndEvent, type DragOverEvent, type DragStartEvent, @@ -876,6 +877,9 @@ function checkThreadOperations( const SIDEBAR_DRAG_DISTANCE = 6; +// dnd-kit's 20% edge zone at full speed runs the list away while the pointer rests near the bottom. +const SIDEBAR_AUTO_SCROLL: AutoScrollOptions = { threshold: { x: 0, y: 0.05 }, acceleration: 3 }; + const SIDEBAR_DRAG_LABEL_HEIGHT = 24; const threadSearchResultId = (index: number) => `sidebar-thread-search-result-${index}`; @@ -1051,6 +1055,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } | null>(null); const dragSensorRef = useRef(null); const contextDragKeyRef = useRef(null); + const dragScrollRef = useRef<{ readonly viewport: Element; readonly top: number } | null>(null); const [actionSweep, setActionSweep] = useState<{ action: SidebarSweepAction; keys: ReadonlySet; @@ -1709,6 +1714,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const finishThreadDrag = (started: boolean) => { dragSensorRef.current = null; contextDragKeyRef.current = null; + dragScrollRef.current = null; endThreadContextDrag(); if (started) { listMotionRef.current?.release(); @@ -1735,6 +1741,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const bounds = threadListRef.current?.getBoundingClientRect(); return bounds !== undefined && (point.x < bounds.left || point.x > bounds.right); }; + // The path out of the list often crosses dnd-kit's edge zone, which autoscrolls the sidebar. + const restoreDragScroll = () => { + const scroll = dragScrollRef.current; + if (scroll && scroll.viewport.scrollTop !== scroll.top) scroll.viewport.scrollTop = scroll.top; + }; const moveThreadContextDrag = (point: { x: number; y: number }) => { const contextDrag = pointerOutsideThreadList(point); setDragState((current) => @@ -1746,6 +1757,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve endThreadContextDrag(); return false; } + restoreDragScroll(); const threads = contextDragThreads(); const title = threadByKeyRef.current.get(contextDragKeyRef.current ?? "")?.title.trim() || "Thread"; @@ -1754,6 +1766,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }; const dropThreadContextDrag = (point: { x: number; y: number }) => { if (!pointerOutsideThreadList(point)) return false; + restoreDragScroll(); dropThreadContext(point, contextDragThreads()); return true; }; @@ -1880,6 +1893,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (activeSection === undefined) return; listMotionRef.current?.suspend(); const list = threadListRef.current; + const viewport = list?.closest('[data-slot="scroll-area-viewport"]'); + dragScrollRef.current = viewport ? { viewport, top: viewport.scrollTop } : null; const header = list?.querySelector('[data-testid="sidebar-pinned-header"]'); if (list && header) { const listRect = list.getBoundingClientRect(); @@ -3280,7 +3295,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve > { }); describe("deriveMessagesTimelineRows", () => { + it.each(["alone", "before tool", "before commentary and tool"])( + "keeps an unfinished task update static %s", + (placement) => { + const runId = RunId.make("task-update-run"); + const at = "2026-11-06T00:00:00Z"; + const tasks: TimelineEntry = { + kind: "work", + id: "tasks", + createdAt: at, + entry: { + id: "tasks", + runId, + createdAt: at, + itemType: "todo_list", + tone: "info", + label: "Tasks 0/1 · Inspect the captures", + toolLifecycleStatus: "inProgress", + }, + }; + const commentary: TimelineEntry = { + kind: "message", + id: "commentary", + createdAt: at, + message: { + id: MessageId.make("commentary"), + role: "assistant", + text: "Checking the rendering.", + runId, + streaming: false, + createdAt: at, + updatedAt: at, + }, + }; + const tool: TimelineEntry = { + kind: "work", + id: "tool", + createdAt: at, + entry: { + id: "tool", + runId, + createdAt: at, + label: "Running sed", + command: "sed", + tone: "tool", + toolLifecycleStatus: "inProgress", + }, + }; + const rows = deriveMessagesTimelineRows({ + timelineEntries: [ + tasks, + ...(placement === "before commentary and tool" ? [commentary] : []), + ...(placement === "alone" ? [] : [tool]), + ], + runningRunId: runId, + isWorking: true, + activeTurnStartedAt: at, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(rows.find((row) => row.id === "tasks")).toMatchObject({ + kind: "work", + groupedEntries: [tasks.entry], + }); + expect(rows.filter((row) => row.kind === "work-live" && row.active)).toEqual( + placement === "alone" ? [] : [expect.objectContaining({ entry: tool.entry })], + ); + }, + ); + it("stops stranded thinking after a steer and follows the next thought or tool", () => { const runId = RunId.make("steered-run"); const at = "2026-10-01T06:19:10Z"; diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index a74f24859cf4f..4536e9a250386 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1627,6 +1627,7 @@ export function deriveMessagesTimelineRows(input: { entry.entry.sourceActivityKind === "runtime.error" || entry.entry.itemType === "system_notice" || entry.entry.itemType === "notification" || + entry.entry.itemType === "todo_list" || entry.entry.questionAnswer !== undefined || isPendingApproval(entry.entry) || !runIdIsActiveResponse(entry.entry.runId) || @@ -1925,6 +1926,7 @@ export function deriveMessagesTimelineRows(input: { timelineEntry.entry.sourceActivityKind === "runtime.error" || timelineEntry.entry.itemType === "system_notice" || timelineEntry.entry.itemType === "notification" || + timelineEntry.entry.itemType === "todo_list" || timelineEntry.entry.questionAnswer !== undefined ) { nextRows.push({ @@ -1950,6 +1952,7 @@ export function deriveMessagesTimelineRows(input: { nextEntry.entry.sourceActivityKind === "runtime.error" || nextEntry.entry.itemType === "system_notice" || nextEntry.entry.itemType === "notification" || + nextEntry.entry.itemType === "todo_list" || nextEntry.entry.questionAnswer !== undefined || isPendingApproval(nextEntry.entry) || activeWorkEntryIds.has(nextEntry.id) || diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 59f9fb69adc1d..6a677fc02f665 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -310,6 +310,11 @@ it("shows a remote subagent's full title in its tooltip even when its environmen { router: "/environment/fork" }, ); + // A finished remote task sits with the other finished agents, not in its own list. + await expect + .element(screen.getByRole("button", { name: new RegExp(longTitle) })) + .not.toBeInTheDocument(); + await screen.getByRole("button", { name: /Previous agents/ }).click(); const row = screen.getByRole("button", { name: new RegExp(longTitle) }); await userEvent.hover(row); await vi.waitFor(() => diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 55abc90a0fa4f..f392c652e05de 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -136,18 +136,32 @@ function ThreadLineageRowList(props: { ); } -function ThreadLineageGroup(props: { +type RemoteSubagent = OrchestrationV2Subagent & { + readonly remoteChild: OrchestrationV2RemoteTaskChild; +}; + +/** A task delegated to a linked environment has no thread here, so it gets its own row kind. */ +type LineageRow = ThreadRelationshipWalkRow | { readonly remote: RemoteSubagent }; + +const lineageRowStatus = (row: LineageRow) => + "remote" in row ? row.remote.status : row.edge.status; + +const isFinishedAgentStatus = (status: string | null | undefined) => + ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes(status ?? ""); + +function ThreadLineageGroup(props: { readonly label: string | null; - readonly rows: ReadonlyArray; + readonly rows: ReadonlyArray; readonly expanded: boolean; - readonly children: (rows: ReadonlyArray) => ReactNode; + readonly children: (rows: ReadonlyArray) => ReactNode; }) { const [expanded, setExpanded] = useState(props.expanded); const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT); const { visibleRows, hiddenCount } = resolveThreadLineageWindow(props.rows, visibleCount); - const failedCount = props.rows.filter( - ({ edge }) => edge.status === "failed" || edge.status === "error", - ).length; + const failedCount = props.rows.filter((row) => { + const status = lineageRowStatus(row); + return status === "failed" || status === "error"; + }).length; if (props.rows.length === 0) return null; return (

@@ -247,9 +261,7 @@ function currentSubagent( * the thread there, when this client is connected to that environment. */ function RemoteSubagentRow(props: { - readonly agent: OrchestrationV2Subagent & { - readonly remoteChild: OrchestrationV2RemoteTaskChild; - }; + readonly agent: RemoteSubagent; readonly provider: ServerProvider | undefined; }) { const navigate = useNavigate(); @@ -537,22 +549,29 @@ export function ThreadRelationshipsPanel(props: { if (!isParent && graph.nodes.get(threadId)?.thread?.lineage.sideChat === true) return "sideChats"; if (edge.kind !== "subagent" || isParent) return "related"; - return ["completed", "failed", "error", "cancelled", "interrupted", "idle"].includes( - edge.status ?? "", - ) - ? "previous" - : "active"; + return isFinishedAgentStatus(edge.status) ? "previous" : "active"; }); - const groups = [ + const { remoteActive = [], remotePrevious = [] } = groupBy( + (projection?.subagents ?? []) + .filter((agent): agent is RemoteSubagent => agent.remoteChild !== undefined) + .map((remote) => ({ remote })), + ({ remote }) => (isFinishedAgentStatus(remote.status) ? "remotePrevious" : "remoteActive"), + ); + const groups: ReadonlyArray<{ + id: string; + label: string | null; + rows: ReadonlyArray; + expanded: boolean; + }> = [ { id: "related", label: null, rows: related, expanded: true }, - { id: "active", label: null, rows: active, expanded: true }, - { id: "previous", label: "Previous agents", rows: previous, expanded: false }, + { id: "active", label: null, rows: [...active, ...remoteActive], expanded: true }, + { + id: "previous", + label: "Previous agents", + rows: [...previous, ...remotePrevious], + expanded: false, + }, ]; - // Tasks running in a linked environment have no thread here; they get their own rows. - const remoteSubagents = (projection?.subagents ?? []).filter( - (agent): agent is OrchestrationV2Subagent & { remoteChild: OrchestrationV2RemoteTaskChild } => - agent.remoteChild !== undefined, - ); const runningCount = (projection?.subagents.filter( (agent) => agent.childThreadId === null && agent.status === "running", @@ -567,7 +586,8 @@ export function ThreadRelationshipsPanel(props: { active.length > 0 || previous.length > 0 || runningCount > 0 || - remoteSubagents.length > 0 || + remoteActive.length > 0 || + remotePrevious.length > 0 || delegatedFrom !== undefined || // Disconnect lives in this heading, so a thread with only side chats still shows it. (canDetach && sideChats.length > 0)); @@ -929,6 +949,7 @@ export function ThreadRelationshipsPanel(props: { canDetach || related.length > 0 || active.length > 0 || + remoteActive.length > 0 || delegatedFrom !== undefined } data-thread-relationships-panel @@ -968,23 +989,24 @@ export function ThreadRelationshipsPanel(props: { )} {groups.map((group) => ( - {(visibleRows) => visibleRows.map(renderRelationshipRow)} + {(visibleRows) => + visibleRows.map((row) => + "remote" in row ? ( + entry.instanceId === row.remote.providerInstanceId)} + /> + ) : ( + renderRelationshipRow(row) + ), + ) + } ))} - {remoteSubagents.length > 0 ? ( - {}}> - {remoteSubagents.map((agent) => ( - entry.instanceId === agent.providerInstanceId)} - /> - ))} - - ) : null} ) : null} {sideChatsVisible ? ( diff --git a/apps/web/src/components/device/DevicePanel.browser.test.tsx b/apps/web/src/components/device/DevicePanel.browser.test.tsx index 8e8e0d27eb966..2212d96927255 100644 --- a/apps/web/src/components/device/DevicePanel.browser.test.tsx +++ b/apps/web/src/components/device/DevicePanel.browser.test.tsx @@ -213,3 +213,24 @@ describe("DevicePanel host probe", () => { ]); }); }); + +describe("DevicePanel discovery warning", () => { + it("a dismissal hides only the cause it was made for", async () => { + setup(); + const withCause = (detail: string): DeviceServiceState => ({ + ...deviceState, + hostStatuses: { local: { status: "ready", detail, incompletePlatforms: ["ios"] } }, + }); + const warning = "iOS list on This Mac may be incomplete."; + currentState = withCause("first cause"); + await using screen = await render(devicePanel(threadA), { container }); + + await screen.getByRole("button", { name: "Dismiss device warning for This Mac" }).click(); + await screen.rerender(devicePanel(threadA)); + await expect.element(screen.getByText(warning)).not.toBeInTheDocument(); + + currentState = withCause("second cause"); + await screen.rerender(devicePanel(threadA)); + await expect.element(screen.getByText(warning)).toBeVisible(); + }); +}); diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsx index cee7a3e4e4bcd..694528af3ac75 100644 --- a/apps/web/src/components/device/DevicePanel.tsx +++ b/apps/web/src/components/device/DevicePanel.tsx @@ -18,6 +18,7 @@ import { import { Button } from "~/components/ui/button"; import { DiscoveryList } from "~/components/ui/discovery-list"; import { Dialog } from "~/components/ui/dialog"; +import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover"; import { WizardPopup } from "~/components/ui/wizard"; import { Spinner } from "~/components/ui/spinner"; import { cn } from "~/lib/utils"; @@ -31,7 +32,12 @@ import { import { formatEnvironmentQueryError } from "~/state/query"; import { useAtomCommand } from "~/state/use-atom-command"; import { DeviceLoadingView } from "./DeviceLoadingView"; -import { DeviceSetup, deviceHubReadiness, isAndroidDiscoveryUncertain } from "./DeviceSetup"; +import { + DeviceSetup, + deviceHubReadiness, + incompleteListings, + isAndroidDiscoveryUncertain, +} from "./DeviceSetup"; import { DeviceWorkspace } from "./DeviceWorkspace"; import { PreviewPanelShell, type PreviewPanelMode } from "../preview/PreviewPanelShell"; @@ -178,7 +184,14 @@ export function DevicePanel(props: { const status = state.hostStatuses[host.id]; const detail = status?.detail ?? (host.kind === "local" ? state.hostStatusDetail : undefined); return detail && (status?.status ?? state.hostStatus) === "ready" - ? [{ hostId: host.id, label: host.label, detail }] + ? [ + { + hostId: host.id, + label: host.label, + detail, + incompletePlatforms: incompleteListings(status), + }, + ] : []; }); const unavailablePlatforms = state.hosts.flatMap((host) => @@ -214,9 +227,11 @@ export function DevicePanel(props: { @@ -228,9 +243,7 @@ export function DevicePanel(props: {
) : null} {operationError ? ( - setOperation(null)}> - {operationError} - + setOperation(null)}>{operationError} ) : null}
@@ -373,20 +386,11 @@ export function DevicePanel(props: { ); } -function DeviceNotice(props: { - readonly tone: "warning" | "error"; - readonly onDismiss: () => void; - readonly children: ReactNode; -}) { +function DeviceNotice(props: { readonly onDismiss: () => void; readonly children: ReactNode }) { return (
@@ -407,14 +411,76 @@ function DeviceNotice(props: { ); } -function DeviceDiscoveryWarning(props: { readonly label: string; readonly detail: string }) { - const [dismissed, setDismissed] = useState(false); - if (dismissed) return null; +function DeviceDiscoveryWarning(props: { + readonly label: string; + readonly detail: string; + readonly incompletePlatforms: readonly DevicePlatform[]; + readonly onRetry: () => Promise; +}) { + const [open, setOpen] = useState(false); + const [retrying, setRetrying] = useState(false); + const [dismissedCause, setDismissedCause] = useState(null); + const cause = `${props.incompletePlatforms.join()}\u0000${props.detail}`; + // A dismissal hides one occurrence; a cause that returns later shows again. + if (dismissedCause !== null && dismissedCause !== cause) setDismissedCause(null); + if (dismissedCause === cause) return null; + const platforms = props.incompletePlatforms.map((platform) => + platform === "ios" ? "iOS" : "Android", + ); return ( - setDismissed(true)}> -

Device discovery warning · {props.label}

- {props.detail} -
+
+ + + + {platforms.length > 0 + ? `${platforms.join(" and ")} ${platforms.length > 1 ? "lists" : "list"} on ${props.label} may be incomplete.` + : `Device discovery on ${props.label} reported a warning.`} + + + + {platforms.length > 0 ? ( + + ) : null} + + } + > + Details + + +

+ {props.detail} +

+
+
+ +
+
); } diff --git a/apps/web/src/components/device/DeviceSetup.test.ts b/apps/web/src/components/device/DeviceSetup.test.ts index 322354763b8d0..f0158641e2a19 100644 --- a/apps/web/src/components/device/DeviceSetup.test.ts +++ b/apps/web/src/components/device/DeviceSetup.test.ts @@ -29,7 +29,7 @@ const deviceState = (overrides: Partial = {}): DeviceService }); describe("device setup guidance", () => { - it("waits for complete Android discovery before advising creation of an AVD", () => { + it("waits for complete discovery before advising device setup", () => { const state = deviceState({ hostStatus: "idle", hosts: [{ ...deviceState().hosts[0]!, id: "remote", kind: "ssh" }], @@ -41,6 +41,12 @@ describe("device setup guidance", () => { platformSetupStatus({ ...state, hostStatuses: { remote: { status: "ready" } } }, "android") .message, ).toContain("Device Manager"); + expect( + platformSetupStatus( + { ...state, hostStatuses: { remote: { status: "ready", incompletePlatforms: ["ios"] } } }, + "ios", + ).message, + ).toContain("discovery reported a problem"); }); it("counts a remote device host when this machine has no simulator tooling", () => { diff --git a/apps/web/src/components/device/DeviceSetup.tsx b/apps/web/src/components/device/DeviceSetup.tsx index 29b46e99319a4..e4836a438b250 100644 --- a/apps/web/src/components/device/DeviceSetup.tsx +++ b/apps/web/src/components/device/DeviceSetup.tsx @@ -24,9 +24,20 @@ const deviceHubDescription = const agentDeviceDescription = "Allow new agent sessions in this environment to start and control local and remote devices, with required tools set up automatically."; +/** Platforms whose latest listing on a ready host may be missing devices. */ +export const incompleteListings = ( + status: DeviceServiceState["hostStatuses"][string] | undefined, +) => + (["ios", "android"] as const).filter( + (platform) => + status?.status === "ready" && + (status.incompletePlatforms?.includes(platform) || + (platform === "android" && status.androidDiscoveryIncomplete === true)), + ); + export const isAndroidDiscoveryUncertain = (state: DeviceServiceState) => - Object.values(state.hostStatuses).some( - (status) => status.status === "ready" && status.androidDiscoveryIncomplete, + Object.values(state.hostStatuses).some((status) => + incompleteListings(status).includes("android"), ); /** @@ -103,6 +114,16 @@ export function platformSetupStatus(state: DeviceServiceState, platform: DeviceP (host.kind === "local" && state.hostStatus === "ready"), ); if (readyHosts.length > 0 && !hasDevices) { + if ( + readyHosts.some((host) => + state.hostStatuses[host.id]?.incompletePlatforms?.includes(platform), + ) + ) { + return { + ready: false, + message: `No ${platformName(platform)} devices were listed because device discovery reported a problem.`, + }; + } return { ready: false, message: diff --git a/apps/web/src/components/settings/DeviceSourcesSettings.tsx b/apps/web/src/components/settings/DeviceSourcesSettings.tsx index 09ccc32fd61b9..9d4e07b0fb0f4 100644 --- a/apps/web/src/components/settings/DeviceSourcesSettings.tsx +++ b/apps/web/src/components/settings/DeviceSourcesSettings.tsx @@ -28,6 +28,7 @@ import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { Spinner } from "../ui/spinner"; import { toastManager } from "../ui/toast"; +import { incompleteListings } from "../device/DeviceSetup"; import { DeviceHostEditor } from "./DeviceHostEditor"; import { updateDeviceHosts, groupDeviceHosts } from "./deviceHostsSettings.logic"; import { EasDeviceHostEditor } from "./EasDeviceHostEditor"; @@ -115,10 +116,12 @@ function hostStatus( if (!state) return { tone: "pending", label: "Loading" }; const status = state.hostStatuses[hostId]; switch (status?.status) { - case "ready": - return status.androidDiscoveryIncomplete - ? { tone: "warning", label: "Android list may be incomplete", detail: status.detail } - : undefined; + case "ready": { + const incomplete = incompleteListings(status); + if (incomplete.length === 0) return undefined; + const list = incomplete.length > 1 ? "Device" : incomplete[0] === "ios" ? "iOS" : "Android"; + return { tone: "warning", label: `${list} list may be incomplete`, detail: status.detail }; + } case "installing": case "starting": return { tone: "pending", label: "Starting", detail: status.detail }; @@ -771,10 +774,20 @@ function DeviceSourceRow(props: { row: SourceRow }) { > {several ? `${environment.label}: ` : ""} - {!several && environment.status.detail + {environment.status.tone === "error" && !several && environment.status.detail ? environment.status.detail : environment.status.label} + {environment.status.tone === "warning" && environment.status.detail ? ( + + }>Details + +

+ {environment.status.detail} +

+
+
+ ) : null} {environment.status.action ? ( {environment.status.action.label} diff --git a/package.json b/package.json index f6731683bbc37..0664806c3ad61 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "build": "vp run --filter './apps/*' build", "build:marketing": "vp run --filter @t3tools/marketing build", "build:desktop": "vp run --filter @t3tools/desktop --filter t3 build", + "build:desktop:bundle": "vp run --filter @t3tools/desktop build:bundle", "build:resource-monitor": "cargo build --locked --release --manifest-path native/resource-monitor/Cargo.toml", "typecheck": "vp run -r --cache --concurrency-limit 4 typecheck", "tc": "vp run -r --cache --concurrency-limit 4 typecheck", diff --git a/packages/contracts/src/device.ts b/packages/contracts/src/device.ts index a36f796abfe41..ad52b213f10fe 100644 --- a/packages/contracts/src/device.ts +++ b/packages/contracts/src/device.ts @@ -256,6 +256,7 @@ export const DeviceHostStatuses = Schema.Record( status: DeviceHostStatus, detail: Schema.optional(Schema.String), androidDiscoveryIncomplete: Schema.optional(Schema.Boolean), + incompletePlatforms: Schema.optional(Schema.Array(DevicePlatform)), }), ); diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index ecbe61e342746..514ac91164153 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -118,6 +118,7 @@ export interface AcpSessionRuntimeOptions { readonly clientCapabilities?: EffectAcpSchema.InitializeRequest["clientCapabilities"]; readonly clientInfo: { readonly name: string; + readonly title?: string; readonly version: string; }; readonly authMethodId?: string; diff --git a/scripts/build-desktop-artifact.test.ts b/scripts/build-desktop-artifact.test.ts index a9bbef31db432..d71622b411de1 100644 --- a/scripts/build-desktop-artifact.test.ts +++ b/scripts/build-desktop-artifact.test.ts @@ -58,6 +58,7 @@ import { packWindowsServerAsar, preflightWindowsDesktopBuild, renderMacPasskeyEntitlements, + resolveMacFileExclusions, resolveMacWebAuthnEntitlements, resolveMacPasskeySigningConfiguration, resolveMergedStageDependencies, @@ -1272,6 +1273,30 @@ it.layer(NodeServices.layer)("build-desktop-artifact", (it) => { ), ); + it("drops the other architecture's Darwin prebuilds from single-architecture Mac builds", () => { + const excludes = (arch: "arm64" | "x64" | "universal", file: string) => + resolveMacFileExclusions(arch).some((glob) => NodePath.matchesGlob(file, glob.slice(1))); + const x64 = [ + "node_modules/node-pty/prebuilds/darwin-x64/pty.node", + "node_modules/objc-js/prebuilds/darwin-x64/node.napi.node", + ]; + const arm64 = [ + "node_modules/node-pty/prebuilds/darwin-arm64/pty.node", + "node_modules/objc-js/prebuilds/darwin-arm64/node.napi.armv8.node", + ]; + + for (const file of x64) { + assert.isTrue(excludes("arm64", file), file); + assert.isFalse(excludes("x64", file), file); + assert.isFalse(excludes("universal", file), file); + } + for (const file of arm64) { + assert.isTrue(excludes("x64", file), file); + assert.isFalse(excludes("arm64", file), file); + assert.isFalse(excludes("universal", file), file); + } + }); + it.effect("unpacks target Windows natives while excluding the other architecture", () => Effect.scoped( Effect.gen(function* () { diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 35e0c6c8dd630..174a3c547196a 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -1037,14 +1037,15 @@ export const LINUX_FILE_EXCLUSIONS = [ "!**/node_modules/node-pty/prebuilds/darwin-*/**/*", ] as const; -// node-pty bundles both Darwin architectures; only universal apps need both. +// Native packages (node-pty, objc-js) ship prebuilds for both Darwin architectures; only universal +// apps need both. macOS 27 warns that an arm64 app holding x64-only code won't open on macOS 28. export function resolveMacFileExclusions(arch?: typeof BuildArch.Type) { if (arch === undefined || arch === "universal") { return [...MAC_FILE_EXCLUSIONS]; } const unusedArch = arch === "arm64" ? "x64" : "arm64"; - return [...MAC_FILE_EXCLUSIONS, `!**/node_modules/node-pty/prebuilds/darwin-${unusedArch}/**/*`]; + return [...MAC_FILE_EXCLUSIONS, `!**/node_modules/**/prebuilds/darwin-${unusedArch}/**/*`]; } // Large ASAR sidecars avoid NSIS extracting thousands of loose files during installs and updates. export const WINDOWS_SERVER_ASAR_RESOURCE = "server.asar"; diff --git a/scripts/lib/linux-arm64-sea.ts b/scripts/lib/linux-arm64-sea.ts index 0071f59c2008a..8851e125e9c27 100644 --- a/scripts/lib/linux-arm64-sea.ts +++ b/scripts/lib/linux-arm64-sea.ts @@ -32,6 +32,7 @@ const run = Effect.fn("LinuxArm64Sea.run")(function* (args: Array, verbo // Builds the SEA blob with this Node and injects it into a copy of this Node with postject. export const injectLinuxArm64Sea = Effect.fn("LinuxArm64Sea.inject")(function* (input: { bundlePath: string; + cliAssetPath: string; outputPath: string; nodeVersion: string; verbose: boolean; @@ -51,11 +52,14 @@ export const injectLinuxArm64Sea = Effect.fn("LinuxArm64Sea.inject")(function* ( configPath, yield* encodeJson({ main: input.bundlePath, + assets: { "binMain.mjs": input.cliAssetPath }, output: blobPath, mainFormat: "module", disableExperimentalSEAWarning: true, // Node SEA useCodeCache breaks import(), which the server needs. useCodeCache: false, + // The bootstrap loads the embedded CLI with require(esm). + execArgv: ["--require-module"], }), ); yield* run(["--experimental-sea-config", configPath], input.verbose); diff --git a/scripts/smoke-cli-archive.ts b/scripts/smoke-cli-archive.ts index 77f83ca610237..27976234c9b0a 100644 --- a/scripts/smoke-cli-archive.ts +++ b/scripts/smoke-cli-archive.ts @@ -257,6 +257,23 @@ const smokeCliArchive = Effect.fn("smokeCliArchive")(function* (input: { }); } + // The service launcher loads outside the embedded CLI. Without S2CODE_HOME it pauses rather than + // exit, so give it an empty home: it then fails fast on the missing service state. + const launcherArgs = ["__service-launcher"] as const; + const launcher = yield* runExecutable(executable, launcherArgs, contentDir, { + S2CODE_HOME: path.join(scratch, "launcher-home"), + }); + if ( + launcher.exitCode !== 1 || + !launcher.stderr.includes("[service-launcher]") || + !launcher.stderr.includes("service-state.json") + ) { + return yield* new CliArchiveSmokeError({ + step: "running __service-launcher", + detail: formatCommandFailure(executable, launcherArgs, launcher), + }); + } + const net = yield* NetService.NetService; const port = yield* net.findAvailablePort(47700); const home = path.join(scratch, "home"); @@ -313,7 +330,9 @@ const smokeCliArchive = Effect.fn("smokeCliArchive")(function* (input: { detail: `no 200 from / within 30s\n${stdout}${stderr}`, }); } - yield* Effect.log(`[cli-smoke] ${root}: --version passed and serve answered on ${String(port)}.`); + yield* Effect.log( + `[cli-smoke] ${root}: --version and __service-launcher passed, and serve answered on ${String(port)}.`, + ); }); const command = Command.make(