From d9cc01412269055dc351621de96b650827d7cd4d Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Wed, 18 Nov 2026 11:47:06 -0500 Subject: [PATCH 1/5] fix(server): bound outbound DNS lookups on macOS getaddrinfo has no timeout, and libuv runs it on at most half of the threadpool. When mDNSResponder never answers a name, two hung lookups block every later resolution in the process, so every outbound fetch fails with a connect timeout. Install a global undici dispatcher whose lookup gives dns.lookup 3s, then answers from c-ares, which does not use the threadpool. The threadpool is also raised to 16 for the backend unless the launcher already set it. Signed-off-by: Yordis Prieto --- .../DesktopBackendConfiguration.test.ts | 1 + .../backend/DesktopBackendConfiguration.ts | 3 + apps/server/src/binMain.ts | 3 + apps/server/src/outboundHttp.test.ts | 114 ++++++++++++++++ apps/server/src/outboundHttp.ts | 124 +++++++++++++++++- 5 files changed, 240 insertions(+), 5 deletions(-) diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 565a50f193e0f..1bc1caeb12998 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -242,6 +242,7 @@ describe("DesktopBackendConfiguration", () => { assert.equal(first.cwd, environment.backendCwd); assert.equal(first.captureOutput, true); assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1"); + assert.match(first.env.UV_THREADPOOL_SIZE ?? "", /^\d+$/); assert.equal(first.env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING, "1"); assert.isUndefined(first.env.T3CODE_PORT); assert.isUndefined(first.env.T3CODE_MODE); diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 82f0a30a40cd9..0902355763bb5 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -530,6 +530,7 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv const environment = yield* DesktopEnvironment.DesktopEnvironment; const serverExposure = yield* DesktopServerExposure.DesktopServerExposure; const backendExposure = yield* serverExposure.backendConfig; + const hostEnv = yield* HostProcess.Environment; const bootstrap = { mode: "desktop" as const, @@ -568,6 +569,8 @@ const resolvePrimaryStartConfig = Effect.fn("desktop.backendConfiguration.resolv env: { ...backendChildEnvPatch(), ELECTRON_RUN_AS_NODE: "1", + // A hung getaddrinfo holds a libuv thread for good; the default four starve everything else. + UV_THREADPOOL_SIZE: hostEnv.UV_THREADPOOL_SIZE ?? "16", T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1", T3CODE_CLI_PATH: Option.getOrUndefined(input.cliPath), [DESKTOP_HOST_SCOPE_ENV]: input.hostScope, diff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts index 0dabd73873440..c8eaacc27334c 100644 --- a/apps/server/src/binMain.ts +++ b/apps/server/src/binMain.ts @@ -4,6 +4,9 @@ import { enableCliCompileCache } from "./cliCompileCache.ts"; // ACP agents spawn `acp-mcp-bridge` per session and `acp-mcp-call` per tool call, so those fast // paths dispatch before the full CLI module graph (seconds of evaluation) loads. export async function runCliCommand() { + // Hung getaddrinfo calls each hold a libuv thread; headroom keeps file and crypto work moving. + // Only effective before the pool's first use, so a launcher-provided value wins. + process.env.UV_THREADPOOL_SIZE ??= "16"; const command = process.argv[2]; // Install the socket guard before importing code that can open outbound connections. const { ignoreMacosTypeOfServiceEinval } = await import("./outboundHttp.ts"); diff --git a/apps/server/src/outboundHttp.test.ts b/apps/server/src/outboundHttp.test.ts index ed3b09abaa5e6..7cc88673445af 100644 --- a/apps/server/src/outboundHttp.test.ts +++ b/apps/server/src/outboundHttp.test.ts @@ -1,4 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off - the test runs a real TLS h2 server to see which protocol fetch negotiates. +import * as NodeDns from "node:dns"; +import * as NodeHttp from "node:http"; import * as NodeHttp2 from "node:http2"; import * as NodeNet from "node:net"; import * as NodeTls from "node:tls"; @@ -16,6 +18,7 @@ import { builtinFetchUsesHttp2, ignoreMacosTypeOfServiceEinval, installHttp1FetchDispatcher, + makeBoundedLookup, } from "./outboundHttp.ts"; // Non-secret, self-signed 127.0.0.1 certificate, valid until 2126; ALPN h2 requires TLS. @@ -164,3 +167,114 @@ if (calls === 0) throw new Error("fetch did not call setTypeOfService"); }).pipe(Effect.provide(NodeServices.layer)), ); }); + +describe("makeBoundedLookup", () => { + type Callback = ( + error: NodeJS.ErrnoException | null, + address?: string | Array, + family?: number, + ) => void; + const hangingLookup = () => {}; + const resolverOf = (v4: Array, v6: Array = []) => ({ + resolve4: (_host: string, cb: (error: Error | null, found?: Array) => void) => + cb(null, v4), + resolve6: (_host: string, cb: (error: Error | null, found?: Array) => void) => + cb(null, v6), + }); + const run = ( + lookup: ReturnType, + options: Parameters[1], + ) => + new Promise<{ + error: NodeJS.ErrnoException | null; + address?: string | Array | undefined; + family?: number | undefined; + }>((resolve) => + lookup("example.test", options, (error, address, family) => + resolve({ error, address, family }), + ), + ); + + it("passes a prompt dns.lookup answer through untouched", async () => { + const lookup = makeBoundedLookup({ + timeoutMs: 50, + lookup: (_host, _options, cb) => cb(null, "10.0.0.1", 4), + resolver: resolverOf(["9.9.9.9"]), + }); + expect(await run(lookup, {})).toEqual({ error: null, address: "10.0.0.1", family: 4 }); + }); + + it("falls back to c-ares when getaddrinfo hangs, honoring family and all", async () => { + const lookup = makeBoundedLookup({ + timeoutMs: 10, + lookup: hangingLookup, + resolver: resolverOf(["192.0.2.1"], ["2001:db8::1"]), + }); + expect(await run(lookup, { family: 4 })).toEqual({ + error: null, + address: "192.0.2.1", + family: 4, + }); + expect(await run(lookup, { family: 6 })).toEqual({ + error: null, + address: "2001:db8::1", + family: 6, + }); + expect(await run(lookup, { all: true })).toEqual({ + error: null, + address: [ + { address: "192.0.2.1", family: 4 }, + { address: "2001:db8::1", family: 6 }, + ], + family: undefined, + }); + }); + + it("ignores a late getaddrinfo answer after the fallback replied", async () => { + let late: Callback = () => {}; + const lookup = makeBoundedLookup({ + timeoutMs: 10, + lookup: (_host, _options, cb) => { + late = cb; + }, + resolver: resolverOf(["192.0.2.1"]), + }); + const calls: Array = []; + await new Promise((resolve) => + lookup("example.test", { family: 4 }, (error, address) => { + calls.push(error ?? address); + resolve(); + }), + ); + late(null, "10.9.9.9", 4); + expect(calls).toEqual(["192.0.2.1"]); + }); + + it("reports ENOTFOUND when the fallback finds nothing", async () => { + const lookup = makeBoundedLookup({ + timeoutMs: 10, + lookup: hangingLookup, + resolver: resolverOf([]), + }); + expect((await run(lookup, { family: 4 })).error?.code).toBe("ENOTFOUND"); + }); + + it("lets undici connect through the bounded lookup while getaddrinfo hangs", async () => { + installHttp1FetchDispatcher({ + lookup: makeBoundedLookup({ + timeoutMs: 10, + lookup: hangingLookup, + resolver: resolverOf(["127.0.0.1"]), + }), + }); + const plain = NodeHttp.createServer((_request, response) => response.end("resolved")); + await new Promise((resolve) => plain.listen(0, "127.0.0.1", resolve)); + try { + const port = (plain.address() as NodeNet.AddressInfo).port; + const response = await Undici.request(`http://hung-dns.test:${port}/`); + expect(await response.body.text()).toBe("resolved"); + } finally { + await new Promise((resolve) => plain.close(() => resolve())); + } + }); +}); diff --git a/apps/server/src/outboundHttp.ts b/apps/server/src/outboundHttp.ts index ead14cb5d2035..f394bb96bb9a9 100644 --- a/apps/server/src/outboundHttp.ts +++ b/apps/server/src/outboundHttp.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics globalTimers:off -- A libuv getaddrinfo cannot be cancelled, so the lookup deadline is a plain timer cleared on every completion path. +import * as NodeDns from "node:dns"; import * as NodeModule from "node:module"; import * as NodeNet from "node:net"; @@ -10,25 +12,137 @@ const requireUndici = NodeModule.createRequire(import.meta.url); export const builtinFetchUsesHttp2 = (bundledUndiciVersion: string | undefined) => Number.parseInt(bundledUndiciVersion ?? "", 10) >= 8; +const LOOKUP_TIMEOUT_MS = 3_000; + +type LookupCallback = ( + error: NodeJS.ErrnoException | null, + address?: string | Array, + family?: number, +) => void; +type Lookup = (hostname: string, options: NodeDns.LookupOptions, callback: LookupCallback) => void; +type ResolveCallback = (error: Error | null, addresses?: Array) => void; +type ResolverLike = { + readonly resolve4: (hostname: string, callback: ResolveCallback) => void; + readonly resolve6: (hostname: string, callback: ResolveCallback) => void; +}; + +const notFound = (hostname: string): NodeJS.ErrnoException => + Object.assign(new Error(`getaddrinfo ENOTFOUND ${hostname}`), { + code: "ENOTFOUND", + syscall: "getaddrinfo", + hostname, + }); + +const wantedFamily = (family: NodeDns.LookupOptions["family"]): 0 | 4 | 6 => + family === 4 || family === "IPv4" ? 4 : family === 6 || family === "IPv6" ? 6 : 0; + +/** + * getaddrinfo has no timeout and every hung call permanently holds one of the four libuv + * threadpool threads (macOS mDNSResponder can stop answering one process for good). Bound the + * wait, then answer from c-ares, which does its own socket I/O and uses no pool thread. + */ +export function makeBoundedLookup( + options: { + readonly timeoutMs?: number; + readonly lookup?: Lookup; + readonly resolver?: ResolverLike; + } = {}, +): NodeNet.LookupFunction { + const timeoutMs = options.timeoutMs ?? LOOKUP_TIMEOUT_MS; + const lookup = options.lookup ?? (NodeDns.lookup as unknown as Lookup); + let resolver = options.resolver; + + return (( + hostname: string, + lookupOptions: NodeDns.LookupOptions | number, + callback: LookupCallback, + ) => { + const normalized: NodeDns.LookupOptions = + typeof lookupOptions === "number" ? { family: lookupOptions } : (lookupOptions ?? {}); + let settled = false; + const deliver = ( + error: NodeJS.ErrnoException | null, + addresses: Array, + ) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (error !== null) return callback(error); + if (normalized.all) return callback(null, addresses); + const first = addresses[0]; + return first === undefined + ? callback(notFound(hostname)) + : callback(null, first.address, first.family); + }; + + const timer = setTimeout(() => { + if (settled) return; + resolver ??= new NodeDns.Resolver({ timeout: 2_000, tries: 2 }); + const dns = resolver; + const family = wantedFamily(normalized.family); + const versions: Array<4 | 6> = family === 0 ? [4, 6] : [family]; + const collected: Partial>> = {}; + let pending = versions.length; + for (const version of versions) { + const onResult: ResolveCallback = (error, found) => { + collected[version] = + error || !found ? [] : found.map((address) => ({ address, family: version })); + if (--pending > 0) return; + const all = [...(collected[4] ?? []), ...(collected[6] ?? [])]; + deliver(all.length === 0 ? notFound(hostname) : null, all); + }; + if (version === 4) dns.resolve4(hostname, onResult); + else dns.resolve6(hostname, onResult); + } + }, timeoutMs); + timer.unref(); + + lookup(hostname, normalized, (error, address, resolvedFamily) => { + if (error) return deliver(error, []); + deliver( + null, + Array.isArray(address) + ? address + : [{ address: address ?? "", family: resolvedFamily ?? 4 }], + ); + }); + }) as NodeNet.LookupFunction; +} + /** Preserves the EnvHttpProxyAgent installed by --use-env-proxy / NODE_USE_ENV_PROXY. */ -export function installHttp1FetchDispatcher(): void { +export function installHttp1FetchDispatcher( + options: { readonly lookup?: NodeNet.LookupFunction } = {}, +): void { const undici = requireUndici("undici") as typeof Undici; + const connectOptions = + options.lookup === undefined ? {} : { connect: { lookup: options.lookup } }; // Node's agent comes from its internal undici copy, so `instanceof` against the npm class is false. const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent"; undici.setGlobalDispatcher( usesEnvProxy ? new undici.EnvHttpProxyAgent({ allowH2: false, + ...connectOptions, + ...(options.lookup === undefined ? {} : { proxyTls: { lookup: options.lookup } }), // ProxyAgent's connector forces h2 and ignores allowH2; replace it for HTTPS proxies. clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }), }) - : new undici.Agent({ allowH2: false }), + : new undici.Agent({ allowH2: false, ...connectOptions }), ); } -/** Avoids uncaught idle-timeout errors on h2 streams (https://github.com/nodejs/undici/issues/5936). */ -export function keepOutboundFetchOnHttp1(): void { - if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher(); +/** + * Avoids uncaught idle-timeout errors on h2 streams (https://github.com/nodejs/undici/issues/5936), + * and on macOS bounds name resolution so a hung getaddrinfo cannot starve the libuv threadpool. + */ +export function keepOutboundFetchOnHttp1( + // oxlint-disable-next-line t3code/no-global-process-runtime -- Runs before ACP dispatch without loading the Effect graph. + platform = process.platform, +): void { + const bounded = platform === "darwin"; + if (bounded || builtinFetchUsesHttp2(process.versions.undici)) { + installHttp1FetchDispatcher(bounded ? { lookup: makeBoundedLookup() } : {}); + } } // @types/node does not declare setTypeOfService yet. From 8179081e245e46f5a4639f66ffaac792cfcebbf4 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Wed, 18 Nov 2026 11:48:40 -0500 Subject: [PATCH 2/5] fix(terminal): fail provider terminal launch on an unreadable secret A provider terminal built its environment from literal variables only, so a secret-backed variable whose read failed was silently dropped and the shell started without the credential, falling back to whatever the server inherited. Read those secrets through the resolver and fail the launch with an error naming the variable and its reference, never the value. Signed-off-by: Yordis Prieto --- apps/server/src/server.ts | 1 + apps/server/src/terminal/Manager.test.ts | 60 +++++++++++++++++++++++- apps/server/src/terminal/Manager.ts | 38 ++++++++++++++- 3 files changed, 97 insertions(+), 2 deletions(-) diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 325c4b77206e2..7d444dcc6b54a 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -533,6 +533,7 @@ const layerTerminal = TerminalManager.layer( Layer.provide(layerPtyAdapter), Layer.provide(layerPortScanner), Layer.provide(layerNativeTelemetry), + Layer.provide(SecretResolver.layer), ); const layerPreview = Layer.empty.pipe( diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index a7d292e274033..a4e86d6182289 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -12,11 +12,13 @@ import { type TerminalOpenInput, ProviderDriverKind, ProviderInstanceId, + SecretProviderId, retainedTerminalHistory, terminalSequenceEnd, terminalSequenceStateAfter, TerminalProviderInstanceNotFoundError, } from "@t3tools/contracts"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { SpawnExecutableResolution } from "@t3tools/shared/shell"; import * as NodePtyAdapter from "./NodePtyAdapter.ts"; @@ -40,7 +42,7 @@ import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; import * as SynchronizedRef from "effect/SynchronizedRef"; import * as TestClock from "effect/testing/TestClock"; -import { expect, vi } from "vite-plus/test"; +import { describe, expect, vi } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; @@ -2744,6 +2746,62 @@ it.layer( ), ); + describe("secret-backed provider environment", () => { + const secret = { provider: SecretProviderId.make("vault"), reference: "kv/api#key" }; + const settingsWithSecret = ServerSettings.layerTest({ + providerInstances: { + [ProviderInstanceId.make("codex_secret")]: { + driver: ProviderDriverKind.make("codex"), + environment: [{ name: "PROVIDER_API_KEY", value: secret, sensitive: true }], + }, + }, + }); + const resolveWith = (read: SecretResolver.SecretResolver["Service"]["read"] | undefined) => + Effect.gen(function* () { + const path = yield* Path.Path; + const serverSettings = yield* ServerSettings.ServerSettingsService; + return yield* TerminalManager.resolveProviderInstanceTerminalEnvironment({ + deriveProviderInstanceConfigMap, + serverSettings, + path, + rawProviderInstanceId: "codex_secret", + env: undefined, + secrets: + read === undefined + ? undefined + : SecretResolver.SecretResolver.of({ + read, + invalidate: () => Effect.void, + label: (provider) => Effect.succeed(provider), + }), + }); + }).pipe(Effect.provide(settingsWithSecret)); + + it.effect("reads the secret into the terminal environment", () => + Effect.gen(function* () { + const environment = yield* resolveWith(() => Effect.succeed(["sk-from-vault"])); + expect(environment.PROVIDER_API_KEY).toBe("sk-from-vault"); + }), + ); + + it.effect("fails the launch naming the variable and reference when the read fails", () => + Effect.gen(function* () { + const error = yield* resolveWith(() => Effect.succeed([undefined])).pipe(Effect.flip); + expect(error._tag).toBe("TerminalProviderEnvironmentError"); + const detail = String((error as { cause: unknown }).cause); + expect(detail).toContain("PROVIDER_API_KEY"); + expect(detail).toContain("vault:kv/api#key"); + }), + ); + + it.effect("fails the launch when no secret resolver is available", () => + Effect.gen(function* () { + const error = yield* resolveWith(undefined).pipe(Effect.flip); + expect(error._tag).toBe("TerminalProviderEnvironmentError"); + }), + ); + }); + it.effect("restarts a running terminal when the resolved provider environment changes", () => Effect.gen(function* () { const providerInstanceId = ProviderInstanceId.make("codex_work"); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 28509cb114bd4..2d5c84b3e83ee 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -75,6 +75,7 @@ import { import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts"; import type { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; +import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as ServerSettings from "../serverSettings.ts"; import { increment, terminalSessionsTotal } from "../observability/Metrics.ts"; import { expandHomeVariable } from "@t3tools/provider-core/server/pathExpansion"; @@ -1707,6 +1708,7 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( readonly path: Path.Path; readonly rawProviderInstanceId: string; readonly env: Record | undefined; + readonly secrets?: SecretResolver.SecretResolver["Service"] | undefined; }) { const providerInstanceId = ProviderInstanceId.make(input.rawProviderInstanceId); const settings = yield* input.serverSettings.getSettings.pipe( @@ -1717,8 +1719,40 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( return yield* new TerminalProviderInstanceNotFoundError({ providerInstanceId }); } + // A shell missing a configured credential would fall back to whatever the server inherited, + // so an unreadable secret fails the launch instead of dropping the variable. + const secretVariables = (instance.environment ?? []).flatMap((variable) => + typeof variable.value === "string" ? [] : [{ name: variable.name, reference: variable.value }], + ); + const secretValues = + secretVariables.length === 0 + ? [] + : input.secrets === undefined + ? secretVariables.map(() => undefined) + : yield* input.secrets.read(secretVariables.map(({ reference }) => reference)); + const unreadable = secretVariables.filter( + (_, index) => (secretValues[index] ?? "").trim() === "", + ); + if (unreadable.length > 0) { + return yield* new TerminalProviderEnvironmentError({ + providerInstanceId, + cause: new Error( + `Could not read ${unreadable + .map(({ name, reference }) => `${name} (${reference.provider}:${reference.reference})`) + .join(", ")} from its secret provider. Unlock it, then try again.`, + ), + }); + } + let resolved = yield* overlayProviderInstanceEnvironment( - literalProviderInstanceEnvironment(instance.environment), + [ + ...literalProviderInstanceEnvironment(instance.environment), + ...secretVariables.map(({ name }, index) => ({ + name, + value: secretValues[index] ?? "", + sensitive: true, + })), + ], input.env ?? {}, ); if (instance.driver === "codex") { @@ -1753,6 +1787,7 @@ export const make = Effect.fn("TerminalManager.make")(function* ( const portDiscovery = yield* PortScanner.PortDiscovery; const nativeTelemetry = yield* NativeTelemetryClient.NativeTelemetryClient; const serverSettings = yield* ServerSettings.ServerSettingsService; + const secrets = yield* SecretResolver.SecretResolver; const path = yield* Path.Path; const resolveProviderInstanceEnvironment = Effect.fn( "terminal.resolveProviderInstanceEnvironment", @@ -1763,6 +1798,7 @@ export const make = Effect.fn("TerminalManager.make")(function* ( path, rawProviderInstanceId, env, + secrets, }), ); return yield* makeWithOptions({ From 91444260d5a211c133c5e884762df509cbcb6507 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 21 Nov 2026 16:09:21 -0500 Subject: [PATCH 3/5] fix(server): proxy lookups and secret retries follow review The HTTPS proxy pool now resolves the proxy hostname through the bounded lookup. A terminal launch that cannot read a secret forgets that failed read so a retry after unlocking asks the provider again, and the error names the unreadable variables and references. Signed-off-by: Yordis Prieto --- .../DesktopBackendConfiguration.test.ts | 11 +++++-- apps/server/src/outboundHttp.test.ts | 33 ++++++++++++++++++- apps/server/src/outboundHttp.ts | 2 +- apps/server/src/terminal/Manager.test.ts | 20 +++++++---- apps/server/src/terminal/Manager.ts | 11 ++++--- packages/contracts/src/terminal.ts | 11 ++++++- 6 files changed, 70 insertions(+), 18 deletions(-) diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts index 1bc1caeb12998..657240420f3cd 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.test.ts @@ -229,8 +229,12 @@ describe("DesktopBackendConfiguration", () => { const environment = yield* DesktopEnvironment.DesktopEnvironment; const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration; - const first = yield* configuration.resolvePrimary; - const second = yield* configuration.resolvePrimary; + const first = yield* configuration.resolvePrimary.pipe( + Effect.provideService(HostProcess.Environment, {}), + ); + const second = yield* configuration.resolvePrimary.pipe( + Effect.provideService(HostProcess.Environment, { UV_THREADPOOL_SIZE: "" }), + ); assert.equal(first.executablePath, process.execPath); assert.deepEqual(first.args.slice(0, 3), [ @@ -242,7 +246,8 @@ describe("DesktopBackendConfiguration", () => { assert.equal(first.cwd, environment.backendCwd); assert.equal(first.captureOutput, true); assert.equal(first.env.ELECTRON_RUN_AS_NODE, "1"); - assert.match(first.env.UV_THREADPOOL_SIZE ?? "", /^\d+$/); + assert.equal(first.env.UV_THREADPOOL_SIZE, "16"); + assert.equal(second.env.UV_THREADPOOL_SIZE, ""); assert.equal(first.env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING, "1"); assert.isUndefined(first.env.T3CODE_PORT); assert.isUndefined(first.env.T3CODE_MODE); diff --git a/apps/server/src/outboundHttp.test.ts b/apps/server/src/outboundHttp.test.ts index 7cc88673445af..7bd5349ee9b33 100644 --- a/apps/server/src/outboundHttp.test.ts +++ b/apps/server/src/outboundHttp.test.ts @@ -12,7 +12,7 @@ import * as Stream from "effect/Stream"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { FetchHttpClient, HttpClient } from "effect/http"; import * as Undici from "undici"; -import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test"; +import { afterAll, afterEach, beforeAll, describe, expect, vi } from "vite-plus/test"; import { builtinFetchUsesHttp2, @@ -277,4 +277,35 @@ describe("makeBoundedLookup", () => { await new Promise((resolve) => plain.close(() => resolve())); } }); + + it("resolves an env proxy hostname through the bounded lookup for HTTPS requests", async () => { + const proxy = NodeHttp.createServer(); + proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => { + const [host, port] = (request.url ?? "").split(":"); + const upstream = NodeNet.connect(Number(port), host, () => { + client.write("HTTP/1.1 200 Connection Established\r\n\r\n"); + upstream.pipe(client); + client.pipe(upstream); + }); + }); + await new Promise((resolve) => proxy.listen(0, "127.0.0.1", resolve)); + try { + const proxyUrl = `http://hung-proxy.test:${(proxy.address() as NodeNet.AddressInfo).port}`; + for (const name of ["https_proxy", "HTTPS_PROXY"]) vi.stubEnv(name, proxyUrl); + for (const name of ["no_proxy", "NO_PROXY"]) vi.stubEnv(name, ""); + Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent()); + installHttp1FetchDispatcher({ + lookup: makeBoundedLookup({ + timeoutMs: 10, + lookup: hangingLookup, + resolver: resolverOf(["127.0.0.1"]), + }), + }); + expect(await versionViaGlobalDispatcher()).toBe("1.1"); + } finally { + vi.unstubAllEnvs(); + proxy.closeAllConnections(); + await new Promise((resolve) => proxy.close(() => resolve())); + } + }); }); diff --git a/apps/server/src/outboundHttp.ts b/apps/server/src/outboundHttp.ts index f394bb96bb9a9..530941475ad24 100644 --- a/apps/server/src/outboundHttp.ts +++ b/apps/server/src/outboundHttp.ts @@ -125,7 +125,7 @@ export function installHttp1FetchDispatcher( ...connectOptions, ...(options.lookup === undefined ? {} : { proxyTls: { lookup: options.lookup } }), // ProxyAgent's connector forces h2 and ignores allowH2; replace it for HTTPS proxies. - clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }), + clientFactory: (origin) => new undici.Pool(origin, { allowH2: false, ...connectOptions }), }) : new undici.Agent({ allowH2: false, ...connectOptions }), ); diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index a4e86d6182289..a37da09f71d99 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -2756,7 +2756,10 @@ it.layer( }, }, }); - const resolveWith = (read: SecretResolver.SecretResolver["Service"]["read"] | undefined) => + const resolveWith = ( + read: SecretResolver.SecretResolver["Service"]["read"] | undefined, + invalidate: SecretResolver.SecretResolver["Service"]["invalidate"] = () => Effect.void, + ) => Effect.gen(function* () { const path = yield* Path.Path; const serverSettings = yield* ServerSettings.ServerSettingsService; @@ -2771,7 +2774,7 @@ it.layer( ? undefined : SecretResolver.SecretResolver.of({ read, - invalidate: () => Effect.void, + invalidate, label: (provider) => Effect.succeed(provider), }), }); @@ -2784,13 +2787,16 @@ it.layer( }), ); - it.effect("fails the launch naming the variable and reference when the read fails", () => + it.effect("fails the launch naming the variable and forgets the failed read", () => Effect.gen(function* () { - const error = yield* resolveWith(() => Effect.succeed([undefined])).pipe(Effect.flip); + const invalidated: Array | undefined> = []; + const error = yield* resolveWith( + () => Effect.succeed([undefined]), + (references) => Effect.sync(() => void invalidated.push(references)), + ).pipe(Effect.flip); expect(error._tag).toBe("TerminalProviderEnvironmentError"); - const detail = String((error as { cause: unknown }).cause); - expect(detail).toContain("PROVIDER_API_KEY"); - expect(detail).toContain("vault:kv/api#key"); + expect(error.message).toContain("PROVIDER_API_KEY (vault:kv/api#key)"); + expect(invalidated).toEqual([[secret]]); }), ); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 2d5c84b3e83ee..6dc05b6973fd9 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -1734,13 +1734,14 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( (_, index) => (secretValues[index] ?? "").trim() === "", ); if (unreadable.length > 0) { + // The resolver caches failed reads too, so a retry after unlocking must ask the provider again. + if (input.secrets !== undefined) { + yield* input.secrets.invalidate(unreadable.map(({ reference }) => reference)); + } return yield* new TerminalProviderEnvironmentError({ providerInstanceId, - cause: new Error( - `Could not read ${unreadable - .map(({ name, reference }) => `${name} (${reference.provider}:${reference.reference})`) - .join(", ")} from its secret provider. Unlock it, then try again.`, - ), + unreadableSecrets: unreadable, + cause: new Error("A configured secret could not be read from its secret provider."), }); } diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index fea5f216f80bd..791c56acc4b53 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -1,6 +1,7 @@ import * as Schema from "effect/Schema"; import { TrimmedNonEmptyString } from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; +import { SecretReference } from "./secretReference.ts"; export const DEFAULT_TERMINAL_ID = "term-1"; export const DEFAULT_MAX_TERMINAL_BUFFER_BYTES = 512 * 1024; @@ -469,11 +470,19 @@ export class TerminalProviderEnvironmentError extends Schema.TaggedError `${name} (${reference.provider}:${reference.reference})`, + ); + return unreadable.length === 0 + ? `Could not prepare the terminal environment for provider instance: ${this.providerInstanceId}` + : `Could not read ${unreadable.join(", ")} for provider instance: ${this.providerInstanceId}. Unlock its secret provider, then try again.`; } } From fb07133a5151c186f910cdb9bb3c4bef2f01d413 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 21 Nov 2026 16:16:55 -0500 Subject: [PATCH 4/5] refactor(server): launchers set the threadpool size and platform is passed in The service launcher now gives its child UV_THREADPOOL_SIZE like the desktop launcher does, instead of the server mutating its own environment at startup. keepOutboundFetchOnHttp1 takes the platform from HostProcess.Platform rather than reading process.platform. Signed-off-by: Yordis Prieto --- apps/server/src/binCli.ts | 26 +++++++++++++++---------- apps/server/src/binMain.ts | 3 --- apps/server/src/outboundHttp.ts | 5 +---- apps/server/src/serviceLauncher.test.ts | 8 +++++--- apps/server/src/serviceLauncher.ts | 7 ++++++- 5 files changed, 28 insertions(+), 21 deletions(-) diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 995b207e7c781..244653829c32e 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -4,6 +4,7 @@ import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Layer from "effect/Layer"; import { Argument, Command } from "effect/cli"; import * as CliError from "effect/cli/CliError"; @@ -121,16 +122,21 @@ export const cli = makeCli(); export function runCli() { extendConnectionAttemptTimeout(); - keepOutboundFetchOnHttp1(); - offerCliInstall({ - args: process.argv.slice(2), - // A child started over IPC (a service launcher) has no one to answer. - interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY) && process.send === undefined, - foreground: inTerminalForeground, - confirm: confirmCliInstall, - }).pipe( - // The offer handles its own errors; even an unexpected defect must not stop the command. - Effect.catchDefect(() => Effect.succeed(true)), + HostProcess.Platform.pipe( + Effect.map(keepOutboundFetchOnHttp1), + Effect.andThen( + offerCliInstall({ + args: process.argv.slice(2), + // A child started over IPC (a service launcher) has no one to answer. + interactive: + Boolean(process.stdin.isTTY && process.stdout.isTTY) && process.send === undefined, + foreground: inTerminalForeground, + confirm: confirmCliInstall, + }).pipe( + // The offer handles its own errors; even an unexpected defect must not stop the command. + Effect.catchDefect(() => Effect.succeed(true)), + ), + ), Effect.flatMap((proceed) => proceed ? Command.run(cli, { version: packageJson.version }) diff --git a/apps/server/src/binMain.ts b/apps/server/src/binMain.ts index c8eaacc27334c..0dabd73873440 100644 --- a/apps/server/src/binMain.ts +++ b/apps/server/src/binMain.ts @@ -4,9 +4,6 @@ import { enableCliCompileCache } from "./cliCompileCache.ts"; // ACP agents spawn `acp-mcp-bridge` per session and `acp-mcp-call` per tool call, so those fast // paths dispatch before the full CLI module graph (seconds of evaluation) loads. export async function runCliCommand() { - // Hung getaddrinfo calls each hold a libuv thread; headroom keeps file and crypto work moving. - // Only effective before the pool's first use, so a launcher-provided value wins. - process.env.UV_THREADPOOL_SIZE ??= "16"; const command = process.argv[2]; // Install the socket guard before importing code that can open outbound connections. const { ignoreMacosTypeOfServiceEinval } = await import("./outboundHttp.ts"); diff --git a/apps/server/src/outboundHttp.ts b/apps/server/src/outboundHttp.ts index 530941475ad24..7d52c5b427a38 100644 --- a/apps/server/src/outboundHttp.ts +++ b/apps/server/src/outboundHttp.ts @@ -135,10 +135,7 @@ export function installHttp1FetchDispatcher( * Avoids uncaught idle-timeout errors on h2 streams (https://github.com/nodejs/undici/issues/5936), * and on macOS bounds name resolution so a hung getaddrinfo cannot starve the libuv threadpool. */ -export function keepOutboundFetchOnHttp1( - // oxlint-disable-next-line t3code/no-global-process-runtime -- Runs before ACP dispatch without loading the Effect graph. - platform = process.platform, -): void { +export function keepOutboundFetchOnHttp1(platform: NodeJS.Platform): void { const bounded = platform === "darwin"; if (bounded || builtinFetchUsesHttp2(process.versions.undici)) { installHttp1FetchDispatcher(bounded ? { lookup: makeBoundedLookup() } : {}); diff --git a/apps/server/src/serviceLauncher.test.ts b/apps/server/src/serviceLauncher.test.ts index 4bfe776a3aba8..a955003a65019 100644 --- a/apps/server/src/serviceLauncher.test.ts +++ b/apps/server/src/serviceLauncher.test.ts @@ -1322,6 +1322,7 @@ if (context.update?.status === "pending") { yield* fs.writeFileString(envPath, "T3CODE_TEST_SERVICE_TOKEN=initial\n"); vi.stubEnv("T3CODE_HOME", root); vi.stubEnv("T3CODE_TEST_SERVICE_TOKEN", "inherited"); + vi.stubEnv("UV_THREADPOOL_SIZE", undefined); yield* Effect.addFinalizer(() => Effect.sync(() => vi.unstubAllEnvs())); yield* fs.makeDirectory(path.dirname(databasePath), { recursive: true }); yield* fs.writeFileString(databasePath, "before trial"); @@ -1331,6 +1332,7 @@ import { appendFileSync, writeFileSync } from "node:fs"; const context = JSON.parse(process.env.T3_SERVICE_LAUNCHER_CONTEXT); appendFileSync(${JSON.stringify(observationsPath)}, JSON.stringify({ token: process.env.T3CODE_TEST_SERVICE_TOKEN, + threadpool: process.env.UV_THREADPOOL_SIZE, update: context.update?.status ?? "active", }) + "\\n"); if (context.update?.status === "pending") { @@ -1391,9 +1393,9 @@ if (context.update?.status === "pending") { .split("\n") .map((line) => JSON.parse(line)); assert.deepEqual(observations, [ - { token: "initial", update: "active" }, - { token: "initial", update: "pending" }, - { token: "initial", update: "rolled-back" }, + { token: "initial", threadpool: "16", update: "active" }, + { token: "initial", threadpool: "16", update: "pending" }, + { token: "initial", threadpool: "16", update: "rolled-back" }, ]); assert.equal((yield* HostProcess.Environment).T3CODE_TEST_SERVICE_TOKEN, "inherited"); assert.equal(yield* fs.readFileString(envPath), "T3CODE_TEST_SERVICE_TOKEN=changed\n"); diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index fad391896d307..665f7f0320f30 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -1176,7 +1176,12 @@ export class Launcher { }; const spawnArguments = runtimeSpawnArguments(paths); const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, { - env: { ...this.#environment, [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context) }, + env: { + ...this.#environment, + // A hung getaddrinfo holds a libuv thread for good; the default four starve everything else. + UV_THREADPOOL_SIZE: this.#environment.UV_THREADPOOL_SIZE ?? "16", + [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context), + }, stdio: this.#output === undefined ? ["inherit", "inherit", "inherit", "ipc"] From 76c508baa662788a238aa062c1335effb1d33b7a Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Sat, 21 Nov 2026 16:41:39 -0500 Subject: [PATCH 5/5] fix(server): address review on threadpool override, env order, and test cleanup - serviceLauncher keeps any spelling of UV_THREADPOOL_SIZE on Windows. - Terminal provider env overlays secrets in configured order, so a later row still wins. - outboundHttp tests close proxy tunnels and use fake timers for lookup deadlines. Signed-off-by: Yordis Prieto --- apps/server/src/outboundHttp.test.ts | 33 +++++++++++++++++------- apps/server/src/serviceLauncher.ts | 6 ++++- apps/server/src/terminal/Manager.test.ts | 18 +++++++++++-- apps/server/src/terminal/Manager.ts | 19 +++++--------- 4 files changed, 52 insertions(+), 24 deletions(-) diff --git a/apps/server/src/outboundHttp.test.ts b/apps/server/src/outboundHttp.test.ts index 7bd5349ee9b33..00325019cd205 100644 --- a/apps/server/src/outboundHttp.test.ts +++ b/apps/server/src/outboundHttp.test.ts @@ -58,6 +58,7 @@ beforeAll(async () => { }); afterEach(() => { + vi.useRealTimers(); Undici.setGlobalDispatcher(defaultDispatcher); NodeNet.setDefaultAutoSelectFamilyAttemptTimeout(defaultAttemptTimeout); }); @@ -195,6 +196,11 @@ describe("makeBoundedLookup", () => { ), ); + const afterDeadline = (pending: Promise) => { + vi.advanceTimersByTime(10); + return pending; + }; + it("passes a prompt dns.lookup answer through untouched", async () => { const lookup = makeBoundedLookup({ timeoutMs: 50, @@ -205,22 +211,23 @@ describe("makeBoundedLookup", () => { }); it("falls back to c-ares when getaddrinfo hangs, honoring family and all", async () => { + vi.useFakeTimers(); const lookup = makeBoundedLookup({ timeoutMs: 10, lookup: hangingLookup, resolver: resolverOf(["192.0.2.1"], ["2001:db8::1"]), }); - expect(await run(lookup, { family: 4 })).toEqual({ + expect(await afterDeadline(run(lookup, { family: 4 }))).toEqual({ error: null, address: "192.0.2.1", family: 4, }); - expect(await run(lookup, { family: 6 })).toEqual({ + expect(await afterDeadline(run(lookup, { family: 6 }))).toEqual({ error: null, address: "2001:db8::1", family: 6, }); - expect(await run(lookup, { all: true })).toEqual({ + expect(await afterDeadline(run(lookup, { all: true }))).toEqual({ error: null, address: [ { address: "192.0.2.1", family: 4 }, @@ -231,6 +238,7 @@ describe("makeBoundedLookup", () => { }); it("ignores a late getaddrinfo answer after the fallback replied", async () => { + vi.useFakeTimers(); let late: Callback = () => {}; const lookup = makeBoundedLookup({ timeoutMs: 10, @@ -240,23 +248,26 @@ describe("makeBoundedLookup", () => { resolver: resolverOf(["192.0.2.1"]), }); const calls: Array = []; - await new Promise((resolve) => - lookup("example.test", { family: 4 }, (error, address) => { - calls.push(error ?? address); - resolve(); - }), + await afterDeadline( + new Promise((resolve) => + lookup("example.test", { family: 4 }, (error, address) => { + calls.push(error ?? address); + resolve(); + }), + ), ); late(null, "10.9.9.9", 4); expect(calls).toEqual(["192.0.2.1"]); }); it("reports ENOTFOUND when the fallback finds nothing", async () => { + vi.useFakeTimers(); const lookup = makeBoundedLookup({ timeoutMs: 10, lookup: hangingLookup, resolver: resolverOf([]), }); - expect((await run(lookup, { family: 4 })).error?.code).toBe("ENOTFOUND"); + expect((await afterDeadline(run(lookup, { family: 4 }))).error?.code).toBe("ENOTFOUND"); }); it("lets undici connect through the bounded lookup while getaddrinfo hangs", async () => { @@ -280,6 +291,8 @@ describe("makeBoundedLookup", () => { it("resolves an env proxy hostname through the bounded lookup for HTTPS requests", async () => { const proxy = NodeHttp.createServer(); + // CONNECT sockets leave the server's connection tracking, so closeAllConnections misses them. + const tunnels: Array = []; proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => { const [host, port] = (request.url ?? "").split(":"); const upstream = NodeNet.connect(Number(port), host, () => { @@ -287,6 +300,7 @@ describe("makeBoundedLookup", () => { upstream.pipe(client); client.pipe(upstream); }); + tunnels.push(client, upstream); }); await new Promise((resolve) => proxy.listen(0, "127.0.0.1", resolve)); try { @@ -304,6 +318,7 @@ describe("makeBoundedLookup", () => { expect(await versionViaGlobalDispatcher()).toBe("1.1"); } finally { vi.unstubAllEnvs(); + for (const socket of tunnels) socket.destroy(); proxy.closeAllConnections(); await new Promise((resolve) => proxy.close(() => resolve())); } diff --git a/apps/server/src/serviceLauncher.ts b/apps/server/src/serviceLauncher.ts index 665f7f0320f30..9abdfd2ba3a05 100644 --- a/apps/server/src/serviceLauncher.ts +++ b/apps/server/src/serviceLauncher.ts @@ -1175,11 +1175,15 @@ export class Launcher { ...(update === undefined ? {} : { update }), }; const spawnArguments = runtimeSpawnArguments(paths); + // Windows reads names without regard to case, so any spelling there is the user's override. + const threadpoolSizeSet = Object.keys(this.#environment).some( + (name) => name.toUpperCase() === "UV_THREADPOOL_SIZE", + ); const child = NodeChildProcess.spawn(spawnArguments.command, spawnArguments.args, { env: { ...this.#environment, // A hung getaddrinfo holds a libuv thread for good; the default four starve everything else. - UV_THREADPOOL_SIZE: this.#environment.UV_THREADPOOL_SIZE ?? "16", + ...(threadpoolSizeSet ? {} : { UV_THREADPOOL_SIZE: "16" }), [SERVICE_LAUNCHER_CONTEXT_ENV]: JSON.stringify(context), }, stdio: diff --git a/apps/server/src/terminal/Manager.test.ts b/apps/server/src/terminal/Manager.test.ts index a37da09f71d99..f250032a21520 100644 --- a/apps/server/src/terminal/Manager.test.ts +++ b/apps/server/src/terminal/Manager.test.ts @@ -2754,11 +2754,19 @@ it.layer( driver: ProviderDriverKind.make("codex"), environment: [{ name: "PROVIDER_API_KEY", value: secret, sensitive: true }], }, + [ProviderInstanceId.make("codex_secret_shadowed")]: { + driver: ProviderDriverKind.make("codex"), + environment: [ + { name: "PROVIDER_API_KEY", value: secret, sensitive: true }, + { name: "PROVIDER_API_KEY", value: "configured-later", sensitive: false }, + ], + }, }, }); const resolveWith = ( read: SecretResolver.SecretResolver["Service"]["read"] | undefined, invalidate: SecretResolver.SecretResolver["Service"]["invalidate"] = () => Effect.void, + rawProviderInstanceId = "codex_secret", ) => Effect.gen(function* () { const path = yield* Path.Path; @@ -2767,7 +2775,7 @@ it.layer( deriveProviderInstanceConfigMap, serverSettings, path, - rawProviderInstanceId: "codex_secret", + rawProviderInstanceId, env: undefined, secrets: read === undefined @@ -2780,10 +2788,16 @@ it.layer( }); }).pipe(Effect.provide(settingsWithSecret)); - it.effect("reads the secret into the terminal environment", () => + it.effect("reads secrets into the terminal environment in configured order", () => Effect.gen(function* () { const environment = yield* resolveWith(() => Effect.succeed(["sk-from-vault"])); expect(environment.PROVIDER_API_KEY).toBe("sk-from-vault"); + const shadowed = yield* resolveWith( + () => Effect.succeed(["sk-from-vault"]), + undefined, + "codex_secret_shadowed", + ); + expect(shadowed.PROVIDER_API_KEY).toBe("configured-later"); }), ); diff --git a/apps/server/src/terminal/Manager.ts b/apps/server/src/terminal/Manager.ts index 6dc05b6973fd9..1bac488899b1b 100644 --- a/apps/server/src/terminal/Manager.ts +++ b/apps/server/src/terminal/Manager.ts @@ -68,10 +68,7 @@ import * as SynchronizedRef from "effect/SynchronizedRef"; import packageJson from "../../package.json" with { type: "json" }; import * as ServerConfig from "../config.ts"; -import { - literalProviderInstanceEnvironment, - overlayProviderInstanceEnvironment, -} from "@t3tools/provider-core/server/instanceEnvironment"; +import { overlayProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; import { resolveCodexHomeLayout } from "../provider/Drivers/CodexHomeLayout.ts"; import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts"; import type { deriveProviderInstanceConfigMap } from "../provider/ProviderInstanceRegistryHydration.ts"; @@ -1745,15 +1742,13 @@ export const resolveProviderInstanceTerminalEnvironment = Effect.fn( }); } + let secretIndex = 0; let resolved = yield* overlayProviderInstanceEnvironment( - [ - ...literalProviderInstanceEnvironment(instance.environment), - ...secretVariables.map(({ name }, index) => ({ - name, - value: secretValues[index] ?? "", - sensitive: true, - })), - ], + (instance.environment ?? []).map((variable) => + typeof variable.value === "string" + ? { ...variable, value: variable.value } + : { ...variable, value: secretValues[secretIndex++] ?? "", sensitive: true }, + ), input.env ?? {}, ); if (instance.driver === "codex") {