From da216062c959b9fbf1bd06fb098d76e14d5f9350 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sun, 1 Nov 2026 02:28:56 -0800 Subject: [PATCH 001/183] fix(web): sidebar project filter no longer refocuses after a pick (#28605) Co-authored-by: Claude Opus 5.5 --- apps/web/src/components/Sidebar.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 4fa3f06e71757..deede26763fdd 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -3057,10 +3057,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve )} + {/* Refocusing the trigger after a pointer close shows its focus ring and opens its tooltip. */} closeType === "keyboard"} > Date: Sun, 1 Nov 2026 04:42:13 -0600 Subject: [PATCH 002/183] feat(desktop): prepare server bytecode cache in native builds (#28572) --- .../scripts/main-process-bundle.test.mjs | 11 +- apps/desktop/src/compileCache.ts | 11 +- apps/desktop/src/serverCompileCache.ts | 1 + apps/desktop/vite.config.ts | 2 +- apps/server/src/compileCache.ts | 8 +- docs/operations/development.md | 22 +++ knip.jsonc | 2 + scripts/build-desktop-artifact.ts | 1 + scripts/lib/server-compile-cache.test.ts | 108 ++++++++++++++ scripts/lib/server-compile-cache.ts | 136 ++++++++++++++++++ scripts/prepare-server-compile-cache.cjs | 55 +++++++ 11 files changed, 345 insertions(+), 12 deletions(-) create mode 100644 apps/desktop/src/serverCompileCache.ts create mode 100644 scripts/lib/server-compile-cache.test.ts create mode 100644 scripts/lib/server-compile-cache.ts create mode 100644 scripts/prepare-server-compile-cache.cjs diff --git a/apps/desktop/scripts/main-process-bundle.test.mjs b/apps/desktop/scripts/main-process-bundle.test.mjs index 678b62f58aaca..6e1f767d7d395 100644 --- a/apps/desktop/scripts/main-process-bundle.test.mjs +++ b/apps/desktop/scripts/main-process-bundle.test.mjs @@ -3,6 +3,7 @@ import * as NodeFSP from "node:fs/promises"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; import * as NodeVM from "node:vm"; +import * as NodeURL from "node:url"; import { build } from "vite-plus/pack"; import { assert, it } from "vite-plus/test"; @@ -114,18 +115,16 @@ it("loads the emitted packaged boot entry and backend cache preload", async () = const directory = await NodeFSP.mkdtemp(NodePath.join(NodeOS.tmpdir(), "t3-desktop-boot-")); try { const entries = ["src/boot.ts", "src/compileCache.ts"]; - await NodeFSP.mkdir(NodePath.join(directory, "src")); - await Promise.all( - entries.map((entry) => - NodeFSP.copyFile(new URL(`../${entry}`, import.meta.url), NodePath.join(directory, entry)), - ), - ); assert.ok(Array.isArray(desktopConfig.pack)); for (const packConfig of desktopConfig.pack) { if (!Array.isArray(packConfig.entry)) continue; if (!packConfig.entry.some((entry) => entries.includes(entry))) continue; await build({ ...packConfig, + entry: packConfig.entry.map((entry) => + NodeURL.fileURLToPath(new URL(`../${entry}`, import.meta.url)), + ), + outDir: NodePath.join(directory, "dist-electron"), config: false, cwd: directory, tsconfig: false, diff --git a/apps/desktop/src/compileCache.ts b/apps/desktop/src/compileCache.ts index abf8918df2af0..7bbd9adc7f407 100644 --- a/apps/desktop/src/compileCache.ts +++ b/apps/desktop/src/compileCache.ts @@ -2,16 +2,23 @@ import * as NodeModule from "node:module"; import * as NodeOS from "node:os"; import * as NodePath from "node:path"; +import { enablePreparedServerCache } from "../../../scripts/lib/server-compile-cache.ts"; // Linux /tmp is shared; macOS and Windows temp dirs are per user. // AppImage mounts change paths each launch, so Node's path-keyed cache would miss and accumulate copies. try { - if (!process.env.APPIMAGE) { + if (!process.env.APPIMAGE || process.env.ELECTRON_RUN_AS_NODE === "1") { const cacheRoot = // oxlint-disable-next-line t3code/no-global-process-runtime -- Loads before any Effect runtime. process.platform === "linux" ? process.env.XDG_CACHE_HOME || NodePath.join(NodeOS.homedir(), ".cache") : NodeOS.tmpdir(); - NodeModule.enableCompileCache(NodePath.join(cacheRoot, "t3code", "compile-cache")); + const directory = NodePath.join(cacheRoot, "t3code", "compile-cache"); + const prepared = + process.env.ELECTRON_RUN_AS_NODE === "1" && + enablePreparedServerCache(process.argv[1] ?? "", directory); + if (!prepared && !process.env.APPIMAGE) { + NodeModule.enableCompileCache(directory); + } } } catch {} diff --git a/apps/desktop/src/serverCompileCache.ts b/apps/desktop/src/serverCompileCache.ts new file mode 100644 index 0000000000000..01e71b1aa8720 --- /dev/null +++ b/apps/desktop/src/serverCompileCache.ts @@ -0,0 +1 @@ +export { generatePreparedServerCache } from "../../../scripts/lib/server-compile-cache.ts"; diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index 55c3aa03b6490..1160d9011275d 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -93,7 +93,7 @@ export default defineConfig({ dts: false, sourcemap: true, outExtensions: () => ({ js: ".cjs" }), - entry: ["src/boot.ts", "src/compileCache.ts"], + entry: ["src/boot.ts", "src/compileCache.ts", "src/serverCompileCache.ts"], clean: false, deps: { neverBundle: (id) => id === "./main.cjs" || id === "./compileCache.cjs", diff --git a/apps/server/src/compileCache.ts b/apps/server/src/compileCache.ts index 0a7345995a811..b01db74cbe34d 100644 --- a/apps/server/src/compileCache.ts +++ b/apps/server/src/compileCache.ts @@ -2,6 +2,8 @@ import * as NodeModule from "node:module"; import * as Effect from "effect/Effect"; // Windows force-kills on quit; persist the cache after startup. -export const flushCompileCache = Effect.try(() => NodeModule.flushCompileCache()).pipe( - Effect.ignore, -); +export const flushCompileCache = Effect.try(() => { + if (!Reflect.get(globalThis, Symbol.for("t3code.preparedServerCache"))) { + NodeModule.flushCompileCache(); + } +}).pipe(Effect.ignore); diff --git a/docs/operations/development.md b/docs/operations/development.md index df4affcad2aea..537e574978faa 100644 --- a/docs/operations/development.md +++ b/docs/operations/development.md @@ -261,6 +261,28 @@ DMGs default to the host architecture. Use `--arch` to choose another target and to retain packaging files for inspection. Run `vp run dist:desktop:artifact --help` for other options. +### Prepared server bytecode + +Native desktop artifact builds generate server bytecode with the packaged Electron executable, +after ASAR creation and before signing. Cross-platform and cross-architecture builds skip this +step explicitly. CLI, SEA and WSL runtimes keep their existing behavior; only desktop backend +imports covered by generation receive prepared bytecode. Worker-only modules compile normally. + +Electron's Node 24 cache has no read-only option and includes the producer UID in its directory +name. The backend links individual prepared files into its writable cache with keys for the +installed module paths. Node replaces files atomically, so regeneration cannot write through those +links into signed resources. Windows uses hard links and falls back to normal caching when volumes +differ or resource permissions prevent linking. Protected installations therefore may not reuse +prepared bytecode. No cache bytes are copied during startup. AppImage backends discard their links +on normal exit because each mount changes module paths. + +The key calculation follows Node's internal portable ESM format. Generation checks that the +packaged engine produced the expected CLI entry and fails the build if that format changes. +The manifest also checks Electron, Node, OS, architecture and V8's flags-sensitive version tag. +Missing or rejected entries compile from the shipped JavaScript. Prepared backends skip the +explicit startup flush; Node can persist missing entries on normal exit. The writable fallback +keeps the explicit flush needed when Windows force-kills the backend. + ### Linux AppImage prerequisites Build on Linux because the browser-secret helper links against the host's libsecret. Install diff --git a/knip.jsonc b/knip.jsonc index c2093737fd942..615581793fb3b 100644 --- a/knip.jsonc +++ b/knip.jsonc @@ -32,6 +32,7 @@ "mobile-native-client.ts", "setup-worktree.ts", "sign-macos.ts", + "prepare-server-compile-cache.cjs", "smoke-desktop-app.ts", "verify-windows-desktop-artifact.ts", ], @@ -73,6 +74,7 @@ "src/snapShot/SnapShotAccessibilityWorker.ts!", "src/boot.ts!", "src/compileCache.ts!", + "src/serverCompileCache.ts!", "src/main.ts!", "src/preload.ts!", "src/preview-pick-preload.ts!", diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 8ba7f1adcbbd2..5de3c068fc6c6 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -2771,6 +2771,7 @@ export const createBuildConfig = Effect.fn("createBuildConfig")(function* ( arch?: typeof BuildArch.Type, ) { const buildConfig: Record = { + afterPack: (yield* Path.Path).join(yield* RepoRoot, "scripts/prepare-server-compile-cache.cjs"), appId: DESKTOP_APP_ID, productName: resolveDesktopProductName(version), artifactName: "T3-Code-${version}-${arch}.${ext}", diff --git a/scripts/lib/server-compile-cache.test.ts b/scripts/lib/server-compile-cache.test.ts new file mode 100644 index 0000000000000..1092de3ec5196 --- /dev/null +++ b/scripts/lib/server-compile-cache.test.ts @@ -0,0 +1,108 @@ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodeOS from "node:os"; +import * as NodePath from "node:path"; +import { expect, it } from "vite-plus/test"; +import { cacheKey, seedPreparedCache } from "./server-compile-cache.ts"; + +it("seeds relocated cache entries without allowing writes into shipped resources", () => { + const root = NodeFS.realpathSync( + NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-prepared-test-")), + ); + try { + const prepared = NodePath.join(root, "resources", "server-compile-cache"); + const active = NodePath.join(root, "user", "different-uid-tag"); + NodeFS.mkdirSync(prepared, { recursive: true }); + NodeFS.mkdirSync(active, { recursive: true }); + NodeFS.writeFileSync(NodePath.join(prepared, "12345678"), "prepared bytes"); + const manifest = { + format: 1, + runtime: "matching", + entries: [{ module: "app.asar/apps/server/dist/chunk.mjs", file: "12345678" }], + }; + NodeFS.writeFileSync(NodePath.join(prepared, "manifest.json"), JSON.stringify(manifest)); + expect(seedPreparedCache(prepared, active, "wrong-engine")).toBe(false); + expect(seedPreparedCache(prepared, active, "matching")).toBe(true); + const key = cacheKey(active, NodePath.join(root, "resources", manifest.entries[0]!.module)); + expect(NodeFS.readFileSync(NodePath.join(active, key), "utf8")).toBe("prepared bytes"); + // Node persists by replacing the directory entry, never by overwriting the linked inode. + NodeFS.rmSync(NodePath.join(active, key)); + NodeFS.writeFileSync(NodePath.join(active, key), "runtime replacement"); + expect(NodeFS.readFileSync(NodePath.join(prepared, "12345678"), "utf8")).toBe("prepared bytes"); + expect(seedPreparedCache(prepared, active, "matching")).toBe(true); + expect(NodeFS.readFileSync(NodePath.join(active, key), "utf8")).toBe("runtime replacement"); + const missing = { module: "app.asar/apps/server/dist/missing.mjs", file: "87654321" }; + for (const entries of [ + [...manifest.entries, missing], + [missing, ...manifest.entries], + ]) { + NodeFS.writeFileSync( + NodePath.join(prepared, "manifest.json"), + JSON.stringify({ ...manifest, entries }), + ); + expect(seedPreparedCache(prepared, active, "matching")).toBe(false); + } + NodeFS.writeFileSync(NodePath.join(prepared, "manifest.json"), "corrupt"); + expect(seedPreparedCache(prepared, active, "matching")).toBe(false); + expect(seedPreparedCache(NodePath.join(root, "missing"), active, "matching")).toBe(false); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } +}); + +it.each(["app", "server"])( + "generates %s.asar cache with the consumer engine and falls back after damage", + async (archive) => { + const { spawnSync } = await import("node:child_process"); + const helper = new URL("./server-compile-cache.ts", import.meta.url).href; + const root = NodeFS.realpathSync( + NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-cache-engine-")), + ); + const run = (code: string) => { + const env = { + ...process.env, + NODE_DEBUG_NATIVE: "COMPILE_CACHE", + NODE_COMPILE_CACHE: undefined, + NODE_DISABLE_COMPILE_CACHE: undefined, + }; + const result = spawnSync(process.execPath, ["--input-type=module", "-e", code], { + env, + encoding: "utf8", + }); + expect(result.status, result.stderr).toBe(0); + return result.stderr; + }; + try { + const producer = NodePath.join(root, "producer", "resources"); + const consumer = NodePath.join(root, "relocated", "resources"); + const relative = `${archive}.asar/apps/server/dist/binCli-fixture.mjs`; + NodeFS.mkdirSync(NodePath.dirname(NodePath.join(producer, relative)), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(producer, relative), "export const answer = 42;"); + run( + `import {generatePreparedServerCache} from ${JSON.stringify(helper)}; await generatePreparedServerCache(${JSON.stringify(producer)});`, + ); + NodeFS.cpSync(producer, consumer, { recursive: true }); + const consume = (home: string, appImage = false) => + run( + `if (${appImage}) process.env.APPIMAGE = "fixture"; import {enablePreparedServerCache} from ${JSON.stringify(helper)}; import {pathToFileURL} from 'node:url'; if(!enablePreparedServerCache(${JSON.stringify(NodePath.join(consumer, relative))},${JSON.stringify(NodePath.join(root, home))})) throw Error('cache disabled'); const m = await import(pathToFileURL(${JSON.stringify(NodePath.join(consumer, relative))}).href); if(m.answer!==42) throw Error('source fallback failed');`, + ); + const prepared = NodePath.join(consumer, "server-compile-cache"); + NodeFS.chmodSync(prepared, 0o555); + expect(consume("first-user")).toContain("was accepted"); + expect(consume("appimage-user", true)).toContain("was accepted"); + expect(NodeFS.readdirSync(NodePath.join(root, "appimage-user", "server"))).toEqual([]); + NodeFS.chmodSync(prepared, 0o755); + for (const file of NodeFS.readdirSync(prepared).filter((file) => file !== "manifest.json")) { + NodeFS.writeFileSync(NodePath.join(prepared, file), "broken"); + } + expect(consume("second-user")).toContain("was not initialized"); + for (const file of NodeFS.readdirSync(prepared).filter((file) => file !== "manifest.json")) { + expect(NodeFS.readFileSync(NodePath.join(prepared, file), "utf8")).toBe("broken"); + } + NodeFS.rmSync(prepared, { recursive: true }); + expect(consume("third-user")).toContain("was not initialized"); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } + }, +); diff --git a/scripts/lib/server-compile-cache.ts b/scripts/lib/server-compile-cache.ts new file mode 100644 index 0000000000000..63a21174ff651 --- /dev/null +++ b/scripts/lib/server-compile-cache.ts @@ -0,0 +1,136 @@ +/* oxlint-disable t3code/no-global-process-runtime -- Runs in the packaged engine before an Effect runtime exists. */ +// @effect-diagnostics nodeBuiltinImport:off +import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; +import * as NodeModule from "node:module"; +import * as NodeV8 from "node:v8"; +import * as NodeZlib from "node:zlib"; +import * as NodeURL from "node:url"; + +export const runtimeIdentity = () => + [ + process.versions.electron, + process.version, + process.platform, + process.arch, + NodeV8.cachedDataVersionTag(), + ].join("-"); + +// Node 24's portable key is CRC32 of the one-byte ESM type followed by the relative filename. +// Generation verifies this against files produced by the packaged engine before shipping them. +export const cacheKey = (active: string, filename: string) => + NodeZlib.crc32(NodePath.relative(active, filename), NodeZlib.crc32(Buffer.from([1]))) + .toString(16) + .padStart(8, "0"); + +export function seedPreparedCache(prepared: string, active: string, runtime: string): boolean { + try { + const manifest: unknown = JSON.parse( + NodeFS.readFileSync(NodePath.join(prepared, "manifest.json"), "utf8"), + ); + if ( + typeof manifest !== "object" || + manifest === null || + !("format" in manifest) || + manifest.format !== 1 || + !("runtime" in manifest) || + manifest.runtime !== runtime || + !("entries" in manifest) || + !Array.isArray(manifest.entries) || + manifest.entries.length === 0 + ) + return false; + for (const entry of manifest.entries) { + if ( + typeof entry?.module !== "string" || + typeof entry?.file !== "string" || + !/^[a-f0-9]{8}$/.test(entry.file) || + !/^(app|server)\.asar\/apps\/server\/dist\/[^/\\]+\.mjs$/.test(entry.module) + ) + return false; + const source = NodePath.join(prepared, entry.file); + const destination = NodePath.join( + active, + cacheKey(active, NodePath.join(NodePath.dirname(prepared), entry.module)), + ); + try { + // Node replaces cache files atomically. A directory link would instead allow writes into signed resources. + if (process.platform === "win32") NodeFS.linkSync(source, destination); + else NodeFS.symlinkSync(source, destination); + } catch {} + if (!NodeFS.existsSync(destination)) return false; + } + return true; + } catch { + return false; + } +} + +export function enablePreparedServerCache(entry: string, cacheRoot: string): boolean { + try { + const archive = entry.match(/^(.*[\\/](?:app|server)\.asar)[\\/]/)?.[1]; + if (!archive) return false; + const resources = NodeFS.realpathSync(NodePath.dirname(archive)); + // Keep different installations and builds separate without reading or copying their source files. + const prepared = NodePath.join(resources, "server-compile-cache"); + if (process.env.APPIMAGE && !NodeFS.existsSync(NodePath.join(prepared, "manifest.json"))) + return false; + const identity = NodeZlib.crc32(resources).toString(16); + NodeFS.mkdirSync(NodePath.join(cacheRoot, "server"), { recursive: true }); + const directory = process.env.APPIMAGE + ? NodeFS.mkdtempSync(NodePath.join(cacheRoot, "server", "appimage-")) + : NodePath.join(cacheRoot, "server", identity); + if (process.env.APPIMAGE) { + // Each mount has different module paths; discard its links rather than accumulating caches. + process.once("exit", () => { + try { + NodeFS.rmSync(directory, { recursive: true, force: true }); + } catch {} + }); + } + const result = NodeModule.enableCompileCache({ + directory, + portable: true, + }); + const active = NodeModule.getCompileCacheDir(); + if (result.status !== NodeModule.constants.compileCacheStatus.ENABLED || !active) return false; + const seeded = seedPreparedCache(prepared, active, runtimeIdentity()); + if (seeded) Reflect.set(globalThis, Symbol.for("t3code.preparedServerCache"), true); + return true; + } catch { + return false; + } +} + +export async function generatePreparedServerCache(resourcesInput: string): Promise { + const resources = NodeFS.realpathSync(resourcesInput); + const prepared = NodePath.join(resources, "server-compile-cache"); + const archive = NodeFS.existsSync(NodePath.join(resources, "server.asar")) + ? "server.asar" + : "app.asar"; + const dist = NodePath.join(resources, archive, "apps/server/dist"); + NodeFS.mkdirSync(prepared, { recursive: true }); + const result = NodeModule.enableCompileCache({ directory: prepared, portable: true }); + if (result.status !== NodeModule.constants.compileCacheStatus.ENABLED) + throw new Error("Cannot enable release compile cache"); + const cli = NodeFS.readdirSync(dist).find((file) => /^binCli-.*\.mjs$/.test(file)); + if (!cli) throw new Error("Missing bundled server CLI"); + await import(NodeURL.pathToFileURL(NodePath.join(dist, cli)).href); + NodeModule.flushCompileCache(); + const active = NodeModule.getCompileCacheDir()!; + const entries = NodeFS.readdirSync(dist) + .filter((file) => file.endsWith(".mjs")) + .flatMap((file) => { + const key = cacheKey(active, NodePath.join(dist, file)); + if (!NodeFS.existsSync(NodePath.join(active, key))) return []; + NodeFS.copyFileSync(NodePath.join(active, key), NodePath.join(prepared, key)); + return [{ module: `${archive}/apps/server/dist/${file}`, file: key }]; + }); + if (!entries.some((entry) => entry.module.endsWith(`/${cli}`))) + throw new Error("Packaged engine cache key format is unsupported"); + NodeFS.writeFileSync( + NodePath.join(prepared, "manifest.json"), + JSON.stringify({ format: 1, runtime: runtimeIdentity(), entries }), + ); + NodeFS.rmSync(active, { recursive: true }); +} diff --git a/scripts/prepare-server-compile-cache.cjs b/scripts/prepare-server-compile-cache.cjs new file mode 100644 index 0000000000000..cc3a28b4ed91f --- /dev/null +++ b/scripts/prepare-server-compile-cache.cjs @@ -0,0 +1,55 @@ +/* oxlint-disable t3code/no-global-process-runtime -- Packaging must compare the build host with the executable target. */ +const { spawnSync } = require("node:child_process"); +const path = require("node:path"); +const fs = require("node:fs"); +const os = require("node:os"); + +// afterPack runs before signing and installer creation, against the final ASAR layout. +module.exports = async ({ appOutDir, electronPlatformName, arch, packager }) => { + const targetArch = ["ia32", "x64", "armv7l", "arm64", "universal"][arch]; + if (electronPlatformName !== process.platform || targetArch !== process.arch) { + console.log( + `[server-compile-cache] Skipping unexecutable target ${electronPlatformName}/${targetArch}`, + ); + return; + } + const product = packager.appInfo.productFilename; + const resources = + electronPlatformName === "darwin" + ? path.join(appOutDir, `${product}.app`, "Contents", "Resources") + : path.join(appOutDir, "resources"); + const executable = + electronPlatformName === "darwin" + ? path.join(appOutDir, `${product}.app`, "Contents", "MacOS", product) + : path.join( + appOutDir, + electronPlatformName === "win32" ? `${product}.exe` : packager.executableName, + ); + const helper = path.join( + resources, + "app.asar", + "apps/desktop/dist-electron/serverCompileCache.cjs", + ); + const env = { ...process.env, ELECTRON_RUN_AS_NODE: "1" }; + for (const name of Object.keys(env)) { + if (name.startsWith("NODE_") || name.startsWith("T3CODE_")) delete env[name]; + } + const state = fs.mkdtempSync(path.join(os.tmpdir(), "t3-release-cache-")); + env.T3CODE_HOME = state; + let result; + try { + result = spawnSync( + executable, + [ + "-e", + `require(${JSON.stringify(helper)}).generatePreparedServerCache(${JSON.stringify(resources)}).then(()=>process.exit(0),e=>{console.error(e);process.exit(1)})`, + ], + { env, encoding: "utf8", timeout: 120000 }, + ); + } finally { + fs.rmSync(state, { recursive: true, force: true }); + } + if (result.status !== 0) + throw new Error(`Server compile cache generation failed: ${result.error || result.stderr}`); + console.log("[server-compile-cache] Prepared server bytecode with packaged Electron"); +}; From 8b4de61b8b4fa902873ec0d0cd88aef2bc3716a7 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 1 Nov 2026 05:04:28 -0600 Subject: [PATCH 003/183] fix(desktop): discover shell environment without blocking startup (#28556) --- .../DesktopBackendConfiguration.test.ts | 4 + .../backend/DesktopBackendConfiguration.ts | 1 + apps/desktop/src/main.ts | 2 +- .../src/shell/DesktopShellEnvironment.test.ts | 279 +++++++++++++++++- .../src/shell/DesktopShellEnvironment.ts | 182 ++++++++++-- .../DesktopTelemetryPublisher.test.ts | 89 ++++-- .../telemetry/DesktopTelemetryPublisher.ts | 4 +- .../DesktopTelemetryReceiver.test.ts | 185 +++++++++++- .../DesktopTelemetryReceiver.ts | 77 +++++ .../src/telemetry/AnalyticsService.test.ts | 26 ++ apps/server/src/telemetry/AnalyticsService.ts | 25 +- apps/server/src/usage/UsageService.test.ts | 1 + packages/contracts/src/resourceTelemetry.ts | 40 +++ packages/shared/src/shell.test.ts | 48 +++ packages/shared/src/shell.ts | 17 +- 15 files changed, 914 insertions(+), 66 deletions(-) diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 7464d8fbe9e2f..26f6dbe026868 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -8,6 +8,7 @@ import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; import { ChildProcessSpawner } from "effect/process"; import * as DesktopEnvironment from "../app/DesktopEnvironment.ts"; @@ -22,6 +23,8 @@ import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts"; const layerShellEnvironment = (prepared = true) => Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, { installIntoProcess: Effect.succeed(prepared), + awaitDiscovery: Effect.succeed(prepared), + updates: Stream.empty, }); const layerBackendConfiguration = (prepared = true) => @@ -237,6 +240,7 @@ describe("DesktopBackendConfiguration", () => { assert.equal(first.cwd, environment.backendCwd); assert.equal(first.captureOutput, true); assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1"); + assert.equal(first.env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING, "1"); assert.isUndefined(first.env.T3CODE_PORT); assert.isUndefined(first.env.T3CODE_MODE); assert.isUndefined(first.env.T3CODE_DESKTOP_LAN_HOST); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 492903139547b..9c8186711f6ec 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -532,6 +532,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv env: { ...backendChildEnvPatch(), ELECTRON_RUN_AS_NODE: "1", + T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1", T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath), }, extendEnv: true, diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9a3c327e6b86b..2890f164f6f12 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -186,10 +186,10 @@ const layerDesktopAppActivation = DesktopAppActivation.layer.pipe( const layerDesktopBackend = DesktopBackendPool.layer.pipe( Layer.provideMerge(DesktopAppIdentity.layer), Layer.provideMerge(DesktopBackendConfiguration.layer), - Layer.provideMerge(DesktopShellEnvironment.layer), Layer.provideMerge(DesktopWslEnvironment.layer), Layer.provideMerge(DesktopWslServerTree.layer), Layer.provideMerge(DesktopTelemetryPublisher.layer), + Layer.provideMerge(DesktopShellEnvironment.layer), Layer.provideMerge(layerDesktopWindow), ); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts index 33325d9de9907..79344567fcd6c 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.test.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.test.ts @@ -3,11 +3,15 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; import * as PlatformError from "effect/PlatformError"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as Schema from "effect/Schema"; +import * as Option from "effect/Option"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as NodeOS from "node:os"; @@ -19,6 +23,15 @@ import * as DesktopShellEnvironment from "./DesktopShellEnvironment.ts"; vi.mock("node:os", { spy: true }); const textEncoder = new TextEncoder(); +const cacheCodec = Schema.fromJsonString( + Schema.Struct({ + version: Schema.Number, + key: Schema.String, + environment: Schema.Record(Schema.String, Schema.NullOr(Schema.String)), + }), +); +const encodeCache = Schema.encodeSync(cacheCodec); +const decodeCache = Schema.decodeUnknownEffect(cacheCodec); function envOutput(values: Readonly>): string { return Object.entries(values) @@ -69,18 +82,28 @@ function runShellEnvironment(input: { readonly env: NodeJS.ProcessEnv; readonly platform: NodeJS.Platform; readonly userShell?: string; + readonly stateDir?: string; + readonly use?: ( + service: DesktopShellEnvironment.DesktopShellEnvironment["Service"], + ) => Effect.Effect; readonly handler: ( command: ChildProcess.Command, ) => string | { output: string; exitCode: number }; readonly failure?: PlatformError.PlatformError; readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; }) { - const layerEnvironment = Layer.succeed( + const layerEnvironment = Layer.effect( DesktopEnvironment.DesktopEnvironment, - DesktopEnvironment.DesktopEnvironment.of({ - platform: input.platform, - } as DesktopEnvironment.DesktopEnvironment["Service"]), - ); + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const stateDir = input.stateDir ?? (yield* fs.makeTempDirectoryScoped()); + return DesktopEnvironment.DesktopEnvironment.of({ + platform: input.platform, + stateDir, + homeDirectory: "/test-home", + } as DesktopEnvironment.DesktopEnvironment["Service"]); + }), + ).pipe(Layer.provide(NodeServices.layer)); const layerSpawner = Layer.succeed( ChildProcessSpawner.ChildProcessSpawner, ChildProcessSpawner.make((command) => { @@ -97,8 +120,9 @@ function runShellEnvironment(input: { const program = Effect.gen(function* () { const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; - const prepared = yield* shellEnvironment.installIntoProcess; - assert.equal(yield* shellEnvironment.installIntoProcess, prepared); + if (input.use) return yield* input.use(shellEnvironment); + const prepared = yield* shellEnvironment.awaitDiscovery; + assert.equal(yield* shellEnvironment.awaitDiscovery, prepared); return prepared; }).pipe( Effect.provide( @@ -121,6 +145,247 @@ function runShellEnvironment(input: { } describe("DesktopShellEnvironment", () => { + it.effect("does not wait for discovery when the cache is missing", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + yield* runShellEnvironment({ + env: { SHELL: "/test-shell", PATH: "/usr/bin" }, + platform: "darwin", + handler: () => "", + processSpawner: ChildProcessSpawner.make(() => + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))), + ), + ), + use: (service) => + Effect.gen(function* () { + const startup = yield* service.installIntoProcess.pipe(Effect.forkChild); + yield* Deferred.await(started); + assert.isDefined(startup.pollUnsafe()); + yield* Deferred.succeed(release, undefined); + return yield* service.awaitDiscovery; + }), + }); + }), + ); + + it.effect( + "reuses cached paths immediately and streams fresh discovery without keeping removed paths", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner.pipe( + Effect.provide(NodeServices.layer), + ); + const executable = yield* HostProcess.ExecutablePath; + const first = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + yield* runShellEnvironment({ + env: first, + stateDir, + platform: "darwin", + handler: () => + envOutput({ + PATH: "/old/bin:/usr/bin", + __MISE_DIFF: "old-mise", + SSH_AUTH_SOCK: "/old-session.sock", + JAVA_HOME: "/old/java", + SSL_CERT_FILE: "/old/cert.pem", + }), + }); + const cachePath = `${stateDir}/shell-environment-cache.json`; + const cached = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache)); + assert.equal(cached.environment.PATH, "/old/bin:/usr/bin"); + assert.notProperty(cached.environment, "SSH_AUTH_SOCK"); + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/launcher/bin", + SSH_AUTH_SOCK: "/current-session.sock", + }; + const source = [ + "const values = { PATH: '/fresh/bin:' + process.env.PATH, __MISE_DIFF: 'fresh-mise', JAVA_HOME: process.env.JAVA_HOME, SSL_CERT_FILE: process.env.SSL_CERT_FILE };", + "for (const [name, value] of Object.entries(values)) {", + " if (value !== undefined) process.stdout.write('__T3CODE_ENV_' + name + '_START__\\n' + value + '\\n__T3CODE_ENV_' + name + '_END__\\n');", + "}", + ].join("\n"); + let calls = 0; + yield* runShellEnvironment({ + env, + stateDir, + platform: "darwin", + handler: () => "", + processSpawner: ChildProcessSpawner.make((command) => { + calls++; + return Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.andThen( + command._tag === "StandardCommand" + ? spawner.spawn(ChildProcess.make(executable, ["-e", source], command.options)) + : Effect.succeed(makeProcess("")), + ), + ); + }), + use: (service) => + Effect.gen(function* () { + yield* service.installIntoProcess; + yield* service.installIntoProcess; + assert.equal(env.PATH, "/old/bin:/usr/bin:/launcher/bin"); + assert.equal(env.SSH_AUTH_SOCK, "/current-session.sock"); + const replay = yield* Stream.runHead(service.updates); + assert.isTrue(Option.isSome(replay)); + if (Option.isSome(replay)) + assert.equal(replay.value.environment.__MISE_DIFF, "old-mise"); + yield* Deferred.await(started); + assert.equal(calls, 1); + yield* Deferred.succeed(release, undefined); + yield* service.awaitDiscovery; + assert.equal(env.PATH, "/fresh/bin:/launcher/bin"); + assert.equal(env.__MISE_DIFF, "fresh-mise"); + assert.isUndefined(env.JAVA_HOME); + assert.isUndefined(env.SSL_CERT_FILE); + const fresh = yield* Stream.runHead(service.updates); + assert.isTrue(Option.isSome(fresh)); + if (Option.isSome(fresh)) { + assert.equal(fresh.value.environment.PATH, env.PATH); + assert.isTrue(fresh.value.discovered); + } + return true; + }), + }); + const refreshed = yield* fs.readFileString(cachePath).pipe(Effect.flatMap(decodeCache)); + assert.equal(refreshed.environment.PATH, "/fresh/bin:/launcher/bin"); + assert.notProperty(refreshed.environment, "JAVA_HOME"); + assert.notProperty(refreshed.environment, "SSL_CERT_FILE"); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect.each([ + "not json", + '{"version":2,"key":"old","environment":{"PATH":"/bad/bin"}}', + '{"version":1,"key":"other-shell","environment":{"PATH":"/bad/bin"}}', + ])("ignores an unusable cache and still starts before discovery: %s", (contents) => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const stateDir = yield* fs.makeTempDirectoryScoped(); + yield* fs.writeFileString(`${stateDir}/shell-environment-cache.json`, contents); + const started = yield* Deferred.make(); + const release = yield* Deferred.make(); + const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin" }; + yield* runShellEnvironment({ + env, + stateDir, + platform: "darwin", + handler: () => "", + processSpawner: ChildProcessSpawner.make(() => + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Deferred.await(release)), + Effect.as(makeProcess(envOutput({ PATH: "/fresh/bin" }))), + ), + ), + use: (service) => + Effect.gen(function* () { + const startup = yield* service.installIntoProcess.pipe(Effect.forkChild); + yield* Deferred.await(started); + assert.isDefined(startup.pollUnsafe()); + assert.equal(env.PATH, "/usr/bin"); + yield* Deferred.succeed(release, undefined); + return yield* service.awaitDiscovery; + }), + }); + assert.equal(env.PATH, "/fresh/bin:/usr/bin"); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect( + "retains the last successful cache on refresh failure and ignores session values in the cache", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const stateDir = yield* fs.makeTempDirectoryScoped(); + const contents = encodeCache({ + version: 1, + key: '["darwin","/test-home","/bin/zsh",""]', + environment: { + PATH: "/cached/bin", + __MISE_DIFF: "cached-mise", + JAVA_HOME: "/cached/java", + NODE_EXTRA_CA_CERTS: "/cached/ca.pem", + SSL_CERT_FILE: "/cached/cert.pem", + SSL_CERT_DIR: "/cached/certs", + SSH_AUTH_SOCK: "/stale.sock", + NODE_OPTIONS: "--bad", + }, + }); + const cachePath = `${stateDir}/shell-environment-cache.json`; + yield* fs.writeFileString(cachePath, contents); + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + __MISE_DIFF: "launcher-mise", + JAVA_HOME: "/launcher/java", + NODE_EXTRA_CA_CERTS: "/launcher/ca.pem", + SSL_CERT_FILE: "", + SSH_AUTH_SOCK: "/current.sock", + }; + const prepared = yield* runShellEnvironment({ + env, + stateDir, + platform: "darwin", + handler: () => "", + use: (service) => + Effect.gen(function* () { + yield* service.installIntoProcess; + const replay = yield* Stream.runHead(service.updates); + assert.isTrue(Option.isSome(replay)); + if (Option.isSome(replay)) { + assert.equal(replay.value.environment.JAVA_HOME, "/launcher/java"); + assert.equal(replay.value.environment.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem"); + } + return yield* service.awaitDiscovery; + }), + }); + assert.isFalse(prepared); + assert.equal(env.PATH, "/cached/bin:/usr/bin"); + assert.equal(env.__MISE_DIFF, "cached-mise"); + assert.equal(env.JAVA_HOME, "/launcher/java"); + assert.equal(env.NODE_EXTRA_CA_CERTS, "/launcher/ca.pem"); + assert.equal(env.SSL_CERT_FILE, ""); + assert.equal(env.SSL_CERT_DIR, "/cached/certs"); + assert.equal(env.SSH_AUTH_SOCK, "/current.sock"); + assert.isUndefined(env.NODE_OPTIONS); + assert.equal(yield* fs.readFileString(cachePath), contents); + }).pipe(Effect.provide(NodeServices.layer)), + ); + + it.effect("cancels background discovery when the application scope closes", () => + Effect.gen(function* () { + const started = yield* Deferred.make(); + const stopped = yield* Deferred.make(); + yield* runShellEnvironment({ + env: { SHELL: "/bin/zsh", PATH: "/usr/bin" }, + platform: "darwin", + handler: () => "", + processSpawner: ChildProcessSpawner.make(() => + Deferred.succeed(started, undefined).pipe( + Effect.andThen(Effect.never), + Effect.ensuring(Deferred.succeed(stopped, undefined)), + ), + ), + use: (service) => + Effect.gen(function* () { + yield* service.installIntoProcess; + yield* Deferred.await(started); + return true; + }), + }); + yield* Deferred.await(stopped); + }), + ); + it.effect( "captures the login-shell PATH when startup writes more than a pipe buffer to stderr", () => diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 255eb202df68a..556f7090b422e 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -1,4 +1,6 @@ +import { DesktopShellEnvironmentSnapshot, ShellEnvironmentPatch } from "@t3tools/contracts"; import { + applyShellEnvironment, buildEnvironmentCaptureCommand, listLoginShellCandidates, setWindowsPath, @@ -6,6 +8,11 @@ import { import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; +import * as Path from "effect/Path"; +import * as PubSub from "effect/PubSub"; +import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -68,8 +75,10 @@ export class DesktopShellEnvironmentCommandTimeoutError extends Schema.TaggedErr export class DesktopShellEnvironment extends Context.Service< DesktopShellEnvironment, { - // Reuses the installation result; false leaves server hydration enabled. + // Desktop owns discovery, including on cache misses; the backend receives updates over fd4. readonly installIntoProcess: Effect.Effect; + readonly awaitDiscovery: Effect.Effect; + readonly updates: Stream.Stream; } >()("@t3tools/desktop/shell/DesktopShellEnvironment") {} @@ -97,6 +106,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", "__MISE_DIFF", + "JAVA_HOME", ] as const; const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const; const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const; @@ -244,6 +254,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( readonly probe: DesktopShellEnvironmentProbe; readonly command: string; readonly args: ReadonlyArray; + readonly env: NodeJS.ProcessEnv; readonly timeout: Duration.Duration; readonly shell?: boolean; }): Effect.fn.Return { @@ -253,6 +264,8 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( const child = yield* spawner.spawn( ChildProcess.make(input.command, input.args, { shell: input.shell ?? false, + env: input.env, + extendEnv: false, stdin: "ignore", stdout: "pipe", stderr: "ignore", @@ -308,6 +321,7 @@ const runCommandOutput = Effect.fn("desktop.shellEnvironment.runCommandOutput")( const readLoginShellEnvironment = ( shell: string, names: ReadonlyArray, + env: NodeJS.ProcessEnv, ): Effect.Effect => names.length === 0 ? Effect.succeed({}) @@ -315,20 +329,24 @@ const readLoginShellEnvironment = ( probe: "login-shell", command: shell, args: ["-ilc", buildEnvironmentCaptureCommand(shell, names)], + env, timeout: LOGIN_SHELL_TIMEOUT, }).pipe(Effect.map((output) => extractEnvironment(output, names))); -const readLaunchctlPath = runCommandOutput({ - probe: "launchctl-path", - command: "/bin/launchctl", - args: ["getenv", "PATH"], - timeout: LAUNCHCTL_TIMEOUT, -}).pipe(Effect.map(trimNonEmpty)); +const readLaunchctlPath = (env: NodeJS.ProcessEnv) => + runCommandOutput({ + env, + probe: "launchctl-path", + command: "/bin/launchctl", + args: ["getenv", "PATH"], + timeout: LAUNCHCTL_TIMEOUT, + }).pipe(Effect.map(trimNonEmpty)); const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEnvironment")( function* ( names: ReadonlyArray, options: WindowsProbeOptions, + env: NodeJS.ProcessEnv, ): Effect.fn.Return { if (names.length === 0) return {}; @@ -345,6 +363,7 @@ const readWindowsEnvironment = Effect.fn("desktop.shellEnvironment.readWindowsEn probe: options.loadProfile ? "powershell-profile" : "powershell-no-profile", command, args, + env, timeout: LOGIN_SHELL_TIMEOUT, }); const environment = extractEnvironment(output, names); @@ -363,8 +382,8 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin ): Effect.fn.Return { const [noProfile, profile] = yield* Effect.all( [ - readWindowsEnvironment(["PATH"], { loadProfile: false }), - readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }), + readWindowsEnvironment(["PATH"], { loadProfile: false }, config.env), + readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }, config.env), ], { concurrency: 2 }, ); @@ -402,14 +421,14 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) { Object.assign( shellEnvironment, - yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES), + yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env), ); if (shellEnvironment.PATH) break; } const launchctlPath = config.platform === "darwin" && !shellEnvironment.PATH - ? yield* readLaunchctlPath + ? yield* readLaunchctlPath(config.env) : Option.none(); const mergedPath = mergePaths(config.platform, [ trimNonEmpty(shellEnvironment.PATH).pipe(Option.orElse(() => launchctlPath)), @@ -450,6 +469,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "SSL_CERT_FILE", "SSL_CERT_DIR", "NODE_EXTRA_CA_CERTS", + "JAVA_HOME", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", ] as const) { @@ -512,24 +532,140 @@ const installShellEnvironment = ( return Effect.succeed(false); }; +const ShellEnvironmentCache = Schema.fromJsonString( + Schema.Struct({ + version: Schema.Literal(1), + key: Schema.String, + environment: ShellEnvironmentPatch, + }), +); +const encodeCacheKey = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); +const decodeCache = Schema.decodeUnknownEffect(ShellEnvironmentCache); +const encodeCache = Schema.encodeEffect(ShellEnvironmentCache); +const CACHED_ENV_NAMES = [ + "PATH", + "__MISE_DIFF", + "HOMEBREW_PREFIX", + "HOMEBREW_CELLAR", + "HOMEBREW_REPOSITORY", + "JAVA_HOME", + "SSL_CERT_FILE", + "SSL_CERT_DIR", + "NODE_EXTRA_CA_CERTS", +] as const; + /** @public */ export const make = Effect.gen(function* () { const environment = yield* DesktopEnvironment.DesktopEnvironment; const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] = - yield* Effect.cached( - installShellEnvironment({ - env: process.env, - platform: environment.platform, - }).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), - Effect.withSpan("desktop.shellEnvironment.installIntoProcess"), - ), + const scope = yield* Scope.Scope; + const env = process.env; + const inherited = { ...env }; + const key = encodeCacheKey([ + environment.platform, + environment.homeDirectory, + inherited.SHELL ?? "", + inherited.ZDOTDIR ?? "", + ]); + const cachePath = path.join(environment.stateDir, "shell-environment-cache.json"); + const changes = yield* PubSub.unbounded(); + const latest = yield* Ref.make>(Option.none()); + const discovered = yield* Deferred.make(); + const publish = Effect.fn("desktop.shellEnvironment.publish")(function* ( + patch: ShellEnvironmentPatch, + discovered = false, + ) { + applyShellEnvironment(env, patch, environment.platform); + const message: DesktopShellEnvironmentSnapshot = { + version: 1, + type: "shellEnvironment", + discovered, + platform: environment.platform, + environment: patch, + }; + yield* Ref.set(latest, Option.some(message)); + yield* PubSub.publish(changes, message); + }); + const refresh = Effect.gen(function* () { + // Refresh from the inherited baseline so removed cached paths and values do not survive. + const fresh = { ...inherited }; + const prepared = yield* installShellEnvironment({ env: fresh, platform: environment.platform }); + const patch = Object.fromEntries( + Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]), ); - - return DesktopShellEnvironment.of({ installIntoProcess }); + if (prepared || Option.isNone(yield* Ref.get(latest))) yield* publish(patch, prepared); + if (prepared) { + const cached = Object.fromEntries( + CACHED_ENV_NAMES.flatMap((name) => (fresh[name] ? [[name, fresh[name]]] : [])), + ); + const persist = Effect.gen(function* () { + const encoded = yield* encodeCache({ version: 1, key, environment: cached }); + yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true }); + yield* fileSystem.writeFileString(cachePath + ".tmp", encoded, { mode: 0o600 }); + yield* fileSystem.rename(cachePath + ".tmp", cachePath); + }); + yield* persist.pipe( + Effect.catch(() => Effect.logWarning("Could not cache shell environment")), + ); + } + return prepared; + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + Effect.withSpan("desktop.shellEnvironment.refresh"), + Effect.onExit((exit) => Deferred.done(discovered, exit)), + ); + const installIntoProcess = yield* Effect.cached( + Effect.gen(function* () { + const cache = yield* fileSystem + .readFileString(cachePath) + .pipe(Effect.flatMap(decodeCache), Effect.option); + if (Option.isSome(cache) && cache.value.key === key) { + const cached = Object.fromEntries( + CACHED_ENV_NAMES.flatMap((name) => { + const value = cache.value.environment[name]; + // mise's metadata must describe the cached PATH entries restored alongside it. + if (name !== "PATH" && name !== "__MISE_DIFF" && inherited[name] !== undefined) + return []; + return typeof value === "string" ? [[name, value]] : []; + }), + ); + const baseline = { ...inherited }; + const cachedPath = cached.PATH; + if (cachedPath) { + cached.PATH = Option.getOrElse( + mergePaths(environment.platform, [Option.some(cachedPath), readEnvPath(inherited)]), + () => cachedPath, + ); + } + applyShellEnvironment(baseline, cached, environment.platform); + yield* publish( + Object.fromEntries( + Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, baseline[name] ?? null]), + ), + ); + } + yield* Effect.forkIn(refresh, scope); + return true; + }).pipe(Effect.withSpan("desktop.shellEnvironment.installIntoProcess")), + ); + const updates = Stream.unwrap( + Effect.gen(function* () { + const subscription = yield* PubSub.subscribe(changes); + const snapshot = yield* Ref.get(latest); + return Stream.concat( + Option.isSome(snapshot) ? Stream.make(snapshot.value) : Stream.empty, + Stream.fromSubscription(subscription), + ); + }), + ); + return DesktopShellEnvironment.of({ + installIntoProcess, + awaitDiscovery: installIntoProcess.pipe(Effect.andThen(Deferred.await(discovered))), + updates, + }); }); export const layer = Layer.effect(DesktopShellEnvironment, make); diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts index f3f0163401ab2..1180c0fa70915 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts @@ -1,6 +1,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; +import * as Context from "effect/Context"; +import * as Option from "effect/Option"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -8,6 +10,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import type * as Electron from "electron"; @@ -18,6 +21,7 @@ import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts"; import * as DesktopTelemetryPublisher from "./DesktopTelemetryPublisher.ts"; import * as DesktopRendererHistory from "./DesktopRendererHistory.ts"; +import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts"; const layerHistory = Layer.succeed(DesktopRendererHistory.DesktopRendererHistory, { register: () => Effect.void, @@ -57,39 +61,66 @@ function layerElectronApp( } describe("DesktopTelemetryPublisher", () => { - it.effect("stops when its scope closes during an Electron telemetry sample", () => - Effect.gen(function* () { - const pollStarted = yield* Deferred.make(); - const blockPoll = yield* Deferred.make(); - const layerPower = Layer.succeed( - ElectronPowerMonitor.ElectronPowerMonitor, - ElectronPowerMonitor.ElectronPowerMonitor.of({ - isOnBatteryPower: Effect.succeed(false), - getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe( - Effect.andThen(Deferred.await(blockPoll)), - Effect.as(0), + it.effect( + "forwards shell discovery while a telemetry sample is pending and stops on scope close", + () => + Effect.gen(function* () { + const pollStarted = yield* Deferred.make(); + const blockPoll = yield* Deferred.make(); + const layerPower = Layer.succeed( + ElectronPowerMonitor.ElectronPowerMonitor, + ElectronPowerMonitor.ElectronPowerMonitor.of({ + isOnBatteryPower: Effect.succeed(false), + getSystemIdleTime: Deferred.succeed(pollStarted, undefined).pipe( + Effect.andThen(Deferred.await(blockPoll)), + Effect.as(0), + ), + getSystemIdleState: () => Effect.succeed("active"), + getCurrentThermalState: Effect.succeed("nominal"), + onSimpleEvent: () => Effect.void, + onThermalStateChange: () => Effect.void, + onSpeedLimitChange: () => Effect.void, + }), + ); + const layer = DesktopTelemetryPublisher.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerElectronApp([]), + layerPower, + layerHistory, + Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, { + installIntoProcess: Effect.succeed(true), + awaitDiscovery: Effect.succeed(true), + updates: Stream.make({ + version: 1, + type: "shellEnvironment", + discovered: true, + platform: "darwin", + environment: { PATH: "/discovered/bin" }, + }), + }), + ), ), - getSystemIdleState: () => Effect.succeed("active"), - getCurrentThermalState: Effect.succeed("nominal"), - onSimpleEvent: () => Effect.void, - onThermalStateChange: () => Effect.void, - onSpeedLimitChange: () => Effect.void, - }), - ); - const layer = DesktopTelemetryPublisher.layer.pipe( - Layer.provide(Layer.mergeAll(layerElectronApp([]), layerPower, layerHistory)), - ); - const scope = yield* Scope.make(); + ); + const scope = yield* Scope.make(); - yield* Layer.buildWithScope(layer, scope); - yield* Deferred.await(pollStarted); + const context = yield* Layer.buildWithScope(layer, scope); + const publisher = Context.get(context, DesktopTelemetryPublisher.DesktopTelemetryPublisher); + const update = yield* publisher.encoded.pipe( + Stream.filter((bytes) => new TextDecoder().decode(bytes).includes("shellEnvironment")), + Stream.runHead, + ); + assert.isTrue(Option.isSome(update)); + if (Option.isSome(update)) + assert.include(new TextDecoder().decode(update.value), "/discovered/bin"); + yield* Deferred.await(pollStarted); - const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach); - yield* Effect.yieldNow; - yield* Effect.yieldNow; + const closeFiber = yield* Scope.close(scope, Exit.void).pipe(Effect.forkDetach); + yield* Effect.yieldNow; + yield* Effect.yieldNow; - assert.isDefined(closeFiber.pollUnsafe()); - }), + assert.isDefined(closeFiber.pollUnsafe()); + }), ); }); diff --git a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts index 8800c4f428331..0a2b10e08c5a8 100644 --- a/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts +++ b/apps/desktop/src/telemetry/DesktopTelemetryPublisher.ts @@ -24,6 +24,7 @@ import * as Stream from "effect/Stream"; import * as ElectronApp from "../electron/ElectronApp.ts"; import * as ElectronPowerMonitor from "../electron/ElectronPowerMonitor.ts"; import * as DesktopRendererHistory from "./DesktopRendererHistory.ts"; +import * as DesktopShellEnvironment from "../shell/DesktopShellEnvironment.ts"; const LIVE_SAMPLE_INTERVAL = Duration.seconds(1); const BATTERY_SAMPLE_INTERVAL = Duration.seconds(5); @@ -146,6 +147,7 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () { const electronApp = yield* ElectronApp.ElectronApp; const powerMonitor = yield* ElectronPowerMonitor.ElectronPowerMonitor; const rendererHistory = yield* DesktopRendererHistory.DesktopRendererHistory; + const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment; yield* electronApp.whenReady; const initialPowerState: PowerState = { @@ -400,7 +402,7 @@ export const make = Effect.fn("desktop.telemetryPublisher.make")(function* () { type: "desktopTelemetryHello", electronPid: process.pid, } as const), - Stream.merge(snapshots, updateReports), + Stream.merge(Stream.merge(snapshots, updateReports), shellEnvironment.updates), ).pipe(Stream.map((message) => textEncoder.encode(`${encodeMessage(message)}\n`))); const publishUpdateReport: DesktopTelemetryPublisher["Service"]["publishUpdateReport"] = ( diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts index 616643c6e1e9e..fe014b82e2dd5 100644 --- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts +++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.test.ts @@ -1,12 +1,195 @@ // @effect-diagnostics nodeBuiltinImport:off import { it } from "@effect/vitest"; +import * as NodeTls from "node:tls"; +import * as NodeCrypto from "node:crypto"; +import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; +import * as Cause from "effect/Cause"; +import * as FileSystem from "effect/FileSystem"; +import * as Logger from "effect/Logger"; +import * as Path from "effect/Path"; +import * as Stream from "effect/Stream"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { describe, expect } from "vite-plus/test"; -import { requireDesktopTelemetryWriteProgress } from "./DesktopTelemetryReceiver.ts"; +import { + makeApplyDesktopShellEnvironmentSnapshot, + requireDesktopTelemetryWriteProgress, +} from "./DesktopTelemetryReceiver.ts"; describe("DesktopTelemetryReceiver", () => { + it.live( + "preserves system and bundled roots when the first snapshot withdraws overlapping extras", + () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const directory = yield* fs.makeTempDirectoryScoped(); + const certificatePath = path.join(directory, "startup-extra-ca.pem"); + yield* fs.writeFileString( + certificatePath, + [...NodeTls.getCACertificates("system"), ...NodeTls.rootCertificates].join("\n"), + ); + const child = yield* spawner.spawn( + ChildProcess.make( + process.execPath, + [ + "--use-bundled-ca", + "--use-system-ca", + "--input-type=module", + "--eval", + ` +import * as NodeAssert from "node:assert/strict"; +import * as NodeCrypto from "node:crypto"; +import * as NodeTls from "node:tls"; +import * as Effect from "effect/Effect"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { makeApplyDesktopShellEnvironmentSnapshot } from ${JSON.stringify(new URL("./DesktopTelemetryReceiver.ts", import.meta.url).href)}; +const fingerprints = (certificates) => [...new Set(certificates.map((pem) => new NodeCrypto.X509Certificate(pem).fingerprint256))].sort(); +const expected = fingerprints([...NodeTls.getCACertificates("bundled"), ...NodeTls.getCACertificates("system")]); +const applySnapshot = makeApplyDesktopShellEnvironmentSnapshot(process.env, process.platform); +await Effect.runPromise(applySnapshot({ + version: 1, + type: "shellEnvironment", + platform: process.platform, + discovered: true, + environment: { NODE_EXTRA_CA_CERTS: null }, +}).pipe(Effect.provide(NodeServices.layer))); +NodeAssert.equal(process.env.NODE_EXTRA_CA_CERTS, undefined); +NodeAssert.deepEqual(fingerprints(NodeTls.getCACertificates("default")), expected); +`, + ], + { + cwd: path.resolve(import.meta.dirname, "../.."), + env: { NODE_OPTIONS: "", NODE_EXTRA_CA_CERTS: certificatePath }, + }, + ), + ); + const result = yield* Effect.all( + { + stderr: child.stderr.pipe(Stream.decodeText(), Stream.mkString), + exitCode: child.exitCode.pipe(Effect.map(Number)), + }, + { concurrency: "unbounded" }, + ); + expect(result.exitCode, result.stderr).toBe(0); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("updates live TLS trust when shell certificates arrive after startup", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped(); + const certificatePath = path.join(directory, "extra-ca.pem"); + const original = NodeTls.getCACertificates("default"); + yield* Effect.addFinalizer(() => + Effect.sync(() => NodeTls.setDefaultCACertificates(original)), + ); + const baseline = NodeTls.rootCertificates[0]!; + const extra = NodeTls.rootCertificates[1]!; + const replacement = NodeTls.rootCertificates[2]!; + NodeTls.setDefaultCACertificates([baseline]); + yield* fs.writeFileString(certificatePath, `${extra}\n${replacement}`); + const environment: NodeJS.ProcessEnv = { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" }; + const applySnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, "darwin"); + const message = { + version: 1, + type: "shellEnvironment", + platform: "darwin", + discovered: true, + environment: { NODE_EXTRA_CA_CERTS: certificatePath }, + } as const; + const fingerprints = (certificates: ReadonlyArray) => + certificates.map((pem) => new NodeCrypto.X509Certificate(pem).fingerprint256).sort(); + yield* applySnapshot({ ...message, platform: "win32" }); + expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(fingerprints([baseline])); + expect(environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING).toBe("1"); + yield* applySnapshot(message); + expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual( + fingerprints([baseline, extra, replacement]), + ); + expect(environment.NODE_EXTRA_CA_CERTS).toBe(certificatePath); + expect(environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING).toBeUndefined(); + + yield* fs.writeFileString(certificatePath, replacement); + yield* applySnapshot(message); + expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual( + fingerprints([baseline, replacement]), + ); + + yield* fs.writeFileString( + certificatePath, + "-----BEGIN CERTIFICATE-----\ninvalid\n-----END CERTIFICATE-----", + ); + yield* applySnapshot(message); + expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual( + fingerprints([baseline, replacement]), + ); + yield* fs.remove(certificatePath); + const warnings: Array> = []; + yield* applySnapshot(message).pipe( + Effect.provide( + Logger.layer([Logger.make((entry) => warnings.push(entry))], { + mergeWithExisting: false, + }), + ), + ); + expect(warnings).toHaveLength(1); + expect(warnings[0]!.message).toEqual(["Failed to update desktop shell TLS certificates."]); + expect(Cause.squash(warnings[0]!.cause)).toMatchObject({ _tag: "PlatformError" }); + expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual( + fingerprints([baseline, replacement]), + ); + + yield* applySnapshot({ ...message, environment: { NODE_EXTRA_CA_CERTS: null } }); + expect(fingerprints(NodeTls.getCACertificates("default"))).toEqual(fingerprints([baseline])); + expect(environment.NODE_EXTRA_CA_CERTS).toBeUndefined(); + + NodeTls.setDefaultCACertificates([]); + yield* fs.writeFileString(certificatePath, extra); + const applyOpaqueTrust = makeApplyDesktopShellEnvironmentSnapshot(environment, "darwin"); + yield* applyOpaqueTrust(message); + expect(NodeTls.getCACertificates("default")).toEqual([]); + expect(environment.NODE_EXTRA_CA_CERTS).toBe(certificatePath); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.each([ + { platform: "darwin", discovered: true, applied: true, pending: false }, + { platform: "win32", discovered: true, applied: false, pending: true }, + { platform: "darwin", discovered: false, applied: true, pending: true }, + ])( + "applies platform=$platform discovered=$discovered with pending=$pending", + ({ platform, discovered, applied, pending }) => + Effect.gen(function* () { + const environment: NodeJS.ProcessEnv = { + PATH: "/old/bin", + JAVA_HOME: "/old/java", + UNRELATED: "keep", + T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1", + }; + yield* makeApplyDesktopShellEnvironmentSnapshot( + environment, + "darwin", + )({ + version: 1, + type: "shellEnvironment", + platform, + discovered, + environment: { PATH: "/fresh/bin", JAVA_HOME: null }, + }); + expect(environment).toEqual({ + PATH: applied ? "/fresh/bin" : "/old/bin", + ...(applied ? {} : { JAVA_HOME: "/old/java" }), + UNRELATED: "keep", + ...(pending ? { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" } : {}), + }); + }).pipe(Effect.provide(NodeServices.layer)), + ); + it.effect("models a zero-byte control write as a stalled descriptor", () => Effect.gen(function* () { const error = yield* requireDesktopTelemetryWriteProgress(7, 42, 0).pipe(Effect.flip); diff --git a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts index 70dc2e8d750ef..7d9de87ecfd98 100644 --- a/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts +++ b/apps/server/src/resourceTelemetry/DesktopTelemetryReceiver.ts @@ -1,22 +1,28 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeFS from "node:fs"; import * as NodeNet from "node:net"; +import * as NodeTls from "node:tls"; import * as NodeStream from "@effect/platform-node/NodeStream"; import { DesktopHostTelemetryMessage, type DesktopHostTelemetryMessage as DesktopHostTelemetryMessageValue, type DesktopHostTelemetrySnapshot, + type DesktopShellEnvironmentSnapshot, DesktopTelemetryControlMessage, type DesktopUpdateChannel, type DesktopUpdateStatusReport, type ResourceTelemetrySourceStatus, } from "@t3tools/contracts"; import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { applyShellEnvironment } from "@t3tools/shared/shell"; +import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as PubSub from "effect/PubSub"; @@ -202,6 +208,70 @@ export class DesktopTelemetryReceiver extends Context.Service< } >()("t3/resourceTelemetry/DesktopTelemetryReceiver") {} +class DesktopShellCertificatesUpdateFailed extends Schema.TaggedError()( + "DesktopShellCertificatesUpdateFailed", + { cause: Schema.Defect() }, +) { + override get message(): string { + return "Failed to update desktop shell TLS certificates."; + } +} + +export function makeApplyDesktopShellEnvironmentSnapshot( + environment: NodeJS.ProcessEnv, + platform: NodeJS.Platform, +) { + let baseCertificates: Array | undefined; + return Effect.fn("resourceTelemetry.desktopTelemetryReceiver.applyShellEnvironment")(function* ( + message: DesktopShellEnvironmentSnapshot, + ) { + if (message.platform !== platform) return; + // Node's first default-CA enumeration consults process.env, so capture it before the patch. + if (message.environment.NODE_EXTRA_CA_CERTS !== undefined && baseCertificates === undefined) { + // Remove only the startup extras, preserving duplicates from bundled or system trust. + const extras = [...NodeTls.getCACertificates("extra")]; + baseCertificates = NodeTls.getCACertificates("default").filter((certificate) => { + const index = extras.indexOf(certificate); + if (index === -1) return true; + extras.splice(index, 1); + return false; + }); + } + applyShellEnvironment(environment, message.environment, platform); + if (message.environment.NODE_EXTRA_CA_CERTS !== undefined) { + yield* Effect.gen(function* () { + const certificates = baseCertificates; + // --use-openssl-ca roots are not enumerable; replacing the list would discard them. + if (certificates === undefined || certificates.length === 0) { + yield* Effect.logWarning( + "Preserving non-enumerable TLS trust. Restart to apply updated desktop shell certificates.", + ); + return; + } + const fs = yield* FileSystem.FileSystem; + const file = message.environment.NODE_EXTRA_CA_CERTS; + const bundle = file ? yield* fs.readFileString(file) : undefined; + yield* Effect.try({ + try: () => { + const extras = + bundle?.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/g) ?? []; + if (bundle?.trim() && extras.length === 0) { + throw new Error("No PEM certificates found."); + } + NodeTls.setDefaultCACertificates([...certificates, ...extras]); + }, + catch: (cause) => new DesktopShellCertificatesUpdateFailed({ cause }), + }); + }).pipe( + Effect.catch((cause) => + Effect.logWarning("Failed to update desktop shell TLS certificates.", Cause.fail(cause)), + ), + ); + } + if (message.discovered) delete environment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING; + }); +} + const decodeMessage = Schema.decodeUnknownEffect(DesktopHostTelemetryMessage); const encodeControlMessage = Schema.encodeEffect( Schema.fromJsonString(DesktopTelemetryControlMessage), @@ -328,6 +398,9 @@ export function requireDesktopTelemetryWriteProgress( /** @public */ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make")(function* () { const config = yield* ServerConfig.ServerConfig; + const environment = yield* HostProcess.Environment; + const platform = yield* HostProcess.Platform; + const applyShellSnapshot = makeApplyDesktopShellEnvironmentSnapshot(environment, platform); const serverSettings = yield* ServerSettings.ServerSettingsService; const latest = yield* Ref.make(Option.none()); const receiverStartedAt = yield* DateTime.now; @@ -523,6 +596,10 @@ export const make = Effect.fn("resourceTelemetry.desktopTelemetryReceiver.make") ); } + if (message.type === "shellEnvironment") { + return recordContact.pipe(Effect.andThen(applyShellSnapshot(message))); + } + if (message.type === "desktopUpdateStatus") { return recordContact.pipe( Effect.andThen(Ref.set(latestUpdateReport, Option.some(message))), diff --git a/apps/server/src/telemetry/AnalyticsService.test.ts b/apps/server/src/telemetry/AnalyticsService.test.ts index 417841cb53e39..eb5858c4ba43b 100644 --- a/apps/server/src/telemetry/AnalyticsService.test.ts +++ b/apps/server/src/telemetry/AnalyticsService.test.ts @@ -165,6 +165,32 @@ const sendFor = ( }); it.layer(NodeServices.layer)("AnalyticsService test", (it) => { + it.effect("waits for desktop shell consent and honors a late telemetry opt-out", () => + Effect.gen(function* () { + const env: NodeJS.ProcessEnv = { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" }; + const batches = yield* sendFor( + 0, + respondWithStatus(204), + Effect.gen(function* () { + const analytics = yield* AnalyticsService.AnalyticsService; + yield* analytics.record("test.before-discovery"); + yield* analytics.flush; + env.T3CODE_TELEMETRY_ENABLED = "false"; + delete env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING; + yield* analytics.record("test.opted-out"); + yield* analytics.flush; + env.T3CODE_TELEMETRY_ENABLED = "true"; + yield* analytics.record("test.allowed"); + yield* analytics.flush; + }), + ).pipe(Effect.provideService(HostProcess.Environment, env)); + assert.deepEqual( + batches.flat().map((event) => event.event), + ["test.allowed"], + ); + }), + ); + it.effect("client owner reports cannot use up the server's owner cap", () => Effect.gen(function* () { const batches = yield* sendFor( diff --git a/apps/server/src/telemetry/AnalyticsService.ts b/apps/server/src/telemetry/AnalyticsService.ts index 4edc6621b0c3e..07b6f604e08a9 100644 --- a/apps/server/src/telemetry/AnalyticsService.ts +++ b/apps/server/src/telemetry/AnalyticsService.ts @@ -3,6 +3,7 @@ import * as HostProcess from "@t3tools/shared/HostProcess"; import type { ClientOs } from "@t3tools/contracts"; import * as Clock from "effect/Clock"; import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; import * as Context from "effect/Context"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; @@ -116,6 +117,26 @@ function serverOsFromNodePlatform(platform: string): ClientOs { /** @public */ export const make = Effect.gen(function* () { const telemetryConfig = yield* TelemetryEnvConfig; + const hostEnvironment = yield* HostProcess.Environment; + const awaitingShellConsent = hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1"; + // A cached PATH does not establish consent from the current login shell. + const telemetryEnabled = Effect.suspend(() => { + if (!telemetryConfig.enabled) return Effect.succeed(false); + if (!awaitingShellConsent) return Effect.succeed(true); + if (hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1") + return Effect.succeed(false); + const preference = hostEnvironment.T3CODE_TELEMETRY_ENABLED; + return Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe( + Config.withDefault(true), + Effect.provideService( + ConfigProvider.ConfigProvider, + ConfigProvider.fromEnv({ + env: preference === undefined ? {} : { T3CODE_TELEMETRY_ENABLED: preference }, + }), + ), + Effect.orElseSucceed(() => false), + ); + }); const httpClient = yield* HttpClient.HttpClient; const serverConfig = yield* ServerConfig.ServerConfig; const { distinctId, installId } = yield* getTelemetryIdentity; @@ -172,7 +193,7 @@ export const make = Effect.gen(function* () { const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* ( events: ReadonlyArray, ) { - if (!telemetryConfig.enabled || !distinctId) return; + if (!(yield* telemetryEnabled) || !distinctId) return; const payload = { api_key: telemetryConfig.posthogKey, @@ -284,7 +305,7 @@ export const make = Effect.gen(function* () { const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")( function* (event, properties) { - if (!telemetryConfig.enabled || !distinctId) return; + if (!(yield* telemetryEnabled) || !distinctId) return; // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs. const uuid = yield* Effect.exit(crypto.randomUUIDv7()); diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index fbb1aaf872614..32ef901326f77 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -2639,6 +2639,7 @@ describe("UsageService", () => { it.live("reports saved usage of a removed directory only for windows it reaches", () => Effect.gen(function* () { + yield* TestClock.setTime(Date.parse("2026-08-12T00:00:00Z")); const { transcript, settings, home } = yield* setup; // Saved usage is pruned after the retention window, so pin "now" near the write. yield* TestClock.setTime(Date.parse("2026-08-15T00:00:00Z")); diff --git a/packages/contracts/src/resourceTelemetry.ts b/packages/contracts/src/resourceTelemetry.ts index 5a004f93a2a4c..5e7045515f1f4 100644 --- a/packages/contracts/src/resourceTelemetry.ts +++ b/packages/contracts/src/resourceTelemetry.ts @@ -295,8 +295,48 @@ export const DesktopUpdateStatusReport = Schema.Struct({ }); export type DesktopUpdateStatusReport = typeof DesktopUpdateStatusReport.Type; +export const ShellEnvironmentPatch = Schema.Struct({ + PATH: Schema.optionalKey(Schema.NullOr(Schema.String)), + DBUS_SESSION_BUS_ADDRESS: Schema.optionalKey(Schema.NullOr(Schema.String)), + DISPLAY: Schema.optionalKey(Schema.NullOr(Schema.String)), + LANG: Schema.optionalKey(Schema.NullOr(Schema.String)), + LC_ALL: Schema.optionalKey(Schema.NullOr(Schema.String)), + LC_CTYPE: Schema.optionalKey(Schema.NullOr(Schema.String)), + SSH_AUTH_SOCK: Schema.optionalKey(Schema.NullOr(Schema.String)), + HOMEBREW_PREFIX: Schema.optionalKey(Schema.NullOr(Schema.String)), + HOMEBREW_CELLAR: Schema.optionalKey(Schema.NullOr(Schema.String)), + HOMEBREW_REPOSITORY: Schema.optionalKey(Schema.NullOr(Schema.String)), + XDG_CONFIG_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)), + XDG_CURRENT_DESKTOP: Schema.optionalKey(Schema.NullOr(Schema.String)), + XDG_DATA_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)), + XDG_RUNTIME_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)), + XDG_SESSION_DESKTOP: Schema.optionalKey(Schema.NullOr(Schema.String)), + XDG_SESSION_TYPE: Schema.optionalKey(Schema.NullOr(Schema.String)), + WAYLAND_DISPLAY: Schema.optionalKey(Schema.NullOr(Schema.String)), + SSL_CERT_FILE: Schema.optionalKey(Schema.NullOr(Schema.String)), + SSL_CERT_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)), + NODE_EXTRA_CA_CERTS: Schema.optionalKey(Schema.NullOr(Schema.String)), + T3CODE_TELEMETRY_ENABLED: Schema.optionalKey(Schema.NullOr(Schema.String)), + T3CODE_GITHUB_APP_CLIENT_ID: Schema.optionalKey(Schema.NullOr(Schema.String)), + __MISE_DIFF: Schema.optionalKey(Schema.NullOr(Schema.String)), + JAVA_HOME: Schema.optionalKey(Schema.NullOr(Schema.String)), + FNM_DIR: Schema.optionalKey(Schema.NullOr(Schema.String)), + FNM_MULTISHELL_PATH: Schema.optionalKey(Schema.NullOr(Schema.String)), +}); +export type ShellEnvironmentPatch = typeof ShellEnvironmentPatch.Type; + +export const DesktopShellEnvironmentSnapshot = Schema.Struct({ + version: Schema.Literal(1), + type: Schema.Literal("shellEnvironment"), + discovered: Schema.Boolean, + platform: Schema.String, + environment: ShellEnvironmentPatch, +}); +export type DesktopShellEnvironmentSnapshot = typeof DesktopShellEnvironmentSnapshot.Type; + export const DesktopHostTelemetryMessage = Schema.Union([ DesktopHostTelemetryHello, + DesktopShellEnvironmentSnapshot, DesktopHostTelemetrySnapshot, DesktopUpdateStatusReport, ]); diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index 690e6d94523c9..a4a17cda2cda9 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -2,6 +2,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it as effectIt } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import { DesktopHostTelemetryMessage } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -14,6 +16,7 @@ import * as NodePath from "node:path"; import { describe, expect, it, vi } from "vite-plus/test"; import { + applyShellEnvironment, CommandAvailability, CommandResolutionCache, type CommandAvailabilityChecker, @@ -35,6 +38,8 @@ import { XcodeGitLocation, } from "./shell.ts"; +const decodeDesktopHostMessage = Schema.decodeUnknownSync(DesktopHostTelemetryMessage); + const nativeProbe = vi.hoisted(() => ({ execFile: vi.fn(), })); @@ -1045,3 +1050,46 @@ effectIt.layer(NodeServices.layer)("resolveWindowsEnvironment", (it) => { }), ); }); + +describe("desktop shell environment updates", () => { + it.each(["win32", "linux", "darwin"] as const)( + "applies shell updates with %s PATH semantics", + (platform) => { + const message = decodeDesktopHostMessage({ + version: 1, + type: "shellEnvironment", + discovered: true, + platform, + environment: { + PATH: "C:\\fresh", + FNM_DIR: null, + __MISE_DIFF: null, + SSH_AUTH_SOCK: "/current.sock", + NODE_OPTIONS: "--bad", + }, + }); + expect(message.type).toBe("shellEnvironment"); + if (message.type !== "shellEnvironment") throw new Error("Expected shell environment update"); + const env: NodeJS.ProcessEnv = { + Path: "C:\\stale", + FNM_DIR: "stale", + __MISE_DIFF: "stale", + UNRELATED: "keep", + }; + applyShellEnvironment(env, message.environment, platform); + expect(env).toEqual({ + PATH: "C:\\fresh", + ...(platform === "win32" ? {} : { Path: "C:\\stale" }), + SSH_AUTH_SOCK: "/current.sock", + UNRELATED: "keep", + }); + env.Path = "C:\\stale"; + env.path = "C:\\other"; + applyShellEnvironment(env, { PATH: null, SSH_AUTH_SOCK: null }, platform); + expect(env).toEqual({ + ...(platform === "win32" ? {} : { Path: "C:\\stale", path: "C:\\other" }), + UNRELATED: "keep", + }); + }, + ); +}); diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index 73c54d1f8b88d..c5e6a7346fbef 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -10,6 +10,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import type { ShellEnvironmentPatch } from "@t3tools/contracts"; import * as HostProcess from "./HostProcess.ts"; import * as Context from "effect/Context"; const SHELL_ENV_NAME_PATTERN = /^[A-Z0-9_]+$/; @@ -908,13 +909,13 @@ function resolveKnownWindowsCliDirs(env: NodeJS.ProcessEnv): ReadonlyArray Date: Sun, 1 Nov 2026 05:05:11 -0600 Subject: [PATCH 004/183] fix(server): refresh Changes totals after remote polls (#28600) --- .../src/vcs/VcsStatusBroadcaster.test.ts | 90 +++++++++++++++---- apps/server/src/vcs/VcsStatusBroadcaster.ts | 16 +--- 2 files changed, 77 insertions(+), 29 deletions(-) diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 042f8274543e5..be3a286ffc32b 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -656,9 +656,12 @@ describe("VcsStatusBroadcaster", () => { }, ); - it.effect("an explicit refresh reads local totals after the fetch", () => { + it.effect("a remote poll refreshes Changes totals when divergence counts stay the same", () => { const state: Parameters[0] = { - currentLocalStatus: baseLocalStatus, + currentLocalStatus: { + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 }, + }, currentRemoteStatus: baseRemoteStatus, localStatusCalls: 0, remoteStatusCalls: 0, @@ -668,24 +671,79 @@ describe("VcsStatusBroadcaster", () => { return Effect.gen(function* () { const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; - const fetchStarted = yield* Deferred.make(); - const finishFetch = yield* Deferred.make(); - state.beforeRemoteStatus = Deferred.succeed(fetchStarted, undefined).pipe( - Effect.andThen(Deferred.await(finishFetch)), + yield* broadcaster.getStatus({ cwd: "/repo" }); + const subscribed = yield* Deferred.make(); + const polled = yield* Deferred.make(); + yield* broadcaster.streamStatus({ cwd: "/repo" }).pipe( + Stream.runForEach((event) => { + if (event._tag === "snapshot") return Deferred.succeed(subscribed, undefined); + if (event._tag === "remoteUpdated") return Deferred.succeed(polled, undefined); + return Effect.void; + }), + Effect.forkScoped, ); - const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped); - yield* Deferred.await(fetchStarted); - - const fetchedLocal: VcsStatusLocalResult = { + yield* Deferred.await(subscribed); + state.currentLocalStatus = { ...baseLocalStatus, - branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 }, + branchChanges: { baseRef: "origin/main", insertions: 107, deletions: 4 }, }; - state.currentLocalStatus = fetchedLocal; - yield* Deferred.succeed(finishFetch, undefined); + state.currentRemoteStatus = remoteStatusWithPr; + yield* TestClock.adjust("30 seconds"); + yield* Deferred.await(polled); + const status = yield* broadcaster.getStatus({ cwd: "/repo" }); + assert.deepStrictEqual(status.branchChanges, state.currentLocalStatus.branchChanges); + }).pipe(Effect.provide(layerTestFor(state)), Effect.scoped); + }); - const status = yield* Fiber.join(refresh); - assert.deepStrictEqual(status.branchChanges, fetchedLocal.branchChanges); - }).pipe(Effect.provide(layerTestFor(state))); + it.effect("an explicit refresh reads local totals after the fetch", () => { + return Effect.gen(function* () { + const fetchStarted = yield* Deferred.make(); + const finishFetch = yield* Deferred.make(); + let local: VcsStatusLocalResult = { + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions: 745, deletions: 24 }, + }; + let cachedLocal: VcsStatusLocalResult | undefined; + const readLocalStatus = () => Effect.sync(() => (cachedLocal ??= local)); + const layerTest = VcsStatusBroadcaster.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide(layerBackgroundPolicy(() => true)), + Layer.provide( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + localStatus: readLocalStatus, + invalidateStatus: () => + Effect.sync(() => { + cachedLocal = undefined; + }), + invalidateLocalStatus: () => + Effect.sync(() => { + cachedLocal = undefined; + }), + currentBranch: () => Effect.succeed(baseLocalStatus.refName), + invalidateRemoteStatus: () => Effect.void, + remoteStatus: () => + Deferred.succeed(fetchStarted, undefined).pipe( + Effect.andThen(Deferred.await(finishFetch)), + Effect.as(baseRemoteStatus), + ), + }), + ), + ); + yield* Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const refresh = yield* broadcaster.refreshStatus("/repo").pipe(Effect.forkScoped); + yield* Deferred.await(fetchStarted); + // Another reader can refill the local cache while fetch is still running. + yield* readLocalStatus(); + local = { + ...baseLocalStatus, + branchChanges: { baseRef: "origin/main", insertions: 0, deletions: 0 }, + }; + yield* Deferred.succeed(finishFetch, undefined); + const status = yield* Fiber.join(refresh); + assert.deepStrictEqual(status.branchChanges, local.branchChanges); + }).pipe(Effect.provide(layerTest)); + }); }); it.effect("publishes local status while an earlier lookup holds the remote lock", () => { diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index a8839d0c1cd0c..327e0bcb1bb41 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -477,23 +477,14 @@ export const make = Effect.gen(function* () { return yield* withRemoteWriteLock( cwd, Effect.gen(function* () { - const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value; const remoteRead = yield* readRemoteStatus(cwd, options); - const remote = remoteRead?.value; const pulled = options?.refreshUpstream === false ? null : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]); if (pulled !== null) return pulled.remote; - if ( - remote && - (!previousRemote || - previousRemote.aheadCount !== remote.aheadCount || - previousRemote.behindCount !== remote.behindCount || - previousRemote.aheadOfDefaultCount !== remote.aheadOfDefaultCount) - ) { - yield* refreshLocalStatusCore(cwd); - } + // Base refs and merge bases can move without changing divergence counts. + yield* refreshLocalStatusCore(cwd); return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true }); }), ); @@ -530,8 +521,7 @@ export const make = Effect.gen(function* () { yield* workflow.invalidateStatus(cwd); const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream }); // Fetch can move the base used for local Changes totals. - const local = yield* workflow.localStatus({ cwd }); - yield* updateCachedLocalStatus(cwd, local, { publish: true }); + yield* refreshLocalStatusCore(cwd); // Without a fetch, the cached behind count cannot justify an automatic pull. const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null; if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote); From 2b1021ce411db0f0aade4c513ab2bb4b0cdcaf94 Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 1 Nov 2026 07:06:39 -0600 Subject: [PATCH 005/183] perf(codex): trace app server request latency (#28666) --- .../src/protocol.test.ts | 90 +++++++++++++++++++ .../effect-codex-app-server/src/protocol.ts | 33 ++++--- 2 files changed, 113 insertions(+), 10 deletions(-) diff --git a/packages/effect-codex-app-server/src/protocol.test.ts b/packages/effect-codex-app-server/src/protocol.test.ts index 351f0d2b87731..b4c3ac7b7558b 100644 --- a/packages/effect-codex-app-server/src/protocol.test.ts +++ b/packages/effect-codex-app-server/src/protocol.test.ts @@ -7,6 +7,7 @@ import * as Schema from "effect/Schema"; import * as Sink from "effect/Sink"; import * as Stdio from "effect/Stdio"; import * as Stream from "effect/Stream"; +import * as Tracer from "effect/Tracer"; import * as TestClock from "effect/testing/TestClock"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -186,6 +187,95 @@ it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => { }), ); + it.effect( + "correlates concurrent request spans through responses, failures and interruption", + () => { + const spans: Array = []; + const tracer = Tracer.make({ + span: (options) => { + const span = new Tracer.NativeSpan(options); + spans.push(span); + return span; + }, + }); + return Effect.gen(function* () { + const { stdio, input, output } = yield* makeInMemoryStdio(); + const transport = yield* CodexProtocol.makeCodexAppServerPatchedProtocol({ stdio }); + const methods = ["model/list", "account/read", "skills/list"]; + const requests = []; + for (const method of methods) { + requests.push( + yield* transport.request(method, { secret: "private-payload" }).pipe(Effect.forkScoped), + ); + yield* Queue.take(output); + } + yield* Queue.offer( + input, + encodeJsonl({ id: 2, error: { code: -32602, message: "Invalid params" } }), + ); + yield* Fiber.await(requests[1]!); + yield* Queue.offer(input, encodeJsonl({ id: 1, result: { secret: "private-result" } })); + yield* Fiber.join(requests[0]!); + yield* Fiber.interrupt(requests[2]!); + // A late response for an interrupted request must not affect the next request. + yield* Queue.offer(input, encodeJsonl({ id: 3, result: {} })); + const next = yield* transport.request("config/read").pipe(Effect.forkScoped); + yield* Queue.take(output); + yield* Queue.offer(input, encodeJsonl({ id: 4, result: {} })); + yield* Fiber.join(next); + for (const [index, method] of [...methods, "config/read"].entries()) { + const request = spans.find( + (span) => + span.name === "CodexAppServerProtocol.request" && + span.attributes.get("rpc.request_id") === index + 1, + ); + assert.isDefined(request); + assert.equal(request!.attributes.get("rpc.method"), method); + assert.equal(request!.attributes.get("rpc.system"), "jsonrpc"); + assert.equal(request!.status._tag, "Ended"); + if (request!.status._tag === "Ended") { + assert.equal( + request!.status.exit._tag, + index === 1 || index === 2 ? "Failure" : "Success", + ); + } + for (const phase of ["enqueue", "awaitResponse"]) { + const child: Tracer.NativeSpan | undefined = spans.find( + (span) => + span.name === `CodexAppServerProtocol.request.${phase}` && + span.parent?._tag === "Some" && + span.parent.value.spanId === request!.spanId, + ); + assert.isDefined(child); + assert.equal(child!.traceId, request!.traceId); + assert.equal(child!.attributes.get("rpc.method"), method); + assert.equal(child!.attributes.get("rpc.request_id"), index + 1); + assert.equal(child!.status._tag, "Ended"); + } + } + const failedSend = yield* transport + .request("thread/start", { value: 1n }) + .pipe(Effect.exit); + assert.equal(failedSend._tag, "Failure"); + const sendSpans = spans.filter((span) => span.attributes.get("rpc.request_id") === 5); + assert.deepEqual( + sendSpans.map((span) => span.name), + ["CodexAppServerProtocol.request", "CodexAppServerProtocol.request.enqueue"], + ); + for (const span of sendSpans) { + assert.equal(span.attributes.get("rpc.method"), "thread/start"); + assert.equal(span.status._tag, "Ended"); + if (span.status._tag === "Ended") assert.equal(span.status.exit._tag, "Failure"); + } + for (const span of spans) { + const attrs = JSON.stringify([...span.attributes]); + assert.notInclude(attrs, "private-payload"); + assert.notInclude(attrs, "private-result"); + } + }).pipe(Effect.withTracer(tracer)); + }, + ); + it.effect.each([1, 7, 1024])( "preserves JSONL framing and UTF-8 across %i-byte input chunks", (chunkSize) => diff --git a/packages/effect-codex-app-server/src/protocol.ts b/packages/effect-codex-app-server/src/protocol.ts index c628079d0b491..fdf0863af0a16 100644 --- a/packages/effect-codex-app-server/src/protocol.ts +++ b/packages/effect-codex-app-server/src/protocol.ts @@ -502,17 +502,30 @@ export const makeCodexAppServerPatchedProtocol = Effect.fn("makeCodexAppServerPa nextRequestId, (current) => [current, current + 1] as const, ); + const attributes = { + "rpc.system": "jsonrpc", + "rpc.method": method, + "rpc.request_id": requestId, + }; + yield* Effect.annotateCurrentSpan(attributes); const deferred = yield* Deferred.make(); - yield* Ref.update(pending, (current) => - new Map(current).set(String(requestId), { deferred, method }), - ); - yield* offerOutgoing({ - id: requestId, - method, - ...(payload !== undefined ? { params: payload } : {}), - }).pipe(Effect.tapError(() => removePending(String(requestId)))); - return yield* Deferred.await(deferred).pipe( - Effect.onInterrupt(() => removePending(String(requestId))), + return yield* Effect.acquireUseRelease( + Ref.update(pending, (current) => + new Map(current).set(String(requestId), { deferred, method }), + ), + () => + Effect.gen(function* () { + yield* offerOutgoing({ + id: requestId, + method, + ...(payload !== undefined ? { params: payload } : {}), + }).pipe(Effect.withSpan("CodexAppServerProtocol.request.enqueue", { attributes })); + // Includes queue/stdin delivery, Codex work and response routing, not just T3 CPU. + return yield* Deferred.await(deferred).pipe( + Effect.withSpan("CodexAppServerProtocol.request.awaitResponse", { attributes }), + ); + }), + () => removePending(String(requestId)), ); }); From 82b10d546c1041d8eff40425f076d61f608d518f Mon Sep 17 00:00:00 2001 From: Yash Singh Date: Sun, 1 Nov 2026 07:21:42 -0600 Subject: [PATCH 006/183] fix(web): align pull request file viewed checkboxes (#28665) --- apps/web/src/components/pullRequest/PullRequestCodeTab.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx index 86e2e27b98365..8246fad432b43 100644 --- a/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx +++ b/apps/web/src/components/pullRequest/PullRequestCodeTab.tsx @@ -204,7 +204,7 @@ function FileViewedToggle({ {stat}