From d4a5218a766f13eec66ec5fdcb2e2e34f65a543c Mon Sep 17 00:00:00 2001 From: JUN Date: Tue, 1 Dec 2026 13:48:42 +0900 Subject: [PATCH 01/50] docs(devlog): Grok Build 3.32.24 / CLI 2.0.6 integration and quota routing notes (#9274) --- .../261201_grok_build_integration/000_plan.md | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 devlog/_plan/261201_grok_build_integration/000_plan.md diff --git a/devlog/_plan/261201_grok_build_integration/000_plan.md b/devlog/_plan/261201_grok_build_integration/000_plan.md new file mode 100644 index 00000000000..0ae66d77c7c --- /dev/null +++ b/devlog/_plan/261201_grok_build_integration/000_plan.md @@ -0,0 +1,74 @@ +# Grok Build (`3.32.24` Desktop / `2.0.6` CLI) integration & quota routing notes + +Date: 2026-12-01. Branch `docs/261201-grok-build-integration`, base `origin/dev` `740109d34e`. + +## Context + +Cursor's desktop application and CLI have converged into **Grok Build**: + +- **Desktop app (`Grok Build.app` `3.32.24`):** In-place display rebrand over the existing Cursor desktop app identity, keeping existing local data directory compatibility while introducing `grok-build` CLI shims alongside `cursor`. +- **Unified CLI (`grok 2.0.6 [unified]`, public `1.0.97`):** Unified channel serving `grok`, `agent`, `cursor-agent`, and `cursor agent` through a shared unified agent-host runtime. +- **Open-source repository (`xai-org/grok-build`):** Public `main` remains at `1.0.45` (`2026-09-29`), while the shipped `2.0.x [unified]` CLI has moved to the unified agent-host architecture rather than the legacy standalone execution loop. + +## Subscription & quota routing behavior + +### 1. Account states and quota pools + +| Account state | Quota / billing model | Notes | +|---|---|---| +| **Unmerged Cursor subscription** (`Pro`, `Pro+`, `Ultra`, `Express`, `Enterprise`) | Split buckets: **Cursor Models** (Auto, Cursor Grok, Composer) + **Other Models** (named third-party models) | Usage beyond Cursor Models limits spills over to Other Models quota or on-demand spend (`Express` is restricted to Cursor Models). | +| **Unified subscription** (`Plus`, `Premium`, `Super`, `Ultra`) | **Single unified pool** (`total` usage) + prepaid credits + banked usage resets | Replaces the split Cursor Models / Other Models buckets once account unification is completed. | +| **Unmerged Grok / SuperGrok subscription** | Legacy xAI CLI proxy quota + `grok.com` reset credits until unified | Signing in with an unmerged SuperGrok / X Premium+ account on the unified CLI prompts the user either to unify accounts or to keep using the legacy `1.0.x` CLI until unified. | + +### 2. Dual-subscription users (unmerged Cursor + Grok) + +Before account unification, neither the desktop app nor the unified CLI combines or alternates between two separate subscriptions automatically — only the currently signed-in account is billed: + +- **`Grok Build.app`:** Uses Cursor sign-in and deducts exclusively from the **Cursor** subscription pool (showing a merge prompt to settle duplicate Cursor billing). +- **Unified CLI (`grok 2.0.6`):** + - Signing in with Cursor deducts exclusively from the **Cursor** subscription pool. + - Signing in with an unmerged Grok account prompts account unification or switching back to the legacy `1.0.x` CLI to spend the standalone Grok subscription. +- **OpenCodex upstream providers:** + - `cursor` provider (`src/oauth/cursor.ts`, `src/adapters/cursor.ts`) deducts from the **Cursor** subscription pool. + - `xai` provider (`src/providers/xai-transport.ts`, `src/grok/reset-coupons.ts`) routes via `cli-chat-proxy.grok.com/v1` and deducts from the **Grok** subscription pool. + +After completing account unification, existing Cursor balances and standalone plans are settled into a single unified account and shared quota pool. + +## Coexisting Cursor models and OpenCodex custom models + +In both the unified CLI (`2.0.6`) and desktop app (`Grok Build.app` `3.32.24`), the hosted Cursor model catalog and Private Inference (`config.toml` / `private-inference.toml`) are **mutually exclusive by design**: + +- Normal mode loads only the hosted Cursor catalog and does not mix in local `[model_providers.*]` entries from `~/.grok/config.toml`. +- Private Inference mode loads only the configured TOML catalog and intentionally fails closed rather than falling back to hosted Cursor models. + +### Practical options for showing both model sets together + +#### CLI (`grok`) + +1. **OpenCodex as single hub (recommended for one unified picker):** + - Authenticate both `cursor` and `xai` (plus any other providers) inside OpenCodex, and expose `cursor/*` models alongside other models in the `[model_providers.opencodex]` block injected into `~/.grok/config.toml` (`src/grok/inject.ts`). + - Works on legacy `1.0.x` CLI directly, and on `2.0.6` when running through the Private Inference TOML config path. +2. **Dual-binary workflow (zero feature loss):** + - Use unified `grok` (`2.0.6`) for native Cursor models and full agent-host features. + - Keep a separate alias for legacy `1.0.x` CLI when routing through OpenCodex `[model_providers.opencodex]`. + +#### Desktop app (`Grok Build.app` / `Cursor Private Inference.app`) + +1. **Regular `Grok Build.app` + BYOK (`Override OpenAI Base URL` + `Add Custom Model`):** + - Keeping Claude/Gemini BYOK keys off leaves `claude-*` and `gemini-*` on the Cursor subscription while routing custom-added models (and `gpt-*`) through the overridden OpenAI Base URL to OpenCodex. + - **Constraint:** BYOK base URL requests are sent from Cursor's backend rather than from localhost, so `127.0.0.1` will not work; OpenCodex must be reachable over a public HTTPS tunnel (with admission token). +2. **Private Inference (`Cursor Private Inference.app` or `private-inference.toml`) + OpenCodex hub:** + - Supports direct `http://127.0.0.1:10100/v1` loopback without a tunnel. + - When OpenCodex serves `cursor/*`, `xai/*`, and third-party models together, all of them appear in a single picker (Cursor models route through OpenCodex's `cursor` adapter rather than the native cloud agent loop). +3. **Dual-app side-by-side:** + - Run `Grok Build.app` for native Cursor models and `Cursor Private Inference.app` for local loopback OpenCodex models. + +## OpenCodex follow-up backlog + +| Item | Area | Goal | +|---|---|---| +| 1 | `src/integrations/cursor-detect.ts` & `src/cli/integration-cursor.ts` | Detect `Grok Build.app` alongside `Cursor.app` and `Cursor Private Inference.app` without breaking existing installs. | +| 2 | `src/grok/inject.ts` | Verify whether OpenCodex-managed `cursor/*` models are included cleanly in injected `[model.*]` blocks and document `2.0.6` vs legacy `1.0.x` CLI behavior. | +| 3 | `src/oauth/cursor.ts` | Track key-bound / DPoP auth requirements on the `cursor` OAuth path so token refresh stays resilient if enforced upstream. | +| 4 | `src/grok/reset-coupons.ts` | Track unified account banked-reset parity alongside existing `grok.com` reset-credit queries for users who complete account unification. | +| 5 | Live verification (isolated `GROK_HOME`) | Re-verify `xai` provider (`cli-chat-proxy.grok.com/v1`) quota behavior for unified vs unmerged accounts without touching user credentials. | From 16a4c46912cc1cea0d4799b88daeb8b0099559c0 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:38:52 +0900 Subject: [PATCH 02/50] test(quota): keep Mistral and Kimi budget fixtures valid across reset dates (#9265) * test(usage): pin Mistral budget observations before the reset deadline * test(providers): keep the Kimi monthly budget fixture current --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- tests/providers/kimi-monthly-quota.test.ts | 3 ++- tests/usage/mistral-budget-reset-identity.test.ts | 5 ++++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/providers/kimi-monthly-quota.test.ts b/tests/providers/kimi-monthly-quota.test.ts index 9189c57cca3..d50d4f56c2f 100644 --- a/tests/providers/kimi-monthly-quota.test.ts +++ b/tests/providers/kimi-monthly-quota.test.ts @@ -69,7 +69,8 @@ function mockUsage(payload: unknown, url = "https://api.kimi.com/coding/v1/usage }) as typeof fetch; } -const resetAt = "2026-12-01T00:00:00Z"; +// The passive pool only exposes windows whose reset is still in the future. +const resetAt = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(); const monthlyRow = { used_ratio: 0.375, reset_at: resetAt }; async function saveKimiFixture(): Promise { diff --git a/tests/usage/mistral-budget-reset-identity.test.ts b/tests/usage/mistral-budget-reset-identity.test.ts index ea348fcabb9..3d3ddd40ed3 100644 --- a/tests/usage/mistral-budget-reset-identity.test.ts +++ b/tests/usage/mistral-budget-reset-identity.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, setSystemTime, test } from "bun:test"; import { mkdtempSync, readFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -59,8 +59,11 @@ beforeEach(() => { resetQuotaResetStoreForTests(); clearProviderQuotaCache(); setQuotaResetSink(event => events.push(event)); + // Observe budget drops before the fixture's December 1 reset deadline. + setSystemTime(new Date("2026-11-30T12:00:00Z")); }); afterEach(() => { + setSystemTime(); globalThis.fetch = originalFetch; setProviderQuotaBeforePublishForTests(null); setQuotaResetSink(null); From 84015d60900d11ac94147e7b1213df1fe173a72a Mon Sep 17 00:00:00 2001 From: Shian Michael <179563420+ShianMike@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:38:57 +0800 Subject: [PATCH 03/50] docs: show how to use a failover combo for shadow calls (#9234) * docs: show how to use a failover combo for shadow calls * docs(es): mirror the failover combo shadow target example * docs: enable quota-only shadow failover in the example Enable the setting when creating the subscription combo, and use a lighter Anthropic target for helper calls. Keep the English and Spanish examples aligned. * docs: clarify temporary cooldown in quota-only failover --------- Co-authored-by: JUN --- .../docs/es/reference/configuration/server.md | 24 +++++++++++++++++++ .../docs/reference/configuration/server.md | 19 +++++++++++++++ structure/fallback-policy.md | 4 ++++ 3 files changed, 47 insertions(+) diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index 73986b0254d..8885d17a053 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -729,6 +729,30 @@ Los ids de modelo sin proveedor que coincidan son elegibles para interceptación } ``` + + +### Usar un combo de conmutación por error como objetivo de sombra + +Para que las llamadas auxiliares interceptadas tengan un respaldo, crea un combo `failover` con tu +ruta preferida en primer lugar. Por ejemplo, si tienes configuradas rutas de suscripción de OpenAI y +Anthropic, crea el combo y selecciónalo como objetivo de sombra con el prefijo `combo/`. Sustituye +los ID de modelo por los de tu configuración. + +```sh +ocx combo set title-helpers --strategy failover --targets "openai/gpt-5.6-sol,anthropic/claude-haiku-5-5" --quota-only-fallback on +ocx models shadow set combo/title-helpers --enabled on +``` + +En este ejemplo, el combo solo prueba el siguiente objetivo elegible si se confirma el agotamiento +de cuota o facturación antes de que empiece la salida. Si el proveedor aplica un límite de frecuencia +temporal a una solicitud, el cliente recibe ese error. Si el primer objetivo sigue en enfriamiento por +un límite temporal, el combo devuelve `503 Service Unavailable` sin contactar con ningún objetivo. +Configura `--quota-only-fallback off` en el combo para permitir la conmutación ante otros fallos +reintentables antes de que empiece la salida. + +Consulta [Combos](/es/guides/combos/) para la elegibilidad de los objetivos y el +[consentimiento de fallback medido](/es/guides/combos/#metered-fallback-consent). + ### Cuando el objetivo no está disponible diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index ad1e46a370f..326f1b0f1bb 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -1123,6 +1123,25 @@ subject to configured memory routing. These rules apply to concrete and combo ta } ``` +### Use a failover combo as the shadow target + +To give intercepted helper calls a backup, create a failover combo with your preferred route first. +For example, if you have OpenAI and Anthropic subscription routes configured, create the combo and +select it as the shadow target using the `combo/` prefix. Substitute model IDs from your configuration. + +```sh +ocx combo set title-helpers --strategy failover --targets "openai/gpt-5.6-sol,anthropic/claude-haiku-5-5" --quota-only-fallback on +ocx models shadow set combo/title-helpers --enabled on +``` + +In this example, the combo tries the next eligible target only after confirmed quota or billing +exhaustion before output begins. If the provider temporarily throttles a request, the caller receives +the rate-limit error. If the first target is already cooling down from a temporary throttle, the combo +returns `503 Service Unavailable` without contacting any target. Set `--quota-only-fallback off` on +the combo to allow fallback for other retryable failures before output begins. + +See [Combos](/guides/combos/) for target eligibility and [metered fallback consent](/guides/combos/#metered-fallback-consent). + ### When the target is unavailable The replacement is the one destination the operator chose, so a target that stops resolving fails diff --git a/structure/fallback-policy.md b/structure/fallback-policy.md index 8e07e0abfd1..a08f5bfd7af 100644 --- a/structure/fallback-policy.md +++ b/structure/fallback-policy.md @@ -129,6 +129,10 @@ owns capture, capability authentication and child propagation. | Subagent model fallback, `src/codex/subagent-model-fallback.ts` | `applySubagentModelFallback`, before the spawn's model is rewritten; the caller in `src/server/responses/request-prepare.ts` returns the refusal | — | `unavailable`, 503 | | Main-account hard-lock fallback, `src/server/responses/main-hard-lock-routing.ts` | before the body is rewritten; `FallbackRefusedError` carries the refusal to `request-prepare.ts` | — | `hard_lock`, 429 | +In a quota-only combo, a temporary cooldown on the first target ends selection with `503` +(`combo_unavailable`) before the proactive hop guard or any upstream send. The guard handles +`quota_exhausted` when selection advances to a later target after confirmed exhaustion. + A refused hop never contacts its refused destination. Hard-lock pre-admission refuses before rewriting the body; its first combo dispatch or profile selection can refuse after that rewrite. From 086cd5415a4e4d604bdd67d9549946b4fe630884 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:41:45 +0900 Subject: [PATCH 04/50] test(advisor): release consultation after observing two heartbeats (#9283) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- tests/advisor/advisor-guard.test.ts | 32 ++++++++++++++++++++--------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/tests/advisor/advisor-guard.test.ts b/tests/advisor/advisor-guard.test.ts index 78f04f8d6d6..7ea4f1c2050 100644 --- a/tests/advisor/advisor-guard.test.ts +++ b/tests/advisor/advisor-guard.test.ts @@ -582,26 +582,38 @@ describe("createAdvisorGuard — manual advisor() interception", () => { }); test("emits heartbeat events while a slow advisor consultation is in flight", async () => { - const { continuation, queues } = makeContinuation(); + const { continuation, queues, requests } = makeContinuation(); queues.push([{ type: "text_delta", text: "after heartbeat" }, { type: "done" }]); + const consultation = Promise.withResolvers(); const slowPlan: AdvisorPlan = { - consult: async () => { - await Bun.sleep(35); - return ADVICE; - }, + consult: () => consultation.promise, formatUnavailable: (kind, error) => `\n${kind}: ${error}\n`, }; const guard = createAdvisorGuard(slowPlan, 5); - const events = await collect(guard({ + const stream = guard({ parsed: baseParsed(), firstEvents: (async function* () { yield* advisorCallEvents("a_slow", { question: "slow model?" }); yield { type: "done" }; })(), continuation, - })); - const heartbeats = events.filter(e => e.type === "heartbeat"); - expect(heartbeats.length).toBeGreaterThanOrEqual(2); - expect(events.some(e => e.type === "text_delta" && e.text === "after heartbeat")).toBe(true); + }); + // Unblock the guard even if it stops emitting heartbeats, so the read fails below. + const watchdog = setTimeout(() => consultation.resolve(ADVICE), 2_000); + try { + expect((await stream.next()).value).toEqual({ type: "heartbeat" }); + expect((await stream.next()).value).toEqual({ type: "heartbeat" }); + expect(requests).toHaveLength(0); + consultation.resolve(ADVICE); + expect(await collect(stream)).toEqual([ + { type: "assistant_boundary" }, + { type: "text_delta", text: "after heartbeat" }, + { type: "done" }, + ]); + } finally { + clearTimeout(watchdog); + consultation.resolve(ADVICE); + await stream.return(undefined); + } }); }); From 385389b6a41f24ec2c7830988d3d53b0c69cb8a3 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:41:51 +0900 Subject: [PATCH 05/50] test(providers): bound and reap the nested Mihomo fixture (#9286) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- tests/providers/provider-outbound.test.ts | 29 ++++++++++++++--------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/tests/providers/provider-outbound.test.ts b/tests/providers/provider-outbound.test.ts index 6f596dd63c3..dd559d7c240 100644 --- a/tests/providers/provider-outbound.test.ts +++ b/tests/providers/provider-outbound.test.ts @@ -12,6 +12,10 @@ import { fixturePath, repoRoot } from "../helpers/repo-root"; const proxyKeys = PROXY_ENV_KEYS.flatMap(key => [key, key.toLowerCase()]); const originalProxyEnv = Object.fromEntries(proxyKeys.map(key => [key, process.env[key]])); +// Allow for cold Bun startup on Windows and reap each fixture before its parent test expires. +const FIXTURE_CHILD_MS = process.platform === "win32" ? 45_000 : 12_000; +const FIXTURE_TEST_MS = FIXTURE_CHILD_MS + 3_000; + afterEach(() => { for (const key of proxyKeys) { const previous = originalProxyEnv[key]; @@ -493,9 +497,6 @@ describe("provider outbound GET transport", () => { expect(override).toHaveBeenCalledTimes(1); }); - // A cold Bun start plus the fixture's imports can exceed 12s on slow Windows runners. The child - // stays bounded and SIGKILLed below the case deadline, so a real hang still fails with its timing. - const PROXY_E2E_CHILD_MS = process.platform === "win32" ? 45_000 : 12_000; test("proxy mode reaches one real proxy across outbound, connection-test, and model-discovery paths", async () => { const startedAt = performance.now(); const childHome = mkdtempSync(join(tmpdir(), "ocx-provider-proxy-e2e-")); @@ -511,7 +512,7 @@ describe("provider outbound GET transport", () => { stdout: "pipe", stderr: "pipe", // Terminate and reap the fixture before the case deadline. - timeout: PROXY_E2E_CHILD_MS, + timeout: FIXTURE_CHILD_MS, killSignal: "SIGKILL", }); @@ -522,7 +523,7 @@ describe("provider outbound GET transport", () => { child.exited, ]); if (exitCode !== 0) { - const bound = child.signalCode ? ` (${child.signalCode} after ${Math.round(performance.now() - startedAt)} ms; bound ${PROXY_E2E_CHILD_MS} ms)` : ""; + const bound = child.signalCode ? ` (${child.signalCode} after ${Math.round(performance.now() - startedAt)} ms; bound ${FIXTURE_CHILD_MS} ms)` : ""; throw new Error(`provider outbound fixture exited ${exitCode}${bound}: ${stderr.trim()}`); } const result = JSON.parse(stdout.trim()) as { @@ -574,7 +575,7 @@ describe("provider outbound GET transport", () => { await child.exited; removeTreeWithRetry(childHome); } - }, PROXY_E2E_CHILD_MS + 3_000); + }, FIXTURE_TEST_MS); }); describe("provider outbound POST transport", () => { @@ -800,23 +801,29 @@ describe("#3462 Mihomo IPv6 fake-IP admission is gated on the scheme-matched pro test("canonical IPv6-only TUN transport preserves pinning and rejects unsafe DNS answers", async () => { const childDir = mkdtempSync(join(tmpdir(), "ocx-mihomo-test-")); const childTest = join(childDir, "mihomo.test.ts"); - // Builtin module mocks are activated by Bun's test loader, not plain bun execution. - writeFileSync(childTest, `import { test } from "bun:test";\ntest("Mihomo matrix", async () => { await import(${JSON.stringify(pathToFileURL(fixturePath("provider-outbound-mihomo.ts")).href)}); });\n`); + let child: Bun.Subprocess<"ignore", "pipe", "pipe"> | undefined; try { - const child = Bun.spawn([process.execPath, "test", childTest], { + // Builtin module mocks are activated by Bun's test loader, not plain bun execution. + writeFileSync(childTest, `import { test } from "bun:test";\ntest("Mihomo matrix", async () => { await import(${JSON.stringify(pathToFileURL(fixturePath("provider-outbound-mihomo.ts")).href)}); });\n`); + child = Bun.spawn([process.execPath, "test", childTest], { cwd: repoRoot(), env: { ...process.env }, stdout: "pipe", stderr: "pipe", + timeout: FIXTURE_CHILD_MS, killSignal: "SIGKILL", }); const [stdout, stderr, exitCode] = await Promise.all([ new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited, ]); - if (exitCode !== 0) throw new Error(`Mihomo fixture exited ${exitCode}: ${stderr}`); + if (exitCode !== 0) throw new Error(`Mihomo fixture exited ${child.signalCode ?? exitCode}: ${stderr}`); const result = stdout.split(/\r?\n/).find(line => line.startsWith("MIHOMO_RESULT=")); expect(result).toBeDefined(); expect(JSON.parse(result!.slice("MIHOMO_RESULT=".length))).toEqual({ ipv6Pinned: 6, proxyBound: 2, denied: 54 }); } finally { + if (child) { + if (child.exitCode === null) child.kill("SIGKILL"); + await child.exited; + } removeTreeWithRetry(childDir); } - }); + }, FIXTURE_TEST_MS); async function run(env: Record, opts: { admit: boolean }) { for (const key of proxyKeys) delete process.env[key]; From 5a19c9a8ec7499d63fd93f41bc1d050a447742f7 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:41:57 +0900 Subject: [PATCH 06/50] test(routing): isolate lifecycle locks in Home route subprocesses (#9279) * test(routing): isolate lifecycle locks in child route scenarios * test(routing): report child spawn errors in Claude fixture --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- tests/clients/route-intent-claude-surface.test.ts | 14 +++++++++++--- tests/routing/route-to-home-native-truth.test.ts | 8 +++++++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/tests/clients/route-intent-claude-surface.test.ts b/tests/clients/route-intent-claude-surface.test.ts index 0a3836715bb..f343661e0d6 100644 --- a/tests/clients/route-intent-claude-surface.test.ts +++ b/tests/clients/route-intent-claude-surface.test.ts @@ -3,16 +3,21 @@ import { spawnSync } from "node:child_process"; import { createTempHome } from "../helpers/temp-home"; import { repoRoot } from "../helpers/repo-root"; +const CHILD_TIMEOUT_MS = 20_000; + test.each([true, false])("Home-local Claude off preserves shared Messages exposure (%s)", enabled => { const home = createTempHome("route-claude-surface-"); try { const script = ` + import { expect } from 'bun:test'; import { mkdirSync } from 'node:fs'; import { join } from 'node:path'; import { getDefaultConfig, saveConfig, loadConfig } from './src/config'; import { materializeLocalRouteIntent } from './src/client/route-intent-apply'; import { ROUTE_CLIENT_IDS } from './src/link/route-intent'; import { resolveApiSurfaceSettings } from './src/protocols/settings'; + import { isolateClientLifecycleLock } from './tests/helpers/client-lifecycle-lock'; + const lifecycle = isolateClientLifecycleLock(process.env.HOME); const config = getDefaultConfig(); config.port = 18274; config.claudeCode = { enabled:true }; if (!${enabled}) config.apiSurfaces = {messages:{enabled:false}}; saveConfig(config); mkdirSync(process.env.CLAUDE_CONFIG_DIR,{recursive:true}); @@ -20,16 +25,19 @@ test.each([true, false])("Home-local Claude off preserves shared Messages exposu clients:Object.fromEntries(ROUTE_CLIENT_IDS.map(client=>[client,{enabled:false}])), sources:Object.fromEntries(ROUTE_CLIENT_IDS.map(client=>[client,'default']))}; const receipt=await materializeLocalRouteIntent(config,document,[]); + expect(new Set(lifecycle.acquisitions.map(({ path }) => path))) + .toEqual(new Set([join(process.env.HOME, 'locks', 'lifecycle.sqlite')])); console.log(JSON.stringify({local:loadConfig().claudeCode.enabled, messages:resolveApiSurfaceSettings(loadConfig()).messages.enabled, live:resolveApiSurfaceSettings(config).messages.enabled, outcome:receipt.outcomes.find(row=>row.client==='claude').outcome})); `; - const result = spawnSync(process.execPath, ["--eval", script], { cwd: repoRoot(), encoding: "utf8", timeout: 20_000, + const result = spawnSync(process.execPath, ["--eval", script], { cwd: repoRoot(), encoding: "utf8", timeout: CHILD_TIMEOUT_MS, env: { ...process.env, HOME: home.root, USERPROFILE: home.root, OPENCODEX_HOME: home.configDir, CODEX_HOME: home.codexHome, CLAUDE_CONFIG_DIR: home.path(".claude"), OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: home.path("desktop"), XDG_CONFIG_HOME: home.path(".config"), GROK_HOME: home.path(".grok"), OCX_TEST_HOME_GUARD: "1" } }); - expect({ status: result.status, stderr: result.stderr }).toMatchObject({ status: 0 }); + expect({ status: result.status, stderr: result.stderr, error: result.error?.message }) + .toMatchObject({ status: 0, error: undefined }); expect(JSON.parse(result.stdout.trim().split("\n").at(-1)!)).toEqual({ local: false, messages: enabled, live: enabled, outcome: "current" }); } finally { home.remove(); } -}); +}, CHILD_TIMEOUT_MS + 5_000); diff --git a/tests/routing/route-to-home-native-truth.test.ts b/tests/routing/route-to-home-native-truth.test.ts index b483539eb05..0a656df7a4e 100644 --- a/tests/routing/route-to-home-native-truth.test.ts +++ b/tests/routing/route-to-home-native-truth.test.ts @@ -20,7 +20,7 @@ function scenario(body: string, linked = false) { const child = spawnSync(process.execPath, ["--eval", ` import { expect } from 'bun:test'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; - import { join } from 'node:path'; + import { join, resolve, sep } from 'node:path'; import { getDefaultConfig, saveConfig, loadConfig } from './src/config'; import { writeLinkStore } from './src/link/store'; import { linkStorePath } from './src/link/paths'; @@ -35,6 +35,8 @@ function scenario(body: string, linked = false) { import { applyIntegration } from './src/integrations/writer'; import { createIntegrationStateStore } from './src/integrations/store'; import { INTEGRATION_CLIENTS } from './src/integrations/registry'; + import { isolateClientLifecycleLock } from './tests/helpers/client-lifecycle-lock'; + const lifecycle = isolateClientLifecycleLock(process.env.HOME); writeFileSync(join(process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR,'_meta.json'),JSON.stringify({entries:[]})); const local = getDefaultConfig(); local.port=18274; local.hostname='127.0.0.1'; local.defaultProvider='fixture';local.providers={fixture:{adapter:'openai-chat',baseUrl:'http://127.0.0.1:1/v1',allowPrivateNetwork:true,liveModels:false,models:['fixture-model']}}; @@ -79,6 +81,10 @@ const orphanedGrok = ` test.each([false, true])("a refused Home Grok off reports the switch it saved (linked %s)", linked => scenario(` ${orphanedGrok} const result = await call('/api/route-to', { client: 'grok', action: 'off', device: 'home' }); + const lockPaths = lifecycle.acquisitions.map(({ path }) => path); + expect(lockPaths).toContain(join(process.env.HOME, 'locks', 'lifecycle.sqlite')); + // Link apply also supplies its own lock under the fixture's OPENCODEX_HOME. + expect(lockPaths.filter(path => !path.startsWith(resolve(process.env.HOME) + sep))).toEqual([]); expect(result.status).toBe(409); expect(result.body).toMatchObject({ code: 'route_apply_unresolved', desiredCommitted: true }); expect(result.body.error).toStartWith("The Home's grok switch was saved, but applying it ended in conflict"); From 3deffcc37bed50745838d01df73c87bf75c57617 Mon Sep 17 00:00:00 2001 From: lcxhh Date: Thu, 3 Dec 2026 06:42:29 -0800 Subject: [PATCH 07/50] fix(responses): keep hosted shell history in translated requests (#9257) * fix(responses): keep hosted shell history in translated requests parseRequest already paired local_shell_call with function_call_output, but a hosted shell_call uses action.commands and shell_call_output. Those items were dropped, so the next translated turn lost both the command and its result. * fix(responses): keep stdout and exit status from hosted shell output A hosted shell_call_output carries stdout, stderr, and an exit or timeout outcome. The shared text-part helper skipped those objects, so a translated follow-up saw an empty result. * fix(responses): replay undeclared hosted shell history as text A hosted shell_call became a tool call named shell even when the request declared no callable shell tool. Translated Anthropic requests then sent tool_use without a tools entry. The command and its output stay in the history as text unless a function or custom tool named shell is declared. * fix(responses): keep hosted shell replay aligned with the tool catalog Shell replay now sees declarations carried in additional_tools and tool_search_output. A custom shell tool stores the command as freeform input. Text replay of a hosted shell result stays on the open assistant turn, so it does not separate a function call from its result. --- src/responses/parser.ts | 143 ++++++++++++++++++++++- tests/responses/responses-parser.test.ts | 96 +++++++++++++++ 2 files changed, 234 insertions(+), 5 deletions(-) diff --git a/src/responses/parser.ts b/src/responses/parser.ts index a191c204367..4089d2f03a9 100644 --- a/src/responses/parser.ts +++ b/src/responses/parser.ts @@ -217,6 +217,96 @@ function nameDestinationContent( return changed ? parts : content; } +function appendShellPiece(pieces: string[], piece: string): void { + if (piece.length === 0) return; + if (pieces.length > 0 && !pieces[pieces.length - 1]!.endsWith("\n")) pieces.push("\n"); + pieces.push(piece); +} + +/** One hosted shell chunk: stdout, stderr, then exit code or timeout. */ +function shellChunkText(chunk: Record): string { + const pieces: string[] = []; + if (typeof chunk.stdout === "string") appendShellPiece(pieces, chunk.stdout); + if (typeof chunk.stderr === "string") appendShellPiece(pieces, chunk.stderr); + const outcome = chunk.outcome; + if (isObj(outcome)) { + if (outcome.type === "timeout") appendShellPiece(pieces, "[timeout]"); + else if (outcome.type === "exit" && typeof outcome.exit_code === "number") appendShellPiece(pieces, `[exit ${outcome.exit_code}]`); + } + return pieces.join(""); +} + +/** + * Hosted `shell_call_output.output` is an array of `{stdout, stderr, outcome}` chunks. + * Content-part arrays and plain strings stay on the shared tool-result helper. + */ +function shellCallOutputContent(output: string | unknown[] | undefined): string | OcxContentPart[] { + if (!Array.isArray(output)) return outputToToolResultContent(output); + const chunks: string[] = []; + let structured = false; + for (const raw of output) { + if (!isObj(raw)) continue; + if (!("stdout" in raw) && !("stderr" in raw) && !("outcome" in raw)) continue; + structured = true; + const text = shellChunkText(raw); + if (text.length > 0) chunks.push(text); + } + return structured ? chunks.join("\n") : outputToToolResultContent(output); +} + +type ShellReplay = "function" | "custom" | "text"; + +function namedShellKind(tool: unknown): Exclude | undefined { + if (!isObj(tool)) return undefined; + if (tool.type === "function" && (tool.name === "shell" || (isObj(tool.function) && tool.function.name === "shell"))) return "function"; + if (tool.type === "custom" && tool.name === "shell") return "custom"; + return undefined; +} + +/** Function wins over custom. Hosted `{type:"shell"}` is not callable on a translated route. */ +function shellReplayKind(tools: unknown): ShellReplay { + if (!Array.isArray(tools)) return "text"; + let custom = false; + const consider = (tool: unknown): boolean => { + const kind = namedShellKind(tool); + if (kind === "function") return true; + if (kind === "custom") custom = true; + if (isObj(tool) && tool.type === "namespace" && tool.name === "functions" && Array.isArray(tool.tools)) { + for (const inner of tool.tools) if (consider(inner)) return true; + } + return false; + }; + for (const tool of tools) if (consider(tool)) return "function"; + return custom ? "custom" : "text"; +} + +function shellCatalog(bodyTools: unknown, items: unknown): unknown[] { + const catalog: unknown[] = Array.isArray(bodyTools) ? [...bodyTools] : []; + if (!Array.isArray(items)) return catalog; + for (const item of items) { + if (!isObj(item)) continue; + if ((item.type === "additional_tools" || item.type === "tool_search_output") && Array.isArray(item.tools)) { + catalog.push(...item.tools); + } + } + return catalog; +} + +/** True while an assistant tool call is still waiting for its tool result. */ +function hasOpenToolBatch(messages: OcxMessage[]): boolean { + let pending = 0; + for (const message of messages) { + if (message.role === "assistant" && Array.isArray(message.content)) { + pending += message.content.filter(part => part.type === "toolCall").length; + } else if (message.role === "toolResult") { + if (pending > 0) pending -= 1; + } else { + pending = 0; + } + } + return pending > 0; +} + /** * Validate a Responses body and normalize its tools, options and conversation. * Restores signed or opaque reasoning from replayed items; late signatures require @@ -297,6 +387,7 @@ export function parseRequest( messages.push({ role: "user", content: data.input, timestamp: now }); } else if (data.input) { const inputItems = (webSearchReplay?.items ?? data.input) as typeof data.input; + const shellReplay = shellReplayKind(shellCatalog(data.tools, inputItems)); for (let itemIndex = 0; itemIndex < inputItems.length; itemIndex++) { const item = inputItems[itemIndex]; // Boundaries are measured on the caller's input, before any replayed-search rewrite. @@ -570,9 +661,12 @@ export function parseRequest( } if (effectiveType === "local_shell_call") { - // codex-rs LocalShellCall replay: pair it as an assistant toolCall so the subsequent - // function_call_output (same call_id) doesn't become an orphaned tool result. - const call = item as { id?: string; call_id?: string; action?: { type?: string; command?: string[] } }; + // codex-rs local shell replays through function_call_output and action.command. + const call = item as { + id?: string; + call_id?: string; + action?: { type?: string; command?: string[] }; + }; const callId = call.call_id ?? call.id; if (callId) { const command = Array.isArray(call.action?.command) ? call.action.command : []; @@ -586,6 +680,31 @@ export function parseRequest( continue; } + if (effectiveType === "shell_call") { + // Hosted shell uses action.commands. A translated route only keeps it as a tool call + // when a callable shell tool is declared; otherwise Anthropic rejects the tool_use. + const call = item as { id?: string; call_id?: string; action?: { command?: unknown; commands?: unknown } }; + const callId = call.call_id ?? call.id; + const listed = Array.isArray(call.action?.commands) + ? call.action.commands + : Array.isArray(call.action?.command) ? call.action.command : []; + if (shellReplay !== "text" && callId) { + const commandText = listed.filter((part): part is string => typeof part === "string" && part.length > 0).join("\n"); + const remembered = replayThoughtSignatureMetadata(callId, replayCacheScope); + assistantHolderWithReasoning().content.push({ + type: "toolCall", id: callId, name: "shell", + arguments: shellReplay === "custom" ? { input: commandText } : (listed.length > 0 ? { command: listed } : {}), + ...(shellReplay === "custom" ? { customWireName: "shell" } : {}), + ...(remembered ? { providerMetadata: remembered } : {}), + }); + continue; + } + const text = listed.filter((part): part is string => typeof part === "string" && part.length > 0).join("\n"); + if (text.length > 0) assistantHolderWithReasoning().content.push({ type: "text", text }); + else if (pendingReasoning.length > 0) assistantHolderWithReasoning(); + continue; + } + if (effectiveType === "web_search_call") { // Without a search declaration the cell stays out of routed history: a call to an undeclared // tool, or assistant-visible marker text the model could echo as a fake answer, would be @@ -639,7 +758,18 @@ export function parseRequest( continue; } - if (effectiveType === "function_call_output") { + if (effectiveType === "function_call_output" || effectiveType === "shell_call_output") { + if (effectiveType === "shell_call_output" && shellReplay === "text") { + pendingReasoning.length = 0; + const content = shellCallOutputContent((item as { output?: string | unknown[] }).output); + if (content.length > 0 && hasOpenToolBatch(messages)) { + if (typeof content === "string") assistantHolderWithReasoning().content.push({ type: "text", text: content }); + else assistantHolderWithReasoning().content.push(...content); + } else if (content.length > 0) { + messages.push({ role: "user", content, timestamp: now }); + } + continue; + } if (externalTaskInput !== undefined) { pendingReasoning.length = 0; messages.push({ role: "user", content: externalTaskInput, timestamp: now }); @@ -652,7 +782,10 @@ export function parseRequest( messages.push({ role: "toolResult", toolCallId: output.call_id, toolName: toolInfo.name, toolNamespace: toolInfo.namespace, - content: outputToToolResultContent(output.output), isError: false, timestamp: now, + content: effectiveType === "shell_call_output" + ? shellCallOutputContent(output.output) + : outputToToolResultContent(output.output), + isError: false, timestamp: now, ...(toolOutputContainsEncryptedContent(output.output) ? { containsEncryptedContent: true } : {}), }); continue; diff --git a/tests/responses/responses-parser.test.ts b/tests/responses/responses-parser.test.ts index 6387308433d..4edf1791a42 100644 --- a/tests/responses/responses-parser.test.ts +++ b/tests/responses/responses-parser.test.ts @@ -921,6 +921,102 @@ describe("codex-rs compat surface (260707)", () => { expect(result?.content).toBe("total 0"); }); + test("shell_call pairs with its shell_call_output", () => { + const parsed = parseRequest({ ...base, tools: [{ type: "function", name: "shell", parameters: { type: "object" } }], input: [ + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "hosted-shell", output: [ + { stdout: "/workspace\n", stderr: "", outcome: { type: "exit", exit_code: 0 } }, + { stdout: "", stderr: "timed out\n", outcome: { type: "timeout" } }, + ] }, + ]}); + const assistant = parsed.context.messages.find(m => m.role === "assistant"); + const call = (assistant?.content as { type: string; id?: string; name?: string; arguments?: Record }[]) + .find(p => p.type === "toolCall"); + expect(call?.id).toBe("hosted-shell"); + expect(call?.name).toBe("shell"); + expect(call?.arguments).toEqual({ command: ["pwd"] }); + const result = parsed.context.messages.find(m => m.role === "toolResult"); + expect(result?.toolCallId).toBe("hosted-shell"); + expect(result?.toolName).toBe("shell"); + expect(result?.content).toBe("/workspace\n[exit 0]\ntimed out\n[timeout]"); + }); + + test("hosted shell history stays text when no callable shell tool is declared", () => { + const parsed = parseRequest({ ...base, input: [ + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "hosted-shell", output: [ + { stdout: "/workspace\n", stderr: "", outcome: { type: "exit", exit_code: 0 } }, + ] }, + ]}); + const assistant = parsed.context.messages.find(m => m.role === "assistant"); + expect(assistant?.content).toEqual([{ type: "text", text: "pwd" }]); + const user = parsed.context.messages.find(m => m.role === "user"); + expect(user?.content).toBe("/workspace\n[exit 0]"); + expect(parsed.context.messages.some(m => m.role === "toolResult")).toBe(false); + }); + + test("a hosted shell declaration alone does not become a tool call", () => { + const parsed = parseRequest({ ...base, tools: [{ type: "shell" }], input: [ + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "hosted-shell", output: "ok" }, + ]}); + expect(parsed.context.messages.find(m => m.role === "assistant")?.content).toEqual([{ type: "text", text: "pwd" }]); + expect(parsed.context.messages.find(m => m.role === "user")?.content).toBe("ok"); + }); + + test("a custom shell tool replays the command as freeform input", () => { + const parsed = parseRequest({ ...base, tools: [{ type: "custom", name: "shell" }], input: [ + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "hosted-shell", output: "ok" }, + ]}); + const call = (parsed.context.messages.find(m => m.role === "assistant")?.content as { type: string; arguments?: Record; customWireName?: string }[]) + .find(part => part.type === "toolCall"); + expect(call?.arguments).toEqual({ input: "pwd" }); + expect(call?.customWireName).toBe("shell"); + expect(parsed.context.messages.find(m => m.role === "toolResult")?.content).toBe("ok"); + }); + + test("an additional_tools shell declaration keeps the hosted call paired", () => { + const parsed = parseRequest({ ...base, input: [ + { type: "additional_tools", tools: [{ type: "function", name: "shell", parameters: { type: "object" } }] }, + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "hosted-shell", output: "ok" }, + ]}); + const call = (parsed.context.messages.find(m => m.role === "assistant")?.content as { type: string; arguments?: Record }[]) + .find(part => part.type === "toolCall"); + expect(call?.arguments).toEqual({ command: ["pwd"] }); + expect(parsed.context.messages.find(m => m.role === "toolResult")?.content).toBe("ok"); + }); + + test("a shell function loaded by tool_search_output keeps the hosted call paired", () => { + const parsed = parseRequest({ ...base, input: [ + { type: "tool_search_output", call_id: "ts", status: "completed", tools: [{ type: "function", name: "shell", parameters: { type: "object" } }] }, + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "hosted-shell", output: "ok" }, + ]}); + const call = (parsed.context.messages.find(m => m.role === "assistant")?.content as { type: string; arguments?: Record }[]) + ?.find(part => part.type === "toolCall" && part.arguments && "command" in part.arguments); + expect(call?.arguments).toEqual({ command: ["pwd"] }); + }); + + test("hosted shell text stays on the assistant turn while a function call is open", () => { + const parsed = parseRequest({ ...base, input: [ + { type: "function_call", call_id: "c1", name: "read", arguments: "{}" }, + { type: "shell_call", call_id: "s1", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "s1", output: [{ stdout: "/workspace\n", stderr: "", outcome: { type: "exit", exit_code: 0 } }] }, + { type: "function_call_output", call_id: "c1", output: "file" }, + ]}); + expect(parsed.context.messages.map(message => message.role)).toEqual(["assistant", "toolResult"]); + const assistant = parsed.context.messages[0]; + expect(assistant?.content).toEqual(expect.arrayContaining([ + expect.objectContaining({ type: "toolCall", id: "c1", name: "read" }), + { type: "text", text: "pwd" }, + { type: "text", text: "/workspace\n[exit 0]" }, + ])); + expect(parsed.context.messages[1]?.toolCallId).toBe("c1"); + expect(parsed.context.messages[1]?.content).toBe("file"); + }); + test("web_search_call replay stays out of assistant-visible history text", () => { const parsed = parseRequest({ ...base, input: [ { type: "web_search_call", status: "completed", action: { type: "search", query: "bun 1.3 release" } }, From 73bca7daa8993fee8cf39dbff4bed111a7b7ea0b Mon Sep 17 00:00:00 2001 From: Parsifal Date: Thu, 3 Dec 2026 22:43:19 +0800 Subject: [PATCH 08/50] fix(integrations): support new Antigravity gateway config path (#9219) --- .../content/docs/es/guides/integrations.md | 25 ++- .../src/content/docs/guides/integrations.md | 20 +- gui/src/i18n/gateway-clients-copy.ts | 6 +- gui/tests/gateway-clients-page.test.tsx | 8 +- .../gateway-clients/antigravity.ts | 162 ++++++++++----- src/integrations/gateway-clients/io.ts | 2 +- src/integrations/gateway-clients/types.ts | 4 +- structure/clients/antigravity-gateway.md | 26 ++- tests/cli/gateway-client-command.test.ts | 4 + tests/clients/gateway-client-restore.test.ts | 190 +++++++++++++++++- tests/clients/gateway-client-safety.test.ts | 152 ++++++++++++-- tests/clients/gateway-clients.test.ts | 92 +++++++-- tests/server/gateway-client-routes.test.ts | 7 +- 13 files changed, 596 insertions(+), 102 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index a1c9f5d179c..2b0b7da4015 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -746,7 +746,7 @@ La app de escritorio Antigravity de Google (2.15 y posteriores) y la CLI `agy` ( funcionar a través del gateway de OpenCodex. Conéctalas desde el panel o desde una terminal: ```bash -ocx connect antigravity --model # desktop app: ~/.antigravity/settings.json +ocx connect antigravity --model # configura ambos archivos de la app de escritorio ocx connect agy # agy CLI: a marked shell function in your profiles ocx connect antigravity status # or: ocx connect agy status ocx disconnect antigravity # or: ocx disconnect agy @@ -754,6 +754,23 @@ ocx disconnect antigravity # or: ocx disconnect agy Usa `--model` solo con `ocx connect antigravity` para fijar el modelo predeterminado de la app de escritorio. +Antigravity 2.15–2.29 lee únicamente `~/.antigravity/settings.json`. La versión 2.30 y las posteriores +leen únicamente `~/.gemini/config/config.json`. Las actualizaciones de la app dejan la configuración +del gateway en su ruta existente. OpenCodex escribe ambos archivos para instalaciones nuevas, +actualizaciones y cambios a versiones anteriores sin detectar la versión de la app. Comprueba ambos +archivos antes de escribir en cualquiera de ellos. + +El estado muestra primero `~/.gemini/config/config.json` y después `~/.antigravity/settings.json`. +Indica `connected` solo cuando ambos coinciden con el gateway de OpenCodex. Una configuración +incompleta se indica como `drifted`. + +OpenCodex acepta los registros de restauración antiguos de Antigravity de un solo archivo. Al +reconectar, conserva los datos originales de restauración del archivo heredado y añade un registro +para el archivo moderno. +La desconexión comprueba y restaura únicamente los archivos registrados, cada uno de forma independiente. +Los fallos parciales de escritura o restauración conservan los datos de recuperación necesarios para +volver a intentarlo. + Conectar registra lo que reemplazó. Desconectar restaura los bytes originales cuando el archivo no ha cambiado y, en caso contrario, revierte solo las entradas propias de OpenCodex y conserva tus otras ediciones. Antigravity puede restaurar la configuración aunque se reordenen las claves JSON y conserva @@ -764,8 +781,10 @@ Recupera de una copia el bloque completo de `agy`, incluidas las dos líneas de entre ellas, y vuelve a intentar la desconexión o la desinstalación. OpenCodex elimina el bloque entero y conserva los cambios que quedan fuera. También puedes restaurar el perfil original guardado, lo que reemplaza las ediciones posteriores. Un enlace simbólico de un perfil de `agy` debe apuntar a otro perfil compatible -de la misma familia de shells dentro de tu directorio personal. El archivo de configuración de -Antigravity debe resolverse a la ruta exacta `~/.antigravity/settings.json`. Reinicia Antigravity, o +de la misma familia de shells dentro de tu directorio personal. Cada archivo de configuración de +Antigravity debe resolverse a su propia ruta exacta dentro de tu directorio personal canónico. Los +directorios superiores deben resolverse a `.gemini/config` para el archivo moderno y a `.antigravity` +para el archivo heredado. Reinicia Antigravity, o abre una terminal nueva para `agy`, para aplicar un cambio. Al desconectar, `agy` omite los perfiles sin registro de restauración si no se pueden resolver o leer. `ocx uninstall` desconecta los clientes con registros de restauración guardados antes de eliminar la diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index fed917bedfe..93a2d32b3f9 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1238,7 +1238,7 @@ Google's Antigravity desktop app (2.15 and newer) and the `agy` CLI (1.2.15 and OpenCodex's gateway. Connect from the dashboard, or from a terminal: ```bash -ocx connect antigravity --model # desktop app: ~/.antigravity/settings.json +ocx connect antigravity --model # configure both desktop app settings files ocx connect agy # agy CLI: a marked shell function in your profiles ocx connect antigravity status # or: ocx connect agy status ocx disconnect antigravity # or: ocx disconnect agy @@ -1246,6 +1246,18 @@ ocx disconnect antigravity # or: ocx disconnect agy Use `--model` only with `ocx connect antigravity` to set the desktop app's default model. +Antigravity 2.15–2.29 reads only `~/.antigravity/settings.json`. Version 2.30 and newer reads only +`~/.gemini/config/config.json`. App upgrades leave the gateway configuration at its existing path. +OpenCodex writes both files for fresh installs, upgrades and downgrades without detecting the app +version. It checks both files before writing either one. + +Status lists `~/.gemini/config/config.json` first and `~/.antigravity/settings.json` second. +It reports `connected` only when both match the OpenCodex gateway. Incomplete wiring is `drifted`. + +OpenCodex accepts older single-file Antigravity restore records. Reconnect preserves the original +legacy restore data and adds a record for the modern file. Disconnect checks and restores only recorded files, +restoring each independently. Partial write or restore failures keep the recovery data needed for a retry. + Connect records what it replaced. Disconnect puts the original bytes back when the file is unchanged, and otherwise reverts only OpenCodex's own entries and keeps your other edits. Antigravity can restore settings after JSON keys are reordered and keeps the file and restore record when a managed setting conflicts. @@ -1254,8 +1266,10 @@ retry. If OpenCodex reports `agy-profile-restore-required`, open the shell profi Restore the complete `agy` block from a copy, including both marker lines and the function between them, then retry disconnect or uninstall. OpenCodex removes the whole block and keeps edits outside it. You can also restore the saved original profile, which replaces any later edits. An `agy` profile symlink must resolve -to another supported profile for the same shell family under your home. Antigravity settings must resolve -to the exact `~/.antigravity/settings.json` path. Restart Antigravity, or open a new terminal for `agy`, +to another supported profile for the same shell family under your home. Each Antigravity settings file +must resolve to its own exact path under your canonical home. The parent directories must resolve to +`.gemini/config` for the modern file and `.antigravity` for the legacy file. +Restart Antigravity, or open a new terminal for `agy`, to apply a change. During disconnect, `agy` skips profiles without a restore record if they cannot be resolved or read. `ocx uninstall` disconnects clients with saved restore records before removing configuration. If a client cannot be restored, uninstall stops and keeps its record. diff --git a/gui/src/i18n/gateway-clients-copy.ts b/gui/src/i18n/gateway-clients-copy.ts index 9185e032d06..e8a95aee055 100644 --- a/gui/src/i18n/gateway-clients-copy.ts +++ b/gui/src/i18n/gateway-clients-copy.ts @@ -23,8 +23,8 @@ const rows = { overrideEnv: ["AGY_LLM_GATEWAY_URL is set in the environment OpenCodex runs in and takes precedence over this connection.","OpenCodex가 실행되는 환경에 AGY_LLM_GATEWAY_URL이 설정되어 있어 이 연결보다 우선해요.","AGY_LLM_GATEWAY_URL ist in der Umgebung von OpenCodex gesetzt und hat Vorrang vor dieser Verbindung.","AGY_LLM_GATEWAY_URL est défini dans l’environnement d’OpenCodex et prime sur cette connexion.","OpenCodex 运行环境中设置了 AGY_LLM_GATEWAY_URL,它优先于此连接。","OpenCodex 執行環境中設定了 AGY_LLM_GATEWAY_URL,它優先於此連線。","В окружении OpenCodex задана AGY_LLM_GATEWAY_URL, и она имеет приоритет над этим подключением.","OpenCodex の実行環境で AGY_LLM_GATEWAY_URL が設定されており、この接続より優先されます。","OpenCodex'in çalıştığı ortamda AGY_LLM_GATEWAY_URL ayarlı ve bu bağlantının önüne geçiyor.","Môi trường chạy OpenCodex có đặt AGY_LLM_GATEWAY_URL, và biến này được ưu tiên hơn kết nối này.","AGY_LLM_GATEWAY_URL está definida no ambiente do OpenCodex e tem prioridade sobre esta conexão.", "AGY_LLM_GATEWAY_URL está definida en el entorno donde se ejecuta OpenCodex y tiene prioridad sobre esta conexión."], noteNoGoogleSignIn: ["While connected, the app does not use your Google sign-in.","연결된 동안 앱은 Google 로그인을 사용하지 않아요.","Solange die Verbindung besteht, nutzt die App Ihre Google-Anmeldung nicht.","Tant qu’elle est connectée, l’application n’utilise pas votre connexion Google.","连接期间,应用不使用你的 Google 登录。","連線期間,應用程式不使用你的 Google 登入。","Пока подключение активно, приложение не использует ваш вход в Google.","接続中、アプリは Google のサインインを使いません。","Bağlıyken uygulama Google oturumunuzu kullanmaz.","Khi đã kết nối, ứng dụng không dùng đăng nhập Google của bạn.","Enquanto conectado, o app não usa o seu login do Google.", "Mientras está conectada, la aplicación no usa tu inicio de sesión de Google."], noteAgyFollowsApp: ["agy also follows this setting unless it is connected on its own.","agy를 따로 연결하지 않으면 agy도 이 설정을 따라요.","agy folgt dieser Einstellung ebenfalls, solange es nicht eigens verbunden ist.","agy suit aussi ce réglage, sauf s’il est connecté séparément.","除非单独连接 agy,否则 agy 也会遵循此设置。","除非單獨連線 agy,否則 agy 也會遵循此設定。","agy тоже следует этой настройке, если не подключён отдельно.","agy を個別に接続しない限り、agy もこの設定に従います。","agy ayrıca bağlanmadıkça o da bu ayarı izler.","agy cũng theo cài đặt này, trừ khi được kết nối riêng.","O agy também segue esta configuração, a menos que seja conectado à parte.", "agy también sigue esta configuración, salvo que se conecte por separado."], - noteSettingsNotJson: ["settings.json is not plain JSON (it has comments, trailing commas or a syntax error), so OpenCodex will not change it. Fix the file, then connect again.","settings.json이 순수 JSON이 아니라서(주석, 끝 쉼표 또는 문법 오류) OpenCodex가 바꾸지 않아요. 파일을 고친 뒤 다시 연결하세요.","settings.json ist kein reines JSON (Kommentare, nachgestellte Kommas oder ein Syntaxfehler), daher ändert OpenCodex sie nicht. Korrigieren Sie die Datei und verbinden Sie erneut.","settings.json n’est pas du JSON pur (commentaires, virgules finales ou erreur de syntaxe) ; OpenCodex ne le modifiera pas. Corrigez le fichier, puis reconnectez.","settings.json 不是纯 JSON(含注释、末尾逗号或语法错误),OpenCodex 不会修改它。修好文件后再连接。","settings.json 不是純 JSON(含註解、結尾逗號或語法錯誤),OpenCodex 不會修改它。修好檔案後再連線。","settings.json — не чистый JSON (комментарии, лишние запятые или синтаксическая ошибка), поэтому OpenCodex его не изменит. Исправьте файл и подключитесь снова.","settings.json が純粋な JSON ではない(コメント、末尾のカンマ、構文エラー)ため、OpenCodex は変更しません。ファイルを直してから再接続してください。","settings.json düz JSON değil (yorumlar, sondaki virgüller ya da bir söz dizimi hatası), bu yüzden OpenCodex onu değiştirmez. Dosyayı düzeltip yeniden bağlanın.","settings.json không phải JSON thuần (có chú thích, dấu phẩy thừa hoặc lỗi cú pháp), nên OpenCodex sẽ không sửa nó. Hãy sửa tệp rồi kết nối lại.","settings.json não é JSON puro (comentários, vírgulas finais ou erro de sintaxe), então o OpenCodex não vai alterá-lo. Corrija o arquivo e conecte de novo.", "settings.json no es JSON puro (tiene comentarios, comas finales o un error de sintaxis), así que OpenCodex no lo modificará. Corrige el archivo y vuelve a conectar."], - noteSettingsNotObject: ["settings.json does not contain a JSON object, so OpenCodex will not change it.","settings.json에 JSON 객체가 없어서 OpenCodex가 바꾸지 않아요.","settings.json enthält kein JSON-Objekt, daher ändert OpenCodex sie nicht.","settings.json ne contient pas d’objet JSON ; OpenCodex ne le modifiera pas.","settings.json 不包含 JSON 对象,OpenCodex 不会修改它。","settings.json 不包含 JSON 物件,OpenCodex 不會修改它。","settings.json не содержит JSON-объект, поэтому OpenCodex его не изменит.","settings.json に JSON オブジェクトがないため、OpenCodex は変更しません。","settings.json bir JSON nesnesi içermiyor, bu yüzden OpenCodex onu değiştirmez.","settings.json không chứa đối tượng JSON, nên OpenCodex sẽ không sửa nó.","settings.json não contém um objeto JSON, então o OpenCodex não vai alterá-lo.", "settings.json no contiene un objeto JSON, así que OpenCodex no lo modificará."], + noteSettingsNotJson: ["config.json / settings.json is not plain JSON (it has comments, trailing commas or a syntax error), so OpenCodex will not change it. Fix the file, then connect again.","config.json / settings.json이 순수 JSON이 아니라서(주석, 끝 쉼표 또는 문법 오류) OpenCodex가 바꾸지 않아요. 파일을 고친 뒤 다시 연결하세요.","config.json / settings.json ist kein reines JSON (Kommentare, nachgestellte Kommas oder ein Syntaxfehler), daher ändert OpenCodex sie nicht. Korrigieren Sie die Datei und verbinden Sie erneut.","config.json / settings.json n’est pas du JSON pur (commentaires, virgules finales ou erreur de syntaxe) ; OpenCodex ne le modifiera pas. Corrigez le fichier, puis reconnectez.","config.json / settings.json 不是纯 JSON(含注释、末尾逗号或语法错误),OpenCodex 不会修改它。修好文件后再连接。","config.json / settings.json 不是純 JSON(含註解、結尾逗號或語法錯誤),OpenCodex 不會修改它。修好檔案後再連線。","config.json / settings.json — не чистый JSON (комментарии, лишние запятые или синтаксическая ошибка), поэтому OpenCodex его не изменит. Исправьте файл и подключитесь снова.","config.json / settings.json が純粋な JSON ではない(コメント、末尾のカンマ、構文エラー)ため、OpenCodex は変更しません。ファイルを直してから再接続してください。","config.json / settings.json düz JSON değil (yorumlar, sondaki virgüller ya da bir söz dizimi hatası), bu yüzden OpenCodex onu değiştirmez. Dosyayı düzeltip yeniden bağlanın.","config.json / settings.json không phải JSON thuần (có chú thích, dấu phẩy thừa hoặc lỗi cú pháp), nên OpenCodex sẽ không sửa nó. Hãy sửa tệp rồi kết nối lại.","config.json / settings.json não é JSON puro (comentários, vírgulas finais ou erro de sintaxe), então o OpenCodex não vai alterá-lo. Corrija o arquivo e conecte de novo.", "config.json / settings.json no es JSON puro (tiene comentarios, comas finales o un error de sintaxis), así que OpenCodex no lo modificará. Corrige el archivo y vuelve a conectar."], + noteSettingsNotObject: ["config.json / settings.json does not contain a JSON object, so OpenCodex will not change it.","config.json / settings.json에 JSON 객체가 없어서 OpenCodex가 바꾸지 않아요.","config.json / settings.json enthält kein JSON-Objekt, daher ändert OpenCodex sie nicht.","config.json / settings.json ne contient pas d’objet JSON ; OpenCodex ne le modifiera pas.","config.json / settings.json 不包含 JSON 对象,OpenCodex 不会修改它。","config.json / settings.json 不包含 JSON 物件,OpenCodex 不會修改它。","config.json / settings.json не содержит JSON-объект, поэтому OpenCodex его не изменит.","config.json / settings.json に JSON オブジェクトがないため、OpenCodex は変更しません。","config.json / settings.json bir JSON nesnesi içermiyor, bu yüzden OpenCodex onu değiştirmez.","config.json / settings.json không chứa đối tượng JSON, nên OpenCodex sẽ không sửa nó.","config.json / settings.json não contém um objeto JSON, então o OpenCodex não vai alterá-lo.", "config.json / settings.json no contiene un objeto JSON, así que OpenCodex no lo modificará."], noteNoRestoreRecord: ["This was connected outside OpenCodex, so Disconnect cannot bring back your earlier settings.","OpenCodex 밖에서 연결되어 있어 연결 해제로 이전 설정을 되돌릴 수 없어요.","Die Verbindung wurde außerhalb von OpenCodex eingerichtet; Trennen kann Ihre früheren Einstellungen daher nicht zurückholen.","La connexion a été faite hors d’OpenCodex ; Déconnecter ne peut donc pas rétablir vos réglages précédents.","这是在 OpenCodex 之外连接的,断开无法恢复你之前的设置。","這是在 OpenCodex 之外連線的,中斷連線無法還原你先前的設定。","Подключение сделано вне OpenCodex, поэтому отключение не вернёт ваши прежние настройки.","OpenCodex の外で接続されたため、切断しても以前の設定には戻せません。","Bu bağlantı OpenCodex dışında yapılmış, bu yüzden Bağlantıyı kes önceki ayarlarınızı geri getiremez.","Kết nối này được tạo bên ngoài OpenCodex, nên Ngắt kết nối không thể khôi phục cài đặt cũ.","Isto foi conectado fora do OpenCodex, então Desconectar não consegue trazer de volta suas configurações anteriores.", "Esta conexión se hizo fuera de OpenCodex, así que Desconectar no puede recuperar tu configuración anterior."], noteAgyVersion: ["Needs agy 1.2.15 or newer.","agy 1.2.15 이상이 필요해요.","Erfordert agy 1.2.15 oder neuer.","Nécessite agy 1.2.15 ou plus récent.","需要 agy 1.2.15 或更新版本。","需要 agy 1.2.15 或更新版本。","Нужна agy 1.2.15 или новее.","agy 1.2.15 以降が必要です。","agy 1.2.15 veya daha yenisi gerekir.","Cần agy 1.2.15 trở lên.","Requer agy 1.2.15 ou mais recente.", "Requiere agy 1.2.15 o posterior."], noteWindowsUnverified: ["Google documents this for macOS and Linux. The Windows build reads the same settings, but this has not been tested end to end on Windows.","Google은 macOS와 Linux용으로만 문서화했어요. Windows 빌드도 같은 설정을 읽지만 Windows에서 처음부터 끝까지 검증하지는 않았어요.","Google dokumentiert dies für macOS und Linux. Die Windows-Version liest dieselben Einstellungen, unter Windows wurde das aber nicht durchgängig getestet.","Google le documente pour macOS et Linux. La version Windows lit les mêmes réglages, mais cela n’a pas été testé de bout en bout sous Windows.","Google 只为 macOS 和 Linux 提供了文档。Windows 版也会读取同样的设置,但尚未在 Windows 上完整验证。","Google 只為 macOS 和 Linux 提供了文件。Windows 版也會讀取同樣的設定,但尚未在 Windows 上完整驗證。","Google описывает это для macOS и Linux. Сборка для Windows читает те же настройки, но под Windows это не проверено полностью.","Google が文書化しているのは macOS と Linux です。Windows 版も同じ設定を読みますが、Windows では通しで検証していません。","Google bunu macOS ve Linux için belgeliyor. Windows sürümü aynı ayarları okur ama Windows'ta uçtan uca test edilmedi.","Google chỉ mô tả cho macOS và Linux. Bản Windows cũng đọc cùng cài đặt, nhưng chưa được kiểm thử đầy đủ trên Windows.","O Google documenta isto para macOS e Linux. A versão para Windows lê as mesmas configurações, mas isso não foi testado de ponta a ponta no Windows.", "Google lo documenta para macOS y Linux. La versión de Windows lee la misma configuración, pero esto no se ha probado de principio a fin en Windows."], @@ -43,7 +43,7 @@ const rows = { hintAgy: ["Open a new terminal to apply it.","적용하려면 새 터미널을 여세요.","Öffnen Sie ein neues Terminal, damit es wirkt.","Ouvrez un nouveau terminal pour l’appliquer.","打开新的终端后生效。","開啟新的終端機後生效。","Откройте новый терминал, чтобы применить.","反映するには新しいターミナルを開いてください。","Uygulamak için yeni bir terminal açın.","Mở terminal mới để áp dụng.","Abra um novo terminal para aplicar.", "Abre una terminal nueva para aplicarlo."], refusedCredential: ["This proxy's address requires an API key, and OpenCodex will not write a real key into these files. Turn on unauthenticatedLoopbackListener or bind the proxy to loopback.","이 프록시 주소는 API 키가 필요하고, OpenCodex는 실제 키를 이 파일들에 쓰지 않아요. unauthenticatedLoopbackListener를 켜거나 프록시를 루프백에 바인딩하세요.","Diese Proxy-Adresse verlangt einen API-Schlüssel, und OpenCodex schreibt keinen echten Schlüssel in diese Dateien. Aktivieren Sie unauthenticatedLoopbackListener oder binden Sie den Proxy an Loopback.","L’adresse de ce proxy exige une clé d’API, et OpenCodex n’écrira pas de vraie clé dans ces fichiers. Activez unauthenticatedLoopbackListener ou liez le proxy à la boucle locale.","此代理地址需要 API 密钥,而 OpenCodex 不会把真实密钥写进这些文件。请开启 unauthenticatedLoopbackListener,或把代理绑定到回环地址。","此代理位址需要 API 金鑰,而 OpenCodex 不會把真實金鑰寫進這些檔案。請開啟 unauthenticatedLoopbackListener,或把代理繫結到回環位址。","Адрес этого прокси требует ключ API, а OpenCodex не запишет настоящий ключ в эти файлы. Включите unauthenticatedLoopbackListener или привяжите прокси к loopback.","このプロキシのアドレスは API キーを必要としますが、OpenCodex は本物のキーをこれらのファイルに書きません。unauthenticatedLoopbackListener を有効にするか、プロキシをループバックにバインドしてください。","Bu proxy adresi bir API anahtarı istiyor ve OpenCodex bu dosyalara gerçek bir anahtar yazmaz. unauthenticatedLoopbackListener'ı açın ya da proxy'yi loopback'e bağlayın.","Địa chỉ proxy này cần khóa API, và OpenCodex sẽ không ghi khóa thật vào các tệp này. Hãy bật unauthenticatedLoopbackListener hoặc gắn proxy vào loopback.","O endereço deste proxy exige uma chave de API, e o OpenCodex não grava uma chave real nesses arquivos. Ative unauthenticatedLoopbackListener ou vincule o proxy ao loopback.", "La dirección de este proxy requiere una clave API, y OpenCodex no escribirá una clave real en estos archivos. Activa unauthenticatedLoopbackListener o vincula el proxy a loopback."], refusedModel: ["The model must be one line of at most 200 characters.","모델은 200자 이하의 한 줄이어야 해요.","Das Modell muss eine Zeile mit höchstens 200 Zeichen sein.","Le modèle doit tenir sur une ligne de 200 caractères au plus.","模型必须是不超过 200 个字符的单行文本。","模型必須是不超過 200 個字元的單行文字。","Модель должна быть одной строкой не длиннее 200 символов.","モデルは 200 文字以内の 1 行にしてください。","Model en fazla 200 karakterlik tek bir satır olmalı.","Mô hình phải là một dòng tối đa 200 ký tự.","O modelo deve ser uma linha de no máximo 200 caracteres.", "El modelo debe ser una sola línea de 200 caracteres como máximo."], - refusedFile: ["settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again.","settings.json을 JSON 객체로 읽을 수 없어 OpenCodex가 그대로 두었어요. 파일을 고친 뒤 다시 시도하세요.","settings.json konnte nicht als JSON-Objekt gelesen werden, daher hat OpenCodex sie nicht verändert. Korrigieren Sie die Datei und versuchen Sie es erneut.","settings.json n’a pas pu être lu comme un objet JSON ; OpenCodex n’y a pas touché. Corrigez le fichier, puis réessayez.","无法把 settings.json 读成 JSON 对象,OpenCodex 没有改动它。修好文件后重试。","無法把 settings.json 讀成 JSON 物件,OpenCodex 沒有變動它。修好檔案後重試。","settings.json не удалось прочитать как JSON-объект, поэтому OpenCodex его не тронул. Исправьте файл и попробуйте снова.","settings.json を JSON オブジェクトとして読めなかったため、OpenCodex は変更していません。ファイルを直してからやり直してください。","settings.json bir JSON nesnesi olarak okunamadı, bu yüzden OpenCodex ona dokunmadı. Dosyayı düzeltip yeniden deneyin.","Không đọc được settings.json như một đối tượng JSON, nên OpenCodex không động vào nó. Hãy sửa tệp rồi thử lại.","Não foi possível ler settings.json como um objeto JSON, então o OpenCodex não o alterou. Corrija o arquivo e tente de novo.", "settings.json no se pudo leer como objeto JSON, así que OpenCodex no lo tocó. Corrige el archivo y vuelve a intentarlo."], + refusedFile: ["config.json / settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again.","config.json / settings.json을 JSON 객체로 읽을 수 없어 OpenCodex가 그대로 두었어요. 파일을 고친 뒤 다시 시도하세요.","config.json / settings.json konnte nicht als JSON-Objekt gelesen werden, daher hat OpenCodex sie nicht verändert. Korrigieren Sie die Datei und versuchen Sie es erneut.","config.json / settings.json n’a pas pu être lu comme un objet JSON ; OpenCodex n’y a pas touché. Corrigez le fichier, puis réessayez.","无法把 config.json / settings.json 读成 JSON 对象,OpenCodex 没有改动它。修好文件后重试。","無法把 config.json / settings.json 讀成 JSON 物件,OpenCodex 沒有變動它。修好檔案後重試。","config.json / settings.json не удалось прочитать как JSON-объект, поэтому OpenCodex его не тронул. Исправьте файл и попробуйте снова.","config.json / settings.json を JSON オブジェクトとして読めなかったため、OpenCodex は変更していません。ファイルを直してからやり直してください。","config.json / settings.json bir JSON nesnesi olarak okunamadı, bu yüzden OpenCodex ona dokunmadı. Dosyayı düzeltip yeniden deneyin.","Không đọc được config.json / settings.json như một đối tượng JSON, nên OpenCodex không động vào nó. Hãy sửa tệp rồi thử lại.","Não foi possível ler config.json / settings.json como um objeto JSON, então o OpenCodex não o alterou. Corrija o arquivo e tente de novo.", "config.json / settings.json no se pudo leer como objeto JSON, así que OpenCodex no lo tocó. Corrige el archivo y vuelve a intentarlo."], refusedIo: ["Could not write the client files:","클라이언트 파일을 쓰지 못했어요:","Die Clientdateien konnten nicht geschrieben werden:","Impossible d’écrire les fichiers du client :","无法写入客户端文件:","無法寫入用戶端檔案:","Не удалось записать файлы клиента:","クライアントのファイルを書き込めませんでした:","İstemci dosyaları yazılamadı:","Không ghi được các tệp của máy khách:","Não foi possível gravar os arquivos do cliente:", "No se pudieron escribir los archivos del cliente:"], refused: ["The proxy refused the change:","프록시가 변경을 거부했어요:","Der Proxy hat die Änderung abgelehnt:","Le proxy a refusé la modification :","代理拒绝了此更改:","代理拒絕了此變更:","Прокси отклонил изменение:","プロキシが変更を拒否しました:","Proxy değişikliği reddetti:","Proxy đã từ chối thay đổi:","O proxy recusou a alteração:", "El proxy rechazó el cambio:"], actionFailed: ["Could not confirm whether the change was applied. Check the client status before trying again.","변경이 적용됐는지 확인하지 못했어요. 다시 시도하기 전에 클라이언트 상태를 확인하세요.","Es ließ sich nicht bestätigen, ob die Änderung übernommen wurde. Prüfen Sie den Client-Status, bevor Sie es erneut versuchen.","Impossible de confirmer si la modification a été appliquée. Vérifiez l’état du client avant de réessayer.","无法确认更改是否已生效。请先检查客户端状态再重试。","無法確認變更是否已生效。請先檢查用戶端狀態再重試。","Не удалось подтвердить, применено ли изменение. Проверьте состояние клиента, прежде чем повторять попытку.","変更が適用されたか確認できませんでした。再試行する前にクライアントの状態を確認してください。","Değişikliğin uygulanıp uygulanmadığı doğrulanamadı. Yeniden denemeden önce istemci durumunu kontrol edin.","Không xác nhận được thay đổi đã được áp dụng hay chưa. Hãy kiểm tra trạng thái client trước khi thử lại.","Não foi possível confirmar se a alteração foi aplicada. Verifique o status do cliente antes de tentar novamente.", "No se pudo confirmar si el cambio se aplicó. Revisa el estado del cliente antes de volver a intentarlo."], diff --git a/gui/tests/gateway-clients-page.test.tsx b/gui/tests/gateway-clients-page.test.tsx index 57e862d538a..e8afbd31e71 100644 --- a/gui/tests/gateway-clients-page.test.tsx +++ b/gui/tests/gateway-clients-page.test.tsx @@ -50,7 +50,10 @@ beforeEach(() => { client({ id: "antigravity", label: "Antigravity", - files: [{ path: "/home/u/.antigravity/settings.json", role: "user settings", exists: true }], + files: [ + { path: "/home/u/.gemini/config/config.json", role: "user settings", exists: true }, + { path: "/home/u/.antigravity/settings.json", role: "user settings", exists: true }, + ], overrides: [{ source: "admin_settings", code: "admin-gateway", detail: "organization admin_settings.json sets the gateway" }], notes: [{ code: "restart-app", text: "Restart Antigravity to apply a change." }, { code: "no-google-sign-in", text: "In gateway mode the app does not use the Google sign-in." }], defaultModel: "gemini-3-pro", @@ -125,6 +128,7 @@ test("lists both clients with state, files, translated notes and the admin_setti const antigravity = card("antigravity"); expect(antigravity.querySelector("[data-gateway-state='disconnected']")?.textContent).toBe("Not connected"); expect(antigravity.textContent).toContain("/home/u/.antigravity/settings.json"); + expect(antigravity.textContent).toContain("/home/u/.gemini/config/config.json"); expect(antigravity.querySelector(".notice-warn")?.textContent).toBe("Your organization's admin_settings.json sets a gateway, so this connection has no effect."); expect(antigravity.textContent).toContain("While connected, the app does not use your Google sign-in."); // The server's English never reaches the page, and the restart hint waits for an action. @@ -174,7 +178,7 @@ test("a refusal is translated from its code, and an I/O error keeps the system t await act(async () => { button(card("antigravity"), "Disconnect").click(); }); await settle(); expect(requests.find(request => request.method === "POST")?.url).toBe(`${apiBase}/api/gateway-clients/antigravity/disconnect`); - expect(card("antigravity").querySelector(".notice-err")?.textContent).toBe("settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again."); + expect(card("antigravity").querySelector(".notice-err")?.textContent).toBe("config.json / settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again."); actionResponse = () => json({ ok: false, code: "io-error", message: "EACCES: permission denied" }, 409); await act(async () => { button(card("agy"), "Disconnect").click(); }); diff --git a/src/integrations/gateway-clients/antigravity.ts b/src/integrations/gateway-clients/antigravity.ts index 5793c7acc93..d2a193e9318 100644 --- a/src/integrations/gateway-clients/antigravity.ts +++ b/src/integrations/gateway-clients/antigravity.ts @@ -1,12 +1,12 @@ /** - * Antigravity desktop app (2.15+): ~/.antigravity/settings.json "gateway" block. + * Antigravity 2.30+ reads ~/.gemini/config/config.json; 2.15–2.29 reads ~/.antigravity/settings.json. * Field facts and the stash-and-restore idea follow Magpie (MIT, (c) yetone), internal/agent/antigravity.go. */ -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { GATEWAY_PLACEHOLDER_KEY, adminGatewayOverride, dropStash, envGatewayOverride, mkdirTracked, normalizeUrl, assertClientSize, checkedClientDestination, clientRefusal, inspectClientFile, inspectStashPresence, isRestoreFile, mutateClient, - readClientFile, readStash, removeCreatedClientFile, rmdirsIfEmpty, sha256, writeClientFile, writeStash, + readClientFile, readStash, removeCreatedClientFile, rmdirsIfEmpty, sha256, writeClientFile, writeStash, type ClientFile, } from "./io"; import { GATEWAY_NOTE_TEXT, gatewayNote, type GatewayClientConnector, type GatewayClientContext, type GatewayClientResult, type GatewayClientStatus, type GatewayNoteCode, type GatewayTarget } from "./types"; @@ -27,12 +27,16 @@ interface Stash extends Written { prior: { gateway: Prior; defaultModelId: Prior; list: Prior; modelsPresent: boolean }; pending?: Written; pathWiseOnly?: true; + restoredSha256?: string; } const statesOf = (stash: Stash): Written[] => [stash, ...(stash.pending ? [stash.pending] : [])]; const ID = "antigravity"; const BOM = String.fromCharCode(0xfeff); -const settingsPath = (ctx: GatewayClientContext) => join(ctx.home, ".antigravity", "settings.json"); +const settingsPaths = (ctx: GatewayClientContext) => [ + join(ctx.home, ".gemini", "config", "config.json"), + join(ctx.home, ".antigravity", "settings.json"), +]; const isObj = (v: unknown): v is Json => !!v && typeof v === "object" && !Array.isArray(v); const same = (a: unknown, b: unknown) => Bun.deepEquals(a, b, true); const prior = (o: Json | undefined, k: string): Prior => o && k in o ? { present: true, value: o[k] } : { present: false }; @@ -71,32 +75,53 @@ function ours(gw: unknown, target?: GatewayTarget): "match" | "other-url" | "no" } function status(ctx: GatewayClientContext, target?: GatewayTarget): GatewayClientStatus { - const path = settingsPath(ctx); - const file = inspectClientFile(ctx, path); - const parsed = parseSettings(file?.bytes ?? null); - const gw = typeof parsed === "string" ? undefined : parsed.doc.gateway; + const settings = settingsPaths(ctx).map(path => { + const file = inspectClientFile(ctx, path); + const parsed = parseSettings(file?.bytes ?? null); + const gw = typeof parsed === "string" ? undefined : parsed.doc.gateway; + return { path, file, parsed, match: ours(gw, target) }; + }); const hasRecord = inspectStashPresence(ctx, ID); - const match = ours(gw, target) === "match"; - const state = match ? "connected" : hasRecord || file === undefined ? "drifted" : "disconnected"; + const match = settings.every(s => s.match === "match"); + const drifted = hasRecord || settings.some(s => s.file === undefined || s.match !== "no"); + const state = match ? "connected" : drifted ? "drifted" : "disconnected"; const overrides: GatewayClientStatus["overrides"] = []; const admin = adminGatewayOverride(ctx); if (admin) overrides.push(admin); const env = envGatewayOverride(ctx, target?.url); if (env) overrides.push(env); const notes = (["restart-app", "no-google-sign-in", "agy-follows-app"] as GatewayNoteCode[]).map(gatewayNote); - if (typeof parsed === "string") notes.push(gatewayNote(parsed)); + for (const { parsed } of settings) { + if (typeof parsed === "string" && !notes.some(n => n.code === parsed)) notes.push(gatewayNote(parsed)); + } if (match && !hasRecord) notes.push(gatewayNote("no-restore-record")); - const models = typeof parsed === "string" || !isObj(parsed.doc.models) ? undefined : parsed.doc.models; - const defaultModel = typeof models?.defaultModelId === "string" ? models.defaultModelId : undefined; - return { id: ID, label: "Antigravity", state, files: [{ path, role: "user settings", exists: file !== null }], overrides, notes, ...(defaultModel ? { defaultModel } : {}) }; + const defaultModel = settings.map(({ parsed }) => { + const models = typeof parsed === "string" || !isObj(parsed.doc.models) ? undefined : parsed.doc.models; + return typeof models?.defaultModelId === "string" ? models.defaultModelId : undefined; + }).find(model => model !== undefined); + const files = settings.map(({ path, file }) => ({ path, role: "user settings", exists: file !== null })); + return { id: ID, label: "Antigravity", state, files, overrides, notes, ...(defaultModel ? { defaultModel } : {}) }; } -function checkedStash(ctx: GatewayClientContext, path: string): Stash | null { - const stash = readStash(ctx, ID); - if (stash && (stash.path !== path || !isRestoreFile(ctx.home, path, stash))) { - throw new Error("Antigravity restore record does not name the expected settings file"); +function checkedStashes(ctx: GatewayClientContext): Map { + const saved = readStash(ctx, ID); + // Releases before dual-file support saved one legacy settings record directly. + const records = saved === null ? [] : "files" in saved ? saved.files : [saved]; + if (!Array.isArray(records)) throw new Error("Invalid Antigravity restore records"); + const allowed = settingsPaths(ctx); + const stashes = new Map(); + for (const stash of records) { + if (!stash || !allowed.includes(stash.path) || stashes.has(stash.path) || !isRestoreFile(ctx.home, stash.path, stash)) { + throw new Error("Antigravity restore record does not name an expected settings file"); + } + stashes.set(stash.path, stash); } - return stash; + return stashes; +} + +function saveStashes(ctx: GatewayClientContext, stashes: Map): void { + if (stashes.size === 0) dropStash(ctx, ID); + else writeStash(ctx, ID, { version: 1, files: [...stashes.values()] }); } function assertSameTarget(stash: Stash | null, target: string | undefined): void { @@ -105,25 +130,18 @@ function assertSameTarget(stash: Stash | null, target: string | undefined): void } } -function connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClientResult { - const path = settingsPath(ctx); - const file = readClientFile(ctx, path); +function planConnect(ctx: GatewayClientContext, target: GatewayTarget, path: string, file: ClientFile | null, parsed: Parsed, stash: Stash | null) { const bytes = file?.bytes ?? null; - const parsed = parseSettings(bytes); - if (typeof parsed === "string") return clientRefusal(GATEWAY_NOTE_TEXT[parsed], "unsupported-file"); const { doc } = parsed; - let stash = checkedStash(ctx, path); assertSameTarget(stash, file?.target); const keep = stash !== null && ours(doc.gateway, undefined) === "match"; const onDisk = keep && file ? statesOf(stash!).find(st => st.writtenSha256 === file.hash) : undefined; const models = isObj(doc.models) ? doc.models : undefined; - const dir = join(ctx.home, ".antigravity"); const resolvedPath = checkedClientDestination(ctx, path, file); assertSameTarget(stash, resolvedPath); - const newDirs = mkdirTracked(dir); if (!keep) { stash = { - version: 1, path, resolvedPath, originalBytes: bytes ? bytes.toString("base64") : null, createdDirs: [...(stash?.createdDirs ?? []), ...newDirs], + version: 1, path, resolvedPath, originalBytes: bytes ? bytes.toString("base64") : null, createdDirs: stash?.createdDirs ?? [], prior: { gateway: prior(doc, "gateway"), defaultModelId: prior(models, "defaultModelId"), list: prior(models, "list"), modelsPresent: models !== undefined }, // Until the new bytes land, the file on disk is the original; exact restoration of it is a no-op. written: { gateway: null, defaultModelId: null }, writtenSha256: file?.hash ?? "", @@ -151,34 +169,49 @@ function connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClien const out = serialize(parsed); const outSha = sha256(out); const next = stash as Stash; + delete next.restoredSha256; const applied: Written = { written: { gateway, defaultModelId: target.defaultModel ?? (keep ? next.written.defaultModelId : null) }, writtenSha256: outSha }; assertClientSize(out); - writeStash(ctx, ID, { ...next, pending: applied }); - writeClientFile(ctx, path, file, out); - // The settings are applied; if this promotion fails, the journaled pending state still describes them. - try { writeStash(ctx, ID, { ...next, ...applied }); } catch { /* pending stays recognisable */ } - const unchanged = file?.hash === outSha; - return { ok: true, changed: !unchanged, changedFiles: unchanged ? [] : [path], message: "Antigravity now uses the OpenCodex gateway. Restart Antigravity to apply it.", notes: status(ctx, target).notes }; + return { path, file, out, next, applied }; } -function disconnect(ctx: GatewayClientContext): GatewayClientResult { - const path = settingsPath(ctx); - const stash = checkedStash(ctx, path); - if (!stash) return { ok: true, changed: false, changedFiles: [], restore: "none", message: "Not connected by OpenCodex; nothing was changed.", notes: [] }; +function connect(ctx: GatewayClientContext, target: GatewayTarget): GatewayClientResult { + const stashes = checkedStashes(ctx); + const plans = []; + for (const path of settingsPaths(ctx)) { + const file = readClientFile(ctx, path); + const parsed = parseSettings(file?.bytes ?? null); + if (typeof parsed === "string") return clientRefusal(GATEWAY_NOTE_TEXT[parsed], "unsupported-file"); + plans.push(planConnect(ctx, target, path, file, parsed, stashes.get(path) ?? null)); + } + const changedFiles: string[] = []; + try { + for (const { path, file, out, next, applied } of plans) { + next.createdDirs = [...next.createdDirs, ...mkdirTracked(dirname(path))]; + stashes.set(path, { ...next, pending: applied }); + saveStashes(ctx, stashes); + writeClientFile(ctx, path, file, out); + if (file?.hash !== applied.writtenSha256) changedFiles.push(path); + // A failed promotion leaves the pending write available for disconnect or retry. + stashes.set(path, { ...next, ...applied }); + try { saveStashes(ctx, stashes); } catch { /* pending stays recognisable */ } + } + } catch (error) { return clientRefusal((error as Error).message, "io-error", changedFiles); } + return { ok: true, changed: changedFiles.length > 0, changedFiles, message: "Antigravity now uses the OpenCodex gateway. Restart Antigravity to apply it.", notes: status(ctx, target).notes }; +} + +interface RestorePlan { stash: Stash; file: ClientFile | null; restore: "exact" | "path-wise" | "none"; out?: Buffer } + +function planRestore(ctx: GatewayClientContext, stash: Stash): RestorePlan | GatewayClientResult { + const { path } = stash; const file = readClientFile(ctx, path); assertSameTarget(stash, file?.target); - const done = (restore: "exact" | "path-wise" | "none", message: string, files: string[]): GatewayClientResult => { - try { dropStash(ctx, ID); } - catch (error) { return clientRefusal(`Could not remove the Antigravity restore record: ${(error as Error).message}`, "io-error", files); } - return { ok: true, changed: files.length > 0, changedFiles: files, restore, message, notes: [gatewayNote("restart-app")] }; - }; + if (file && file.hash === stash.restoredSha256) return { stash, file: null, restore: "none" }; const states = statesOf(stash); if (file && !stash.pathWiseOnly && states.some(st => st.writtenSha256 === file.hash)) { - if (stash.originalBytes === null) { removeCreatedClientFile(ctx, path, file); rmdirsIfEmpty(ctx, stash.createdDirs); } - else writeClientFile(ctx, path, file, Buffer.from(stash.originalBytes, "base64")); - return done("exact", "Antigravity settings restored byte for byte.", [path]); + return { stash, file, restore: "exact", ...(stash.originalBytes === null ? {} : { out: Buffer.from(stash.originalBytes, "base64") }) }; } - if (!file) return done("none", "The settings file is already gone; the restore record was cleared.", []); + if (!file) return { stash, file, restore: "none" }; const parsed = parseSettings(file.bytes); if (typeof parsed === "string") return clientRefusal(`${GATEWAY_NOTE_TEXT[parsed]} The restore record was kept.`, "unsupported-file"); const { doc } = parsed; @@ -213,8 +246,39 @@ function disconnect(ctx: GatewayClientContext): GatewayClientResult { } const finalModels = isObj(doc.models) ? doc.models : undefined; if (finalModels && Object.keys(finalModels).length === 0 && !stash.prior.modelsPresent) delete doc.models; - writeClientFile(ctx, path, file, serialize(parsed)); - return done("path-wise", `The file changed after OpenCodex wrote it, so only the gateway, models.defaultModelId and models.list entries were restored; your other edits were kept.`, [path]); + return { stash, file, restore: "path-wise", out: serialize(parsed) }; +} + +function disconnect(ctx: GatewayClientContext): GatewayClientResult { + const stashes = checkedStashes(ctx); + const plans: RestorePlan[] = []; + for (const stash of stashes.values()) { + const plan = planRestore(ctx, stash); + if ("ok" in plan) return plan; + plans.push(plan); + } + const changedFiles: string[] = []; + try { + for (const { stash, file, out } of plans) { + if (file) { + if (out) { + stashes.set(stash.path, { ...stash, restoredSha256: sha256(out) }); + saveStashes(ctx, stashes); + writeClientFile(ctx, stash.path, file, out); + } + else removeCreatedClientFile(ctx, stash.path, file); + changedFiles.push(stash.path); + } + if (stash.originalBytes === null) rmdirsIfEmpty(ctx, stash.createdDirs); + stashes.delete(stash.path); + saveStashes(ctx, stashes); + } + } catch (error) { return clientRefusal((error as Error).message, "io-error", changedFiles); } + const restore = plans.some(p => p.restore === "path-wise") ? "path-wise" : plans.some(p => p.restore === "exact") ? "exact" : "none"; + const message = restore === "path-wise" + ? "The settings changed after OpenCodex wrote them. Only the managed gateway and model entries were restored, keeping your other edits." + : restore === "exact" ? "Antigravity settings restored byte for byte." : "No recorded settings remain to restore."; + return { ok: true, changed: changedFiles.length > 0, changedFiles, restore, message, notes: [gatewayNote("restart-app")] }; } export const ANTIGRAVITY_CONNECTOR: GatewayClientConnector = { diff --git a/src/integrations/gateway-clients/io.ts b/src/integrations/gateway-clients/io.ts index a9a7b0a1393..70aab18b11a 100644 --- a/src/integrations/gateway-clients/io.ts +++ b/src/integrations/gateway-clients/io.ts @@ -274,5 +274,5 @@ export function envGatewayOverride(ctx: GatewayClientContext, targetUrl?: string if (targetUrl && normalizeUrl(raw) === normalizeUrl(targetUrl)) return null; let shown = "an unparseable value"; try { shown = new URL(raw).origin; } catch { /* keep generic */ } - return { source: "env", code: "env-gateway", detail: `AGY_LLM_GATEWAY_URL is set to ${shown} in the environment OpenCodex sees (other shells are not checked) and wins over ~/.antigravity/settings.json` }; + return { source: "env", code: "env-gateway", detail: `AGY_LLM_GATEWAY_URL is set to ${shown} in the environment OpenCodex sees (other shells are not checked) and wins over the user gateway settings files` }; } diff --git a/src/integrations/gateway-clients/types.ts b/src/integrations/gateway-clients/types.ts index 101fa14e8a6..98ae00dfb90 100644 --- a/src/integrations/gateway-clients/types.ts +++ b/src/integrations/gateway-clients/types.ts @@ -27,8 +27,8 @@ export const GATEWAY_NOTE_TEXT = { "restart-app": "Restart Antigravity to apply a change.", "no-google-sign-in": "In gateway mode the app does not use the Google sign-in.", "agy-follows-app": "agy follows this file unless it is connected on its own.", - "settings-not-json": "settings.json is not strict JSON (comments, trailing commas or a syntax error). OpenCodex will not rewrite a file it cannot round-trip; fix or simplify it, then connect again.", - "settings-not-object": "settings.json does not hold a JSON object, so OpenCodex left it untouched.", + "settings-not-json": "The Antigravity settings file must contain strict JSON. Remove comments, trailing commas or syntax errors, then connect again.", + "settings-not-object": "The Antigravity settings file must contain a JSON object.", "no-restore-record": "No restore record exists (connected outside OpenCodex), so disconnect cannot restore your previous settings.", "new-terminal": "Open a new terminal to pick up the agy function.", "agy-version": "Gateway support needs agy 1.2.15 or newer.", diff --git a/structure/clients/antigravity-gateway.md b/structure/clients/antigravity-gateway.md index 8eef4425e74..14443de3471 100644 --- a/structure/clients/antigravity-gateway.md +++ b/structure/clients/antigravity-gateway.md @@ -9,9 +9,13 @@ these clients are configured through Google's gateway settings, not through a pr | Id | What it is | Where the gateway setting lives | | --- | --- | --- | -| `antigravity` | The desktop app (2.15 and newer) | the `gateway` block and `models.defaultModelId` in `~/.antigravity/settings.json` | +| `antigravity` | The desktop app (2.15 and newer) | the `gateway` block and `models.defaultModelId` in `~/.gemini/config/config.json` for 2.30+ and `~/.antigravity/settings.json` for 2.15–2.29 | | `agy` | The command-line client (1.2.15 and newer) | a marked shell function in the bash, zsh and PowerShell profiles, exporting `AGY_LLM_GATEWAY_*` for `agy` only | +Each desktop version reads only its own settings file, and app upgrades leave gateway configuration +at its existing path. The connector in `src/integrations/gateway-clients/antigravity.ts` writes both +paths for fresh installs, upgrades and downgrades without detecting the app version. + The `agy` connector edits shell profiles. On Windows it uses existing PowerShell 7 and Windows PowerShell profiles, or creates the PowerShell 7 profile if neither exists. It also uses an existing `.bashrc`. On macOS and Linux it uses existing bash, zsh and PowerShell profiles and creates the @@ -35,10 +39,19 @@ and the applied or pending SHA-256 in `/gateway-clients/.json`. owner-only permissions, including a protected ACL on Windows. Client files use ordinary atomic replacement with inherited ACLs on Windows and retain their existing mode on POSIX. -The named restore destination must match the Antigravity settings path or a fixed agy profile -candidate under the user's home. Connectors explicitly resolve client symlinks and read regular files -up to 4 MiB. The named file's parent must resolve to its expected directory. The resolved file must -match the exact settings path or a fixed agy path for the same shell family under the canonical home. +The Antigravity stash uses `version` 1 with a `files` array of per-file records. The connector also +accepts the older flat version-1 record for `~/.antigravity/settings.json`. Reconnect adds the modern file's record while +preserving the original legacy restore data. Connect preflights both settings files before writing +either one. Disconnect preflights and restores only recorded files, restoring each independently +and retiring each completed record. Partial write or restore failures keep the recovery data needed +for a retry. + +The named restore destination must match one of the two Antigravity settings paths or a fixed agy +profile candidate under the user's home. Connectors explicitly resolve client symlinks and read +regular files up to 4 MiB. Each Antigravity settings file must resolve to its own exact path under +the canonical home, and its parent must resolve to the corresponding `.gemini/config` or +`.antigravity` directory. An agy file must resolve to a fixed profile path for the same shell family +under the canonical home, and its parent must resolve to its expected directory. Multiple agy profiles resolving to one file are updated once. The check runs before staging and again before replacement or removal. New restore records also pin the resolved destination. If the file or its resolved destination changes before replacement, the write is refused. Connect and disconnect use the @@ -85,6 +98,9 @@ and preserves unknown entries inside it. ## Which setting wins +Status lists `~/.gemini/config/config.json` first and `~/.antigravity/settings.json` second. It reports +`connected` only when both files match the OpenCodex gateway. Incomplete wiring is `drifted`. + Antigravity resolves the gateway as `admin_settings.json` over `AGY_LLM_GATEWAY_*` variables over the user settings file. Status reports an organisation `admin_settings.json` that sets `gateway` and an `AGY_LLM_GATEWAY_URL` in the OpenCodex process environment as `overrides` without echoing a diff --git a/tests/cli/gateway-client-command.test.ts b/tests/cli/gateway-client-command.test.ts index 42899fc1b5d..6003b50b44b 100644 --- a/tests/cli/gateway-client-command.test.ts +++ b/tests/cli/gateway-client-command.test.ts @@ -52,11 +52,15 @@ describe("ocx connect|disconnect antigravity|agy", () => { const body = JSON.parse(io.out.join("\n")); expect(body).toMatchObject({ ok: true, id: "antigravity", action: "connect", status: { state: "connected" } }); expect(JSON.parse(readFileSync(join(ctx.home, ".antigravity", "settings.json"), "utf8")).models.defaultModelId).toBe("gemini-3"); + const modern = join(ctx.home, ".gemini", "config", "config.json"); + expect(JSON.parse(readFileSync(modern, "utf8")).models.defaultModelId).toBe("gemini-3"); + expect(body.changedFiles).toContain(modern); io.out.length = 0; expect(await runGatewayClientFromArgs("connect", ["antigravity", "status", "--json"], offline())).toBe(0); expect(JSON.parse(io.out.join("\n"))).toMatchObject({ id: "antigravity", state: "connected" }); expect(await runGatewayClientFromArgs("disconnect", ["antigravity"], offline())).toBe(0); expect(existsSync(join(ctx.home, ".antigravity"))).toBe(false); + expect(existsSync(join(ctx.home, ".gemini"))).toBe(false); expect(io.out.join("\n")).toContain("restore: exact"); } finally { io.restore(); } }); diff --git a/tests/clients/gateway-client-restore.test.ts b/tests/clients/gateway-client-restore.test.ts index ef5ed886bf0..c65805e62a7 100644 --- a/tests/clients/gateway-client-restore.test.ts +++ b/tests/clients/gateway-client-restore.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; import { GATEWAY_CLIENTS, type GatewayClientContext } from "../../src/integrations/gateway-clients"; import * as gatewayIO from "../../src/integrations/gateway-clients/io"; @@ -21,6 +21,7 @@ afterEach(() => rmSync(root, { recursive: true, force: true })); const read = (path: string) => readFileSync(path, "utf8"); const record = (id: string) => join(ctx.stateDir, "gateway-clients", id + ".json"); const settings = () => join(ctx.home, ".antigravity", "settings.json"); +const modernSettings = () => join(ctx.home, ".gemini", "config", "config.json"); const originalSettings = { theme: "dark", gateway: { enabled: false }, @@ -155,3 +156,190 @@ test.each(["gateway", "models.defaultModelId", "models.list"])( expect(existsSync(record("antigravity"))).toBe(false); }, ); + +function seedLegacyConnection() { + const original = JSON.stringify(originalSettings, null, 2) + "\n"; + const gateway = { enabled: true, url: target.url, apiKey: target.apiKey, wireProtocol: "openai" }; + const connected = JSON.stringify({ ...originalSettings, gateway, models: { defaultModelId: target.defaultModel } }, null, 2) + "\n"; + const saved = { + version: 1, path: settings(), originalBytes: Buffer.from(original).toString("base64"), createdDirs: [], + prior: { + gateway: { present: true, value: originalSettings.gateway }, + defaultModelId: { present: true, value: originalSettings.models.defaultModelId }, + list: { present: true, value: originalSettings.models.list }, modelsPresent: true, + }, + written: { gateway, defaultModelId: target.defaultModel }, + writtenSha256: gatewayIO.sha256(Buffer.from(connected)), + }; + writeFileSync(settings(), connected); + mkdirSync(dirname(record("antigravity")), { recursive: true }); + writeFileSync(record("antigravity"), JSON.stringify(saved)); + return { original, saved }; +} + +test.each([false, true])("Antigravity restores a single-file v1 record with modern settings present = %s", modernExists => { + const { original } = seedLegacyConnection(); + const modern = '{"theme":"modern","models":{"defaultModelId":"native-model"}}\n'; + if (modernExists) { + mkdirSync(dirname(modernSettings()), { recursive: true }); + writeFileSync(modernSettings(), modern); + } + const app = GATEWAY_CLIENTS.antigravity; + expect(app.status(ctx, target).state).toBe("drifted"); + expect(app.disconnect(ctx)).toMatchObject({ ok: true, restore: "exact", changedFiles: [settings()] }); + expect(read(settings())).toBe(original); + expect(existsSync(modernSettings())).toBe(modernExists); + if (modernExists) expect(read(modernSettings())).toBe(modern); + expect(existsSync(record("antigravity"))).toBe(false); +}); + +test("Antigravity keeps a single-file v1 original when reconnect adds modern settings", () => { + const { original, saved } = seedLegacyConnection(); + const app = GATEWAY_CLIENTS.antigravity; + expect(app.connect(ctx, target).ok).toBe(true); + expect(app.status(ctx, target).state).toBe("connected"); + const upgraded = JSON.parse(read(record("antigravity"))); + expect(upgraded).toMatchObject({ version: 1 }); + expect(upgraded.files).toHaveLength(2); + expect(upgraded.files.find((file: { path: string }) => file.path === settings())).toMatchObject({ + originalBytes: saved.originalBytes, prior: saved.prior, + }); + expect(upgraded.files.find((file: { path: string }) => file.path === modernSettings())).toMatchObject({ originalBytes: null }); + expect(app.connect(ctx, { ...target, defaultModel: "second-model" }).ok).toBe(true); + expect(app.disconnect(ctx)).toMatchObject({ ok: true, restore: "exact" }); + expect(read(settings())).toBe(original); + expect(existsSync(join(ctx.home, ".gemini"))).toBe(false); + expect(existsSync(record("antigravity"))).toBe(false); +}); + +test.each([false, true])("Antigravity reconnect preserves both originals with unrelated edits = %s", edited => { + const app = GATEWAY_CLIENTS.antigravity; + const modernOriginal = { ...originalSettings, theme: "modern", models: { defaultModelId: "modern-model", list: [{ modelId: "modern-model" }] } }; + const legacyBytes = JSON.stringify(originalSettings, null, 4) + "\n"; + const modernBytes = "\ufeff" + JSON.stringify(modernOriginal, null, 2).replace(/\n/g, "\r\n") + "\r\n"; + mkdirSync(dirname(modernSettings()), { recursive: true }); + writeFileSync(modernSettings(), modernBytes); + writeFileSync(settings(), legacyBytes); + expect(app.connect(ctx, target)).toMatchObject({ ok: true, changedFiles: [modernSettings(), settings()] }); + if (edited) { + for (const path of [modernSettings(), settings()]) { + const connected = JSON.parse(read(path).replace(/^\ufeff/, "")); + writeFileSync(path, JSON.stringify({ ...connected, theme: "light", unrelated: path })); + } + } + expect(app.connect(ctx, { ...target, url: "http://127.0.0.1:10200", defaultModel: "second-model" }).ok).toBe(true); + const saved = JSON.parse(read(record("antigravity"))); + expect(saved).toMatchObject({ version: 1 }); + expect(saved.files).toHaveLength(2); + expect(saved.files.find((file: { path: string }) => file.path === modernSettings()).originalBytes).toBe(Buffer.from(modernBytes).toString("base64")); + expect(saved.files.find((file: { path: string }) => file.path === settings()).originalBytes).toBe(Buffer.from(legacyBytes).toString("base64")); + expect(app.disconnect(ctx)).toMatchObject({ ok: true, restore: edited ? "path-wise" : "exact" }); + if (edited) { + expect(JSON.parse(read(modernSettings()))).toEqual({ ...modernOriginal, theme: "light", unrelated: modernSettings() }); + expect(JSON.parse(read(settings()))).toEqual({ ...originalSettings, theme: "light", unrelated: settings() }); + } else { + expect(read(modernSettings())).toBe(modernBytes); + expect(read(settings())).toBe(legacyBytes); + } + expect(existsSync(record("antigravity"))).toBe(false); +}); + +test.each(["disconnect", "reconnect"])("Antigravity recovers a failed second settings write by %s", recovery => { + const app = GATEWAY_CLIENTS.antigravity; + const legacy = JSON.stringify(originalSettings, null, 4) + "\n"; + const modern = '{"theme":"modern","models":{"defaultModelId":"modern-model"}}\n'; + mkdirSync(dirname(modernSettings()), { recursive: true }); + writeFileSync(modernSettings(), modern); + writeFileSync(settings(), legacy); + const write = gatewayIO.writeClientFile; + const fault = spyOn(gatewayIO, "writeClientFile").mockImplementation((...args) => { + if (args[1] === settings()) throw new Error("fixture interrupted the second settings write"); + write(...args); + }); + try { + expect(app.connect(ctx, target)).toMatchObject({ ok: false, code: "io-error", changed: true, changedFiles: [modernSettings()] }); + } finally { + fault.mockRestore(); + } + expect(JSON.parse(read(modernSettings())).gateway.url).toBe(target.url); + expect(read(settings())).toBe(legacy); + const saved = JSON.parse(read(record("antigravity"))); + expect(saved).toMatchObject({ version: 1 }); + expect(saved.files).toHaveLength(2); + const pending = saved.files.find((file: { path: string }) => file.path === settings()); + expect(pending).toMatchObject({ + originalBytes: Buffer.from(legacy).toString("base64"), + pending: { written: { gateway: { url: target.url }, defaultModelId: target.defaultModel } }, + }); + expect(app.status(ctx, target).state).toBe("drifted"); + if (recovery === "reconnect") { + expect(app.connect(ctx, target).ok).toBe(true); + expect(app.status(ctx, target).state).toBe("connected"); + } + expect(app.disconnect(ctx)).toMatchObject({ ok: true, restore: "exact" }); + expect(read(modernSettings())).toBe(modern); + expect(read(settings())).toBe(legacy); + expect(existsSync(record("antigravity"))).toBe(false); +}); + +test("Antigravity retries a partial restore without revisiting the restored modern file", () => { + const app = GATEWAY_CLIENTS.antigravity; + mkdirSync(dirname(modernSettings()), { recursive: true }); + for (const path of [modernSettings(), settings()]) writeFileSync(path, JSON.stringify(originalSettings)); + expect(app.connect(ctx, target).ok).toBe(true); + for (const path of [modernSettings(), settings()]) { + writeFileSync(path, JSON.stringify({ ...JSON.parse(read(path)), theme: "light" })); + } + const write = gatewayIO.writeClientFile; + const fault = spyOn(gatewayIO, "writeClientFile").mockImplementation((...args) => { + if (args[1] === settings()) throw new Error("fixture interrupted the second settings restore"); + write(...args); + }); + try { + expect(app.disconnect(ctx)).toMatchObject({ ok: false, code: "io-error", changed: true, changedFiles: [modernSettings()] }); + } finally { + fault.mockRestore(); + } + expect(JSON.parse(read(modernSettings()))).toEqual({ ...originalSettings, theme: "light" }); + expect(JSON.parse(read(settings())).gateway.url).toBe(target.url); + expect(existsSync(record("antigravity"))).toBe(true); + const modernEdit = JSON.stringify({ ...JSON.parse(read(modernSettings())), gateway: { enabled: true, url: "https://user.example" } }); + writeFileSync(modernSettings(), modernEdit); + expect(app.disconnect(ctx)).toMatchObject({ ok: true, restore: "path-wise", changedFiles: [settings()] }); + expect(read(modernSettings())).toBe(modernEdit); + expect(JSON.parse(read(settings()))).toEqual({ ...originalSettings, theme: "light" }); + expect(existsSync(record("antigravity"))).toBe(false); +}); + +test("Antigravity retries after a restored file could not be removed from the journal", () => { + const app = GATEWAY_CLIENTS.antigravity; + const modernOriginal = '{\n "theme" : "modern"\n}\n'; + const legacyOriginal = '{ "theme" : "legacy" }\n'; + mkdirSync(dirname(modernSettings()), { recursive: true }); + writeFileSync(modernSettings(), modernOriginal); + writeFileSync(settings(), legacyOriginal); + expect(app.connect(ctx, target).ok).toBe(true); + + const write = gatewayIO.writeStash; + let writes = 0; + const fault = spyOn(gatewayIO, "writeStash").mockImplementation((...args) => { + writes += 1; + if (writes === 2) throw new Error("fixture interrupted journal retirement"); + write(...args); + }); + try { + expect(app.disconnect(ctx)).toMatchObject({ + ok: false, code: "io-error", changedFiles: [modernSettings()], + }); + } finally { + fault.mockRestore(); + } + expect(read(modernSettings())).toBe(modernOriginal); + expect(JSON.parse(read(settings())).gateway.url).toBe(target.url); + expect(existsSync(record("antigravity"))).toBe(true); + + expect(app.disconnect(ctx)).toMatchObject({ ok: true, changedFiles: [settings()] }); + expect(read(modernSettings())).toBe(modernOriginal); + expect(read(settings())).toBe(legacyOriginal); + expect(existsSync(record("antigravity"))).toBe(false); +}); diff --git a/tests/clients/gateway-client-safety.test.ts b/tests/clients/gateway-client-safety.test.ts index ad266c041fe..bd97fa7efee 100644 --- a/tests/clients/gateway-client-safety.test.ts +++ b/tests/clients/gateway-client-safety.test.ts @@ -1,7 +1,7 @@ import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { Database } from "bun:sqlite"; import { - existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, + chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, symlinkSync, truncateSync, writeFileSync, } from "node:fs"; import { tmpdir } from "node:os"; @@ -27,6 +27,7 @@ afterEach(() => rmSync(root, { recursive: true, force: true })); const read = (path: string) => readFileSync(path, "utf8"); const recordPath = (id: string) => join(ctx.stateDir, "gateway-clients", id + ".json"); const settings = () => join(ctx.home, ".antigravity", "settings.json"); +const modernSettings = () => join(ctx.home, ".gemini", "config", "config.json"); const profile = () => join(ctx.home, ".zshrc"); for (const [id, pathOf] of [["antigravity", settings], ["agy", profile]] as const) { @@ -39,12 +40,16 @@ for (const [id, pathOf] of [["antigravity", settings], ["agy", profile]] as cons const other = join(root, "unrelated"); writeFileSync(other, connected); const record = JSON.parse(read(recordPath(id))); - (id === "agy" ? record.files[0] : record).path = other; - writeFileSync(recordPath(id), JSON.stringify(record)); + const entry = record.files.find((file: { path: string }) => file.path === path); + entry.path = other; + const invalidRecord = JSON.stringify(record); + writeFileSync(recordPath(id), invalidRecord); + const modernBefore = id === "antigravity" ? read(modernSettings()) : undefined; expect(client.disconnect(ctx)).toMatchObject({ ok: false, changed: false }); expect(read(other)).toBe(connected); expect(read(path)).toBe(connected); - expect(existsSync(recordPath(id))).toBe(true); + if (id === "antigravity") expect(read(modernSettings())).toBe(modernBefore); + expect(read(recordPath(id))).toBe(invalidRecord); }); for (const action of ["connect", "disconnect"] as const) { @@ -60,7 +65,8 @@ for (const [id, pathOf] of [["antigravity", settings], ["agy", profile]] as cons }); try { const result = action === "connect" ? client.connect(ctx, target) : client.disconnect(ctx); - expect(result).toMatchObject({ ok: false, code: "io-error", changed: false }); + const changedFiles = id === "antigravity" ? [modernSettings()] : []; + expect(result).toMatchObject({ ok: false, code: "io-error", changed: changedFiles.length > 0, changedFiles }); } finally { rename.mockRestore(); } expect(read(path)).toBe(edit); expect(existsSync(recordPath(id))).toBe(true); @@ -199,6 +205,7 @@ test("Windows ACL hardening applies to restore records and leaves client files i const under = (dir: string) => aclPaths.some(path => dirname(path) === dir); expect(under(join(ctx.stateDir, "gateway-clients"))).toBe(true); expect(under(dirname(settings()))).toBe(false); + expect(under(dirname(modernSettings()))).toBe(false); expect(under(dirname(ps))).toBe(false); } finally { setWindowsHardeningForTests(null); @@ -226,16 +233,137 @@ test("agy refuses BOM-less UTF-16 instead of appending a different encoding", () expect(readFileSync(profile())).toEqual(utf16); }); -test("Antigravity reconnect retains a matching pending default after an unrelated edit", () => { - writeFileSync(settings(), originals.antigravity); +test("Antigravity reconnect retains matching pending defaults after unrelated edits", () => { + mkdirSync(dirname(modernSettings()), { recursive: true }); + for (const path of [modernSettings(), settings()]) writeFileSync(path, originals.antigravity); expect(GATEWAY_CLIENTS.antigravity.connect(ctx, target).ok).toBe(true); const old = JSON.parse(read(recordPath("antigravity"))); expect(GATEWAY_CLIENTS.antigravity.connect(ctx, { ...target, defaultModel: "pending" }).ok).toBe(true); - const { written, writtenSha256 } = JSON.parse(read(recordPath("antigravity"))); - writeFileSync(recordPath("antigravity"), JSON.stringify({ ...old, pending: { written, writtenSha256 } })); - const doc = JSON.parse(read(settings())); - writeFileSync(settings(), JSON.stringify({ ...doc, theme: "light" })); + const applied = JSON.parse(read(recordPath("antigravity"))); + for (const entry of old.files) { + const next = applied.files.find((file: { path: string }) => file.path === entry.path); + entry.pending = { written: next.written, writtenSha256: next.writtenSha256 }; + const doc = JSON.parse(read(entry.path)); + writeFileSync(entry.path, JSON.stringify({ ...doc, theme: "light" })); + } + writeFileSync(recordPath("antigravity"), JSON.stringify(old)); expect(GATEWAY_CLIENTS.antigravity.connect(ctx, target).ok).toBe(true); expect(GATEWAY_CLIENTS.antigravity.disconnect(ctx).restore).toBe("path-wise"); - expect(JSON.parse(read(settings()))).toEqual({ theme: "light", models: { defaultModelId: "mine" } }); + for (const path of [modernSettings(), settings()]) { + expect(JSON.parse(read(path))).toEqual({ theme: "light", models: { defaultModelId: "mine" } }); + } +}); + +for (const [label, pathOf] of [["modern", modernSettings], ["legacy", settings]] as const) { + test.each([false, true])("Antigravity preflights malformed " + label + " settings before edits with an existing record = %s", connected => { + mkdirSync(dirname(modernSettings()), { recursive: true }); + for (const path of [modernSettings(), settings()]) writeFileSync(path, originals.antigravity); + const app = GATEWAY_CLIENTS.antigravity; + if (connected) expect(app.connect(ctx, target).ok).toBe(true); + const saved = connected ? read(recordPath("antigravity")) : null; + writeFileSync(pathOf(), '{"theme":'); + const before = [modernSettings(), settings()].map(path => read(path)); + expect(app.connect(ctx, { ...target, defaultModel: "new-model" })).toMatchObject({ + ok: false, code: "unsupported-file", changed: false, changedFiles: [], + }); + expect([modernSettings(), settings()].map(path => read(path))).toEqual(before); + expect(existsSync(recordPath("antigravity"))).toBe(connected); + if (connected) expect(read(recordPath("antigravity"))).toBe(saved); + }); + + test("Antigravity validates the exact " + label + " restore path before any restore", () => { + mkdirSync(dirname(modernSettings()), { recursive: true }); + for (const path of [modernSettings(), settings()]) writeFileSync(path, originals.antigravity); + const app = GATEWAY_CLIENTS.antigravity; + expect(app.connect(ctx, target).ok).toBe(true); + const before = [modernSettings(), settings()].map(path => read(path)); + const sibling = pathOf() + ".backup"; + writeFileSync(sibling, read(pathOf())); + const saved = JSON.parse(read(recordPath("antigravity"))); + const entry = saved.files.find((file: { path: string }) => file.path === pathOf()); + entry.path = sibling; + entry.resolvedPath = sibling; + const invalid = JSON.stringify(saved); + writeFileSync(recordPath("antigravity"), invalid); + expect(app.disconnect(ctx)).toMatchObject({ ok: false, changed: false, changedFiles: [] }); + expect([modernSettings(), settings()].map(path => read(path))).toEqual(before); + expect(read(sibling)).toBe(read(pathOf())); + expect(read(recordPath("antigravity"))).toBe(invalid); + }); +} + +test.skipIf(process.platform === "win32")("Antigravity refuses a modern symlink to the allowed legacy settings file", () => { + const app = GATEWAY_CLIENTS.antigravity; + writeFileSync(settings(), originals.antigravity); + mkdirSync(dirname(modernSettings()), { recursive: true }); + symlinkSync(settings(), modernSettings()); + expect(app.status(ctx, target)).toMatchObject({ + state: "drifted", files: [{ path: modernSettings() }, { path: settings() }], + }); + expect(app.connect(ctx, target)).toMatchObject({ ok: false, code: "io-error", changed: false, changedFiles: [] }); + expect(read(settings())).toBe(originals.antigravity); + expect(readlinkSync(modernSettings())).toBe(settings()); + expect(existsSync(recordPath("antigravity"))).toBe(false); +}); + +test.skipIf(process.platform === "win32")("Antigravity refuses a dangling modern settings symlink before touching legacy", () => { + writeFileSync(settings(), originals.antigravity); + mkdirSync(dirname(modernSettings()), { recursive: true }); + const missing = join(ctx.home, "missing-settings.json"); + symlinkSync(missing, modernSettings()); + expect(GATEWAY_CLIENTS.antigravity.status(ctx, target).state).toBe("drifted"); + expect(GATEWAY_CLIENTS.antigravity.connect(ctx, target)).toMatchObject({ + ok: false, code: "io-error", changed: false, changedFiles: [], + }); + expect(read(settings())).toBe(originals.antigravity); + expect(readlinkSync(modernSettings())).toBe(missing); + expect(existsSync(missing)).toBe(false); + expect(existsSync(recordPath("antigravity"))).toBe(false); +}); + +test.skipIf(process.platform === "win32")("Antigravity refuses a redirected modern config directory even when config.json is absent", () => { + writeFileSync(settings(), originals.antigravity); + mkdirSync(join(ctx.home, ".gemini")); + const outside = join(root, "redirected-config"); + mkdirSync(outside); + symlinkSync(outside, dirname(modernSettings()), "dir"); + expect(GATEWAY_CLIENTS.antigravity.status(ctx, target).state).toBe("drifted"); + expect(GATEWAY_CLIENTS.antigravity.connect(ctx, target)).toMatchObject({ + ok: false, code: "io-error", changed: false, changedFiles: [], + }); + expect(read(settings())).toBe(originals.antigravity); + expect(readlinkSync(dirname(modernSettings()))).toBe(outside); + expect(existsSync(join(outside, "config.json"))).toBe(false); + expect(existsSync(recordPath("antigravity"))).toBe(false); +}); + +test("Antigravity refuses a non-regular modern settings file before touching legacy", () => { + writeFileSync(settings(), originals.antigravity); + mkdirSync(modernSettings(), { recursive: true }); + expect(GATEWAY_CLIENTS.antigravity.status(ctx, target).state).toBe("drifted"); + expect(GATEWAY_CLIENTS.antigravity.connect(ctx, target)).toMatchObject({ + ok: false, code: "io-error", changed: false, changedFiles: [], + }); + expect(read(settings())).toBe(originals.antigravity); + expect(lstatSync(modernSettings()).isDirectory()).toBe(true); + expect(existsSync(recordPath("antigravity"))).toBe(false); +}); + +test.skipIf(process.platform === "win32" || process.getuid?.() === 0)("Antigravity treats an unreadable modern directory as drifted and leaves legacy untouched", () => { + writeFileSync(settings(), originals.antigravity); + const modernDirectory = dirname(modernSettings()); + mkdirSync(modernDirectory, { recursive: true }); + writeFileSync(modernSettings(), originals.antigravity); + chmodSync(modernDirectory, 0); + try { + expect(GATEWAY_CLIENTS.antigravity.status(ctx, target).state).toBe("drifted"); + expect(GATEWAY_CLIENTS.antigravity.connect(ctx, target)).toMatchObject({ + ok: false, code: "io-error", changed: false, changedFiles: [], + }); + expect(read(settings())).toBe(originals.antigravity); + expect(existsSync(recordPath("antigravity"))).toBe(false); + } finally { + chmodSync(modernDirectory, 0o755); + } + expect(read(modernSettings())).toBe(originals.antigravity); }); diff --git a/tests/clients/gateway-clients.test.ts b/tests/clients/gateway-clients.test.ts index 1733fd4e449..09166a51b90 100644 --- a/tests/clients/gateway-clients.test.ts +++ b/tests/clients/gateway-clients.test.ts @@ -11,6 +11,7 @@ const target: GatewayTarget = { url: "http://127.0.0.1:10100", apiKey: "opencode let root: string; let ctx: GatewayClientContext; const settings = () => join(ctx.home, ".antigravity", "settings.json"); +const modernSettings = () => join(ctx.home, ".gemini", "config", "config.json"); const read = (p: string) => readFileSync(p, "utf8"); beforeEach(() => { @@ -45,15 +46,43 @@ describe("antigravity connector", () => { expect(existsSync(join(ctx.stateDir, "gateway-clients", "antigravity.json"))).toBe(false); }); - test("an absent file and directory are removed again on disconnect", () => { + test.each([false, true])("creates both settings files and cleans up with an existing Gemini directory = %s", existingDirectory => { const a = GATEWAY_CLIENTS.antigravity; - a.connect(ctx, target); - expect(existsSync(settings())).toBe(true); - a.disconnect(ctx); + if (existingDirectory) mkdirSync(join(ctx.home, ".gemini")); + expect(a.connect(ctx, target)).toMatchObject({ + ok: true, changed: true, changedFiles: [modernSettings(), settings()], + }); + for (const path of [modernSettings(), settings()]) { + expect(JSON.parse(read(path)).gateway).toEqual({ enabled: true, ...target, wireProtocol: "openai" }); + } + expect(a.status(ctx, target)).toMatchObject({ + state: "connected", + files: [{ path: modernSettings(), exists: true }, { path: settings(), exists: true }], + }); + expect(a.disconnect(ctx)).toMatchObject({ ok: true, restore: "exact" }); + expect(existsSync(join(ctx.home, ".gemini", "config"))).toBe(false); + expect(existsSync(join(ctx.home, ".gemini"))).toBe(existingDirectory); expect(existsSync(join(ctx.home, ".antigravity"))).toBe(false); expect(existsSync(join(ctx.stateDir, "gateway-clients"))).toBe(false); }); + test("an upgraded legacy-only connection is drifted until connect creates modern settings", () => { + mkdirSync(join(ctx.home, ".antigravity")); + const legacy = JSON.stringify({ gateway: { enabled: true, ...target, wireProtocol: "openai" } }); + writeFileSync(settings(), legacy); + const a = GATEWAY_CLIENTS.antigravity; + expect(a.status(ctx, target)).toMatchObject({ + state: "drifted", + files: [{ path: modernSettings(), exists: false }, { path: settings(), exists: true }], + }); + expect(a.connect(ctx, target).ok).toBe(true); + expect(JSON.parse(read(modernSettings())).gateway).toEqual({ enabled: true, ...target, wireProtocol: "openai" }); + expect(a.status(ctx, target).state).toBe("connected"); + expect(a.disconnect(ctx).ok).toBe(true); + expect(read(settings())).toBe(legacy); + expect(existsSync(join(ctx.home, ".gemini"))).toBe(false); + }); + test("a user edit after connect is kept and only the three stashed paths are restored", () => { mkdirSync(join(ctx.home, ".antigravity")); writeFileSync(settings(), USER_SETTINGS); @@ -85,29 +114,54 @@ describe("antigravity connector", () => { expect(doc.gateway.apiKey).toBe("user-key"); }); - test("a reconnect whose settings write did not land, or landed unpromoted, is still restorable", () => { + test.each([false, true])("a pending reconnect is restorable with settings writes landed = %s", landed => { mkdirSync(join(ctx.home, ".antigravity")); writeFileSync(settings(), USER_SETTINGS); const a = GATEWAY_CLIENTS.antigravity; const record = join(ctx.stateDir, "gateway-clients", "antigravity.json"); - a.connect(ctx, target); + expect(a.connect(ctx, target).ok).toBe(true); const appliedA = JSON.parse(read(record)); - const fileA = read(settings()); - a.connect(ctx, { ...target, url: "http://127.0.0.1:10200" }); + const before = new Map([modernSettings(), settings()].map(path => [path, read(path)])); + expect(a.connect(ctx, { ...target, url: "http://127.0.0.1:10200" }).ok).toBe(true); const appliedB = JSON.parse(read(record)); - // Write of B failed: the file still holds A while the journal names B as pending. - writeFileSync(settings(), fileA); - writeFileSync(record, JSON.stringify({ ...appliedA, pending: { written: appliedB.written, writtenSha256: appliedB.writtenSha256 } })); - expect(a.disconnect(ctx).restore).toBe("exact"); - expect(read(settings())).toBe(USER_SETTINGS); - // Write of B landed but the journal was never promoted. - a.connect(ctx, target); - const againA = JSON.parse(read(record)); - a.connect(ctx, { ...target, url: "http://127.0.0.1:10200" }); - const againB = JSON.parse(read(record)); - writeFileSync(record, JSON.stringify({ ...againA, pending: { written: againB.written, writtenSha256: againB.writtenSha256 } })); + if (!landed) { + for (const [path, bytes] of before) writeFileSync(path, bytes); + } + for (const entry of appliedA.files) { + const next = appliedB.files.find((file: { path: string }) => file.path === entry.path); + entry.pending = { written: next.written, writtenSha256: next.writtenSha256 }; + } + writeFileSync(record, JSON.stringify(appliedA)); expect(a.disconnect(ctx).restore).toBe("exact"); expect(read(settings())).toBe(USER_SETTINGS); + expect(existsSync(join(ctx.home, ".gemini"))).toBe(false); + expect(existsSync(record)).toBe(false); + }); + + test.each([ + ["neither file", false, false, "disconnected"], + ["modern only", true, false, "drifted"], + ["legacy only", false, true, "drifted"], + ["both files", true, true, "connected"], + ] as const)("status reports the gateway match for %s", (_label, modernMatches, legacyMatches, state) => { + mkdirSync(join(ctx.home, ".gemini", "config"), { recursive: true }); + mkdirSync(join(ctx.home, ".antigravity")); + const gateway = { enabled: true, ...target, wireProtocol: "openai" }; + writeFileSync(modernSettings(), JSON.stringify({ gateway: modernMatches ? gateway : { enabled: false } })); + writeFileSync(settings(), JSON.stringify({ gateway: legacyMatches ? gateway : { enabled: false } })); + expect(GATEWAY_CLIENTS.antigravity.status(ctx, target)).toMatchObject({ + state, files: [{ path: modernSettings(), exists: true }, { path: settings(), exists: true }], + }); + }); + + test.each([undefined, "modern-model"])("status prefers the modern default model when it is %s", modernModel => { + mkdirSync(join(ctx.home, ".gemini", "config"), { recursive: true }); + mkdirSync(join(ctx.home, ".antigravity")); + writeFileSync(modernSettings(), JSON.stringify({ models: { defaultModelId: modernModel } })); + writeFileSync(settings(), JSON.stringify({ models: { defaultModelId: "legacy-model" } })); + expect(GATEWAY_CLIENTS.antigravity.status(ctx, target)).toMatchObject({ + state: "disconnected", defaultModel: modernModel ?? "legacy-model", + }); }); test("a file with comments is refused and left untouched; disconnect without a record changes nothing", () => { diff --git a/tests/server/gateway-client-routes.test.ts b/tests/server/gateway-client-routes.test.ts index d4ca402cd3a..179ce2d8642 100644 --- a/tests/server/gateway-client-routes.test.ts +++ b/tests/server/gateway-client-routes.test.ts @@ -9,6 +9,7 @@ import type { OcxConfig } from "../../src/types"; let root: string; let gateway: GatewayClientContext; const settings = () => join(gateway.home, ".antigravity", "settings.json"); +const modernSettings = () => join(gateway.home, ".gemini", "config", "config.json"); beforeEach(() => { root = mkdtempSync(join(tmpdir(), "ocx-gw-routes-")); @@ -36,8 +37,9 @@ describe("gateway client management routes", () => { expect(initial.json.clients.map((c: { id: string; state: string }) => `${c.id}:${c.state}`)).toEqual(["antigravity:disconnected", "agy:disconnected"]); const connected = await call("POST", "/api/gateway-clients/antigravity/connect", { model: "gemini-3" }); - expect(connected).toMatchObject({ status: 200, json: { ok: true, id: "antigravity", action: "connect", changed: true, changedFiles: [settings()], status: { state: "connected" } } }); + expect(connected).toMatchObject({ status: 200, json: { ok: true, id: "antigravity", action: "connect", changed: true, changedFiles: [modernSettings(), settings()], status: { state: "connected" } } }); expect(JSON.parse(readFileSync(settings(), "utf8")).gateway.url).toBe("http://127.0.0.1:10100"); + expect(JSON.parse(readFileSync(modernSettings(), "utf8")).gateway.url).toBe("http://127.0.0.1:10100"); const viaAgy = await call("POST", "/api/gateway-clients/agy/connect", {}); expect(viaAgy.json).toMatchObject({ ok: true, id: "agy", status: { state: "connected" } }); @@ -49,6 +51,7 @@ describe("gateway client management routes", () => { const off = await call("POST", "/api/gateway-clients/antigravity/disconnect"); expect(off).toMatchObject({ status: 200, json: { ok: true, action: "disconnect", restore: "exact", status: { state: "disconnected" } } }); expect(existsSync(join(gateway.home, ".antigravity"))).toBe(false); + expect(existsSync(join(gateway.home, ".gemini"))).toBe(false); expect((await call("POST", "/api/gateway-clients/agy/disconnect")).json.restore).toBe("exact"); expect(existsSync(join(gateway.home, ".bashrc"))).toBe(false); }); @@ -102,7 +105,7 @@ describe("gateway client management routes", () => { truncateSync(profile, 4 * 1024 * 1024 + 1); const status = await call("GET", "/api/gateway-clients"); expect(status).toMatchObject({ status: 200, json: { clients: [ - { id: "antigravity", state: "drifted", files: [{ path, exists: true }] }, + { id: "antigravity", state: "drifted", files: [{ path: modernSettings(), exists: false }, { path, exists: true }] }, { id: "agy", state: "drifted", files: [{ path: profile, exists: true }] }, ] } }); expect(status.json.clients[0]).not.toHaveProperty("defaultModel"); From 2cc403756e99e59b979a47ac3363645bb48c683b Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:43:27 +0900 Subject: [PATCH 09/50] fix(windows): report Korean Task Scheduler access denial on fresh installs (#9278) * fix(windows): recognize Korean scheduler access denial on fresh installs * docs(es): describe the Korean scheduler diagnostic * test: stabilize quota dates and isolate Home route subprocess locks Carry the verified fixture corrections from lidge-jun/opencodex#9265 and #9279 into #9278. Keep production behavior and all existing assertions, pin Mistral observations within the fixture period, keep the Kimi reset in the future, and use a separate real lifecycle lock for each child fixture. (cherry picked from commit d97f06f1a76e0ce72fbced9933ac569b6e06d3e9) (cherry picked from commit 4499f63096d51a46160eeb21f504c7a6828320e7) (cherry picked from commit 30d9b1e9311082d69b105b2f19e31a6c777f816f) (cherry picked from commit a812fae6ca36a372e2925d25ea088a3ca252d7e6) * ci: run the broad scheduler test selection across Ubuntu shards The corrected changed-test lane exited 124 at its 25-minute wrapper limit (run 46821050194) without a new assertion failure. Use the repository's existing ci:full label to split the full suite across its five Ubuntu test jobs. The label selector requires a new pull-request synchronization event. This commit retains the previously validated source tree and existing CI policy. --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- docs-site/src/content/docs/es/reference/cli/lifecycle.md | 2 +- docs-site/src/content/docs/ko/reference/cli/lifecycle.md | 2 +- docs-site/src/content/docs/reference/cli/lifecycle.md | 1 + src/lib/windows-elevation.ts | 7 ++++++- structure/ops/service-and-sidecars.md | 2 +- tests/windows/windows-elevation.test.ts | 4 ++++ 6 files changed, 14 insertions(+), 4 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index a3d9536b3f0..4705aeb930e 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -639,7 +639,7 @@ el código 1 por sí solo no confirma una denegación de acceso; el texto de acc en la eliminación sigue clasificándose como tal. En Windows, la sintaxis es `ocx service install [--native|--scheduler] [--allow-uac]`. -En una instalación nueva con el Programador de tareas, la CLI intenta registrar la tarea con los permisos actuales. Si se deniega el acceso, ejecute `ocx service install --scheduler` desde PowerShell como administrador, o use `ocx service install --scheduler --allow-uac` para que Windows pueda pedir autorización. Sin la opción, ni el registro ni la limpieza tras un fallo abren un aviso de UAC. Si durante la reversión se intenta eliminar la tarea, la CLI indica si sigue registrada cuando puede verificar el resultado. Si la instalación falla, compruebe `ocx service status` antes de volver a intentarla. La opción solo se admite al ejecutar `service install` con el Programador de tareas. La aprobación y el éxito de la instalación siguen dependiendo de Windows. WinSW (`--native`) y `ocx service repair` conservan sus propios mecanismos de elevación. +En una instalación nueva con el Programador de tareas, la CLI intenta registrar la tarea con los permisos actuales. Si se deniega el acceso, ejecute `ocx service install --scheduler` desde PowerShell como administrador, o use `ocx service install --scheduler --allow-uac` para que Windows pueda pedir autorización. Si el Programador de tareas devuelve el mensaje en coreano `오류: 액세스가 거부되었습니다.`, la CLI muestra esas mismas instrucciones. Sin la opción, ni el registro ni la limpieza tras un fallo abren un aviso de UAC. Si durante la reversión se intenta eliminar la tarea, la CLI indica si sigue registrada cuando puede verificar el resultado. Si la instalación falla, compruebe `ocx service status` antes de volver a intentarla. La opción solo se admite al ejecutar `service install` con el Programador de tareas. La aprobación y el éxito de la instalación siguen dependiendo de Windows. WinSW (`--native`) y `ocx service repair` conservan sus propios mecanismos de elevación. Si la tarea de OpenCodex no existe en el Programador de tareas de Windows, se registra sin `/f`. Si reconoce una denegación de acceso, `ocx service install` la comunica sin abrir un aviso de UAC. Al elegir **Instalar** para el Programador de tareas en el panel, se ejecuta `ocx service install --allow-uac`, que permite a la CLI pedir elevación si Windows deniega el registro. diff --git a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md index e06228ebc3f..bc026ac04bf 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -397,7 +397,7 @@ Windows에서는 `ocx service status`가 Task Scheduler 등록 상태를 ID가 Windows 작업 스케줄러에 새로 설치할 때 CLI는 먼저 현재 권한으로 작업 등록을 시도합니다. 접근이 거부되면 관리자 권한으로 연 PowerShell에서 `ocx service install --scheduler`를 실행하거나, `ocx service install --scheduler --allow-uac`로 Windows가 권한 상승 승인을 요청하도록 허용하세요. 옵션을 생략하면 등록할 때와 설치 실패 후 작업을 정리할 때 모두 UAC 창이 뜨지 않습니다. 롤백 중에 작업 삭제를 시도한 경우, CLI는 결과를 확인할 수 있으면 작업이 여전히 등록되어 있는지 알려줍니다. 설치가 실패하면 재시도 전에 `ocx service status`로 상태를 확인하세요. 이 옵션은 작업 스케줄러를 사용해 `service install`을 명시적으로 실행할 때만 적용됩니다. 권한 상승에는 승인이 필요하며 설치는 여전히 실패할 수 있습니다. -Windows 작업 스케줄러에 OpenCodex 작업이 없으면 `/f` 없이 등록합니다. `ocx service install`은 접근 거부를 확인하면 UAC 창을 띄우지 않고 오류를 알립니다. 대시보드에서 작업 스케줄러 **설치**를 선택하면 `ocx service install --allow-uac`가 실행되어, Windows가 등록을 거부했을 때 CLI가 권한 상승을 요청할 수 있습니다. +Windows 작업 스케줄러에 OpenCodex 작업이 없으면 `/f` 없이 등록합니다. 작업 스케줄러가 `오류: 액세스가 거부되었습니다.`를 반환하면 CLI는 위의 두 가지 설치 방법을 안내합니다. `ocx service install`은 접근 거부를 확인하면 UAC 창을 띄우지 않고 오류를 알립니다. 대시보드에서 작업 스케줄러 **설치**를 선택하면 `ocx service install --allow-uac`가 실행되어, Windows가 등록을 거부했을 때 CLI가 권한 상승을 요청할 수 있습니다. OpenCodex가 `/f`로 자신의 기존 작업을 교체할 때는 실행 중인 프로세스에 관리자 권한이 없음을 확인한 경우 종료 코드 1도 접근 거부로 해석합니다. 대시보드가 별도로 권한 상승을 요청해 재시도하는 동작은 **설치**에만 적용됩니다. **복구**는 복구 절차 안에서 필요한 권한 상승을 요청합니다. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index bbd9bf76a97..b997ac9cee6 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -922,6 +922,7 @@ On Windows, the install syntax is `ocx service install [--native|--scheduler] [- For a fresh Task Scheduler install, the CLI first tries to register the task with the current permissions. If Windows denies access, run `ocx service install --scheduler` from an administrator PowerShell, or run `ocx service install --scheduler --allow-uac` to allow Windows to ask for elevation. +The CLI also recognizes the Korean Task Scheduler message `오류: 액세스가 거부되었습니다.` and displays the same instructions. The prompt still requires approval and installation can still fail. Without the flag, the CLI opens no UAC prompt for registration or for cleanup if the install fails. When rollback attempts to delete the task, the CLI reports whether it is still registered if it can verify the result. After any failed install, diff --git a/src/lib/windows-elevation.ts b/src/lib/windows-elevation.ts index d57d271cb68..11bbc55de27 100644 --- a/src/lib/windows-elevation.ts +++ b/src/lib/windows-elevation.ts @@ -3,6 +3,7 @@ import { existsSync } from "node:fs"; import { isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path"; import { dlopen, ptr, type Pointer } from "bun:ffi"; import { isTestHomeGuardArmed } from "./test-home-guard"; +import { decodeWindowsTextBytes } from "./windows-text"; type ElevationSpawn = ( command: string, @@ -456,7 +457,11 @@ export function toFreshWindowsSchedulerCreateError(error: unknown, args: string[ // A non-forced create can exit 1 on a name collision. Require a denial from // the child rather than its command line (the XML path can contain arbitrary text). const child = error as Error & { stderr?: string | Buffer; stdout?: string | Buffer }; - if (schedulerExitStatus(child) === 5 + const status = schedulerExitStatus(child); + // Korean schtasks can write CP949 even in an English session. Match only its complete denial. + const koreanDenial = status === 1 && Buffer.isBuffer(child.stderr) && child.stderr.length <= 128 + && decodeWindowsTextBytes(child.stderr, { locale: "ko-KR" }) === "오류: 액세스가 거부되었습니다."; + if (status === 5 || koreanDenial || [child.stderr, child.stdout].some(output => output && windowsAccessDeniedText(String(output)))) { return new WindowsSchtasksError("create", "access-denied", "Windows denied access to create the Task Scheduler task.", null); } diff --git a/structure/ops/service-and-sidecars.md b/structure/ops/service-and-sidecars.md index 0a07cc58fb6..3a476a84690 100644 --- a/structure/ops/service-and-sidecars.md +++ b/structure/ops/service-and-sidecars.md @@ -22,7 +22,7 @@ any platform status probe. macOS and Linux check the registration file. Windows Only proven absence enters registration. If a query fails, the bare command returns status guidance so it cannot recreate an existing task. Explicit `ocx service install` requests registration. After a generic Scheduler `/run` failure, `ocx service start` uses the same probe. Confirmed absence returns exit 1 with the install command. Present or unreadable registrations and explicit access denials retain the original failure. -Fresh Windows Task Scheduler installs try registration with the current token first. Only explicit `ocx service install --allow-uac` or the dashboard's Windows service install action permits a UAC prompt. A CLI create denial without consent names the opt-in command and the alternative of using an elevated terminal. Rollback uses the same consent and verifies ownership before deleting the task. An unconfirmed cleanup reports the remaining or unknown task state. WinSW installation and scheduler repair have separate elevation paths. +Fresh Windows Task Scheduler installs try registration with the current token first. The fresh create recognizes the exact Korean access-denied diagnostic on stderr even when Task Scheduler writes CP949 in an English session. Exit code 1 alone can also indicate a name collision. Only explicit `ocx service install --allow-uac` or the dashboard's Windows service install action permits a UAC prompt. A CLI create denial without consent names the opt-in command and the alternative of using an elevated terminal. Rollback uses the same consent and verifies ownership before deleting the task. An unconfirmed cleanup reports the remaining or unknown task state. WinSW installation and scheduler repair have separate elevation paths. `src/lib/windows-elevation.ts` formats scheduler exec failures without echoing child stderr; generic failures retain the numeric exit status. Delete, run and end access denials name the exact command to run from an elevated terminal. `src/service/windows-scheduler.ts` also classifies an owned-task delete exiting 1 as denied when a fresh probe proves the task survived; absent, unreadable and failed probes do not establish that classification. `src/service/windows-ops.ts` retains service assets until deletion is proven complete. `tests/windows/windows-scheduler-errors.test.ts` exercises these paths with injected runners. diff --git a/tests/windows/windows-elevation.test.ts b/tests/windows/windows-elevation.test.ts index 497b7a08322..92b281b1e6f 100644 --- a/tests/windows/windows-elevation.test.ts +++ b/tests/windows/windows-elevation.test.ts @@ -139,6 +139,8 @@ describe("windows elevation helpers", () => { const args = buildWindowsSchtasksCreateArgsForXml("staged task.xml", false); for (const result of [ { status: 1, stderr: Buffer.from("ERROR: Access is denied.") }, + // Captured from Korean schtasks in a Windows session reporting en-US. + { status: 1, stderr: Buffer.from("bfc0b7f93a20bed7bcbcbdbab0a120b0c5baceb5c7befabdc0b4cfb4d92e0d0d0a", "hex") }, { status: 1, stdout: "FEHLER: Zugriff verweigert" }, { status: 5, stderr: "" }, ]) { @@ -170,6 +172,8 @@ describe("windows elevation helpers", () => { for (const failure of [ Object.assign(new Error(`Command failed: schtasks ${args.join(" ")}`), { status: 1, stderr: "" }), Object.assign(new Error("Command failed"), { status: 1, stderr: "The specified task already exists." }), + Object.assign(new Error("Command failed"), { status: 1, stderr: Buffer.from("오류: 액세스가 거부되었습니다. (task.xml)") }), + Object.assign(new Error("Command failed"), { status: 2, stderr: Buffer.from("오류: 액세스가 거부되었습니다.") }), new Error("Access is denied."), "Access is denied.", ]) { From f56ea229cf049f8be803d63b830c880d2c1a7991 Mon Sep 17 00:00:00 2001 From: LilMGenius Date: Thu, 3 Dec 2026 23:44:49 +0900 Subject: [PATCH 10/50] fix(responses): keep a replayed web_search_call id when store is false (#9303) * fix(responses): keep a replayed web_search_call id when store is false With store: false the passthrough strips every input item id. A Claude search that a Responses gateway (CLIProxyAPI) returned as a web_search_call lost its ws_srvtoolu_ id that way, and the gateway rebuilds Claude's server_tool_use and web_search_tool_result pair only from that id, so it dropped the replayed cell and the next turn answered that it had never searched. The cell carries its whole search, so its id names no stored item and now stays on the wire. Fixes #9300 * test(responses): pin the id of a search cell replayed without results Codex CLI stores a web_search_call without its results array, so the cell it replays carries only the id, status and action. The id still lets the gateway rebuild the search call, which tells the model it searched and for what. Without this case a fix that kept the id only when results were present passed the suite. * docs(responses): state that a web_search_call keeps its id under store false The structure transport docs and the preserveResponsesInputItemIds row said every input id is stripped when store is false. * docs(responses): say what keeping a search cell's id does not restore CodeRabbit on #9303: the comment and structure/transports/responses.md said the cell carries its whole search, while a cell replayed without results keeps its id and still lacks them. Describe the id as the search's identity that a gateway rebuilds the call from, with whatever results the cell still carries. * docs(responses): state when store false keeps input ids CodeRabbit on #9303: the structure doc said store false strips every input id except a web_search_call's, while preserveResponsesInputItemIds keeps them all and the shape check that runs first still removes a web_search_call id without the ws_ prefix. State both conditions. * docs(responses): name the xAI and bridged-search cases of the id rule CodeRabbit on #9303: the store false paragraph left out that an xAI Responses destination keeps or repairs custom_tool_call ids, and that a cell the webSearchBridge recorded is replaced by the call and output the bridge produced before ids are sanitized, so it does not reach the destination without results. * docs(responses): state when the bridge restores a replayed search cell CodeRabbit on #9303: a recorded search alone does not restore the cell; the replay scope must match and the recorded call_id must not already be in the input, as restoreBridgedWebSearchCalls checks. --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 2 +- .../openai-responses/request-strips.ts | 9 ++++- structure/transports/responses-wire-shapes.md | 2 +- structure/transports/responses.md | 2 +- ...ponses-chatgpt-web-replay-metadata.test.ts | 37 +++++++++++++++++++ 6 files changed, 49 insertions(+), 5 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index b77f5f37067..5b3f5af8113 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -243,7 +243,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | `chatServiceTier?` | `boolean` | Chat-wire en todo el proveedor opt-in para el reenvío de llamadas `service_tier` valores. En una ruta clasificada gobierna valores extranjeros como `flex`, no canónica propiedad de proxy Fast después de la validación de la capacidad; en una ruta no clasificada gobierna cada valor de llamada porque no se ha validado ninguna capacidad Fast. La capacidad del modelo exacto no autoriza el reenvío extranjero. Responses rutas conservan su comportamiento de reenvío de llamadas basado en la capacidad. | | `promptCacheKey?` | `boolean` | Opción de todo el proveedor `openai-chat` para reenviar `prompt_cache_key`. El adaptador reenvía la clave recibida sin inventarla, aunque no siempre procede del cliente: la conversión de Claude Messages obtiene una a partir de `metadata.user_id` o de un grupo de modelo, sistema y herramientas cuando no hay metadatos. Está desactivada por defecto salvo que lo indique el preajuste. Mistral la habilita según su [contrato de caché de instrucciones](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching); un `false` explícito la desactiva. Habilítala solo si el proveedor documenta compatibilidad, porque una pasarela estricta puede rechazar ese campo con HTTP 400. | | `preserveResponsesReasoningContent?` | `boolean` | Por defecto para los proveedores personalizados. En **Proveedores → Configuración**, habilite **Replay razonamiento de texto plano** para un punto final personalizado Responses solo si acepta este historial. Esto envía un razonamiento previo de texto sin formato a ese punto final y puede aumentar el uso de tokens. Mantenga el contenido de razonamiento de texto plano en los elementos de razonamiento Responses reproducidos en lugar de borrarlo, incluida la entrada compacta nativa personalizada v1 (blanking es la regla del backend ChatGPT). Habilitar para aguas arriba cuyo contrato acepta la repetición de razonamiento, como DeepSeek o un Kimi autoalojado en vLLM. Los sobres `ocxr1` con proxy siempre se eliminan. Un proveedor `openai-responses` configurado manualmente sin él registra una advertencia por host la primera vez que se elimina el razonamiento de texto sin formato. `preserveReasoningContentModels` no afecta a este cable. | -| `preserveResponsesInputItemIds?` | `boolean` | Por defecto. Preservar `input[].id` válido cuando `store: false` para relés de lanzador de confianza explícita que requieren identidad de turno. Responses proveedores ordinarios siguen eliminando las identificaciones; xAI La reparación del ID de llamada personalizada permanece activa. | +| `preserveResponsesInputItemIds?` | `boolean` | Por defecto. Preservar `input[].id` válido cuando `store: false` para relés de lanzador de confianza explícita que requieren identidad de turno. Responses proveedores ordinarios siguen eliminando las identificaciones, salvo la de un `web_search_call` alojado, que una pasarela de búsqueda necesita para emparejar la llamada con sus resultados; xAI La reparación del ID de llamada personalizada permanece activa. | | `preserveResponsesMessageMetadata?` | `boolean` | Por defecto. Preservar `internal_chat_message_metadata_passthrough` privado en elementos de entrada para relés de lanzador de confianza explícita, incluidas las solicitudes compactas nativas personalizadas v1. Esto reenvía metadatos privados de turno/sesión a ese destino; no habilite las puertas de enlace ordinarias. | | `dropResponsesReasoningItems?` | `boolean` | Elimine por completo los elementos Responses `reasoning` reproducidos de la entrada de continuación, incluidas las solicitudes compactas nativas v1 personalizadas, en lugar de reenviarlos con contenido en blanco. Esto es con pérdida: resúmenes, identificadores de ítems y `encrypted_content` van con ellos, por lo que no queda ningún ítem de razonamiento del turno anterior en la entrada reenviada. No elimina `previous_response_id`, por lo que un curso arriba que mantiene su propio estado de giro aún puede alcanzarlo. Habilitar solo para un upstream que rechaza la repetición de razonamiento directamente: el preajuste integrado Volcengine Ark Coding Plan lo establece porque las continuaciones de la herramienta validadas respondieron `400 InvalidParameter` de lo contrario. Establezca a `false` en ese proveedor para reenviar los elementos de razonamiento nuevamente. | | `disabled?` | `boolean` | Mantenga el proveedor en el disco, pero excluya el enrutamiento y los listados de modelos/catálogos. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index a60ad83580b..920f49cbfdd 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -360,7 +360,7 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `chatServiceTier?` | `boolean` | Provider-wide Chat-wire opt-in for forwarding caller `service_tier` values. On a classified route it governs foreign values such as `flex`, not proxy-owned canonical Fast after capability validation; on an unclassified route it governs every caller value because no Fast capability has been validated. Exact model capability does not authorize foreign forwarding. Responses routes retain their capability-based caller forwarding behavior. | | `promptCacheKey?` | `boolean` | Provider-wide `openai-chat` opt-in for forwarding a `prompt_cache_key`. The adapter forwards the key it is given and never invents one, but the key is not always the caller's: Claude Messages translation derives one from `metadata.user_id`, or from a model/system/tools cohort when no metadata is sent. Default off unless declared by the provider preset; Mistral enables it per its [prompt-caching contract](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching), and explicit `false` disables it. Enable only when the upstream documents support, because strict gateways may reject the unknown field with HTTP 400. | | `preserveResponsesReasoningContent?` | `boolean` | Default off for custom providers. In **Providers → Settings**, enable **Replay plaintext reasoning** for a custom Responses endpoint only if it accepts this history. This sends prior plaintext reasoning to that endpoint and may increase token use. Keep plaintext reasoning content on replayed Responses reasoning items instead of blanking it, including custom native v1 compact input (blanking is the ChatGPT backend's rule). Enable for upstreams whose contract accepts reasoning replay, such as DeepSeek or a self-hosted Kimi on vLLM. Proxy-minted `ocxr1` envelopes are always stripped. A hand-configured `openai-responses` provider without it logs one warning per host the first time plaintext reasoning is dropped. `preserveReasoningContentModels` does not affect this wire. | -| `preserveResponsesInputItemIds?` | `boolean` | Default off. Preserve valid `input[].id` when `store: false` for explicitly trusted launcher relays that require turn identity. Ordinary Responses providers keep stripping IDs; xAI custom-call ID repair remains active. | +| `preserveResponsesInputItemIds?` | `boolean` | Default off. Preserve valid `input[].id` when `store: false` for explicitly trusted launcher relays that require turn identity. Ordinary Responses providers keep stripping IDs, except a hosted `web_search_call`'s, which a search gateway needs to pair the call with its results; xAI custom-call ID repair remains active. | | `preserveResponsesMessageMetadata?` | `boolean` | Default off. Preserve private `internal_chat_message_metadata_passthrough` on input items for explicitly trusted launcher relays, including custom native v1 compact requests. This forwards private turn/session metadata to that destination; do not enable for ordinary gateways. | | `dropResponsesReasoningItems?` | `boolean` | Remove replayed Responses `reasoning` items from continuation input entirely, including custom native v1 compact requests, instead of forwarding them with blanked content. This is lossy: summaries, item ids, and `encrypted_content` go with them, so no reasoning item from the previous turn remains in the forwarded input. It does not remove `previous_response_id`, so an upstream holding its own turn state may still reach it. Enable only for an upstream that rejects reasoning replay outright — the built-in Volcengine Ark Coding Plan preset sets it because validated tool continuations answered `400 InvalidParameter` otherwise. Set it to `false` on that provider to forward reasoning items again. | | `disabled?` | `boolean` | Keep the provider on disk but exclude it from routing and model/catalog listings. | diff --git a/src/adapters/openai-responses/request-strips.ts b/src/adapters/openai-responses/request-strips.ts index 910fbdca822..ffcf05acee8 100644 --- a/src/adapters/openai-responses/request-strips.ts +++ b/src/adapters/openai-responses/request-strips.ts @@ -362,6 +362,13 @@ export function stripRejectedSamplingParams( * — `call_id` pairing is unaffected. Also repairs missing or broken xAI custom_tool_call IDs * when `requireCustomCallIds` is true, regardless of `preserveIds`. * Matches codex-rs behavior (core/src/client.rs:918-925). + * + * A hosted `web_search_call` keeps its ID. The ID is the search's identity, not a reference to + * a stored item: a gateway that bridges a provider's server-side search rebuilds the call, with + * whatever results the replayed cell still carries, from it. CLIProxyAPI rebuilds Claude's + * `server_tool_use` and `web_search_tool_result` from that ID and drops a cell without one, so + * the next turn lost the search (#9300). Keeping the ID restores nothing a client dropped: a + * cell replayed without `results` still reaches the gateway without them. */ export function stripItemIdsWhenUnstored( body: unknown, @@ -397,7 +404,7 @@ export function stripItemIdsWhenUnstored( return item; } } - if (preserveIds || body.store !== false || !("id" in item)) return item; + if (preserveIds || body.store !== false || !("id" in item) || item.type === "web_search_call") return item; changed = true; const next = { ...item }; delete next.id; diff --git a/structure/transports/responses-wire-shapes.md b/structure/transports/responses-wire-shapes.md index 3dc3de3c926..edd7f4cb5f3 100644 --- a/structure/transports/responses-wire-shapes.md +++ b/structure/transports/responses-wire-shapes.md @@ -60,7 +60,7 @@ string on this wire instead of the numeric `thinking_budget` the Chat wire appli stays unpinned. `tests/providers/alibaba-token-plan-wire-defaults.test.ts` covers the pins and the replay flag. -Trusted custom Responses relays may opt into `preserveResponsesInputItemIds` and `preserveResponsesMessageMetadata` for launcher replay (#6220). Ordinary destinations still strip IDs when `store: false` and private `internal_chat_message_metadata_passthrough`; xAI custom-call ID repair remains active. +Trusted custom Responses relays may opt into `preserveResponsesInputItemIds` and `preserveResponsesMessageMetadata` for launcher replay (#6220). Ordinary destinations still strip IDs when `store: false`, except a hosted `web_search_call`'s (#9300), and private `internal_chat_message_metadata_passthrough`; xAI custom-call ID repair remains active. Exact upstream IDs in a provider’s `arkKimiResponsesModels` opt in to the Ark Kimi Responses projection. Drop only `output.encrypted_content` from includes. Drop only the cipher on an unreferenced empty-summary reasoning item immediately before a user message when preceded by a user or matching function call/result pair. A developer message is also an eligible following boundary, but only after a matching function call/result pair; a preceding user alone does not qualify. Preserve meaningful or unknown fields, and leave forward auth and other models untouched. Google metadata follows the [destination-scoped replay projection](../providers/google.md#google-tool-call-thought-signature-replay). xAI keeps `openai-chat` provider-wide; Grok 4.5/4.6/4.7 subscription Responses default to native `openai-responses`, retaining namespace, hosted-search and reasoning-replay normalization. The reserved `xai` OAuth transport is name-pinned diff --git a/structure/transports/responses.md b/structure/transports/responses.md index 2ce5b56250f..03330d690c8 100644 --- a/structure/transports/responses.md +++ b/structure/transports/responses.md @@ -334,7 +334,7 @@ native blob is relayed only when there is no known serving-identity mismatch and The same serving-identity mismatch signal therefore strips reasoning `encrypted_content` unless the narrowly scoped [native reasoning retention](native-reasoning-retention.md#runtime-boundary) policy permits it; native compaction blobs still degrade through the existing opaque-note path independently of that policy. Claude-native reasoning batches rejected blob tags into one scrub pass: only the matching durable endpoint and generation-bearing credential retain raw and parsed carriers. Without recorded thread identity, the destination gate remains. Cold opaque preflight and identified rejection recovery follow the [cold-history contract](native-reasoning-retention.md#cold-opaque-state-rejection-recovery). Noncanonical forward providers receive no caller credentials and may point at any backend. On any other routed destination the blob also degrades to the same opaque note the bridged parser uses, because forwarding it there fails the turn and the item outlives the failure in the client transcript, repeating on every later turn including the compaction -turn the proxy itself drives. With `store: false`, request sanitization strips ids from every input item, including compact-wire items, matching codex-rs (`core/src/client.rs:918-925`). Compact-wire items remain exempt from response-side field backfill. +turn the proxy itself drives. With `store: false`, request sanitization strips ids from every input item, including compact-wire items, matching codex-rs (`core/src/client.rs:918-925`), unless the provider sets `preserveResponsesInputItemIds: true`, which keeps them. Two kinds of item keep an id either way. A hosted `web_search_call` keeps its id because the id is the search's identity: a gateway that bridges a provider's server-side search rebuilds the call from that id, with whatever results the replayed cell still carries. CLIProxyAPI rebuilds Claude's `server_tool_use` and `web_search_tool_result` from it and drops a cell without one (#9300, `tests/responses/responses-chatgpt-web-replay-metadata.test.ts`). On an xAI Responses destination, with or without `store: false`, a `custom_tool_call` keeps an id that starts with `ctc_`, and one with another id or none gets a `ctc_` id hashed from its `call_id`, `name` and `input` when those are strings. The shape check that runs first (`stripInvalidItemIds`) still removes any item id with the wrong prefix for its type, a `web_search_call` id without `ws_` included. A cell replayed without `results` keeps its id and still lacks its results, unless the provider's `webSearchBridge` recorded that search under the same caller, conversation and serving identity and the input does not already hold the recorded `call_id`: `restoreBridgedWebSearchCalls` then replaces the cell with the destination's own `function_call` and the `function_call_output` the bridge produced for it, before the ids are sanitized. Compact-wire items remain exempt from response-side field backfill. For replayed `encrypted_content` slots whose minting provenance is unavailable after a restart or full-history resend, the plaintext-compatibility boundary requires canonical key-independent Fernet diff --git a/tests/responses/responses-chatgpt-web-replay-metadata.test.ts b/tests/responses/responses-chatgpt-web-replay-metadata.test.ts index e41bc3a0c40..8ee241405b6 100644 --- a/tests/responses/responses-chatgpt-web-replay-metadata.test.ts +++ b/tests/responses/responses-chatgpt-web-replay-metadata.test.ts @@ -63,6 +63,43 @@ test("ordinary noncanonical Responses destinations strip input IDs when store: f expect(firstItem.role).toBe("user"); }); +test("ordinary noncanonical Responses destinations keep a replayed web_search_call id when store: false (#9300)", () => { + // A Claude search as a Responses gateway (CLIProxyAPI) returns it. The gateway rebuilds the + // server_tool_use and web_search_tool_result pair from this id and drops a cell without one. + const cell = { + id: "ws_srvtoolu_01B1ZVKQAa49ANVWr6Ew94zM", + type: "web_search_call", + status: "completed", + action: { type: "search", query: "RFC 2606 reserved example domain names", queries: ["RFC 2606 reserved example domain names"] }, + results: [{ + type: "web_search_result", + title: "RFC 2606 - Reserved Top Level DNS Names", + url: "https://datatracker.ietf.org/doc/rfc2606/", + encrypted_content: "opaque-provider-ciphertext", + page_age: "1070 days ago", + }], + }; + const { results: _results, ...cellAsCodexStoresIt } = { ...cell, id: "ws_srvtoolu_01Hnten9k4YHeTmniygHFgMe" }; + const sent = sentBody(ORDINARY_NONCANONICAL_KEY, { + model: "claude-opus-5-5", + store: false, + tools: [{ type: "web_search" }], + input: [ + { id: "msg_user_1", type: "message", role: "user", content: [{ type: "input_text", text: "Search once." }] }, + cell, + { id: "msg_assistant_1", type: "message", role: "assistant", content: [{ type: "output_text", text: "DONE" }] }, + { id: "fc_not_a_search_id", type: "web_search_call", status: "completed", action: { type: "search", query: "q", queries: ["q"] } }, + cellAsCodexStoresIt, + ], + }); + const items = sent.input as Record[]; + expect(items[1]).toEqual(cell); + expect(items[0]).not.toHaveProperty("id"); + expect(items[2]).not.toHaveProperty("id"); + expect(items[3]).not.toHaveProperty("id"); + expect(items[4]).toEqual(cellAsCodexStoresIt); +}); + test("opted-in provider preserves input IDs when store: false for launcher session replay (#6220)", () => { const sent = sentBody(CHATGPT_WEB_RELAY_KEY, sampleCodexClientBody()); expect(sent.input).toBeArray(); From efeef7b5a009a8e4802af318b3a0d15d720a2d6e Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 3 Dec 2026 23:58:47 +0900 Subject: [PATCH 11/50] fix(responses): lower shell_call_output media parts to assistant text (#9312) --- src/responses/parser.ts | 29 ++++++++++++++++++++++-- tests/responses/responses-parser.test.ts | 24 ++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/responses/parser.ts b/src/responses/parser.ts index 4089d2f03a9..f2bf3c7b3d1 100644 --- a/src/responses/parser.ts +++ b/src/responses/parser.ts @@ -254,6 +254,32 @@ function shellCallOutputContent(output: string | unknown[] | undefined): string return structured ? chunks.join("\n") : outputToToolResultContent(output); } +/** + * Lower shell replay output to assistant-valid text parts when folding into an open tool + * batch; assistant messages accept text, thinking, and tool calls, never media parts. + */ +function assistantReplayTextParts(content: string | OcxContentPart[]): OcxTextContent[] { + if (typeof content === "string") return content.length > 0 ? [{ type: "text", text: content }] : []; + return content.map((part): OcxTextContent => { + switch (part.type) { + case "text": + return part; + case "audio": + return { type: "text", text: part.text }; + case "image": + return { type: "text", text: "[image]" }; + case "video": + return { type: "text", text: "[video]" }; + case "document": + return { type: "text", text: part.filename ? `[document: ${part.filename}]` : "[document]" }; + default: { + const exhaustive: never = part; + return exhaustive; + } + } + }); +} + type ShellReplay = "function" | "custom" | "text"; function namedShellKind(tool: unknown): Exclude | undefined { @@ -763,8 +789,7 @@ export function parseRequest( pendingReasoning.length = 0; const content = shellCallOutputContent((item as { output?: string | unknown[] }).output); if (content.length > 0 && hasOpenToolBatch(messages)) { - if (typeof content === "string") assistantHolderWithReasoning().content.push({ type: "text", text: content }); - else assistantHolderWithReasoning().content.push(...content); + assistantHolderWithReasoning().content.push(...assistantReplayTextParts(content)); } else if (content.length > 0) { messages.push({ role: "user", content, timestamp: now }); } diff --git a/tests/responses/responses-parser.test.ts b/tests/responses/responses-parser.test.ts index 4edf1791a42..62b9e2e87c9 100644 --- a/tests/responses/responses-parser.test.ts +++ b/tests/responses/responses-parser.test.ts @@ -1017,6 +1017,30 @@ describe("codex-rs compat surface (260707)", () => { expect(parsed.context.messages[1]?.content).toBe("file"); }); + test("hosted shell output with mixed text and media lowers to assistant text parts inside an open tool batch", () => { + const parsed = parseRequest({ ...base, input: [ + { type: "function_call", call_id: "c1", name: "read", arguments: "{}" }, + { type: "shell_call", call_id: "s1", action: { commands: ["inspect"] } }, + { type: "shell_call_output", call_id: "s1", output: [ + { type: "input_text", text: "frame:" }, + { type: "input_image", image_url: "data:image/png;base64,AAAA" }, + { type: "input_audio", audio_url: "data:audio/wav;base64,YWJj" }, + ] }, + { type: "function_call_output", call_id: "c1", output: "file" }, + ]}); + expect(parsed.context.messages.map(message => message.role)).toEqual(["assistant", "toolResult"]); + const assistant = parsed.context.messages[0]; + expect(assistant?.content).toEqual([ + expect.objectContaining({ type: "toolCall", id: "c1", name: "read" }), + { type: "text", text: "inspect" }, + { type: "text", text: "frame:" }, + { type: "text", text: "[image]" }, + { type: "text", text: "[audio: wav]" }, + ]); + expect(parsed.context.messages[1]?.toolCallId).toBe("c1"); + expect(parsed.context.messages[1]?.content).toBe("file"); + }); + test("web_search_call replay stays out of assistant-visible history text", () => { const parsed = parseRequest({ ...base, input: [ { type: "web_search_call", status: "completed", action: { type: "search", query: "bun 1.3 release" } }, From b2fdc46b4fa88d08dedbf80b7e03b90c5923aac2 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:59:31 +0900 Subject: [PATCH 12/50] test(storage): finish server teardown before switching fixture homes (#9294) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- ...api-storage-policy-already-running.test.ts | 82 ++++----- tests/storage/api-storage-policy.test.ts | 142 +++++++-------- tests/storage/api-storage.test.ts | 162 +++++++++--------- 3 files changed, 201 insertions(+), 185 deletions(-) diff --git a/tests/storage/api-storage-policy-already-running.test.ts b/tests/storage/api-storage-policy-already-running.test.ts index 815a7e92aea..a46f590e529 100644 --- a/tests/storage/api-storage-policy-already-running.test.ts +++ b/tests/storage/api-storage-policy-already-running.test.ts @@ -13,54 +13,58 @@ import { uninstallPolicyApiHarness, waitForJobIdle, type PolicyApiHarness, - resetStorageCleanupPolicyJobForTestsAsync, } from "../helpers/storage-policy-api"; +import { SERVER_BUDGET_MS } from "../helpers/test-budget"; -let harness: PolicyApiHarness; +let harnessSetup: Promise; +let activeServer: ReturnType | undefined; -beforeEach(async () => { - harness = await installPolicyApiHarness("ocx-api-storage-policy-busy"); -}); +beforeEach(() => { + harnessSetup = installPolicyApiHarness("ocx-api-storage-policy-busy"); + return harnessSetup; +}, SERVER_BUDGET_MS); afterEach(async () => { - await uninstallPolicyApiHarness(harness); -}); + if (activeServer) { + await stopPolicyServer(activeServer); + activeServer = undefined; + } + // Setup rolls back on rejection. If it outlives its hook, join it before restoring the homes. + await harnessSetup.then(uninstallPolicyApiHarness, () => {}); +}, SERVER_BUDGET_MS); test("POST run rejects when a job is already running", async () => { setStorageCleanupPolicyJobTestHooks({ blockMs: 800 }); + const harness = await harnessSetup; seedArchived(harness.isolatedCodexHome.path); - const server = startServer(0); - try { - await fetch(new URL("/api/storage/cleanup-policy", server.url), { - method: "PUT", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ - enabled: true, - trigger: { archivedBytesOver: 50 }, - target: { removeOldestPercent: 50 }, - schedule: "manual", - mode: "quarantine", - }), - }); + activeServer = startServer(0); + const serverUrl = activeServer.url; + await fetch(new URL("/api/storage/cleanup-policy", serverUrl), { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + enabled: true, + trigger: { archivedBytesOver: 50 }, + target: { removeOldestPercent: 50 }, + schedule: "manual", + mode: "quarantine", + }), + }); - const first = await fetch(new URL("/api/storage/cleanup-policy/run", server.url), { - method: "POST", - }); - expect(first.status).toBe(200); - const firstBody = await first.json(); - expect(firstBody.started).toBe(true); + const first = await fetch(new URL("/api/storage/cleanup-policy/run", serverUrl), { + method: "POST", + }); + expect(first.status).toBe(200); + const firstBody = await first.json(); + expect(firstBody.started).toBe(true); - const second = await fetch(new URL("/api/storage/cleanup-policy/run", server.url), { - method: "POST", - }); - expect(second.status).toBe(409); - const secondBody = await second.json(); - expect(secondBody.error).toBe("already_running"); - expect(secondBody.started).toBe(false); + const second = await fetch(new URL("/api/storage/cleanup-policy/run", serverUrl), { + method: "POST", + }); + expect(second.status).toBe(409); + const secondBody = await second.json(); + expect(secondBody.error).toBe("already_running"); + expect(secondBody.started).toBe(false); - await waitForJobIdle(server.url, firstBody.job.startedAt); - } finally { - await stopPolicyServer(server); - await resetStorageCleanupPolicyJobForTestsAsync(); - } -}, { timeout: 30_000 }); + await waitForJobIdle(serverUrl, firstBody.job.startedAt); +}, SERVER_BUDGET_MS); diff --git a/tests/storage/api-storage-policy.test.ts b/tests/storage/api-storage-policy.test.ts index f28f12e7457..8c28fd0e448 100644 --- a/tests/storage/api-storage-policy.test.ts +++ b/tests/storage/api-storage-policy.test.ts @@ -10,85 +10,89 @@ import { stopPolicyServer, uninstallPolicyApiHarness, type PolicyApiHarness, - resetStorageCleanupPolicyJobForTestsAsync, } from "../helpers/storage-policy-api"; +import { SERVER_BUDGET_MS } from "../helpers/test-budget"; -let harness: PolicyApiHarness; +let harnessSetup: Promise; +let activeServer: ReturnType | undefined; +let fixtureCleanup: Promise | undefined; -beforeEach(async () => { - harness = await installPolicyApiHarness("ocx-api-storage-policy"); -}); +beforeEach(() => { + if (fixtureCleanup) throw new Error("The previous storage policy fixture is still stopping."); + harnessSetup = installPolicyApiHarness("ocx-api-storage-policy"); + return harnessSetup; +}, SERVER_BUDGET_MS); -afterEach(async () => { - await uninstallPolicyApiHarness(harness); -}); +function startPolicyEndpoint(): URL { + activeServer = startServer(0); + return new URL("/api/storage/cleanup-policy", activeServer.url); +} + +async function releaseFixture(): Promise { + if (activeServer) { + await stopPolicyServer(activeServer); + activeServer = undefined; + } + // A rejected setup restores its own homes. + await harnessSetup.then(uninstallPolicyApiHarness, () => {}); +} + +afterEach(() => { + fixtureCleanup ??= releaseFixture().then(() => { fixtureCleanup = undefined; }); + return fixtureCleanup; +}, SERVER_BUDGET_MS); describe("storage cleanup policy API", () => { test("GET returns default-off policy without enabling", async () => { - const server = startServer(0); - try { - const res = await fetch(new URL("/api/storage/cleanup-policy", server.url)); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.enabled).toBe(false); - expect(body.mode).toBe("quarantine"); - expect(body.schedule).toBe("manual"); - expect(body.trigger.archivedBytesOver).toBeGreaterThan(0); - expect(body.job.status).toBe("idle"); - } finally { - await stopPolicyServer(server); - await resetStorageCleanupPolicyJobForTestsAsync(); - } - }); + const endpoint = startPolicyEndpoint(); + const res = await fetch(endpoint); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.enabled).toBe(false); + expect(body.mode).toBe("quarantine"); + expect(body.schedule).toBe("manual"); + expect(body.trigger.archivedBytesOver).toBeGreaterThan(0); + expect(body.job.status).toBe("idle"); + }, SERVER_BUDGET_MS); test("PUT persists policy and never enables when enabled omitted", async () => { - const server = startServer(0); - try { - const res = await fetch(new URL("/api/storage/cleanup-policy", server.url), { - method: "PUT", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ - trigger: { archivedBytesOver: 1024 }, - target: { removeOldestPercent: 40 }, - schedule: "daily", - mode: "quarantine", - }), - }); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.ok).toBe(true); - expect(body.policy.enabled).toBe(false); - expect(body.policy.trigger.archivedBytesOver).toBe(1024); - expect(body.policy.target.removeOldestPercent).toBe(40); - expect(body.policy.schedule).toBe("daily"); + const endpoint = startPolicyEndpoint(); + const res = await fetch(endpoint, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + trigger: { archivedBytesOver: 1024 }, + target: { removeOldestPercent: 40 }, + schedule: "daily", + mode: "quarantine", + }), + }); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.ok).toBe(true); + expect(body.policy.enabled).toBe(false); + expect(body.policy.trigger.archivedBytesOver).toBe(1024); + expect(body.policy.target.removeOldestPercent).toBe(40); + expect(body.policy.schedule).toBe("daily"); - const get = await fetch(new URL("/api/storage/cleanup-policy", server.url)); - const again = await get.json(); - expect(again.enabled).toBe(false); - expect(again.trigger.archivedBytesOver).toBe(1024); - } finally { - await stopPolicyServer(server); - await resetStorageCleanupPolicyJobForTestsAsync(); - } - }); + const get = await fetch(endpoint); + const again = await get.json(); + expect(again.enabled).toBe(false); + expect(again.trigger.archivedBytesOver).toBe(1024); + }, SERVER_BUDGET_MS); test("PUT rejects invalid target", async () => { - const server = startServer(0); - try { - const res = await fetch(new URL("/api/storage/cleanup-policy", server.url), { - method: "PUT", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ - enabled: true, - target: { reduceToBytes: 1, removeOldestPercent: 10 }, - }), - }); - expect(res.status).toBe(400); - const body = await res.json(); - expect(body.error).toContain("target"); - } finally { - await stopPolicyServer(server); - await resetStorageCleanupPolicyJobForTestsAsync(); - } - }); + const endpoint = startPolicyEndpoint(); + const res = await fetch(endpoint, { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + enabled: true, + target: { reduceToBytes: 1, removeOldestPercent: 10 }, + }), + }); + expect(res.status).toBe(400); + const body = await res.json(); + expect(body.error).toContain("target"); + }, SERVER_BUDGET_MS); }); diff --git a/tests/storage/api-storage.test.ts b/tests/storage/api-storage.test.ts index cb9c17c08b5..823a594d1d3 100644 --- a/tests/storage/api-storage.test.ts +++ b/tests/storage/api-storage.test.ts @@ -9,7 +9,10 @@ import { startServer } from "../../src/server"; import type { OcxConfig } from "../../src/types"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { SERVER_BUDGET_MS } from "../helpers/test-budget"; +let activeServer: ReturnType | undefined; +let fixtureCleanup: Promise | undefined; let testDir = ""; let previousHome: string | undefined; let isolatedCodexHome: IsolatedCodexHome | null = null; @@ -59,101 +62,106 @@ function inventoryCodexHome(codexHome: string): { bytes: number; fileCount: numb } beforeEach(() => { + if (fixtureCleanup) throw new Error("The previous storage API fixture is still stopping."); previousHome = process.env.OPENCODEX_HOME; isolatedCodexHome = installIsolatedCodexHome("ocx-api-storage-codex-"); testDir = mkdtempSync(join(tmpdir(), "ocx-api-storage-")); process.env.OPENCODEX_HOME = testDir; saveConfig(baseConfig()); -}); +}, SERVER_BUDGET_MS); -afterEach(() => { +async function releaseFixture(): Promise { + if (activeServer) { + await activeServer.stop(true); + activeServer = undefined; + } if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; isolatedCodexHome?.restore(); isolatedCodexHome = null; if (testDir) removeTreeWithRetry(testDir); testDir = ""; -}); +} + +afterEach(() => { + fixtureCleanup ??= releaseFixture().then(() => { fixtureCleanup = undefined; }); + return fixtureCleanup; +}, SERVER_BUDGET_MS); describe("GET /api/storage", () => { test("returns the scan report with buckets and totals, no error field", async () => { - writeSessionsFixture(isolatedCodexHome!.path); - const server = startServer(0); - try { - // Native-main startup takes its CODEX_HOME owner lock and runs its first exclusive claim - // in the background after startServer() returns; on Windows the lock's ACL hardening is a - // subprocess. In dev batch run 43818098370 the owner journal and the claim database landed - // between the scan and the inventory below. The startup gate settles only after both, and - // nothing writes into CODEX_HOME after it, so the scan and the inventory see the same tree. - await waitForNativeMainStartupGate(); - const settledInventory = inventoryCodexHome(isolatedCodexHome!.path); - const res = await fetch(new URL("/api/storage", server.url)); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.codexHome).toBe(isolatedCodexHome!.path); - expect(body.generatedAt).toBeGreaterThan(0); - expect(body.error).toBeUndefined(); - expect(Array.isArray(body.buckets)).toBe(true); + const codexHome = isolatedCodexHome!.path; + writeSessionsFixture(codexHome); + activeServer = startServer(0); + const serverUrl = activeServer.url; + // Native-main startup takes its CODEX_HOME owner lock and runs its first exclusive claim + // in the background after startServer() returns; on Windows the lock's ACL hardening is a + // subprocess. In dev batch run 43818098370 the owner journal and the claim database landed + // between the scan and the inventory below. The startup gate settles only after both, and + // nothing writes into CODEX_HOME after it, so the scan and the inventory see the same tree. + await waitForNativeMainStartupGate(); + const settledInventory = inventoryCodexHome(codexHome); + const res = await fetch(new URL("/api/storage", serverUrl)); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.codexHome).toBe(codexHome); + expect(body.generatedAt).toBeGreaterThan(0); + expect(body.error).toBeUndefined(); + expect(Array.isArray(body.buckets)).toBe(true); - const sessions = body.buckets.find((b: { key: string }) => b.key === "sessions"); - expect(sessions.bytes).toBe(500); - expect(sessions.fileCount).toBe(1); - const archived = body.buckets.find((b: { key: string }) => b.key === "archived_sessions"); - expect(archived.bytes).toBe(120); - expect(archived.fileCount).toBe(1); - const other = body.buckets.find((b: { key: string }) => b.key === "other"); - expect(other).toBeDefined(); - expect(other.fileCount).toBeGreaterThanOrEqual(1); + const sessions = body.buckets.find((b: { key: string }) => b.key === "sessions"); + expect(sessions.bytes).toBe(500); + expect(sessions.fileCount).toBe(1); + const archived = body.buckets.find((b: { key: string }) => b.key === "archived_sessions"); + expect(archived.bytes).toBe(120); + expect(archived.fileCount).toBe(1); + const other = body.buckets.find((b: { key: string }) => b.key === "other"); + expect(other).toBeDefined(); + expect(other.fileCount).toBeGreaterThanOrEqual(1); - // config.toml and live native-main coordination files legitimately land in - // "other"; compare against the filesystem without fixing their exact count. - const inventory = inventoryCodexHome(isolatedCodexHome!.path); - expect(inventory).toEqual(settledInventory); - expect(body.total).toEqual({ bytes: inventory.bytes, fileCount: inventory.fileCount }); - const fixturePaths = [ - "archived_sessions/rollout-y.jsonl", - "config.toml", - "sessions/2026/07/01/rollout-x.jsonl", - ]; - const coordinationDatabases = [ - ".opencodex-native-main.claim.sqlite", - ".opencodex-native-main.owner.sqlite", - ".opencodex-native-profile.lock.sqlite", - ]; - const sqliteSidecars = ["-journal", "-wal", "-shm"]; - expect(inventory.paths).toEqual(expect.arrayContaining(fixturePaths)); - expect(inventory.paths.filter(path => - !fixturePaths.includes(path) - && !coordinationDatabases.some(database => - path === database || sqliteSidecars.some(suffix => path === `${database}${suffix}`) - ) - )).toEqual([]); - expect(body.total.fileCount).toBeGreaterThanOrEqual(3); - expect(body.total.bytes).toBeGreaterThan(620); - } finally { - await server.stop(true); - } - }); + // config.toml and live native-main coordination files legitimately land in + // "other"; compare against the filesystem without fixing their exact count. + const inventory = inventoryCodexHome(codexHome); + expect(inventory).toEqual(settledInventory); + expect(body.total).toEqual({ bytes: inventory.bytes, fileCount: inventory.fileCount }); + const fixturePaths = [ + "archived_sessions/rollout-y.jsonl", + "config.toml", + "sessions/2026/07/01/rollout-x.jsonl", + ]; + const coordinationDatabases = [ + ".opencodex-native-main.claim.sqlite", + ".opencodex-native-main.owner.sqlite", + ".opencodex-native-profile.lock.sqlite", + ]; + const sqliteSidecars = ["-journal", "-wal", "-shm"]; + expect(inventory.paths).toEqual(expect.arrayContaining(fixturePaths)); + expect(inventory.paths.filter(path => + !fixturePaths.includes(path) + && !coordinationDatabases.some(database => + path === database || sqliteSidecars.some(suffix => path === `${database}${suffix}`) + ) + )).toEqual([]); + expect(body.total.fileCount).toBeGreaterThanOrEqual(3); + expect(body.total.bytes).toBeGreaterThan(620); + }, SERVER_BUDGET_MS); test("scan failure returns the fallback envelope with scan_failed", async () => { - const server = startServer(0); - try { - // Point CODEX_HOME at a regular file: resolveCodexHomeDir() accepts it, the - // scanner's root readdir then fails with ENOTDIR — the endpoint must answer - // with the documented fallback envelope instead of a 500. - const brokenHome = join(testDir, "codex-home-is-a-file"); - writeFileSync(brokenHome, "not a directory"); - process.env.CODEX_HOME = brokenHome; + activeServer = startServer(0); + const serverUrl = activeServer.url; + // Point CODEX_HOME at a regular file: resolveCodexHomeDir() accepts it, the + // scanner's root readdir then fails with ENOTDIR — the endpoint must answer + // with the documented fallback envelope instead of a 500. + const brokenHome = join(testDir, "codex-home-is-a-file"); + writeFileSync(brokenHome, "not a directory"); + process.env.CODEX_HOME = brokenHome; - const res = await fetch(new URL("/api/storage", server.url)); - expect(res.status).toBe(200); - const body = await res.json(); - expect(body.error).toBe("scan_failed"); - expect(body.total).toEqual({ bytes: 0, fileCount: 0 }); - expect(body.buckets).toEqual([]); - expect(typeof body.codexHome).toBe("string"); - } finally { - await server.stop(true); - } - }); + const res = await fetch(new URL("/api/storage", serverUrl)); + expect(res.status).toBe(200); + const body = await res.json(); + expect(body.error).toBe("scan_failed"); + expect(body.total).toEqual({ bytes: 0, fileCount: 0 }); + expect(body.buckets).toEqual([]); + expect(typeof body.codexHome).toBe("string"); + }, SERVER_BUDGET_MS); }); From 76c49e676f04333ccdbfafe5b89ae8e7aa96ba32 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:59:39 +0900 Subject: [PATCH 13/50] Preserve retained Gemini turns on failed writes and across branches (#9269) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- .../docs/es/reference/proxy-formats.md | 2 +- .../content/docs/reference/proxy-formats.md | 12 +-- src/server/gemini-interactions-store.ts | 54 ++++++++----- structure/data-planes/gemini-inbound.md | 16 ++-- .../server/gemini-interactions-store.test.ts | 76 +++++++++++++++++++ ...server-gemini-interactions-inbound.test.ts | 21 ++++- 6 files changed, 145 insertions(+), 36 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index 10e51751879..198731096ac 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -488,7 +488,7 @@ Los clientes de Gemini, como el SDK google-genai con una URL base personalizada, - `:generateContent` y `:streamGenerateContent`, bajo `/v1beta/models/` o `/v1/models/`, traducen `contents`, `systemInstruction`, imágenes en línea, declaraciones y llamadas de funciones, y `generationConfig`. Las firmas de pensamiento de las partes `functionCall` viajan en ambos sentidos. Con `alt=sse` el flujo es SSE; sin él la respuesta es un único array JSON, como lo envía la API REST de Google. Las herramientas alojadas de Gemini se ignoran. Un `candidateCount` distinto de 1, datos en línea que no son imágenes y partes de archivo se rechazan con 400. - `:countTokens` devuelve `{ "totalTokens": n }` a partir de una estimación local y no envía nada al proveedor. `:embedContent` y `:batchEmbedContents` responden 501. - `POST /v1beta/interactions`, o `POST /v1/interactions`, crea una interacción a partir de `input` (texto, imágenes base64 o pasos que incluyen `function_call` y `function_result`), `system_instruction`, herramientas `function`, `generation_config` y un `response_format` de texto. Un flujo usa los eventos de Interactions `interaction.created`, `step.start`, `step.delta`, `step.stop` e `interaction.completed`. Un turno que termina en llamadas de funciones tiene el estado `requires_action`. Los campos que el proxy no puede respetar se rechazan con 400: `agent`, `background: true`, `webhook_config`, `environment`, `agent_config`, `safety_settings`, herramientas alojadas, contenido de entrada que no sea texto ni imagen, y salida que no sea texto. El proveedor seleccionado aplica su propia política de seguridad. -- `previous_interaction_id` continúa una interacción guardada. El proxy guarda las interacciones solo en memoria, como máximo 24 horas desde la última escritura, y solo la clave que creó una puede leerla, continuarla o borrarla; los llamantes de loopback sin clave comparten un único propietario. La retención no está garantizada: cada clave guarda como máximo 200 interacciones y 16 MiB, el proxy guarda como máximo 1.000 y 64 MiB en total, y el presupuesto de memoria del proxy puede eliminarlas antes. Las claves hacen espacio eliminando únicamente sus propias interacciones más antiguas. Una escritura de loopback sin clave solo hace espacio eliminando turnos anteriores de la conversación que continúa, por lo que las demás conversaciones sin clave se conservan; si eso no basta para respetar el límite compartido o global, el proxy devuelve la respuesta sin guardar la nueva interacción. En el límite global, una clave que no tiene nada propio con lo que hacer espacio recibe igualmente su respuesta sin que la interacción se guarde, y lo mismo ocurre con una interacción mayor que 8 MiB o que el límite de cuerpo de entrada configurado, el que sea menor. Una respuesta no transmitida en flujo indica si se guardó en `x-opencodex-interaction-stored: true|false`. Un reinicio las olvida todas, y un id que falta o caducó responde 404, así que el cliente debe conservar su historial para reenviarlo. Una solicitud con `store: false` no se guarda. `GET /v1beta/interactions/{id}` devuelve una interacción guardada, `DELETE` la elimina y `POST /v1beta/interactions/{id}/cancel` responde 400 porque nada se ejecuta en segundo plano. Ambos alias de Interactions devuelven `Cache-Control: no-store`. +- `previous_interaction_id` continúa una interacción guardada. El proxy guarda las interacciones solo en memoria, como máximo 24 horas desde la última escritura, y solo la clave que creó una puede leerla, continuarla o borrarla; los llamantes de loopback sin clave comparten un único propietario. La retención no está garantizada: cada clave guarda como máximo 200 interacciones y 16 MiB, el proxy guarda como máximo 1.000 y 64 MiB en total, y el presupuesto de memoria del proxy puede eliminarlas antes. Las claves hacen espacio eliminando únicamente sus propias interacciones más antiguas. Una escritura de loopback sin clave solo puede eliminar la interacción indicada por `previous_interaction_id` y los turnos anteriores de esa rama que aún estén guardados. Los identificadores exclusivos de otras ramas y los de otras conversaciones siguen disponibles. Si las interacciones que se pueden eliminar no bastan para respetar ambos límites, el proxy devuelve la respuesta sin guardar la nueva interacción y conserva todas las que siguen vigentes. Esto se aplica a las escrituras con y sin clave. El proxy tampoco guarda una interacción que supere el menor de estos dos límites, 8 MiB o el límite de cuerpo de entrada configurado. Una respuesta no transmitida en flujo indica si se guardó en `x-opencodex-interaction-stored: true|false`. Un reinicio las olvida todas, y un id que falta o caducó responde 404, así que el cliente debe conservar su historial para reenviarlo. Una solicitud con `store: false` no se guarda. `GET /v1beta/interactions/{id}` devuelve una interacción guardada, `DELETE` la elimina y `POST /v1beta/interactions/{id}/cancel` responde 400 porque nada se ejecuta en segundo plano. Ambos alias de Interactions devuelven `Cache-Control: no-store`. ## `POST /v1/live` y banda lateral en tiempo real diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index c8b462760c4..3cb48d585d5 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -911,12 +911,12 @@ from the URL and headers before the request is logged or forwarded. Errors use G delete it; a keyless loopback caller shares one owner. Retention is best effort: each key keeps at most 200 interactions and 16 MiB, the proxy keeps at most 1,000 and 64 MiB in total, and the proxy's memory budget can remove interactions earlier. Keys make room only by removing their own oldest interactions. - A keyless loopback write makes room only by removing earlier turns of the conversation it continues, so - other keyless conversations stay in place; when that is not enough to stay within the shared or global - limit, the proxy returns the answer without storing the new interaction. A key with nothing of its own to make room - with at the global limit likewise gets its answer without the interaction being kept, as does one larger - than 8 MiB or the configured inbound body limit, whichever is smaller. A buffered answer reports whether it - was kept in `x-opencodex-interaction-stored: true|false`. A restart forgets them all, and a missing + A keyless loopback write can remove only stored turns on the path back from its `previous_interaction_id`, + including that interaction itself. IDs unique to sibling branches and IDs from other conversations stay available. + If the eligible turns cannot make room within the owner and global limits, the proxy returns the answer without storing + the new interaction and keeps every unexpired entry. This applies to both keyed and keyless writes. + The proxy also skips interactions larger than 8 MiB or the configured inbound body limit, whichever is smaller. + A buffered answer reports whether it was kept in `x-opencodex-interaction-stored: true|false`. A restart forgets them all, and a missing or expired id answers 404, so a client should keep its history to resend it. A request with `store: false` is not kept. `GET /v1beta/interactions/{id}` returns a stored interaction, `DELETE` removes it, and `POST /v1beta/interactions/{id}/cancel` answers 400 because nothing runs in the diff --git a/src/server/gemini-interactions-store.ts b/src/server/gemini-interactions-store.ts index 45d1939eace..f910212ff17 100644 --- a/src/server/gemini-interactions-store.ts +++ b/src/server/gemini-interactions-store.ts @@ -9,8 +9,8 @@ * an expired entry is dropped on the next write or lookup, and the app-owned memory budget can evict it * before that. Bounds: 24 hours from the last * write, 1,000 entries and 64 MiB in total, 200 entries and 16 MiB per owner, 8 MiB per entry. A write - * can rotate entries belonging to its own key. A shared keyless write rotates only earlier turns of its - * own conversation, never another retained conversation. A new interaction that cannot fit is not kept. + * can rotate entries belonging to its own key. A shared keyless write rotates only predecessors of the + * selected branch. A write that cannot fit leaves every unexpired entry in place. * Only the app-owned memory budget evicts across owners. */ import type { RetainedStoreSnapshot } from "../lib/app-owned-memory"; @@ -38,11 +38,22 @@ export interface StoredInteraction { const entries = new Map(); const ownerTotals = new Map(); +// Edges only between retained keyless turns. Deleted turns retain neither history nor metadata. +const keylessParents = new Map(); let totalBytes = 0; function drop(id: string): void { const entry = entries.get(id); if (!entry) return; + if (entry.owner === KEYLESS_INTERACTION_OWNER) { + const parent = keylessParents.get(id); + keylessParents.delete(id); + for (const [child, predecessor] of keylessParents) { + if (predecessor !== id) continue; + if (parent === undefined) keylessParents.delete(child); + else keylessParents.set(child, parent); + } + } entries.delete(id); totalBytes -= entry.bytes; const totals = ownerTotals.get(entry.owner); @@ -60,13 +71,6 @@ function sweep(now: number): void { } } -function oldestOf(owner: string, exceptId: string, chain?: string): string | undefined { - for (const [id, entry] of entries) { - if (entry.owner === owner && id !== exceptId && (chain === undefined || entry.chain === chain)) return id; - } - return undefined; -} - export function interactionEntryBytes(entry: Pick): number { return Buffer.byteLength(JSON.stringify(entry.history)) + Buffer.byteLength(JSON.stringify(entry.resource)); } @@ -87,19 +91,32 @@ export function rememberInteraction( if (previous && previous.owner !== entry.owner) return false; const extraCount = previous ? 0 : 1; const extraBytes = bytes - (previous?.bytes ?? 0); - const owned = () => ownerTotals.get(entry.owner) ?? { count: 0, bytes: 0 }; - while (owned().count + extraCount > MAX_OWNER_INTERACTIONS || owned().bytes + extraBytes > MAX_OWNER_INTERACTION_BYTES - || entries.size + extraCount > MAX_STORED_INTERACTIONS || totalBytes + extraBytes > MAX_INTERACTION_STORE_BYTES) { - // Keyless callers share one owner, so a keyless write may only retire its own conversation's earlier - // turns; each stored turn carries the full history, so the newest turn supersedes them. - const oldest = oldestOf(entry.owner, entry.id, entry.owner === KEYLESS_INTERACTION_OWNER ? chain : undefined); - if (oldest === undefined) return false; - drop(oldest); + const owned = ownerTotals.get(entry.owner); + let countNeeded = Math.max((owned?.count ?? 0) + extraCount - MAX_OWNER_INTERACTIONS, entries.size + extraCount - MAX_STORED_INTERACTIONS); + let bytesNeeded = Math.max((owned?.bytes ?? 0) + extraBytes - MAX_OWNER_INTERACTION_BYTES, totalBytes + extraBytes - MAX_INTERACTION_STORE_BYTES); + const keyless = entry.owner === KEYLESS_INTERACTION_OWNER; + let parentId = keyless && parent?.owner === entry.owner && entries.get(parent.id) === parent ? parent.id : undefined; + const retire = new Set(); + if (countNeeded > 0 || bytesNeeded > 0) { + const ancestors = new Set(); + for (let id = parentId; id !== undefined; id = keylessParents.get(id)) ancestors.add(id); + for (const candidate of entries.values()) { + if (candidate.owner !== entry.owner || candidate.id === entry.id || (keyless && !ancestors.has(candidate.id))) continue; + retire.add(candidate.id); + countNeeded--; + bytesNeeded -= candidate.bytes; + if (countNeeded <= 0 && bytesNeeded <= 0) break; + } + if (countNeeded > 0 || bytesNeeded > 0) return false; } + // A replacement must not link back to the old incarnation of its own id. + while (parentId !== undefined && (parentId === entry.id || retire.has(parentId))) parentId = keylessParents.get(parentId); + for (const id of retire) drop(id); drop(entry.id); + if (parentId !== undefined) keylessParents.set(entry.id, parentId); entries.set(entry.id, { id: entry.id, owner: entry.owner, history: entry.history, resource: entry.resource, bytes, writtenAt: now, chain }); totalBytes += bytes; - const totals = owned(); + const totals = ownerTotals.get(entry.owner) ?? { count: 0, bytes: 0 }; ownerTotals.set(entry.owner, { count: totals.count + 1, bytes: totals.bytes + bytes }); return true; } @@ -134,5 +151,6 @@ export function evictOldestInteractionForBudget(): number { export function clearInteractionsForTests(): void { entries.clear(); ownerTotals.clear(); + keylessParents.clear(); totalBytes = 0; } diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 0ab22baf7d0..47d5310ae78 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -137,14 +137,14 @@ mints a new principal, so its earlier chains answer 404. A lookup, delete or can indistinguishable from a missing id. The dispatcher sets `Cache-Control: no-store` on both Interactions aliases, including successes and owner-scoped misses. Bounds: 24 hours from the last write (expiry is lazy, on the next write or lookup), 1,000 entries and 64 MiB in total, 200 entries and 16 MiB per owner, and per entry the smaller of 8 MiB and the inbound body limit, since a larger history -could never be chained. A keyed write evicts only its own owner's oldest entries, at the owner and the global limits; -when the store is full and the writer owns nothing to evict, the interaction is not kept. Because keyless loopback -callers have no caller identity, a keyless write evicts only earlier entries of the conversation it continues (the -`chain` inherited through `previous_interaction_id`; each entry holds the full history, so the newest turn supersedes -them) and never another retained keyless conversation: when that cannot make room at either capacity, the new -interaction is not kept. The settled answer is still returned. Buffered answers report -`x-opencodex-interaction-stored: false` when retention fails. Only the -app-owned memory budget evicts across owners. The store is `gemini_interactions` on the app-owned memory roster (category +could never be chained. A keyed write makes room at either limit by evicting only its owner's entries, oldest first. +A keyless loopback write may evict only its `previous_interaction_id` and earlier turns on that branch +that are still stored. IDs unique to sibling branches and IDs from other conversations survive the write. +For either caller, the store evicts eligible entries only if doing so makes room under both limits. +If capacity prevents storage, every unexpired entry survives and the caller receives the settled answer. +Buffered answers report `x-opencodex-interaction-stored: false` when retention fails. Independently, the +app-owned memory budget can evict across owners, and a restart clears the store. +The store is `gemini_interactions` on the app-owned memory roster (category `continuation`, passively evictable). A chained turn sends `system` from this request, then the stored history (prior input and answers, diff --git a/tests/server/gemini-interactions-store.test.ts b/tests/server/gemini-interactions-store.test.ts index 853d90283a5..5ed9af335f2 100644 --- a/tests/server/gemini-interactions-store.test.ts +++ b/tests/server/gemini-interactions-store.test.ts @@ -3,6 +3,8 @@ import { INTERACTION_TTL_MS, KEYLESS_INTERACTION_OWNER, MAX_INTERACTION_BYTES, + MAX_INTERACTION_STORE_BYTES, + MAX_OWNER_INTERACTION_BYTES, MAX_OWNER_INTERACTIONS, clearInteractionsForTests, evictOldestInteractionForBudget, @@ -73,6 +75,60 @@ describe("stored Gemini interactions", () => { expect(interactionsRetainedStoreSnapshot().count).toBe(MAX_OWNER_INTERACTIONS); }); + test.each(["new", "current"])("a refused write to %s preserves every retained turn and its accounting", id => { + const owner = KEYLESS_INTERACTION_OWNER; + // Three records of this size cannot share the owner budget, even after retiring all eligible turns. + const section = "x".repeat(Math.floor(MAX_OWNER_INTERACTION_BYTES / 3) + 1); + expect(rememberInteraction(entry("report-a", owner, section), 1)).toBe(true); + expect(rememberInteraction(entry("report-b", owner, section), 2)).toBe(true); + expect(rememberInteraction(entry("root", owner, "first"), 3)).toBe(true); + expect(rememberInteraction({ ...entry("current", owner, "second"), previous: "root" }, 4)).toBe(true); + const before = interactionsRetainedStoreSnapshot(); + const previous = id === "new" ? "current" : "root"; + + expect(rememberInteraction({ ...entry(id, owner, section), previous }, 5)).toBe(false); + expect(interactionsRetainedStoreSnapshot()).toEqual(before); + expect(recallInteraction("root", owner, 6)?.history).toEqual(entry("root", owner, "first").history); + expect(recallInteraction("current", owner, 6)?.history).toEqual(entry("current", owner, "second").history); + expect(recallInteraction("report-a", owner, 6)?.resource.id).toBe("report-a"); + expect(recallInteraction("report-b", owner, 6)?.resource.id).toBe("report-b"); + expect(recallInteraction("new", owner, 6)).toBeUndefined(); + }); + + test("a keyless branch can progress at capacity while a sibling tip remains available", () => { + const owner = KEYLESS_INTERACTION_OWNER; + expect(rememberInteraction(entry("root", owner), 0)).toBe(true); + expect(rememberInteraction({ ...entry("left", owner, "plan A"), previous: "root" }, 1)).toBe(true); + expect(rememberInteraction({ ...entry("right", owner, "plan B"), previous: "root" }, 2)).toBe(true); + for (let i = 3; i < MAX_OWNER_INTERACTIONS; i++) { + expect(rememberInteraction(entry(`separate-${i}`, owner), i)).toBe(true); + } + const now = MAX_OWNER_INTERACTIONS; + expect(rememberInteraction({ ...entry("right-2", owner), previous: "right" }, now)).toBe(true); + expect(rememberInteraction({ ...entry("right-3", owner), previous: "right-2" }, now + 1)).toBe(true); + expect(recallInteraction("left", owner, now + 2)?.history).toEqual(entry("left", owner, "plan A").history); + expect(recallInteraction("right-3", owner, now + 2)).toBeDefined(); + expect(interactionsRetainedStoreSnapshot().count).toBe(MAX_OWNER_INTERACTIONS); + }); + + test("deleting an intermediate turn keeps its older predecessor eligible and frees the id for a new conversation", () => { + const owner = KEYLESS_INTERACTION_OWNER; + expect(rememberInteraction(entry("root", owner), 1)).toBe(true); + expect(rememberInteraction({ ...entry("middle", owner), previous: "root" }, 2)).toBe(true); + expect(rememberInteraction({ ...entry("tip", owner), previous: "middle" }, 3)).toBe(true); + expect(forgetInteraction("middle", owner, 4)).toBe(true); + expect(rememberInteraction(entry("middle", owner, "unrelated"), 5)).toBe(true); + for (let i = 3; i < MAX_OWNER_INTERACTIONS; i++) { + expect(rememberInteraction(entry(`other-${i}`, owner), 6)).toBe(true); + } + expect(rememberInteraction({ ...entry("next", owner), previous: "tip" }, 7)).toBe(true); + expect(recallInteraction("root", owner, 7)).toBeUndefined(); + expect(recallInteraction("tip", owner, 7)).toBeDefined(); + expect(rememberInteraction({ ...entry("later", owner), previous: "next" }, 8)).toBe(true); + expect(rememberInteraction({ ...entry("latest", owner), previous: "later" }, 9)).toBe(true); + expect(recallInteraction("middle", owner, 9)?.history).toEqual(entry("middle", owner, "unrelated").history); + }); + test("a long keyless conversation keeps its newest turn past 16 MiB without touching another conversation", () => { const turn = { role: "user", content: "x".repeat(20_000) }; expect(rememberInteraction(entry("other", KEYLESS_INTERACTION_OWNER), 0)).toBe(true); @@ -109,6 +165,26 @@ describe("stored Gemini interactions", () => { }); describe("stored Gemini interactions at the global limit", () => { + test("refusing a keyed turn at the global byte limit removes only expired entries", () => { + expect(rememberInteraction(entry("expired", "old-owner"), 0)).toBe(true); + const expiredBytes = recallInteraction("expired", "old-owner", 0)!.bytes; + const section = "x".repeat(MAX_INTERACTION_BYTES - 1024); + const reports = MAX_INTERACTION_STORE_BYTES / MAX_INTERACTION_BYTES; + for (let i = 0; i < reports; i++) { + expect(rememberInteraction(entry(`report-${i}`, `owner-${i}`, section), 1)).toBe(true); + } + expect(rememberInteraction(entry("original", "writer"), 2)).toBe(true); + const before = interactionsRetainedStoreSnapshot(); + + expect(rememberInteraction(entry("next", "writer", "x".repeat(reports * 1024)), INTERACTION_TTL_MS)).toBe(false); + expect(interactionsRetainedStoreSnapshot()).toEqual({ + ...before, count: before.count - 1, bytes: before.bytes - expiredBytes, evictableBytes: before.evictableBytes - expiredBytes, oldestAt: 1, + }); + expect(recallInteraction("expired", "old-owner", INTERACTION_TTL_MS)).toBeUndefined(); + expect(recallInteraction("original", "writer", INTERACTION_TTL_MS)).toBeDefined(); + expect(recallInteraction("next", "writer", INTERACTION_TTL_MS)).toBeUndefined(); + }); + test("a full store never evicts another owner's entry; the writer evicts its own oldest or keeps nothing", () => { for (let owner = 0; owner < 5; owner++) { for (let n = 0; n < MAX_OWNER_INTERACTIONS; n++) { diff --git a/tests/server/server-gemini-interactions-inbound.test.ts b/tests/server/server-gemini-interactions-inbound.test.ts index 5ba644ecb77..dea9139bf17 100644 --- a/tests/server/server-gemini-interactions-inbound.test.ts +++ b/tests/server/server-gemini-interactions-inbound.test.ts @@ -440,7 +440,10 @@ describe("Gemini Interactions state: ownership and chaining rules", () => { const first = await post(base, path, turn, {}); expect(first.headers.get("x-opencodex-interaction-stored")).toBe("true"); const { id: firstId } = await first.json() as { id: string }; - for (let i = 1; i < MAX_OWNER_INTERACTIONS; i++) { + const sibling = await post(base, path, { ...turn, input: "left branch", previous_interaction_id: firstId }, {}); + expect(sibling.headers.get("x-opencodex-interaction-stored")).toBe("true"); + const { id: siblingId } = await sibling.json() as { id: string }; + for (let i = 2; i < MAX_OWNER_INTERACTIONS; i++) { const id = `capacity-fixture-${i}`; expect(rememberInteraction({ id, owner: KEYLESS_INTERACTION_OWNER, history: [], resource: { id } })).toBe(true); } @@ -463,14 +466,26 @@ describe("Gemini Interactions state: ownership and chaining rules", () => { await keyed.text(); // A keyless continuation retires only its own conversation's earlier turn to make room. - const chained = await post(base, path, { ...turn, previous_interaction_id: firstId }, {}); + const chained = await post(base, path, { ...turn, input: "right branch", previous_interaction_id: firstId }, {}); expect(chained.headers.get("x-opencodex-interaction-stored")).toBe("true"); const { id: chainedId } = await chained.json() as { id: string }; const superseded = await fetch(new URL(path + "/" + firstId, base)); expect(superseded.status).toBe(404); await superseded.text(); expect((await fetch(new URL(path + "/" + chainedId, base))).status).toBe(200); - expect(recallInteraction("capacity-fixture-1", KEYLESS_INTERACTION_OWNER)).toBeDefined(); + const right = await post(base, path, { ...turn, previous_interaction_id: chainedId }, {}); + expect(right.headers.get("x-opencodex-interaction-stored")).toBe("true"); + const { id: rightId } = await right.json() as { id: string }; + const priorSibling = await fetch(new URL(path + "/" + siblingId, base)); + expect(priorSibling.status).toBe(200); + expect(await priorSibling.json()).toMatchObject({ id: siblingId, status: "completed" }); + const left = await post(base, path, { ...turn, input: "continue left", previous_interaction_id: siblingId }, {}); + expect(left.headers.get("x-opencodex-interaction-stored")).toBe("true"); + expect(await left.json()).toMatchObject({ previous_interaction_id: siblingId, status: "completed" }); + const messages = seen.at(-1)!.body.messages as { role: string; content: string }[]; + expect(messages.filter(message => message.role === "user").map(message => message.content)).toEqual(["hi", "left branch", "continue left"]); + expect((await fetch(new URL(path + "/" + rightId, base))).status).toBe(200); + expect(recallInteraction("capacity-fixture-2", KEYLESS_INTERACTION_OWNER)).toBeDefined(); }); } finally { clearInteractionsForTests(); From b0619bef5ad1b69a7467eb1ae94c54d28021e34e Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:59:47 +0900 Subject: [PATCH 14/50] Account for retained text in the Grok stream translator budget (#9268) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/lib/tool-envelope-echo-filter.ts | 5 ++ src/server/grok-upstream-envelope-echo.ts | 68 +++++++++++++------ src/server/responses/passthrough-delivery.ts | 1 + structure/providers/xai-grok.md | 3 +- ...hrough-grok-upstream-envelope-echo.test.ts | 54 ++++++++++++++- 5 files changed, 107 insertions(+), 24 deletions(-) diff --git a/src/lib/tool-envelope-echo-filter.ts b/src/lib/tool-envelope-echo-filter.ts index 446defd75ab..d4e24303b3e 100644 --- a/src/lib/tool-envelope-echo-filter.ts +++ b/src/lib/tool-envelope-echo-filter.ts @@ -102,6 +102,11 @@ export class ToolEnvelopeEchoFilter { /** A fenced marker whose hold overflowed was released without proof that the block closes. */ unverifiedMarker = false; + /** A later finish() may emit text using the most recent delta's metadata. */ + get hasPendingText(): boolean { + return this.pending.length > 0 || (this.held !== null && this.held.length > 0); + } + feed(delta: string): string { if (this.failure) throw this.failure; if (this.matched) return ""; diff --git a/src/server/grok-upstream-envelope-echo.ts b/src/server/grok-upstream-envelope-echo.ts index 58f5c415093..ea5358869d6 100644 --- a/src/server/grok-upstream-envelope-echo.ts +++ b/src/server/grok-upstream-envelope-echo.ts @@ -1,6 +1,6 @@ import { ToolEnvelopeEchoFilter, stripToolEnvelopeEcho } from "../lib/tool-envelope-echo-filter"; import { responsesCompletionError } from "../lib/errors"; -import { isTranslatorBudgetExceededError } from "../lib/translator-budget"; +import { isTranslatorBudgetExceededError, type TranslatorBudget } from "../lib/translator-budget"; import { replaceSseDataPayload, sseDataPayload, type SseBlockRewrite } from "./sse-payload-rewrite"; function record(value: unknown): value is Record { @@ -52,20 +52,11 @@ type TextState = { delivered: string; /** Raw upstream text already accepted for this output part, before echo stripping. */ seen: string; - lastDeltaBlock: string; - lastDeltaEvent: Record; + textBytes: number; + flushTemplate: string; + templateBytes: number; }; -/** - * xAI's OAuth Responses stream repeats the current answer as each output_text delta, or sends - * the text so far. A delta that begins with the raw text already seen contributes only its - * unseen suffix. A delta that does not is a real increment and is kept whole, so a later copy - * of an earlier sentence still survives once other text has been seen. - */ -function novelUpstreamDelta(seen: string, delta: string): string { - return seen.length > 0 && delta.startsWith(seen) ? delta.slice(seen.length) : delta; -} - export type GrokUpstreamEnvelopeEchoOptions = { /** * Collapse repeated or cumulative `output_text.delta` snapshots to their unseen suffix. @@ -77,21 +68,38 @@ export type GrokUpstreamEnvelopeEchoOptions = { /** Keep xAI text deltas, done events, terminal snapshots and replay state in agreement. */ export function createGrokUpstreamEnvelopeEchoBlockRewrite( + budget: TranslatorBudget, onCompletedResponse?: (response: Record) => void, options?: GrokUpstreamEnvelopeEchoOptions, ): SseBlockRewrite { const collapseCumulativeDeltas = options?.collapseCumulativeDeltas === true; const states = new Map(); + const scope = { kind: "retained_collectors" } as const; + let retainedBytes = 0; + const adjustRetainedBytes = (delta: number) => { + if (delta > 0) budget.chargeRetained(delta, scope); + if (delta < 0) budget.releaseRetained(-delta, scope); + retainedBytes += delta; + }; + const dispose = () => { + states.clear(); + adjustRetainedBytes(-retainedBytes); + }; let errorCompletionSeen = false; const key = (output: unknown, content: unknown): string => `${typeof output === "number" ? output : 0}:${typeof content === "number" ? content : 0}`; const flush = (state: TextState): string[] => { const suffix = state.filter.finish(); + const template = state.flushTemplate; + state.flushTemplate = ""; + adjustRetainedBytes(-state.templateBytes); + state.templateBytes = 0; if (!suffix) return []; state.delivered += suffix; - return [replaceSseDataPayload(state.lastDeltaBlock, JSON.stringify({ ...state.lastDeltaEvent, delta: suffix }))]; + const event = JSON.parse(sseDataPayload(template)!); + return [replaceSseDataPayload(template, JSON.stringify({ ...event, delta: suffix }))]; }; - return (block) => { + const rewrite: SseBlockRewrite = (block) => { const payload = sseDataPayload(block); if (payload === null) return [block]; if (payload === "[DONE]") return [...[...states.values()].flatMap(flush), block]; @@ -103,16 +111,35 @@ export function createGrokUpstreamEnvelopeEchoBlockRewrite( const id = key(event.output_index, event.content_index); let state = states.get(id); if (!state) { - state = { filter: new ToolEnvelopeEchoFilter(), delivered: "", seen: "", lastDeltaBlock: "", lastDeltaEvent: event }; + adjustRetainedBytes(Buffer.byteLength(id)); + state = { filter: new ToolEnvelopeEchoFilter(), delivered: "", seen: "", textBytes: 0, flushTemplate: "", templateBytes: 0 }; states.set(id, state); } - const novel = collapseCumulativeDeltas ? novelUpstreamDelta(state.seen, event.delta) : event.delta; + if (state.filter.matched) return []; + const snapshot = collapseCumulativeDeltas && event.delta.startsWith(state.seen); + const novel = snapshot ? event.delta.slice(state.seen.length) : event.delta; if (collapseCumulativeDeltas && novel.length === 0) return []; - state.seen += novel; - state.lastDeltaBlock = block; - state.lastDeltaEvent = event; + // Input lives in the filter or delivered text. Only cumulative streams also need a raw cursor. + const bytes = Buffer.byteLength(novel) * (collapseCumulativeDeltas ? 2 : 1); + adjustRetainedBytes(bytes); + state.textBytes += bytes; const delta = state.filter.feed(novel); state.delivered += delta; + if (state.filter.matched) { + state.seen = ""; + const deliveredBytes = Buffer.byteLength(state.delivered); + adjustRetainedBytes(deliveredBytes - state.textBytes); + state.textBytes = deliveredBytes; + } else if (collapseCumulativeDeltas) { + // Keep the newest full snapshot directly so its suffix cannot pin older snapshots. + state.seen = snapshot ? event.delta : state.seen + novel; + } + // Only an unfinished line needs the frame again. Its text is already held by the filter. + const template = state.filter.hasPendingText ? replaceSseDataPayload(block, JSON.stringify({ ...event, delta: "" })) : ""; + const templateBytes = Buffer.byteLength(template); + adjustRetainedBytes(templateBytes - state.templateBytes); + state.flushTemplate = template; + state.templateBytes = templateBytes; if (!delta) return []; return [replaceSseDataPayload(block, JSON.stringify({ ...event, delta }))]; } @@ -149,4 +176,5 @@ export function createGrokUpstreamEnvelopeEchoBlockRewrite( } return [block]; }; + return Object.assign(rewrite, { dispose }); } diff --git a/src/server/responses/passthrough-delivery.ts b/src/server/responses/passthrough-delivery.ts index 6d38ffa7a46..a420e27844e 100644 --- a/src/server/responses/passthrough-delivery.ts +++ b/src/server/responses/passthrough-delivery.ts @@ -1004,6 +1004,7 @@ export async function deliverPassthroughResponse( : undefined, grokUpstreamEchoEnabled ? createGrokUpstreamEnvelopeEchoBlockRewrite( + translatorBudget, rememberPassthroughResponse ? (response) => { if (requiredStreamGuard) requiredStreamGuard.rememberCompleted(response, rememberPassthroughResponseChecked); else rememberPassthroughResponseChecked(response); diff --git a/structure/providers/xai-grok.md b/structure/providers/xai-grok.md index 0701e0db04a..c92bc5411fe 100644 --- a/structure/providers/xai-grok.md +++ b/structure/providers/xai-grok.md @@ -28,7 +28,8 @@ tool-result repair), or a `previous_response_id` continuation whose history live merely starts with a result or error marker, such as `[Tool Result] shows the build passed.`, is an answer and reaches the client whole (`tests/adapters/tool-envelope-echo-whole-line.test.ts`). The same filter preserves leading prose and normalizes text-done events, completed snapshots, non-streaming JSON, and the stored -continuation snapshot. It does not rotate an xAI upstream conversation. +continuation snapshot. It does not rotate an xAI upstream conversation. Stream text and pending +delta metadata share the request's translator budget until relay teardown. Only cumulative streams retain a raw snapshot cursor. The shared [pending-line bound](../transports/byte-accounting.md#stream-buffer-accounting) fails with `translation_buffer_limit` before a refused turn enters continuation state. Buffered JSON returns 502 instead of falling back to the original body; an SSE rewrite propagates the budget diff --git a/tests/responses/passthrough-grok-upstream-envelope-echo.test.ts b/tests/responses/passthrough-grok-upstream-envelope-echo.test.ts index cf443ea9629..7388b653f29 100644 --- a/tests/responses/passthrough-grok-upstream-envelope-echo.test.ts +++ b/tests/responses/passthrough-grok-upstream-envelope-echo.test.ts @@ -23,9 +23,10 @@ async function relay( ) { const bytes = new TextEncoder().encode(input); const body = new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close(); } }); + const budget = createTestTranslatorBudget(); const output = await new Response(relaySseWithBlockRewrite( - body, createGrokUpstreamEnvelopeEchoBlockRewrite(onCompleted, options), createTestTranslatorBudget(), - )).text(); + body, createGrokUpstreamEnvelopeEchoBlockRewrite(budget, onCompleted, options), budget, + )).text().finally(() => expect(budget.snapshot().currentBytes).toBe(0)); return output.split(/\n\n/).filter(Boolean).map(block => JSON.parse(block.split("\ndata: ")[1]!) as Record); } @@ -35,6 +36,53 @@ const snapshot = (text: string) => ({ }); describe("xAI Responses upstream tool-envelope echoes", () => { + test.each([false, true])("stream text shares the request budget until disposal (cumulative=%s)", cumulative => { + const maxTurnBytes = 256; + const budget = createTestTranslatorBudget({ maxTurnBytes }); + const sibling = { kind: "retained_collectors" } as const; + budget.chargeRetained(8, sibling); + const rewrite = createGrokUpstreamEnvelopeEchoBlockRewrite(budget, undefined, { collapseCumulativeDeltas: cumulative }); + const send = (delta: string) => rewrite(frame("response.output_text.delta", { delta }).trimEnd()); + send("Hi"); + const before = budget.snapshot().currentBytes; + send(cumulative ? "Hi하" : "하"); + expect(budget.snapshot().currentBytes - before).toBe(Buffer.byteLength("하") * (cumulative ? 2 : 1)); + const remaining = maxTurnBytes - budget.snapshot().currentBytes; + budget.chargeRetained(remaining, sibling); + expect(() => send("!")).toThrow(TranslatorBudgetExceededError); + rewrite.dispose?.(); + rewrite.dispose?.(); + expect(budget.snapshot().currentBytes).toBe(8 + remaining); + }); + + test("a settled echo releases its cursor and ignores subsequent text", () => { + const budget = createTestTranslatorBudget(); + const rewrite = createGrokUpstreamEnvelopeEchoBlockRewrite(budget, undefined, { collapseCumulativeDeltas: true }); + const send = (delta: string) => rewrite(frame("response.output_text.delta", { delta }).trimEnd()); + send("Greeting.\n"); + const before = budget.snapshot().currentBytes; + send("Greeting.\n[Tool Result]\n"); + const settled = budget.snapshot().currentBytes; + expect(settled).toBeLessThan(before); + expect(send("sample tool output")).toEqual([]); + expect(budget.snapshot().currentBytes).toBe(settled); + rewrite.dispose?.(); + expect(budget.snapshot().currentBytes).toBe(0); + }); + + test("cancelling a relay releases held text without disposing the request budget", async () => { + const budget = createTestTranslatorBudget(); + budget.chargeRetained(8, { kind: "retained_collectors" }); + const input = new ReadableStream({ start(controller) { + controller.enqueue(new TextEncoder().encode(frame("response.output_text.delta", { delta: "Hi\n[Too" }))); + } }); + const reader = relaySseWithBlockRewrite(input, createGrokUpstreamEnvelopeEchoBlockRewrite(budget), budget).getReader(); + expect((await reader.read()).done).toBe(false); + expect(budget.snapshot().currentBytes).toBeGreaterThan(8); + await reader.cancel(); + expect(budget.snapshot().currentBytes).toBe(8); + }); + test.each([true, false])("JSON delivery refuses overflow only for armed requests (armed=%s)", async armed => { const raw = `[Tool Result]${" ".repeat(64 * 1024)}\nprivate-fixture`; const request = new Request("http://127.0.0.1/v1/responses", { method: "POST" }); @@ -139,7 +187,7 @@ describe("xAI Responses upstream tool-envelope echoes", () => { }); test("a terminal [DONE] flushes a harmless partial prefix", () => { - const rewrite = createGrokUpstreamEnvelopeEchoBlockRewrite(); + const rewrite = createGrokUpstreamEnvelopeEchoBlockRewrite(createTestTranslatorBudget()); expect(rewrite(frame("response.output_text.delta", { delta: "[Too" }).trimEnd())).toEqual([]); const flushed = rewrite("data: [DONE]"); expect(flushed).toHaveLength(2); From 7379923538ed476bc465dec2924fbac131995af4 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Thu, 3 Dec 2026 23:59:57 +0900 Subject: [PATCH 15/50] Explain unverified Codex journal baselines in ocx doctor (#9264) * fix(doctor): explain unverified Codex journal baselines * fix(doctor): name unreadable Codex journal inputs --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- .../content/docs/guides/codex-integration.md | 7 +++ src/cli/doctor.ts | 5 ++ src/codex/inject.ts | 2 +- src/codex/inject/restore.ts | 2 +- src/codex/journal.ts | 55 +++++++++++++++++++ structure/codex-home.md | 2 +- tests/codex-integration/codex-journal.test.ts | 32 +++++++++++ tests/codex-integration/doctor.test.ts | 34 +++++++++++- 8 files changed, 135 insertions(+), 4 deletions(-) diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 439adbb63c8..4ba13abb8fa 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -1554,6 +1554,13 @@ and lacks its own injected-state hash, automatic journal recovery and native res without changing either file or the journal. The saved original remains available for comparison; review it alongside the current files before choosing a manual recovery action. +Run `ocx doctor` on the affected host. Its **Codex recovery journal** section compares each file +with the original and reports whether the journal recorded its injected state. For example, +`config.toml` may differ while the profile was absent in both states. The comparison works +with the proxy stopped and prints no configuration values. If either file cannot be read safely, +the report names it. Keep the current files and the journal. +A local routing URL alone cannot establish which settings OpenCodex wrote. + Files already equal to their saved originals are accepted without rewriting them. A missing file is distinct from an empty file. Verified injected hashes still allow normal snapshot restoration, and later edits in hash-backed configurations retain the existing owned-field cleanup behavior. diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts index 035381713fe..e85809f1437 100644 --- a/src/cli/doctor.ts +++ b/src/cli/doctor.ts @@ -1716,6 +1716,11 @@ export async function runDoctor(args: string[] = []): Promise { } console.log("\nCodex native-write coordinator"); for (const line of formatCoordinatorDoctorLines(inspectCodexCoordinator())) console.log(line); + const journalEvidence = (await import("../codex/journal")).describeUnverifiedJournal(resolveCodexHomeDirImpl()); + if (journalEvidence.length) { + console.log("\nCodex recovery journal"); + for (const line of journalEvidence) console.log(` ${line}`); + } const pending = countPendingOpencodexHistory(); if (pending.failed) { if (pending.failureReason === "busy") { diff --git a/src/codex/inject.ts b/src/codex/inject.ts index 6810229b128..ac44388ea63 100644 --- a/src/codex/inject.ts +++ b/src/codex/inject.ts @@ -381,7 +381,7 @@ async function injectCodexConfigImpl( return !hasInjectedCodexRouting(nativeInput) && !ownsRoot("openai_base_url") && !ownsRoot(REALTIME_WS_BASE_URL_KEY); }; const readCurrentProfile = readCodexProfileSource; - const unverifiedJournalMessage = "Codex configuration was not written: the journal has no verified baseline for the current config/profile. Current files and the journal were preserved."; + const unverifiedJournalMessage = "Codex configuration was not written: the journal has no verified baseline for the current config/profile. Current files and the journal were preserved. Run ocx doctor to compare each file with its journal baseline."; // When the reconcile will rewrite config.toml under the lock, the baseline it // must be journaled against does not exist yet — this check runs inside the // boundary on the post-transition plan instead. Otherwise the admitted bytes diff --git a/src/codex/inject/restore.ts b/src/codex/inject/restore.ts index 85da8c08597..ac51dbd5924 100644 --- a/src/codex/inject/restore.ts +++ b/src/codex/inject/restore.ts @@ -453,7 +453,7 @@ function restoreCodexConfigInlineImpl( if (journal.unverified) { return { state: "failed", changed: false, action: "failed", - message: "Codex journal recovery was not verified; current configuration files and the journal were preserved.", + message: "Codex journal recovery was not verified; current configuration files and the journal were preserved. Run ocx doctor to compare each file with its journal baseline.", }; } if (journal.profileRestoreFailed) { diff --git a/src/codex/journal.ts b/src/codex/journal.ts index b2f5e9ab500..d5817aa33b4 100644 --- a/src/codex/journal.ts +++ b/src/codex/journal.ts @@ -6,6 +6,7 @@ import { join } from "node:path"; import { atomicWriteFile, withConfigMutationLockSync } from "../config"; import { assertCodexHomeOwner, codexHomeIsAbsent, CODEX_HOME_JOURNAL_FILE, CodexHomeOwnerRefusal, opencodexHomeForInjection, readCodexHomeJournal, type CodexHomeOwnerRefusalReason } from "./codex-home-owner"; import { hasInjectedCodexRouting } from "./injected-marker"; +import { readBoundedCodexConfig } from "./inject/bounded-config-reader"; import { ConfigWriteContentChanged, configWriteLockFailureMessage, withConfigWriteLockHeld } from "./config-write-lock"; import type { LockHandle } from "./config-write-lock"; import { CODEX_HOME, CODEX_CONFIG_PATH, CODEX_PROFILE_PATH, resolveCodexCatalogPath } from "./paths"; @@ -156,6 +157,8 @@ function compareJournalState(journal: Journal, config: string | null, profile: s originalProfile, configAlreadyOriginal, profileAlreadyOriginal, + configHashKnown, + profileHashKnown, configUnchanged: configAlreadyOriginal || ( configHashKnown && sha256(config) === journal.injectedConfigHash && defaultOwnershipAllowsSnapshot(journal, config) @@ -171,6 +174,58 @@ export function hasUnverifiedJournalBaseline(config: string | null, profile: str return journal !== null && compareJournalState(journal, config, profile).unverified; } +/** Offline doctor evidence. Print only fixed file names and comparison results. */ +export function describeUnverifiedJournal(home: string): string[] { + const read = readCodexHomeJournal(join(home, CODEX_HOME_JOURNAL_FILE)); + if (read.kind === "missing") return []; + if (read.kind === "unknown") return ["Codex journal could not be read safely."]; + const journal = read.journal as unknown as Journal; + const validHash = (value: unknown) => typeof value === "string" && /^[0-9a-f]{64}$/.test(value); + if (journal.injectedConfigHash !== undefined && !validHash(journal.injectedConfigHash) + || journal.injectedProfileHash != null && !validHash(journal.injectedProfileHash)) { + return ["Codex journal contains invalid injected-state evidence."]; + } + if (journal.injectedConfigHash !== undefined && journal.injectedProfileHash !== undefined) return []; + for (const original of [journal.originalConfig, journal.originalProfile]) { + if (original !== null && Buffer.from(original, "base64").toString("base64") !== original) { + return ["Codex journal contains an unreadable original snapshot."]; + } + } + try { + assertCodexHomeOwner(home); + const unreadable: string[] = []; + const inspect = (name: "config.toml" | "opencodex.config.toml") => { + const path = join(home, name); + try { + const content = readBoundedCodexConfig(path); + if (content !== null || codexHomeIsAbsent(path)) return content; + } catch { + // Report only the fixed filename, including when the filesystem error contains a path. + } + unreadable.push(`${name} could not be read safely.`); + }; + const config = inspect("config.toml"); + const profile = inspect("opencodex.config.toml"); + if (config === undefined || profile === undefined) return unreadable; + const comparison = compareJournalState(journal, config, profile); + if (!comparison.unverified) return []; + const describe = (file: string, current: string | null, original: string | null, recorded: boolean) => { + let state = current === original ? "matches original" : "differs from original"; + if (current === null) state = original === null ? "absent in both states" : "now absent"; + else if (original === null) state = "created since original"; + return `${file}: ${state}. Injected state ${recorded ? "recorded" : "not recorded"}.`; + }; + return [ + describe("config.toml", config, comparison.originalConfig, comparison.configHashKnown), + describe("opencodex.config.toml", profile, comparison.originalProfile, comparison.profileHashKnown), + "Keep the current files and opencodex-journal.json. Compare the saved originals with the current files before choosing a recovery baseline.", + ]; + } catch (error) { + if (error instanceof CodexHomeOwnerRefusal) return [error.message]; + return ["Codex journal comparison unavailable."]; + } +} + /** What a plain native restore's journal step would do to config.toml and the profile. */ export type JournalRestorePreview = | { kind: "none" } diff --git a/structure/codex-home.md b/structure/codex-home.md index e522ef79d02..d7b922378e0 100644 --- a/structure/codex-home.md +++ b/structure/codex-home.md @@ -74,7 +74,7 @@ without a backup. The original backup, historical user-selected settings and ses Journal restoration compares config and profile independently against their saved originals and recorded injected hashes. Restore never reverts a `config.toml` change made after injection (bound as INV-RESTORE-02 in [overview](overview.md), `tests/codex-integration/codex-restore-later-edits.test.ts`): the saved original is replayed whole only over bytes identical to the first injected file; stop strips owned fields, and disconnect, start and mismatched-client recovery take the three-way owned-field restore, so a changed file keeps every later edit or the recovery refuses and keeps both files. Every OpenCodex publication of `config.toml` goes through `publishCodexConfigIfUnchanged` in `src/codex/inject/config-write-section.ts`, which refuses retryably, writing nothing, when the file no longer holds the bytes the decision was computed from (the lock's inode witness alone missed in-place writers); the comparison runs immediately before the rename, so an in-place write landing between the two is still replaced. Failure compensation in `src/codex/inject-coordination.ts` reverts or removes `config.toml` only while it still holds exactly the bytes judged to be this section's own publication; a native `codex` child's publication is recorded by re-reading after the child exits, so a non-OpenCodex write landing between the child's rename and that read counts as OpenCodex's. Start and client recovery that hit such a refusal keep the journal and retry on the next start. The journal's `injectedRootHistory` records every root routing URL injections under it wrote, so a Codex app write-back of an earlier injection's URL is stripped and re-pointed instead of being snapshotted as the user's. Disconnect additionally restores matching owned fields through `src/codex/journal-config-restore.ts`, preserving later model, hooks, trusted-project and Computer Use path edits. New journals capture owned-field spans; older hash-backed journals use their recorded URLs/catalog/default values and refuse ambiguous blocks or changed routing values. Owned provider/profile paths reserialized as inline or dotted TOML are detected and refused when field-level removal cannot be proved, preserving both config and recovery journal. Retry an interrupted `rotation: recovery-required` disconnect with `ocx disconnect` (retain `--keep-catalog` if initially used); credential or ownership conflicts remain refusals. If either changed artifact lacks its injected hash, the config/profile pair and journal remain untouched and the result is explicitly unverified; callers must not -convert that refusal into successful fallback cleanup. Already-original bytes need no rewrite, +convert that refusal into successful fallback cleanup. For an unverified pair, `ocx doctor` compares each artifact with the original and reports whether the journal recorded its injected state. It names each artifact that fails its bounded read and prints only fixed filenames and status text. Already-original bytes need no rewrite, and absence is distinct from an empty file. The injector checks a retained hashless journal against the same `baselineContent` it snapshots, plus the current profile, before writing or assigning a new injected hash. Native content can establish a fresh snapshot; routed content cannot promote an diff --git a/tests/codex-integration/codex-journal.test.ts b/tests/codex-integration/codex-journal.test.ts index 56ebd5c0fbe..c438ee24864 100644 --- a/tests/codex-integration/codex-journal.test.ts +++ b/tests/codex-integration/codex-journal.test.ts @@ -11,6 +11,7 @@ import { } from "../../src/codex/subagent-defaults"; import { SPAWN_BUDGET_MS } from "../helpers/test-budget"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { describeUnverifiedJournal } from "../../src/codex/journal"; const repoRoot = dirname(fileURLToPath(new URL("../../package.json", import.meta.url))); @@ -40,6 +41,37 @@ describe("codex-journal", () => { removeTreeWithRetry(testDir); }); + test("journal diagnosis distinguishes empty, absent, recorded and unreadable artifacts", () => { + const path = join(testDir, "opencodex-journal.json"); + const original = readFileSync(join(testDir, "config.toml")).toString("base64"); + const record = { version: 1, originalConfig: original, originalProfile: "", injectedConfigHash: "a".repeat(64) }; + writeFileSync(path, JSON.stringify(record)); + expect(describeUnverifiedJournal(testDir).slice(0, 2)).toEqual([ + "config.toml: matches original. Injected state recorded.", + "opencodex.config.toml: now absent. Injected state not recorded.", + ]); + writeFileSync(join(testDir, "opencodex.config.toml"), ""); + expect(describeUnverifiedJournal(testDir)).toEqual([]); + writeFileSync(path, JSON.stringify({ ...record, injectedConfigHash: "invalid" })); + expect(describeUnverifiedJournal(testDir)).toEqual(["Codex journal contains invalid injected-state evidence."]); + writeFileSync(path, JSON.stringify({ ...record, originalConfig: "???" })); + expect(describeUnverifiedJournal(testDir)).toEqual(["Codex journal contains an unreadable original snapshot."]); + }); + + test("journal diagnosis names each unreadable current file", () => { + writeFileSync(join(testDir, "opencodex-journal.json"), JSON.stringify({ + version: 1, originalConfig: "", originalProfile: null, + })); + mkdirSync(join(testDir, "opencodex.config.toml")); + expect(describeUnverifiedJournal(testDir)).toEqual(["opencodex.config.toml could not be read safely."]); + + writeFileSync(join(testDir, "config.toml"), Buffer.alloc(1024 * 1024 + 1)); + expect(describeUnverifiedJournal(testDir)).toEqual([ + "config.toml could not be read safely.", + "opencodex.config.toml could not be read safely.", + ]); + }); + test("writeJournal creates journal file", () => { const r = runScript(testDir, ` const { writeJournal } = require("./src/codex/journal"); diff --git a/tests/codex-integration/doctor.test.ts b/tests/codex-integration/doctor.test.ts index d9e7d5e039b..e960bc5302c 100644 --- a/tests/codex-integration/doctor.test.ts +++ b/tests/codex-integration/doctor.test.ts @@ -6,7 +6,7 @@ import * as desktopSupervision from "../../src/service/desktop-supervision.mjs"; import * as cliHelp from "../../src/cli/help"; import { getDefaultConfig } from "../../src/config"; import { spawn, spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { homedir, tmpdir } from "node:os"; import { @@ -90,6 +90,38 @@ describe("doctor", () => { if (existsSync(TEST_DIR)) removeTreeWithRetry(TEST_DIR); }); + test("offline doctor explains a hashless routed journal without exposing or changing either state", async () => { + const configPath = join(TEST_CODEX_HOME, "config.toml"); + const journalPath = join(TEST_CODEX_HOME, "opencodex-journal.json"); + const original = "# private original comment\n"; + const current = '# Auto-injected by opencodex\nopenai_base_url = "http://127.0.0.1:10100/v1"\n# private later edit\n'; + const journal = JSON.stringify({ version: 1, originalConfig: Buffer.from(original).toString("base64"), + originalProfile: null, pid: 99, owner: { kind: "process", pid: 99 } }); + writeFileSync(configPath, current); + writeFileSync(journalPath, journal); + const lines: string[] = []; + const log = spyOn(console, "log").mockImplementation((...args) => { lines.push(args.join(" ")); }); + const fetch = spyOn(globalThis, "fetch").mockImplementation(async () => new Response(null, { status: 503 })); + const live = spyOn(proxyLiveness, "findLiveProxy").mockResolvedValue(null); + const previousExitCode = process.exitCode; + try { + await runDoctor([]); + const output = lines.join("\n"); + expect(output).toContain("config.toml: differs from original. Injected state not recorded."); + expect(output).toContain("opencodex.config.toml: absent in both states. Injected state not recorded."); + expect(output).not.toContain("private original comment"); + expect(output).not.toContain("private later edit"); + expect(readFileSync(configPath, "utf8")).toBe(current); + expect(readFileSync(journalPath, "utf8")).toBe(journal); + expect(existsSync(join(TEST_CODEX_HOME, "opencodex.config.toml"))).toBe(false); + } finally { + process.exitCode = previousExitCode; + live.mockRestore(); + fetch.mockRestore(); + log.mockRestore(); + } + }, STORE_BUDGET_MS); + test("path report flips auth.json/config.json from absent to present", () => { let rows = collectPaths(); const auth = () => rows.find(r => r.label === "CODEX_HOME/auth.json")!; From 6cf8cea2c82546e689f6205fb4cd5402b71aa90a Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Fri, 4 Dec 2026 00:00:39 +0900 Subject: [PATCH 16/50] fix(build): embed standalone workers without rewriting the checkout (#9276) * fix(build): embed standalone workers without writing into the source checkout * test(quota): keep budget fixtures valid across reset dates Carry the verified fixture corrections from lidge-jun/opencodex#9265 into #9276. Pin Mistral observations within the fixture period and keep the Kimi reset in the future without changing production behavior or expected results. (cherry picked from commit d97f06f1a76e0ce72fbced9933ac569b6e06d3e9) (cherry picked from commit 4499f63096d51a46160eeb21f504c7a6828320e7) * test(routing): isolate Home route subprocess lifecycle locks Fix the client_lifecycle_busy and Home route 500 failures exposed by the build PR's changed-test lane. Carry the two reviewed fixture corrections from lidge-jun/opencodex#9279 and use the same real SQLite lifecycle-lock isolation in the four adjacent Home/Child scenario harnesses. Assert that lock acquisitions stay inside each fixture and that representative writes acquire the expected lifecycle database. Existing route assertions and production locking behavior are preserved. A private SQLite contention probe reproduces failure before isolation and success after it. Use the existing ci:full label for full Ubuntu shard validation, including the native Codex cases blocked by this local container's /tmp ownership guard. (cherry picked from commit 30d9b1e9311082d69b105b2f19e31a6c777f816f) (cherry picked from commit a812fae6ca36a372e2925d25ea088a3ca252d7e6) --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- scripts/build-standalone.ts | 44 +++++--------- scripts/standalone-targets.ts | 2 +- src/generated/worker-bundles.gen.ts | 5 +- src/lib/worker-embed.ts | 2 +- structure/ops/docs-and-release.md | 2 +- tests/gui/standalone-build-script.test.ts | 59 ++++++++++++++++++- tests/routing/route-to-child-defaults.test.ts | 7 ++- tests/routing/route-to-home-decisions.test.ts | 7 ++- .../routing/route-to-home-live-flags.test.ts | 7 ++- .../routing/route-to-home-sync-review.test.ts | 7 ++- 10 files changed, 100 insertions(+), 42 deletions(-) diff --git a/scripts/build-standalone.ts b/scripts/build-standalone.ts index 1c104a5c2c6..785f17f7247 100644 --- a/scripts/build-standalone.ts +++ b/scripts/build-standalone.ts @@ -41,9 +41,7 @@ const WORKER_ENTRIES: Record = { "request-history-rebuild-worker": join(repoRoot, "src", "routing", "history", "rebuild-worker.ts"), "windows-native-principal-worker": join(repoRoot, "src", "lib", "windows-native-principal-worker.ts"), }; -const GEN_FILE = join(repoRoot, "src", "generated", "worker-bundles.gen.ts"); -const GEN_PLACEHOLDER = `// Generated by scripts/build-standalone.ts — do not edit by hand.\n// Placeholder for source checkouts; standalone builds overwrite this file\n// with pre-bundled worker sources before compiling.\nexport const WORKER_BUNDLES: Record = {};\n`; -const bundleLines: string[] = []; +const workerBundles: Record = {}; const workerOut = join(output, ".worker-bundles"); for (const [key, entry] of Object.entries(WORKER_ENTRIES)) { const bundled = Bun.spawnSync([process.execPath, "build", entry, "--target", "bun", "--outdir", workerOut], { @@ -52,34 +50,20 @@ for (const [key, entry] of Object.entries(WORKER_ENTRIES)) { }); if (bundled.exitCode !== 0) process.exit(bundled.exitCode ?? 1); const name = `${basename(entry, ".ts")}.js`; - bundleLines.push(` ${JSON.stringify(key)}: ${JSON.stringify(readFileSync(join(workerOut, name), "utf8"))},`); + workerBundles[key] = readFileSync(join(workerOut, name), "utf8"); } -writeFileSync( - GEN_FILE, - `// Generated by scripts/build-standalone.ts — do not edit by hand.\nexport const WORKER_BUNDLES: Record = {\n${bundleLines.join("\n")}\n};\n`, -); - -// The generated bundles only exist while the compile below consumes them. -// Always restore the empty placeholder afterwards — success or failure — so -// source-checkout runs and tests keep spawning workers from source files -// instead of a stale committed bundle. -function restoreGenPlaceholder(): void { - writeFileSync(GEN_FILE, GEN_PLACEHOLDER); -} - -const compileArgs = [process.execPath, "build", "--compile"]; -// Cross-compiling to the host target produces a binary the kernel kills on -// launch; only pass --target when it differs from the host. -if (target !== hostTarget()) compileArgs.push("--target", target); -compileArgs.push(join(repoRoot, "src", "cli", "index.ts"), "--outfile", executable); -// process.exit() skips `finally`, so exit only after the placeholder is back. -let compileExitCode: number; -try { - compileExitCode = Bun.spawnSync(compileArgs, { stdout: "inherit", stderr: "inherit" }).exitCode ?? 1; -} finally { - restoreGenPlaceholder(); -} -if (compileExitCode !== 0) process.exit(compileExitCode); +// Override only the compiler's view. The tracked placeholder can be open in a +// source process or another target's build for the entire compile. +await Bun.build({ + entrypoints: [join(repoRoot, "src", "cli", "index.ts")], + target: "bun", + files: { + [join(repoRoot, "src", "generated", "worker-bundles.gen.ts")]: + `export const WORKER_BUNDLES = ${JSON.stringify(workerBundles)};\n`, + }, + // Explicitly cross-compiling for the host can yield an unlaunchable binary. + compile: target === hostTarget() ? { outfile: executable } : { target, outfile: executable }, +}); // N-API binaries cannot execute from Bun's virtual `$bunfs`. Keep the exact target addon outside // the compiled executable so source/npm resolution and packaged resolution share one binding API. diff --git a/scripts/standalone-targets.ts b/scripts/standalone-targets.ts index 27b9a635b1e..be9594efb5a 100644 --- a/scripts/standalone-targets.ts +++ b/scripts/standalone-targets.ts @@ -12,7 +12,7 @@ export const standaloneTargets = [ "bun-linux-arm64", ] as const; -export function isStandaloneTarget(value: string): boolean { +export function isStandaloneTarget(value: string): value is typeof standaloneTargets[number] { return (standaloneTargets as readonly string[]).includes(value); } diff --git a/src/generated/worker-bundles.gen.ts b/src/generated/worker-bundles.gen.ts index a1a928011a7..3ab99563790 100644 --- a/src/generated/worker-bundles.gen.ts +++ b/src/generated/worker-bundles.gen.ts @@ -1,4 +1,3 @@ -// Generated by scripts/build-standalone.ts — do not edit by hand. -// Placeholder for source checkouts; standalone builds overwrite this file -// with pre-bundled worker sources before compiling. +// Source checkouts load workers from their original entrypoints. Standalone +// compilation supplies the bundled worker table through Bun's virtual files. export const WORKER_BUNDLES: Record = {}; diff --git a/src/lib/worker-embed.ts b/src/lib/worker-embed.ts index 7ff393c4822..aac106ea4c9 100644 --- a/src/lib/worker-embed.ts +++ b/src/lib/worker-embed.ts @@ -6,7 +6,7 @@ * additional entrypoints keep their nested paths, so `new Worker(new URL(...))` * dies with ModuleNotFound in compiled binaries. Standalone builds therefore * embed each worker as a pre-bundled source string (generated by - * scripts/build-standalone.ts into src/generated/worker-bundles.gen.ts) and + * scripts/build-standalone.ts as a virtual worker-bundles.gen.ts module) and * spawn it from a Blob URL, which works in both compiled binaries and source * checkouts. Source checkouts without generated bundles fall back to the * dev-mode URL form. diff --git a/structure/ops/docs-and-release.md b/structure/ops/docs-and-release.md index de16d10b66f..c9fde8975e5 100644 --- a/structure/ops/docs-and-release.md +++ b/structure/ops/docs-and-release.md @@ -418,7 +418,7 @@ dispatches ordinary runs only, so a resume is dispatched by hand. The `package-standalone` job in `.github/workflows/release.yml` also builds Bun compiled `ocx` archives for Linux, macOS, and Windows, bundles `gui/dist`, smoke-tests `/healthz`, and -publishes SHA-256 sidecars for the attach job. Each archive also carries the target-matching +publishes SHA-256 sidecars for the attach job. The compiler receives the bundled worker table as a virtual module; successful and failed builds preserve the source checkout's worker placeholder. Each archive also carries the target-matching `@napi-rs/keyring` native addon under `keyring/`; the macOS release installs both optional Darwin packages so its separate arm64 and x64 builds cannot silently reuse the hosted runner's architecture. Desktop preparation copies those same pinned assets into Tauri resources. The loader and packaged-app proof are owned by the [desktop keyring contract](../desktop-shell.md#packaged-native-keyring-binding). diff --git a/tests/gui/standalone-build-script.test.ts b/tests/gui/standalone-build-script.test.ts index 4a04129920f..e4012b442f2 100644 --- a/tests/gui/standalone-build-script.test.ts +++ b/tests/gui/standalone-build-script.test.ts @@ -1,4 +1,10 @@ import { expect, test } from "bun:test"; +import { copyFileSync, createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { SPAWN_BUDGET_MS } from "../helpers/test-budget"; import { repoPath } from "../helpers/repo-root"; const script = await Bun.file(repoPath("scripts", "build-standalone.ts")).text(); @@ -15,9 +21,58 @@ test("standalone build script exposes supported targets and packaging contract", "bun-linux-x64", "bun-linux-arm64", ]) expect(targets).toContain(target); - expect(script).toContain("--compile"); - expect(script).toContain("--outfile"); expect(script).toContain("gui/dist"); expect(script).toContain("stageStandaloneKeyringAddon"); expect(script).toContain("SHA256SUMS"); }); + +test("standalone compilation embeds a working worker without touching the checkout on success or failure", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-standalone-workers-")); + function put(path: string, contents: string): string { + const file = join(root, path); + mkdirSync(dirname(file), { recursive: true }); + writeFileSync(file, contents); + return file; + } + function build(directory: string) { + return Bun.spawnSync([process.execPath, "scripts/build-standalone.ts", "--out", directory], { cwd: root, timeout: SPAWN_BUDGET_MS }); + } + try { + put("scripts/build-standalone.ts", script); + put("scripts/standalone-targets.ts", targets); + put("scripts/standalone-keyring.ts", "export function stageStandaloneKeyringAddon() {}"); + put("gui/dist/index.html", "fixture"); + const original = "export const WORKER_BUNDLES = {}; // local edits survive the build\n"; + const generated = put("src/generated/worker-bundles.gen.ts", original); + for (const worker of ["storage/policy-worker", "storage/restore-worker", "codex/history-worker", + "codex/cli-update-worker", "routing/history/rebuild-worker", "lib/windows-native-principal-worker"]) { + put(`src/${worker}.ts`, `postMessage(${JSON.stringify(worker)});\n`); + } + copyFileSync(repoPath("src", "lib", "worker-embed.ts"), join(root, "src", "lib", "worker-embed.ts")); + const main = put("src/cli/index.ts", ` + import { spawnWorker } from "../lib/worker-embed"; + const guard = setTimeout(() => process.exit(2), 5000); + const worker = spawnWorker("missing://source-must-not-be-used", "policy-worker"); + worker.onmessage = event => { console.log(event.data); clearTimeout(guard); worker.terminate(); }; + `); + const built = build("success"); + expect(built.exitCode, built.stderr.toString().slice(-2000)).toBe(0); + expect(readFileSync(generated, "utf8")).toBe(original); + const name = process.platform === "win32" ? "ocx.exe" : "ocx"; + const binary = join(root, "success", name); + const result = Bun.spawnSync([binary], { cwd: root, timeout: 10000 }); + expect(result.exitCode).toBe(0); + expect(result.stdout.toString().trim()).toBe("storage/policy-worker"); + const hash = createHash("sha256"); + for await (const chunk of createReadStream(binary)) hash.update(chunk); + expect(readFileSync(join(root, "success", "SHA256SUMS"), "utf8")).toBe(`${hash.digest("hex")} ${name}\n`); + expect(readFileSync(join(root, "success", "gui", "dist", "index.html"), "utf8")).toBe("fixture"); + + writeFileSync(main, 'import "./unresolvable-standalone-dependency";'); + expect(build("failure").exitCode).not.toBe(0); + expect(existsSync(join(root, "failure", "SHA256SUMS"))).toBe(false); + expect(readFileSync(generated, "utf8")).toBe(original); + } finally { + removeTreeWithRetry(root); + } +}, SPAWN_BUDGET_MS); diff --git a/tests/routing/route-to-child-defaults.test.ts b/tests/routing/route-to-child-defaults.test.ts index 60e846d20c4..7fbe1a7b323 100644 --- a/tests/routing/route-to-child-defaults.test.ts +++ b/tests/routing/route-to-child-defaults.test.ts @@ -19,7 +19,7 @@ function scenario(body: string) { const child = spawnSync(process.execPath, ["--eval", ` import { expect } from 'bun:test'; import { existsSync, writeFileSync } from 'node:fs'; - import { join } from 'node:path'; + import { join, resolve, sep } from 'node:path'; import { getDefaultConfig, saveConfig, loadConfig } from './src/config'; import { setIntegrationEnabled } from './src/codex/desired-state'; import { setHomeIntegrationEnabled } from './src/routing/home-route-capture'; @@ -35,6 +35,8 @@ function scenario(body: string) { import { readRouteIntentState, routeIntentStatePath } from './src/routing/route-intent-state'; import { setPersistedConfigMutationBeforeCommitForTests } from './src/config/persisted-mutation'; import { dispatchCommand } from './src/cli/dispatch'; + import { isolateClientLifecycleLock } from './tests/helpers/client-lifecycle-lock'; + const clientLifecycle = isolateClientLifecycleLock(process.env.HOME); writeFileSync(join(process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR,'_meta.json'),JSON.stringify({entries:[]})); const local = getDefaultConfig(); local.port=18274; local.hostname='127.0.0.1'; local.defaultProvider='fixture';local.providers={fixture:{adapter:'openai-chat',baseUrl:'http://127.0.0.1:1/v1',allowPrivateNetwork:true,liveModels:false,models:['fixture-model']}}; @@ -67,6 +69,8 @@ function scenario(body: string) { } finally { console.log = log; console.error = error; } }; ${body} + const clientLockPaths = clientLifecycle.acquisitions.map(({ path }) => path); + expect(clientLockPaths.filter(path => !path.startsWith(resolve(process.env.HOME) + sep))).toEqual([]); `], { cwd: repoRoot(), encoding: "utf8", timeout: SPAWN_BUDGET_MS - 5_000, env: { ...process.env, HOME: home, USERPROFILE: home, CODEX_HOME: join(home, ".codex"), CODEX_SQLITE_HOME: join(home, ".codex"), OPENCODEX_HOME: join(home, ".opencodex"), @@ -84,6 +88,7 @@ test("ocx restore on an upgraded linked Home with no saved route intent keeps Ch expect((await childIntent()).codex).toEqual({ enabled: true }); // A later initialization captures nothing from the Home-only change. expect((await call('/api/route-to', { client: 'pi', action: 'off' })).status).toBe(200); + expect(clientLifecycle.acquisitions.map(({ path }) => path)).toContain(join(process.env.HOME, 'locks', 'lifecycle.sqlite')); expect(readRouteIntentState().defaults.codex).toEqual({ enabled: true }); expect((await childIntent()).codex).toEqual({ enabled: true }); `), SPAWN_BUDGET_MS); diff --git a/tests/routing/route-to-home-decisions.test.ts b/tests/routing/route-to-home-decisions.test.ts index 020a8cc1126..3df239992dc 100644 --- a/tests/routing/route-to-home-decisions.test.ts +++ b/tests/routing/route-to-home-decisions.test.ts @@ -19,7 +19,7 @@ function scenario(body: string) { const child = spawnSync(process.execPath, ["--eval", ` import { expect } from 'bun:test'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; - import { join } from 'node:path'; + import { join, resolve, sep } from 'node:path'; import { getDefaultConfig, saveConfig, loadConfig } from './src/config'; import { writeLinkStore } from './src/link/store'; import { linkStorePath } from './src/link/paths'; @@ -34,6 +34,8 @@ function scenario(body: string) { import { applyIntegration } from './src/integrations/writer'; import { createIntegrationStateStore } from './src/integrations/store'; import { INTEGRATION_CLIENTS } from './src/integrations/registry'; + import { isolateClientLifecycleLock } from './tests/helpers/client-lifecycle-lock'; + const clientLifecycle = isolateClientLifecycleLock(process.env.HOME); writeFileSync(join(process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR,'_meta.json'),JSON.stringify({entries:[]})); const local = getDefaultConfig(); local.port=18274; local.hostname='127.0.0.1'; local.defaultProvider='fixture';local.providers={fixture:{adapter:'openai-chat',baseUrl:'http://127.0.0.1:1/v1',allowPrivateNetwork:true,liveModels:false,models:['fixture-model']}}; @@ -69,6 +71,8 @@ function scenario(body: string) { }; const asideRouted = () => !!JSON.parse(readFileSync(asideModels, 'utf8')).providers.opencodex; ${body} + const clientLockPaths = clientLifecycle.acquisitions.map(({ path }) => path); + expect(clientLockPaths.filter(path => !path.startsWith(resolve(process.env.HOME) + sep))).toEqual([]); `], { cwd: repoRoot(), encoding: "utf8", timeout: SPAWN_BUDGET_MS - 5_000, env: { ...process.env, HOME: home, USERPROFILE: home, CODEX_HOME: join(home, ".codex"), CODEX_SQLITE_HOME: join(home, ".codex"), OPENCODEX_HOME: join(home, ".opencodex"), @@ -90,6 +94,7 @@ test("on an upgraded linked Home a dashboard toggle leaves the Children's file d expect(readRouteIntentState().defaults.pi).toEqual({ enabled: false }); expect(readRouteIntentState().devices.home?.pi).toEqual({ enabled: true }); expect((await homeSync('pi'))?.outcome).toBe('current'); + expect(clientLifecycle.acquisitions.map(({ path }) => path)).toContain(join(process.env.HOME, 'locks', 'lifecycle.sqlite')); expect(piRouted()).toBe(true); expect(readRouteIntentState().defaults.pi).toEqual({ enabled: false }); expect((await childIntent()).pi).toEqual({ enabled: false }); diff --git a/tests/routing/route-to-home-live-flags.test.ts b/tests/routing/route-to-home-live-flags.test.ts index 4e8917df599..13dccaa38a0 100644 --- a/tests/routing/route-to-home-live-flags.test.ts +++ b/tests/routing/route-to-home-live-flags.test.ts @@ -18,7 +18,7 @@ function scenario(body: string) { const child = spawnSync(process.execPath, ["--eval", ` import { expect } from 'bun:test'; import { existsSync, readFileSync, writeFileSync } from 'node:fs'; - import { join } from 'node:path'; + import { join, resolve, sep } from 'node:path'; import { getDefaultConfig, saveConfig, loadConfig } from './src/config'; import { commitClaudeCodeBlock } from './src/claude/claude-code-block'; import { setIntegrationEnabled } from './src/codex/desired-state'; @@ -27,6 +27,8 @@ function scenario(body: string) { import { applyProtocolSettingsPatch } from './src/server/management/protocol-settings-patch'; import { readHomeRouteIntentState } from './src/routing/home-route-intent'; import { readRouteIntentState, setRouteClientIntent, writeRouteIntentState } from './src/routing/route-intent-state'; + import { isolateClientLifecycleLock } from './tests/helpers/client-lifecycle-lock'; + const clientLifecycle = isolateClientLifecycleLock(process.env.HOME); const library = process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR; writeFileSync(join(library,'_meta.json'),JSON.stringify({entries:[]})); const local = getDefaultConfig(); local.port=18274; local.hostname='127.0.0.1'; @@ -53,6 +55,8 @@ function scenario(body: string) { const codexConfig = () => existsSync(join(process.env.CODEX_HOME,'config.toml')) ? readFileSync(join(process.env.CODEX_HOME,'config.toml'),'utf8') : ''; const homeRow = (body, client) => body.devices.find(row => row.id === 'home').clients.find(row => row.client === client); ${body} + const clientLockPaths = clientLifecycle.acquisitions.map(({ path }) => path); + expect(clientLockPaths.filter(path => !path.startsWith(resolve(process.env.HOME) + sep))).toEqual([]); `], { cwd: repoRoot(), encoding: "utf8", timeout: SPAWN_BUDGET_MS - 5_000, env: { ...process.env, HOME: home, USERPROFILE: home, CODEX_HOME: join(home, ".codex"), CODEX_SQLITE_HOME: join(home, ".codex"), OPENCODEX_HOME: join(home, ".opencodex"), @@ -65,6 +69,7 @@ function scenario(body: string) { const restoreAndMessagesOff = ` // The first route operation captures the Home defaults (Codex and Claude on). expect((await call('/api/route-to', { client: 'pi', action: 'off' })).status).toBe(200); + expect(clientLifecycle.acquisitions.map(({ path }) => path)).toContain(join(process.env.HOME, 'locks', 'lifecycle.sqlite')); expect(readHomeRouteIntentState(loadConfig()).defaults.codex).toEqual({ enabled: true }); expect(readHomeRouteIntentState(loadConfig()).defaults.claude).toEqual({ enabled: true }); // ocx restore turns Codex off; Messages off turns Claude Code off. Neither records route intent. diff --git a/tests/routing/route-to-home-sync-review.test.ts b/tests/routing/route-to-home-sync-review.test.ts index 63e193c2071..0df870fd64d 100644 --- a/tests/routing/route-to-home-sync-review.test.ts +++ b/tests/routing/route-to-home-sync-review.test.ts @@ -21,7 +21,7 @@ function scenario(body: string) { const child = spawnSync(process.execPath, ["--eval", ` import { expect } from 'bun:test'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; - import { join } from 'node:path'; + import { join, resolve, sep } from 'node:path'; import { getDefaultConfig, saveConfig, loadConfig } from './src/config'; import { writeLinkStore } from './src/link/store'; import { linkStorePath } from './src/link/paths'; @@ -38,6 +38,8 @@ function scenario(body: string) { import { applyIntegration } from './src/integrations/writer'; import { createIntegrationStateStore } from './src/integrations/store'; import { INTEGRATION_CLIENTS } from './src/integrations/registry'; + import { isolateClientLifecycleLock } from './tests/helpers/client-lifecycle-lock'; + const clientLifecycle = isolateClientLifecycleLock(process.env.HOME); writeFileSync(join(process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR,'_meta.json'),JSON.stringify({entries:[]})); const local = getDefaultConfig(); local.port=18274; local.hostname='127.0.0.1'; local.defaultProvider='fixture';local.providers={fixture:{adapter:'openai-chat',baseUrl:'http://127.0.0.1:1/v1',allowPrivateNetwork:true,liveModels:false,models:['fixture-model']}}; @@ -73,6 +75,8 @@ function scenario(body: string) { }; const asideRouted = () => !!JSON.parse(readFileSync(asideModels, 'utf8')).providers.opencodex; ${body} + const clientLockPaths = clientLifecycle.acquisitions.map(({ path }) => path); + expect(clientLockPaths.filter(path => !path.startsWith(resolve(process.env.HOME) + sep))).toEqual([]); `], { cwd: repoRoot(), encoding: "utf8", timeout: SPAWN_BUDGET_MS - 5_000, env: { ...process.env, HOME: home, USERPROFILE: home, CODEX_HOME: join(home, ".codex"), CODEX_SQLITE_HOME: join(home, ".codex"), OPENCODEX_HOME: join(home, ".opencodex"), @@ -103,6 +107,7 @@ const unresolvedHome = ` test("a full route-to sync on unresolved Aside reports the other clients and Aside as unresolved, with the recovery warning", () => scenario(unresolvedHome + ` const synced = await call('/api/route-to/sync', {}); expect(synced.status).toBe(200); + expect(clientLifecycle.acquisitions.map(({ path }) => path)).toContain(join(process.env.HOME, 'locks', 'lifecycle.sqlite')); const home = synced.body.devices.find(row => row.id === 'home'); expect(home.clients.find(row => row.client === 'aside')).toEqual({ client: 'aside', intent: 'unresolved', source: 'default', applied: null }); expect(home.clients.find(row => row.client === 'pi')).toMatchObject({ intent: 'on', applied: 'current' }); From 18728dab83bfbe0fd1f04d3be4293acae0f22ac7 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Fri, 4 Dec 2026 00:00:47 +0900 Subject: [PATCH 17/50] fix(history): refuse legacy relabels when rollout evidence is incomplete (#9292) * fix(history): refuse legacy relabels when rollout evidence is incomplete * test(quota): keep history PR budget fixtures valid across reset dates Carry the verified quota-clock corrections from lidge-jun/opencodex#9265 into #9292. The changed-test lane reported four Mistral reset-classification failures and three Kimi monthly-window failures after the fixture reset date passed. Keep all existing assertions and restore the clock after each test. (cherry picked from commit d97f06f1a76e0ce72fbced9933ac569b6e06d3e9) (cherry picked from commit 4499f63096d51a46160eeb21f504c7a6828320e7) * docs(history): state the terminating newline requirement for legacy relabels --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- .../docs/es/reference/cli/lifecycle.md | 2 + .../docs/fr/reference/cli/lifecycle.md | 2 + .../docs/ja/reference/cli/lifecycle.md | 2 + .../docs/ko/reference/cli/lifecycle.md | 2 + .../content/docs/reference/cli/lifecycle.md | 5 + .../docs/ru/reference/cli/lifecycle.md | 2 + .../docs/tr/reference/cli/lifecycle.md | 2 + .../docs/zh-cn/reference/cli/lifecycle.md | 2 + .../docs/zh-tw/reference/cli/lifecycle.md | 2 + src/codex/history-provider.ts | 71 ++++++++---- structure/codex-home.md | 2 +- .../codex-history-provider.test.ts | 105 ++++++++++++++++++ 12 files changed, 174 insertions(+), 25 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 4705aeb930e..7f6b961092d 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -185,6 +185,8 @@ Recuperación explícita para versiones de desarrollo anteriores que volvieron a Este es un reetiquetado amplio y destructivo: cada hilo de mensaje de usuario etiquetado actualmente `opencodex` se cambia a `openai`, `exec` se normaliza a `cli` y se establece el marcador de evento. Eso incluye la historia legítima de proveedores dedicados. Realice una copia de seguridad del estado y ejecútelo solo cuando se pretenda ese alcance completo. +La comprobación previa se detiene antes de reetiquetar y muestra `history_rollout_uninspectable` si el historial de un hilo solo existe en formato `.jsonl.zst`, si el último registro no termina con un salto de línea o si no se puede determinar el formato de los últimos registros al leer hasta 16 MiB. Conserve los archivos existentes. Este comando no reconstruye el índice de conversaciones de la aplicación móvil. + ### `ocx recover-history --ocx-compaction --yes` Repare un hilo que se compactó a través de un proveedor enrutado antes de reanudarlo a través del Codex nativo. El comando lee el subproceso exacto seleccionado por UUID, guarda una copia de seguridad privada de byte por byte y, a continuación, convierte solo el estado de compactación `ocx1:` / `ocx2:` propiedad de OpenCodeX en un resumen sencillo que el Codex nativo puede reproducir. El contenido cifrado nativo y otros hilos se dejan sin cambios. Cierre el subproceso seleccionado antes de ejecutar el comando; un cambio de implementación concurrente hace que la recuperación se detenga sin reemplazar el archivo. diff --git a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md index 24a67794a74..f3f1805ce77 100644 --- a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md @@ -85,6 +85,8 @@ Récupération explicite destinée aux anciennes versions de développement qui Il s'agit d'un réétiquetage large et destructif : chaque fil contenant un message utilisateur et actuellement marqué `opencodex` passe à `openai`, `exec` est normalisé en `cli` et l'indicateur d'événement est activé. L'historique légitime d'un fournisseur dédié est également concerné. Sauvegardez l'état et n'exécutez la commande que si vous souhaitez cette portée complète. +La vérification préalable s’arrête avant le réétiquetage et signale `history_rollout_uninspectable` si l’historique d’un fil n’existe qu’au format `.jsonl.zst`, si le dernier enregistrement ne se termine pas par un saut de ligne ou si la lecture des 16 derniers Mio ne permet pas de déterminer le format des derniers enregistrements. Conservez les fichiers en place. Cette commande ne reconstruit pas l’index des conversations de l’application mobile. + ### `ocx recover-history --ocx-compaction --yes` Réparez l'historique d'une tâche compactée par un fournisseur routé avant de la reprendre avec Codex natif. La commande sélectionne exactement une tâche par UUID, enregistre d'abord une sauvegarde privée octet par octet, puis convertit uniquement l'état de compaction `ocx1:`/`ocx2:` propre à OpenCodeX en résumé ordinaire relisible par Codex natif. Le contenu chiffré natif et les autres tâches restent inchangés. Fermez la tâche sélectionnée avant d'exécuter la commande ; toute modification simultanée du rollout interrompt la récupération sans remplacer le fichier. diff --git a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md index 88442c08a12..a42d736caa1 100644 --- a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md @@ -75,6 +75,8 @@ ocx eject back これは広範囲で破壊的な再ラベル付けです。ユーザーメッセージを持ち、現在 `opencodex` とタグ付けされているすべてのスレッドを `openai` に変更し、`exec` を `cli` に正規化してイベントマーカーを設定します。正当な専用プロバイダー履歴も対象です。状態をバックアップし、この全範囲を意図する場合にのみ実行してください。 +スレッドの履歴が `.jsonl.zst` 形式でしか残っていない場合、最後のレコードの末尾に改行がない場合、または末尾から最大 16 MiB を読み取ってもレコードの形式を判定できない場合は、事前チェックで `history_rollout_uninspectable` が表示され、ラベルを変更する前に処理が停止します。既存のファイルはそのままにしてください。このコマンドはモバイルアプリの会話インデックスを再構築しません。 + ### `ocx recover-history --ocx-compaction --yes` ルーティングされたプロバイダーで圧縮されたタスクをネイティブ Codex で再開する前に、その履歴を修復します。このコマンドは UUID で 1 つのタスクだけを選択し、非公開のバイト単位バックアップを保存してから、OpenCodeX 所有の `ocx1:`/`ocx2:` 圧縮状態だけをネイティブ Codex が再生できる通常の要約に変換します。ネイティブの暗号化コンテンツと他のタスクは変更しません。実行前に対象タスクを閉じてください。処理中に rollout が変更された場合、ファイルを置き換えずに修復を中止します。 diff --git a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md index bc026ac04bf..dc793f3aca0 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -118,6 +118,8 @@ ocx eject back thread를 `openai`로 바꾸고, `exec`를 `cli`로 정규화하며 event marker를 설정합니다. 정상적인 dedicated-provider history도 포함됩니다. 상태를 백업하고 이 전체 범위를 의도한 경우에만 실행하세요. +스레드 기록이 `.jsonl.zst`로만 남아 있거나, 마지막 레코드 끝에 줄바꿈이 없거나, 파일 끝에서 최대 16 MiB를 읽어도 마지막 레코드의 형식을 판별할 수 없으면, 사전 검사에서 `history_rollout_uninspectable`을 표시하고 태그를 바꾸기 전에 중단합니다. 기존 파일은 그대로 두세요. 이 명령으로 모바일 앱의 대화 색인을 다시 만들 수는 없습니다. + ### `ocx recover-history --ocx-compaction --yes` 라우팅된 provider를 통해 압축된 작업을 native Codex에서 다시 열기 전에 해당 기록을 복구합니다. 이 명령은 UUID로 정확히 하나의 작업을 선택하고 비공개 바이트 단위 백업을 저장한 뒤, OpenCodeX가 소유한 `ocx1:`/`ocx2:` 압축 상태만 native Codex가 재생할 수 있는 일반 요약으로 변환합니다. native 암호화 콘텐츠와 다른 작업은 변경하지 않습니다. 실행 전에 선택한 작업을 닫으십시오. 처리 중 rollout이 변경되면 파일을 교체하지 않고 복구를 중단합니다. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index b997ac9cee6..630f2801c76 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -379,6 +379,11 @@ changed to `openai`, `exec` is normalized to `cli`, and the event marker is set. legitimate dedicated-provider history. Back up the state and run it only when that full scope is intended. +Preflight stops before relabeling and reports `history_rollout_uninspectable` if a thread’s history +exists only as `.jsonl.zst`, the last record lacks a terminating newline, or the final records +cannot be classified within the 16 MiB read limit. +Leave the existing files in place. This command does not rebuild the mobile conversation index. + ### `ocx recover-history --ocx-compaction --yes` Repair one thread that was compacted through a routed provider before resuming it through native diff --git a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md index 5d31678324e..dbf658e5062 100644 --- a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md @@ -113,6 +113,8 @@ ocx eject back устанавливается. Корректная история выделенного провайдера тоже входит в охват. Сначала сделайте резервную копию и запускайте команду только если нужен весь этот охват. +Если история треда сохранилась только в формате `.jsonl.zst`, после последней записи нет перевода строки или по последним 16 МиБ файла нельзя определить формат записей, предварительная проверка выдаст `history_rollout_uninspectable` и остановит команду до изменения меток. Сохраните исходные файлы на месте. Эта команда не перестраивает индекс бесед мобильного приложения. + ### `ocx recover-history --ocx-compaction --yes` Исправьте историю одной задачи, сжатой через маршрутизируемого провайдера, перед её возобновлением в нативном Codex. Команда выбирает ровно одну задачу по UUID, сначала сохраняет приватную побайтовую резервную копию, а затем преобразует только принадлежащее OpenCodeX состояние сжатия `ocx1:`/`ocx2:` в обычную сводку, которую может воспроизвести нативный Codex. Нативное зашифрованное содержимое и другие задачи не изменяются. Перед запуском закройте выбранную задачу; если rollout изменится во время обработки, восстановление остановится без замены файла. diff --git a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md index 9ef0865b6ae..f3c9b5639cb 100644 --- a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md @@ -111,6 +111,8 @@ Bu, geniş kapsamlı ve yıkıcı bir yeniden etiketlemedir: kullanıcı iletisi olarak normalleştirilir ve event marker ayarlanır. Geçerli dedicated-provider geçmişi de kapsama dahildir. Durumu yedekleyin ve yalnızca bu kapsamın tamamını istiyorsanız çalıştırın. +Bir konuşmanın geçmişi yalnızca `.jsonl.zst` biçiminde bulunuyorsa, son kaydın sonunda satır sonu karakteri yoksa veya dosyanın sonundan en fazla 16 MiB okunduğunda son kayıtların biçimi belirlenemiyorsa ön denetim `history_rollout_uninspectable` hatası verir ve etiketleme başlamadan komut durur. Mevcut dosyaları yerinde bırakın. Bu komut mobil uygulamanın konuşma dizinini yeniden oluşturmaz. + ### `ocx recover-history --ocx-compaction --yes` Yönlendirilmiş bir sağlayıcı üzerinden sıkıştırılmış bir görevi yerel Codex ile sürdürmeden önce geçmişini onarın. Komut UUID ile yalnızca bir görevi seçer, önce özel ve bayt bayt bir yedek kaydeder, ardından yalnızca OpenCodeX'e ait `ocx1:`/`ocx2:` sıkıştırma durumunu yerel Codex'in yeniden oynatabileceği düz bir özete dönüştürür. Yerel şifreli içerik ve diğer görevler değişmeden kalır. Komutu çalıştırmadan önce seçili görevi kapatın; işlem sırasında rollout değişirse kurtarma dosyayı değiştirmeden durur. diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md index c064870f2c5..71d8de7a8b0 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md @@ -74,6 +74,8 @@ ocx eject back 这是范围很广且具有破坏性的重标记:所有包含用户消息且当前标记为 `opencodex` 的线程都会改标为 `openai`,`exec` 会规范化为 `cli`,并设置事件标记。正常的专用提供方历史记录也在范围内。请先备份状态,并且仅在确实需要这一完整范围时执行。 +如果某个线程的历史记录只剩 `.jsonl.zst` 文件、最后一条记录末尾没有换行符,或从文件末尾读取最多 16 MiB 仍无法判定末尾记录的格式,预检会报告 `history_rollout_uninspectable`,并在更改标签前停止。请保留现有文件。此命令不会重建移动应用的对话索引。 + ### `ocx recover-history --ocx-compaction --yes` 在通过原生 Codex 恢复某个曾由路由提供方压缩的任务前,修复该任务的历史记录。此命令按 UUID 精确选择一个任务,先保存私有的逐字节备份,然后仅将 OpenCodeX 自有的 `ocx1:`/`ocx2:` 压缩状态转换为原生 Codex 可重放的普通摘要。原生加密内容和其他任务保持不变。运行前请关闭所选任务;如果 rollout 在处理期间发生变化,恢复会停止且不会替换原文件。 diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md index 2425eeca438..6fa0ca8b76f 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md @@ -71,6 +71,8 @@ ocx eject back 這是範圍很廣且具破壞性的重新標記:所有含有使用者訊息且目前標記為 `opencodex` 的 thread 都會改標為 `openai`,`exec` 會正規化為 `cli`,並設定 event marker。正常的專用 provider 歷史也包含在內。請先備份狀態,而且只有在確實需要這個完整範圍時才執行。 +如果某個討論串的歷史記錄只剩 `.jsonl.zst` 檔案、最後一筆記錄末尾沒有換行字元,或從檔案末端讀取最多 16 MiB 仍無法判定末端記錄的格式,預先檢查會回報 `history_rollout_uninspectable`,並在變更標籤前停止。請保留現有檔案。此指令不會重建行動應用程式的對話索引。 + ### `ocx recover-history --ocx-compaction --yes` 在透過原生 Codex 恢復曾由路由提供方壓縮的工作前,修復該工作的歷史記錄。此命令依 UUID 精確選取一個工作,先儲存私有的逐位元組備份,然後只把 OpenCodeX 自有的 `ocx1:`/`ocx2:` 壓縮狀態轉換成原生 Codex 可重播的普通摘要。原生加密內容與其他工作不會變更。執行前請關閉所選工作;若 rollout 在處理期間發生變化,復原會停止且不會取代原始檔案。 diff --git a/src/codex/history-provider.ts b/src/codex/history-provider.ts index 38511fd04c1..42652da23a6 100644 --- a/src/codex/history-provider.ts +++ b/src/codex/history-provider.ts @@ -200,29 +200,36 @@ function readFirstRolloutLine(fd: number): string | null { * after such a migration carries an ordinal, so the newest records are where * the evidence is. * - * One read of a fixed window from EOF, split once. An earlier draft grew the - * window chunk by chunk and re-decoded the accumulated buffer on every - * iteration, which is quadratic: a rollout whose only `session_meta` sits at - * the top would have decoded and split up to the whole window ~256 times. The - * window is a cap, not a target — it is not walked and it is not the file. - * - * Returns `null` only when the file cannot be measured, which the caller - * treats as an unreadable record rather than a writable rollout. + * Inspect records touching the last 1 MiB, including the record crossing + * its left boundary. A short compensating metadata append can follow it. */ const ROLLOUT_TAIL_WINDOW_BYTES = 1 << 20; +const MAX_ROLLOUT_TAIL_BYTES = 1 << 24; function readRolloutTailCompleteLines(fd: number): string[] | null { const size = Number(fstatSync(fd).size); - if (!Number.isFinite(size) || size < 0) return null; - if (size === 0) return []; - const start = Math.max(0, size - ROLLOUT_TAIL_WINDOW_BYTES); + if (!Number.isSafeInteger(size) || size <= 0) return null; + let start = Math.max(0, size - ROLLOUT_TAIL_WINDOW_BYTES); + const floor = Math.max(0, size - MAX_ROLLOUT_TAIL_BYTES - 1); + let step = 4096; + while (start > floor) { + const length = Math.min(start - floor, step); + start -= length; + const prefix = Buffer.alloc(length); + if (readSync(fd, prefix, 0, length, start) !== length) return null; + const newline = prefix.lastIndexOf(0x0a); + if (newline !== -1) { + start += newline + 1; + break; + } + step *= 2; + } + if (size - start > MAX_ROLLOUT_TAIL_BYTES) return null; const window = Buffer.alloc(size - start); - const read = readSync(fd, window, 0, window.length, start); - if (read === 0) return []; - const lines = window.subarray(0, read).toString("utf8").split("\n"); - // Unless the window reached BOF, the first element starts mid-record (and - // possibly mid-codepoint), so it is not a complete line. - return (start === 0 ? lines : lines.slice(1)).filter(line => line.length > 0); + if (readSync(fd, window, 0, window.length, start) !== window.length) return null; + // The writer appends a JSON line without a leading separator. + if (window.at(-1) !== 0x0a) return null; + return window.toString("utf8").split("\n").filter(line => line.length > 0); } function planFirstLineProvider(firstLine: string, expectedId: string, provider: string): FirstLineProviderPlan { @@ -393,8 +400,25 @@ let historyAppendHooks: { } | undefined; export function setHistoryAppendHooksForTests(hooks: typeof historyAppendHooks): void { historyAppendHooks = hooks; } +function hasLegacyRolloutFile(path: string): boolean { + if (!path) return false; + if (existsSync(path)) { + if (path.endsWith(".jsonl.zst")) throw new CodexHistoryIntegrityError("history_rollout_uninspectable"); + return true; + } + // Codex can retain the plain path in SQLite while storing its compressed sibling. + if (path.endsWith(".jsonl") && existsSync(path + ".zst")) { + throw new CodexHistoryIntegrityError("history_rollout_uninspectable"); + } + return false; +} + +function tolerateMissingRollout(error: unknown, path: string): void { + if ((error as NodeJS.ErrnoException)?.code !== "ENOENT" || hasLegacyRolloutFile(path)) throw error; +} + function assertLegacyHistoryWritable(path: string, heldFd?: number): void { - if (!path || !existsSync(path)) return; + if (!hasLegacyRolloutFile(path)) return; const fd = heldFd ?? openSync(path, "r"); try { assertHistoryDescriptorIdentity(path, fd); @@ -407,8 +431,7 @@ function assertLegacyHistoryWritable(path: string, heldFd?: number): void { // cloned ordinal-0 append. Inspect a bounded window of the newest records // and refuse before any mutation of the rollout, the row, or the manifest. const tail = readRolloutTailCompleteLines(fd); - if (tail === null) throw new CodexHistoryIntegrityError("history_rollout_record_invalid"); - if (tail.length === 0) return; + if (!tail?.length) throw new CodexHistoryIntegrityError("history_rollout_uninspectable"); const last = tail[tail.length - 1]; if (!last) throw new CodexHistoryIntegrityError("history_rollout_record_invalid"); if (last !== first) assertLegacyHistoryRecord(last); @@ -1170,7 +1193,7 @@ function updateSessionMeta( expectedLatestSource?: string; } = {}, ): SessionMetaUpdateResult { - if (!path || !existsSync(path)) return { changed: false, durableProvider: false }; + if (!hasLegacyRolloutFile(path)) return { changed: false, durableProvider: false }; const validatedIdentity = lstatSync(path, { bigint: true }); if (options.expectedFileIdentity !== undefined && historyFileIdentity(path) !== options.expectedFileIdentity) { @@ -1314,7 +1337,7 @@ function relabelAllRoutedHistoryToOpenai(db: Database): { rows: number; files: n source: row.source === "exec" ? "cli" : undefined, }).changed) files++; } catch (error) { - if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error; + tolerateMissingRollout(error, row.rollout_path); } } @@ -1528,14 +1551,14 @@ function syncCodexHistoryProviderUnsafe(provider: CodexHistoryProvider, stateDbP try { if (updateSessionMeta(row.rollout_path, row.id, { provider: "opencodex" }).changed) files++; } catch (error) { - if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error; + tolerateMissingRollout(error, row.rollout_path); } } for (const row of execRows) { try { if (updateSessionMeta(row.rollout_path, row.id, { source: "cli" }).changed) files++; } catch (error) { - if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error; + tolerateMissingRollout(error, row.rollout_path); } } }); diff --git a/structure/codex-home.md b/structure/codex-home.md index d7b922378e0..c0ff113ae35 100644 --- a/structure/codex-home.md +++ b/structure/codex-home.md @@ -549,7 +549,7 @@ The [probe contract](codex-prompts.md#prompt-text-probe) governs prompt capture ## Paginated history writer boundary -`src/codex/history-provider.ts` rejects provider-history changes with `history_paginated_requires_native_writer` when a target begins with an ordinal-bearing record, later contains a paginated record after a legacy start (#4311), or declares `history_mode=paginated`. The first line alone is not sufficient: a rollout that started unnumbered and was later migrated is also refused. Apply, manifest-backed restore, and explicit legacy recovery preflight all selected targets before changing database rows or manifests. The append boundary checks again. Codex owns ordinal allocation and the live projection cursor; reading the last ordinal and appending N+1 is not safe concurrent coordination. Legacy unnumbered rollouts retain their existing behavior. History Worker targets resolve the canonical manifest first and an existing pre-normalization Windows filename second, so passing an explicit target cannot bypass upgrade recovery. This guard prevents the observed stable-format corruption; it does not implement native-writer integration. Stop history writes also follow the [lifecycle ownership boundary](runtime.md), including H/C serialization for the Worker and synchronous exit. +`src/codex/history-provider.ts` rejects provider-history changes with `history_paginated_requires_native_writer` when a target begins with an ordinal-bearing record, later contains a paginated record after a legacy start (#4311), or declares `history_mode=paginated`. On legacy schemas, `history_rollout_uninspectable` blocks relabeling when only the compressed rollout exists, the trailing records cannot be classified within 16 MiB, or the final record lacks its terminating newline. The tail check normally covers the last 1 MiB. Apply, manifest-backed restore, and explicit legacy recovery preflight all selected targets before changing database rows or manifests. The append boundary checks again. Codex owns ordinal allocation and the live projection cursor; reading the last ordinal and appending N+1 is not safe concurrent coordination. Readable, newline-terminated unnumbered rollouts retain their existing behavior. History Worker targets resolve the canonical manifest first and an existing pre-normalization Windows filename second, so passing an explicit target cannot bypass upgrade recovery. This guard prevents the observed stable-format corruption; it does not implement native-writer integration. Stop history writes also follow the [lifecycle ownership boundary](runtime.md), including H/C serialization for the Worker and synchronous exit. Injection preflights affected history using the normalized config candidate before writing config/profile/journal, then checks again after the complete artifact write. Native restore also rechecks after successful journal restoration or fallback removal, while exact config/profile/journal preimages and any coordinated remove transaction remain available for compensation. diff --git a/tests/codex-integration/codex-history-provider.test.ts b/tests/codex-integration/codex-history-provider.test.ts index 3f9c994d5b9..c11e050c559 100644 --- a/tests/codex-integration/codex-history-provider.test.ts +++ b/tests/codex-integration/codex-history-provider.test.ts @@ -3,6 +3,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync import * as fs from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { zstdCompressSync } from "node:zlib"; import { Database } from "bun:sqlite"; import { afterEach, describe, expect, setDefaultTimeout, spyOn, test } from "bun:test"; import { classifyRecoverableHistoryError, countPendingOpencodexHistory, historyBackupPathFor, isRecoverableHistoryError, legacyHistoryBackupPathFor, migrateHistoryToOpenai, resolveExistingHistoryBackupPath, restoreLegacyOpenaiHistory, restoredUserEventFor, setAfterNoopPendingCountForTests, setAfterStrictHistoryRolloutAppendForTests, setBeforeHistoryApplyTransactionForTests, setBeforeHistoryBackupConsumeForTests, setBeforeStrictHistoryRolloutAppendForTests, setHistoryDbBusyTimeoutForTests, snapshotCodexHistoryNoop, syncCodexHistoryProvider, withHistoryRetry } from "../../src/codex/history-provider"; @@ -241,6 +242,110 @@ describe("Codex history provider sync", () => { expect(existsSync(fixture.backupPath)).toBe(false); }); + test.each(["compressed sibling", "large ordinal", "large ordinal before legacy metadata", "beyond inspection cap", "blank tail window"])("preflight and apply preserve history with %s", kind => { + const fixture = makeFixture(); + noopSnapshotArtifacts.add(join(fixture.dbPath, "..")); + const first = readFileSync(fixture.rollout, "utf8").split("\n")[0]!; + const compressed = kind === "compressed sibling"; + const large = kind === "beyond inspection cap" ? (1 << 24) : (1 << 20); + const last = { ordinal: 1, type: "event_msg", payload: { message: "x".repeat(compressed ? 1 : large) } }; + let trailer = ""; + if (kind === "large ordinal before legacy metadata") trailer = first + "\n"; + if (kind === "blank tail window") trailer = "\n".repeat(1 << 20); + const data = Buffer.from(first + "\n" + JSON.stringify(last) + "\n" + trailer); + const path = compressed ? fixture.rollout + ".zst" : fixture.rollout; + const original = compressed ? zstdCompressSync(data) : data; + if (compressed) rmSync(fixture.rollout); + writeFileSync(path, original); + const code = kind.startsWith("large ordinal") ? "history_paginated_requires_native_writer" : "history_rollout_uninspectable"; + expect(preflightCodexHistoryInjection(true, true, fixture.dbPath)).toBe(code); + expect(syncCodexHistoryProvider("opencodex", fixture.dbPath, fixture.backupPath)) + .toMatchObject({ rows: 0, files: 0, failed: true, integrityCode: code }); + expect(readFileSync(path).equals(original)).toBe(true); + if (compressed) expect(existsSync(fixture.rollout)).toBe(false); + expect(existsSync(fixture.backupPath)).toBe(false); + const db = new Database(fixture.dbPath, { readonly: true }); + try { + expect(db.query("SELECT model_provider FROM threads WHERE id='thread-1'").get()).toEqual({ model_provider: "openai" }); + } finally { db.close(); } + }); + + test.each([true, false])("direct compressed path during explicit legacy recovery (exists=%s)", present => { + const fixture = makeFixture({ includeLegacy: true }); + noopSnapshotArtifacts.add(join(fixture.dbPath, "..")); + const path = fixture.legacyRollout + ".zst"; + const original = zstdCompressSync(readFileSync(fixture.legacyRollout)); + if (present) writeFileSync(path, original); + rmSync(fixture.legacyRollout); + const db = new Database(fixture.dbPath); + try { + db.run("UPDATE threads SET rollout_path=? WHERE id='thread-3'", [path]); + const result = restoreLegacyOpenaiHistory(fixture.dbPath); + if (present) { + expect(result).toMatchObject({ rows: 0, files: 0, failed: true, integrityCode: "history_rollout_uninspectable" }); + expect(readFileSync(path).equals(original)).toBe(true); + } else { + expect(result).toMatchObject({ rows: 1, files: 0 }); + expect(existsSync(path)).toBe(false); + } + expect(db.query("SELECT model_provider FROM threads WHERE id='thread-3'").get()) + .toEqual({ model_provider: present ? "opencodex" : "openai" }); + } finally { db.close(); } + }); + + test("an unterminated legacy record cannot be joined to a metadata append", () => { + const fixture = makeFixture(); + noopSnapshotArtifacts.add(join(fixture.dbPath, "..")); + const original = readFileSync(fixture.rollout, "utf8").trimEnd(); + writeFileSync(fixture.rollout, original); + expect(syncCodexHistoryProvider("opencodex", fixture.dbPath, fixture.backupPath)) + .toMatchObject({ rows: 0, files: 0, failed: true, integrityCode: "history_rollout_uninspectable" }); + expect(readFileSync(fixture.rollout, "utf8")).toBe(original); + expect(existsSync(fixture.backupPath)).toBe(false); + }); + + test("compression between the file check and lstat rolls back the provider change", () => { + const fixture = makeFixture(); + noopSnapshotArtifacts.add(join(fixture.dbPath, "..")); + const compressed = zstdCompressSync(readFileSync(fixture.rollout)); + let armed = false; + let converted = false; + setBeforeHistoryApplyTransactionForTests(() => { armed = true; }); + const originalLstat = fs.lstatSync; + const stat = spyOn(fs, "lstatSync").mockImplementation(((path, options) => { + if (armed && !converted && path === fixture.rollout) { + writeFileSync(fixture.rollout + ".zst", compressed); + rmSync(fixture.rollout); + converted = true; + } + return originalLstat(path, options); + }) as typeof fs.lstatSync); + try { + expect(syncCodexHistoryProvider("opencodex", fixture.dbPath, fixture.backupPath)) + .toMatchObject({ failed: true, rows: 0, files: 0, integrityCode: "history_rollout_uninspectable" }); + } finally { stat.mockRestore(); } + expect(converted).toBe(true); + expect(readFileSync(fixture.rollout + ".zst").equals(compressed)).toBe(true); + expect(JSON.parse(readFileSync(fixture.backupPath, "utf8")).entries["thread-1"].relabel).toBe("pending"); + const db = new Database(fixture.dbPath, { readonly: true }); + try { + expect(db.query("SELECT model_provider FROM threads WHERE id='thread-1'").get()).toEqual({ model_provider: "openai" }); + } finally { db.close(); } + }); + + test.each(["metadata", "event"])("large unnumbered legacy %s remains routable", kind => { + const fixture = makeFixture(); + noopSnapshotArtifacts.add(join(fixture.dbPath, "..")); + const meta = JSON.parse(readFileSync(fixture.rollout, "utf8").split("\n")[0]!); + const large = "한".repeat(360_000); + const records = [meta]; + if (kind === "metadata") meta.payload.base_instructions = { text: large }; + else records.push({ type: "event_msg", payload: { message: large } }); + writeFileSync(fixture.rollout, records.map(record => JSON.stringify(record)).join("\r\n") + "\r\n"); + expect(syncCodexHistoryProvider("opencodex", fixture.dbPath, fixture.backupPath)).toMatchObject({ rows: 1, files: 1 }); + expect(latestSessionMetaPayload(fixture.rollout).model_provider).toBe("opencodex"); + }); + for (const marker of ["ordinal", "history_mode"] as const) { test(`refuses paginated ${marker} before routing any row or writing a manifest`, () => { const fixture = makeFixture(); From 72ab42099671cfe7320974c24535bb651889d8b0 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Fri, 4 Dec 2026 00:00:55 +0900 Subject: [PATCH 18/50] fix(update): show verified Windows stop refusals in dashboard jobs (#9281) * fix(update): report verified Windows stop failures in dashboard jobs * test(update): preserve worker file limits and stop fixture inputs * fix(update): name the stop deadline option for a budget refusal * test(advisor): wait for observed heartbeats before completing consultation Carry the verified fixture correction from lidge-jun/opencodex#9283 into #9281. Preserve heartbeat, continuation-order, and terminal-event assertions with bounded cleanup. (cherry picked from commit 6d07fbcf8d0497b8bb4eaced3a96e7f1da20122b) --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- bin/ocx.mjs | 11 +++- .../docs/es/troubleshooting/update-failed.md | 3 +- .../docs/tr/troubleshooting/update-failed.md | 4 +- .../docs/troubleshooting/update-failed.md | 8 ++- src/update/check-types.ts | 12 ++++ src/update/job.ts | 39 ++++++------- src/update/update-failure-guidance.d.mts | 7 +++ src/update/update-failure-guidance.mjs | 58 ++++++++++++++++++- structure/ops/update-supervised-recovery.md | 1 + tests/cli/ocx-launcher-source.test.ts | 2 +- tests/helpers/update-import-policy.ts | 4 +- tests/update/update-desktop-owner.test.ts | 1 + tests/update/update-home-worker.test.ts | 42 +++++++++++++- tests/update/update-job.test.ts | 2 +- .../update/update-recovery-boundaries.test.ts | 1 + .../update/update-stop-classification.test.ts | 49 ++++++++++++++++ tests/update/update-stop-first.test.ts | 4 +- 17 files changed, 209 insertions(+), 39 deletions(-) diff --git a/bin/ocx.mjs b/bin/ocx.mjs index a156f0fc00e..0e78ae3852e 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -69,7 +69,7 @@ import { } from "../src/update/npm-cache-preflight.mjs"; import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../src/update/tray-update-plan.mjs"; import { bootRestoreProbe, launcherUsableAfterNpmUpdate, transactionalNpmUpdate as transactionalNpmUpdateSync, transactionalNpmUpdateAsync } from "../src/update/transactional-install.mjs"; -import { manualUpdateFailureGuidance, npmUpdateFailureGuidance } from "../src/update/update-failure-guidance.mjs"; +import { dashboardStopMarker, manualUpdateFailureGuidance, npmUpdateFailureGuidance, takeDashboardStopToken } from "../src/update/update-failure-guidance.mjs"; import { captureCodexCliTransportEnv, CODEX_CLI_TRANSPORT_ENV_KEYS, @@ -84,6 +84,7 @@ import { } from "../src/update/supervised-recovery.mjs"; const PKG = "@bitkyc08/opencodex"; +const dashboardStopToken = takeDashboardStopToken(process.argv, process.platform); const UPDATE_RECOVERY_READY_MS = 30_000; const UPDATE_RECOVERY_POLL_MS = 100; const UPDATE_RECOVERY_SLEEP = new Int32Array(new SharedArrayBuffer(4)); @@ -933,8 +934,10 @@ async function runPackageManagerSelfUpdate(manager, child) { stopAttempted = true; console.log("⏹ Stopping the running proxy before updating..."); if (!homePolicy.authorizeMutation(serviceWasInstalled ? "service" : "runtime")) { releaseUpdateLease(); process.exit(1); } - const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, [launcher, "stop"], { - stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(), + const stopArgs = dashboardStopToken ? [launcher, "stop", "--json"] : [launcher, "stop"]; + const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, stopArgs, { + stdio: dashboardStopToken ? ["inherit", "pipe", "inherit"] : "inherit", encoding: "utf8", + windowsHide: true, env: mutationChildEnvironment(), }); const stillHasRuntimeState = existsSync(join(configDir(), "ocx.pid")) || existsSync(join(configDir(), "runtime-port.json")); @@ -965,6 +968,8 @@ async function runPackageManagerSelfUpdate(manager, child) { ? `opencodex: could not confirm the proxy on ${bakeHostname}:${bakePort} is stopped; aborting the update. Run 'ocx stop' and retry.` : "opencodex: could not stop the running proxy; aborting the update. Run 'ocx stop' and retry."); releaseUpdateLease(); + const marker = decision.reason === "stop-failed" && dashboardStopMarker(dashboardStopToken, stopRes); + if (marker) console.log("\n" + marker); // Node writes synchronously to the Windows dashboard's pipe. process.exit(1); } if (historyOnlyStop || historyRestoreIncomplete()) { diff --git a/docs-site/src/content/docs/es/troubleshooting/update-failed.md b/docs-site/src/content/docs/es/troubleshooting/update-failed.md index 05a6e559af3..6c79e803fce 100644 --- a/docs-site/src/content/docs/es/troubleshooting/update-failed.md +++ b/docs-site/src/content/docs/es/troubleshooting/update-failed.md @@ -27,7 +27,8 @@ ocx --version ocx status ``` -El trabajo del panel de control solo registra el estado de salida, ya que la propia salida del instalador puede contener rutas locales. La ejecución de `ocx update` en un terminal muestra el paso que falló y el siguiente paso a tomar. +En instalaciones de Windows con npm o pnpm, el panel puede indicar por qué se detuvo la actualización antes de reemplazar el paquete. El servicio puede informar que se denegó el acceso, que no se pudo leer su estado o el de un proceso, que no se pudo verificar el propietario del proceso de servicio o que faltó tiempo para confirmar la parada. Ejecuta `ocx stop` con la misma cuenta de Windows. Cuando confirme la parada, ejecuta `ocx update`. +Para otros fallos, ejecuta `ocx update` en un terminal para ver los detalles. El panel oculta la salida original del instalador porque puede contener rutas locales. diff --git a/docs-site/src/content/docs/tr/troubleshooting/update-failed.md b/docs-site/src/content/docs/tr/troubleshooting/update-failed.md index c88de504397..1c1f42bc61a 100644 --- a/docs-site/src/content/docs/tr/troubleshooting/update-failed.md +++ b/docs-site/src/content/docs/tr/troubleshooting/update-failed.md @@ -30,8 +30,8 @@ ocx --version ocx status ``` -Kurulum çıktısı yerel yollar içerebildiği için pano işi yalnızca çıkış durumunu -kaydeder. Terminalde `ocx update` çalıştırmak başarısız adımı ve sonraki işlemi gösterir. +Windows'ta npm veya pnpm ile kurulum yapıldıysa pano, paket değiştirilmeden önce güncellemenin neden durduğunu gösterebilir. Hizmet durdurulurken erişim reddedilmiş, hizmet veya işlem durumu okunamamış, sarmalayıcı işlemin sahipliği doğrulanamamış ya da durdurmayı doğrulamak için yeterli süre kalmamış olabilir. Aynı Windows hesabında `ocx stop` çalıştırın. Hizmetin durduğu doğrulandıktan sonra `ocx update` çalıştırın. +Diğer hatalarda ayrıntıları görmek için terminalde `ocx update` çalıştırın. Kurulum çıktısı yerel yollar içerebildiğinden pano ham çıktıyı göstermez. ## Güncellemeyi tamamlama diff --git a/docs-site/src/content/docs/troubleshooting/update-failed.md b/docs-site/src/content/docs/troubleshooting/update-failed.md index c6894268b2d..2cc945074e1 100644 --- a/docs-site/src/content/docs/troubleshooting/update-failed.md +++ b/docs-site/src/content/docs/troubleshooting/update-failed.md @@ -36,8 +36,12 @@ ocx --version ocx status ``` -The dashboard job only records the exit status, because the installer's own output can contain local -paths. Running `ocx update` in a terminal shows the step that failed and the next step to take. +For Windows npm and pnpm installs, a dashboard update can stop before replacing the package. +If the service stop reports access denied, unreadable service or process state, unverified wrapper +ownership, or insufficient time to verify the stop, the dashboard shows that reason. Run `ocx stop` +in the same Windows account. Once it confirms the stop, run `ocx update`. +For other failures, run `ocx update` in a terminal for details. The dashboard withholds raw +installer output because it can contain local paths. ## Finish the update diff --git a/src/update/check-types.ts b/src/update/check-types.ts index 64aa41b0e14..5f534362f8b 100644 --- a/src/update/check-types.ts +++ b/src/update/check-types.ts @@ -1,5 +1,17 @@ import type { Channel, Installer, InstallOwnership } from "./index"; +export interface UpdateCheckResult { + currentVersion: string; + latestVersion: string | null; + channel: Channel; + installer: Installer; + updateAvailable: boolean; + canUpdate: boolean; + command: string; + releaseNotesUrl: string; + reason?: string; +} + export interface UpdateCheckDeps { currentVersion: () => string; detectInstall: () => Installer; diff --git a/src/update/job.ts b/src/update/job.ts index 1498e451daa..68af2e8a869 100644 --- a/src/update/job.ts +++ b/src/update/job.ts @@ -41,14 +41,15 @@ import { resolveCurrentPnpmGlobalOwner, resolvePnpmActiveLauncher, } from "./index"; -import type { UpdateCheckDeps } from "./check-types"; +import type { UpdateCheckDeps, UpdateCheckResult } from "./check-types"; import { managedReleaseDirectory } from "./managed-release"; -export type { UpdateCheckDeps } from "./check-types"; +export type { UpdateCheckDeps, UpdateCheckResult } from "./check-types"; import type { PnpmGlobalOwner } from "./pnpm-global-install.mjs"; import { isNewer } from "./notify"; import { isRealBunBinary } from "../lib/bun-binary-validator.mjs"; import { planWindowsTrayUpdate } from "./tray-update-plan.mjs"; -import { GUI_UPDATE_FAILURE_NEXT_STEP } from "./update-failure-guidance.mjs"; +import { DASHBOARD_STOP_ARG, dashboardStopFailureMessage, GUI_UPDATE_FAILURE_NEXT_STEP, readDashboardStopReason } from "./update-failure-guidance.mjs"; +import type { StopServiceReason } from "../cli/stop-report"; import { npmCachePreflightFailureMessage, runNpmCachePreflight, @@ -81,18 +82,6 @@ export const RESTART_PORT_RECLAIM_MS = 30_000; export type UpdateJobStatus = "running" | "restarting" | "succeeded" | "failed"; -export interface UpdateCheckResult { - currentVersion: string; - latestVersion: string | null; - channel: Channel; - installer: Installer; - updateAvailable: boolean; - canUpdate: boolean; - command: string; - releaseNotesUrl: string; - reason?: string; -} - export interface UpdateJobState { id: string; status: UpdateJobStatus; @@ -715,15 +704,20 @@ function runLoggedCommand( env?: NodeJS.ProcessEnv, authorizeMutation: UpdateMutationAuthorizer = () => false, kind: Parameters[0] = "runtime", -): { status: number | null; signal: NodeJS.Signals | null; timedOut: boolean } { + io?: Pick, +): { status: number | null; signal: NodeJS.Signals | null; timedOut: boolean; stopReason?: StopServiceReason | null } { job = updateJob(job, {}, `$ ${formatCommand(bin, args)}`); if (!authorizeMutation(kind)) return { status: 1, signal: null, timedOut: false }; - const result = guardedSpawnSync(authorizeMutation, kind, bin, args, { + const captureStop = kind === "package" && (io?.platform ?? process.platform) === "win32" + && usesNodeLauncher(job.installer) && args.at(-1) === "--update-worker-result" && !args.includes("--update-package-only"); + const token = captureStop ? crypto.randomUUID().replaceAll("-", "") : null; + const spawnArgs = token ? [...args, DASHBOARD_STOP_ARG + token] : args; + const result = guardedSpawnSync(authorizeMutation, kind, bin, spawnArgs, { encoding: "utf8", timeout, windowsHide: true, ...(env ? { env } : {}), - }); + }, io?.spawnUpdateFn); const stdout = typeof result.stdout === "string" ? result.stdout.trim() : ""; const stderr = typeof result.stderr === "string" ? result.stderr.trim() : ""; const summary = summarizeCommandOutput(stdout, stderr, result.status, result.signal); @@ -732,6 +726,7 @@ function runLoggedCommand( status: result.status, signal: result.signal, timedOut: (result.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT", + stopReason: readDashboardStopReason(token, result), }; } @@ -1766,6 +1761,7 @@ async function confirmPackageManagerExplicitRestart( * observable: a failed pre-flight must leave `runCommand` untouched. */ export interface GuiUpdateWorkerIo { + spawnUpdateFn?: typeof import("node:child_process").spawnSync; cachePreflightFn?: () => { ok: boolean; reason: string }; /** Force the resolved update target. A source checkout otherwise aborts before the update branch. */ checkForUpdateFn?: (channel: Channel) => ReturnType; @@ -1791,7 +1787,7 @@ export interface GuiUpdateWorkerIo { args: string[], timeout: number, env?: NodeJS.ProcessEnv, - ) => { status: number | null; signal: NodeJS.Signals | null }; + ) => { status: number | null; signal: NodeJS.Signals | null; stopReason?: StopServiceReason | null }; } export async function runGuiUpdateWorker( jobId: string, @@ -1925,7 +1921,7 @@ export async function runGuiUpdateWorker( const updateEnv = restart ? withUpdateTeardownHandover(process.env) : withoutUpdateTeardownHandover(process.env); // Raw package-manager lanes cannot carry the baseline argv; the parent rechecks it at the boundary. if (!homePolicy.authorizeMutation("package")) { refuseWorkerHome(); return; } - const result = (io.runCommandFn ?? runLoggedCommand)(job, cmd.bin, cmd.args, UPDATE_TIMEOUT_MS, updateEnv, homePolicy.authorizeMutation, "package"); + const result = (io.runCommandFn ?? runLoggedCommand)(job, cmd.bin, cmd.args, UPDATE_TIMEOUT_MS, updateEnv, homePolicy.authorizeMutation, "package", io); if (packageOnlyUpdateSucceeded(cmd, result.status, homePolicy.packageOnly)) { homePolicy.check({ kind: "unknown" }); if (!homePolicy.authorizeMutation("package-publish")) { refuseWorkerHome(); return; } @@ -1945,7 +1941,8 @@ export async function runGuiUpdateWorker( status: "failed", exitCode: result.status, signal: result.signal, - error: `update command failed (${result.status ?? "?"}). ${GUI_UPDATE_FAILURE_NEXT_STEP}`, + error: (result.stopReason && dashboardStopFailureMessage(result.stopReason)) + || `update command failed (${result.status ?? "?"}). ${GUI_UPDATE_FAILURE_NEXT_STEP}`, }); return; } diff --git a/src/update/update-failure-guidance.d.mts b/src/update/update-failure-guidance.d.mts index ff1bafb4c4f..ff695577199 100644 --- a/src/update/update-failure-guidance.d.mts +++ b/src/update/update-failure-guidance.d.mts @@ -12,3 +12,10 @@ export function npmUpdateFailureGuidance(failure: { tag?: string; }): { previousVersionKept: boolean; lines: string[] }; export const GUI_UPDATE_FAILURE_NEXT_STEP: string; +type StopReason = import("../cli/stop-report").StopServiceReason; +type ChildResult = { status: number | null; signal: string | null; stdout: unknown; error?: unknown }; +export const DASHBOARD_STOP_ARG: string; +export function takeDashboardStopToken(argv: string[], platform: string): string | null; +export function dashboardStopMarker(token: string | null, result: ChildResult): string | null; +export function readDashboardStopReason(token: string | null, result: ChildResult): StopReason | null; +export function dashboardStopFailureMessage(reason: unknown): string | null; diff --git a/src/update/update-failure-guidance.mjs b/src/update/update-failure-guidance.mjs index 6d701498145..06477b113a4 100644 --- a/src/update/update-failure-guidance.mjs +++ b/src/update/update-failure-guidance.mjs @@ -65,8 +65,62 @@ export function npmUpdateFailureGuidance({ phase, rolledBack, pkgName, version, } /** - * The dashboard job only sees the launcher's exit status; its output is withheld because it can - * carry local paths. Point at the terminal, where the launcher prints the phase-specific step. + * Generic dashboard failures retain the launcher's exit status. Its output can carry local + * paths, so point at the terminal where the launcher prints the phase-specific step. */ export const GUI_UPDATE_FAILURE_NEXT_STEP = "Run 'ocx update' in a terminal to see the reason and the exact recovery step."; + +const stopMessages = new Map([ + ["access-denied", "Windows denied access during the service stop."], + ["evidence-unreadable", "OpenCodex could not read the Windows service or process state needed to verify the stop."], + ["unbound-wrapper", "OpenCodex could not verify ownership of the Windows service wrapper."], + ["unverified-budget", "The remaining time was insufficient to verify the Windows service stop."], +]); +export const DASHBOARD_STOP_ARG = "--ocx-dashboard-stop="; + +// The worker appends this private argument after logging the public command. Consume it +// before the launcher starts children. Older launchers ignore the argument and construct +// their own stop and package-manager argv; neither receives the worker's correlation value. +export function takeDashboardStopToken(argv, platform) { + const arg = argv.at(-1); + if (platform !== "win32" || argv[2] !== "update" || !argv.includes("--update-worker-result") + || typeof arg !== "string" || !arg.startsWith(DASHBOARD_STOP_ARG)) return null; + const token = arg.slice(DASHBOARD_STOP_ARG.length); + if (!/^[0-9a-f]{32}$/.test(token)) return null; + argv.pop(); + return token; +} + +/** Only the stdout of the launcher's own stop --json child is a stop report. */ +export function dashboardStopMarker(token, result) { + if (!token || result.status !== 1 || result.signal || result.error + || typeof result.stdout !== "string" || result.stdout.length > 8192) return null; + try { + const report = JSON.parse(result.stdout); + if (report?.schema === "ocx-stop/1" && report.ok === false && report.outcome === "failed" + && report.exitCode === 1 && stopMessages.has(report.serviceStopReason)) { + return `ocx-dashboard-pre-stop/1 ${token} ${report.serviceStopReason}`; + } + } catch { /* Old or malformed output keeps the generic update failure. */ } + return null; +} + +export function readDashboardStopReason(token, result) { + if (!token || result.status !== 1 || result.signal || result.error || typeof result.stdout !== "string") return null; + const stdout = result.stdout.trimEnd(); + const line = stdout.slice(stdout.lastIndexOf("\n") + 1); + for (const reason of stopMessages.keys()) { + if (line === `ocx-dashboard-pre-stop/1 ${token} ${reason}`) return reason; + } + return null; +} + +export function dashboardStopFailureMessage(reason) { + const message = stopMessages.get(reason); + if (!message) return null; + const stop = reason === "unverified-budget" + ? "Run 'ocx stop --deadline-ms ' with a longer total deadline" + : "Run 'ocx stop'"; + return `Update stopped before package replacement. ${message} ${stop} in the same Windows account. Once the stop is verified, run 'ocx update'.`; +} diff --git a/structure/ops/update-supervised-recovery.md b/structure/ops/update-supervised-recovery.md index dcafec4dcda..d5ad9702734 100644 --- a/structure/ops/update-supervised-recovery.md +++ b/structure/ops/update-supervised-recovery.md @@ -66,6 +66,7 @@ invokes on a later event. Synchronous updater/report callbacks run before their The worker prepares its latest stored job snapshot, directory and serialized payload before the success-write adapter in `src/update/job.ts`; publishing `succeeded` without an authorizer refuses even when reached through an ordinary job-store helper. +For a Windows npm or pnpm dashboard update, the Node launcher attaches a per-invocation marker to a checked pre-update stop refusal. The marker carries only a recognized `serviceStopReason` from its own failed `ocx stop --json` child. The worker renders fixed guidance for a matching marker and keeps raw stop and installer output out of the job record. The adapter carries the same synchronous gate through the atomic writer's `validateBeforeRename` hook, after temp preparation and before every native rename attempt, including Windows retries. Runtime PID termination similarly authorizes each actual signal: diff --git a/tests/cli/ocx-launcher-source.test.ts b/tests/cli/ocx-launcher-source.test.ts index 3d9e453348d..5de4506791e 100644 --- a/tests/cli/ocx-launcher-source.test.ts +++ b/tests/cli/ocx-launcher-source.test.ts @@ -222,7 +222,7 @@ test("Desktop supervision is freshly checked before Node stop and both package-m expect(source.match(/createSupervisionLatch\(\)/g)).toHaveLength(1); const initial = source.indexOf("supervision: observeSupervision()", source.indexOf("const initialOwnership")); const gate = source.indexOf("const preStopPlan = planUpdateRuntimeHandling({"); - const stop = source.indexOf('const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, [launcher, "stop"]'); + const stop = source.indexOf('const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, stopArgs'); const npm = source.indexOf("const tx = await transactionalNpmUpdate({"); const pnpm = source.indexOf("const update = runPnpmGlobalUpdate({"); expect(initial).toBeGreaterThan(0); expect(gate).toBeGreaterThan(initial); diff --git a/tests/helpers/update-import-policy.ts b/tests/helpers/update-import-policy.ts index 1411d206368..550cdeabd3e 100644 --- a/tests/helpers/update-import-policy.ts +++ b/tests/helpers/update-import-policy.ts @@ -52,7 +52,7 @@ const baseStaticImports: Readonly> = { "import { npmCachePreflightFailureMessage, resolveNpmCachePath, runNpmCachePreflight, } from \"../src/update/npm-cache-preflight.mjs\";", "import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from \"../src/update/tray-update-plan.mjs\";", "import { bootRestoreProbe, launcherUsableAfterNpmUpdate, transactionalNpmUpdate as transactionalNpmUpdateSync, transactionalNpmUpdateAsync } from \"../src/update/transactional-install.mjs\";", - "import { manualUpdateFailureGuidance, npmUpdateFailureGuidance } from \"../src/update/update-failure-guidance.mjs\";", + "import { dashboardStopMarker, manualUpdateFailureGuidance, npmUpdateFailureGuidance, takeDashboardStopToken } from \"../src/update/update-failure-guidance.mjs\";", "import { captureCodexCliTransportEnv, CODEX_CLI_TRANSPORT_ENV_KEYS, CODEX_CLI_VERSION_MANAGER_ROOT_ENV_SLOTS, codexCliInspectionLookupSeeds, carriesCodexCliUpdateInspectionContext, isCodexCliUpdateInspectionArgv, } from \"../src/update/codex-cli-update-launch-policy.mjs\";", "import { freshServingPid, hasRestartableServiceManager, readParentPid, readServiceManagerPid, restartServiceManagerJob, supervisionVerdict, unsettledManagerWarning, unsupervisedRuntimeWarning, } from \"../src/update/supervised-recovery.mjs\";" ], @@ -196,7 +196,7 @@ const baseStaticImports: Readonly> = { "import { isNewer } from \"./notify\";", "import { isRealBunBinary } from \"../lib/bun-binary-validator.mjs\";", "import { planWindowsTrayUpdate } from \"./tray-update-plan.mjs\";", - "import { GUI_UPDATE_FAILURE_NEXT_STEP } from \"./update-failure-guidance.mjs\";", + "import { DASHBOARD_STOP_ARG, dashboardStopFailureMessage, GUI_UPDATE_FAILURE_NEXT_STEP, readDashboardStopReason } from \"./update-failure-guidance.mjs\";", "import { npmCachePreflightFailureMessage, runNpmCachePreflight, type NpmCachePreflightReason, } from \"./npm-cache-preflight.mjs\";", "import { guiUpdateWorkerCommand } from \"./worker-launch\";", "import { prepareWorkerUpdateHome, packageOnlyUpdateSucceeded } from \"./job-update-home\";", diff --git a/tests/update/update-desktop-owner.test.ts b/tests/update/update-desktop-owner.test.ts index b53c466aa40..9ef6aaa39d4 100644 --- a/tests/update/update-desktop-owner.test.ts +++ b/tests/update/update-desktop-owner.test.ts @@ -367,6 +367,7 @@ async function exercisePreStop(lane: "Bun" | "Node", evidence: SupervisionEviden try { await run({ runtimePlan, serviceWasInstalled: true, readPid: () => 321, readRuntimePort: () => ({}), + dashboardStopToken: null, homePolicy: { check: () => homeAllowed, serviceAllowed: true, packageOnly: false }, pendingTeardownOutstanding: () => false, stopNeeded: true, resolvedRuntimeOwnership: async () => owner, readOwnership: () => owner, diff --git a/tests/update/update-home-worker.test.ts b/tests/update/update-home-worker.test.ts index 099d0cf3254..1fdec1dc3e6 100644 --- a/tests/update/update-home-worker.test.ts +++ b/tests/update/update-home-worker.test.ts @@ -1,11 +1,49 @@ import { expect, test } from "bun:test"; -import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { createTempHome } from "../helpers/temp-home"; import { automaticUpdateLauncherSupported, packageOnlyUpdateSucceeded, prepareWorkerUpdateHome } from "../../src/update/job-update-home"; import { join } from "node:path"; -import { readUpdateJob, runGuiUpdateWorker } from "../../src/update/job"; +import { readUpdateJob, runGuiUpdateWorker, updateJobPath } from "../../src/update/job"; +import { dashboardStopMarker, takeDashboardStopToken } from "../../src/update/update-failure-guidance.mjs"; +import { planWindowsTrayUpdate } from "../../src/update/tray-update-plan.mjs"; import type { UpdateServiceHomeAuthority } from "../../src/update/service-home-policy.mjs"; +test.each(["npm", "pnpm"] as const)("a failed %s dashboard update reports the checked Windows stop before package replacement", async installer => { + const box = createTempHome("ocx-update-stop-report-"); + try { + let token: string | null = null; + await runGuiUpdateWorker("stop-report", "latest", false, { + checkForUpdateFn: () => ({ currentVersion: "1.0.0", latestVersion: "1.0.1", channel: "latest", + installer, updateAvailable: true, canUpdate: true, command: "ocx update", releaseNotesUrl: "" }), + platform: "win32", + integrityFn: () => ({ ok: true, integrity: "sha512-fixture" }), + cachePreflightFn: () => ({ ok: true, reason: "" }), + serviceHomeAuthorityFn: () => ({ kind: "same" }), + launcherSupportsUpdateHomeFn: () => true, + resolvePnpmOwnerFn: () => ({ ok: true, owner: { commandPath: "/fixture/pnpm", packagePath: "/fixture/package", + globalDir: "/fixture/global", globalRoot: "/fixture/root", globalBinDir: "/fixture/bin" } }), + resolvePnpmActiveLauncherFn: () => null, + trayHandoffFn: () => planWindowsTrayUpdate({}), + spawnUpdateFn: ((node: string, args: string[]) => { + const argv = [node, ...args]; + token = takeDashboardStopToken(argv, "win32"); + expect(token).toMatch(/^[0-9a-f]{32}$/); + expect(argv.at(-1)).toBe("--update-worker-result"); + const report = { schema: "ocx-stop/1", ok: false, outcome: "failed", exitCode: 1, + serviceStopReason: "unverified-budget", message: "private-child-detail" }; + const marker = dashboardStopMarker(token, { status: 1, signal: null, stdout: JSON.stringify(report) }); + return { status: 1, signal: null, stdout: "private-launcher-output\n" + marker + "\n", stderr: "private-vendor-output" }; + }) as typeof import("node:child_process").spawnSync, + }); + const job = readUpdateJob("stop-report"); + expect(job?.error).toContain("remaining time"); + expect(job?.exitCode).toBe(1); + const persisted = readFileSync(updateJobPath(), "utf8"); + expect(persisted).not.toContain(token!); + expect(persisted).not.toMatch(/private-(child|launcher|vendor)-/); + } finally { box.remove(); } +}); + test("an old delegated launcher is refused before automatic update starts", async () => { const box = createTempHome("ocx-update-home-worker-"); const priorHome = process.env.HOME; diff --git a/tests/update/update-job.test.ts b/tests/update/update-job.test.ts index 962a42405f7..34fa30f9030 100644 --- a/tests/update/update-job.test.ts +++ b/tests/update/update-job.test.ts @@ -1882,7 +1882,7 @@ describe("immutable update target (WP160)", () => { const cacheGateAt = source.indexOf("const cachePreflight = (io.cachePreflightFn ?? runNpmCachePreflight)();"); const trayStopAt = source.indexOf("io.trayHandoffFn ?? defaultWorkerTrayHandoff"); const failAt = source.indexOf('updateJob(job, { status: "failed", error: integrity.reason });'); - const spawnAt = source.indexOf('const result = (io.runCommandFn ?? runLoggedCommand)(job, cmd.bin, cmd.args, UPDATE_TIMEOUT_MS, updateEnv, homePolicy.authorizeMutation, "package");'); + const spawnAt = source.indexOf('const result = (io.runCommandFn ?? runLoggedCommand)(job, cmd.bin, cmd.args, UPDATE_TIMEOUT_MS, updateEnv, homePolicy.authorizeMutation, "package", io);'); expect(gateAt).toBeGreaterThan(-1); expect(cacheGateAt).toBeGreaterThan(-1); expect(trayStopAt).toBeGreaterThan(-1); diff --git a/tests/update/update-recovery-boundaries.test.ts b/tests/update/update-recovery-boundaries.test.ts index e3d4f41ac34..06daaaaf9d0 100644 --- a/tests/update/update-recovery-boundaries.test.ts +++ b/tests/update/update-recovery-boundaries.test.ts @@ -254,6 +254,7 @@ test("production Node full stop refuses lost service permission before Windows w home = { kind: changed }; const deps = { homePolicy, serviceWasInstalled: captured, hasRuntimeState: !captured, hasPendingTeardown: false, + dashboardStopToken: null, runtimePlan: { mayStopRuntime: true }, readOwnership: () => ({ ownership: null, ownershipUnknown: false }), observeSupervision: () => false, planUpdateRuntimeHandling, stopAttempted: false, releaseUpdateLease() {}, console: { log() {}, warn: (line: string) => warnings.push(line), error() {} }, diff --git a/tests/update/update-stop-classification.test.ts b/tests/update/update-stop-classification.test.ts index a2f74556b1a..02b2f5a4129 100644 --- a/tests/update/update-stop-classification.test.ts +++ b/tests/update/update-stop-classification.test.ts @@ -6,8 +6,57 @@ import { join } from "node:path"; import { STOP_HISTORY_DEFERRED_EXIT_CODE, STOP_HISTORY_INCOMPLETE_EXIT_CODE } from "../../src/update/stop-contract.mjs"; import { probeProxyLiveness } from "../../src/update/proxy-liveness-probe.mjs"; import { decidePostStopUpdate } from "../../src/update/stop-decision.mjs"; +import { DASHBOARD_STOP_ARG, dashboardStopFailureMessage, dashboardStopMarker, readDashboardStopReason, takeDashboardStopToken } from "../../src/update/update-failure-guidance.mjs"; import { repoRoot as resolveRepoRoot } from "../helpers/repo-root"; +describe("Windows dashboard pre-update stop reporting", () => { + const token = "a".repeat(32); + const report = { schema: "ocx-stop/1", exitCode: 1, ok: false, outcome: "failed", serviceStopReason: "evidence-unreadable" }; + const failure = { status: 1, signal: null, stdout: JSON.stringify(report) }; + + test("only the worker launcher consumes the private argument", () => { + const argv = ["node", "launcher", "update", "--tag", "latest", "--update-worker-home", "same", "--update-worker-result"]; + const requested = [...argv, DASHBOARD_STOP_ARG + token]; + expect(takeDashboardStopToken([...requested], "linux")).toBeNull(); + expect(takeDashboardStopToken([...argv.slice(0, -1), DASHBOARD_STOP_ARG + token], "win32")).toBeNull(); + expect(takeDashboardStopToken([...argv, DASHBOARD_STOP_ARG + "invalid"], "win32")).toBeNull(); + expect(takeDashboardStopToken(requested, "win32")).toBe(token); + expect(requested).toEqual(argv); + }); + + test("extracts only the four declared reasons from the failed stop", () => { + for (const reason of ["access-denied", "evidence-unreadable", "unbound-wrapper", "unverified-budget"]) { + const stdout = JSON.stringify({ ...report, serviceStopReason: reason, message: "private-message", detail: "private-detail" }); + const marker = dashboardStopMarker(token, { ...failure, stdout }); + expect(marker).not.toBeNull(); + expect(marker).not.toContain("private"); + expect(readDashboardStopReason(token, { ...failure, stdout: "launcher preamble\n" + marker + "\r\n" })).toBe(reason); + expect(dashboardStopFailureMessage(reason)).toContain("before package replacement"); + expect(dashboardStopFailureMessage(reason)?.includes("--deadline-ms")).toBe(reason === "unverified-budget"); + } + expect(dashboardStopFailureMessage("private-message")).toBeNull(); + for (const extra of [{ schema: "other" }, { ok: true }, { outcome: "stopped" }, { exitCode: 0 }, + { serviceStopReason: "timeout" }, { serviceStopReason: ["access-denied"] }, { message: "x".repeat(8192) }]) { + expect(dashboardStopMarker(token, { ...failure, stdout: JSON.stringify({ ...report, ...extra }) })).toBeNull(); + } + expect(dashboardStopMarker(token, { ...failure, stdout: "vendor output\n" + failure.stdout })).toBeNull(); + }); + + test("a vendor line, another attempt, and abnormal exits keep the generic failure", () => { + const marker = dashboardStopMarker(token, failure)!; + for (const stdout of [failure.stdout, marker.replace(token, "b".repeat(32)), "vendor: " + marker, + marker + "\nmore output", marker.replace("evidence-unreadable", "unknown")]) { + expect(readDashboardStopReason(token, { ...failure, stdout })).toBeNull(); + } + for (const exit of [{ status: 0 }, { status: 79 }, { status: 80 }, { status: 81 }, { status: 2 }, + { status: null, signal: "SIGTERM" }, { signal: "SIGTERM" }, { error: new Error("spawn failure") }]) { + expect(dashboardStopMarker(token, { ...failure, ...exit })).toBeNull(); + expect(readDashboardStopReason(token, { ...failure, stdout: marker, ...exit })).toBeNull(); + } + expect(readDashboardStopReason(null, { ...failure, stdout: marker })).toBeNull(); + }); +}); + const repoRoot = resolveRepoRoot(); const read = (rel: string): string => readFileSync(join(repoRoot, rel), "utf8"); diff --git a/tests/update/update-stop-first.test.ts b/tests/update/update-stop-first.test.ts index 11538fca042..7fb4bc6fac0 100644 --- a/tests/update/update-stop-first.test.ts +++ b/tests/update/update-stop-first.test.ts @@ -585,8 +585,8 @@ describe("update stops the running proxy before replacing files", () => { }); test("npm launcher update path stops via its own launcher path before npm install", () => { - expect(launcherSource).toContain('guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, [launcher, "stop"]'); - const stopAt = launcherSource.indexOf('[launcher, "stop"]'); + expect(launcherSource).toContain('const stopArgs = dashboardStopToken ? [launcher, "stop", "--json"] : [launcher, "stop"]'); + const stopAt = launcherSource.indexOf('guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, stopArgs'); // #1942: the destructive step is now the transactional staged update, not a direct // global npm install. The stop must still precede it. const installAt = launcherSource.indexOf("transactionalNpmUpdate({"); From 1126bdcf67e689b0235f83175eeb08ff9daaa78a Mon Sep 17 00:00:00 2001 From: Shian Michael <179563420+ShianMike@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:06:47 +0800 Subject: [PATCH 19/50] fix(cli): refuse stale combo edits and renames (#9254) Send the source combo revision when building a save from a prior read. Preserve the competing edit and report how to review the current combos on conflict. --- docs-site/src/content/docs/guides/combos.md | 5 +++ src/cli/combo.ts | 12 +++++-- structure/cli-management.md | 2 +- tests/cli/cli-combo-parity.test.ts | 7 +++++ tests/cli/cli-combo-partial-update.test.ts | 21 +++++++++++-- tests/cli/cli-combo-set-targets.test.ts | 35 +++++++++++++++++++-- 6 files changed, 73 insertions(+), 9 deletions(-) diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index d0d27dec864..ee8b826f620 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1195,6 +1195,11 @@ the target list: without `--strategy` the stored strategy and its JEV settings s model alias and a non-empty display name. `create` and `update` are aliases for `set`; `delete` is an alias for `remove`; and the same subcommands are available under `ocx route combo`. +On proxies that support combo revisions, `set` reports a conflict if the source combo changes +before an edit or rename is saved, or if the rename destination is already in use. +The command exits with code 5. Run `ocx combo list --json` to review the current combos +before retrying. + ### Management API Headless clients use `GET`, `PUT`, and `DELETE` on `/api/combos`. `GET` lists normalized combo diff --git a/src/cli/combo.ts b/src/cli/combo.ts index dc2c8653728..c0ce430977a 100644 --- a/src/cli/combo.ts +++ b/src/cli/combo.ts @@ -46,7 +46,7 @@ const USAGE = `Usage: (one synthetic decision probe through the decision method; may spend a decision call) ocx combo discover [--query ] [--json]`; -type ComboRow = Record & { id?: string; model?: string; strategy?: string }; +type ComboRow = Record & { id?: string; model?: string; strategy?: string; revision?: string }; const STRATEGIES = ["failover", "round-robin", "random", "least-used", "reset-window", "jev"] as const; const isComboStrategy = (value: string): value is typeof STRATEGIES[number] => (STRATEGIES as readonly string[]).includes(value); // Combo writes print fixed messages instead of server text. When --targets kept a stored JEV @@ -54,6 +54,7 @@ const isComboStrategy = (value: string): value is typeof STRATEGIES[number] => ( const KEPT_JEV_REJECTED = "combo_targets_rejected_by_kept_jev"; const KEPT_JEV_FIELDS = new Set(["targets", "decisionProvider", "decisionModel", "decisionTimeoutMs", "decisionQuotaSignals", "decisionQuotaTiers", "sessionPin"]); const SET_ERRORS = { + combo_revision_conflict: "The combo changed or the destination ID is already in use. Review the current combos with ocx combo list --json before retrying.", [KEPT_JEV_REJECTED]: "The selected target rejected the new targets or the kept jev settings. Without --strategy, --targets keeps the stored jev strategy with its decision method, quota policy and session pin, and the save checks the new targets together with them. Inspect the combo with ocx combo show --json, then fix the targets or those settings, or pass --strategy to change the strategy.", }; @@ -109,7 +110,8 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise { const additional = await prepareComboInput(args, deps); const targetsRaw = takeOption(args, "--targets"); const parsedTargets = targetsRaw === undefined ? undefined : parseTargets(targetsRaw); - const renameFrom = takeOption(args, "--rename-from"); + const renameFrom = takeOption(args, "--rename-from")?.trim(); + if (renameFrom === "") throw new CliUsageError("--rename-from requires a nonblank combo ID", USAGE); const replacingTargets = parsedTargets !== undefined || additional.targets !== undefined; const strategyRaw = takeOption(args, "--strategy"); if (strategyRaw !== undefined && !isComboStrategy(strategyRaw)) throw new CliUsageError("--strategy must be failover, round-robin, random, least-used, reset-window, or jev", USAGE); @@ -197,6 +199,10 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise { if (!replacingTargets && !existing) { throw new CliUsageError("--targets is required when creating a combo", USAGE); } + const ifRevision = existing?.revision; + if (ifRevision !== undefined && (typeof ifRevision !== "string" || !ifRevision)) { + throw new Error("Invalid combo revision"); + } const strategy = strategyRaw ?? existing?.strategy ?? "failover"; if (!isComboStrategy(strategy)) throw new CliUsageError(`combo ${renameFrom ?? id} has an unsupported stored strategy; pass --strategy`, USAGE); if (strategyRaw === undefined) requireStrategyFlags(strategy); @@ -266,7 +272,7 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise { try { result = await runtimeRequest("/api/combos", { method: "PUT", redirect: "error", - body: serializeManagementJson({ id, combo, ...(renameFrom ? { renameFrom } : {}) }), + body: serializeManagementJson({ id, combo, ...(renameFrom ? { renameFrom } : {}), ifRevision }), }, deps); } catch (error) { const field = error instanceof RuntimeApiError && error.body !== null && typeof error.body === "object" diff --git a/structure/cli-management.md b/structure/cli-management.md index 62c7b888617..dac496c7b31 100644 --- a/structure/cli-management.md +++ b/structure/cli-management.md @@ -117,7 +117,7 @@ live and latest durable rows are captured under the same mutation lock as deleti `src/cli/models-order.ts` owns raw upstream display-name addressing and routed picker operations. Status preserves saved native identities, while manual/preset replacement requires explicit reset of native-inclusive order. Manual input is a full unique routed permutation with the observed featured prefix; settings/identity rereads reject observable drift without claiming CAS. `src/cli/model-picker-ordering.ts` mirrors the GUI's pure identity/sort projection without importing GUI code into the CLI. Independent ordering fixtures and test-only GUI conformance exercise the deliberate shared contract. Most-used consumes complete all/all requested-model usage, not representative resolved-model attribution. The registry declares the existing display-name PUT; its handler remains authoritative, including saved-but-failed HTTP503. -`src/cli/route-policy-write.ts` accepts editable-only documents, requires the caller's update revision and uses fixed create/update/delete requests. Strict nested field ownership is local; provider/alias/routing validation stays on the server, without fabricated config context. Profile writes may activate already-enabled Lab automation. `src/cli/combo-input.ts` preserves target metadata and explicit false/default options before transport; `src/cli/combo.ts` applies them through its existing merge stages, retaining a carried force policy's omitted default effort. `--allow-metered-targets on|off` sets the optional combo boolean; omission preserves it, explicit off clears it, and the receipt retains it. Eligibility follows the [runtime consent contract](runtime.md#request-local-target-compatibility). These combo upserts are not revision CAS. `--decision-quota-signals on|off|-` and `--decision-quota-tiers JSON|-` share quota validation; target replacement (`--targets-file` or `--targets`) and rename preserve omitted policy; without `--strategy` an existing combo keeps its stored strategy, strategy-only flags are checked against it, and a new combo defaults to failover (#7579). Off retains tiers and a strategy switch drops it. A 400 whose `field` is `targets` or a JEV setting after `--targets` kept a stored JEV strategy maps to a fixed message naming that kept policy; other refusals keep the generic message. The receipt rebuild validates both fields; [loaded advisory quota](providers/jev-decision.md#loaded-advisory-quota) owns defaults and privacy. `src/cli/combo-stats.ts` reports actual JEV decision/token/coverage facts and nullable/incomplete observations without a savings estimate or decision probe. +`src/cli/route-policy-write.ts` accepts editable-only documents, requires the caller's update revision and uses fixed create/update/delete requests. Strict nested field ownership is local; provider/alias/routing validation stays on the server, without fabricated config context. Profile writes may activate already-enabled Lab automation. `src/cli/combo-input.ts` preserves target metadata and explicit false/default options before transport; `src/cli/combo.ts` applies them through its existing merge stages, retaining a carried force policy's omitted default effort. `--allow-metered-targets on|off` sets the optional combo boolean; omission preserves it, explicit off clears it, and the receipt retains it. Eligibility follows the [runtime consent contract](runtime.md#request-local-target-compatibility). Combo edits and renames send the revision read from the source row when the proxy returns one. A `combo_revision_conflict` returns exit 5 and points to `ocx combo list --json` before retrying. `--decision-quota-signals on|off|-` and `--decision-quota-tiers JSON|-` share quota validation; target replacement (`--targets-file` or `--targets`) and rename preserve omitted policy; without `--strategy` an existing combo keeps its stored strategy, strategy-only flags are checked against it, and a new combo defaults to failover (#7579). Off retains tiers and a strategy switch drops it. A 400 whose `field` is `targets` or a JEV setting after `--targets` kept a stored JEV strategy maps to a fixed message naming that kept policy; other refusals keep the generic message. The receipt rebuild validates both fields; [loaded advisory quota](providers/jev-decision.md#loaded-advisory-quota) owns defaults and privacy. `src/cli/combo-stats.ts` reports actual JEV decision/token/coverage facts and nullable/incomplete observations without a savings estimate or decision probe. `src/cli/catalog-command-result.ts` owns fixed safe errors and shared catalog evidence only; callers validate their distinct public DTOs. `src/cli/combo-result.ts` rebuilds the combo write receipt and verifies the requested identity. Numeric partial outcomes reach the original root dispatch, and read-back is required before any caller retry. The helpers do not select endpoints, grant authority, perform writes or execute generic CRUD. Existing provider receipt semantics remain separate. Local discovery refusals raised by `runtimeBaseUrl` before any request carry a typed `RuntimeApiError.code` (`proxy_not_running`, `client_role_management_unavailable`) and render a fixed "No request was sent" message instead of uncertain-write wording; integration-route errors (normalized, unredirected path) may append a fixed recovery line keyed on the closed `reason` set; the writer's `message` prose is never echoed. diff --git a/tests/cli/cli-combo-parity.test.ts b/tests/cli/cli-combo-parity.test.ts index 28f2936092c..25e54754b1f 100644 --- a/tests/cli/cli-combo-parity.test.ts +++ b/tests/cli/cli-combo-parity.test.ts @@ -3,6 +3,7 @@ import { readFileSync, writeFileSync } from "node:fs"; import { Readable } from "node:stream"; import { prepareComboInput } from "../../src/cli/combo-input"; import { handleComboCommand } from "../../src/cli/combo"; +import { saveConfig } from "../../src/config"; import { handleComboRoutes } from "../../src/server/management/combo-routes"; import type { RuntimeApiDeps } from "../../src/cli/runtime-api"; import type { OcxConfig } from "../../src/types"; @@ -113,6 +114,7 @@ function realRuntime(refresh: CatalogDisposition = { status: "committed", change combos: { saved: { strategy: "failover", targets: [{ ...target, weight: 2, reasoningEfforts: ["high"], modelProfile: "kept profile", lastResort: true }, { provider: "fixture", model: "second" }], imageInput: "disabled", reasoningEffortMode: "adaptive", defaultEffortMode: "force", defaultEffort: "high" } }, }; + saveConfig(config); const calls: Array<{ url: string; method: string; body?: Record }> = []; let resolutions = 0; const deps: RuntimeApiDeps = { @@ -171,6 +173,7 @@ describe("integrated combo extension and actual management persistence", () => { test("a target-file replacement preserves unrelated strategy and public identity", async () => { const f = realRuntime(); Object.assign(f.config.combos!.saved!, { strategy: "round-robin", stickyLimit: 3, alias: "my-combo", displayName: "My combo" }); + saveConfig(f.config); expect(await handleComboCommand(["set", "saved", "--targets-file", file([target]), "--json"], f.deps)).toBe(0); expect(f.config.combos!.saved).toMatchObject({ strategy: "round-robin", stickyLimit: 3, alias: "my-combo", displayName: "My combo", defaultEffort: "high", defaultEffortMode: "force" }); @@ -206,6 +209,8 @@ describe("integrated combo extension and actual management persistence", () => { const f = realRuntime(); f.config.combos!.saved!.nativeAlias = true; f.config.combos!.saved!.alias = "gpt-6-astra"; + f.config.combos!.saved!.displayName = "Native alias fixture"; + saveConfig(f.config); expect(await handleComboCommand(["set", "saved", "--native-alias", "off", "--alias", "-", "--json"], f.deps)).toBe(0); expect(f.config.combos!.saved).not.toHaveProperty("nativeAlias"); expect(f.config.combos!.saved).not.toHaveProperty("alias"); @@ -214,6 +219,8 @@ describe("integrated combo extension and actual management persistence", () => { const f = realRuntime(); f.config.combos!.saved!.nativeAlias = true; f.config.combos!.saved!.alias = "gpt-6-astra"; + f.config.combos!.saved!.displayName = "Native alias fixture"; + saveConfig(f.config); expect(await handleComboCommand(["set", "saved", "--native-alias", "off", "--json"], f.deps)).toBe(1); expect(f.config.combos!.saved).toMatchObject({ alias: "gpt-6-astra", nativeAlias: true }); expect(output).not.toHaveBeenCalled(); diff --git a/tests/cli/cli-combo-partial-update.test.ts b/tests/cli/cli-combo-partial-update.test.ts index 85ee1440223..8b1f3914044 100644 --- a/tests/cli/cli-combo-partial-update.test.ts +++ b/tests/cli/cli-combo-partial-update.test.ts @@ -100,11 +100,26 @@ describe("combo partial update and decision selector CLI", () => { expect(r.body()?.combo.targets).toEqual(original.targets); }); - test("partial rename fetches the source and preserves targets", async () => { + test("partial rename checks the source revision and preserves targets", async () => { + quiet(); + const r = runtime({ ...original, revision: "saved-revision" }); + expect(await handleComboCommand(["set", "auto2", "--rename-from", " auto ", "--decision-model", "a/m1"], r.deps)).toBe(0); + expect(r.body()).toMatchObject({ id: "auto2", renameFrom: "auto", ifRevision: "saved-revision", combo: { targets: original.targets } }); + expect(r.body()?.combo).not.toHaveProperty("revision"); + }); + + test("a blank rename source fails before writing", async () => { quiet(); const r = runtime(); - expect(await handleComboCommand(["set", "auto2", "--rename-from", "auto", "--decision-model", "a/m1"], r.deps)).toBe(0); - expect(r.body()).toMatchObject({ id: "auto2", renameFrom: "auto", combo: { targets: original.targets } }); + expect(await handleComboCommand(["set", "new", "--rename-from", " ", "--targets", "a/m1"], r.deps)).toBe(2); + expect(r.requests).toEqual([]); + }); + + test("a malformed revision fails before writing", async () => { + quiet(); + const r = runtime({ ...original, revision: 42 }); + expect(await handleComboCommand(["set", "auto", "--description", "new"], r.deps)).toBe(1); + expect(r.requests.map(request => request.method)).toEqual(["GET"]); }); test("creating still requires targets and explicit empty targets reject", async () => { diff --git a/tests/cli/cli-combo-set-targets.test.ts b/tests/cli/cli-combo-set-targets.test.ts index a24e328084e..4ab2151b098 100644 --- a/tests/cli/cli-combo-set-targets.test.ts +++ b/tests/cli/cli-combo-set-targets.test.ts @@ -34,7 +34,7 @@ beforeEach(() => { defaultProvider: "fixture", providers: { fixture: { adapter: "openai-chat", baseUrl: "https://fixture.invalid/v1", models: ["m", "n"] }, - tev: { adapter: "jev-decision", baseUrl: "http://127.0.0.1:11434/v1/systemone", defaultModel: "tev1:4b" }, + tev: { adapter: "jev-decision", baseUrl: "https://decision.fixture.invalid/v1/systemone", defaultModel: "tev1:4b" }, }, combos: { auto: { ...jevPolicy, targets: [{ provider: "fixture", model: "m" }] }, @@ -57,6 +57,37 @@ const deps: RuntimeApiDeps = { }; const stored = () => JSON.parse(readFileSync(getConfigPath(), "utf8")).combos as Record>; +test.each([ + { name: "edit", args: ["set", "auto", "--display-name", "CLI edit"] }, + { name: "rename", args: ["set", "renamed", "--rename-from", "auto"] }, +])("combo set refuses a concurrent $name without replacing the newer save", async ({ args }) => { + const fetch = deps.fetchImpl!; + let puts = 0; + let savedByOtherClient: string | undefined; + const concurrentDeps: RuntimeApiDeps = { + ...deps, + fetchImpl: (async (input, init) => { + if (init?.method === "PUT" && ++puts === 1) { + const newer = await fetch(input, { + ...init, + body: JSON.stringify({ id: "auto", combo: { ...config.combos!.auto, description: "Saved by another client" } }), + }); + expect(newer.status).toBe(200); + savedByOtherClient = readFileSync(getConfigPath(), "utf8"); + } + return fetch(input, init); + }) as typeof fetch, + }; + + const exitCode = await handleComboCommand([...args, "--json"], concurrentDeps); + expect(puts).toBe(1); + expect(savedByOtherClient).toBeDefined(); + expect(readFileSync(getConfigPath(), "utf8") === savedByOtherClient).toBe(true); + expect(exitCode).toBe(5); + expect(errors.join("\n")).toContain("Review the current combos with ocx combo list --json"); + expect(log).not.toHaveBeenCalled(); +}); + describe("ocx combo set --targets keeps the stored strategy (#7579)", () => { test("replacing a JEV combo's targets keeps JEV and its whole policy", async () => { expect(await handleComboCommand(["set", "auto", "--targets", "fixture/n,fixture/m:2", "--json"], deps)).toBe(0); @@ -86,7 +117,7 @@ describe("ocx combo set --targets keeps the stored strategy (#7579)", () => { expect(errors.join("\n")).toContain("the kept jev settings"); errors.length = 0; // A rename onto an existing combo is refused for its own reason, not for the kept policy. - expect(await handleComboCommand(["set", "judged", "--rename-from", "auto", "--targets", "fixture/n", "--json"], deps)).toBe(1); + expect(await handleComboCommand(["set", "judged", "--rename-from", "auto", "--targets", "fixture/n", "--json"], deps)).toBe(5); expect(errors.join("\n")).not.toContain("jev"); expect(readFileSync(getConfigPath(), "utf8")).toBe(before); }); From 3187ecf302578062262a0e3272b27e7c5ad9c2ce Mon Sep 17 00:00:00 2001 From: Arthur tinseau <65445747+atinseau@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:10:52 +0100 Subject: [PATCH 20/50] fix(codex-cli-update): recognize the Windows standalone Codex installer (#9255) * fix(codex-cli-update): recognize the Windows standalone Codex installer On Windows, a Codex CLI installed by OpenAI's standalone installer was never observed: inspection only accepted an npm codex.cmd named by CODEX_CLI_PATH, so the dashboard reported the install as uninspectable and the plan refused with windows_inspection_deferred. Recognize the installer's junction layout (Programs\OpenAI\Codex\bin -> packages\standalone\current\bin -> releases\-) from the known-folder LocalAppData, read the release codex-package.json through the native handle-bound reader, and report it as an unmanaged standalone install with its version. The plan refuses it as not_managed. * fix(codex-cli-update): normalize a configured standalone launcher before matching A CODEX_CLI_PATH spelled with a dot component (bin\.\codex.exe) names the installer launcher but skipped standalone recognition and fell back to the app-bundle classification. Addresses the CodeRabbit review on #9255. --- src/codex/cli-install-provenance.ts | 54 +++++++- src/codex/cli-update-plan.ts | 5 +- .../cli-windows-standalone-provenance.ts | 106 +++++++++++++++ structure/INDEX.md | 1 + structure/codex-cli-update.md | 14 ++ structure/manifest.json | 1 + .../codex-cli-install-provenance.test.ts | 121 ++++++++++++++++++ .../codex-cli-update-plan.test.ts | 22 ++++ 8 files changed, 319 insertions(+), 5 deletions(-) create mode 100644 src/codex/cli-windows-standalone-provenance.ts diff --git a/src/codex/cli-install-provenance.ts b/src/codex/cli-install-provenance.ts index 9e44ae48677..13bfb17c25e 100644 --- a/src/codex/cli-install-provenance.ts +++ b/src/codex/cli-install-provenance.ts @@ -64,7 +64,7 @@ export type CodexCliInstallReason = | "unverified_standalone" | "inspection_failed"; -export type CodexCliCandidateSource = "environment" | "persisted"; +export type CodexCliCandidateSource = "environment" | "persisted" | "installer-default"; export type CodexCliInstallEvidence = | "canonical_path" | "app_bundle_path" @@ -185,6 +185,11 @@ export interface CodexCliInstallProvenanceDeps { * turn a different installation managed. */ readonly selectedCommand?: string | null; + /** + * Windows only: the visible bin directory of OpenAI's standalone installer. Defaults to + * `Programs\OpenAI\Codex\bin` under the known-folder LocalAppData; null skips recognition. + */ + readonly windowsStandaloneBinDir?: string | null; } interface PackageManifestEvidence { @@ -1055,16 +1060,57 @@ function observeInstallContent( requests.map(req => ({ role: req.role, digest: observed.get(req.role)?.digest }))); } +/** + * Report OpenAI's standalone installer layout when no candidate is configured, or when the + * configured candidate is that installer's own launcher. The report stays unmanaged: the + * installer updates its own releases, and nothing here establishes which `codex` PATH selects. + */ +async function inspectWindowsStandaloneCandidate( + candidate: ReadOnlyCodexRuntimeCandidate | null, + deps: CodexCliInstallProvenanceDeps, +): Promise { + const standaloneModule = await import("./cli-windows-standalone-provenance"); + const binDir = deps.windowsStandaloneBinDir !== undefined + ? deps.windowsStandaloneBinDir + : await standaloneModule.defaultWindowsStandaloneCodexBinDir(); + if (!binDir) return null; + if (candidate && !samePath(win32.normalize(candidate.command), win32.join(binDir, "codex.exe"), "win32")) return null; + const install = await standaloneModule.inspectWindowsStandaloneCodexInstall(binDir); + if (!install) return null; + return freezeReport({ + schemaVersion: 1, + candidateAvailable: true, + candidateVersion: candidate?.version ?? null, + candidateSource: candidate?.evidence ?? "installer-default", + selectionAttested: false, + versionEvidence: Object.freeze({ kind: "package-manifest" as const }), + provenance: "standalone-unverified", + managed: false, + reason: "unverified_standalone", + location: publicExecutableLocation("codex.exe", "win32"), + installDigest: null, + installContentDigest: null, + packageVersion: install.version, + shim: Object.freeze({ status: "unknown", backingKind: null }), + evidence: Object.freeze(["canonical_path", "package_manifest"] as const), + }); +} + /** Inspect ownership of one configured Codex CLI candidate, without mutation. */ export async function inspectCodexCliInstall( deps: CodexCliInstallProvenanceDeps = {}, ): Promise { const platform = deps.platform ?? process.platform; const candidate = observeCodexRuntimeCandidateReadOnly(deps); + if (isWindowsPlatform(platform)) { + const standalone = await inspectWindowsStandaloneCandidate(candidate, deps); + if (standalone) return standalone; + } if (!candidate) { - // This slice reads no candidate or configuration file on Windows, so an - // absent proof-captured environment candidate does not establish that no - // Codex CLI exists: a persisted selection is simply never consulted there. + // Apart from the standalone installer layout above, this slice reads no + // candidate or configuration file on Windows, so an absent proof-captured + // environment candidate does not establish that no Codex CLI exists: a + // persisted selection is simply never consulted there. // Report the deferral that actually happened instead of the stronger claim // that the candidate is unavailable. POSIX retains its existing result // when no candidate is observed. diff --git a/src/codex/cli-update-plan.ts b/src/codex/cli-update-plan.ts index f8c7202d623..19e103582f4 100644 --- a/src/codex/cli-update-plan.ts +++ b/src/codex/cli-update-plan.ts @@ -612,8 +612,11 @@ export async function createCodexCliUpdatePlan(deps: CodexCliUpdatePlanDeps = {} // Windows planning requires private evidence from the production handle-bound // predicate. A synthetic/copyable public managed flag cannot open this lane. + // A recognized standalone installer is never managed, so it refuses as not_managed below. const windowsEvidence = windowsCodexCliPlanEvidence(report); - if ((platform === "win32" && !windowsEvidence) || report.reason === "windows_inspection_deferred") { + const windowsStandalone = platform === "win32" && report.reason === "unverified_standalone"; + if ((platform === "win32" && !windowsEvidence && !windowsStandalone) + || report.reason === "windows_inspection_deferred") { return refusedPlan("windows_inspection_deferred", report, channel, null, NOT_EVALUATED); } if (!report.managed || report.provenance !== "npm-global") { diff --git a/src/codex/cli-windows-standalone-provenance.ts b/src/codex/cli-windows-standalone-provenance.ts new file mode 100644 index 00000000000..b71220b0d22 --- /dev/null +++ b/src/codex/cli-windows-standalone-provenance.ts @@ -0,0 +1,106 @@ +import { lstatSync, readlinkSync } from "node:fs"; +import { win32 } from "node:path"; +import { parseStrictSemver } from "../lib/strict-semver"; +import { inspectWindowsInstallationFiles } from "./windows-installation-files"; + +/** + * OpenAI's standalone Windows installer (scripts/install/install.ps1 in openai/codex) + * publishes `%LOCALAPPDATA%\Programs\OpenAI\Codex\bin` as a junction to + * `\packages\standalone\current\bin`. `current` is itself a junction to + * `releases\-`, whose `codex-package.json` records the installed version. + * The native reader refuses reparse points, so both junctions are read by name while the + * reader holds their parent directory open, then read again after the release files are held. + */ +const CURRENT_BIN_SUFFIX = "\\current\\bin"; +const STANDALONE_ROOT_SUFFIX = "\\packages\\standalone"; +const MAX_PACKAGE_MANIFEST_BYTES = 64 * 1024; + +export interface WindowsStandaloneCodexInstall { + readonly version: string; +} + +export interface WindowsStandaloneInspectionDeps { + readonly readJunction?: (path: string) => string | null; + readonly inspectFiles?: typeof inspectWindowsInstallationFiles; +} + +/** The installer's default visible bin directory, from the known folder rather than the environment. */ +export async function defaultWindowsStandaloneCodexBinDir(): Promise { + try { + const { resolveWindowsLocalAppData } = await import("./windows-local-appdata"); + const localAppData = resolveWindowsLocalAppData(() => { + throw new Error("Windows LocalAppData known-folder lookup is unavailable."); + }); + return win32.join(localAppData, "Programs", "OpenAI", "Codex", "bin"); + } catch { + return null; + } +} + +function readJunctionTarget(path: string): string | null { + try { + return lstatSync(path).isSymbolicLink() ? win32.normalize(readlinkSync(path)) : null; + } catch { + return null; + } +} + +function isDriveAbsolute(path: string): boolean { + return /^[A-Za-z]:\\/.test(path); +} + +function parsePackageManifest(bytes: Uint8Array, releaseName: string): WindowsStandaloneCodexInstall | null { + let manifest: unknown; + try { + manifest = JSON.parse(Buffer.from(bytes).toString("utf8")); + } catch { + return null; + } + if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) return null; + const { layoutVersion, version, target, entrypoint } = manifest as Record; + if (layoutVersion !== 1 || entrypoint !== "bin/codex.exe") return null; + if (typeof version !== "string" || typeof target !== "string" || !parseStrictSemver(version, 96)) return null; + // The installer names each release directory after its manifest. + if (`${version}-${target}` !== releaseName) return null; + return { version }; +} + +/** + * Recognize the standalone installer's layout behind `visibleBinDir` and read the selected + * release version. Read-only: nothing is executed, and any other layout returns null. + */ +export async function inspectWindowsStandaloneCodexInstall( + visibleBinDir: string, + deps: WindowsStandaloneInspectionDeps = {}, +): Promise { + const inspectFiles = deps.inspectFiles ?? inspectWindowsInstallationFiles; + const readJunction = deps.readJunction ?? readJunctionTarget; + const readJunctionUnderHeldParent = async (path: string): Promise => { + let target: string | null = null; + const held = await inspectFiles([{ + path: win32.dirname(path), maxBytes: 0, metadataOnly: true, directory: true, requireCanonicalPath: true, + }], () => { + target = readJunction(path); + return target !== null; + }); + return held.kind === "observed" ? target : null; + }; + + const binDir = win32.normalize(visibleBinDir); + if (!isDriveAbsolute(binDir)) return null; + const currentBinDir = await readJunctionUnderHeldParent(binDir); + if (!currentBinDir || !isDriveAbsolute(currentBinDir) + || !currentBinDir.toLowerCase().endsWith(STANDALONE_ROOT_SUFFIX + CURRENT_BIN_SUFFIX)) return null; + const standaloneRoot = currentBinDir.slice(0, -CURRENT_BIN_SUFFIX.length); + const currentDir = win32.join(standaloneRoot, "current"); + const releaseDir = await readJunctionUnderHeldParent(currentDir); + if (!releaseDir + || win32.dirname(releaseDir).toLowerCase() !== win32.join(standaloneRoot, "releases").toLowerCase()) return null; + + const observed = await inspectFiles([ + { path: win32.join(releaseDir, "codex-package.json"), maxBytes: MAX_PACKAGE_MANIFEST_BYTES, requireCanonicalPath: true }, + { path: win32.join(releaseDir, "bin", "codex.exe"), maxBytes: 0, metadataOnly: true, requireCanonicalPath: true }, + ], () => readJunction(binDir) === currentBinDir && readJunction(currentDir) === releaseDir); + if (observed.kind !== "observed") return null; + return parsePackageManifest(observed.files[0]!.bytes, win32.basename(releaseDir)); +} diff --git a/structure/INDEX.md b/structure/INDEX.md index 8dbd8107a32..90a01202efb 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -347,6 +347,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/codex/cli-update-worker-recovery.ts` | [`codex-cli-update.md`](codex-cli-update.md) | | `src/codex/cli-update-worker.ts` | [`codex-cli-update.md`](codex-cli-update.md) | | `src/codex/cli-windows-plan-provenance.ts` | [`codex-cli-update.md`](codex-cli-update.md) | +| `src/codex/cli-windows-standalone-provenance.ts` | [`codex-cli-update.md`](codex-cli-update.md) | | `src/codex/forward-transport-headers.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/codex/installation-id.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/codex/main-account.ts` | [`providers/native-main-login-retention.md`](providers/native-main-login-retention.md) | diff --git a/structure/codex-cli-update.md b/structure/codex-cli-update.md index 4565393a435..dc9c72e6d34 100644 --- a/structure/codex-cli-update.md +++ b/structure/codex-cli-update.md @@ -96,6 +96,20 @@ entrypoint, npm CLI, native and full Node digest streams stay unread, with a nul PATH-only candidate selection, autostart wrappers, global/vendor fallback, app/Store/MSIX bundles and version-manager ownership remain unverified and unmanaged. + +`src/codex/cli-windows-standalone-provenance.ts` recognizes OpenAI's standalone installer +before that predicate runs, when no candidate is configured or `CODEX_CLI_PATH` names that +installer's own `codex.exe`. The visible bin directory is `Programs\OpenAI\Codex\bin` under the +known-folder LocalAppData from `src/codex/windows-local-appdata.ts`, never an environment value. +It must be a junction to `\packages\standalone\current\bin`, and `current` must be a junction +to `\packages\standalone\releases\-`. Each junction is read by name while +`src/codex/windows-installation-files.ts` holds its parent directory. The release's +`codex-package.json` (layout 1, entrypoint `bin\codex.exe`, directory named `-`) +and `bin\codex.exe` are then held under their canonical names, and both junctions must read back +unchanged. The report is `standalone-unverified`, unmanaged and unattested, with `package-manifest` +version evidence. It does not establish which `codex` PATH selects. The plan refuses it as +`not_managed` before any registry query or process scan. Every other layout keeps the deferred report. + The explicit `attest` report stays observation-only. Only the production plan predicate creates private plan evidence; copying a public report cannot enable Windows planning. Refusals retain fixed gate codes and available native/derivation reason codes in a report-keyed diff --git a/structure/manifest.json b/structure/manifest.json index a697eeb6fcb..4e4db0dce3c 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -230,6 +230,7 @@ "src/codex/cli-update-windows-apply.ts", "src/codex/cli-update-windows-observation.ts", "src/codex/cli-windows-plan-provenance.ts", + "src/codex/cli-windows-standalone-provenance.ts", "src/codex/windows-installation-files.ts", "src/codex/windows-npm-execution.ts", "src/lib/windows-owner-acl.ts", diff --git a/tests/codex-integration/codex-cli-install-provenance.test.ts b/tests/codex-integration/codex-cli-install-provenance.test.ts index b482bdc83e7..6872950c298 100644 --- a/tests/codex-integration/codex-cli-install-provenance.test.ts +++ b/tests/codex-integration/codex-cli-install-provenance.test.ts @@ -24,6 +24,8 @@ import { isCodexCliUpdateVersionManagerPath, type CodexCliInstallProvenanceDeps, } from "../../src/codex/cli-install-provenance"; +import { inspectWindowsStandaloneCodexInstall } from "../../src/codex/cli-windows-standalone-provenance"; +import type { inspectWindowsInstallationFiles } from "../../src/codex/windows-installation-files"; import { buildUnixCodexShim } from "../../src/codex/shim"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { @@ -146,6 +148,7 @@ describe("Codex CLI install provenance", () => { platform: "win32", configDir: "C:\\OpenCodex", env: { PATH: "C:\\Tools" }, + windowsStandaloneBinDir: null, }); // Persisted state is still never read on Windows, so the command cannot // know whether a candidate exists. It must not claim that none does. @@ -1199,3 +1202,121 @@ describe("install content binding", () => { expect(oversized.installContentDigest).toBeNull(); }); }); + +const STANDALONE_RELEASE = "0.172.0-x86_64-pc-windows-msvc"; +const STANDALONE_MANIFEST = JSON.stringify({ + layoutVersion: 1, + version: "0.172.0", + target: "x86_64-pc-windows-msvc", + variant: "codex", + entrypoint: "bin/codex.exe", + execServer: "bin/codex-exec-server.exe", +}); + +describe("Windows standalone installer layout", () => { + const VISIBLE = "C:\\Users\\u\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin"; + const CURRENT_BIN = "C:\\Users\\u\\.codex\\packages\\standalone\\current\\bin"; + const CURRENT = "C:\\Users\\u\\.codex\\packages\\standalone\\current"; + const RELEASE = "C:\\Users\\u\\.codex\\packages\\standalone\\releases\\" + STANDALONE_RELEASE; + + function fakeFiles(manifest: string, opened: string[]): typeof inspectWindowsInstallationFiles { + return async (requests, finalize) => { + const files = requests.map(request => { + opened.push(request.path); + return { + path: request.path, + identity: { volumeSerial: "1", fileId: "1", size: 0, lastWriteTime: "0", changeTime: "0" }, + bytes: request.path.endsWith("codex-package.json") ? new TextEncoder().encode(manifest) : new Uint8Array(), + digest: "", + }; + }); + if (finalize && !await finalize(files)) return { kind: "refused", reason: "identity-changed" }; + return { kind: "observed", files }; + }; + } + + test("reads the selected release version through both installer junctions", async () => { + const opened: string[] = []; + const junctions: Record = { [VISIBLE]: CURRENT_BIN, [CURRENT]: RELEASE }; + const install = await inspectWindowsStandaloneCodexInstall(VISIBLE, { + readJunction: path => junctions[path] ?? null, + inspectFiles: fakeFiles(STANDALONE_MANIFEST, opened), + }); + expect(install).toEqual({ version: "0.172.0" }); + // Each junction is read while its parent is held; the release files are read directly. + expect(opened).toEqual([ + "C:\\Users\\u\\AppData\\Local\\Programs\\OpenAI\\Codex", + "C:\\Users\\u\\.codex\\packages\\standalone", + RELEASE + "\\codex-package.json", + RELEASE + "\\bin\\codex.exe", + ]); + }); + + test("refuses other junction targets, mismatched manifests and a selection that moves", async () => { + const selected = { [VISIBLE]: CURRENT_BIN, [CURRENT]: RELEASE }; + const cases: { junctions: Record; manifest?: string; moved?: boolean }[] = [ + { junctions: { [VISIBLE]: "C:\\Tools\\codex\\bin", [CURRENT]: RELEASE } }, + { junctions: { [VISIBLE]: CURRENT_BIN, [CURRENT]: "C:\\Elsewhere\\" + STANDALONE_RELEASE } }, + { junctions: selected, manifest: STANDALONE_MANIFEST.replace("0.172.0", "0.171.0") }, + { junctions: selected, manifest: STANDALONE_MANIFEST.replace("bin/codex.exe", "codex.exe") }, + { junctions: selected, moved: true }, + ]; + for (const { junctions, manifest, moved } of cases) { + let currentReads = 0; + const install = await inspectWindowsStandaloneCodexInstall(VISIBLE, { + readJunction: path => { + if (path === CURRENT && moved) currentReads += 1; + // The installer retargets current after the release files were read. + if (path === CURRENT && currentReads > 1) return RELEASE + ".next"; + return junctions[path] ?? null; + }, + inspectFiles: fakeFiles(manifest ?? STANDALONE_MANIFEST, []), + }); + expect(install).toBeNull(); + } + }); + + test.skipIf(process.platform !== "win32" || process.arch !== "x64")( + "reports a real installer layout as an unmanaged standalone install", + async () => { + const root = realpathSync.native(tempRoot("ocx-standalone-")); + const standalone = join(root, "codex-home", "packages", "standalone"); + const release = join(standalone, "releases", STANDALONE_RELEASE); + mkdirSync(join(release, "bin"), { recursive: true }); + writeFileSync(join(release, "codex-package.json"), STANDALONE_MANIFEST); + writeFileSync(join(release, "bin", "codex.exe"), "MZ"); + symlinkSync(release, join(standalone, "current"), "junction"); + const visible = join(root, "Programs", "OpenAI", "Codex", "bin"); + mkdirSync(dirname(visible), { recursive: true }); + symlinkSync(join(standalone, "current", "bin"), visible, "junction"); + + const discovered = await inspectCodexCliInstall({ + platform: "win32", env: { PATH: "" }, windowsStandaloneBinDir: visible, + }); + expect(discovered).toMatchObject({ + candidateSource: "installer-default", provenance: "standalone-unverified", managed: false, + reason: "unverified_standalone", packageVersion: "0.172.0", versionEvidence: { kind: "package-manifest" }, + location: "/codex.exe", + }); + // A dot component names the same launcher and must not fall back to lexical classification. + for (const launcher of [join(visible, "codex.exe"), visible + "\\.\\codex.exe"]) { + const configured = await inspectCodexCliInstall({ + platform: "win32", env: { CODEX_CLI_PATH: launcher, PATH: "" }, windowsStandaloneBinDir: visible, + }); + expect(configured).toMatchObject({ + candidateSource: "environment", provenance: "standalone-unverified", packageVersion: "0.172.0", + }); + } + + // A plain directory holding copied binaries is outside the recognized layout. + const copied = join(root, "Copied", "bin"); + mkdirSync(copied, { recursive: true }); + writeFileSync(join(copied, "codex.exe"), "MZ"); + const unrecognized = await inspectCodexCliInstall({ + platform: "win32", env: { PATH: "" }, windowsStandaloneBinDir: copied, + }); + expect(unrecognized.reason).toBe("windows_inspection_deferred"); + expect(unrecognized.candidateAvailable).toBe(false); + }, + ); +}); diff --git a/tests/codex-integration/codex-cli-update-plan.test.ts b/tests/codex-integration/codex-cli-update-plan.test.ts index 505c7485b4b..c2ee7e105ce 100644 --- a/tests/codex-integration/codex-cli-update-plan.test.ts +++ b/tests/codex-integration/codex-cli-update-plan.test.ts @@ -130,6 +130,28 @@ describe("Codex CLI update dry-run plan", () => { expect(plan.session.state).toBe("not-evaluated"); }); + test("a Windows standalone installer refuses as not managed and reports its version", async () => { + let queries = 0; + let scans = 0; + const plan = await createCodexCliUpdatePlan(planDeps({ + platform: "win32", + inspect: async () => report({ + reason: "unverified_standalone", managed: false, provenance: "standalone-unverified", + candidateSource: "installer-default", selectionAttested: false, packageVersion: "0.172.0", + installDigest: null, installContentDigest: null, + }), + resolveTarget: () => { queries += 1; return RESOLVED; }, + scanProcesses: () => { scans += 1; return { kind: "observed", processes: [] }; }, + })); + expect(plan.applicable).toBe(false); + expect(plan.refusal).toBe("not_managed"); + expect(plan.provenance).toBe("standalone-unverified"); + expect(plan.installedVersion).toBe("0.172.0"); + expect(plan.planId).toBeNull(); + expect(queries).toBe(0); + expect(scans).toBe(0); + }); + test("an installation we do not own is never adopted", async () => { for (const owned of [ report({ managed: false, provenance: "app-bundle", reason: "app_bundle" }), From fb34a240c23846998ff65bb01f7fe5bda8d48c00 Mon Sep 17 00:00:00 2001 From: Arthur tinseau <65445747+atinseau@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:10:59 +0100 Subject: [PATCH 21/50] fix(gui,cli): strip every /api/config decoration before a provider editor PUT (#9263) * fix(gui,cli): strip every /api/config decoration before a provider editor PUT GET /api/config decorates OAuth rows with knownSubscriptionOAuth and the canonical ChatGPT forward row with canonicalOpenAiForward. The dashboard JSON editor and ocx provider snapshot each kept their own list of display-only fields and both missed these two, so PUT /api/providers rejected every save ("contains non-editable field") on any config holding an OAuth or canonical openai row. Both clients now strip through one dependency-free list in src/lib/provider-editor-dto-fields.ts, and a server test fails when safeConfigDTO adds a decoration the list lacks. * test(providers): exercise every safeConfigDTO decoration branch in the drift check The drift check only looked at the decorations its roster produced. It had no Vertex row, no xai row and no stored first-selection record, so a new decoration in one of those branches, or a list entry that lost its producer, went unnoticed. A second test now builds one row per producing branch and asserts that the emitted decorations are exactly PROVIDER_CONFIG_DTO_DERIVED_FIELDS; the round-trip test is unchanged. --- gui/src/hooks/useJsonConfigEditor.ts | 23 ++---- gui/tests/use-json-config-editor.test.tsx | 4 + src/cli/provider-batch.ts | 6 +- src/lib/provider-editor-dto-fields.ts | 39 ++++++++++ structure/cli-management.md | 2 +- tests/cli/cli-provider-batch.test.ts | 6 +- .../provider-config-batch-management.test.ts | 77 ++++++++++++++++++- 7 files changed, 133 insertions(+), 24 deletions(-) create mode 100644 src/lib/provider-editor-dto-fields.ts diff --git a/gui/src/hooks/useJsonConfigEditor.ts b/gui/src/hooks/useJsonConfigEditor.ts index 605ccdfbb4f..a89c58a7766 100644 --- a/gui/src/hooks/useJsonConfigEditor.ts +++ b/gui/src/hooks/useJsonConfigEditor.ts @@ -1,6 +1,7 @@ import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react"; import { deepEqualJson, threeWayMergeJson } from "../provider-workspace/provider-draft-merge"; import { captureApiTarget, targetFetch } from "../api"; +import { withoutProviderConfigDtoDerivedFields } from "../../../src/lib/provider-editor-dto-fields"; export interface Config { port: number; @@ -8,32 +9,18 @@ export interface Config { providers: Record & { adapter: string; baseUrl: string; hasApiKey?: boolean; hasHeaders?: boolean; xaiResponsesOptInState?: boolean | "mixed" }>; } -const PROVIDER_EDITOR_DERIVED_FIELDS = [ - "hasApiKey", - "hasHeaders", - "vertexCredentialKind", - "vertexCredentialVerified", - "xaiResponsesOptInState", - "initialModelSelection", -] as const; - type ProviderEditorConfig = { defaultProvider: string; providers: Record>; }; -const PROVIDER_EDITOR_DERIVED_FIELD_SET = new Set(PROVIDER_EDITOR_DERIVED_FIELDS); - function projectProviderEditorConfig(config: Config): ProviderEditorConfig { return { defaultProvider: config.defaultProvider, - providers: Object.fromEntries(Object.entries(config.providers).map(([name, provider]) => { - const projected: Record = {}; - for (const [field, value] of Object.entries(provider)) { - if (!PROVIDER_EDITOR_DERIVED_FIELD_SET.has(field)) projected[field] = structuredClone(value); - } - return [name, projected]; - })), + // Display-only fields (credential presence, OAuth recognition, the canonical ChatGPT forward + // check, ...) come from one shared list: PUT /api/providers rejects any it cannot store. + providers: Object.fromEntries(Object.entries(config.providers).map(([name, provider]) => + [name, structuredClone(withoutProviderConfigDtoDerivedFields(provider))])), }; } diff --git a/gui/tests/use-json-config-editor.test.tsx b/gui/tests/use-json-config-editor.test.tsx index 2cb61a94897..9e3a1c9faa2 100644 --- a/gui/tests/use-json-config-editor.test.tsx +++ b/gui/tests/use-json-config-editor.test.tsx @@ -26,6 +26,9 @@ const config: Config = { hasApiKey: true, hasHeaders: true, vertexCredentialKind: "marker", + // Every display-only field the server adds must be stripped, including the two an + // OAuth row and the canonical ChatGPT forward row carry (PUT rejected them before). + canonicalOpenAiForward: true, initialModelSelection: { version: 1, registrationId: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa", status: "pending" }, note: "derived registry note", }, @@ -33,6 +36,7 @@ const config: Config = { adapter: "anthropic", baseUrl: "https://beta.example.test/v1", hasApiKey: false, + knownSubscriptionOAuth: true, }, }, } as Config; diff --git a/src/cli/provider-batch.ts b/src/cli/provider-batch.ts index 162acac1743..9825829bd48 100644 --- a/src/cli/provider-batch.ts +++ b/src/cli/provider-batch.ts @@ -1,4 +1,5 @@ import { parseProviderEditorConfigDTO } from "../server/auth-cors"; +import { withoutProviderConfigDtoDerivedFields } from "../lib/provider-editor-dto-fields"; import { readJsonInput, serializeManagementJson } from "./json-input"; import { printProviderReceipt, runProviderAction } from "./provider-result"; import { @@ -24,10 +25,9 @@ async function snapshot(wantsJson: boolean, deps: RuntimeApiDeps): Promise { if (!record(provider)) throw new Error("Invalid provider snapshot response."); - // These are the four dashboard decorations, not editor fields. Any other + // The shared list names every display-only field /api/config adds. Any other // unexpected field must reach the canonical parser and fail closed. - const { hasApiKey, hasHeaders, xaiResponsesOptInState, initialModelSelection, ...editable } = provider; - return [name, editable] as const; + return [name, withoutProviderConfigDtoDerivedFields(provider)] as const; }); const parsed = parseProviderEditorConfigDTO({ defaultProvider: fetched.defaultProvider, diff --git a/src/lib/provider-editor-dto-fields.ts b/src/lib/provider-editor-dto-fields.ts new file mode 100644 index 00000000000..92d9d467c04 --- /dev/null +++ b/src/lib/provider-editor-dto-fields.ts @@ -0,0 +1,39 @@ +/** + * Display-only fields that `safeConfigDTO` adds to each provider row of `GET /api/config`. + * + * They describe derived state (credential presence, OAuth recognition, the canonical ChatGPT + * forward check, Vertex credential proof, xAI wire state, first model selection), never stored + * configuration. `PUT /api/providers` parses its baseline and next documents strictly and rejects + * any field it cannot store, so every editor client must drop exactly these before it sends a row + * back. The dashboard JSON editor and `ocx provider snapshot` both read this one list; a server + * test fails when `safeConfigDTO` grows a decoration that is missing here. + * + * Dependency-free on purpose: the dashboard bundle imports it directly. + */ +export const PROVIDER_CONFIG_DTO_DERIVED_FIELDS = [ + "hasApiKey", + "hasHeaders", + "knownSubscriptionOAuth", + "canonicalOpenAiForward", + "vertexCredentialKind", + "vertexCredentialVerified", + "xaiResponsesOptInState", + "initialModelSelection", +] as const; + +export type ProviderConfigDtoDerivedField = typeof PROVIDER_CONFIG_DTO_DERIVED_FIELDS[number]; + +const DERIVED_FIELD_SET: ReadonlySet = new Set(PROVIDER_CONFIG_DTO_DERIVED_FIELDS); + +export function isProviderConfigDtoDerivedField(field: string): field is ProviderConfigDtoDerivedField { + return DERIVED_FIELD_SET.has(field); +} + +/** A shallow copy of one `GET /api/config` provider row without its display-only fields. */ +export function withoutProviderConfigDtoDerivedFields>(row: T): Record { + const editable: Record = {}; + for (const [field, value] of Object.entries(row)) { + if (!DERIVED_FIELD_SET.has(field)) editable[field] = value; + } + return editable; +} diff --git a/structure/cli-management.md b/structure/cli-management.md index dac496c7b31..2e20e2f284c 100644 --- a/structure/cli-management.md +++ b/structure/cli-management.md @@ -107,7 +107,7 @@ live and latest durable rows are captured under the same mutation lock as deleti `src/cli/provider-settings.ts` consumes only the three additional edit fields and owns pacing rules/status. Configured rules come from config, observations from the separate pacing endpoint. Scalar writes preserve observed model rules but replace the entire block without CAS; numeric changes do not implicitly enable pacing. Complete-file replacement is exclusive with scalar flags and uses the canonical pacing validator. `src/cli/provider-runtime.ts` propagates the safe provider edit result's numeric outcome and the connectivity test outcome. Failed connectivity remains exit 1 through the outer provider dispatcher; successful and non-applicable static-catalog observations remain exit 0. `ocx provider test --model ` instead posts `{ model, confirm: true }` to `POST /api/providers/test-completion` only after printing the provider/model and a quota/cost warning and receiving consent: an interactive yes, or `--yes` (required for non-TTY and `--json`); a declined prompt exits 1 and usage errors send nothing. Its result prints TTFT, total latency and upstream-reported metadata for the wire model with a metadata-only disclaimer; a mismatch is shown distinctly but exits 0, non-applicable rows exit 0 and failed tests exit 1. -`src/cli/provider-batch.ts` reuses the authoritative named editor parser from `src/server/auth-cors.ts`. Snapshot strips only four GUI decorations, validates, then emits exactly defaultProvider/providers. Supplied baseline/next documents are not stripped or normalized; removals require --yes, the wire body is one exact PUT, and stale baselines are not automatically refreshed or retried. Batch removal does not claim single-DELETE OAuth account cleanup. Neither the snapshot nor address pinning supplies a cross-invocation process identity guarantee. +`src/cli/provider-batch.ts` reuses the authoritative named editor parser from `src/server/auth-cors.ts`. Snapshot strips the display-only fields named in `src/lib/provider-editor-dto-fields.ts` (the list the dashboard JSON editor also strips, and that `tests/providers/provider-config-batch-management.test.ts` holds to every `safeConfigDTO` decoration), validates, then emits exactly defaultProvider/providers. Supplied baseline/next documents are not stripped or normalized; removals require --yes, the wire body is one exact PUT, and stale baselines are not automatically refreshed or retried. Batch removal does not claim single-DELETE OAuth account cleanup. Neither the snapshot nor address pinning supplies a cross-invocation process identity guarantee. `src/cli/json-input.ts` shares the server's 4 MiB limit and also checks the serialized composite body. Explicit stdin and regular files have a 30-second default input deadline, strict UTF-8 decoding, static errors and owned-resource cleanup. At most one batch input can use stdin. Mutable buffers are wiped; immutable parsed strings are not claimed erased. `src/cli/provider-result.ts` projects only the known receipt/catalog fields, emits fixed known-code/status errors without raw response bodies, and returns saved-but-unconverged failures numerically. Existing global CLI error behavior remains separate. Provider workflow regressions bind these contracts to injected transports, owned homes, actual CLI subprocesses and isolated server editor handlers. diff --git a/tests/cli/cli-provider-batch.test.ts b/tests/cli/cli-provider-batch.test.ts index ac38815bcb9..75d2585783d 100644 --- a/tests/cli/cli-provider-batch.test.ts +++ b/tests/cli/cli-provider-batch.test.ts @@ -80,11 +80,15 @@ afterEach(() => { }); describe("provider snapshot", () => { - test("projects the two editor roots and strips only four GUI decorations", async () => { + test("projects the two editor roots and strips every display-only field /api/config adds", async () => { const expected = editor(); response = { ...expected, port: 10100, unexportedRoot: sentinel, providers: { alpha: { ...expected.providers.alpha, hasApiKey: true, hasHeaders: true, xaiResponsesOptInState: "mixed", initialModelSelection: { status: "pending" }, + // An OAuth row and the canonical ChatGPT forward row carry these two; before they were + // stripped, snapshot failed closed for every config holding either kind of provider. + knownSubscriptionOAuth: true, canonicalOpenAiForward: true, + vertexCredentialKind: "marker", vertexCredentialVerified: false, } } }; expect(await handleProviderBatchCommand("snapshot", ["--json"], deps())).toBe(0); expect(JSON.parse(stdout.join("\n"))).toEqual(expected); diff --git a/tests/providers/provider-config-batch-management.test.ts b/tests/providers/provider-config-batch-management.test.ts index 8c594fd8c39..c2197e5cf9e 100644 --- a/tests/providers/provider-config-batch-management.test.ts +++ b/tests/providers/provider-config-batch-management.test.ts @@ -5,7 +5,8 @@ import { join } from "node:path"; import * as configModule from "../../src/config"; import { getConfigPath, loadConfig, saveConfig } from "../../src/config"; import * as destinationPolicy from "../../src/lib/destination-policy"; -import { safeConfigDTO } from "../../src/server/auth-cors"; +import { PROVIDER_CONFIG_DTO_DERIVED_FIELDS, withoutProviderConfigDtoDerivedFields } from "../../src/lib/provider-editor-dto-fields"; +import { providerEditorConfigDTO, safeConfigDTO } from "../../src/server/auth-cors"; import { handleManagementAPI } from "../../src/server/management-api"; import type { OcxConfig } from "../../src/types"; import { catalogConvergenceFactory } from "../helpers/catalog-convergence"; @@ -271,6 +272,80 @@ describe("atomic provider editor batch", () => { } }); + test("the shared display-only field list covers every /api/config decoration and round-trips through PUT", async () => { + // A realistic roster: the canonical ChatGPT forward row and a subscription OAuth row are the + // two kinds whose decorations editor clients used to keep, which made every save a 400. + const liveConfig: OcxConfig = { + ...seededConfig(), + providers: { + ...seededConfig().providers, + openai: { + adapter: "openai-responses", + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", + codexAccountMode: "pool", + }, + anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "oauth" }, + }, + }; + saveConfig(liveConfig); + const beforeBytes = readFileSync(getConfigPath(), "utf8"); + const dto = safeConfigDTO(liveConfig) as EditorConfig; + const editor = providerEditorConfigDTO(liveConfig); + for (const [name, row] of Object.entries(dto.providers)) { + const decorations = Object.keys(row).filter(field => !Object.hasOwn(editor.providers[name]!, field)); + for (const field of decorations) expect(PROVIDER_CONFIG_DTO_DERIVED_FIELDS as readonly string[]).toContain(field); + } + expect(dto.providers.openai).toHaveProperty("canonicalOpenAiForward", true); + expect(dto.providers.anthropic).toHaveProperty("knownSubscriptionOAuth"); + + const projected: EditorConfig = { + defaultProvider: dto.defaultProvider, + providers: Object.fromEntries(Object.entries(dto.providers) + .map(([name, row]) => [name, withoutProviderConfigDtoDerivedFields(row)])), + }; + const response = await putBatch(liveConfig, { baseline: projected, next: projected }); + + expect(response?.status).toBe(200); + expect(readFileSync(getConfigPath(), "utf8")).toBe(beforeBytes); + }); + + test("every safeConfigDTO decoration branch emits only, and all of, the shared list", () => { + // One row per producing branch, so a decoration added to any of them, or a list entry that no + // longer has a producer, fails here rather than in an editor save. + const config: OcxConfig = { + ...seededConfig(), + providers: { + // hasApiKey, hasHeaders, and a stored first-selection record. + alpha: { + ...seededConfig().providers.alpha!, + initialModelSelection: { version: 1, registrationId: "1b4e28ba-2fa1-4d2c-8f7e-0d1c2b3a4f5e", status: "ready" }, + }, + openai: { + adapter: "openai-responses", + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", + }, + anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "oauth" }, + // A marker credential is always checked against the local ADC store, so the proof is reported. + vertex: { + adapter: "google", + baseUrl: "https://aiplatform.googleapis.com", + googleMode: "vertex", + apiKey: "gcp-sa:test-project/abc123", + }, + xai: { adapter: "openai-responses", baseUrl: "https://api.x.ai/v1", apiKey: "xai-test-key" }, + }, + }; + const dto = safeConfigDTO(config) as EditorConfig; + const editor = providerEditorConfigDTO(config); + const emitted = new Set(); + for (const [name, row] of Object.entries(dto.providers)) { + for (const field of Object.keys(row)) if (!Object.hasOwn(editor.providers[name]!, field)) emitted.add(field); + } + expect([...emitted].sort()).toEqual([...PROVIDER_CONFIG_DTO_DERIVED_FIELDS].sort()); + }); + test("rejects runtime-derived provider metadata as editor write authority", async () => { const liveConfig = seededConfig(); saveConfig(liveConfig); From cc05e1db764121a1cf5d77a876577e592984ad6e Mon Sep 17 00:00:00 2001 From: inforanger Date: Fri, 4 Dec 2026 00:14:47 +0900 Subject: [PATCH 22/50] fix(anthropic): record upstream served model in request logs (#9229) * fix(anthropic): record upstream served model observations * fix: guard parseStream wrap when adapter lacks it --- src/adapters/anthropic.ts | 6 +- src/lib/response-served-model.ts | 31 +++++ src/server/messages-native.ts | 23 +++- src/server/responses/request-transport.ts | 15 ++- .../messages-native.test.ts | 49 ++++++++ tests/server/response-model-identity.test.ts | 108 +++++++++++++++++- 6 files changed, 225 insertions(+), 7 deletions(-) create mode 100644 src/lib/response-served-model.ts diff --git a/src/adapters/anthropic.ts b/src/adapters/anthropic.ts index 04ff84fa1dd..e5c5cdbf72e 100644 --- a/src/adapters/anthropic.ts +++ b/src/adapters/anthropic.ts @@ -7,6 +7,7 @@ import { createAdapterTierMetadata, type AdapterTierMetadata } from "../provider import { ANTHROPIC_FAST_MODE_BETA, mergeAnthropicBetaHeader } from "../providers/anthropic-fast"; import { createToolCallIdAllocator, type ToolCallIdAllocator } from "./tool-call-id"; import { debugDroppedFrame } from "../lib/debug"; +import { reportResponseServedModel } from "../lib/response-served-model"; import type { AdapterEvent, OcxAssistantMessage, @@ -1457,7 +1458,9 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti switch (record.event || data.type) { case "message_start": { - const message = data.message as { usage?: unknown } | undefined; + const message = data.message as { usage?: unknown; model?: unknown } | undefined; + // The upstream's own model, for the request log. The log filters echoes and unknown ids. + reportResponseServedModel(response, message?.model); pendingUsage = mergeAnthropicUsage(pendingUsage, message?.usage); // Fast mode reports the speed actually served here (`usage.speed`). observeAnthropicSpeed(message?.usage, tierMetadata); @@ -1722,6 +1725,7 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti }]; } const json = parsed; + reportResponseServedModel(response, json.model); const responseBytes = Buffer.byteLength(JSON.stringify(json), "utf8"); budget.chargeRetained(responseBytes, { kind: "retained_collectors" }); try { diff --git a/src/lib/response-served-model.ts b/src/lib/response-served-model.ts new file mode 100644 index 00000000000..c97054fd4cc --- /dev/null +++ b/src/lib/response-served-model.ts @@ -0,0 +1,31 @@ +/** + * The model an upstream reported for one response, handed from an adapter parser to the request + * log without widening `AdapterEvent`. + * + * An adapter that reads a real `model` field from the upstream body (Anthropic's + * `message_start.message.model` and non-streaming `model`) reports it here, keyed by the + * response its parse was handed. The transport that owns the request's log context registers a + * sink for that response and decides what to record: the report is an observation, not a + * verdict, so `recordObservedServedModel` still applies its known-id and client-selector-echo + * filters. A parse nobody observes (a lab harness, a unit test) reports into the void. + */ +type ServedModelSink = (model: unknown) => void; +const sinks = new WeakMap(); + +/** Receive the model the parse of `response` reports. Returns the release. */ +export function observeResponseServedModel(response: object, sink: ServedModelSink): () => void { + sinks.set(response, sink); + return () => { + if (sinks.get(response) === sink) sinks.delete(response); + }; +} + +/** Report the model the upstream named in the body of `response`; the sink validates it. */ +export function reportResponseServedModel(response: object, model: unknown): void { + if (model === undefined || model === null) return; + try { + sinks.get(response)?.(model); + } catch { + // Request logging is best-effort and must not affect request delivery. + } +} diff --git a/src/server/messages-native.ts b/src/server/messages-native.ts index 13b78fc1ed6..d54cb611eaa 100644 --- a/src/server/messages-native.ts +++ b/src/server/messages-native.ts @@ -137,6 +137,7 @@ import { type RequestLogContext, } from "./request-log"; import { recordKeyAttemptFailure } from "./request-log-key-failure"; +import { recordObservedServedModel } from "../usage/log"; import { fetchWithHeaderTimeout, physicalSendObserverInit, providerFetch, safeHostLabel, sendWithConnectionPolicy } from "./responses/fetch-helpers"; import { isLocalUpstream } from "../lib/local-upstream"; import { resolveConnectTimeoutMs, resolveJsonBodyReadTimeoutMs } from "../stall-timeout"; @@ -276,7 +277,11 @@ function observeNativeMessagesChunks( const MODEL_ECHO_SCAN_BYTES = 64 * 1024; /** The `message_start` frame with `message.model` set to `model`, or undefined for any other frame. */ -function messageStartWithModel(frame: string, model: string): { text: string; canonicalError: boolean } | undefined { +function messageStartWithModel( + frame: string, + model: string, + observeUpstreamModel?: (upstreamModel: unknown) => void, +): { text: string; canonicalError: boolean } | undefined { const lines = frame.split(/\r\n|\r|\n/); const data = lines .map(line => sseFieldValue(line, "data")) @@ -286,6 +291,8 @@ function messageStartWithModel(frame: string, model: string): { text: string; ca let parsed: unknown; try { parsed = JSON.parse(data); } catch { return undefined; } if (!isRec(parsed) || parsed.type !== "message_start" || !isRec(parsed.message)) return undefined; + // The upstream's own model is read before the client's selector overwrites it. + observeUpstreamModel?.(parsed.message.model); parsed.message.model = model; const replacement = `data: ${JSON.stringify(parsed)}`; // Keep the original canonical framing for error-tagged starts. The final filter @@ -311,7 +318,12 @@ function messageStartWithModel(frame: string, model: string): { text: string; ca * (`responsesSseToAnthropicSse` is given the requested model). Works on bytes: frames before and * including `message_start` are split on the blank line, and everything after is relayed as is. */ -export function echoRequestedModel(body: ReadableStream, model: string, frames: MessagesSseFrameContext): ReadableStream { +export function echoRequestedModel( + body: ReadableStream, + model: string, + frames: MessagesSseFrameContext, + observeUpstreamModel?: (upstreamModel: unknown) => void, +): ReadableStream { const reader = body.getReader(); const encoder = new TextEncoder(); const decoder = new TextDecoder(); @@ -389,7 +401,7 @@ export function echoRequestedModel(body: ReadableStream, model: stri start = end; index = end; const decoded = decoder.decode(frame); - const rewritten = messageStartWithModel(decoded, model); + const rewritten = messageStartWithModel(decoded, model, observeUpstreamModel); // A bare CR completes the frame now. A later LF belongs to that same delimiter. if (endsOnCr) { if (end - carried === value.byteLength) { @@ -1144,7 +1156,8 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp ? restoreOAuthToolNamesInSse(observed, activeRequest.oauthToolNames, translatorBudget) : observed; const frames = new MessagesSseFrameContext(); - const echoed = echoRequestedModel(renamed, options.echoModel ?? requestedModel, frames); + const echoed = echoRequestedModel(renamed, options.echoModel ?? requestedModel, frames, + upstreamModel => recordObservedServedModel(logCtx, upstreamModel)); let toolRefusal: string | undefined; const source = clientDeclaredEmptyToolCatalog ? guardNativeMessagesEmptyToolCatalog(echoed, translatorBudget, message => { @@ -1320,6 +1333,8 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp } throw error; } + // Record the upstream's own model before the client's selector replaces it below. + recordObservedServedModel(logCtx, message.model); // The client's selector, not the wire id, as the translated lane answers. message.model = options.echoModel ?? requestedModel; const serialized = JSON.stringify(message); diff --git a/src/server/responses/request-transport.ts b/src/server/responses/request-transport.ts index ab079e2468e..48538d1d477 100644 --- a/src/server/responses/request-transport.ts +++ b/src/server/responses/request-transport.ts @@ -129,9 +129,10 @@ import { import { recordKeyAttemptFailure } from "../request-log-key-failure"; import { sealCredentialRefusal } from "../credential-recovery-attempt"; import { sealedCredentialRefusals } from "../request-log-attempt-recovery"; -import type { AttemptRecoveryKind } from "../../usage/log"; +import { recordObservedServedModel, type AttemptRecoveryKind } from "../../usage/log"; import { bindAttemptDeliveryRecorder } from "../../usage/attempt-delivery"; import { observeResponseSendReadings } from "../../lib/response-send-readings"; +import { observeResponseServedModel } from "../../lib/response-served-model"; import { resolvePassiveRouteSubjectId } from "../passive-route-linker"; import { anthropicPoolCooldownResponse, clientCancelledResponse } from "./core-errors"; import { acquireAccountLease, KIRO_ACCOUNT_WAIT_MS } from "../../oauth/kiro-account-load"; @@ -800,6 +801,18 @@ export async function prepareResponsesTransport( return request; }); }; + // The model an adapter parser reads from the upstream body (Anthropic `message.model`) reaches the + // log through the same validation as a Responses body: known ids only, never the client's echo. + // Registered before the forward-mode return so a caller-forwarded credential is observed too. + const bindServedModel = (response: object): void => { observeResponseServedModel(response, model => recordObservedServedModel(logCtx, model)); }; + if (resolved.parseStream) { + const parseStreamServed = resolved.parseStream.bind(resolved); + resolved.parseStream = (...args) => { bindServedModel(args[0]); return parseStreamServed(...args); }; + } + if (resolved.parseResponse) { + const parseResponseServed = resolved.parseResponse.bind(resolved); + resolved.parseResponse = (...args) => { bindServedModel(args[0]); return parseResponseServed(...args); }; + } if (route.provider.authMode === "forward") return resolved; const binding: DispatchBinding | undefined = route.provider.authMode === "oauth" ? oauthSelection && servingOAuthSnapshot diff --git a/tests/claude-integration/messages-native.test.ts b/tests/claude-integration/messages-native.test.ts index b605eb46d9c..4090804ee27 100644 --- a/tests/claude-integration/messages-native.test.ts +++ b/tests/claude-integration/messages-native.test.ts @@ -839,3 +839,52 @@ describe("managed native Messages", () => { expect(seen).toHaveLength(1); }); }); + +describe("managed native Messages records the upstream's own model", () => { + const replyModeled = (model: unknown): Reply => seenRequest => { + if (seenRequest.body.stream === true) { + return new Response(sseText(SSE_FRAMES.map((frame, index) => index === 0 + ? { ...frame, data: { ...frame.data, message: { ...(frame.data as { message: Record }).message, model } } } + : frame)), { headers: { "content-type": "text/event-stream" } }); + } + return Response.json({ ...MESSAGE_JSON, model }); + }; + // A known model that is neither the route's wire model nor the client selector: the pinned Codex catalog. + const OTHER_KNOWN_MODEL = "gpt-5.5"; + + for (const stream of [false, true]) { + test(`records the wire model before the selector overwrites it, stream=${stream}`, async () => { + const config = fixtureConfig(startUpstream(replyModeled("claude-x"))); + const { requestId, response, text } = await send(config, { ...SOURCE_BODY, stream }); + expect(response.status).toBe(200); + // The client still sees its own selector. + expect(text).toContain('"model":"anth/claude-x"'); + expect(text).not.toContain('"model":"claude-x"'); + expect(rowFor(requestId).servedModel).toBe("claude-x"); + }); + + test(`does not record an echoed client selector, stream=${stream}`, async () => { + const config = fixtureConfig(startUpstream(replyModeled("anth/claude-x"))); + const { requestId, response } = await send(config, { ...SOURCE_BODY, stream }); + expect(response.status).toBe(200); + expect(rowFor(requestId).servedModel).toBeUndefined(); + }); + + test(`records a known model that differs from the route as a mismatch, stream=${stream}`, async () => { + const config = fixtureConfig(startUpstream(replyModeled(OTHER_KNOWN_MODEL))); + const { requestId, response, text } = await send(config, { ...SOURCE_BODY, stream }); + expect(response.status).toBe(200); + expect(text).not.toContain(OTHER_KNOWN_MODEL); + const row = rowFor(requestId); + expect(row.servedModel).toBe(OTHER_KNOWN_MODEL); + expect(row.wireModel ?? row.model).not.toBe(OTHER_KNOWN_MODEL); + }); + + test(`drops an unknown reported model, stream=${stream}`, async () => { + const config = fixtureConfig(startUpstream(replyModeled("unlisted-model-9"))); + const { requestId, response } = await send(config, { ...SOURCE_BODY, stream }); + expect(response.status).toBe(200); + expect(rowFor(requestId).servedModel).toBeUndefined(); + }); + } +}); diff --git a/tests/server/response-model-identity.test.ts b/tests/server/response-model-identity.test.ts index 744e1837f0d..9124d9b44ea 100644 --- a/tests/server/response-model-identity.test.ts +++ b/tests/server/response-model-identity.test.ts @@ -1,5 +1,6 @@ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { handleResponses } from "../../src/server/responses/core"; +import * as adapterResolveModule from "../../src/server/adapter-resolve"; import { inspectResponseLogJson, inspectResponseLogSsePayload, type RequestLogContext, } from "../../src/server/request-log"; @@ -360,3 +361,108 @@ describe("Anthropic response model identity", () => { expect(result.logCtx.resolvedModel).toBe("wire-model"); }); }); + +/** A real Anthropic Messages answer (JSON or SSE) whose `message.model` is `reported`. */ +function anthropicWireResponse(reported: unknown, stream: boolean): Response { + const message = { + id: "msg_fixture", type: "message", role: "assistant", model: reported, + content: [{ type: "text", text: "ok" }], stop_reason: "end_turn", stop_sequence: null, + usage: { input_tokens: 3, output_tokens: 2 }, + }; + if (!stream) return new Response(JSON.stringify(message), { status: 200, headers: { "content-type": "application/json" } }); + const frames: Array<[string, unknown]> = [ + ["message_start", { type: "message_start", message: { ...message, content: [], stop_reason: null, usage: { input_tokens: 3, output_tokens: 0 } } }], + ["content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }], + ["content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } }], + ["content_block_stop", { type: "content_block_stop", index: 0 }], + ["message_delta", { type: "message_delta", delta: { stop_reason: "end_turn", stop_sequence: null }, usage: { output_tokens: 2 } }], + ["message_stop", { type: "message_stop" }], + ]; + return new Response(frames.map(([event, data]) => `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`).join(""), + { status: 200, headers: { "content-type": "text/event-stream" } }); +} + +async function postAnthropicWire(args: { selector: string; reported: unknown; stream: boolean; providerName?: string }): Promise<{ logCtx: RequestLogContext; body: string }> { + const providerName = args.providerName ?? "fixture-anthropic"; + // A test may post several times; release the previous lease before taking the next. + releaseSpendHome?.(); + releaseSpendHome = acquireOwnedSpendHome(); + globalThis.fetch = (async () => anthropicWireResponse(args.reported, args.stream)) as unknown as typeof fetch; + const logCtx = { model: "", provider: "" } as RequestLogContext; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: args.selector, input: "ping", stream: args.stream }), + }), routedConfig(providerName, "anthropic", "claude-sonnet-5"), logCtx, {}); + const body = await response.text(); + // Non-vacuous: the Anthropic adapter answered and the row context was filled in. + expect(response.status).toBe(200); + expect(logCtx.provider).toBe(providerName); + return { logCtx, body }; +} + +describe("Anthropic adapter records the model the upstream reported", () => { + test.each([[false], [true]])("a reported wire model becomes the served model (stream=%p)", async stream => { + const { logCtx } = await postAnthropicWire({ selector: "fixture-anthropic/claude-sonnet-5", reported: "claude-sonnet-5", stream }); + expect(logCtx.servedModel).toBe("claude-sonnet-5"); + expect(modelIdentityLogFields(logCtx).servedModel).toBe("claude-sonnet-5"); + }); + + test.each([[false], [true]])("the client selector echoed upstream is not a served model (stream=%p)", async stream => { + for (const echo of ["fixture-anthropic/claude-sonnet-5"]) { + const { logCtx } = await postAnthropicWire({ selector: "fixture-anthropic/claude-sonnet-5", reported: echo, stream }); + expect(logCtx.servedModel).toBeUndefined(); + expect(modelIdentityLogFields(logCtx).servedModel).toBeUndefined(); + } + }); + + test.each([[false], [true]])("an unknown or credential-shaped reported model is dropped (stream=%p)", async stream => { + const key = "zq7Vb2LmN4pX9tR1sK8wD3fH6jY0cA5e"; + for (const reported of ["unlisted-model-9", key, 42]) { + const { logCtx, body } = await postAnthropicWire({ selector: "fixture-anthropic/claude-sonnet-5", reported, stream }); + expect(logCtx.servedModel).toBeUndefined(); + expect(JSON.stringify([body, logCtx.servedModel, logCtx.resolvedModel])).not.toContain(key); + } + }); + + test.each([[false], [true]])("a reported model that differs from the route is kept as a mismatch (stream=%p)", async stream => { + // The bundled metadata catalog knows claude-opus-5-5 for `anthropic-key` (an alias of `anthropic`), so a different + // known id is a real observation: served differs from wire, which is the reroute signal. + const { logCtx } = await postAnthropicWire({ selector: "anthropic-key/claude-sonnet-5", reported: "claude-opus-5-5", stream, providerName: "anthropic-key" }); + expect(logCtx.servedModel).toBe("claude-opus-5-5"); + expect(logCtx.wireModel ?? logCtx.model).not.toBe("claude-opus-5-5"); + expect(modelIdentityLogFields(logCtx).servedModel).toBe("claude-opus-5-5"); + }); + + test("the client still receives its own selector, not the upstream model", async () => { + const { body } = await postAnthropicWire({ selector: "fixture-anthropic/claude-sonnet-5", reported: "claude-sonnet-5", stream: false }); + expect((JSON.parse(body) as Record).model).toBe("fixture-anthropic/claude-sonnet-5"); + }); +}); + +// A forwarded credential returns from the served-model wrap before any later parser wrapping runs. +function forwardConfig(): OcxConfig { + const config = routedConfig("fixture-anthropic", "anthropic", "claude-sonnet-5"); + config.providers["fixture-anthropic"]!.authMode = "forward"; + return config; +} + +describe("served-model parser wrapping tolerates adapters without parseStream", () => { + test("a pre-send build failure propagates unchanged", async () => { + releaseSpendHome?.(); + releaseSpendHome = acquireOwnedSpendHome(); + const adapterSpy = spyOn(adapterResolveModule, "resolveAdapter").mockReturnValue({ + name: "openai-responses", + passthrough: true, + buildRequest: async () => { throw new Error("synthetic build failure"); }, + } as unknown as ReturnType); + try { + await expect(handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture-anthropic/claude-sonnet-5", input: "ping", stream: false }), + }), forwardConfig(), { model: "", provider: "" } as RequestLogContext, {})) + .rejects.toThrow("synthetic build failure"); + } finally { + adapterSpy.mockRestore(); + } + }); +}); From e8846decb6e47e2939dc472dc502b071f018096a Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:18:28 +0900 Subject: [PATCH 23/50] docs(es): restore Spanish localization parity on dev (#9322) --- docs-site/src/content/docs/es/guides/codex-integration.md | 7 +++++++ docs-site/src/content/docs/es/guides/combos.md | 5 +++++ docs-site/src/content/docs/es/guides/integrations.md | 2 +- docs-site/src/content/docs/es/reference/cli/lifecycle.md | 2 ++ 4 files changed, 15 insertions(+), 1 deletion(-) diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index 7f489e3b548..e44c17de5d5 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -760,6 +760,13 @@ Cuando opencodex se ejecuta como un [servicio de fondo](/es/reference/cli/lifecy La revista guarda los hashes originales `config.toml` y `opencodex.config.toml` más del estado OpenCodex inyectado. Un diario heredado o una interrupción antes de que se registraran esos hashes no pueden probar que el contenido posterior del archivo pertenezca a OpenCodex. Si cualquiera de los archivos difiere de su original guardado y carece de su propio hash de estado inyectado, la recuperación automática del diario y el error del informe de restauración nativa sin cambiar el archivo o la revista. El original guardado permanece disponible para la comparación; revíselo junto con los archivos actuales antes de elegir una acción de recuperación manual. +Ejecute `ocx doctor` en el host afectado. Su sección **Codex recovery journal** compara cada archivo +con el original e informa si el diario registró su estado inyectado. Por ejemplo, `config.toml` puede +diferir mientras que el perfil estaba ausente en ambos estados. La comparación funciona con el proxy +detenido y no imprime valores de configuración. Si alguno de los archivos no se puede leer de forma segura, +el informe lo nombra. Conserve los archivos actuales y el diario. +Una URL de enrutamiento local por sí sola no puede establecer qué ajustes escribió OpenCodex. + Los archivos que ya son iguales a sus originales guardados se aceptan sin reescribirlos. Un archivo faltante es distinto de un archivo vacío. Los hashes inyectados verificados aún permiten la restauración normal de instantáneas y las ediciones posteriores en configuraciones respaldadas por hash conservan el comportamiento de limpieza de campo propio existente. Sync y `ocx restore back` también rechazan una configuración enrutada existente cuyo diario sin hash no coincide con la línea base previa a la inyección. Esto evita que un nuevo hash de inyección se adhiera a un original más antiguo. Una configuración genuinamente nativa se puede guardar como una nueva línea de base antes de la inyección. El comportamiento explícito de exclusión de proveedores externos no se modifica. diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 74cd2989ade..e8b7451afc5 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -778,6 +778,11 @@ ocx combo remove --yes `set` también acepta `--strategy`, `--sticky`, `--effort`, `--alias`, `--native-alias`, `--allow-metered-targets on|off`, `--cooldown-reprobe on|off`, `--cooldown-reprobe-interval`, `--display-name`, `--description`, `--decision-provider`, `--decision-timeout` y `--rename-from`. Utilice `-` como el valor de `--effort`, `--alias`, `--display-name`, `--description`, `--decision-provider`, o `--decision-timeout` para borrar ese campo. Las dos opciones de decisión solo se aplican cuando la estrategia efectiva es JEV: al indicar `--strategy jev` o al omitir `--strategy` en un combo JEV existente. En un combo existente, `--targets` solo sustituye la lista de destinos; sin `--strategy`, conserva la estrategia guardada y sus ajustes JEV. `--native-alias` requiere un alias de modelo nativo desnudo actualmente soportado y un nombre de visualización no vacío. `create` y `update` son alias para `set`; `delete` es un alias para `remove`; y los mismos subcomandos están disponibles bajo `ocx route combo`. +En los proxies que admiten revisiones de combos, `set` informa de un conflicto si el combo de origen +cambia antes de que se guarde una edición o un cambio de nombre, o si el destino del cambio de nombre +ya está en uso. El comando termina con el código de salida 5. Ejecute `ocx combo list --json` para +revisar los combos actuales antes de volver a intentarlo. + ### API de administración diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index 2b0b7da4015..9810ce068f3 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -746,7 +746,7 @@ La app de escritorio Antigravity de Google (2.15 y posteriores) y la CLI `agy` ( funcionar a través del gateway de OpenCodex. Conéctalas desde el panel o desde una terminal: ```bash -ocx connect antigravity --model # configura ambos archivos de la app de escritorio +ocx connect antigravity --model # configure both desktop app settings files ocx connect agy # agy CLI: a marked shell function in your profiles ocx connect antigravity status # or: ocx connect agy status ocx disconnect antigravity # or: ocx disconnect agy diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 7f6b961092d..03fa8fea993 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -142,6 +142,8 @@ Si otro programa escucha en el puerto después de que terminen los procesos de e La parada solo finaliza la instancia activa. Los desencadenadores de inicio de sesión y desbloqueo de la tarea siguen habilitados, por lo que el proxy volverá a iniciarse en el siguiente inicio de sesión o desbloqueo; usa `ocx service uninstall` para eliminar el servicio. `ocx service stop`, `ocx service uninstall`, `ocx uninstall` y `ocx service install` usan la misma parada verificada: la desinstalación y la instalación rechazan eliminar o reemplazar la tarea si no se puede demostrar que el servicio está detenido, y la instalación también se detiene si otro programa ocupa el puerto. En Windows en Arm aún no se pueden finalizar los envoltorios, por lo que una parada que lo requiera devuelve `evidence-unreadable`; finaliza el envoltorio manualmente y vuelve a intentarlo. +Durante una instalación del Programador de tareas, el tiempo no utilizado del análisis de procesos puede dar a la CLI hasta cuatro segundos para verificar la tarea registrada y detener sus instancias en ejecución dentro del mismo plazo. + Para una adquisición aprobada por el escritorio, `ocx stop --json` también acepta el conjunto completo de `--expect-*` valores suministrados por `ocx resolve --json`. En Windows, esta parada vigilada puede detener una tarea del Programador de tareas solo cuando su definición registrada, el estado de ejecución y el antepasado de la envoltura demuestren que posee el proxy aprobado. Un servicio WinSW debe probar su ruta binaria instalada y la ascendencia PID del servicio. Después de detener cualquiera de los administradores, el CLI señala el proxy aprobado por separado y verifica que la tarea ya no se esté ejecutando, que no sobreviva ningún envoltorio y que se detenga WinSW. Un proceso `wscript.exe`, `cscript.exe` o `cmd.exe` con una línea de comandos ilegible en la cadena de supervisión del proxy aprobado (o sobrevivir bajo el administrador detenido) deja desconocida la propiedad del envoltorio, por lo que el stop vigilado no puede informar el éxito. La evidencia faltante o ilegible bloquea la parada vigilada. ### `ocx restart` From 0f2b1013cc7db5233edcba040da37e430bb00f09 Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:18:35 +0900 Subject: [PATCH 24/50] fix(subagents): resolve bare combo aliases in entryParts and subagentModelForce (carry #9150) (#9315) Carry of #9150 with combo-alias agent naming fix (name from roster entry as written; dedupe on name+route). Co-authored-by: Albi Fahrizqi <145648337+Verrat0@users.noreply.github.com> --- src/claude/agents-inject.ts | 8 +- src/claude/subagent-model.ts | 63 ++++++- structure/subagents.md | 2 +- .../claude-subagent-model-force.test.ts | 176 ++++++++++++++++++ tests/routing/combo-management-api.test.ts | 4 +- tests/server/subagent-model-force-api.test.ts | 69 +++++++ 6 files changed, 307 insertions(+), 15 deletions(-) diff --git a/src/claude/agents-inject.ts b/src/claude/agents-inject.ts index 4ed16454f3e..17b0bc1cfc3 100644 --- a/src/claude/agents-inject.ts +++ b/src/claude/agents-inject.ts @@ -99,9 +99,11 @@ export function buildClaudeAgentDefs( // main-session auto-context predicate (a 372K route marked [1m] would be // accounted at 1M with no compaction safety net in the subagent). const model = withSubagentContextMarker(alias, windows, accountsAt200k(config)); - const bare = alias.toLowerCase(); - if (coveredModels.has(bare)) return; - coveredModels.add(bare); + // Keyed by name and route: a repeated entry is one agent, but two spellings of one combo + // (`combo/old` and its alias) keep the distinct agents users already reference. + const covered = `${name}\n${alias.toLowerCase()}`; + if (coveredModels.has(covered)) return; + coveredModels.add(covered); let unique = name; for (let i = 2; usedNames.has(unique); i++) unique = `${name}-${i}`; usedNames.add(unique); diff --git a/src/claude/subagent-model.ts b/src/claude/subagent-model.ts index e7c04c8e5ed..813d62c37e3 100644 --- a/src/claude/subagent-model.ts +++ b/src/claude/subagent-model.ts @@ -7,11 +7,12 @@ import { knownModelIdsForProvider } from "../router"; import { decodeRoutedModelIdOrThrow } from "../providers/slug-codec"; import { SAFE_AGENT_MODEL_ID } from "../config/subagent-models"; import { resolveDesktop3pAlias } from "./desktop-3p"; +import { COMBO_NAMESPACE, isNativeAliasCombo, preservesPhysicalComboProvider, resolveComboId } from "../combos/identifiers"; export { SAFE_AGENT_MODEL_ID } from "../config/subagent-models"; -/** Roster entry -> alias + display parts. Entries are bare native slugs or "provider/id". - * Codex-facing encoded ids (`provider/vendor-model`) decode to the native slash id first - * so the alias joins the raw-native context-window map (context-windows.ts). */ +/** Roster entry -> alias + display parts. Entries are bare native slugs, configured combo aliases, + * or "provider/id". Codex-facing encoded ids (`provider/vendor-model`) decode to the native slash + * id first so the alias joins the raw-native context-window map (context-windows.ts). */ /** * Generated subagent defs cannot rely on the parent's auto-context compaction @@ -56,7 +57,44 @@ export function withSubagentContextMarker(selector: string, windows: Record + stripOneMillionMarker(disabled).toLowerCase() === canonical, + ); +} + +function bareNativeAliasComboId(entry: string, config: OcxConfig): string | null { + if (preservesPhysicalComboProvider(config)) return null; + const bare = stripOneMillionMarker(entry); + if (bare.startsWith(`${COMBO_NAMESPACE}/`)) return null; + const comboId = resolveComboId(config, bare); + return comboId && isNativeAliasCombo(config.combos?.[comboId] ?? {}) ? comboId : null; +} + +function nativePreservingEntryAlias(value: string, config: OcxConfig): string { + if (bareNativeAliasComboId(value, config)) return claudeCodeNativeAlias(value); + return entryParts(value, config).alias; +} + export function entryParts(entry: string, config: OcxConfig): { alias: string; id: string; provider: string } { + const bare = stripOneMillionMarker(entry); + const suffix = entry.slice(bare.length); + if (!preservesPhysicalComboProvider(config)) { + const comboId = resolveComboId(config, bare); + if (comboId) { + const bareNativeAlias = !bare.startsWith(`${COMBO_NAMESPACE}/`) + && isNativeAliasCombo(config.combos?.[comboId] ?? {}); + if (!bareNativeAlias || !isComboDisabled(config, comboId)) { + const canonical = `${comboId}${suffix}`; + // The route is the canonical combo; the id names the generated agent, so an alias keeps the + // agent name it had before aliases resolved here and existing references to it stay valid. + const aliasSlash = entry.indexOf("/"); + const id = bare.startsWith(`${COMBO_NAMESPACE}/`) ? canonical : entry.slice(aliasSlash + 1); + return { alias: claudeCodeAlias(COMBO_NAMESPACE, canonical), id, provider: COMBO_NAMESPACE }; + } + } + } const slash = entry.indexOf("/"); if (slash > 0) { const provider = entry.slice(0, slash); @@ -90,15 +128,20 @@ export function resolveSubagentForceModel(config: OcxConfig, windows: Record { - try { return selectorIdentity(entryParts(disabled, config).alias) === selectorIdentity(parts.alias); } catch { return false; } - })) return null; + let parts = entryParts(entry, config); const selectors = "selectors" in available ? available.selectors : available.entries.flatMap(candidate => { - try { return [entryParts(candidate, config).alias]; } catch { return []; } + try { return [nativePreservingEntryAlias(candidate, config)]; } catch { return []; } }); - const exposed = selectors.some(candidate => selectorIdentity(candidate) === selectorIdentity(parts.alias)); - if (!exposed) return null; + const isExposed = (alias: string) => selectors.some(candidate => selectorIdentity(candidate) === selectorIdentity(alias)); + if (!isExposed(parts.alias) && bareNativeAliasComboId(entry, config)) { + const nativeAlias = claudeCodeNativeAlias(entry); + if (isExposed(nativeAlias)) parts = { alias: nativeAlias, id: entry, provider: "native" }; + } + const targetIdentity = selectorIdentity(parts.alias); + if ((config.disabledModels ?? []).some(disabled => { + try { return selectorIdentity(nativePreservingEntryAlias(disabled, config)) === targetIdentity; } catch { return false; } + })) return null; + if (!isExposed(parts.alias)) return null; const bare = stripOneMillionMarker(parts.alias); const requestedMarker = bare !== parts.alias; const exactMarkedExposure = requestedMarker && selectors.some(candidate => diff --git a/structure/subagents.md b/structure/subagents.md index bb304a81f17..66793f7d90e 100644 --- a/structure/subagents.md +++ b/structure/subagents.md @@ -595,6 +595,6 @@ Automatic account exhaustion and recovery use the [spendable Codex credit eviden ### Forced Claude Code subagent model -`src/claude/subagent-model.ts` shares the roster alias and authoritative context-marker resolver with routed launch force. `claudeCode.subagentModelForce` is opt-in and default-off. Force availability excludes retained unavailable roster entries. Caller-added `[1m]` suffixes require a finite authoritative long window (`src/claude/long-context.ts`: 1M, or at least the 829,800 default compact window; a genuine 1M for Claude models on either Anthropic pool or a bare `claude-*` id) or an exact advertised marked identity; generated markers follow the same rule; exact upstream ids remain literal, while legacy roster marker handling is unchanged. `claudeCode.contextAccounting` `"200k"` stops automatic marking on generated and forced selectors; an explicit `[1m]` still follows the window rule above ([Claude Desktop picker mode](clients/claude-desktop.md#picker-mode-the-desktop-egress-proxy)). The generated-agent legacy directive cannot replace a wire selector matching the configured forced alias. `src/claude/subagent-force-status.ts` performs bounded, read-only server-local version and settings-key inspection; unknown is not supported. +`src/claude/subagent-model.ts` shares the roster alias and authoritative context-marker resolver with routed launch force. `entryParts` resolves configured combo aliases (including bare aliases) to canonical `combo/` aliases unless a physical `combo` provider is preserved or a `nativeAlias` combo is disabled in `disabledModels`, so roster generation, force exposure, disabled-model checks, and `[1m]` context lookup share the same combo identity while enabled native OpenAI slugs stay usable when a `nativeAlias` combo is disabled or omitted from catalog selectors. A generated agent keeps its name from the roster entry as written (`ocx-`), so existing references survive; only its model route is canonical. `claudeCode.subagentModelForce` is opt-in and default-off. Force availability excludes retained unavailable roster entries. Caller-added `[1m]` suffixes require a finite authoritative long window (`src/claude/long-context.ts`: 1M, or at least the 829,800 default compact window; a genuine 1M for Claude models on either Anthropic pool or a bare `claude-*` id) or an exact advertised marked identity; generated markers follow the same rule; exact upstream ids remain literal, while legacy roster marker handling is unchanged. `claudeCode.contextAccounting` `"200k"` stops automatic marking on generated and forced selectors; an explicit `[1m]` still follows the window rule above ([Claude Desktop picker mode](clients/claude-desktop.md#picker-mode-the-desktop-egress-proxy)). The generated-agent legacy directive cannot replace a wire selector matching the configured forced alias. `src/claude/subagent-force-status.ts` performs bounded, read-only server-local version and settings-key inspection; unknown is not supported. Explicit gateway selectors outrank generated-agent `ocx-route` fallback independently of saved force state. `src/claude/inbound-model-options.ts` shares this precedence across Messages and count-tokens; bare Claude fallback and requests without directives retain their existing behavior. Native Claude force targets use reversible native aliases, restored before existing credential/model-map checks. Connected launch exposure comes from fresh authenticated gateway rows, not cached context-window keys; acquisition is independent of cache-write success. diff --git a/tests/claude-integration/claude-subagent-model-force.test.ts b/tests/claude-integration/claude-subagent-model-force.test.ts index 78739c93c89..38a6813af9c 100644 --- a/tests/claude-integration/claude-subagent-model-force.test.ts +++ b/tests/claude-integration/claude-subagent-model-force.test.ts @@ -3,6 +3,7 @@ import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { delimiter, join } from "node:path"; import { buildClaudeEnv, buildNativeClaudeEnv } from "../../src/cli/claude"; +import { buildClaudeAgentDefs } from "../../src/claude/agents-inject"; import { entryParts, resolveSubagentForceModel, withSubagentContextMarker } from "../../src/claude/subagent-model"; import { inspectSubagentForceStatus, probeInstalledClaudeCodeVersion, subagentForceSupport } from "../../src/claude/subagent-force-status"; import { extractOcxRouteDirective } from "../../src/claude/inbound-model-options"; @@ -181,3 +182,178 @@ test("force preserves exact advertised genuine marked models and legacy alias id expect(resolveSubagentForceModel(config("mock/model[1m]"), { "ocx-claude-mock--model[1m]": 200000, "ocx-claude-mock--model": 1000000 }, { entries: ["mock/model"] })).toBeNull(); expect(withSubagentContextMarker("ocx-claude-mock--legacy[1m]", {})).toBe("ocx-claude-mock--legacy[1m]"); }); + +test("bare combo aliases resolve to canonical combo selectors across entryParts, force, [1m], disabledModels and agents-inject", () => { + const comboCfg = (force?: string, overrides: Partial = {}): OcxConfig => ({ + ...config(force), + combos: { + "bare-combo": { alias: "bare-combo", targets: [{ provider: "ollama", model: "qwen3" }] }, + "combo-id": { alias: "aliased-combo", targets: [{ provider: "ollama", model: "qwen3" }] }, + fast: { alias: "team/fast", targets: [{ provider: "ollama", model: "qwen3" }] }, + }, + ...overrides, + }); + + expect(entryParts("bare-combo", comboCfg())).toEqual({ alias: "ocx-claude-combo--bare-combo", id: "bare-combo", provider: "combo" }); + expect(entryParts("combo/bare-combo", comboCfg())).toEqual({ alias: "ocx-claude-combo--bare-combo", id: "bare-combo", provider: "combo" }); + expect(entryParts("bare-combo[1m]", comboCfg())).toEqual({ alias: "ocx-claude-combo--bare-combo[1m]", id: "bare-combo[1m]", provider: "combo" }); + expect(entryParts("bare-combo[1M]", comboCfg())).toEqual({ alias: "ocx-claude-combo--bare-combo[1M]", id: "bare-combo[1M]", provider: "combo" }); + expect(entryParts("aliased-combo", comboCfg())).toEqual({ alias: "ocx-claude-combo--combo-id", id: "aliased-combo", provider: "combo" }); + expect(entryParts("combo/combo-id", comboCfg())).toEqual({ alias: "ocx-claude-combo--combo-id", id: "combo-id", provider: "combo" }); + expect(entryParts("team/fast", comboCfg())).toEqual({ alias: "ocx-claude-combo--fast", id: "fast", provider: "combo" }); + + const selector = "ocx-claude-combo--bare-combo"; + for (const force of ["bare-combo", "combo/bare-combo"]) { + const c = comboCfg(force); + expect(resolveSubagentForceModel(c, {}, { entries: ["bare-combo"] })).toBe(selector); + expect(resolveSubagentForceModel(c, {}, { selectors: [selector] })).toBe(selector); + expect(resolveSubagentForceModel(c, { [selector]: 829_799 }, { entries: ["bare-combo"] })).toBe(selector); + expect(resolveSubagentForceModel(c, { [selector]: 829_800 }, { entries: ["bare-combo"] })).toBe(`${selector}[1m]`); + expect(resolveSubagentForceModel(c, { [selector]: 1_000_000 }, { selectors: [selector] })).toBe(`${selector}[1m]`); + } + + expect(resolveSubagentForceModel(comboCfg("bare-combo[1m]"), {}, { entries: ["bare-combo"] })).toBeNull(); + expect(resolveSubagentForceModel(comboCfg("bare-combo[1m]"), { [selector]: 1_000_000 }, { entries: ["bare-combo"] })).toBe(`${selector}[1m]`); + expect(resolveSubagentForceModel(comboCfg("bare-combo[1M]"), {}, { entries: ["bare-combo"] })).toBeNull(); + expect(resolveSubagentForceModel(comboCfg("bare-combo[1M]"), { [selector]: 1_000_000 }, { entries: ["bare-combo"] })).toBe(`${selector}[1M]`); + expect(resolveSubagentForceModel(comboCfg("aliased-combo"), {}, { entries: ["aliased-combo"] })).toBe("ocx-claude-combo--combo-id"); + expect(resolveSubagentForceModel(comboCfg("combo/combo-id"), {}, { entries: ["aliased-combo"] })).toBe("ocx-claude-combo--combo-id"); + expect(resolveSubagentForceModel(comboCfg("aliased-combo"), {}, { selectors: ["ocx-claude-combo--combo-id"] })).toBe("ocx-claude-combo--combo-id"); + expect(resolveSubagentForceModel(comboCfg("team/fast"), {}, { entries: ["team/fast"] })).toBe("ocx-claude-combo--fast"); + expect(resolveSubagentForceModel(comboCfg("team/fast"), {}, { selectors: ["ocx-claude-combo--fast"] })).toBe("ocx-claude-combo--fast"); + + expect(resolveSubagentForceModel(comboCfg("bare-combo", { disabledModels: ["combo/bare-combo"] }), {}, { entries: ["bare-combo"] })).toBeNull(); + expect(resolveSubagentForceModel(comboCfg("combo/bare-combo", { disabledModels: ["bare-combo"] }), {}, { selectors: [selector] })).toBeNull(); + + const localEnv = buildClaudeEnv(comboCfg("bare-combo"), 10100, {}, { [selector]: 1_000_000 }, { ...deps, forceAvailable: ["bare-combo"] }); + expect(localEnv[MODEL]).toBe(`${selector}[1m]`); + expect(localEnv[FORCE]).toBe("1"); + const connectedEnv = buildClaudeEnv(comboCfg("bare-combo"), 10100, {}, { [selector]: 1_000_000 }, { ...deps, forceAvailable: undefined, forceAvailableSelectors: [selector] }); + expect(connectedEnv[MODEL]).toBe(`${selector}[1m]`); + expect(connectedEnv[FORCE]).toBe("1"); + + const dir = mkdtempSync(join(tmpdir(), "ocx-bare-combo-agents-")); + try { + const defs = buildClaudeAgentDefs(comboCfg(undefined, { subagentModels: ["bare-combo", "combo/bare-combo", "aliased-combo"] }), { [selector]: 1_000_000 }, dir); + expect(defs.map(d => ({ name: d.name, model: d.model, file: d.file }))).toEqual([ + { name: "ocx-bare-combo", model: `${selector}[1m]`, file: "ocx-bare-combo.md" }, + // An alias keeps the agent name it generated before aliases resolved to the combo route. + { name: "ocx-aliased-combo", model: "ocx-claude-combo--combo-id", file: "ocx-aliased-combo.md" }, + ]); + expect(defs[0]?.description).toContain("bare-combo (combo)"); + expect(defs[1]?.description).toContain("aliased-combo (combo)"); + } finally { + removeTreeWithRetry(dir); + } +}); + +test("physical combo provider without configured combos preserves routed decoding", () => { + const physicalCfg: OcxConfig = { + ...config("combo/vendor-model"), + providers: { + combo: { baseUrl: "https://example.invalid", apiKey: "k", api: "openai-completions", models: ["vendor/model"] }, + }, + combos: {}, + }; + expect(entryParts("combo/vendor-model", physicalCfg)).toEqual({ + alias: "ocx-claude2-combo--vendor~smodel", + id: "vendor/model", + provider: "combo", + }); + expect(resolveSubagentForceModel(physicalCfg, {}, { entries: ["combo/vendor-model"] })) + .toBe("ocx-claude2-combo--vendor~smodel"); + expect(resolveSubagentForceModel(physicalCfg, {}, { selectors: ["ocx-claude2-combo--vendor~smodel"] })) + .toBe("ocx-claude2-combo--vendor~smodel"); +}); + +test("nativeAlias combo disable and catalog omission preserve still-enabled native OpenAI slug", () => { + const nativeAliasCfg = (force?: string, overrides: Partial = {}): OcxConfig => ({ + ...config(force), + combos: { + astra: { alias: "gpt-6.2-astra", nativeAlias: true, targets: [{ provider: "ollama", model: "qwen3" }] }, + }, + ...overrides, + }); + + // Native disabled: combo remains forceable via canonical combo/astra. + expect(resolveSubagentForceModel( + nativeAliasCfg("combo/astra", { disabledModels: ["gpt-6.2-astra"] }), + {}, + { selectors: ["ocx-claude-combo--astra"] }, + )).toBe("ocx-claude-combo--astra"); + expect(resolveSubagentForceModel( + nativeAliasCfg("combo/astra", { disabledModels: ["gpt-6.2-astra"] }), + {}, + { entries: ["combo/astra"] }, + )).toBe("ocx-claude-combo--astra"); + + // Combo disabled: bare native slug falls back to native OpenAI model across entryParts, force, and agents-inject. + const disabledComboCfg = nativeAliasCfg("gpt-6.2-astra", { disabledModels: ["combo/astra"] }); + expect(entryParts("gpt-6.2-astra", disabledComboCfg)).toEqual({ + alias: "ocx-claude-native--gpt-6.2-astra", + id: "gpt-6.2-astra", + provider: "native", + }); + expect(resolveSubagentForceModel(disabledComboCfg, {}, { entries: ["gpt-6.2-astra"] })) + .toBe("ocx-claude-native--gpt-6.2-astra"); + expect(resolveSubagentForceModel(disabledComboCfg, {}, { selectors: ["ocx-claude-native--gpt-6.2-astra"] })) + .toBe("ocx-claude-native--gpt-6.2-astra"); + expect(resolveSubagentForceModel( + nativeAliasCfg("combo/astra", { disabledModels: ["combo/astra"] }), + {}, + { selectors: ["ocx-claude-combo--astra", "ocx-claude-native--gpt-6.2-astra"] }, + )).toBeNull(); + expect(resolveSubagentForceModel( + nativeAliasCfg("gpt-6.2-astra", { disabledModels: ["combo/astra", "gpt-6.2-astra"] }), + {}, + { selectors: ["ocx-claude-native--gpt-6.2-astra"] }, + )).toBeNull(); + + const dir = mkdtempSync(join(tmpdir(), "ocx-native-alias-disabled-")); + try { + const defs = buildClaudeAgentDefs( + nativeAliasCfg(undefined, { disabledModels: ["combo/astra"], subagentModels: ["gpt-6.2-astra"] }), + {}, + dir, + ); + expect(defs.map(d => ({ name: d.name, model: d.model, file: d.file }))).toEqual([ + { name: "ocx-gpt-6-2-astra", model: "ocx-claude-native--gpt-6.2-astra", file: "ocx-gpt-6-2-astra.md" }, + ]); + expect(defs[0]?.description).toContain("gpt-6.2-astra (native)"); + } finally { + removeTreeWithRetry(dir); + } + + // Unhealthy nativeAlias combo omitted from catalog while native OpenAI model is exposed. + expect(resolveSubagentForceModel( + nativeAliasCfg("gpt-6.2-astra"), + {}, + { selectors: ["ocx-claude-native--gpt-6.2-astra"] }, + )).toBe("ocx-claude-native--gpt-6.2-astra"); + expect(resolveSubagentForceModel( + nativeAliasCfg("gpt-6.2-astra", { disabledModels: ["gpt-6.2-astra"] }), + {}, + { selectors: ["ocx-claude-native--gpt-6.2-astra"] }, + )).toBeNull(); + expect(resolveSubagentForceModel( + nativeAliasCfg("combo/astra"), + {}, + { selectors: ["ocx-claude-native--gpt-6.2-astra"] }, + )).toBeNull(); + // Same omission invariant through the entries exposure path (GET/PUT /api/subagent-models). + expect(resolveSubagentForceModel( + nativeAliasCfg("gpt-6.2-astra"), + {}, + { entries: ["gpt-6.2-astra"] }, + )).toBe("ocx-claude-native--gpt-6.2-astra"); + expect(resolveSubagentForceModel( + nativeAliasCfg("gpt-6.2-astra", { disabledModels: ["gpt-6.2-astra"] }), + {}, + { entries: ["gpt-6.2-astra"] }, + )).toBeNull(); + expect(resolveSubagentForceModel( + nativeAliasCfg("combo/astra"), + {}, + { entries: ["gpt-6.2-astra"] }, + )).toBeNull(); +}); diff --git a/tests/routing/combo-management-api.test.ts b/tests/routing/combo-management-api.test.ts index e500ab9320f..c4cbdbf81db 100644 --- a/tests/routing/combo-management-api.test.ts +++ b/tests/routing/combo-management-api.test.ts @@ -1175,7 +1175,8 @@ describe("combo management API", () => { }); saveConfig(config); injectClaudeAgentDefs(config, {}); - expect(readdirSync(join(process.env.CLAUDE_CONFIG_DIR!, "agents"))).toContain("ocx-old-public.md"); + // Both spellings of the combo keep the agent names they generated before aliases resolved. + expect(readdirSync(join(process.env.CLAUDE_CONFIG_DIR!, "agents"))).toEqual(expect.arrayContaining(["ocx-old.md", "ocx-old-public.md"])); const oldCombo = getCombo(config, "old")!; const oldPick = pickComboTarget(config, "old")!; noteComboSuccess("old", oldCombo, oldPick.target); @@ -1221,6 +1222,7 @@ describe("combo management API", () => { expect(agentBodies).toContain("new-public"); expect(agentBodies).not.toContain("old-public"); expect(agentBodies).not.toContain("combo/old"); + expect(agentBodies).not.toContain("ocx-claude-combo--old"); expect(isComboTargetInCooldown("old", { provider: "a", model: "m1" })).toBe(false); expect(isComboTargetInCooldown("new", { provider: "b", model: "m2" })).toBe(false); expect(pickComboTarget(config, "new")?.target.provider).toBe("b"); diff --git a/tests/server/subagent-model-force-api.test.ts b/tests/server/subagent-model-force-api.test.ts index 12e0215d412..c5fc3df0da1 100644 --- a/tests/server/subagent-model-force-api.test.ts +++ b/tests/server/subagent-model-force-api.test.ts @@ -193,3 +193,72 @@ test("force API keeps genuine marked catalog entries and ordinary unmarked write expect(live.claudeCode?.subagentModelForce).toBe(force); } }); + +test("force GET/PUT accepts bare combo alias and canonical combo/ for bare-aliased combos", async () => { + const bareComboConfig = (force?: string, disabledModels?: string[]): OcxConfig => ({ + ...cfg(), + combos: { + "bare-combo": { alias: "bare-combo", targets: [{ provider: "ollama", model: "qwen3" }] }, + }, + ...(disabledModels ? { disabledModels } : {}), + claudeCode: { subagentEffort: "high", model: "keep", ...(force === undefined ? {} : { subagentModelForce: force }) }, + }); + const fetchBareCombo = async () => [{ provider: "combo", id: "bare-combo", alias: "bare-combo" }]; + + for (const force of ["bare-combo", "combo/bare-combo"]) { + const live = bareComboConfig(); + const putCtx = context(live, { force }); + putCtx.deps.fetchAllModels = fetchBareCombo; + const putRes = await handleSubagentModelRoutes(putCtx, apply); + expect(putRes?.status).toBe(200); + expect(await putRes!.json()).toMatchObject({ ok: true, force }); + expect(live.claudeCode?.subagentModelForce).toBe(force); + + const getUrl = new URL("http://localhost/api/subagent-models"); + const getCtx: ManagementContext = { + ...putCtx, + url: getUrl, + req: new Request(getUrl, { method: "GET" }), + }; + const getRes = await handleSubagentModelRoutes(getCtx, apply); + expect(getRes?.status).toBe(200); + const getBody = await getRes!.json() as { force: string | null; forceAvailable: string[]; forceStatus: { targetValid: boolean } | null }; + expect(getBody.force).toBe(force); + expect(getBody.forceAvailable).toContain("bare-combo"); + expect(getBody.forceStatus?.targetValid).toBe(true); + } + + for (const disabled of [["bare-combo"], ["combo/bare-combo"]]) { + for (const force of ["bare-combo", "combo/bare-combo"]) { + const live = bareComboConfig(undefined, disabled); + const putCtx = context(live, { force }); + putCtx.deps.fetchAllModels = fetchBareCombo; + expect((await handleSubagentModelRoutes(putCtx, apply))?.status).toBe(400); + expect(putCtx.deps.saveConfigPreservingClaudeCode).not.toHaveBeenCalled(); + } + } + + // Omitted nativeAlias combo must stay invalid as canonical combo/ even when its native slug is exposed. + const omittedNativeAliasCfg: OcxConfig = { + ...cfg(), + combos: { + astra: { alias: "gpt-6.2-astra", nativeAlias: true, targets: [{ provider: "ollama", model: "qwen3" }] }, + }, + claudeCode: { subagentEffort: "high", model: "keep", subagentModelForce: "combo/astra" }, + }; + const omittedGetUrl = new URL("http://localhost/api/subagent-models"); + const omittedGetCtx: ManagementContext = { + ...context(omittedNativeAliasCfg, {}), + url: omittedGetUrl, + req: new Request(omittedGetUrl, { method: "GET" }), + }; + omittedGetCtx.deps.fetchAllModels = async () => []; + const omittedGetRes = await handleSubagentModelRoutes(omittedGetCtx, apply); + expect(omittedGetRes?.status).toBe(200); + const omittedGetBody = await omittedGetRes!.json() as { forceStatus: { targetValid: boolean } | null }; + expect(omittedGetBody.forceStatus?.targetValid).toBe(false); + + const omittedPutCtx = context({ ...omittedNativeAliasCfg, claudeCode: { subagentEffort: "high", model: "keep" } }, { force: "combo/astra" }); + omittedPutCtx.deps.fetchAllModels = async () => []; + expect((await handleSubagentModelRoutes(omittedPutCtx, apply))?.status).toBe(400); +}); From 18d27c161be049db743b1d7d1745a5e709394cf3 Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:18:45 +0900 Subject: [PATCH 25/50] fix(responses): synthesize a result for a dangling shell call (carry #9259) (#9316) Carry of #9259 (synthesizes result for dangling shell_call and lowers orphaned shell_call_output to a labeled user message). Co-authored-by: lcxhh <59329914+lcxhh521@users.noreply.github.com> --- .../openai-responses/tool-output-recovery.ts | 65 ++++++++++++++-- ...ses-stateless-dangling-call-repair.test.ts | 78 ++++++++++++++++++- 2 files changed, 135 insertions(+), 8 deletions(-) diff --git a/src/adapters/openai-responses/tool-output-recovery.ts b/src/adapters/openai-responses/tool-output-recovery.ts index c0ce0260525..f20b60bfd52 100644 --- a/src/adapters/openai-responses/tool-output-recovery.ts +++ b/src/adapters/openai-responses/tool-output-recovery.ts @@ -122,6 +122,23 @@ function orphanedToolOutputContent(output: unknown, callId = ""): Record 0) pieces.push(field); + } + const outcome = chunk.outcome; + if (isPlainObject(outcome) && outcome.type === "timeout") pieces.push("[timeout]"); + else if (isPlainObject(outcome) && outcome.type === "exit" && typeof outcome.exit_code === "number") pieces.push(`[exit ${outcome.exit_code}]`); + } + return pieces.join("\n"); +} + /** True when a Responses tool output item is present but carries no usable content. */ function isToolOutputEmpty(output: unknown): boolean { if (typeof output === "string") return output.trim() === ""; @@ -197,7 +214,7 @@ export function repairUnidentifiedToolOutputItems(body: unknown): unknown { * expansion misses (proxy restart, unrecorded prior turn), previous_response_id is stripped * (the ChatGPT backend rejects it), so the delta may carry items that reference now-absent * prior items and 400 upstream: - * - `function_call`/`local_shell_call`/`custom_tool_call` without their paired output item + * - `function_call`/`local_shell_call`/`shell_call`/`custom_tool_call` without their paired output item * ("No tool output found for tool call "). A stateless upstream cannot resolve * the pair from its own storage, so a placeholder output is synthesized to keep the * turn continuable without pretending the result was real. Synthetic outputs are @@ -210,7 +227,10 @@ export function repairUnidentifiedToolOutputItems(body: unknown): unknown { * `repairOrphanOutputs` is enabled * ("No tool call found for function call output with call_id ..."). Converted to user * messages so the result text survives. `function_call_output` also pairs with - * `local_shell_call` (codex-rs emits shell outputs as function_call_output). + * `local_shell_call` (codex-rs emits shell outputs as function_call_output). A hosted + * `shell_call` is satisfied by `shell_call_output` or `function_call_output`; a missing + * result is still synthesized as `function_call_output`. The hosted output item itself + * is left unchanged. * - `reasoning` items ("Item 'rs_*' ... was provided without its required following item"). * Dropped, but only when `dropReasoning` (unexpanded miss): on a replay hit the prior * reasoning chain is intact and must be preserved. @@ -378,9 +398,9 @@ export function repairOrphanedInputItems( const customOutputIds = new Set(); for (const item of input) { if (!isPlainObject(item) || typeof item.call_id !== "string") continue; - if (item.type === "function_call" || item.type === "local_shell_call") functionCallIds.add(item.call_id); + if (item.type === "function_call" || item.type === "local_shell_call" || item.type === "shell_call") functionCallIds.add(item.call_id); else if (item.type === "custom_tool_call") customCallIds.add(item.call_id); - else if (item.type === "function_call_output") functionOutputIds.add(item.call_id); + else if (item.type === "function_call_output" || item.type === "shell_call_output") functionOutputIds.add(item.call_id); else if (item.type === "custom_tool_call_output") customOutputIds.add(item.call_id); } @@ -396,6 +416,24 @@ export function repairOrphanedInputItems( for (const item of input) { if (!isPlainObject(item)) { flushPendingSyntheticOutputs(); repaired.push(item); continue; } if (dropReasoning && item.type === "reasoning") { changed = true; continue; } + // A hosted shell result whose call is absent is the same orphan as a function output: keep its + // text as a labeled user message instead of leaving an unresolved reference upstream. + if (item.type === "shell_call_output" && repairOrphanOutputs) { + const callId = typeof item.call_id === "string" ? item.call_id : ""; + if (callId.length > 0 && !functionCallIds.has(callId)) { + flushPendingSyntheticOutputs(); + changed = true; + const text = hostedShellOutputText(item.output); + const msg: Record = { + type: "message", + role: "user", + content: [{ type: "input_text", text: `[tool output for ${callId}]${text ? `\n${text}` : ""}` }], + }; + copyItemProvenance(item, msg); + repaired.push(msg); + continue; + } + } const isFnOutput = item.type === "function_call_output"; const isCustomOutput = item.type === "custom_tool_call_output"; if (isFnOutput || isCustomOutput) { @@ -428,7 +466,7 @@ export function repairOrphanedInputItems( continue; } } - const isFnCall = item.type === "function_call" || item.type === "local_shell_call"; + const isFnCall = item.type === "function_call" || item.type === "local_shell_call" || item.type === "shell_call"; const isCustomCall = item.type === "custom_tool_call"; if (isFnCall || isCustomCall) { repaired.push(item); @@ -456,13 +494,13 @@ export function repairOrphanedInputItems( const callKeyOf = (item: unknown): string | null => { if (!isPlainObject(item) || typeof item.call_id !== "string") return null; - if (item.type === "function_call" || item.type === "local_shell_call") return `function:${item.call_id}`; + if (item.type === "function_call" || item.type === "local_shell_call" || item.type === "shell_call") return `function:${item.call_id}`; if (item.type === "custom_tool_call") return `custom:${item.call_id}`; return null; }; const outputKeyOf = (item: unknown): string | null => { if (!isPlainObject(item) || typeof item.call_id !== "string") return null; - if (item.type === "function_call_output") return `function:${item.call_id}`; + if (item.type === "function_call_output" || item.type === "shell_call_output") return `function:${item.call_id}`; if (item.type === "custom_tool_call_output") return `custom:${item.call_id}`; return null; }; @@ -625,6 +663,18 @@ function normalizeAdjacentToolBatches(body: unknown): unknown { else map.set(key, [index]); }; + // A placeholder for a dangling shell_call is a function_call_output, but the call stays a + // shell_call. Indexing that output with no call makes this pass return the body unchanged + // and skips every other batch. Ignore only that placeholder. A real shell_call_output is + // not indexed here, so a complete hosted pair still does not join the reordering. + const shellIds = new Set(); + const functionIds = new Set(); + for (const item of input) { + if (!isPlainObject(item) || typeof item.call_id !== "string" || item.call_id.length === 0) continue; + if (item.type === "shell_call") shellIds.add(item.call_id); + else if (item.type === "function_call" || item.type === "local_shell_call") functionIds.add(item.call_id); + } + const shellOnly = new Set([...shellIds].filter(id => !functionIds.has(id))); for (let index = 0; index < input.length; index += 1) { const item = input[index]; if (!isPlainObject(item) || typeof item.call_id !== "string" || item.call_id.length === 0) continue; @@ -633,6 +683,7 @@ function normalizeAdjacentToolBatches(body: unknown): unknown { } else if (item.type === "custom_tool_call") { appendIndex(calls, `custom:${item.call_id}`, index); } else if (item.type === "function_call_output") { + if (shellOnly.has(item.call_id)) continue; appendIndex(outputs, `function:${item.call_id}`, index); } else if (item.type === "custom_tool_call_output") { appendIndex(outputs, `custom:${item.call_id}`, index); diff --git a/tests/responses/responses-stateless-dangling-call-repair.test.ts b/tests/responses/responses-stateless-dangling-call-repair.test.ts index 224e37688db..9529dc3e38e 100644 --- a/tests/responses/responses-stateless-dangling-call-repair.test.ts +++ b/tests/responses/responses-stateless-dangling-call-repair.test.ts @@ -2,13 +2,14 @@ * Stateless Responses wire repair for orphaned tool CALLS. * * DeepSeek's official Responses route is stateless and strict: a `function_call`, - * `local_shell_call`, or `custom_tool_call` item with no matching output item in the same + * `local_shell_call`, `shell_call`, or `custom_tool_call` item with no matching output item in the same * body 400s with "No tool output found for tool call ". A Codex thread can reach * that state when an interrupted tool turn records the call but not its late-arriving * result. ocx already repaired orphaned OUTPUTS (output without call); these tests pin the * mirrored repair: synthesize an honest placeholder output right after the orphaned call. */ import { afterEach, describe, expect, test } from "bun:test"; +import { repairOrphanedInputItems } from "../../src/adapters/openai-responses/tool-output-recovery"; import { providerConfigSeed } from "../../src/providers/derive"; import { getProviderRegistryEntry } from "../../src/providers/registry"; import { handleResponses } from "../../src/server/responses/core"; @@ -85,6 +86,81 @@ describe("stateless Responses wire repairs orphaned tool calls", () => { expect(String((input[1] as { output: unknown }).output)).toContain("no tool result was recorded"); }); + test("synthesizes a function_call_output after a dangling shell_call", async () => { + const { body } = await drive([ + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + ]); + const input = body.input as Array>; + expect(input[0]).toMatchObject({ type: "shell_call", call_id: "hosted-shell" }); + expect(input[1]).toMatchObject({ type: "function_call_output", call_id: "hosted-shell" }); + expect(String((input[1] as { output: unknown }).output)).toContain("no tool result was recorded"); + expect(input).toHaveLength(2); + }); + + test("keeps a shell_call_output instead of synthesizing a second result", async () => { + const { body } = await drive([ + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "shell_call_output", call_id: "hosted-shell", output: "ok" }, + ]); + const input = body.input as Array>; + expect(input.map(item => item.type)).toEqual(["shell_call", "shell_call_output"]); + expect(input[1]).toMatchObject({ call_id: "hosted-shell", output: "ok" }); + }); + + test("lowers an orphaned shell_call_output to a labeled user message with its text", async () => { + const { body } = await drive([ + { type: "shell_call_output", call_id: "gone-shell", output: [ + { stdout: "listing", stderr: "", outcome: { type: "exit", exit_code: 0 } }, + ] }, + { type: "message", role: "user", content: [{ type: "input_text", text: "next" }] }, + ]); + const input = body.input as Array>; + expect(input.some(item => item.type === "shell_call_output")).toBe(false); + expect(input[0]).toMatchObject({ type: "message", role: "user" }); + expect(JSON.stringify(input[0])).toContain("[tool output for gone-shell]\\nlisting\\n[exit 0]"); + }); + + test("a dangling shell placeholder does not block function-call adjacency", async () => { + const { body } = await drive([ + { type: "reasoning", id: "rs_1", summary: [{ type: "summary_text", text: "thinking" }] }, + { type: "function_call", id: "fc_a", call_id: "call_a", name: "exec_command", arguments: "{}" }, + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "message", role: "developer", content: [{ type: "input_text", text: "hook" }] }, + { type: "function_call_output", call_id: "call_a", output: "ok" }, + ]); + const input = body.input as Array>; + expect(input.map(item => item.type === "message" || item.type === "reasoning" ? item.type : `${item.type}:${item.call_id}`)).toEqual([ + "reasoning", + "function_call:call_a", + "function_call_output:call_a", + "shell_call:hosted-shell", + "function_call_output:hosted-shell", + "message", + ]); + }); + + test("keeps a hosted shell output in call order inside a repaired batch", () => { + const repaired = repairOrphanedInputItems({ + input: [ + { type: "function_call", call_id: "call_f", name: "exec_command", arguments: "{}" }, + { type: "shell_call", call_id: "hosted-shell", action: { commands: ["pwd"] } }, + { type: "function_call", call_id: "call_g", name: "exec_command", arguments: "{}" }, + { type: "shell_call_output", call_id: "hosted-shell", output: "pwd-out" }, + { type: "function_call_output", call_id: "call_g", output: "G" }, + ], + }, false, true, true) as { input: Array> }; + expect(repaired.input.map(item => `${item.type}:${item.call_id}`)).toEqual([ + "function_call:call_f", + "shell_call:hosted-shell", + "function_call:call_g", + "function_call_output:call_f", + "shell_call_output:hosted-shell", + "function_call_output:call_g", + ]); + expect(repaired.input[4]).toMatchObject({ output: "pwd-out" }); + expect(String(repaired.input[3]?.output)).toContain("no tool result was recorded"); + }); + test("synthesizes a custom_tool_call_output after a dangling custom_tool_call", async () => { const { body } = await drive([ { type: "custom_tool_call", id: "ctc_1", call_id: "call_dangling_ct", name: "custom_probe", input: "{}" }, From e87efd419d73577b57b512ebbf0c897920172ada Mon Sep 17 00:00:00 2001 From: Chenyu Shi Date: Thu, 3 Dec 2026 23:21:10 +0800 Subject: [PATCH 26/50] feat(gui,docs): surface Antigravity gateway clients in Route (#9210) * feat(gui,docs): surface Antigravity gateway clients in Route and support matrix Add a read-only Gateway clients section for Antigravity (desktop) and agy (CLI) in Route -> Clients using Route card state styling, propagate AbortSignal cancellation in loadGatewayClientOverview, and generate gateway client entries across localized READMEs and client support matrix docs (with unified Enrutamiento/Routage navigation labels). Refs #9204 * fix(gui): keep a connected agy connected when its URL is exported * fix(gui): keep gateway client links inside their cards * docs: list the Gemini endpoints on the client support pages * fix(gui): show unknown when Antigravity settings can't be parsed * fix(gui): use hash buttons, reject malformed gateway rows, and invalidate caches * fix(gui): keep gateway badges in card header and avoid redundant refresh --------- Co-authored-by: JUN --- README.md | 2 + .../docs/es/reference/client-support.md | 17 ++- .../docs/fr/reference/client-support.md | 17 ++- .../docs/ja/reference/client-support.md | 17 ++- .../docs/ko/reference/client-support.md | 17 ++- .../content/docs/reference/client-support.md | 17 ++- .../docs/ru/reference/client-support.md | 17 ++- .../docs/tr/reference/client-support.md | 17 ++- .../docs/zh-cn/reference/client-support.md | 17 ++- .../docs/zh-tw/reference/client-support.md | 17 ++- gui/src/design/pages/connect.css | 1 + gui/src/i18n/gateway-clients-copy.ts | 6 + .../integrations/GatewayClientsOverview.tsx | 70 ++++++++++++ .../pages/integrations/GatewayClientsPage.tsx | 5 +- .../integrations/IntegrationsOverview.tsx | 3 + .../pages/integrations/gateway-clients-api.ts | 55 ++++++++- gui/tests/gateway-clients-api.test.ts | 79 ++++++++++++- gui/tests/gateway-clients-page.test.tsx | 105 +++++++++++++++++- readme/README.es.md | 2 + readme/README.fr.md | 2 + readme/README.ja.md | 2 + readme/README.ko.md | 2 + readme/README.ru.md | 2 + readme/README.tr.md | 2 + readme/README.zh-CN.md | 2 + readme/README.zh-TW.md | 2 + readme/i18n-manifest.json | 16 +-- scripts/client-support-matrix/locales.ts | 84 +++++++++----- scripts/client-support-matrix/metadata.ts | 21 +++- scripts/generate-client-support-matrix.ts | 74 +++++++++--- structure/clients/antigravity-gateway.md | 8 ++ structure/clients/client-support-matrix.md | 12 +- .../client-support-matrix.test.ts | 34 +++++- .../client-support-runtime.test.ts | 23 +++- tests/clients/gateway-clients.test.ts | 1 + 35 files changed, 672 insertions(+), 96 deletions(-) create mode 100644 gui/src/pages/integrations/GatewayClientsOverview.tsx diff --git a/README.md b/README.md index 18ab5e06d03..97474781ae5 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,8 @@ Connect the tool you already use: | Claude Code | With the `claude` CLI installed, run `ocx claude`. It starts the proxy if needed and launches Claude Code through it. | | Claude Desktop | Run `ocx claude desktop`. On a new install it sets up the gateway profile for the whole app; an existing first-party setup is kept, and `ocx claude desktop apply --gateway` switches explicitly. See the [Claude Code guide](https://opencodex.me/guides/claude-code/). Fully quit and reopen Claude Desktop after a switch. | | Grok Build | On a local listener with Grok integration enabled, `ocx start` registers the models when `~/.grok` exists; pick an `ocx-*` model in Grok Build. Remote setups: see the [Grok Build guide](https://opencodex.me/guides/grok-build/). After adding providers, restart the proxy (or run `ocx ensure` when Codex autostart is enabled) to refresh the list. | +| Google Antigravity (desktop) | On the dashboard, open **Route → Antigravity** (also linked from **Route → Clients**), or run `ocx connect antigravity` on the machine where it is installed. | +| agy (CLI) | Use **Route → Antigravity** or run `ocx connect agy` on the machine where it is installed. Reload the indicated shell profile before running `agy`. | | Tools with a managed integration | Use the dashboard **Route** page, or `ocx integration client enable --client `. | | Any other tool | Set a custom OpenAI-compatible base URL of `http://localhost:10100/v1`, or an Anthropic base URL of `http://localhost:10100`. | diff --git a/docs-site/src/content/docs/es/reference/client-support.md b/docs-site/src/content/docs/es/reference/client-support.md index d35541a45e4..3edf3f3a270 100644 --- a/docs-site/src/content/docs/es/reference/client-support.md +++ b/docs-site/src/content/docs/es/reference/client-support.md @@ -6,11 +6,11 @@ description: "Qué herramientas de programación conecta opencodex, cómo se con -opencodex es una única pasarela local para tus herramientas de programación con IA y tus modelos. Configura algunas herramientas de forma nativa; para las demás, exporta o administra un archivo de configuración que las dirige al proxy local. Esta página se genera a partir de los registros del código, por lo que enumera exactamente lo que ofrece la versión actual. +opencodex es una única pasarela local para tus herramientas de programación con IA y tus modelos. Puede configurar herramientas de forma nativa, exportar o administrar un archivo de configuración o usar un conector de gateway dedicado. Esta página se genera a partir de los registros del código, por lo que enumera exactamente lo que ofrece la versión actual. ## Niveles de compatibilidad -- **implemented**: el cliente figura en el registro. Para las configuraciones exportadas, el protocolo mostrado se lee de la configuración que genera opencodex, y la generación falla si cambia. Un protocolo marcado como *revisado* indica un endpoint determinado mediante una revisión, en lugar de obtenerse de la propia configuración (clientes nativos y clientes que convierten un ajuste en un endpoint concreto); el generador comprueba que el código revisado siga presente. Las filas «Compatible con OpenAI» no afirman que se use un endpoint concreto. +- **implemented**: el cliente figura en el registro. Para las configuraciones exportadas, el protocolo mostrado se lee de la configuración que genera opencodex, y la generación falla si cambia. Un protocolo marcado como *revisado* se obtiene de una revisión del código, no de una inspección automatizada de la configuración; el generador comprueba que el código revisado siga presente. Las filas «Compatible con OpenAI» no afirman que se use un endpoint concreto. - **test-covered**: cumple implemented y enlaza un caso de prueba elegido durante la revisión que ejercita este cliente. El generador solo comprueba que la prueba siga existiendo y esté habilitada; léela para saber qué verifica. - **Verificado en ejecución**: una observación histórica: una persona ejecutó el producto cliente y la versión exactos que se indican con la versión de opencodex mostrada, en el escenario y la fecha señalados, y enlazó la evidencia. No demuestra nada sobre otras versiones o productos. La evidencia se revisa al añadir el resultado; el generador no vuelve a ejecutar la prueba. Un guion significa que no hay ningún resultado registrado. @@ -47,6 +47,15 @@ opencodex es una única pasarela local para tus herramientas de programación co | Gentle Shell | — | JSON | Sí | Chat Completions | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Solo escucha local. | | T3 Code | — | JSON | Sí | Anthropic Messages | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Solo escucha local. Antes de aplicar los cambios, se ejecuta una comprobación específica del cliente que puede rechazarlos. | +## Clientes de gateway + +Abre **Enrutamiento → Antigravity** en el panel (también hay un enlace en **Enrutamiento → Clientes**) o ejecuta los comandos de abajo. Estos conectores configuran el gateway del cliente; no exportan configuraciones ni usan el flujo de integración mediante archivo administrado. Para agy, vuelve a cargar el perfil de shell indicado antes de ejecutar la CLI. + +| Cliente | Protocolo de entrada | Nivel de compatibilidad | Verificado en ejecución | Configurar en este equipo | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | Compatible con OpenAI (endpoint elegido por el cliente) (revisado) | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (revisado) | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Endpoints de entrada El proxy acepta estos protocolos. Una herramienta que no figure arriba puede conectarse si permite configurar un endpoint personalizado para alguno de ellos. @@ -54,7 +63,9 @@ El proxy acepta estos protocolos. Una herramienta que no figure arriba puede con - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Mantener esta página actualizada -Esta página se genera mediante `scripts/generate-client-support-matrix.ts` a partir de los registros de exportación, integración administrada e integración nativa. Para añadir un cliente, añade su entrada en `scripts/client-support-matrix/metadata.ts` y ejecuta `bun run docs:clients`; `bun run docs:clients:check` falla mientras la página guardada en el repositorio esté desactualizada. +Esta página se genera mediante `scripts/generate-client-support-matrix.ts` a partir de los registros de exportación, integración administrada, integración nativa y clientes de gateway. Para añadir un cliente, añade su entrada en `scripts/client-support-matrix/metadata.ts` y ejecuta `bun run docs:clients`; `bun run docs:clients:check` falla mientras la página guardada en el repositorio esté desactualizada. diff --git a/docs-site/src/content/docs/fr/reference/client-support.md b/docs-site/src/content/docs/fr/reference/client-support.md index c78d42b7da7..2fed2951cfb 100644 --- a/docs-site/src/content/docs/fr/reference/client-support.md +++ b/docs-site/src/content/docs/fr/reference/client-support.md @@ -6,11 +6,11 @@ description: "Les outils de code auxquels opencodex se connecte, la façon dont -opencodex est une passerelle locale unique pour vos outils de code IA et vos modèles. Il configure certains outils nativement ; pour les autres, il exporte ou gère un fichier de configuration qui dirige l’outil vers le proxy local. Cette page est générée à partir des registres du code et reflète donc exactement ce que fournit la version actuelle. +opencodex est une passerelle locale unique pour vos outils de code IA et vos modèles. Il peut configurer un outil nativement, exporter ou gérer un fichier de configuration, ou utiliser un connecteur de passerelle dédié. Cette page est générée à partir des registres du code et reflète donc exactement ce que fournit la version actuelle. ## Niveaux de prise en charge -- **implemented**: le client figure dans le registre. Pour les configurations exportées, le protocole indiqué est lu dans la configuration générée par opencodex, et la génération échoue s’il change. Un protocole marqué *revu* désigne un point de terminaison issu d’une revue plutôt que de la configuration elle-même (clients natifs, et clients qui déduisent un point de terminaison précis d’un réglage) ; le générateur vérifie que le code revu est toujours en place. Les lignes « Compatible OpenAI » n’affirment aucun point de terminaison. +- **implemented**: le client figure dans le registre. Pour les configurations exportées, le protocole indiqué est lu dans la configuration générée par opencodex, et la génération échoue s’il change. Un protocole marqué *revu* est établi par une revue de code, et non par une inspection automatisée de la configuration ; le générateur vérifie que le code revu est toujours en place. Les lignes « Compatible OpenAI » n’affirment aucun point de terminaison. - **test-covered**: implemented, et un cas de test choisi en revue qui exerce ce client est lié. Le générateur vérifie seulement que le test existe toujours et qu’il est actif ; lisez-le pour savoir ce qu’il vérifie. - **Vérifié à l’exécution**: une observation datée : une personne a exécuté le produit et la version du client indiqués avec la version d’opencodex indiquée, pour le scénario décrit, à cette date, et a lié la preuve. Cela ne dit rien des autres versions ou produits. La preuve est revue lors de l’ajout du résultat ; le générateur ne la rejoue pas. Un tiret signifie qu’aucun résultat n’est enregistré. @@ -47,6 +47,15 @@ opencodex est une passerelle locale unique pour vos outils de code IA et vos mod | Gentle Shell | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Écoute locale uniquement. | | T3 Code | — | JSON | Oui | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Écoute locale uniquement. L’application exécute d’abord une vérification propre au client et peut refuser. | +## Clients de passerelle + +Ouvrez **Routage → Antigravity** dans le tableau de bord (également accessible depuis **Routage → Clients**) ou exécutez les commandes ci-dessous. Ces connecteurs configurent la passerelle du client ; ils n’exportent pas de configuration et n’utilisent pas le flux d’intégration de fichiers gérés. Pour agy, rechargez le profil de shell indiqué avant de lancer la CLI. + +| Client | Protocole entrant | Niveau | Vérifié à l’exécution | Configurer sur cette machine | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | Compatible OpenAI (point de terminaison choisi par le client) (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Points de terminaison entrants Le proxy accepte ces protocoles. Un outil absent de la liste peut quand même se connecter s’il permet de définir un point de terminaison personnalisé pour l’un d’eux. @@ -54,7 +63,9 @@ Le proxy accepte ces protocoles. Un outil absent de la liste peut quand même se - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Tenir cette page à jour -Cette page est générée par `scripts/generate-client-support-matrix.ts` à partir des registres d’export, d’intégration gérée et d’intégration native. Pour ajouter un client, ajoutez son entrée dans `scripts/client-support-matrix/metadata.ts` puis lancez `bun run docs:clients` ; `bun run docs:clients:check` échoue tant que la page validée est obsolète. +Cette page est générée par `scripts/generate-client-support-matrix.ts` à partir des registres d’export, d’intégration gérée, d’intégration native et de clients de passerelle. Pour ajouter un client, ajoutez son entrée dans `scripts/client-support-matrix/metadata.ts` puis lancez `bun run docs:clients` ; `bun run docs:clients:check` échoue tant que la page validée est obsolète. diff --git a/docs-site/src/content/docs/ja/reference/client-support.md b/docs-site/src/content/docs/ja/reference/client-support.md index fc92aed9064..3dfa580c08f 100644 --- a/docs-site/src/content/docs/ja/reference/client-support.md +++ b/docs-site/src/content/docs/ja/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex が接続するコーディングツール、それぞ -opencodex は、AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイです。一部のツールはネイティブに設定し、それ以外はローカルプロキシを指す設定ファイルをエクスポートまたは管理します。このページはコードのレジストリから生成されるため、現在のリリースの内容と正確に一致します。 +opencodex は、AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイです。ツールをネイティブに設定するほか、設定ファイルをエクスポートまたは管理したり、専用のゲートウェイコネクターを使用したりできます。このページはコードのレジストリから生成されるため、現在のリリースの内容と正確に一致します。 ## サポートレベル -- **implemented**: レジストリに登録されたクライアントです。エクスポートされる設定では、表のプロトコルは opencodex が生成する設定から読み取られ、変わると生成が失敗します。*レビュー済み*は、エンドポイントが設定そのものではなくレビューに基づくことを示します(ネイティブクライアントと、設定を特定のエンドポイントに変換するクライアント)。レビューしたコードが残っているかを生成時に確認します。「OpenAI 互換」の行は特定のエンドポイントを主張しません。 +- **implemented**: レジストリに登録されたクライアントです。エクスポートされる設定では、表のプロトコルは opencodex が生成する設定から読み取られ、変わると生成が失敗します。*レビュー済み*は、設定の自動検査ではなくコードレビューで確認したプロトコルです。レビューしたコードが残っているかを生成時に確認します。「OpenAI 互換」の行は特定のエンドポイントを主張しません。 - **test-covered**: implemented であり、レビューで選んだこのクライアントのテストケースへのリンクがあります。生成時に確認するのはテストが存在し無効化されていないことだけです。何を検証しているかはテストを読んでください。 - **実行確認**: ある時点の観察記録です。表のクライアント製品・バージョンを表の opencodex バージョンで、記載のシナリオにより、その日付に人が実行し、証拠をリンクしました。ほかのバージョンや製品については何も示しません。証拠は結果の追加時にレビューされ、生成時に再実行はされません。ダッシュは記録がないことを示します。 @@ -47,6 +47,15 @@ opencodex は、AI コーディングツールとモデルをつなぐ 1 つの | Gentle Shell | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | ローカルリスナーのみ。 | | T3 Code | — | JSON | はい | Anthropic Messages | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | ローカルリスナーのみ。適用前にクライアント固有のチェックを実行し、拒否することがあります。 | +## ゲートウェイクライアント + +ダッシュボードで **ルート → Antigravity** を開くか(**ルート → クライアント** からも移動できます)、以下のコマンドを実行します。各コネクターはクライアントのゲートウェイを設定します。設定のエクスポートや管理対象ファイル連携は使用しません。agy CLI を起動する前に、案内されたシェルプロファイルを再読み込みしてください。 + +| クライアント | 受信プロトコル | サポートレベル | 実行確認 | このマシンでセットアップ | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 互換(エンドポイントはクライアントが選択) (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 受信エンドポイント プロキシは次のプロトコルを受け付けます。上の表にないツールでも、いずれかのカスタムエンドポイントを設定できれば接続できます。 @@ -54,7 +63,9 @@ opencodex は、AI コーディングツールとモデルをつなぐ 1 つの - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## このページを最新に保つ -このページは `scripts/generate-client-support-matrix.ts` がエクスポート・管理連携・ネイティブ連携のレジストリから生成します。クライアントを追加するには `scripts/client-support-matrix/metadata.ts` にエントリを追加し、`bun run docs:clients` を実行してください。コミット済みのページが古いと `bun run docs:clients:check` が失敗します。 +このページは `scripts/generate-client-support-matrix.ts` がエクスポート・管理連携・ネイティブ連携・ゲートウェイクライアントのレジストリから生成します。クライアントを追加するには `scripts/client-support-matrix/metadata.ts` にエントリを追加し、`bun run docs:clients` を実行してください。コミット済みのページが古いと `bun run docs:clients:check` が失敗します。 diff --git a/docs-site/src/content/docs/ko/reference/client-support.md b/docs-site/src/content/docs/ko/reference/client-support.md index ada4d6c65d5..113ced001c1 100644 --- a/docs-site/src/content/docs/ko/reference/client-support.md +++ b/docs-site/src/content/docs/ko/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex가 연결하는 코딩 도구, 각 도구의 연결 방 -opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이입니다. 일부 도구는 직접(네이티브로) 설정하고, 나머지는 로컬 프록시를 가리키는 설정 파일을 내보내거나 관리합니다. 이 페이지는 코드 레지스트리에서 생성되므로 현재 릴리스가 제공하는 내용과 정확히 일치합니다. +opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이입니다. 도구를 네이티브로 설정하거나, 설정 파일을 내보내거나 관리하거나, 전용 게이트웨이 커넥터로 연결합니다. 이 페이지는 코드 레지스트리에서 생성되므로 현재 릴리스가 제공하는 내용과 정확히 일치합니다. ## 지원 수준 -- **implemented**: 레지스트리에 등록된 클라이언트입니다. 내보내는 설정의 경우 표의 프로토콜은 opencodex가 생성하는 설정에서 읽으며, 바뀌면 생성이 실패합니다. *검토됨* 표시는 설정 자체가 아니라 리뷰에서 나온 특정 엔드포인트를 뜻합니다(네이티브 클라이언트, 설정값을 특정 엔드포인트로 바꾸는 클라이언트). 생성기는 리뷰한 코드가 그대로 있는지 확인합니다. 'OpenAI 호환' 행은 엔드포인트를 단정하지 않습니다. +- **implemented**: 레지스트리에 등록된 클라이언트입니다. 내보내는 설정의 경우 표의 프로토콜은 opencodex가 생성하는 설정에서 읽으며, 바뀌면 생성이 실패합니다. *검토됨* 표시는 프로토콜을 설정에서 자동으로 읽은 것이 아니라 코드 검토로 확인했다는 뜻입니다. 생성기는 리뷰한 코드가 그대로 있는지 확인합니다. 'OpenAI 호환' 행은 엔드포인트를 단정하지 않습니다. - **test-covered**: implemented이면서, 리뷰로 고른 이 클라이언트의 테스트 케이스가 링크되어 있습니다. 생성기는 테스트가 존재하고 비활성화되지 않았는지만 확인하므로, 무엇을 검증하는지는 테스트를 직접 읽어 보세요. - **실행 검증**: 특정 시점의 관찰 기록입니다. 표에 적힌 클라이언트 제품·버전을 표에 적힌 opencodex 버전과 함께, 명시한 시나리오로, 그 날짜에 사람이 실행하고 증거를 링크했습니다. 다른 버전이나 제품에 대해서는 아무것도 보장하지 않습니다. 증거는 결과를 추가할 때 리뷰하며, 생성기가 다시 실행하지 않습니다. 대시(—)는 기록된 결과가 없다는 뜻입니다. @@ -47,6 +47,15 @@ opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨 | Gentle Shell | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | 로컬 리스너 전용. | | T3 Code | — | JSON | 예 | Anthropic Messages | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | 로컬 리스너 전용. 적용 전에 클라이언트별 검사를 실행하며 거부할 수 있습니다. | +## 게이트웨이 클라이언트 + +대시보드에서 **라우트 → Antigravity**를 열거나(**라우트 → 클라이언트**에서도 이동할 수 있음) 아래 명령을 실행하세요. 이 커넥터는 클라이언트의 게이트웨이를 설정하며 설정을 내보내거나 관리형 파일 통합 절차를 사용하지 않아요. agy CLI를 실행하기 전에 안내된 셸 프로필을 다시 불러오세요. + +| 클라이언트 | 수신 프로토콜 | 지원 수준 | 실행 검증 | 이 컴퓨터에서 설정 | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 호환(엔드포인트는 클라이언트가 선택) (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 수신 엔드포인트 프록시는 아래 프로토콜을 받습니다. 위 목록에 없는 도구도 이 중 하나로 사용자 지정 엔드포인트를 설정할 수 있으면 연결할 수 있습니다. @@ -54,7 +63,9 @@ opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨 - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## 이 페이지 최신 상태 유지 -이 페이지는 `scripts/generate-client-support-matrix.ts`가 내보내기·관리형 연동·네이티브 연동 레지스트리로부터 생성합니다. 클라이언트를 추가하려면 `scripts/client-support-matrix/metadata.ts`에 항목을 넣고 `bun run docs:clients`를 실행하세요. 커밋된 페이지가 오래되면 `bun run docs:clients:check`가 실패합니다. +이 페이지는 `scripts/generate-client-support-matrix.ts`가 내보내기·관리형 연동·네이티브 연동·게이트웨이 클라이언트 레지스트리로부터 생성합니다. 클라이언트를 추가하려면 `scripts/client-support-matrix/metadata.ts`에 항목을 넣고 `bun run docs:clients`를 실행하세요. 커밋된 페이지가 오래되면 `bun run docs:clients:check`가 실패합니다. diff --git a/docs-site/src/content/docs/reference/client-support.md b/docs-site/src/content/docs/reference/client-support.md index 80aa83eea3b..3c9a6e243c7 100644 --- a/docs-site/src/content/docs/reference/client-support.md +++ b/docs-site/src/content/docs/reference/client-support.md @@ -6,11 +6,11 @@ description: "Which coding tools opencodex connects to, how each one is wired, a -opencodex is one local gateway for your AI coding tools and models. Some tools it configures natively; for the others it exports or manages a config file that points the tool at the local proxy. This page is generated from the code registries, so it lists exactly what the current release ships. +opencodex is one local gateway for your AI coding tools and models. It can configure tools natively, export or manage a config file, or use a dedicated gateway connector. This page is generated from the code registries, so it lists exactly what the current release ships. ## Support levels -- **implemented**: the client is in the registry. For exported configs, the protocol shown is read from the config opencodex generates, and generation fails if it changes. A protocol marked *curated* names an endpoint that comes from a review instead of the config itself (native clients, and clients that turn a setting into a specific endpoint); the generator checks that the reviewed code is still in place. "OpenAI-compatible" rows make no endpoint claim. +- **implemented**: the client is in the registry. For exported configs, the protocol shown is read from the config opencodex generates, and generation fails if it changes. A protocol marked *curated* comes from a code review rather than automated config inspection; the generator checks that the reviewed code is still in place. "OpenAI-compatible" rows make no endpoint claim. - **test-covered**: implemented, and a test case chosen in review that exercises this client is linked. The generator checks only that the test still exists and is enabled; read it to see what it asserts. - **Runtime verified**: a historical observation: a person ran the exact client product and version shown against the opencodex version shown, for the stated scenario, on that date, and linked the evidence. It says nothing about other versions or products. The evidence is reviewed when a result is added; the generator does not re-run it. A dash means no result is recorded. @@ -47,6 +47,15 @@ opencodex is one local gateway for your AI coding tools and models. Some tools i | Gentle Shell | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Local listener only. | | T3 Code | — | JSON | Yes | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Local listener only. Apply runs a client-specific check first and can refuse. | +## Gateway clients + +Use **Route → Antigravity** on the dashboard (also linked from **Route → Clients**) or run the commands below. These connectors set up the gateway for their respective client; they do not export a config or use the managed file integration workflow. For agy, reload the indicated shell profile before running the CLI. + +| Client | Inbound protocol | Support level | Runtime verified | Set up on this machine | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI-compatible (endpoint chosen by the client) (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Inbound endpoints The proxy accepts these protocols. A tool that is not listed above can still connect if it lets you set a custom endpoint for one of them. @@ -54,7 +63,9 @@ The proxy accepts these protocols. A tool that is not listed above can still con - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Keeping this page current -This page is generated by `scripts/generate-client-support-matrix.ts` from the export, managed-integration and native-integration registries. To add a client, add its entry in `scripts/client-support-matrix/metadata.ts` and run `bun run docs:clients`; `bun run docs:clients:check` fails while the committed page is stale. +This page is generated by `scripts/generate-client-support-matrix.ts` from the export, managed-integration, native-integration and gateway-client registries. To add a client, add its entry in `scripts/client-support-matrix/metadata.ts` and run `bun run docs:clients`; `bun run docs:clients:check` fails while the committed page is stale. diff --git a/docs-site/src/content/docs/ru/reference/client-support.md b/docs-site/src/content/docs/ru/reference/client-support.md index 2784e8508f9..3ba61efd2d7 100644 --- a/docs-site/src/content/docs/ru/reference/client-support.md +++ b/docs-site/src/content/docs/ru/reference/client-support.md @@ -6,11 +6,11 @@ description: "К каким инструментам для кода подкл -opencodex — единый локальный шлюз для ваших ИИ-инструментов для кода и моделей. Часть инструментов он настраивает нативно; для остальных он экспортирует или ведёт файл конфигурации, который направляет инструмент на локальный прокси. Страница сгенерирована из реестров в коде и поэтому в точности соответствует текущему релизу. +opencodex — единый локальный шлюз для ваших ИИ-инструментов для кода и моделей. Он может настраивать инструменты нативно, экспортировать или вести файл конфигурации либо использовать отдельный коннектор шлюза. Страница сгенерирована из реестров в коде и поэтому в точности соответствует текущему релизу. ## Уровни поддержки -- **implemented**: клиент есть в реестре. Для экспортируемых конфигураций протокол берётся из конфигурации, которую генерирует opencodex, и генерация падает, если он меняется. Пометка *проверено* означает, что эндпоинт взят из ревью, а не из самой конфигурации (нативные клиенты и клиенты, которые превращают настройку в конкретный эндпоинт); генератор проверяет, что проверенный код на месте. Строки «Совместим с OpenAI» не утверждают конкретный эндпоинт. +- **implemented**: клиент есть в реестре. Для экспортируемых конфигураций протокол берётся из конфигурации, которую генерирует opencodex, и генерация падает, если он меняется. Пометка *проверено* означает, что протокол определён при ревью кода, а не при автоматической проверке конфигурации; генератор проверяет, что проверенный код на месте. Строки «Совместим с OpenAI» не утверждают конкретный эндпоинт. - **test-covered**: implemented, и есть ссылка на выбранный при ревью тест, который задействует этого клиента. Генератор проверяет только, что тест существует и не отключён; что именно он проверяет, смотрите в самом тесте. - **Проверено в работе**: историческое наблюдение: человек запустил указанные продукт и версию клиента с указанной версией opencodex по описанному сценарию в эту дату и приложил ссылку на подтверждение. Это ничего не говорит о других версиях или продуктах. Подтверждение проверяется при добавлении результата; генератор его не перезапускает. Прочерк означает, что результатов нет. @@ -47,6 +47,15 @@ opencodex — единый локальный шлюз для ваших ИИ-и | Gentle Shell | — | JSON | Да | Chat Completions | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Только локальный слушатель. | | T3 Code | — | JSON | Да | Anthropic Messages | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Только локальный слушатель. Перед применением выполняется проверка, специфичная для клиента, и возможен отказ. | +## Клиенты шлюза + +Откройте **Маршрут → Antigravity** на панели управления (ссылка также есть в разделе **Маршрут → Клиенты**) или выполните команды ниже. Эти коннекторы настраивают шлюз для клиента без экспорта конфигурации или управляемой файловой интеграции. Перед запуском agy перечитайте указанный профиль оболочки. + +| Клиент | Входящий протокол | Уровень | Проверено в работе | Настроить на этом компьютере | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | Совместим с OpenAI (эндпоинт выбирает клиент) (проверено) | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (проверено) | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Входящие эндпоинты Прокси принимает эти протоколы. Инструмент, которого нет в таблице, всё равно может подключиться, если позволяет задать собственный эндпоинт для одного из них. @@ -54,7 +63,9 @@ opencodex — единый локальный шлюз для ваших ИИ-и - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Актуальность страницы -Страница генерируется скриптом `scripts/generate-client-support-matrix.ts` из реестров экспорта, управляемых и нативных интеграций. Чтобы добавить клиента, добавьте запись в `scripts/client-support-matrix/metadata.ts` и выполните `bun run docs:clients`; `bun run docs:clients:check` падает, пока закоммиченная страница устарела. +Страница генерируется скриптом `scripts/generate-client-support-matrix.ts` из реестров экспорта, управляемых интеграций, нативных интеграций и клиентов шлюза. Чтобы добавить клиента, добавьте запись в `scripts/client-support-matrix/metadata.ts` и выполните `bun run docs:clients`; `bun run docs:clients:check` падает, пока закоммиченная страница устарела. diff --git a/docs-site/src/content/docs/tr/reference/client-support.md b/docs-site/src/content/docs/tr/reference/client-support.md index e0d62b2d51a..a305b1cc75f 100644 --- a/docs-site/src/content/docs/tr/reference/client-support.md +++ b/docs-site/src/content/docs/tr/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex'in bağlandığı kodlama araçları, her birinin nasıl -opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yerel ağ geçididir. Bazı araçları yerel olarak yapılandırır; diğerleri için aracı yerel proxy'ye yönlendiren bir yapılandırma dosyasını dışa aktarır veya yönetir. Bu sayfa koddaki kayıtlardan üretilir; bu yüzden mevcut sürümün sunduğu şeyle birebir aynıdır. +opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yerel ağ geçididir. Araçları yerel olarak yapılandırabilir, yapılandırma dosyası dışa aktarabilir veya yönetebilir, ya da özel bir ağ geçidi bağlayıcısı kullanabilir. Bu sayfa koddaki kayıtlardan üretilir; bu yüzden mevcut sürümün sunduğu şeyle birebir aynıdır. ## Destek düzeyleri -- **implemented**: istemci kayıtta yer alır. Dışa aktarılan yapılandırmalarda gösterilen protokol, opencodex'in ürettiği yapılandırmadan okunur ve değişirse üretim başarısız olur. *İncelendi* işareti, uç noktanın yapılandırmanın kendisinden değil bir incelemeden geldiğini belirtir (yerel istemciler ve bir ayarı belirli bir uç noktaya çeviren istemciler); üretici, incelenen kodun hâlâ yerinde olduğunu denetler. "OpenAI uyumlu" satırlar belirli bir uç nokta iddia etmez. +- **implemented**: istemci kayıtta yer alır. Dışa aktarılan yapılandırmalarda gösterilen protokol, opencodex'in ürettiği yapılandırmadan okunur ve değişirse üretim başarısız olur. *İncelendi* işareti, protokolün otomatik yapılandırma denetiminden değil, kod incelemesinden geldiğini belirtir; üretici, incelenen kodun hâlâ yerinde olduğunu denetler. "OpenAI uyumlu" satırlar belirli bir uç nokta iddia etmez. - **test-covered**: implemented olmanın yanında, incelemede seçilmiş ve bu istemciyi çalıştıran bir test durumuna bağlantı verilir. Üretici yalnızca testin hâlâ var ve etkin olduğunu denetler; neyi doğruladığını görmek için testi okuyun. - **Çalışırken doğrulandı**: tarihli bir gözlem: bir kişi gösterilen istemci ürününü ve sürümünü gösterilen opencodex sürümüyle, belirtilen senaryo için o tarihte çalıştırdı ve kanıtı bağladı. Diğer sürümler veya ürünler hakkında bir şey söylemez. Kanıt sonuç eklenirken incelenir; üretici yeniden çalıştırmaz. Tire, kayıtlı sonuç olmadığı anlamına gelir. @@ -47,6 +47,15 @@ opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yere | Gentle Shell | — | JSON | Evet | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Yalnızca yerel dinleyici. | | T3 Code | — | JSON | Evet | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Yalnızca yerel dinleyici. Uygulamadan önce istemciye özgü bir denetim çalışır ve reddedebilir. | +## Ağ geçidi istemcileri + +Panoda **Rota → Antigravity** bölümünü açın (**Rota → İstemciler** bölümünde de bağlantısı var) veya aşağıdaki komutları çalıştırın. Bu bağlayıcılar istemcinin ağ geçidini kurar; yapılandırma dışa aktarmaz veya yönetilen dosya entegrasyonu akışını kullanmaz. agy CLI’ını çalıştırmadan önce belirtilen kabuk profilini yeniden yükleyin. + +| İstemci | Gelen protokol | Destek düzeyi | Çalışırken doğrulandı | Bu makinede kur | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI uyumlu (uç noktayı istemci seçer) (incelendi) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (incelendi) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Gelen uç noktalar Proxy bu protokolleri kabul eder. Yukarıda listelenmeyen bir araç, bunlardan biri için özel uç nokta ayarlamaya izin veriyorsa yine de bağlanabilir. @@ -54,7 +63,9 @@ Proxy bu protokolleri kabul eder. Yukarıda listelenmeyen bir araç, bunlardan b - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Bu sayfayı güncel tutmak -Bu sayfa `scripts/generate-client-support-matrix.ts` tarafından dışa aktarma, yönetilen entegrasyon ve yerel entegrasyon kayıtlarından üretilir. İstemci eklemek için `scripts/client-support-matrix/metadata.ts` dosyasına kaydını ekleyip `bun run docs:clients` çalıştırın; işlenmiş sayfa eskidiğinde `bun run docs:clients:check` başarısız olur. +Bu sayfa `scripts/generate-client-support-matrix.ts` tarafından dışa aktarma, yönetilen entegrasyon, yerel entegrasyon ve ağ geçidi istemcisi kayıtlarından üretilir. İstemci eklemek için `scripts/client-support-matrix/metadata.ts` dosyasına kaydını ekleyip `bun run docs:clients` çalıştırın; işlenmiş sayfa eskidiğinde `bun run docs:clients:check` başarısız olur. diff --git a/docs-site/src/content/docs/zh-cn/reference/client-support.md b/docs-site/src/content/docs/zh-cn/reference/client-support.md index 100e1a9ff75..80f814b78bd 100644 --- a/docs-site/src/content/docs/zh-cn/reference/client-support.md +++ b/docs-site/src/content/docs/zh-cn/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex 能连接哪些编程工具、每个工具如何接入 -opencodex 是一个本地网关,连接你的 AI 编程工具与模型。部分工具由它原生配置;其余工具则通过导出或托管一个指向本地代理的配置文件来接入。本页由代码中的注册表生成,因此与当前版本实际提供的内容完全一致。 +opencodex 是一个本地网关,连接你的 AI 编程工具与模型。它可以原生配置工具,也可以导出或托管配置文件,或使用专用网关连接器。本页由代码中的注册表生成,因此与当前版本实际提供的内容完全一致。 ## 支持级别 -- **implemented**: 客户端已在注册表中。对于导出的配置,表中协议读取自 opencodex 生成的配置,一旦变化生成就会失败。标有*已审阅*的协议表示其端点来自审阅而非配置本身(原生客户端,以及会把某个设置转换为特定端点的客户端);生成器会检查被审阅的代码是否仍然存在。“OpenAI 兼容”的行不声明具体端点。 +- **implemented**: 客户端已在注册表中。对于导出的配置,表中协议读取自 opencodex 生成的配置,一旦变化生成就会失败。标有*已审阅*的协议来自代码审阅,而非自动读取配置;生成器会检查被审阅的代码是否仍然存在。“OpenAI 兼容”的行不声明具体端点。 - **test-covered**: 满足 implemented,并链接了一个经评审选定、覆盖该客户端的测试用例。生成器只检查该测试仍然存在且未被禁用;它具体断言了什么,请阅读测试本身。 - **运行验证**: 一次历史观察:有人在该日期,用表中所列的 opencodex 版本运行了表中所列的客户端产品与版本,执行了所述场景,并附上证据链接。它不代表其他版本或产品。证据在添加结果时经过评审,生成器不会重新运行。短横线表示尚无记录。 @@ -47,6 +47,15 @@ opencodex 是一个本地网关,连接你的 AI 编程工具与模型。部分 | Gentle Shell | — | JSON | 是 | Chat Completions | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | 仅限本地监听。 | | T3 Code | — | JSON | 是 | Anthropic Messages | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | 仅限本地监听。应用前先运行针对该客户端的检查,可能拒绝。 | +## 网关客户端 + +在控制台打开 **路由 → Antigravity**(也可从 **路由 → 客户端** 进入),或运行下列命令。这些连接器为各自客户端设置网关,不导出配置,也不走托管文件集成流程。使用 agy 前,请重新加载提示的 shell 配置文件。 + +| 客户端 | 入站协议 | 支持级别 | 运行验证 | 在本机设置 | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 兼容(端点由客户端选择) (已审阅) | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (已审阅) | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 入站端点 代理接受以下协议。未列在上表中的工具,只要能为其中之一设置自定义端点,也可以接入。 @@ -54,7 +63,9 @@ opencodex 是一个本地网关,连接你的 AI 编程工具与模型。部分 - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## 保持本页最新 -本页由 `scripts/generate-client-support-matrix.ts` 根据导出、托管集成和原生集成注册表生成。要添加客户端,请在 `scripts/client-support-matrix/metadata.ts` 中添加条目并运行 `bun run docs:clients`;已提交的页面过期时,`bun run docs:clients:check` 会失败。 +本页由 `scripts/generate-client-support-matrix.ts` 根据导出、托管集成、原生集成和网关客户端注册表生成。要添加客户端,请在 `scripts/client-support-matrix/metadata.ts` 中添加条目并运行 `bun run docs:clients`;已提交的页面过期时,`bun run docs:clients:check` 会失败。 diff --git a/docs-site/src/content/docs/zh-tw/reference/client-support.md b/docs-site/src/content/docs/zh-tw/reference/client-support.md index bb8c14dbddb..9a7ee10dccc 100644 --- a/docs-site/src/content/docs/zh-tw/reference/client-support.md +++ b/docs-site/src/content/docs/zh-tw/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex 能連接哪些程式開發工具、每個工具如何 -opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。部分工具由它原生設定;其餘工具則透過匯出或代管一個指向本機代理的設定檔來接入。本頁由程式碼中的登錄表產生,因此與目前版本實際提供的內容完全一致。 +opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。它可以原生設定工具,也可以匯出或代管設定檔,或使用專用閘道連接器。本頁由程式碼中的登錄表產生,因此與目前版本實際提供的內容完全一致。 ## 支援等級 -- **implemented**: 用戶端已在登錄表中。對於匯出的設定,表中協定讀取自 opencodex 產生的設定,一旦變更產生就會失敗。標示*已審查*的協定表示其端點來自審查而非設定本身(原生用戶端,以及會把某個設定轉換為特定端點的用戶端);產生器會檢查被審查的程式碼是否仍然存在。「OpenAI 相容」的列不聲明具體端點。 +- **implemented**: 用戶端已在登錄表中。對於匯出的設定,表中協定讀取自 opencodex 產生的設定,一旦變更產生就會失敗。標示*已審查*的協定來自程式碼審查,而非自動讀取設定;產生器會檢查被審查的程式碼是否仍然存在。「OpenAI 相容」的列不聲明具體端點。 - **test-covered**: 符合 implemented,並連結了一個經審查選定、涵蓋該用戶端的測試案例。產生器只檢查該測試仍然存在且未被停用;它實際驗證什麼,請閱讀測試本身。 - **執行驗證**: 一次歷史觀察:有人在該日期,以表中所列的 opencodex 版本執行了表中所列的用戶端產品與版本,執行了所述情境,並附上證據連結。它不代表其他版本或產品。證據在新增結果時經過審查,產生器不會重新執行。短橫線表示尚無紀錄。 @@ -47,6 +47,15 @@ opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。 | Gentle Shell | — | JSON | 是 | Chat Completions | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | 僅限本機監聽。 | | T3 Code | — | JSON | 是 | Anthropic Messages | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | 僅限本機監聽。套用前先執行該用戶端專屬的檢查,可能拒絕。 | +## 閘道用戶端 + +在控制台開啟 **路由 → Antigravity**(也可從 **路由 → 用戶端** 前往),或執行下列指令。這些連接器為各自的用戶端設定閘道,不匯出設定,也不使用受管理檔案整合流程。執行 agy 前,請重新載入提示的 shell 設定檔。 + +| 用戶端 | 入站協定 | 支援等級 | 執行驗證 | 在本機設定 | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 相容(端點由用戶端選擇) (已審查) | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (已審查) | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 入站端點 代理接受以下協定。未列在上表中的工具,只要能為其中之一設定自訂端點,也可以接入。 @@ -54,7 +63,9 @@ opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。 - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## 保持本頁最新 -本頁由 `scripts/generate-client-support-matrix.ts` 根據匯出、代管整合與原生整合登錄表產生。要新增用戶端,請在 `scripts/client-support-matrix/metadata.ts` 中加入項目並執行 `bun run docs:clients`;已提交的頁面過期時,`bun run docs:clients:check` 會失敗。 +本頁由 `scripts/generate-client-support-matrix.ts` 根據匯出、代管整合、原生整合與閘道用戶端登錄表產生。要新增用戶端,請在 `scripts/client-support-matrix/metadata.ts` 中加入項目並執行 `bun run docs:clients`;已提交的頁面過期時,`bun run docs:clients:check` 會失敗。 diff --git a/gui/src/design/pages/connect.css b/gui/src/design/pages/connect.css index ef122b6e333..5e324d77301 100644 --- a/gui/src/design/pages/connect.css +++ b/gui/src/design/pages/connect.css @@ -98,6 +98,7 @@ .connect-catalog-head > .connect-disable-all:hover:not(:disabled) { color: var(--ocx-danger); background: var(--ocx-danger-soft); } .connect-help-panel { margin: 0 0 12px; max-width: 72ch; } .integrations-overview > h3 { margin: 40px 0 12px; } +.integrations-overview > .gateway-clients-overview { margin-top: 40px; } /* ---- overview: the API keys row, one quiet line -------------------------------- */ .integrations-overview .integration-api-keys-row { diff --git a/gui/src/i18n/gateway-clients-copy.ts b/gui/src/i18n/gateway-clients-copy.ts index e8a95aee055..8ba51d87c82 100644 --- a/gui/src/i18n/gateway-clients-copy.ts +++ b/gui/src/i18n/gateway-clients-copy.ts @@ -9,6 +9,12 @@ const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { + overviewTitle: ["Gateway clients", "게이트웨이 클라이언트", "Gateway-Clients", "Clients de passerelle", "网关客户端", "閘道用戶端", "Клиенты шлюза", "ゲートウェイクライアント", "Ağ geçidi istemcileri", "Máy khách cổng kết nối", "Clientes de gateway", "Clientes de gateway"], + overviewDesktop: ["Antigravity (desktop)", "Antigravity (데스크톱)", "Antigravity (Desktop)", "Antigravity (bureau)", "Antigravity(桌面版)", "Antigravity(桌面版)", "Antigravity (настольное приложение)", "Antigravity(デスクトップ)", "Antigravity (masaüstü)", "Antigravity (máy tính)", "Antigravity (desktop)", "Antigravity (escritorio)"], + overviewCli: ["agy (CLI)", "agy (명령줄)", "agy (Befehlszeile)", "agy (ligne de commande)", "agy(命令行)", "agy(命令列)", "agy (командная строка)", "agy(コマンドライン)", "agy (komut satırı)", "agy (dòng lệnh)", "agy (linha de comando)", "agy (línea de comandos)"], + overviewHint: ["These statuses reflect gateway settings, not whether the apps are installed or running.", "이 상태는 게이트웨이 설정을 나타내며, 앱의 설치나 실행 여부는 확인하지 않아요.", "Der Status zeigt die Gateway-Einstellungen, nicht ob die Apps installiert sind oder laufen.", "Ces états reflètent les réglages de la passerelle, pas l’installation ni l’exécution des applications.", "状态仅反映网关配置,不代表客户端已安装或正在运行。", "狀態僅反映閘道設定,不代表用戶端已安裝或正在執行。", "Статусы показывают настройки шлюза, а не наличие или запуск приложений.", "状態はゲートウェイ設定を示すもので、アプリのインストールや実行の有無は示しません。", "Bu durumlar ağ geçidi ayarlarını gösterir; uygulamaların kurulu veya çalışır durumda olduğunu göstermez.", "Các trạng thái này phản ánh cài đặt cổng, không cho biết ứng dụng đã cài đặt hay đang chạy.", "Os estados refletem a configuração do gateway, não se os apps estão instalados ou em execução.", "Estos estados reflejan la configuración del gateway, no si las aplicaciones están instaladas o en ejecución."], + overviewOverride: ["Override detected", "설정 재정의 감지", "Überschreibung erkannt", "Réglage prioritaire détecté", "检测到配置覆盖", "偵測到設定覆寫", "Обнаружено переопределение", "上書き設定あり", "Geçersiz kılan ayar algılandı", "Phát hiện cài đặt ghi đè", "Configuração sobreposta detectada", "Ajuste de mayor prioridad detectado"], + overviewUnknown: ["Status unknown", "상태를 알 수 없음", "Status unbekannt", "État inconnu", "状态未知", "狀態未知", "Состояние неизвестно", "状態不明", "Durum bilinmiyor", "Không rõ trạng thái", "Estado desconhecido", "Estado desconocido"], tab: ["Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity", "Antigravity"], title: ["Antigravity and agy","Antigravity 및 agy","Antigravity und agy","Antigravity et agy","Antigravity 和 agy","Antigravity 與 agy","Antigravity и agy","Antigravity と agy","Antigravity ve agy","Antigravity và agy","Antigravity e agy", "Antigravity y agy"], intro: ["Send Google's Antigravity desktop app and the agy CLI through this proxy. Connect writes their gateway settings and keeps a copy of what was there; Disconnect puts it back.","Google의 Antigravity 데스크톱 앱과 agy CLI가 이 프록시를 거치게 해요. 연결하면 게이트웨이 설정을 쓰고 기존 내용을 보관하며, 연결 해제하면 되돌려요.","Leitet Googles Antigravity-Desktop-App und die agy-CLI über diesen Proxy. Verbinden schreibt ihre Gateway-Einstellungen und sichert den vorherigen Stand; Trennen stellt ihn wieder her.","Fait passer l’application de bureau Antigravity de Google et la CLI agy par ce proxy. Connecter écrit leurs réglages de passerelle et conserve l’état précédent ; Déconnecter le rétablit.","让 Google 的 Antigravity 桌面应用和 agy 命令行经由此代理。连接会写入它们的网关设置并保留原有内容;断开会恢复原样。","讓 Google 的 Antigravity 桌面應用程式和 agy 命令列經由此代理。連線會寫入它們的閘道設定並保留原有內容;中斷連線會還原。","Направляет настольное приложение Google Antigravity и CLI agy через этот прокси. Подключение записывает настройки шлюза и сохраняет прежнее содержимое; отключение возвращает его.","Google の Antigravity デスクトップアプリと agy CLI をこのプロキシ経由にします。接続するとゲートウェイ設定を書き込み、元の内容を保管します。切断すると元に戻します。","Google'ın Antigravity masaüstü uygulamasını ve agy CLI'ını bu proxy üzerinden geçirir. Bağlan, ağ geçidi ayarlarını yazar ve önceki hâlini saklar; Bağlantıyı kes onu geri yükler.","Cho ứng dụng Antigravity trên máy tính của Google và CLI agy đi qua proxy này. Kết nối sẽ ghi cài đặt cổng và giữ bản cũ; Ngắt kết nối sẽ khôi phục lại.","Faz o app de desktop Antigravity do Google e a CLI agy passarem por este proxy. Conectar grava as configurações de gateway e guarda o estado anterior; Desconectar o restaura.", "Haz que la aplicación de escritorio Antigravity de Google y la CLI agy pasen por este proxy. Conectar escribe su configuración de gateway y guarda una copia de lo que había; Desconectar la restaura."], diff --git a/gui/src/pages/integrations/GatewayClientsOverview.tsx b/gui/src/pages/integrations/GatewayClientsOverview.tsx new file mode 100644 index 00000000000..3d5cc86d275 --- /dev/null +++ b/gui/src/pages/integrations/GatewayClientsOverview.tsx @@ -0,0 +1,70 @@ +import { useCallback } from "react"; +import ClientMark from "../../components/ClientMark"; +import { INTEGRATION_MARKS } from "../../components/integration-marks"; +import { useDataSurface } from "../../data-surface"; +import { navigateHash } from "../../hash-routing"; +import { useT, type TKey } from "../../i18n/shared"; +import { loadGatewayClientOverview, type GatewayClientId, type GatewayClientState } from "./gateway-clients-api"; + +const clients: readonly { id: GatewayClientId; label: TKey }[] = [ + { id: "antigravity", label: "gatewayClients.overviewDesktop" }, + { id: "agy", label: "gatewayClients.overviewCli" }, +]; +const badges: Record = { + connected: { key: "gatewayClients.connected", visual: "current", className: "badge badge-green" }, + disconnected: { key: "gatewayClients.notConnected", visual: "absent", className: "badge badge-muted" }, + drifted: { key: "integrations.state.stale", visual: "stale", className: "badge badge-amber" }, +}; +const openAntigravitySetup = () => { navigateHash("integrations/antigravity"); }; + +/** A read-only catalog. Gateway states are not installation counts or bulk file operations. */ +export default function GatewayClientsOverview({ apiBase, active }: { apiBase: string; active: boolean }) { + const t = useT(); + const fetchStatuses = useCallback((signal: AbortSignal) => loadGatewayClientOverview(apiBase, signal), [apiBase]); + const resource = useDataSurface( + `integration-gateway-overview:${apiBase}`, [apiBase], fetchStatuses, { enabled: active, isEmpty: () => false }, + ); + const view = resource.state; + return ( +
+
+

{t("gatewayClients.overviewTitle")}

+
+

{t("gatewayClients.overviewHint")}

+
    + {clients.map(({ id, label }) => { + // On error, keep the navigation available but do not assert a stale connection state. + const status = !view.showError ? view.data?.[id] : undefined; + const badge = status + ? status.overridden + ? { key: "gatewayClients.overviewOverride" as const, visual: "stale", className: "badge badge-amber" } + : badges[status.state] + : { + key: view.showSkeleton ? "common.loading" as const : "gatewayClients.overviewUnknown" as const, + visual: "unknown", + className: "badge badge-muted", + }; + return ( +
  • +
    + +

    + +

    + {t(badge.key)} +
    + {id === "antigravity" &&

    {t("gatewayClients.noteAgyFollowsApp")}

    } +
    + +
    +
  • + ); + })} +
+
+ ); +} diff --git a/gui/src/pages/integrations/GatewayClientsPage.tsx b/gui/src/pages/integrations/GatewayClientsPage.tsx index 440e509c5f0..626205ef192 100644 --- a/gui/src/pages/integrations/GatewayClientsPage.tsx +++ b/gui/src/pages/integrations/GatewayClientsPage.tsx @@ -91,11 +91,9 @@ function describeOutcome(id: GatewayClientId, action: GatewayClientAction, outco function GatewayClientCard({ apiBase, client, - onSettled, }: { apiBase: string; client: GatewayClientStatus; - onSettled: () => void; }) { const t = useT(); // `null` until the user types: the field then shows what settings.json holds right now. @@ -118,7 +116,6 @@ function GatewayClientCard({ setResult(describeOutcome(client.id, action, outcome)); if (outcome.ok) setModelDraft(null); setPending(null); - onSettled(); }; return ( @@ -210,7 +207,7 @@ export default function GatewayClientsPage({ apiBase, active }: { apiBase: strin {resource.state.showError && {t("gatewayClients.unavailable")}} {!clients && !resource.state.showError && } {clients?.map(client => ( - resource.refresh()} /> + ))} ); diff --git a/gui/src/pages/integrations/IntegrationsOverview.tsx b/gui/src/pages/integrations/IntegrationsOverview.tsx index 0b2ec495b1d..a137f5eca01 100644 --- a/gui/src/pages/integrations/IntegrationsOverview.tsx +++ b/gui/src/pages/integrations/IntegrationsOverview.tsx @@ -12,6 +12,7 @@ import ConsequenceDialog, { type ConsequenceCopy } from "./ConsequenceDialog"; import RestoreDialog from "./RestoreDialog"; import { RollbackHistory } from "./RollbackHistory"; import ConnectionsPanel from "./ConnectionsPanel"; +import GatewayClientsOverview from "./GatewayClientsOverview"; import { describeRefusal } from "./refusal-copy"; import { previewRecoveryFor, type PreviewRecovery } from "./preview-recovery"; import { loadCursorIntegrationStatus } from "./cursor-api"; @@ -899,6 +900,8 @@ export default function IntegrationsOverview({ )} + + {/* Read-only: where Codex and Claude go now, who owns their files, what switching back changes. */} diff --git a/gui/src/pages/integrations/gateway-clients-api.ts b/gui/src/pages/integrations/gateway-clients-api.ts index 16a38f3769c..b8dca672c33 100644 --- a/gui/src/pages/integrations/gateway-clients-api.ts +++ b/gui/src/pages/integrations/gateway-clients-api.ts @@ -3,6 +3,7 @@ * (src/server/management/gateway-client-routes.ts). Every note, override and refusal carries a * code; the page translates the code and never shows the server's English sentence. */ +import { invalidateClientResource } from "../../client-resource"; import { readJsonIfOk } from "../../fetch-json"; export type GatewayClientId = "antigravity" | "agy"; @@ -13,6 +14,8 @@ export type GatewayNoteCode = | "no-restore-record" | "new-terminal" | "agy-version" | "windows-unverified" | "agy-env-exported"; export type GatewayOverrideCode = "admin-gateway" | "admin-unreadable" | "env-gateway"; +const OVERRIDE_CODES = new Set(["admin-gateway", "admin-unreadable", "env-gateway"]); + export interface GatewayClientStatus { id: GatewayClientId; label: string; @@ -39,15 +42,62 @@ export interface GatewayClientActionOutcome { } export async function loadGatewayClients(apiBase: string, signal?: AbortSignal): Promise { + if (signal?.aborted) throw signal.reason ?? new DOMException("Aborted", "AbortError"); try { const response = await fetch(`${apiBase}/api/gateway-clients`, { signal }); const body = await readJsonIfOk<{ clients?: unknown }>(response); + if (signal?.aborted) throw signal.reason ?? new DOMException("Aborted", "AbortError"); return Array.isArray(body?.clients) ? body.clients as GatewayClientStatus[] : null; - } catch { + } catch (error) { + if (signal?.aborted) throw signal.reason ?? error; return null; } } +type GatewayClientOverview = Partial>; + +function hasValidOverrides(value: unknown): value is { code: GatewayOverrideCode }[] { + return Array.isArray(value) + && value.every(entry => Boolean(entry) && typeof entry === "object" && typeof (entry as { code?: unknown }).code === "string" && OVERRIDE_CODES.has((entry as { code: string }).code)); +} + +function hasValidNotes(value: unknown): value is { code: string }[] { + return Array.isArray(value) + && value.every(entry => Boolean(entry) && typeof entry === "object" && typeof (entry as { code?: unknown }).code === "string"); +} + +/** The overview only consumes known IDs and state. It neither stores nor displays paths and details. */ +export async function loadGatewayClientOverview(apiBase: string, signal?: AbortSignal): Promise { + const clients = await loadGatewayClients(apiBase, signal); + if (!clients) throw new Error("gateway client status unavailable"); + const result: GatewayClientOverview = {}; + const seen = new Set(); + for (const client of clients) { + if (!client || (client.id !== "antigravity" && client.id !== "agy")) continue; + if (seen.has(client.id)) { + delete result[client.id]; + continue; + } + seen.add(client.id); + if ( + (client.state === "connected" || client.state === "disconnected" || client.state === "drifted") + && hasValidOverrides(client.overrides) + && hasValidNotes(client.notes) + ) { + // The connected agy function sets these variables itself, so an exported URL does not win. + const wrapped = client.id === "agy" && client.state === "connected"; + const overridden = client.overrides.some(override => + override.code === "admin-gateway" || (override.code === "env-gateway" && !wrapped)); + const adminUnreadable = client.overrides.some(override => override.code === "admin-unreadable"); + // The server reports settings it can't parse as disconnected, but the app may still read them. + const unparsed = client.state === "disconnected" + && client.notes.some(note => note.code === "settings-not-json" || note.code === "settings-not-object"); + if (overridden || (!unparsed && !adminUnreadable)) result[client.id] = { state: client.state, overridden }; + } + } + return result; +} + const RESTORES = new Set(["exact", "path-wise", "none"]); type ActionBody = { ok?: unknown; code?: unknown; message?: unknown; profilePath?: unknown; changed?: unknown; restore?: unknown }; @@ -87,5 +137,8 @@ export async function runGatewayClientAction( return actionOutcome(true, await response.json() as ActionBody); } catch { return { reached: false, ok: false, code: null, message: null, profilePath: null, changed: false, restore: null }; + } finally { + invalidateClientResource(`integration-gateway-overview:${apiBase}`); + invalidateClientResource(`integration-gateway-clients:${apiBase}`); } } diff --git a/gui/tests/gateway-clients-api.test.ts b/gui/tests/gateway-clients-api.test.ts index 322ba5ba990..d16bfcc81b2 100644 --- a/gui/tests/gateway-clients-api.test.ts +++ b/gui/tests/gateway-clients-api.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, test } from "bun:test"; -import { runGatewayClientAction } from "../src/pages/integrations/gateway-clients-api"; +import { loadGatewayClientOverview, loadGatewayClients, runGatewayClientAction } from "../src/pages/integrations/gateway-clients-api"; /** The action client reads a refusal's code but never parses a body it has no contract for. */ const previousFetch = globalThis.fetch; @@ -22,3 +22,80 @@ test("a 5xx answer is reached but not parsed", async () => { reached: true, ok: false, code: null, message: null, profilePath: null, changed: false, restore: null, }); }); + +test("a gateway summary keeps a valid state, rejects duplicates and does not retain wire details", async () => { + answer(Response.json({ clients: [ + null, + { id: "antigravity", state: "connected", overrides: [], notes: [] }, + { id: "antigravity", state: "???", overrides: [], notes: [] }, + { id: "antigravity", state: "connected", overrides: [], notes: [] }, + { id: "unrecognized", state: "connected", overrides: [], notes: [] }, + { id: "agy", state: "drifted", files: [{ path: "/private/.bashrc" }], overrides: [{ code: "env-gateway", detail: "private detail" }], notes: [] }, + ] })); + expect(await loadGatewayClientOverview("")).toEqual({ agy: { state: "drifted", overridden: true } }); +}); + +test.each([ + ["agy", "connected", ["env-gateway"], false], + ["agy", "connected", ["admin-gateway", "env-gateway"], true], + ["agy", "disconnected", ["env-gateway"], true], + ["agy", "drifted", ["env-gateway"], true], + ["antigravity", "connected", ["env-gateway"], true], +] as const)("%s %s with %j reports overridden=%p", async (id, state, codes, overridden) => { + answer(Response.json({ clients: [{ id, state, overrides: codes.map(code => ({ code })), notes: [] }] })); + expect(await loadGatewayClientOverview("")).toEqual({ [id]: { state, overridden } }); +}); + +test("admin-unreadable is unknown unless a confirmed override is also present", async () => { + answer(Response.json({ clients: [{ id: "agy", state: "connected", overrides: [{ code: "admin-unreadable" }], notes: [] }] })); + expect(await loadGatewayClientOverview("")).toEqual({}); + answer(Response.json({ clients: [{ id: "antigravity", state: "connected", overrides: [{ code: "admin-unreadable" }, { code: "env-gateway" }], notes: [] }] })); + expect(await loadGatewayClientOverview("")).toEqual({ antigravity: { state: "connected", overridden: true } }); +}); + +test("a malformed or absent gateway row never defaults to connected, disconnected or overridden", async () => { + for (const row of [ + { id: "agy", state: "connected", overrides: {}, notes: [] }, + { id: "antigravity", state: "disconnected", overrides: [] }, + { id: "antigravity", state: "disconnected", overrides: [], notes: {} }, + { id: "antigravity", state: "disconnected", overrides: [], notes: [{}] }, + { id: "agy", state: "drifted", overrides: [{ detail: "missing code" }], notes: [] }, + { id: "agy", state: "drifted", overrides: [{ code: "unknown-override" }], notes: [] }, + ]) { + answer(Response.json({ clients: [row] })); + expect(await loadGatewayClientOverview("")).toEqual({}); + } + answer(Response.json({ clients: {} })); + await expect(loadGatewayClientOverview("")).rejects.toThrow("gateway client status unavailable"); +}); + +test.each(["settings-not-json", "settings-not-object"])("%s is unknown unless a confirmed override is present", async code => { + const row = { id: "antigravity", state: "disconnected", notes: [{ code }] }; + answer(Response.json({ clients: [{ ...row, overrides: [] }] })); + expect(await loadGatewayClientOverview("")).toEqual({}); + answer(Response.json({ clients: [{ ...row, overrides: [{ code: "admin-unreadable" }] }] })); + expect(await loadGatewayClientOverview("")).toEqual({}); + answer(Response.json({ clients: [{ ...row, overrides: [{ code: "admin-gateway" }] }] })); + expect(await loadGatewayClientOverview("")).toEqual({ antigravity: { state: "disconnected", overridden: true } }); +}); + +test("aborted gateway requests reject with the abort error instead of unavailable", async () => { + const preAborted = new AbortController(); + const reason = new DOMException("cancelled", "AbortError"); + preAborted.abort(reason); + let called = false; + globalThis.fetch = (async () => { + called = true; + return Response.json({ clients: [] }); + }) as unknown as typeof fetch; + await expect(loadGatewayClients("", preAborted.signal)).rejects.toBe(reason); + await expect(loadGatewayClientOverview("", preAborted.signal)).rejects.toBe(reason); + expect(called).toBe(false); + + const inFlight = new AbortController(); + globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { + inFlight.abort(); + throw init?.signal?.reason ?? new DOMException("Aborted", "AbortError"); + }) as unknown as typeof fetch; + await expect(loadGatewayClientOverview("", inFlight.signal)).rejects.toMatchObject({ name: "AbortError" }); +}); diff --git a/gui/tests/gateway-clients-page.test.tsx b/gui/tests/gateway-clients-page.test.tsx index e8afbd31e71..cf1241a3ea6 100644 --- a/gui/tests/gateway-clients-page.test.tsx +++ b/gui/tests/gateway-clients-page.test.tsx @@ -21,6 +21,7 @@ let mountCount = 0; let apiBase = ""; let clients: GatewayClientStatus[]; let actionResponse: () => Response; +let statusResponse: () => Response; function json(body: unknown, status = 200): Response { return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); @@ -66,12 +67,14 @@ beforeEach(() => { notes: [{ code: "agy-version", text: "Gateway support needs agy 1.2.15 or newer." }], }), ]; + statusResponse = () => json({ clients }); actionResponse = () => json({ ok: true, id: "antigravity", action: "connect", changed: true, changedFiles: [], message: "Antigravity now uses OpenCodex.", notes: [{ code: "restart-app", text: "Restart Antigravity to apply a change." }], status: clients[0] }); const mockFetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input instanceof Request ? input.url : input); const method = init?.method ?? "GET"; requests.push({ method, url, body: typeof init?.body === "string" ? init.body : null }); - return method === "POST" ? actionResponse() : json({ clients }); + if (url === `${apiBase}/api/gateway-clients` && method === "GET") return statusResponse(); + return method === "POST" ? actionResponse() : json({}, 404); }) as typeof fetch; Object.defineProperty(globalThis, "fetch", { configurable: true, value: mockFetch }); Object.defineProperty(testWindow, "fetch", { configurable: true, value: mockFetch }); @@ -92,6 +95,7 @@ afterEach(async () => { async function settle(): Promise { await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 30)); }); + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); } async function mount(): Promise { @@ -205,3 +209,102 @@ test("agy disconnect shows the affected shell profile and recovery instructions" ); expect(button(agy, "Disconnect").disabled).toBe(false); }); + +async function mountClientsOverview(): Promise { + const [{ createRoot }, { LanguageProvider }, { default: Integrations }] = await Promise.all([ + import("react-dom/client"), + import("../src/i18n/provider"), + import("../src/pages/Integrations"), + ]); + testWindow.location.hash = "#integrations"; + await act(async () => { + root = createRoot(container); + root.render(); + }); + await settle(); + const section = container.querySelector("[aria-labelledby='gateway-client-overview-title']"); + if (!section) throw new Error("no gateway clients section in the Clients overview"); + return section; +} + +test("Clients lists both gateway clients without writes, and setup opens the existing Antigravity tab", async () => { + clients[0]!.state = "connected"; + const section = await mountClientsOverview(); + expect(Array.from(section.querySelectorAll("h4"), node => node.textContent)).toEqual(["Antigravity (desktop)", "agy (CLI)"]); + expect(Array.from(section.querySelectorAll(".badge"), node => node.textContent)).toEqual(["Override detected", "Connected"]); + expect(Array.from(section.querySelectorAll(".badge"), node => [node.getAttribute("data-integration-state"), node.className])) + .toEqual([["stale", "badge badge-amber"], ["current", "badge badge-green"]]); + expect(Array.from(section.querySelectorAll(".integration-card"), node => node.getAttribute("data-tone"))) + .toEqual(["attention", null]); + expect(section.textContent).not.toContain("/home/u"); + expect(section.textContent).not.toContain("settings.json"); + expect(section.querySelectorAll("[role='switch'], .btn-danger")).toHaveLength(0); + expect(section.querySelectorAll("a")).toHaveLength(0); + expect(section.querySelector(".integration-meta")?.textContent).toContain("agy also follows this setting"); + const titleButtons = [...section.querySelectorAll(".integration-card-link")]; + expect(titleButtons.map(btn => btn.textContent)).toEqual(["Antigravity (desktop)", "agy (CLI)"]); + const settingsButtons = [...section.querySelectorAll(".integration-card-actions button")]; + expect(settingsButtons.map(btn => [btn.textContent, btn.tabIndex])).toEqual([["Settings", -1], ["Settings", -1]]); + expect(requests.filter(request => request.url.endsWith("/api/gateway-clients"))).toHaveLength(1); + expect((container.querySelector(".connect-disable-all") as HTMLButtonElement).disabled).toBe(true); + await act(async () => { titleButtons[1]!.click(); }); + await settle(); + expect(testWindow.location.hash).toBe("#integrations/antigravity"); + expect(container.querySelector("#integrations-tab-antigravity")?.getAttribute("aria-selected")).toBe("true"); + expect(card("agy").textContent).toContain("Needs agy"); + expect(requests.every(request => request.method === "GET")).toBe(true); +}); + +test("Clients renders drifted and unparseable states accurately without false disconnects", async () => { + clients[0]!.state = "disconnected"; + clients[0]!.overrides = []; + clients[0]!.notes = [{ code: "settings-not-json", text: "settings.json could not be parsed" }]; + clients[1]!.state = "drifted"; + clients[1]!.overrides = []; + const section = await mountClientsOverview(); + expect(Array.from(section.querySelectorAll(".badge"), node => node.textContent)).toEqual(["Status unknown", "Update needed"]); + expect(Array.from(section.querySelectorAll(".badge"), node => node.getAttribute("data-integration-state"))) + .toEqual(["unknown", "stale"]); + expect(Array.from(section.querySelectorAll(".integration-card"), node => node.getAttribute("data-tone"))) + .toEqual([null, "attention"]); +}); + +test("a failed gateway status read keeps both setup controls and does not report a false disconnect", async () => { + statusResponse = () => json({}, 503); + const section = await mountClientsOverview(); + expect(Array.from(section.querySelectorAll(".badge"), node => node.textContent)).toEqual(["Status unknown", "Status unknown"]); + expect(section.querySelectorAll(".integration-card-link")).toHaveLength(2); + expect(requests.every(request => request.method === "GET")).toBe(true); +}); + +test("after a dedicated setup action Clients rereads state even when switching back while the action is in flight", async () => { + const section = await mountClientsOverview(); + const agyBadge = () => section.querySelectorAll(".badge")[1]?.textContent; + expect(agyBadge()).toBe("Connected"); + await act(async () => { section.querySelectorAll(".integration-card-link")[1]!.click(); }); + await settle(); + + let resolveAction!: (response: Response) => void; + actionResponse = () => new Promise(resolve => { resolveAction = resolve; }); + await act(async () => { button(card("agy"), "Disconnect").click(); }); + // Switch back to Clients before the POST settles so Overview reads the pre-mutation state first. + await act(async () => { (container.querySelector("#integrations-tab-overview") as HTMLButtonElement).click(); }); + await settle(); + expect(agyBadge()).toBe("Connected"); + + await act(async () => { + clients[1]!.state = "disconnected"; + resolveAction(json({ ok: true, id: "agy", action: "disconnect", changed: true, restore: "exact" })); + }); + await settle(); + expect(requests.filter(request => request.method === "POST").map(request => request.url)) + .toEqual([`${apiBase}/api/gateway-clients/agy/disconnect`]); + expect(agyBadge()).toBe("Not connected"); + + await act(async () => { section.querySelectorAll(".integration-card-link")[0]!.click(); }); + await settle(); + statusResponse = () => json({}, 503); + await act(async () => { (container.querySelector("#integrations-tab-overview") as HTMLButtonElement).click(); }); + await settle(); + expect(agyBadge()).toBe("Status unknown"); +}); diff --git a/readme/README.es.md b/readme/README.es.md index 5a6306adcd6..3132345d6f7 100644 --- a/readme/README.es.md +++ b/readme/README.es.md @@ -111,6 +111,8 @@ Conecta la herramienta que ya utilizas: | Claude Code | Una vez instalada la CLI `claude`, ejecuta `ocx claude`. Inicia el proxy si hace falta y abre Claude Code a través de él. | | Claude Desktop | Ejecuta `ocx claude desktop`. Para una instalación nueva configura el perfil de puerta de enlace para toda la aplicación. Conserva una configuración oficial existente; `ocx claude desktop apply --gateway` cambia explícitamente al perfil de puerta de enlace. Consulta la [guía de Claude Code](https://opencodex.me/es/guides/claude-code/). Cierra por completo y vuelve a abrir Claude Desktop después de cambiar. | | Grok Build | Si el proxy escucha localmente, la integración de Grok está habilitada y existe `~/.grok`, `ocx start` registra los modelos. Elige un modelo `ocx-*` en Grok Build. Para el acceso remoto, consulta la [guía de Grok Build](https://opencodex.me/es/guides/grok-build/). Después de añadir proveedores, reinicia el proxy (o ejecuta `ocx ensure` si está habilitado el inicio automático con Codex) para actualizar la lista. | +| Google Antigravity (escritorio) | En el panel, abre **Enrutamiento → Antigravity** (también hay un enlace en **Enrutamiento → Clientes**) o ejecuta `ocx connect antigravity` en el equipo donde esté instalado. | +| agy (CLI) | Abre **Enrutamiento → Antigravity** o ejecuta `ocx connect agy` en el equipo donde esté instalado. Vuelve a cargar el perfil de shell indicado antes de ejecutar `agy`. | | Herramientas con integración administrada | Usa **Enrutamiento** en el panel o `ocx integration client enable --client `. | | Cualquier otra herramienta | Configura `http://localhost:10100/v1` como URL base compatible con OpenAI o `http://localhost:10100` como URL base para Anthropic. | diff --git a/readme/README.fr.md b/readme/README.fr.md index 2b71617e0fd..472594bbdb7 100644 --- a/readme/README.fr.md +++ b/readme/README.fr.md @@ -109,6 +109,8 @@ Connectez l’outil que vous utilisez déjà : | Claude Code | Avec le CLI `claude` installé, exécutez `ocx claude`. Il démarre le proxy si nécessaire et lance Claude Code à travers celui-ci. | | Claude Desktop | Exécutez `ocx claude desktop`. Lors d’une nouvelle installation, cette commande configure le profil de passerelle pour toute l’application ; une configuration first-party existante est conservée et `ocx claude desktop apply --gateway` permet de changer explicitement. Consultez le [guide Claude Code](https://opencodex.me/fr/guides/claude-code/). Quittez complètement puis rouvrez Claude Desktop après un changement. | | Grok Build | Sur une écoute locale avec l’intégration Grok activée, `ocx start` enregistre les modèles lorsque `~/.grok` existe ; choisissez un modèle `ocx-*` dans Grok Build. Pour une configuration distante, consultez le [guide Grok Build](https://opencodex.me/fr/guides/grok-build/). Après avoir ajouté des fournisseurs, redémarrez le proxy (ou lancez `ocx ensure` lorsque le démarrage automatique de Codex est activé) pour actualiser la liste. | +| Google Antigravity (bureau) | Dans le tableau de bord, ouvrez **Routage → Antigravity** (également accessible depuis **Routage → Clients**) ou exécutez `ocx connect antigravity` sur la machine où il est installé. | +| agy (CLI) | Ouvrez **Routage → Antigravity** ou exécutez `ocx connect agy` sur la machine où il est installé. Rechargez le profil de shell indiqué avant de lancer `agy`. | | Outils avec intégration gérée | Utilisez la page **Routage** du tableau de bord ou `ocx integration client enable --client `. | | Tout autre outil | Définissez l’URL de base compatible OpenAI `http://localhost:10100/v1` ou l’URL de base Anthropic `http://localhost:10100`. | diff --git a/readme/README.ja.md b/readme/README.ja.md index cb49a556cb3..b89bd9cbcb8 100644 --- a/readme/README.ja.md +++ b/readme/README.ja.md @@ -108,6 +108,8 @@ ocx start # プロキシとダッシュボードが loca | Claude Code | `claude` CLI をインストールした状態で `ocx claude` を実行します。必要に応じてプロキシを起動し、そこを経由して Claude Code を起動します。 | | Claude Desktop | `ocx claude desktop` を実行します。新規インストールではアプリ全体にゲートウェイプロファイルを設定します。既存の first-party 設定は維持され、`ocx claude desktop apply --gateway` で明示的に切り替えられます。[Claude Code ガイド](https://opencodex.me/ja/guides/claude-code/)を参照してください。 切り替えた後は Claude Desktop を完全に終了してから開き直してください。 | | Grok Build | ローカルリスナーで Grok 連携が有効かつ `~/.grok` が存在する場合、`ocx start` がモデルを登録します。Grok Build で `ocx-*` モデルを選択してください。リモート設定は [Grok Build ガイド](https://opencodex.me/ja/guides/grok-build/)を参照してください。プロバイダーを追加した後は、プロキシを再起動する(または Codex 自動起動が有効なら `ocx ensure` を実行する)と一覧を更新できます。 | +| Google Antigravity(デスクトップ) | ダッシュボードの **ルート → Antigravity** を開くか(**ルート → クライアント** からも移動できます)、インストール済みのマシンで `ocx connect antigravity` を実行します。 | +| agy (CLI) | **ルート → Antigravity** を開くか、インストール済みのマシンで `ocx connect agy` を実行します。`agy` を起動する前に、案内されたシェルプロファイルを再読み込みしてください。 | | 管理対象の統合があるツール | ダッシュボードの **ルート** ページか `ocx integration client enable --client ` を使います。 | | その他のツール | カスタムの OpenAI 互換ベース URL に `http://localhost:10100/v1` を、または Anthropic ベース URL に `http://localhost:10100` を設定します。 | diff --git a/readme/README.ko.md b/readme/README.ko.md index f6d6f594beb..e39da2f362d 100644 --- a/readme/README.ko.md +++ b/readme/README.ko.md @@ -107,6 +107,8 @@ ocx start # 프록시 + 대시보드: localhost:10100 | Claude Code | `claude` CLI가 설치된 상태에서 `ocx claude`를 실행하세요. 필요하면 프록시를 시작하고 이를 통해 Claude Code를 실행합니다. | | Claude Desktop | `ocx claude desktop`을 실행하세요. 새로 설치할 때는 앱 전체에 게이트웨이 프로필을 설정합니다. 기존 first-party 설정은 유지되며, `ocx claude desktop apply --gateway`로 명시적으로 전환할 수 있습니다. [Claude Code 가이드](https://opencodex.me/ko/guides/claude-code/)를 참조하세요. 전환한 뒤에는 Claude Desktop을 완전히 종료했다가 다시 여세요. | | Grok Build | 로컬 리스너에서 Grok 통합이 활성화되어 있고 `~/.grok`이 있으면 `ocx start`가 모델을 등록합니다. Grok Build에서 `ocx-*` 모델을 선택하세요. 원격 설정은 [Grok Build 가이드](https://opencodex.me/ko/guides/grok-build/)를 참조하세요. 프로바이더를 추가한 뒤에는 프록시를 재시작해(또는 Codex 자동 시작이 활성화된 경우 `ocx ensure`를 실행해) 목록을 갱신하세요. | +| Google Antigravity (데스크톱) | 대시보드에서 **라우트 → Antigravity**를 열거나(**라우트 → 클라이언트**에서도 이동 가능), 설치된 컴퓨터에서 `ocx connect antigravity`를 실행하세요. | +| agy (CLI) | **라우트 → Antigravity**를 열거나 설치된 컴퓨터에서 `ocx connect agy`를 실행하세요. 안내된 셸 프로필을 다시 불러온 뒤 `agy`를 실행하세요. | | 관리형 통합이 있는 도구 | 대시보드의 **라우트** 페이지 또는 `ocx integration client enable --client `를 사용하세요. | | 그 밖의 도구 | OpenAI 호환 기본 URL을 `http://localhost:10100/v1`로, 또는 Anthropic 기본 URL을 `http://localhost:10100`으로 설정하세요. | diff --git a/readme/README.ru.md b/readme/README.ru.md index a86bfd0d28d..bb173c45d26 100644 --- a/readme/README.ru.md +++ b/readme/README.ru.md @@ -108,6 +108,8 @@ ocx start # прокси + панель управлен | Claude Code | Установив CLI `claude`, выполните `ocx claude`. Команда при необходимости запускает прокси и запускает через него Claude Code. | | Claude Desktop | Выполните `ocx claude desktop`. При новой установке команда настраивает профиль шлюза для всего приложения; существующая настройка first-party сохраняется, а `ocx claude desktop apply --gateway` явно переключает режим. См. [руководство Claude Code](https://opencodex.me/ru/guides/claude-code/). После переключения полностью закройте и снова откройте Claude Desktop. | | Grok Build | При локальном прослушивании и включённой интеграции Grok команда `ocx start` регистрирует модели, если существует `~/.grok`; выберите модель `ocx-*` в Grok Build. Об удалённой настройке см. [руководство Grok Build](https://opencodex.me/ru/guides/grok-build/). После добавления провайдеров перезапустите прокси (или выполните `ocx ensure`, если включён автозапуск Codex), чтобы обновить список. | +| Google Antigravity (настольное приложение) | Откройте на панели **Маршрут → Antigravity** (ссылка также есть в разделе **Маршрут → Клиенты**) или выполните `ocx connect antigravity` на компьютере, где установлено приложение. | +| agy (CLI) | Откройте **Маршрут → Antigravity** или выполните `ocx connect agy` на компьютере, где установлена утилита. Перед запуском `agy` перечитайте указанный профиль оболочки. | | Инструменты с управляемой интеграцией | Используйте страницу **Маршрут** панели или `ocx integration client enable --client `. | | Любой другой инструмент | Укажите пользовательский базовый URL, совместимый с OpenAI: `http://localhost:10100/v1`, либо базовый URL Anthropic: `http://localhost:10100`. | diff --git a/readme/README.tr.md b/readme/README.tr.md index 7ef8b4d6c70..ca39552715a 100644 --- a/readme/README.tr.md +++ b/readme/README.tr.md @@ -108,6 +108,8 @@ Zaten kullandığınız aracı bağlayın: | Claude Code | `claude` CLI kuruluysa `ocx claude` çalıştırın. Gerekirse proxy’yi başlatır ve Claude Code’u onun üzerinden açar. | | Claude Desktop | `ocx claude desktop` çalıştırın. Yeni kurulumda tüm uygulama için ağ geçidi profilini ayarlar; mevcut first-party yapılandırması korunur ve `ocx claude desktop apply --gateway` açıkça geçiş yapar. [Claude Code kılavuzuna](https://opencodex.me/tr/guides/claude-code/) bakın. Geçişten sonra Claude Desktop’tan tamamen çıkıp yeniden açın. | | Grok Build | Yerel bir dinleyicide Grok entegrasyonu etkinse ve `~/.grok` mevcutsa, `ocx start` modelleri kaydeder; Grok Build içinde bir `ocx-*` modeli seçin. Uzak kurulumlar için [Grok Build kılavuzuna](https://opencodex.me/tr/guides/grok-build/) bakın. Sağlayıcı ekledikten sonra listeyi yenilemek için proxy’yi yeniden başlatın (veya Codex otomatik başlatma etkinse `ocx ensure` çalıştırın). | +| Google Antigravity (masaüstü) | Panoda **Rota → Antigravity** bölümünü açın (**Rota → İstemciler** bölümünde de bağlantısı var) veya kurulu olduğu makinede `ocx connect antigravity` komutunu çalıştırın. | +| agy (CLI) | **Rota → Antigravity** bölümünü açın veya kurulu olduğu makinede `ocx connect agy` komutunu çalıştırın. `agy` komutunu çalıştırmadan önce belirtilen kabuk profilini yeniden yükleyin. | | Yönetilen entegrasyonu olan araçlar | Panelin **Rota** sayfasını veya `ocx integration client enable --client ` komutunu kullanın. | | Diğer tüm araçlar | Özel OpenAI uyumlu temel URL’yi `http://localhost:10100/v1` veya Anthropic temel URL’sini `http://localhost:10100` olarak ayarlayın. | diff --git a/readme/README.zh-CN.md b/readme/README.zh-CN.md index b7e47f48a32..e5f355b65f9 100644 --- a/readme/README.zh-CN.md +++ b/readme/README.zh-CN.md @@ -108,6 +108,8 @@ ocx start # 代理 + 仪表板:localhost:10100 | Claude Code | 安装 `claude` CLI 后运行 `ocx claude`。它会在需要时启动代理,并通过代理启动 Claude Code。 | | Claude Desktop | 运行 `ocx claude desktop`。全新安装时会为整个应用设置网关配置;已有的 first-party 设置会保持原样,可运行 `ocx claude desktop apply --gateway` 明确切换。详见 [Claude Code 指南](https://opencodex.me/zh-cn/guides/claude-code/)。 切换后请完全退出并重新打开 Claude Desktop。 | | Grok Build | 在本地监听且启用 Grok 集成时,若 `~/.grok` 存在,`ocx start` 会注册模型;在 Grok Build 中选择 `ocx-*` 模型。远程配置请参见 [Grok Build 指南](https://opencodex.me/zh-cn/guides/grok-build/)。添加提供商后,重启代理(或在启用 Codex 自启动时运行 `ocx ensure`)以刷新列表。 | +| Google Antigravity(桌面版) | 在控制台打开 **路由 → Antigravity**(也可从 **路由 → 客户端** 进入),或在安装客户端的机器上运行 `ocx connect antigravity`。 | +| agy (CLI) | 打开 **路由 → Antigravity**,或在安装客户端的机器上运行 `ocx connect agy`。运行 `agy` 前,重新加载提示的 shell 配置文件。 | | 有托管集成的工具 | 使用仪表盘 **路由** 页面,或运行 `ocx integration client enable --client `。 | | 其他工具 | 将自定义 OpenAI 兼容 base URL 设为 `http://localhost:10100/v1`,或将 Anthropic base URL 设为 `http://localhost:10100`。 | diff --git a/readme/README.zh-TW.md b/readme/README.zh-TW.md index 965c5c89849..c031d352e12 100644 --- a/readme/README.zh-TW.md +++ b/readme/README.zh-TW.md @@ -108,6 +108,8 @@ ocx start # 代理 + 儀表板位於 localhost:10100 | Claude Code | 安裝 `claude` CLI 後執行 `ocx claude`。它會在需要時啟動代理,並透過代理啟動 Claude Code。 | | Claude Desktop | 執行 `ocx claude desktop`。全新安裝時會為整個應用程式設定閘道設定檔;既有的 first-party 設定會保留,可執行 `ocx claude desktop apply --gateway` 明確切換。詳見 [Claude Code 指南](https://opencodex.me/zh-tw/guides/claude-code/)。 切換後請完全結束並重新開啟 Claude Desktop。 | | Grok Build | 在本機監聽且啟用 Grok 整合時,若 `~/.grok` 存在,`ocx start` 會註冊模型;在 Grok Build 中選擇 `ocx-*` 模型。遠端設定請參見 [Grok Build 指南](https://opencodex.me/zh-tw/guides/grok-build/)。新增供應商後,重新啟動代理(或在啟用 Codex 自動啟動時執行 `ocx ensure`)以更新清單。 | +| Google Antigravity(桌面版) | 在控制台開啟 **路由 → Antigravity**(也可從 **路由 → 用戶端** 前往),或在安裝用戶端的電腦上執行 `ocx connect antigravity`。 | +| agy (CLI) | 開啟 **路由 → Antigravity**,或在安裝用戶端的電腦上執行 `ocx connect agy`。執行 `agy` 前,請重新載入提示的 shell 設定檔。 | | 具備受管理整合的工具 | 使用儀表板的 **路由** 頁面,或執行 `ocx integration client enable --client `。 | | 其他工具 | 將自訂 OpenAI 相容基本 URL 設為 `http://localhost:10100/v1`,或將 Anthropic 基本 URL 設為 `http://localhost:10100`。 | diff --git a/readme/i18n-manifest.json b/readme/i18n-manifest.json index 6b77bf8665a..01a3faf69d3 100644 --- a/readme/i18n-manifest.json +++ b/readme/i18n-manifest.json @@ -6,49 +6,49 @@ "file": "readme/README.fr.md", "label": "Français", "docsPath": "fr", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" }, "ko": { "file": "readme/README.ko.md", "label": "한국어", "docsPath": "ko", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" }, "zh-CN": { "file": "readme/README.zh-CN.md", "label": "简体中文", "docsPath": "zh-cn", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" }, "zh-TW": { "file": "readme/README.zh-TW.md", "label": "繁體中文", "docsPath": "zh-tw", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" }, "ru": { "file": "readme/README.ru.md", "label": "Русский", "docsPath": "ru", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" }, "ja": { "file": "readme/README.ja.md", "label": "日本語", "docsPath": "ja", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" }, "tr": { "file": "readme/README.tr.md", "label": "Türkçe", "docsPath": "tr", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" }, "es": { "file": "readme/README.es.md", "label": "Español", "docsPath": "es", - "sourceSha256": "f7584f54895e02ef55bfcfc66e2c372a5dde88682d6517248e09eda2584762aa" + "sourceSha256": "12c497b28225b1c4fab3b21c4f36c4d363928f10a3dcfc999276acaf5e09a5f9" } } } diff --git a/scripts/client-support-matrix/locales.ts b/scripts/client-support-matrix/locales.ts index e0c2e05d86a..bf938c70c5c 100644 --- a/scripts/client-support-matrix/locales.ts +++ b/scripts/client-support-matrix/locales.ts @@ -33,6 +33,9 @@ export interface Strings { validateApply: string; clientSelected: string; }; + gatewayHeading: string; + gatewayIntro: string; + gatewaySetup: string; endpointsHeading: string; endpointsIntro: string; maintenanceHeading: string; @@ -43,9 +46,9 @@ export const LOCALES = { root: { title: "Client support", description: "Which coding tools opencodex connects to, how each one is wired, and which protocol it speaks.", - intro: "opencodex is one local gateway for your AI coding tools and models. Some tools it configures natively; for the others it exports or manages a config file that points the tool at the local proxy. This page is generated from the code registries, so it lists exactly what the current release ships.", + intro: "opencodex is one local gateway for your AI coding tools and models. It can configure tools natively, export or manage a config file, or use a dedicated gateway connector. This page is generated from the code registries, so it lists exactly what the current release ships.", levelsHeading: "Support levels", - implementedDefinition: "the client is in the registry. For exported configs, the protocol shown is read from the config opencodex generates, and generation fails if it changes. A protocol marked *curated* names an endpoint that comes from a review instead of the config itself (native clients, and clients that turn a setting into a specific endpoint); the generator checks that the reviewed code is still in place. \"OpenAI-compatible\" rows make no endpoint claim.", + implementedDefinition: "the client is in the registry. For exported configs, the protocol shown is read from the config opencodex generates, and generation fails if it changes. A protocol marked *curated* comes from a code review rather than automated config inspection; the generator checks that the reviewed code is still in place. \"OpenAI-compatible\" rows make no endpoint claim.", testCoveredDefinition: "implemented, and a test case chosen in review that exercises this client is linked. The generator checks only that the test still exists and is enabled; read it to see what it asserts.", clientsHeading: "Clients", columns: { client: "Client", native: "Native", configExport: "Config export", managed: "Managed file integration", protocol: "Inbound protocol", level: "Support level", runtime: "Runtime verified", notes: "Notes" }, @@ -68,17 +71,20 @@ export const LOCALES = { validateApply: "Apply runs a client-specific check first and can refuse.", clientSelected: "The client picks the endpoint from this setting (reviewed against the client's documented behavior).", }, + gatewayHeading: "Gateway clients", + gatewayIntro: "Use **Route → Antigravity** on the dashboard (also linked from **Route → Clients**) or run the commands below. These connectors set up the gateway for their respective client; they do not export a config or use the managed file integration workflow. For agy, reload the indicated shell profile before running the CLI.", + gatewaySetup: "Set up on this machine", endpointsHeading: "Inbound endpoints", endpointsIntro: "The proxy accepts these protocols. A tool that is not listed above can still connect if it lets you set a custom endpoint for one of them.", maintenanceHeading: "Keeping this page current", - maintenance: "This page is generated by `scripts/generate-client-support-matrix.ts` from the export, managed-integration and native-integration registries. To add a client, add its entry in `scripts/client-support-matrix/metadata.ts` and run `bun run docs:clients`; `bun run docs:clients:check` fails while the committed page is stale.", + maintenance: "This page is generated by `scripts/generate-client-support-matrix.ts` from the export, managed-integration, native-integration and gateway-client registries. To add a client, add its entry in `scripts/client-support-matrix/metadata.ts` and run `bun run docs:clients`; `bun run docs:clients:check` fails while the committed page is stale.", }, es: { title: "Compatibilidad con clientes", description: "Qué herramientas de programación conecta opencodex, cómo se conecta cada una y qué protocolo utiliza.", - intro: "opencodex es una única pasarela local para tus herramientas de programación con IA y tus modelos. Configura algunas herramientas de forma nativa; para las demás, exporta o administra un archivo de configuración que las dirige al proxy local. Esta página se genera a partir de los registros del código, por lo que enumera exactamente lo que ofrece la versión actual.", + intro: "opencodex es una única pasarela local para tus herramientas de programación con IA y tus modelos. Puede configurar herramientas de forma nativa, exportar o administrar un archivo de configuración o usar un conector de gateway dedicado. Esta página se genera a partir de los registros del código, por lo que enumera exactamente lo que ofrece la versión actual.", levelsHeading: "Niveles de compatibilidad", - implementedDefinition: "el cliente figura en el registro. Para las configuraciones exportadas, el protocolo mostrado se lee de la configuración que genera opencodex, y la generación falla si cambia. Un protocolo marcado como *revisado* indica un endpoint determinado mediante una revisión, en lugar de obtenerse de la propia configuración (clientes nativos y clientes que convierten un ajuste en un endpoint concreto); el generador comprueba que el código revisado siga presente. Las filas «Compatible con OpenAI» no afirman que se use un endpoint concreto.", + implementedDefinition: "el cliente figura en el registro. Para las configuraciones exportadas, el protocolo mostrado se lee de la configuración que genera opencodex, y la generación falla si cambia. Un protocolo marcado como *revisado* se obtiene de una revisión del código, no de una inspección automatizada de la configuración; el generador comprueba que el código revisado siga presente. Las filas «Compatible con OpenAI» no afirman que se use un endpoint concreto.", testCoveredDefinition: "cumple implemented y enlaza un caso de prueba elegido durante la revisión que ejercita este cliente. El generador solo comprueba que la prueba siga existiendo y esté habilitada; léela para saber qué verifica.", clientsHeading: "Clientes", columns: { client: "Cliente", native: "Nativo", configExport: "Exportación de configuración", managed: "Integración mediante archivo administrado", protocol: "Protocolo de entrada", level: "Nivel de compatibilidad", runtime: "Verificado en ejecución", notes: "Notas" }, @@ -101,17 +107,20 @@ export const LOCALES = { validateApply: "Antes de aplicar los cambios, se ejecuta una comprobación específica del cliente que puede rechazarlos.", clientSelected: "El cliente elige el endpoint a partir de este ajuste (revisado según el comportamiento documentado del cliente).", }, + gatewayHeading: "Clientes de gateway", + gatewayIntro: "Abre **Enrutamiento → Antigravity** en el panel (también hay un enlace en **Enrutamiento → Clientes**) o ejecuta los comandos de abajo. Estos conectores configuran el gateway del cliente; no exportan configuraciones ni usan el flujo de integración mediante archivo administrado. Para agy, vuelve a cargar el perfil de shell indicado antes de ejecutar la CLI.", + gatewaySetup: "Configurar en este equipo", endpointsHeading: "Endpoints de entrada", endpointsIntro: "El proxy acepta estos protocolos. Una herramienta que no figure arriba puede conectarse si permite configurar un endpoint personalizado para alguno de ellos.", maintenanceHeading: "Mantener esta página actualizada", - maintenance: "Esta página se genera mediante `scripts/generate-client-support-matrix.ts` a partir de los registros de exportación, integración administrada e integración nativa. Para añadir un cliente, añade su entrada en `scripts/client-support-matrix/metadata.ts` y ejecuta `bun run docs:clients`; `bun run docs:clients:check` falla mientras la página guardada en el repositorio esté desactualizada.", + maintenance: "Esta página se genera mediante `scripts/generate-client-support-matrix.ts` a partir de los registros de exportación, integración administrada, integración nativa y clientes de gateway. Para añadir un cliente, añade su entrada en `scripts/client-support-matrix/metadata.ts` y ejecuta `bun run docs:clients`; `bun run docs:clients:check` falla mientras la página guardada en el repositorio esté desactualizada.", }, fr: { title: "Clients pris en charge", description: "Les outils de code auxquels opencodex se connecte, la façon dont chacun est relié et le protocole qu’il utilise.", - intro: "opencodex est une passerelle locale unique pour vos outils de code IA et vos modèles. Il configure certains outils nativement ; pour les autres, il exporte ou gère un fichier de configuration qui dirige l’outil vers le proxy local. Cette page est générée à partir des registres du code et reflète donc exactement ce que fournit la version actuelle.", + intro: "opencodex est une passerelle locale unique pour vos outils de code IA et vos modèles. Il peut configurer un outil nativement, exporter ou gérer un fichier de configuration, ou utiliser un connecteur de passerelle dédié. Cette page est générée à partir des registres du code et reflète donc exactement ce que fournit la version actuelle.", levelsHeading: "Niveaux de prise en charge", - implementedDefinition: "le client figure dans le registre. Pour les configurations exportées, le protocole indiqué est lu dans la configuration générée par opencodex, et la génération échoue s’il change. Un protocole marqué *revu* désigne un point de terminaison issu d’une revue plutôt que de la configuration elle-même (clients natifs, et clients qui déduisent un point de terminaison précis d’un réglage) ; le générateur vérifie que le code revu est toujours en place. Les lignes « Compatible OpenAI » n’affirment aucun point de terminaison.", + implementedDefinition: "le client figure dans le registre. Pour les configurations exportées, le protocole indiqué est lu dans la configuration générée par opencodex, et la génération échoue s’il change. Un protocole marqué *revu* est établi par une revue de code, et non par une inspection automatisée de la configuration ; le générateur vérifie que le code revu est toujours en place. Les lignes « Compatible OpenAI » n’affirment aucun point de terminaison.", testCoveredDefinition: "implemented, et un cas de test choisi en revue qui exerce ce client est lié. Le générateur vérifie seulement que le test existe toujours et qu’il est actif ; lisez-le pour savoir ce qu’il vérifie.", clientsHeading: "Clients", columns: { client: "Client", native: "Natif", configExport: "Export de configuration", managed: "Intégration de fichier gérée", protocol: "Protocole entrant", level: "Niveau", runtime: "Vérifié à l’exécution", notes: "Remarques" }, @@ -134,17 +143,20 @@ export const LOCALES = { validateApply: "L’application exécute d’abord une vérification propre au client et peut refuser.", clientSelected: "Le client choisit le point de terminaison à partir de ce réglage (vérifié en revue d’après le comportement documenté du client).", }, + gatewayHeading: "Clients de passerelle", + gatewayIntro: "Ouvrez **Routage → Antigravity** dans le tableau de bord (également accessible depuis **Routage → Clients**) ou exécutez les commandes ci-dessous. Ces connecteurs configurent la passerelle du client ; ils n’exportent pas de configuration et n’utilisent pas le flux d’intégration de fichiers gérés. Pour agy, rechargez le profil de shell indiqué avant de lancer la CLI.", + gatewaySetup: "Configurer sur cette machine", endpointsHeading: "Points de terminaison entrants", endpointsIntro: "Le proxy accepte ces protocoles. Un outil absent de la liste peut quand même se connecter s’il permet de définir un point de terminaison personnalisé pour l’un d’eux.", maintenanceHeading: "Tenir cette page à jour", - maintenance: "Cette page est générée par `scripts/generate-client-support-matrix.ts` à partir des registres d’export, d’intégration gérée et d’intégration native. Pour ajouter un client, ajoutez son entrée dans `scripts/client-support-matrix/metadata.ts` puis lancez `bun run docs:clients` ; `bun run docs:clients:check` échoue tant que la page validée est obsolète.", + maintenance: "Cette page est générée par `scripts/generate-client-support-matrix.ts` à partir des registres d’export, d’intégration gérée, d’intégration native et de clients de passerelle. Pour ajouter un client, ajoutez son entrée dans `scripts/client-support-matrix/metadata.ts` puis lancez `bun run docs:clients` ; `bun run docs:clients:check` échoue tant que la page validée est obsolète.", }, ko: { title: "클라이언트 지원", description: "opencodex가 연결하는 코딩 도구, 각 도구의 연결 방식, 사용하는 프로토콜.", - intro: "opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이입니다. 일부 도구는 직접(네이티브로) 설정하고, 나머지는 로컬 프록시를 가리키는 설정 파일을 내보내거나 관리합니다. 이 페이지는 코드 레지스트리에서 생성되므로 현재 릴리스가 제공하는 내용과 정확히 일치합니다.", + intro: "opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이입니다. 도구를 네이티브로 설정하거나, 설정 파일을 내보내거나 관리하거나, 전용 게이트웨이 커넥터로 연결합니다. 이 페이지는 코드 레지스트리에서 생성되므로 현재 릴리스가 제공하는 내용과 정확히 일치합니다.", levelsHeading: "지원 수준", - implementedDefinition: "레지스트리에 등록된 클라이언트입니다. 내보내는 설정의 경우 표의 프로토콜은 opencodex가 생성하는 설정에서 읽으며, 바뀌면 생성이 실패합니다. *검토됨* 표시는 설정 자체가 아니라 리뷰에서 나온 특정 엔드포인트를 뜻합니다(네이티브 클라이언트, 설정값을 특정 엔드포인트로 바꾸는 클라이언트). 생성기는 리뷰한 코드가 그대로 있는지 확인합니다. 'OpenAI 호환' 행은 엔드포인트를 단정하지 않습니다.", + implementedDefinition: "레지스트리에 등록된 클라이언트입니다. 내보내는 설정의 경우 표의 프로토콜은 opencodex가 생성하는 설정에서 읽으며, 바뀌면 생성이 실패합니다. *검토됨* 표시는 프로토콜을 설정에서 자동으로 읽은 것이 아니라 코드 검토로 확인했다는 뜻입니다. 생성기는 리뷰한 코드가 그대로 있는지 확인합니다. 'OpenAI 호환' 행은 엔드포인트를 단정하지 않습니다.", testCoveredDefinition: "implemented이면서, 리뷰로 고른 이 클라이언트의 테스트 케이스가 링크되어 있습니다. 생성기는 테스트가 존재하고 비활성화되지 않았는지만 확인하므로, 무엇을 검증하는지는 테스트를 직접 읽어 보세요.", clientsHeading: "클라이언트", columns: { client: "클라이언트", native: "네이티브", configExport: "설정 내보내기", managed: "관리형 파일 연동", protocol: "수신 프로토콜", level: "지원 수준", runtime: "실행 검증", notes: "참고" }, @@ -167,17 +179,20 @@ export const LOCALES = { validateApply: "적용 전에 클라이언트별 검사를 실행하며 거부할 수 있습니다.", clientSelected: "클라이언트가 이 설정값으로 엔드포인트를 고릅니다(클라이언트 문서 동작 기준으로 리뷰함).", }, + gatewayHeading: "게이트웨이 클라이언트", + gatewayIntro: "대시보드에서 **라우트 → Antigravity**를 열거나(**라우트 → 클라이언트**에서도 이동할 수 있음) 아래 명령을 실행하세요. 이 커넥터는 클라이언트의 게이트웨이를 설정하며 설정을 내보내거나 관리형 파일 통합 절차를 사용하지 않아요. agy CLI를 실행하기 전에 안내된 셸 프로필을 다시 불러오세요.", + gatewaySetup: "이 컴퓨터에서 설정", endpointsHeading: "수신 엔드포인트", endpointsIntro: "프록시는 아래 프로토콜을 받습니다. 위 목록에 없는 도구도 이 중 하나로 사용자 지정 엔드포인트를 설정할 수 있으면 연결할 수 있습니다.", maintenanceHeading: "이 페이지 최신 상태 유지", - maintenance: "이 페이지는 `scripts/generate-client-support-matrix.ts`가 내보내기·관리형 연동·네이티브 연동 레지스트리로부터 생성합니다. 클라이언트를 추가하려면 `scripts/client-support-matrix/metadata.ts`에 항목을 넣고 `bun run docs:clients`를 실행하세요. 커밋된 페이지가 오래되면 `bun run docs:clients:check`가 실패합니다.", + maintenance: "이 페이지는 `scripts/generate-client-support-matrix.ts`가 내보내기·관리형 연동·네이티브 연동·게이트웨이 클라이언트 레지스트리로부터 생성합니다. 클라이언트를 추가하려면 `scripts/client-support-matrix/metadata.ts`에 항목을 넣고 `bun run docs:clients`를 실행하세요. 커밋된 페이지가 오래되면 `bun run docs:clients:check`가 실패합니다.", }, "zh-cn": { title: "客户端支持", description: "opencodex 能连接哪些编程工具、每个工具如何接入,以及它使用的协议。", - intro: "opencodex 是一个本地网关,连接你的 AI 编程工具与模型。部分工具由它原生配置;其余工具则通过导出或托管一个指向本地代理的配置文件来接入。本页由代码中的注册表生成,因此与当前版本实际提供的内容完全一致。", + intro: "opencodex 是一个本地网关,连接你的 AI 编程工具与模型。它可以原生配置工具,也可以导出或托管配置文件,或使用专用网关连接器。本页由代码中的注册表生成,因此与当前版本实际提供的内容完全一致。", levelsHeading: "支持级别", - implementedDefinition: "客户端已在注册表中。对于导出的配置,表中协议读取自 opencodex 生成的配置,一旦变化生成就会失败。标有*已审阅*的协议表示其端点来自审阅而非配置本身(原生客户端,以及会把某个设置转换为特定端点的客户端);生成器会检查被审阅的代码是否仍然存在。“OpenAI 兼容”的行不声明具体端点。", + implementedDefinition: "客户端已在注册表中。对于导出的配置,表中协议读取自 opencodex 生成的配置,一旦变化生成就会失败。标有*已审阅*的协议来自代码审阅,而非自动读取配置;生成器会检查被审阅的代码是否仍然存在。“OpenAI 兼容”的行不声明具体端点。", testCoveredDefinition: "满足 implemented,并链接了一个经评审选定、覆盖该客户端的测试用例。生成器只检查该测试仍然存在且未被禁用;它具体断言了什么,请阅读测试本身。", clientsHeading: "客户端", columns: { client: "客户端", native: "原生", configExport: "配置导出", managed: "托管文件集成", protocol: "入站协议", level: "支持级别", runtime: "运行验证", notes: "说明" }, @@ -200,17 +215,20 @@ export const LOCALES = { validateApply: "应用前先运行针对该客户端的检查,可能拒绝。", clientSelected: "客户端根据此设置选择端点(已依据客户端的文档行为评审)。", }, + gatewayHeading: "网关客户端", + gatewayIntro: "在控制台打开 **路由 → Antigravity**(也可从 **路由 → 客户端** 进入),或运行下列命令。这些连接器为各自客户端设置网关,不导出配置,也不走托管文件集成流程。使用 agy 前,请重新加载提示的 shell 配置文件。", + gatewaySetup: "在本机设置", endpointsHeading: "入站端点", endpointsIntro: "代理接受以下协议。未列在上表中的工具,只要能为其中之一设置自定义端点,也可以接入。", maintenanceHeading: "保持本页最新", - maintenance: "本页由 `scripts/generate-client-support-matrix.ts` 根据导出、托管集成和原生集成注册表生成。要添加客户端,请在 `scripts/client-support-matrix/metadata.ts` 中添加条目并运行 `bun run docs:clients`;已提交的页面过期时,`bun run docs:clients:check` 会失败。", + maintenance: "本页由 `scripts/generate-client-support-matrix.ts` 根据导出、托管集成、原生集成和网关客户端注册表生成。要添加客户端,请在 `scripts/client-support-matrix/metadata.ts` 中添加条目并运行 `bun run docs:clients`;已提交的页面过期时,`bun run docs:clients:check` 会失败。", }, "zh-tw": { title: "用戶端支援", description: "opencodex 能連接哪些程式開發工具、每個工具如何接入,以及它使用的協定。", - intro: "opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。部分工具由它原生設定;其餘工具則透過匯出或代管一個指向本機代理的設定檔來接入。本頁由程式碼中的登錄表產生,因此與目前版本實際提供的內容完全一致。", + intro: "opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。它可以原生設定工具,也可以匯出或代管設定檔,或使用專用閘道連接器。本頁由程式碼中的登錄表產生,因此與目前版本實際提供的內容完全一致。", levelsHeading: "支援等級", - implementedDefinition: "用戶端已在登錄表中。對於匯出的設定,表中協定讀取自 opencodex 產生的設定,一旦變更產生就會失敗。標示*已審查*的協定表示其端點來自審查而非設定本身(原生用戶端,以及會把某個設定轉換為特定端點的用戶端);產生器會檢查被審查的程式碼是否仍然存在。「OpenAI 相容」的列不聲明具體端點。", + implementedDefinition: "用戶端已在登錄表中。對於匯出的設定,表中協定讀取自 opencodex 產生的設定,一旦變更產生就會失敗。標示*已審查*的協定來自程式碼審查,而非自動讀取設定;產生器會檢查被審查的程式碼是否仍然存在。「OpenAI 相容」的列不聲明具體端點。", testCoveredDefinition: "符合 implemented,並連結了一個經審查選定、涵蓋該用戶端的測試案例。產生器只檢查該測試仍然存在且未被停用;它實際驗證什麼,請閱讀測試本身。", clientsHeading: "用戶端", columns: { client: "用戶端", native: "原生", configExport: "設定匯出", managed: "代管檔案整合", protocol: "入站協定", level: "支援等級", runtime: "執行驗證", notes: "說明" }, @@ -233,17 +251,20 @@ export const LOCALES = { validateApply: "套用前先執行該用戶端專屬的檢查,可能拒絕。", clientSelected: "用戶端依此設定選擇端點(已依用戶端的文件行為審查)。", }, + gatewayHeading: "閘道用戶端", + gatewayIntro: "在控制台開啟 **路由 → Antigravity**(也可從 **路由 → 用戶端** 前往),或執行下列指令。這些連接器為各自的用戶端設定閘道,不匯出設定,也不使用受管理檔案整合流程。執行 agy 前,請重新載入提示的 shell 設定檔。", + gatewaySetup: "在本機設定", endpointsHeading: "入站端點", endpointsIntro: "代理接受以下協定。未列在上表中的工具,只要能為其中之一設定自訂端點,也可以接入。", maintenanceHeading: "保持本頁最新", - maintenance: "本頁由 `scripts/generate-client-support-matrix.ts` 根據匯出、代管整合與原生整合登錄表產生。要新增用戶端,請在 `scripts/client-support-matrix/metadata.ts` 中加入項目並執行 `bun run docs:clients`;已提交的頁面過期時,`bun run docs:clients:check` 會失敗。", + maintenance: "本頁由 `scripts/generate-client-support-matrix.ts` 根據匯出、代管整合、原生整合與閘道用戶端登錄表產生。要新增用戶端,請在 `scripts/client-support-matrix/metadata.ts` 中加入項目並執行 `bun run docs:clients`;已提交的頁面過期時,`bun run docs:clients:check` 會失敗。", }, ru: { title: "Поддержка клиентов", description: "К каким инструментам для кода подключается opencodex, как подключён каждый из них и какой протокол он использует.", - intro: "opencodex — единый локальный шлюз для ваших ИИ-инструментов для кода и моделей. Часть инструментов он настраивает нативно; для остальных он экспортирует или ведёт файл конфигурации, который направляет инструмент на локальный прокси. Страница сгенерирована из реестров в коде и поэтому в точности соответствует текущему релизу.", + intro: "opencodex — единый локальный шлюз для ваших ИИ-инструментов для кода и моделей. Он может настраивать инструменты нативно, экспортировать или вести файл конфигурации либо использовать отдельный коннектор шлюза. Страница сгенерирована из реестров в коде и поэтому в точности соответствует текущему релизу.", levelsHeading: "Уровни поддержки", - implementedDefinition: "клиент есть в реестре. Для экспортируемых конфигураций протокол берётся из конфигурации, которую генерирует opencodex, и генерация падает, если он меняется. Пометка *проверено* означает, что эндпоинт взят из ревью, а не из самой конфигурации (нативные клиенты и клиенты, которые превращают настройку в конкретный эндпоинт); генератор проверяет, что проверенный код на месте. Строки «Совместим с OpenAI» не утверждают конкретный эндпоинт.", + implementedDefinition: "клиент есть в реестре. Для экспортируемых конфигураций протокол берётся из конфигурации, которую генерирует opencodex, и генерация падает, если он меняется. Пометка *проверено* означает, что протокол определён при ревью кода, а не при автоматической проверке конфигурации; генератор проверяет, что проверенный код на месте. Строки «Совместим с OpenAI» не утверждают конкретный эндпоинт.", testCoveredDefinition: "implemented, и есть ссылка на выбранный при ревью тест, который задействует этого клиента. Генератор проверяет только, что тест существует и не отключён; что именно он проверяет, смотрите в самом тесте.", clientsHeading: "Клиенты", columns: { client: "Клиент", native: "Нативно", configExport: "Экспорт конфигурации", managed: "Управляемая интеграция файла", protocol: "Входящий протокол", level: "Уровень", runtime: "Проверено в работе", notes: "Примечания" }, @@ -266,17 +287,20 @@ export const LOCALES = { validateApply: "Перед применением выполняется проверка, специфичная для клиента, и возможен отказ.", clientSelected: "Клиент выбирает эндпоинт по этой настройке (проверено при ревью по документированному поведению клиента).", }, + gatewayHeading: "Клиенты шлюза", + gatewayIntro: "Откройте **Маршрут → Antigravity** на панели управления (ссылка также есть в разделе **Маршрут → Клиенты**) или выполните команды ниже. Эти коннекторы настраивают шлюз для клиента без экспорта конфигурации или управляемой файловой интеграции. Перед запуском agy перечитайте указанный профиль оболочки.", + gatewaySetup: "Настроить на этом компьютере", endpointsHeading: "Входящие эндпоинты", endpointsIntro: "Прокси принимает эти протоколы. Инструмент, которого нет в таблице, всё равно может подключиться, если позволяет задать собственный эндпоинт для одного из них.", maintenanceHeading: "Актуальность страницы", - maintenance: "Страница генерируется скриптом `scripts/generate-client-support-matrix.ts` из реестров экспорта, управляемых и нативных интеграций. Чтобы добавить клиента, добавьте запись в `scripts/client-support-matrix/metadata.ts` и выполните `bun run docs:clients`; `bun run docs:clients:check` падает, пока закоммиченная страница устарела.", + maintenance: "Страница генерируется скриптом `scripts/generate-client-support-matrix.ts` из реестров экспорта, управляемых интеграций, нативных интеграций и клиентов шлюза. Чтобы добавить клиента, добавьте запись в `scripts/client-support-matrix/metadata.ts` и выполните `bun run docs:clients`; `bun run docs:clients:check` падает, пока закоммиченная страница устарела.", }, ja: { title: "クライアント対応", description: "opencodex が接続するコーディングツール、それぞれの接続方法、使用するプロトコル。", - intro: "opencodex は、AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイです。一部のツールはネイティブに設定し、それ以外はローカルプロキシを指す設定ファイルをエクスポートまたは管理します。このページはコードのレジストリから生成されるため、現在のリリースの内容と正確に一致します。", + intro: "opencodex は、AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイです。ツールをネイティブに設定するほか、設定ファイルをエクスポートまたは管理したり、専用のゲートウェイコネクターを使用したりできます。このページはコードのレジストリから生成されるため、現在のリリースの内容と正確に一致します。", levelsHeading: "サポートレベル", - implementedDefinition: "レジストリに登録されたクライアントです。エクスポートされる設定では、表のプロトコルは opencodex が生成する設定から読み取られ、変わると生成が失敗します。*レビュー済み*は、エンドポイントが設定そのものではなくレビューに基づくことを示します(ネイティブクライアントと、設定を特定のエンドポイントに変換するクライアント)。レビューしたコードが残っているかを生成時に確認します。「OpenAI 互換」の行は特定のエンドポイントを主張しません。", + implementedDefinition: "レジストリに登録されたクライアントです。エクスポートされる設定では、表のプロトコルは opencodex が生成する設定から読み取られ、変わると生成が失敗します。*レビュー済み*は、設定の自動検査ではなくコードレビューで確認したプロトコルです。レビューしたコードが残っているかを生成時に確認します。「OpenAI 互換」の行は特定のエンドポイントを主張しません。", testCoveredDefinition: "implemented であり、レビューで選んだこのクライアントのテストケースへのリンクがあります。生成時に確認するのはテストが存在し無効化されていないことだけです。何を検証しているかはテストを読んでください。", clientsHeading: "クライアント", columns: { client: "クライアント", native: "ネイティブ", configExport: "設定エクスポート", managed: "管理ファイル連携", protocol: "受信プロトコル", level: "サポートレベル", runtime: "実行確認", notes: "備考" }, @@ -299,17 +323,20 @@ export const LOCALES = { validateApply: "適用前にクライアント固有のチェックを実行し、拒否することがあります。", clientSelected: "クライアントがこの設定からエンドポイントを選びます(クライアントの文書化された動作に基づきレビュー済み)。", }, + gatewayHeading: "ゲートウェイクライアント", + gatewayIntro: "ダッシュボードで **ルート → Antigravity** を開くか(**ルート → クライアント** からも移動できます)、以下のコマンドを実行します。各コネクターはクライアントのゲートウェイを設定します。設定のエクスポートや管理対象ファイル連携は使用しません。agy CLI を起動する前に、案内されたシェルプロファイルを再読み込みしてください。", + gatewaySetup: "このマシンでセットアップ", endpointsHeading: "受信エンドポイント", endpointsIntro: "プロキシは次のプロトコルを受け付けます。上の表にないツールでも、いずれかのカスタムエンドポイントを設定できれば接続できます。", maintenanceHeading: "このページを最新に保つ", - maintenance: "このページは `scripts/generate-client-support-matrix.ts` がエクスポート・管理連携・ネイティブ連携のレジストリから生成します。クライアントを追加するには `scripts/client-support-matrix/metadata.ts` にエントリを追加し、`bun run docs:clients` を実行してください。コミット済みのページが古いと `bun run docs:clients:check` が失敗します。", + maintenance: "このページは `scripts/generate-client-support-matrix.ts` がエクスポート・管理連携・ネイティブ連携・ゲートウェイクライアントのレジストリから生成します。クライアントを追加するには `scripts/client-support-matrix/metadata.ts` にエントリを追加し、`bun run docs:clients` を実行してください。コミット済みのページが古いと `bun run docs:clients:check` が失敗します。", }, tr: { title: "İstemci desteği", description: "opencodex'in bağlandığı kodlama araçları, her birinin nasıl bağlandığı ve hangi protokolü kullandığı.", - intro: "opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yerel ağ geçididir. Bazı araçları yerel olarak yapılandırır; diğerleri için aracı yerel proxy'ye yönlendiren bir yapılandırma dosyasını dışa aktarır veya yönetir. Bu sayfa koddaki kayıtlardan üretilir; bu yüzden mevcut sürümün sunduğu şeyle birebir aynıdır.", + intro: "opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yerel ağ geçididir. Araçları yerel olarak yapılandırabilir, yapılandırma dosyası dışa aktarabilir veya yönetebilir, ya da özel bir ağ geçidi bağlayıcısı kullanabilir. Bu sayfa koddaki kayıtlardan üretilir; bu yüzden mevcut sürümün sunduğu şeyle birebir aynıdır.", levelsHeading: "Destek düzeyleri", - implementedDefinition: "istemci kayıtta yer alır. Dışa aktarılan yapılandırmalarda gösterilen protokol, opencodex'in ürettiği yapılandırmadan okunur ve değişirse üretim başarısız olur. *İncelendi* işareti, uç noktanın yapılandırmanın kendisinden değil bir incelemeden geldiğini belirtir (yerel istemciler ve bir ayarı belirli bir uç noktaya çeviren istemciler); üretici, incelenen kodun hâlâ yerinde olduğunu denetler. \"OpenAI uyumlu\" satırlar belirli bir uç nokta iddia etmez.", + implementedDefinition: "istemci kayıtta yer alır. Dışa aktarılan yapılandırmalarda gösterilen protokol, opencodex'in ürettiği yapılandırmadan okunur ve değişirse üretim başarısız olur. *İncelendi* işareti, protokolün otomatik yapılandırma denetiminden değil, kod incelemesinden geldiğini belirtir; üretici, incelenen kodun hâlâ yerinde olduğunu denetler. \"OpenAI uyumlu\" satırlar belirli bir uç nokta iddia etmez.", testCoveredDefinition: "implemented olmanın yanında, incelemede seçilmiş ve bu istemciyi çalıştıran bir test durumuna bağlantı verilir. Üretici yalnızca testin hâlâ var ve etkin olduğunu denetler; neyi doğruladığını görmek için testi okuyun.", clientsHeading: "İstemciler", columns: { client: "İstemci", native: "Yerel", configExport: "Yapılandırma dışa aktarımı", managed: "Yönetilen dosya entegrasyonu", protocol: "Gelen protokol", level: "Destek düzeyi", runtime: "Çalışırken doğrulandı", notes: "Notlar" }, @@ -332,10 +359,13 @@ export const LOCALES = { validateApply: "Uygulamadan önce istemciye özgü bir denetim çalışır ve reddedebilir.", clientSelected: "İstemci uç noktayı bu ayardan seçer (istemcinin belgelenmiş davranışına göre incelendi).", }, + gatewayHeading: "Ağ geçidi istemcileri", + gatewayIntro: "Panoda **Rota → Antigravity** bölümünü açın (**Rota → İstemciler** bölümünde de bağlantısı var) veya aşağıdaki komutları çalıştırın. Bu bağlayıcılar istemcinin ağ geçidini kurar; yapılandırma dışa aktarmaz veya yönetilen dosya entegrasyonu akışını kullanmaz. agy CLI’ını çalıştırmadan önce belirtilen kabuk profilini yeniden yükleyin.", + gatewaySetup: "Bu makinede kur", endpointsHeading: "Gelen uç noktalar", endpointsIntro: "Proxy bu protokolleri kabul eder. Yukarıda listelenmeyen bir araç, bunlardan biri için özel uç nokta ayarlamaya izin veriyorsa yine de bağlanabilir.", maintenanceHeading: "Bu sayfayı güncel tutmak", - maintenance: "Bu sayfa `scripts/generate-client-support-matrix.ts` tarafından dışa aktarma, yönetilen entegrasyon ve yerel entegrasyon kayıtlarından üretilir. İstemci eklemek için `scripts/client-support-matrix/metadata.ts` dosyasına kaydını ekleyip `bun run docs:clients` çalıştırın; işlenmiş sayfa eskidiğinde `bun run docs:clients:check` başarısız olur.", + maintenance: "Bu sayfa `scripts/generate-client-support-matrix.ts` tarafından dışa aktarma, yönetilen entegrasyon, yerel entegrasyon ve ağ geçidi istemcisi kayıtlarından üretilir. İstemci eklemek için `scripts/client-support-matrix/metadata.ts` dosyasına kaydını ekleyip `bun run docs:clients` çalıştırın; işlenmiş sayfa eskidiğinde `bun run docs:clients:check` başarısız olur.", }, } as const satisfies Record; diff --git a/scripts/client-support-matrix/metadata.ts b/scripts/client-support-matrix/metadata.ts index f1bf204f84f..504d78f948f 100644 --- a/scripts/client-support-matrix/metadata.ts +++ b/scripts/client-support-matrix/metadata.ts @@ -16,7 +16,7 @@ * Adding a client: add an entry here, then run `bun run docs:clients`. */ -export type MatrixProtocol = "responses" | "chat-completions" | "anthropic-messages" | "openai-compatible"; +export type MatrixProtocol = "responses" | "chat-completions" | "anthropic-messages" | "openai-compatible" | "gemini-compatible"; export interface ProtocolField { /** Dotted path into the built config; `*` matches any key or array index. */ @@ -253,3 +253,22 @@ export const NATIVE_CLIENT_METADATA: Readonly> = { + antigravity: { + label: "Antigravity (desktop)", + protocols: ["openai-compatible"], + anchors: [{ file: "src/integrations/gateway-clients/antigravity.ts", text: 'wireProtocol: "openai"' }], + test: { file: "tests/clients/gateway-clients.test.ts", title: "connect then disconnect restores a user file byte for byte, and re-connect is idempotent", mentions: ["GATEWAY_CLIENTS.antigravity"] }, + }, + agy: { + label: "agy (CLI)", + protocols: ["gemini-compatible"], + anchors: [ + { file: "src/integrations/gateway-clients/agy.ts", text: "AGY_LLM_GATEWAY_WIRE_PROTOCOL='genai'" }, + { file: "src/integrations/gateway-clients/agy.ts", text: "$env:AGY_LLM_GATEWAY_WIRE_PROTOCOL = 'genai'" }, + ], + test: { file: "tests/clients/gateway-clients.test.ts", title: "zsh profile created when none exists, then removed with its file on disconnect", mentions: ["GATEWAY_CLIENTS.agy"] }, + }, +}; diff --git a/scripts/generate-client-support-matrix.ts b/scripts/generate-client-support-matrix.ts index a5b4eb2ab37..87a9d3749d7 100644 --- a/scripts/generate-client-support-matrix.ts +++ b/scripts/generate-client-support-matrix.ts @@ -4,9 +4,10 @@ * bun scripts/generate-client-support-matrix.ts # write every locale page * bun scripts/generate-client-support-matrix.ts --check # exit 1 when a committed page is stale * - * Rows come from three registries: the export roster (EXPORT_CLIENT_IDS / EXPORT_CLIENTS), the + * Rows come from four registries: the export roster (EXPORT_CLIENT_IDS / EXPORT_CLIENTS), the * managed file integrations (INTEGRATION_CLIENTS) and the native owners (the - * NativeIntegrationClientId union, parsed from its declaration). Curated facts live in + * NativeIntegrationClientId union, parsed from its declaration), and the gateway clients + * (GATEWAY_CLIENT_IDS). Curated facts live in * scripts/client-support-matrix/metadata.ts and are re-checked against the code here, so a stale * claim fails generation instead of shipping. Rendering is pure; I/O stays in the CLI entry point. */ @@ -15,11 +16,14 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { EXPORT_CLIENT_IDS } from "../src/clients/client-ids"; import { EXPORT_CLIENTS, buildClientConfigText, type ExportContext, type ExportModel } from "../src/clients/config-export"; +import { GATEWAY_CLIENT_IDS } from "../src/integrations/gateway-clients"; import { INTEGRATION_CLIENTS } from "../src/integrations/registry"; +import { isGeminiGenerationPath } from "../src/server/gemini-native-paths"; import { CONFIGURABLE_JSON_BODY_ROUTES } from "../src/server/inbound-body-admission"; import type { OcxConfig } from "../src/types"; import { EXPORT_CLIENT_METADATA, + GATEWAY_CLIENT_METADATA, NATIVE_CLIENT_METADATA, type ExportClientMetadata, type MatrixProtocol, @@ -41,12 +45,15 @@ const PROTOCOL_NAMES: Record, strin responses: "Responses", "chat-completions": "Chat Completions", "anthropic-messages": "Anthropic Messages", + "gemini-compatible": "Gemini-compatible (GenAI)", }; -/** Inbound endpoint per protocol; each must be a route the proxy admits. */ +/** Inbound endpoints by protocol; each must be a route the proxy admits. */ const ENDPOINTS: ReadonlyArray<{ protocol: Exclude; route: string }> = [ { protocol: "responses", route: "/v1/responses" }, { protocol: "chat-completions", route: "/v1/chat/completions" }, { protocol: "anthropic-messages", route: "/v1/messages" }, + { protocol: "gemini-compatible", route: "/v1beta/models/{model}:generateContent" }, + { protocol: "gemini-compatible", route: "/v1beta/models/{model}:streamGenerateContent" }, ]; // Fixture catalog for protocol checks: one routed model, one native OpenAI model and one model on a @@ -83,6 +90,8 @@ export interface MatrixInputs { readRepoFile: (path: string) => string | undefined; exportMetadata: Readonly>; nativeMetadata: Readonly>; + gatewayIds: readonly string[]; + gatewayMetadata: Readonly>; /** Text of the runtime results file; undefined when the file is missing. */ runtimeResultsText: string | undefined; } @@ -104,6 +113,8 @@ export function defaultInputs(): MatrixInputs { }, exportMetadata: EXPORT_CLIENT_METADATA, nativeMetadata: NATIVE_CLIENT_METADATA, + gatewayIds: GATEWAY_CLIENT_IDS, + gatewayMetadata: GATEWAY_CLIENT_METADATA, runtimeResultsText: readRuntimeResultsText(), }; } @@ -115,6 +126,7 @@ export interface MatrixRow { label: string; native: boolean; configExport?: string; + gateway?: true; managed: boolean; protocols: ProtocolCell[]; curated: boolean; @@ -263,6 +275,16 @@ export function checkTestReference(owner: string, ref: TestReference, readRepoFi } } +function checkCuratedClient(id: string, meta: NativeClientMetadata, inputs: MatrixInputs, problems: string[]): void { + for (const anchor of meta.anchors) { + const source = inputs.readRepoFile(anchor.file); + if (source === undefined || !withoutComments(source).includes(anchor.text)) { + problems.push(`${id}: reviewed code ${JSON.stringify(anchor.text)} is no longer in ${anchor.file}; re-review the curated protocol`); + } + } + if (meta.test) checkTestReference(id, meta.test, inputs.readRepoFile, problems); +} + export function collectRows(inputs: MatrixInputs = defaultInputs()): MatrixRow[] { const problems: string[] = []; const exportIds = [...inputs.exportIds]; @@ -290,20 +312,14 @@ export function collectRows(inputs: MatrixInputs = defaultInputs()): MatrixRow[] } for (const { route } of ENDPOINTS) { - if (!inputs.inboundRoutes.has(route)) problems.push(`inbound route ${route} is no longer admitted; update ENDPOINTS`); + if (!inputs.inboundRoutes.has(route) && !isGeminiGenerationPath(route)) problems.push(`inbound route ${route} is no longer admitted; update ENDPOINTS`); } const rows: MatrixRow[] = []; // Metadata order is the display order; the parsed union decides membership. for (const id of Object.keys(inputs.nativeMetadata).filter(id => nativeIds.includes(id))) { const meta = inputs.nativeMetadata[id]!; - for (const anchor of meta.anchors) { - const source = inputs.readRepoFile(anchor.file); - if (source === undefined || !withoutComments(source).includes(anchor.text)) { - problems.push(`${id}: reviewed code ${JSON.stringify(anchor.text)} is no longer in ${anchor.file}; re-review the curated protocol`); - } - } - if (meta.test) checkTestReference(id, meta.test, inputs.readRepoFile, problems); + checkCuratedClient(id, meta, inputs, problems); rows.push({ id, label: meta.label, native: true, managed: false, protocols: meta.protocols.map(protocol => ({ protocol })), curated: true, test: meta.test, notes: ["native"], guide: meta.guide }); } @@ -338,6 +354,25 @@ export function collectRows(inputs: MatrixInputs = defaultInputs()): MatrixRow[] rows.push({ id, label: meta.label, native: false, configExport: spec.format.toUpperCase(), managed: integration !== undefined, protocols, curated: meta.clientSelected !== undefined, test: meta.test, notes, guide: meta.guide }); } + const documentedIds = new Set(rows.map(row => row.id)); + for (const id of Object.keys(inputs.gatewayMetadata)) { + if (!inputs.gatewayIds.includes(id)) problems.push(`${id}: gateway metadata for a client that is no longer in GATEWAY_CLIENT_IDS; remove it`); + } + for (const id of inputs.gatewayIds) { + if (documentedIds.has(id)) { + problems.push(`${id}: gateway client id also appears in another client row`); + continue; + } + documentedIds.add(id); + const meta = Object.hasOwn(inputs.gatewayMetadata, id) ? inputs.gatewayMetadata[id] : undefined; + if (!meta) { + problems.push(`${id}: gateway client without metadata; add it to GATEWAY_CLIENT_METADATA`); + continue; + } + checkCuratedClient(id, meta, inputs, problems); + rows.push({ id, label: meta.label, gateway: true, native: false, managed: false, protocols: meta.protocols.map(protocol => ({ protocol })), curated: true, test: meta.test, notes: [] }); + } + const runtime = parseRuntimeResults(inputs.runtimeResultsText, new Set(rows.map(row => row.id)), RUNTIME_RESULTS_FILE); problems.push(...runtime.problems); const selected = selectRuntimeResults(runtime.results); @@ -364,6 +399,10 @@ function protocolText(entry: ProtocolCell, strings: Strings): string { } /** Validated fields carry no Markdown-breaking characters, so they are rendered as written. */ +function levelText(row: MatrixRow, s: Strings): string { + return row.test ? `test-covered ([${s.testLink}](${REPO_BLOB}${row.test.file}))` : "implemented"; +} + function runtimeCell(entry: SelectedRuntimeResult | undefined, s: Strings): string { if (!entry) return "—"; const r = entry.result; @@ -396,13 +435,22 @@ export function renderPage(rows: readonly MatrixRow[], locale: MatrixLocale): st `| ${c.client} | ${c.native} | ${c.configExport} | ${c.managed} | ${c.protocol} | ${c.level} | ${c.runtime} | ${c.notes} |`, "| --- | --- | --- | --- | --- | --- | --- | --- |", ]; - for (const row of rows) { + for (const row of rows.filter(row => !row.gateway)) { const protocol = row.protocols.map(entry => protocolText(entry, s)).join("; ") + (row.curated ? ` (${s.curated})` : ""); - const level = row.test ? `test-covered ([${s.testLink}](${REPO_BLOB}${row.test.file}))` : "implemented"; + const level = levelText(row, s); const separator = locale === "zh-cn" || locale === "zh-tw" || locale === "ja" ? "" : " "; const notes = row.notes.map(key => s.notes[key]).join(separator) + (row.guide ? ` [${s.guideLink}](${localePrefix(locale)}${row.guide}/)` : ""); lines.push(`| ${cell(row.label)} | ${row.native ? s.yes : "—"} | ${row.configExport ?? "—"} | ${row.managed ? s.yes : "—"} | ${cell(protocol)} | ${level} | ${runtimeCell(row.runtime, s)} | ${cell(notes)} |`); } + const gatewayRows = rows.filter(row => row.gateway); + if (gatewayRows.length > 0) { + lines.push("", `## ${s.gatewayHeading}`, "", s.gatewayIntro, "", + `| ${c.client} | ${c.protocol} | ${c.level} | ${c.runtime} | ${s.gatewaySetup} |`, "| --- | --- | --- | --- | --- |"); + for (const row of gatewayRows) { + const protocol = row.protocols.map(entry => protocolText(entry, s)).join("; ") + ` (${s.curated})`; + lines.push(`| ${cell(row.label)} | ${cell(protocol)} | ${levelText(row, s)} | ${runtimeCell(row.runtime, s)} | \`ocx connect ${row.id}\` |`); + } + } lines.push("", `## ${s.endpointsHeading}`, "", s.endpointsIntro, ""); for (const { protocol, route } of ENDPOINTS) lines.push(`- \`POST ${route}\`: ${PROTOCOL_NAMES[protocol]}`); lines.push("", `## ${s.maintenanceHeading}`, "", s.maintenance, ""); diff --git a/structure/clients/antigravity-gateway.md b/structure/clients/antigravity-gateway.md index 14443de3471..0e7f508c6be 100644 --- a/structure/clients/antigravity-gateway.md +++ b/structure/clients/antigravity-gateway.md @@ -108,6 +108,14 @@ credential. An override set only in the Antigravity process is invisible to Open ## Surfaces +Route → Clients includes a separate read-only Gateway clients section. It links both clients to +Route → Antigravity, and reads the gateway status route (no file writes, bulk disable or install +counts). Missing, malformed or failed status is unknown, and so are an unreadable `admin_settings.json` and a +disconnected client whose settings file cannot be parsed unless a confirmed override applies. A confirmed override takes priority over an unknown or connection badge. +The exception is `env-gateway` on a connected agy: its shell function sets those variables itself. +The badges describe configuration, not whether the app is installed or running. They use the +Route card state styling, while the text distinguishes an override from ordinary drift. + `src/server/management/gateway-client-routes.ts` serves `GET /api/gateway-clients` and `POST /api/gateway-clients/{id}/connect|disconnect`; `handleIntegrationRoutes` in `src/server/management/integration-routes.ts` loads it on demand for that prefix, so diff --git a/structure/clients/client-support-matrix.md b/structure/clients/client-support-matrix.md index 9da385fbb24..6b8ed655010 100644 --- a/structure/clients/client-support-matrix.md +++ b/structure/clients/client-support-matrix.md @@ -2,19 +2,21 @@ The public client support page (`docs-site/src/content/docs/reference/client-support.md` and its copy under each docs locale) is generated, never edited by hand. It is the one place users read which coding tools -opencodex connects to natively, which it exports or manages a config file for, and which inbound -protocol each speaks. +opencodex connects to natively, which it exports or manages a config file for, which it sets up +through a separate gateway connector, and which inbound protocol each speaks. ## Sources -`scripts/generate-client-support-matrix.ts` builds the rows from three registries: +`scripts/generate-client-support-matrix.ts` builds the rows from four registries: - the export roster, `EXPORT_CLIENT_IDS` and `EXPORT_CLIENTS` in `src/clients/`; - the managed file integrations, `INTEGRATION_CLIENTS` in `src/integrations/registry.ts`, which must stay a subset of the export roster (an integration-only id fails generation instead of vanishing); - the native owners, parsed from the one-line `NativeIntegrationClientId` union in `src/server/management/native-integration-routes.ts`. The scripts are outside the typecheck, so the - parse refuses any other declaration shape and compares the members with the metadata both ways. + parse refuses any other declaration shape and compares the members with the metadata both ways; +- the gateway connectors, `GATEWAY_CLIENT_IDS` in `src/integrations/gateway-clients/index.ts`. They + appear in a separate table with their `ocx connect` commands, never as managed/native/export rows. ## Curated facts and how they stay true @@ -28,7 +30,7 @@ fields, reviewed claims and linked tests. Generation fails when one no longer ho A field marked `perModel` (OpenCode's per-model `provider.npm` / `package` overrides) is the one exception to "every matched entry carries it": entries may inherit the provider default, but the fixture must contain at least one explicit override, which the direct-Chat fixture model provides. -- Rows whose client picks the endpoint (ZCode, Raycast) and native rows are curated. Each keeps a +- Rows whose client picks the endpoint (ZCode, Raycast) and native/gateway rows are curated. Each keeps a source anchor; the client-selected rows also pin the exporter file's sha256, so any edit asks for a fresh review. - `test-covered` links a reviewed test case. The generator checks that the case exists once, names diff --git a/tests/ci-workflows/client-support-matrix.test.ts b/tests/ci-workflows/client-support-matrix.test.ts index 9acce499dff..03c0b974e26 100644 --- a/tests/ci-workflows/client-support-matrix.test.ts +++ b/tests/ci-workflows/client-support-matrix.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { EXPORT_CLIENT_IDS } from "../../src/clients/client-ids"; +import { GATEWAY_CLIENT_IDS } from "../../src/integrations/gateway-clients"; import { INTEGRATION_CLIENTS } from "../../src/integrations/registry"; import { MatrixError, @@ -11,7 +12,7 @@ import { renderAll, type MatrixInputs, } from "../../scripts/generate-client-support-matrix"; -import { EXPORT_CLIENT_METADATA, NATIVE_CLIENT_METADATA } from "../../scripts/client-support-matrix/metadata"; +import { EXPORT_CLIENT_METADATA, GATEWAY_CLIENT_METADATA, NATIVE_CLIENT_METADATA } from "../../scripts/client-support-matrix/metadata"; import { LOCALES } from "../../scripts/client-support-matrix/locales"; import { repoPath } from "../helpers/repo-root"; @@ -64,12 +65,39 @@ describe("client support matrix", () => { } }); - test("rows cover the export roster, the managed integrations and the native union", () => { + test("rows cover the export roster, managed integrations, the native union and gateway connectors", () => { const rows = collectRows(); const nativeIds = parseNativeRoster(readFileSync(repoPath(NATIVE_ROSTER_FILE), "utf8")); - expect(rows.map(row => row.id).sort()).toEqual([...EXPORT_CLIENT_IDS, ...nativeIds].sort()); + expect(rows.map(row => row.id).sort()).toEqual([...EXPORT_CLIENT_IDS, ...nativeIds, ...GATEWAY_CLIENT_IDS].sort()); expect(rows.filter(row => row.managed).map(row => row.id).sort()).toEqual(Object.keys(INTEGRATION_CLIENTS).sort()); expect(rows.filter(row => row.native).map(row => row.id).sort()).toEqual([...nativeIds].sort()); + expect(rows.filter(row => row.gateway).map(row => row.id).sort()).toEqual([...GATEWAY_CLIENT_IDS].sort()); + expect(rows.filter(row => row.gateway && (row.managed || row.native || row.configExport))).toEqual([]); + }); + + test("gateway rows render in their own section with setup commands, not as runtime-verified", () => { + for (const [path, page] of Object.entries(renderAll())) { + const tableRows = page.split("\n").filter(line => /^\| (Antigravity \(desktop\)|agy \(CLI\)) /.test(line)); + expect(tableRows, path).toHaveLength(2); + expect(tableRows[0], path).toContain("| — | \`ocx connect antigravity\` |"); + expect(tableRows[1], path).toContain("| — | \`ocx connect agy\` |"); + const locale = Object.values(LOCALES).find(candidate => page.includes(`## ${candidate.gatewayHeading}\n`)); + expect(locale, path).toBeDefined(); + const heading = page.indexOf(`## ${locale!.gatewayHeading}\n`); + expect(page.indexOf(tableRows[0]!)).toBeGreaterThan(heading); + } + }); + + test("gateway roster and curated protocol changes do not silently ship stale docs", () => { + expect(problemsWith({ gatewayIds: [...GATEWAY_CLIENT_IDS, "newgateway"] })) + .toContain("newgateway: gateway client without metadata; add it to GATEWAY_CLIENT_METADATA"); + expect(problemsWith({ gatewayIds: ["agy"] })) + .toContain("antigravity: gateway metadata for a client that is no longer in GATEWAY_CLIENT_IDS; remove it"); + expect(problemsWith({ gatewayIds: [...GATEWAY_CLIENT_IDS, "grok"] })) + .toContain("grok: gateway client id also appears in another client row"); + const anchor = GATEWAY_CLIENT_METADATA.agy!.anchors[0]!; + const changed = problemsWith({ readRepoFile: withFile(anchor.file, text => text.replace(anchor.text, "replacement")) }); + expect(changed.some(problem => problem.startsWith("agy: reviewed code"))).toBe(true); }); test("a new export client without metadata fails with its id", () => { diff --git a/tests/ci-workflows/client-support-runtime.test.ts b/tests/ci-workflows/client-support-runtime.test.ts index b4af057dc9a..43067d674e8 100644 --- a/tests/ci-workflows/client-support-runtime.test.ts +++ b/tests/ci-workflows/client-support-runtime.test.ts @@ -31,9 +31,20 @@ function problems(text: string | undefined, ids = new Set(["codex", "qoder-cn"]) } /** The "Runtime verified" cell of every table row on a rendered page. */ -function runtimeCells(page: string): string[] { - return page.split("\n").filter(line => line.startsWith("| ") && !line.startsWith("| ---")) - .slice(1).map(line => line.split(" | ")[6]!); +function runtimeCells(page: string, runtimeHeading: string): string[] { + let column = -1; + return page.split("\n").flatMap(line => { + if (!line.startsWith("| ")) return []; + const cells = line.split(" | "); + if (cells.every(cell => cell.replace(/^\| | \|$/g, "") === "---")) return []; + const heading = cells.indexOf(runtimeHeading); + if (heading >= 0) { + column = heading; + return []; + } + if (column < 0 || cells[column] === undefined) throw new Error(`missing runtime column: ${line}`); + return [cells[column]]; + }); } const TEXT_RULE = (field: string) => `data.json results[0].${field} may only use letters, digits, spaces and . , : ; / + ' ! ? # % = -`; @@ -48,14 +59,15 @@ describe("client support runtime results", () => { for (const locale of LOCALE_IDS) { const page = renderPage(rows, locale); expect(page).toContain(LOCALES[locale].runtimeDefinition); - expect(new Set(runtimeCells(page))).toEqual(new Set(["—"])); + expect(new Set(runtimeCells(page, LOCALES[locale].columns.runtime))).toEqual(new Set(["—"])); } }); - test("a result renders product, both versions, scenario, date and evidence on native and export rows", () => { + test("a result renders product, both versions, scenario, date and evidence on native, export and gateway rows", () => { const rows = rowsWith(fileWith([ result(), result({ client: "qoder-cn", product: "Qoder CN CLI", clientVersion: "1.1.70", scenario: "single chat turn" }), + result({ client: "agy", product: "agy CLI", clientVersion: "1.2.15", scenario: "gateway request with one tool call" }), ])); const codex = rows.find(row => row.id === "codex")!; const qoderCn = rows.find(row => row.id === "qoder-cn")!; @@ -66,6 +78,7 @@ describe("client support runtime results", () => { const s = LOCALES[locale]; expect(page).toContain(`Codex CLI 0.150.0 + opencodex 2.40.0: streamed reply with one tool call (2026-10-20, [${s.evidenceLink}](https://github.com/lidge-jun/opencodex/pull/1))`); expect(page).toContain("Qoder CN CLI 1.1.70 + opencodex 2.40.0: single chat turn (2026-10-20,"); + expect(page.split("\n").find(line => line.startsWith("| agy (CLI) |"))).toContain("agy CLI 1.2.15 + opencodex 2.40.0: gateway request with one tool call (2026-10-20,"); // The support level is independent of the runtime column: Qoder CN stays implemented. expect(page.split("\n").find(line => line.startsWith("| Qoder CN |"))).toContain("| implemented |"); } diff --git a/tests/clients/gateway-clients.test.ts b/tests/clients/gateway-clients.test.ts index 09166a51b90..0e802f644f4 100644 --- a/tests/clients/gateway-clients.test.ts +++ b/tests/clients/gateway-clients.test.ts @@ -199,6 +199,7 @@ describe("agy connector", () => { expect(agy.connect(ctx, target).ok).toBe(true); const zshrc = join(ctx.home, ".zshrc"); expect(read(zshrc)).toContain("agy() { AGY_LLM_GATEWAY_URL='http://127.0.0.1:10100'"); + expect(read(zshrc)).toContain("AGY_LLM_GATEWAY_WIRE_PROTOCOL='genai'"); expect(agy.status(ctx, target).state).toBe("connected"); expect(agy.disconnect(ctx).restore).toBe("exact"); expect(existsSync(zshrc)).toBe(false); From f7e92b2d2f2c265c75e0eb4135561be8b7ed7b45 Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:30:43 +0900 Subject: [PATCH 27/50] fix(openai-chat): read Responses-style usage aliases from Chat gateways (#9314) * fix(openai-chat): read Responses-style usage aliases from Chat gateways (#9306) Some Chat Completions gateways (CoreMind) report usage as input_tokens / output_tokens with input/output_tokens_details, which recorded zero tokens and no tok/s. usageFromOpenAIChat now falls back to those aliases only when the Chat field carries no number, so a reported Chat zero still wins. * docs(structure): record the Chat usage alias fallback (#9306) --- src/adapters/openai-chat/response-events.ts | 38 +++++++++++--- structure/providers/chat-compat.md | 2 + tests/adapters/adapter-usage.test.ts | 56 +++++++++++++++++++++ 3 files changed, 90 insertions(+), 6 deletions(-) diff --git a/src/adapters/openai-chat/response-events.ts b/src/adapters/openai-chat/response-events.ts index ae0d53b019e..1f24522f3cd 100644 --- a/src/adapters/openai-chat/response-events.ts +++ b/src/adapters/openai-chat/response-events.ts @@ -223,14 +223,40 @@ export function unnamedToolCallEvent(usage?: OcxUsage): Extract)[key] : undefined; +} + +/** The Chat value when it is a number (zero included), else a numeric Responses-style alias. */ +function chatOrAlias(chat: unknown, alias: unknown): number | undefined { + if (typeof chat === "number") return chat; + return typeof alias === "number" ? alias : undefined; +} + +/** Details keep their historical pass-through of any defined Chat value when no number exists. */ +function chatDetailOrAlias(chat: unknown, alias: unknown): number | undefined { + return chatOrAlias(chat, alias) ?? (chat !== undefined ? chat as number : undefined); +} + +/** + * Some Chat Completions gateways report usage with Responses field names (`input_tokens`, + * `output_tokens`, and their `*_details`), which used to record zero tokens (#9306). The + * standard Chat field wins whenever it carries a number, so a reported zero is kept. + */ export function usageFromOpenAIChat(usage: Record | undefined): OcxUsage | undefined { if (!usage) return undefined; - const promptDetails = usage.prompt_tokens_details as Record | undefined; - const completionDetails = usage.completion_tokens_details as Record | undefined; + const cached = chatDetailOrAlias( + usageDetail(usage.prompt_tokens_details, "cached_tokens"), + usageDetail(usage.input_tokens_details, "cached_tokens"), + ); + const reasoning = chatDetailOrAlias( + usageDetail(usage.completion_tokens_details, "reasoning_tokens"), + usageDetail(usage.output_tokens_details, "reasoning_tokens"), + ); return { - inputTokens: typeof usage.prompt_tokens === "number" ? usage.prompt_tokens : 0, - outputTokens: typeof usage.completion_tokens === "number" ? usage.completion_tokens : 0, - ...(promptDetails?.cached_tokens !== undefined ? { cachedInputTokens: promptDetails.cached_tokens } : {}), - ...(completionDetails?.reasoning_tokens !== undefined ? { reasoningOutputTokens: completionDetails.reasoning_tokens } : {}), + inputTokens: chatOrAlias(usage.prompt_tokens, usage.input_tokens) ?? 0, + outputTokens: chatOrAlias(usage.completion_tokens, usage.output_tokens) ?? 0, + ...(cached !== undefined ? { cachedInputTokens: cached } : {}), + ...(reasoning !== undefined ? { reasoningOutputTokens: reasoning } : {}), }; } diff --git a/structure/providers/chat-compat.md b/structure/providers/chat-compat.md index d132ac8bb24..3a33d414c23 100644 --- a/structure/providers/chat-compat.md +++ b/structure/providers/chat-compat.md @@ -51,6 +51,8 @@ The [canonical Mistral wire policy](mistral-chat.md) also covers native Chat req On that same host, `src/adapters/openai-chat/messages.ts` reconstructs historical thinking as native `content` chunks before assistant text, for every hosted model family. An explicit `preserveReasoningContentModels` list, including `[]`, still controls enrollment; the default preserves supplied thinking. The shared prompt projection counts that thinking. Replay can recover actual text from the existing scoped tool-call cache, but never invents placeholders or forwards generic IR signatures. Original chunk metadata and exact chunk boundaries are not retained by this text-only reconstruction. Native Chat passthrough and other destinations retain their existing behavior. Tests: `tests/adapters/openai/openai-chat-mistral-content.test.ts`; byte budgets retain their existing limits. +Usage normalization (`usageFromOpenAIChat` in `src/adapters/openai-chat/response-events.ts`, shared by the streaming and buffered paths) reads the Chat fields first and falls back to Responses-style aliases some gateways send (#9306): `prompt_tokens` ← `input_tokens`, `completion_tokens` ← `output_tokens`, `prompt_tokens_details.cached_tokens` ← `input_tokens_details.cached_tokens`, `completion_tokens_details.reasoning_tokens` ← `output_tokens_details.reasoning_tokens`. A numeric Chat field always wins, zero included; an alias is read only when the Chat field carries no number. Tests: `tests/adapters/adapter-usage.test.ts`. + ### Inline think-tag recovery A gateway that serves a thinking model without a server-side reasoning parser returns the chain diff --git a/tests/adapters/adapter-usage.test.ts b/tests/adapters/adapter-usage.test.ts index ef119014978..76aa9a6b135 100644 --- a/tests/adapters/adapter-usage.test.ts +++ b/tests/adapters/adapter-usage.test.ts @@ -53,6 +53,62 @@ describe("adapter reasoning and usage details", () => { ]); }); + // #9306: some Chat Completions gateways report usage with Responses field names. + test("OpenAI-compatible non-streaming reads Responses-style usage aliases", async () => { + const adapter = createOpenAIChatAdapter(provider); + const events = await adapter.parseResponse?.(new Response(JSON.stringify({ + choices: [{ message: { content: "OK" } }], + usage: { + input_tokens: 35, + output_tokens: 12, + total_tokens: 47, + input_tokens_details: { cached_tokens: 8 }, + output_tokens_details: { reasoning_tokens: 4 }, + }, + }))); + + expect(events?.at(-1)).toEqual({ + type: "done", + usage: { inputTokens: 35, outputTokens: 12, cachedInputTokens: 8, reasoningOutputTokens: 4 }, + }); + }); + + test("OpenAI-compatible streaming reads Responses-style usage from a terminal usage chunk", async () => { + const adapter = createOpenAIChatAdapter(provider); + const response = new Response([ + "data: {\"choices\":[{\"delta\":{\"content\":\"OK\"}}]}\n\n", + "data: {\"choices\":[],\"usage\":{\"input_tokens\":48,\"output_tokens\":384,\"total_tokens\":432}}\n\n", + "data: [DONE]\n\n", + ].join("")); + + const events = []; + for await (const event of adapter.parseStream(response)) events.push(event); + + expect(events.at(-1)).toEqual({ type: "done", usage: { inputTokens: 48, outputTokens: 384 } }); + }); + + test("Chat Completions usage fields win over Responses aliases, zero included", async () => { + const adapter = createOpenAIChatAdapter(provider); + const events = await adapter.parseResponse?.(new Response(JSON.stringify({ + choices: [{ message: { content: "OK" } }], + usage: { + prompt_tokens: 0, + completion_tokens: 7, + input_tokens: 99, + output_tokens: 99, + prompt_tokens_details: { cached_tokens: 0 }, + input_tokens_details: { cached_tokens: 50 }, + completion_tokens_details: { reasoning_tokens: 2 }, + output_tokens_details: { reasoning_tokens: 60 }, + }, + }))); + + expect(events?.at(-1)).toEqual({ + type: "done", + usage: { inputTokens: 0, outputTokens: 7, cachedInputTokens: 0, reasoningOutputTokens: 2 }, + }); + }); + test("OpenAI-compatible non-OpenAI providers receive the tool catalog nudge", async () => { const adapter = createOpenAIChatAdapter(provider); const request = await adapter.buildRequest({ From 1113cade58dfd21a029cbaf19de47172a874710a Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:30:50 +0900 Subject: [PATCH 28/50] fix(opencode): write the loopback placeholder apiKey from serving-config exports (#9318) * fix(opencode): write the loopback placeholder apiKey whenever admission is not required (#9293) A default loopback bind (listener unset) still exported {env:OPENCODEX_OPENCODE_API_KEY}. OpenCode resolves an unset reference to an empty string and refuses the Responses provider with "Missing auth credential: apiKey" before sending. opencodeProviderConnection now writes the non-secret opencodex-loopback placeholder whenever shouldInjectApiAuthHeader is false and the base URL is loopback, matching Pi, Kilo and ZCode. Authenticated binds keep the x-opencodex-api-key header with the env reference. * fix(opencode): assert the keyless destination only from the serving config (#9293) Review found that inferring the placeholder inside opencodeProviderConnection also changed `ocx export --client opencode` and the `ocx opencode` launcher. Those pair a probed endpoint with saved local config, which can describe a different (authenticated or SSH-forwarded) listener. That is the #9069 caveat. opencodeProviderConnection is back to placeholder only on keylessInference. The two callers that build the export from the serving process's own config, exportContextOf (managed integration and refresh) and /api/client-config, now set keylessInference whenever shouldInjectApiAuthHeader is false: a plain loopback bind as well as the enabled keyless listener. The CLI export and the launcher keep the env reference. --- src/clients/config-export.ts | 6 ++++-- src/integrations/state.ts | 9 +++++--- src/server/management/model-routes.ts | 5 +++-- structure/clients/integrations.md | 2 +- tests/clients/integrations-writer.test.ts | 14 ++++++++----- tests/clients/opencode-kilo-refresh.test.ts | 3 ++- .../management-client-config-route.test.ts | 21 +++++++++++++++++++ 7 files changed, 46 insertions(+), 14 deletions(-) diff --git a/src/clients/config-export.ts b/src/clients/config-export.ts index 2124669439d..607acb5e468 100644 --- a/src/clients/config-export.ts +++ b/src/clients/config-export.ts @@ -761,8 +761,10 @@ function opencodeProviderConnection( return options; } // OpenCode refuses an empty key before it sends anything, so an unset reference fails even - // against a listener that never reads one (#9069). Only a caller that selected the keyless - // listener may say so; everything else keeps the reference. + // against a listener that never reads one (#9069, #9293). Only a caller that resolved the + // destination from the serving process's own admission policy may say so (the managed + // integration and `/api/client-config`); a CLI export or launcher pairing a probed endpoint + // with saved config keeps the reference, because those two can describe different listeners. options.apiKey = keylessInference ? LOOPBACK_API_KEY_PLACEHOLDER : OPENCODE_API_KEY_ENV_REF; return options; } diff --git a/src/integrations/state.ts b/src/integrations/state.ts index a738bb197e5..1ef4510e486 100644 --- a/src/integrations/state.ts +++ b/src/integrations/state.ts @@ -15,6 +15,7 @@ import { qoderLegacyCatalogCollision } from "../clients/config-export/qoder"; import { resolveModelNames, type ExportModelNames } from "../clients/config-export/model-names"; import { namedExportContext } from "../clients/config-export/alias-selectors"; import type { ConfigFormat } from "../clients/config-export"; +import { shouldInjectApiAuthHeader } from "../codex/loopback-target"; import type { OcxConfig } from "../types"; import { PARSE_FAILED, loadTarget, parseConfig, type IntegrationIO } from "./config-io"; import { SNAPSHOT_RETENTION } from "./journal"; @@ -521,7 +522,8 @@ export function exportContextOf(input: { droidReasoningDefaults?: Record; document?: unknown; }): { baseUrl: string; models: readonly ExportModel[]; config: OcxConfig; keylessInference?: boolean; droidReasoningDefaults?: Record; document?: unknown } { - const keylessListener = input.config.unauthenticatedLoopbackListener?.enabled === true; + // No admission on this bind: the enabled keyless listener, or a plain loopback bind (#9293). + const keylessDestination = !shouldInjectApiAuthHeader(input.config); return { /* * Composed through the SAME helper `ocx export` uses. Interpolating the @@ -535,8 +537,9 @@ export function exportContextOf(input: { baseUrl: opencodeProxyBaseUrl(input.port, input.config.hostname, input.config), models: input.models, config: input.config, - // `opencodeProxyBaseUrl` above dials the keyless listener whenever it is enabled. - ...(keylessListener ? { keylessInference: true } : {}), + // `opencodeProxyBaseUrl` above dials the keyless listener whenever it is enabled, and + // otherwise this loopback bind, which checks no admission key either. + ...(keylessDestination ? { keylessInference: true } : {}), ...(input.droidReasoningDefaults === undefined ? {} : { droidReasoningDefaults: input.droidReasoningDefaults }), // Forwarded only when the caller parsed a target: a client that resolves // between two document roots (Command Code) needs the bytes on disk. diff --git a/src/server/management/model-routes.ts b/src/server/management/model-routes.ts index e5061e7e6cb..06b54ef3f26 100644 --- a/src/server/management/model-routes.ts +++ b/src/server/management/model-routes.ts @@ -699,8 +699,9 @@ export async function handleModelRoutes(ctx: ManagementContext): Promise { expect(readIntegrationState(request)).toMatchObject({ state: "current" }); }); - test("an authenticated bind keeps the admission header and a loopback bind keeps the reference", () => { + test("an authenticated bind keeps the admission header and a default loopback bind gets the placeholder (#9293)", () => { const authenticatedPath = installOpencode(); const authenticated = input({ clientId: "opencode", config: { ...CONFIG, hostname: "100.64.0.10" } as OcxConfig }); expect(applyIntegration(authenticated).ok).toBe(true); @@ -542,12 +542,16 @@ describe("apply", () => { expect(remote.providers.opencodex.headers).toEqual({ "x-opencodex-api-key": "{env:OPENCODEX_OPENCODE_API_KEY}" }); expect(disableIntegration(authenticated).ok).toBe(true); - // Without the listener, a loopback base URL does not prove a keyless destination. + // A default loopback bind does not require admission (`shouldInjectApiAuthHeader` is false), so + // OpenCode gets the non-secret placeholder instead of an unset reference it refuses (#9293). expect(applyIntegration(input({ clientId: "opencode" })).ok).toBe(true); const loopback = read(authenticatedPath); - expect(loopback.provider.opencodex.options.apiKey).toBe("{env:OPENCODEX_OPENCODE_API_KEY}"); - expect(loopback.providers.opencodex.settings.apiKey).toBe("{env:OPENCODEX_OPENCODE_API_KEY}"); - expect(exportContextOf({ models: MODELS, config: CONFIG, port: 10100 }).keylessInference).toBeUndefined(); + expect(loopback.provider.opencodex.options.apiKey).toBe("opencodex-loopback"); + expect(loopback.providers.opencodex.settings.apiKey).toBe("opencodex-loopback"); + expect(loopback.provider.opencodex.options.headers).toBeUndefined(); + expect(loopback.providers.opencodex.headers).toBeUndefined(); + expect(exportContextOf({ models: MODELS, config: CONFIG, port: 10100 }).keylessInference).toBe(true); + expect(exportContextOf({ models: MODELS, config: { ...CONFIG, hostname: "100.64.0.10" } as OcxConfig, port: 10100 }).keylessInference).toBeUndefined(); }); }); diff --git a/tests/clients/opencode-kilo-refresh.test.ts b/tests/clients/opencode-kilo-refresh.test.ts index d3997054b34..78e2e4738f9 100644 --- a/tests/clients/opencode-kilo-refresh.test.ts +++ b/tests/clients/opencode-kilo-refresh.test.ts @@ -47,7 +47,8 @@ describe("OpenCode and Kilo owned model configuration convergence", () => { return JSON.parse(readFileSync(INTEGRATION_CLIENTS[client].configPath({}, home), "utf8")); } function expected(client: typeof clients[number], roster = models) { - return buildClientContribution(client, { config, baseUrl: "http://127.0.0.1:10100/v1", models: roster }); + // The managed context asserts a keyless destination on this loopback bind (#9293). + return buildClientContribution(client, { config, baseUrl: "http://127.0.0.1:10100/v1", models: roster, keylessInference: true }); } test("unowned configs are untouched and do not load models", async () => { diff --git a/tests/server/management-client-config-route.test.ts b/tests/server/management-client-config-route.test.ts index d7676b43eb9..5751ff1365b 100644 --- a/tests/server/management-client-config-route.test.ts +++ b/tests/server/management-client-config-route.test.ts @@ -338,6 +338,25 @@ describe("GET /api/client-config", () => { .toBe("http://127.0.0.1:10237/v1"); }); + test("OpenCode export writes the placeholder apiKey on a default loopback bind and the env header elsewhere (#9293)", async () => { + type Connection = { apiKey?: string; headers?: Record }; + const read = async (config: OcxConfig) => { + const body = await (await clientConfigApi(config, "?client=opencode")).json() as ClientConfigEnvelope; + const document = body.config as { provider: { opencodex: { options: Connection } }; providers: { opencodex: { settings: Connection; headers?: Record } } }; + return { v1: document.provider.opencodex.options, v2: document.providers.opencodex }; + }; + // The serving bind checks no admission key, so OpenCode needs a nonempty non-secret key. + const loopback = await read(baseConfig()); + expect(loopback.v1.apiKey).toBe(LOOPBACK_API_KEY_PLACEHOLDER); + expect(loopback.v1.headers).toBeUndefined(); + expect(loopback.v2.settings.apiKey).toBe(LOOPBACK_API_KEY_PLACEHOLDER); + expect(loopback.v2.headers).toBeUndefined(); + // An authenticated bind keeps admission on the env-reference header. + const remote = await read(baseConfig({ hostname: "0.0.0.0" })); + expect(remote.v1.headers).toEqual({ "x-opencodex-api-key": "{env:OPENCODEX_OPENCODE_API_KEY}" }); + expect(remote.v2.headers).toEqual({ "x-opencodex-api-key": "{env:OPENCODEX_OPENCODE_API_KEY}" }); + }); + test("Raycast export uses the main port for an ordinary loopback bind", async () => { const response = await clientConfigApi(baseConfig(), "?client=raycast"); expect(response.status).toBe(200); @@ -365,6 +384,8 @@ describe("GET /api/client-config", () => { baseUrl: "http://127.0.0.1:10100/v1", models: rows.filter(row => !row.disabled).map(toExportModel), config, + // The route asserts a keyless destination on a loopback bind (#9293). + keylessInference: true, }); expect(body.config).toEqual(expected as Record); expect(JSON.stringify(body.config)).toBe(JSON.stringify(expected)); From 85b9c58e33d182ac62d7f4c2ff3846fac2ce65b7 Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:30:58 +0900 Subject: [PATCH 29/50] fix(link): prove macOS tunnel ownership from the kernel TCP table (#9319) * fix(link): prove macOS tunnel ownership from the kernel TCP table (#9272) The Darwin branch of inspectIpv4LoopbackListener ran lsof, which blocks on filesystem metadata while a removable volume is busy. During USB writes it missed the 2 s tunnel-owner deadline, so the Child answered 503 home_unreachable. It now reads /usr/sbin/netstat -anv -p tcp, finds the owner column by header (process:pid, or pid on older releases), counts fixed trailing columns so process names with spaces parse, and accepts only an exact 127.0.0.1 (or IPv4-mapped) LISTEN row. The 2 s deadline is unchanged. Conflicting owners and an empty valid table are a mismatch; an unrecognized table or a matching row without a PID is a lookup_error. * fix(link): reject reshaped netstat rows before reading the owner PID (#9272) Review hardening: every column after the owner must be numeric or hex and a row may not be shorter than the header, so a malformed row cannot let a spaced process-name fragment such as x:42 stand in for the PID. Such a row is a lookup_error. --- src/server/port-reclaim.ts | 53 +++++++++++++++--- structure/remote-link.md | 2 +- tests/server/port-reclaim.test.ts | 90 +++++++++++++++++++++++-------- 3 files changed, 115 insertions(+), 30 deletions(-) diff --git a/src/server/port-reclaim.ts b/src/server/port-reclaim.ts index 58da4700651..cc34ca77e45 100644 --- a/src/server/port-reclaim.ts +++ b/src/server/port-reclaim.ts @@ -447,6 +447,47 @@ async function runOwnerLookup(file: string, args: string[], timeoutMs: number): return stdout; } +/** + * Owners of the exact `127.0.0.1:port` (or IPv4-mapped) LISTEN socket in macOS + * `netstat -anv -p tcp`, or null when the table cannot prove ownership (#9272). + * + * The kernel table replaces `lsof`, which stalls on filesystem metadata while a removable + * volume is busy and pushed the tunnel-owner check past its deadline. The owner column is + * found by header (`process:pid` on current macOS, `pid` on older releases) and read by + * counting the fixed trailing columns from the end, because process names may contain + * spaces. Wildcard binds and other addresses never match; an unrecognized table or a + * matching row without a positive PID is a lookup failure rather than a mismatch. + */ +export function parseDarwinIpv4LoopbackListenPids(output: string, port: number): number[] | null { + const lines = output.split(/\r?\n/); + const headerIndex = lines.findIndex(line => /^\s*Proto\s/.test(line)); + if (headerIndex < 0) return null; + const header = lines[headerIndex]!.replace("Local Address", "Local_Address") + .replace("Foreign Address", "Foreign_Address").trim().split(/\s+/); + const ownerColumn = header.findIndex(name => name === "process:pid" || name === "pid"); + if (ownerColumn < 0 || header[3] !== "Local_Address" || header[5] !== "(state)") return null; + const plainPid = header[ownerColumn] === "pid"; + const trailing = header.length - 1 - ownerColumn; + const wanted = new Set([`127.0.0.1.${port}`, `::ffff:127.0.0.1.${port}`]); + const pids = new Set(); + for (const line of lines.slice(headerIndex + 1)) { + const fields = line.trim().split(/\s+/); + if (!/^tcp(?:4|6|46)?$/.test(fields[0] ?? "")) continue; + if (!wanted.has((fields[3] ?? "").toLowerCase()) || fields[5] !== "LISTEN") continue; + const last = fields.length - 1 - trailing; + // Every column after the owner is numeric or hex on every recognized layout. Validating them + // keeps a malformed or reshaped row from letting a spaced process-name fragment such as + // `x:42` stand in for the PID; such a row cannot prove ownership. + if (last < ownerColumn || fields.length < header.length + || !fields.slice(last + 1).every(field => /^(?:0x)?[0-9a-f]+$/i.test(field))) return null; + const owner = fields.slice(ownerColumn, last + 1).join(" "); + const pid = Number((plainPid ? /^(\d+)$/ : /:(\d+)$/).exec(owner)?.[1]); + if (!Number.isSafeInteger(pid) || pid < 1) return null; + pids.add(pid); + } + return [...pids]; +} + export type LoopbackOwnerLookupResult = { kind: "match" | "mismatch" | "lookup_error" | "deadline"; elapsedMs: number; @@ -512,9 +553,10 @@ async function inspectListener( } const run = io.run ?? runOwnerLookup; if (platform === "darwin") { - const stdout = await run("/usr/sbin/lsof", ["-nP", "-a", `-iTCP@127.0.0.1:${port}`, "-sTCP:LISTEN", "-t"], OWNER_LOOKUP_TIMEOUT_MS); - const pids = new Set(stdout.split(/\r?\n/).map(line => Number(line.trim())).filter(pid => Number.isSafeInteger(pid) && pid > 0)); - return pids.size === 1 && pids.has(expectedPid); + const stdout = await run("/usr/sbin/netstat", ["-anv", "-p", "tcp"], OWNER_LOOKUP_TIMEOUT_MS); + const pids = parseDarwinIpv4LoopbackListenPids(stdout, port); + if (pids === null) throw new Error("unrecognized netstat TCP table"); + return pids.length === 1 && pids[0] === expectedPid; } if (platform === "win32") { const netstat = `${process.env.SystemRoot ?? "C:\\Windows"}\\System32\\netstat.exe`; @@ -537,11 +579,8 @@ async function inspectListener( matches => matches ? "match" as const : "mismatch" as const, error => { const failure = error as { - killed?: boolean; signal?: string | null; code?: unknown; stdout?: unknown; stderr?: unknown; + killed?: boolean; signal?: string | null; code?: unknown; } | null; - // lsof exits 1 with no output when no socket matches its selectors. - if (platform === "darwin" && failure?.code === 1 && !failure.killed - && failure.signal == null && failure.stdout === "" && failure.stderr === "") return "mismatch" as const; // execFile's timeout kills with SIGTERM; other spawn/exit/buffer errors are lookup failures. return failure?.killed === true && failure.signal === "SIGTERM" && failure.code === null ? "deadline" as const : "lookup_error" as const; diff --git a/structure/remote-link.md b/structure/remote-link.md index b70a7efccc0..b1706aea9a0 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -175,7 +175,7 @@ What a journalled revoke's refusal may leave changed, per code, on a first and o ## Client link transport -The Child relay requires a `connected()` result with `kind: "match"` from `src/client/link-tunnel.ts` before every fetch. The gate returns one typed `LinkAdmissionResult` containing the verdict and bounded timing/generation/check metadata; diagnostic callbacks do not supply admission or recovery decisions. The supervisor has one typed ownership dependency, `inspectLoopbackListener`. Before the first keyed readiness probe and after a tunnel restart, the supervisor asynchronously proves the exact `127.0.0.1:` LISTEN socket belongs to its SSH child; an adopted process also needs matching pidfile argv and start time. `src/server/port-reclaim.ts` uses Linux `/proc/net/tcp{,6}` plus the expected PID's `/proc//fd` socket symlinks without external tools, macOS `lsof` and Windows `netstat` with bounded asynchronous execution. Every key-bearing probe and relayed request makes a fresh bounded asynchronous owner lookup; an adopted process also has its current argv and start time rechecked on every admission. An unreadable or timed-out identity denies only that admission and is retried; a confirmed mismatch releases the adopted PID without signalling it and lets the next tick start a fresh tunnel. An unknown socket-owner lookup likewise denies the current admission. A missing supervisor, or a failed or stopped tunnel, returns a retryable 503 without sending the link key or body to the persisted loopback port; its body carries `code: "home_unreachable"` under the [fallback policy](fallback-policy.md#hub-down). A Home-initiated Child is the exception: the Home owns that link's `ssh -R` forward, so the Child has no sidecar, no supervisor and no SSH process whose socket it could prove. A join writes `/link/child-initiated.json` (the link id, mode 0600) beside the sidecar and removes it with the sidecar, so a Child-initiated link that lost its sidecar is recognised (`isChildInitiatedLink` in `src/client/link-state.ts`; an unreadable marker counts as present) and gets no gate. Only a link-mode runtime with neither the sidecar nor a marker for its link id is treated as Home-initiated: `src/client/runtime.ts` passes it `HOME_INITIATED_LINK_TUNNEL` (`src/client/link-relay.ts`), which omits local process ownership proof and reconnect holding but still uses the connection-bound relay authentication below. A refused connection answers 503. A held request rechecks the verdict after its wait and before each retry. +The Child relay requires a `connected()` result with `kind: "match"` from `src/client/link-tunnel.ts` before every fetch. The gate returns one typed `LinkAdmissionResult` containing the verdict and bounded timing/generation/check metadata; diagnostic callbacks do not supply admission or recovery decisions. The supervisor has one typed ownership dependency, `inspectLoopbackListener`. Before the first keyed readiness probe and after a tunnel restart, the supervisor asynchronously proves the exact `127.0.0.1:` LISTEN socket belongs to its SSH child; an adopted process also needs matching pidfile argv and start time. `src/server/port-reclaim.ts` uses Linux `/proc/net/tcp{,6}` plus the expected PID's `/proc//fd` socket symlinks without external tools, the macOS kernel TCP table from `/usr/sbin/netstat -anv -p tcp` (owner column located by header, never `lsof`, which stalls on filesystem metadata while a removable volume is busy, #9272) and Windows `netstat` with bounded asynchronous execution. Every key-bearing probe and relayed request makes a fresh bounded asynchronous owner lookup; an adopted process also has its current argv and start time rechecked on every admission. An unreadable or timed-out identity denies only that admission and is retried; a confirmed mismatch releases the adopted PID without signalling it and lets the next tick start a fresh tunnel. An unknown socket-owner lookup likewise denies the current admission. A missing supervisor, or a failed or stopped tunnel, returns a retryable 503 without sending the link key or body to the persisted loopback port; its body carries `code: "home_unreachable"` under the [fallback policy](fallback-policy.md#hub-down). A Home-initiated Child is the exception: the Home owns that link's `ssh -R` forward, so the Child has no sidecar, no supervisor and no SSH process whose socket it could prove. A join writes `/link/child-initiated.json` (the link id, mode 0600) beside the sidecar and removes it with the sidecar, so a Child-initiated link that lost its sidecar is recognised (`isChildInitiatedLink` in `src/client/link-state.ts`; an unreadable marker counts as present) and gets no gate. Only a link-mode runtime with neither the sidecar nor a marker for its link id is treated as Home-initiated: `src/client/runtime.ts` passes it `HOME_INITIATED_LINK_TUNNEL` (`src/client/link-relay.ts`), which omits local process ownership proof and reconnect holding but still uses the connection-bound relay authentication below. A refused connection answers 503. A held request rechecks the verdict after its wait and before each retry. The listener can change between an ownership check and the TCP connect. The data relay now authenticates that physical connection before sending the key or body (see [Connection-bound relay authentication](#connection-bound-relay-authentication)); this does not change the separate readiness/enrollment probes. A private Unix-socket forward could additionally remove competing TCP listeners from those probe paths. diff --git a/tests/server/port-reclaim.test.ts b/tests/server/port-reclaim.test.ts index 4b02092eaba..3d96e1e07e7 100644 --- a/tests/server/port-reclaim.test.ts +++ b/tests/server/port-reclaim.test.ts @@ -23,6 +23,15 @@ import { } from "../../src/server/windows-tcp-drop"; import { parseListenPidsFromNetstat } from "../../src/server/port-reclaim"; +/** A macOS 27 `netstat -anv -p tcp` table, header and column layout as recorded on a real host. */ +const DARWIN_NETSTAT_HEADER = "Proto Recv-Q Send-Q Local Address Foreign Address (state) rxbytes txbytes rhiwat shiwat process:pid state options gencnt flags flags1 usecnt rtncnt fltrs"; +function darwinRow(local: string, owner: string, proto = "tcp4", state = "LISTEN", foreign = "*.*"): string { + return `${proto} 0 0 ${local.padEnd(22)} ${foreign.padEnd(22)} ${state.padEnd(16)} 0 0 131072 131072 ${owner.padStart(20)} 00100 00000006 000000001d9ca5b6 00000000 00000800 1 0 000000`; +} +function darwinNetstat(rows: string[]): string { + return ["Active Internet connections (including servers)", DARWIN_NETSTAT_HEADER, ...rows, ""].join("\n"); +} + /** Exercise several scans and the deadline without depending on wall-clock scheduling. */ async function reclaimWithMockClock(options: ReclaimListenPortOptions): Promise { let now = 1_000; @@ -114,14 +123,20 @@ describe("exact IPv4 loopback listener ownership", () => { }); test.each(["darwin", "win32"] as const)("%s reports match, mismatch and ambiguous owners with boolean compatibility", async platform => { - const row = (pid: number) => platform === "darwin" ? `${pid}\n` + const row = (pid: number) => platform === "darwin" ? darwinNetstat([darwinRow("127.0.0.1.25000", `ssh:${pid}`)]) : `TCP 127.0.0.1:25000 0.0.0.0:0 LISTENING ${pid}\n`; + const empty = platform === "darwin" ? darwinNetstat([]) : ""; + const both = platform === "darwin" + ? darwinNetstat([darwinRow("127.0.0.1.25000", "ssh:42"), darwinRow("127.0.0.1.25000", "ssh:43")]) + : row(42) + row(43); for (const [stdout, kind] of [[row(42), "match"], [row(43), "mismatch"], - [row(42) + row(43), "mismatch"], ["", "mismatch"]] as const) { + [both, "mismatch"], [empty, "mismatch"]] as const) { let now = 100; const io: LoopbackOwnerLookupIo = { platform, nowMs: () => now, - run: async (_file, _args, timeoutMs) => { + run: async (file, args, timeoutMs) => { expect(timeoutMs).toBe(2_000); + // #9272: macOS reads the kernel TCP table; lsof stalls on busy removable volumes. + if (platform === "darwin") expect([file, ...args]).toEqual(["/usr/sbin/netstat", "-anv", "-p", "tcp"]); now += 7; return stdout; } }; @@ -131,30 +146,61 @@ describe("exact IPv4 loopback listener ownership", () => { }); test.each([ - ["darwin", {}, "mismatch"], - ["darwin", { signal: undefined }, "mismatch"], - ["darwin", { killed: undefined }, "mismatch"], - ["win32", {}, "lookup_error"], - ["darwin", { killed: true }, "lookup_error"], - ["darwin", { signal: "SIGTERM" }, "lookup_error"], - ["darwin", { code: 2 }, "lookup_error"], - ["darwin", { code: "1" }, "lookup_error"], - ["darwin", { stdout: "42\n" }, "lookup_error"], - ["darwin", { stderr: "lsof: permission denied" }, "lookup_error"], - ["darwin", { stdout: "\n" }, "lookup_error"], - ["darwin", { stderr: "\n" }, "lookup_error"], - ["darwin", { stdout: undefined }, "lookup_error"], - ["darwin", { stderr: undefined }, "lookup_error"], - ] as const)("%s empty lsof exit 1 with overrides %j reports %s", async (platform, overrides, kind) => { - const failure = Object.assign(new Error("Command failed: lsof"), { + ["darwin", {}], + ["win32", {}], + ["darwin", { code: 2 }], + ["darwin", { stderr: "netstat: sysctl: permission denied" }], + ] as const)("%s owner-lookup command failure %j reports lookup_error", async (platform, overrides) => { + const failure = Object.assign(new Error("Command failed: netstat"), { code: 1, killed: false, signal: null, stdout: "", stderr: "", ...overrides, }); const io: LoopbackOwnerLookupIo = { platform, nowMs: () => 100, run: async () => { throw failure; } }; - expect(await inspectIpv4LoopbackListener(25000, 42, io)).toEqual({ kind, elapsedMs: 0 }); + expect(await inspectIpv4LoopbackListener(25000, 42, io)).toEqual({ kind: "lookup_error", elapsedMs: 0 }); expect(await ownsIpv4LoopbackListener(25000, 42, io)).toBe(false); }); + test.each([ + ["the exact owner", [darwinRow("127.0.0.1.25000", "ssh:42")], "match"], + ["an IPv4-mapped exact owner", [darwinRow("::ffff:127.0.0.1.25000", "ssh:42", "tcp6")], "match"], + ["a process name with spaces", [darwinRow("127.0.0.1.25000", "GOAT (Nightly):42")], "match"], + ["duplicate rows for one socket", [darwinRow("127.0.0.1.25000", "ssh:42"), darwinRow("127.0.0.1.25000", "ssh:42")], "match"], + ["a foreign ::1 listener beside the owner", [darwinRow("127.0.0.1.25000", "ssh:42"), darwinRow("::1.25000", "bun:99", "tcp6")], "match"], + ["only a wildcard bind", [darwinRow("*.25000", "ssh:42", "tcp46")], "mismatch"], + ["only an established connection", [darwinRow("127.0.0.1.25000", "ssh:42", "tcp4", "ESTABLISHED", "127.0.0.1.51000")], "mismatch"], + ["a neighbouring port", [darwinRow("127.0.0.1.250001", "ssh:42"), darwinRow("127.0.0.1.2500", "ssh:42")], "mismatch"], + ["conflicting owners", [darwinRow("127.0.0.1.25000", "ssh:42"), darwinRow("127.0.0.1.25000", "ssh:43")], "mismatch"], + ["a missing PID", [darwinRow("127.0.0.1.25000", "ssh")], "lookup_error"], + ["a zero PID", [darwinRow("127.0.0.1.25000", "ssh:0")], "lookup_error"], + ["a name ending in the expected PID owned by another", [darwinRow("127.0.0.1.25000", "evil:42:99")], "mismatch"], + ["a spaced spoofed name owned by another", [darwinRow("127.0.0.1.25000", "x:42 y:99")], "mismatch"], + ["a row missing a trailing column", [darwinRow("127.0.0.1.25000", "x:42 y:99").replace(/ 000000$/, "")], "lookup_error"], + ["a row with an extra trailing column", [`${darwinRow("127.0.0.1.25000", "ssh:42")} extra`], "lookup_error"], + ] as const)("darwin netstat table with %s classifies the owner", async (_label, rows, kind) => { + const io: LoopbackOwnerLookupIo = { platform: "darwin", nowMs: () => 1, run: async () => darwinNetstat([...rows]) }; + expect((await inspectIpv4LoopbackListener(25000, 42, io)).kind).toBe(kind); + }); + + test("darwin netstat with an older plain pid column still proves the owner", async () => { + const header = "Proto Recv-Q Send-Q Local Address Foreign Address (state) rhiwat shiwat pid epid state options"; + const table = [ + "Active Internet connections (including servers)", header, + "tcp4 0 0 127.0.0.1.25000 *.* LISTEN 131072 131072 42 0 0x0100 0x00000006", + ].join("\n"); + const io: LoopbackOwnerLookupIo = { platform: "darwin", nowMs: () => 1, run: async () => table }; + expect((await inspectIpv4LoopbackListener(25000, 42, io)).kind).toBe("match"); + expect((await inspectIpv4LoopbackListener(25000, 43, io)).kind).toBe("mismatch"); + }); + + test.each([ + ["no header", "tcp4 0 0 127.0.0.1.25000 *.* LISTEN 0 0 131072 131072 ssh:42 00100 00000006 0 1 800 1 0 0\n"], + ["a header without an owner column", "Proto Recv-Q Send-Q Local Address Foreign Address (state)\n"], + ["the legacy lsof PID list", "42\n"], + ])("darwin netstat output with %s reports lookup_error", async (_label, stdout) => { + const io: LoopbackOwnerLookupIo = { platform: "darwin", nowMs: () => 1, run: async () => stdout }; + expect((await inspectIpv4LoopbackListener(25000, 42, io)).kind).toBe("lookup_error"); + }); + test.each([ [Object.assign(new Error("private spawn detail"), { code: "ENOENT" }), "lookup_error"], [{ killed: true, signal: "SIGTERM", code: null }, "deadline"], @@ -203,7 +249,7 @@ describe("exact IPv4 loopback listener ownership", () => { let expire!: () => void; let cancelled = false; const pending = inspectIpv4LoopbackListener(25000, 42, { platform: "darwin", nowMs: () => 10, - run: async () => "42\n", scheduleDeadline: callback => { + run: async () => darwinNetstat([darwinRow("127.0.0.1.25000", "ssh:42")]), scheduleDeadline: callback => { expire = callback; return () => { cancelled = true; }; } }); @@ -219,7 +265,7 @@ describe("exact IPv4 loopback listener ownership", () => { run: async () => { throw new Error("must not run"); } })).toEqual({ kind: "mismatch", elapsedMs: 0 }); }); - test.skipIf(process.platform !== "darwin")("a closed IPv4 loopback port reports mismatch with real lsof", async () => { + test.skipIf(process.platform !== "darwin")("a closed IPv4 loopback port reports mismatch with real netstat", async () => { const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response("ok") }); const port = server.port!; await server.stop(true); From b61a86e80fd637432079cd3c029a6566bac2c72b Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:37:08 +0900 Subject: [PATCH 30/50] fix(kiro): count bonus credits and retry a burst 429 on the same account (#9307) (#9321) * fix(kiro): count bonus credits and retry a burst 429 on the same account (#9307) parseKiroUsage counts active, unexpired bonus pools toward the routed percentage and exhaustion, and a pooled request retries its own account once on a short burst throttle before handing off; monthly or overage refusals, long delays and a repeat 429 still fail over at once. * fix(kiro): keep a spent bonus window out of routing and the pooled retry off the shared throttle gate * fix(kiro): pool an active free trial into the routed percentage and drop spent trial windows --- scripts/test-layout/layout-kiro-usage.json | 2 + src/adapters/kiro-retry.ts | 20 ++- src/providers/kiro-account-state-disk.ts | 10 +- src/providers/kiro-usage.ts | 69 +++++++-- structure/providers/kiro.md | 12 ++ tests/fixtures/test-layout-expected.json | 4 +- .../kiro/kiro-pooled-throttle.test.ts | 71 ++++++++++ .../kiro/kiro-refusal-failover.test.ts | 6 +- tests/providers/kiro/kiro-usage-bonus.test.ts | 131 ++++++++++++++++++ tests/server/server-kiro-refusal-e2e.test.ts | 31 ++++- 10 files changed, 335 insertions(+), 21 deletions(-) create mode 100644 tests/providers/kiro/kiro-pooled-throttle.test.ts create mode 100644 tests/providers/kiro/kiro-usage-bonus.test.ts diff --git a/scripts/test-layout/layout-kiro-usage.json b/scripts/test-layout/layout-kiro-usage.json index 827802f26a0..5e134424ec0 100644 --- a/scripts/test-layout/layout-kiro-usage.json +++ b/scripts/test-layout/layout-kiro-usage.json @@ -1,4 +1,6 @@ { + "kiro-usage-bonus.test.ts": "providers/kiro", + "kiro-pooled-throttle.test.ts": "providers/kiro", "responses-combo-bridge-usage.test.ts": "responses", "server-kiro-usage-log-e2e.test.ts": "server" } diff --git a/src/adapters/kiro-retry.ts b/src/adapters/kiro-retry.ts index 6c355e05dc0..69d3fc132e5 100644 --- a/src/adapters/kiro-retry.ts +++ b/src/adapters/kiro-retry.ts @@ -2,6 +2,7 @@ import type { AdapterFetchContext, AdapterRequest } from "./base"; import { fetchWithPhysicalSendReceipt } from "../lib/executor-physical-send-receipt"; import type { AttemptRecoveryKind } from "../usage/log"; import { classifyKiroHttpError, safeKiroHttpErrorMessage } from "./kiro-errors"; +import { classifyKiroRefusal } from "./kiro-refusal"; import { normalizeUpstreamHttpErrorResponse } from "./upstream-http-error"; import { readBoundedResponseBody } from "../lib/bounded-body"; import { resolveClientRetryAfter } from "../lib/retry-after"; @@ -21,6 +22,12 @@ const RESET_ATTEMPTS = 3; const RESET_RETRY_BASE_MS = 150; const RESET_RETRY_MAX_MS = 1_000; const THROTTLE_ATTEMPTS = 3; +/** + * A pooled request still retries its own account once when the throttle is a short burst (#9307). + * Handing off on the first 429 moved the pool's active account for good on a refusal one quick + * retry would have absorbed; a longer stated delay is a real limit, and the sibling serves now. + */ +const POOLED_SAME_ACCOUNT_RETRY_MAX_MS = 5_000; // A throttle round can try both the runtime and legacy endpoint. export const KIRO_FETCH_SEND_LIMIT = THROTTLE_ATTEMPTS * 2 * RESET_ATTEMPTS; const CANONICAL_RUNTIME_HOST = /^runtime\.([a-z]{2}(?:-[a-z]+)+-\d)\.kiro\.dev$/i; @@ -290,7 +297,10 @@ async function inspectKiroThrottle( const delayMs = retryAfter === "0" ? 0 : parseRetryAfterMs(retryAfter) ?? 2_000; return { response: rebuilt, - transient: failure.retryable && failure.code === "rate_limit_exceeded", + // A spent monthly or overage allowance can arrive as a 429 the generic classifier calls a rate + // limit; replaying it on the same account cannot succeed. + transient: failure.retryable && failure.code === "rate_limit_exceeded" + && classifyKiroRefusal(response.status, payloadText).kind === "rate", delayMs, }; } @@ -363,6 +373,14 @@ export async function fetchKiroWithRetry(request: AdapterRequest, ctx: KiroFetch const throttle = await inspectKiroThrottle(response, ctx.abortSignal); if (throttle && ctx.kiroPreferAccountFailover) { releaseKiroThrottleProbe(probeToken); + probeToken = undefined; + // Waited out here, not through the process-wide gate: siblings serving other accounts + // must not queue behind one account's burst. + if (throttle.transient && attempt === 0 && throttle.delayMs <= POOLED_SAME_ACCOUNT_RETRY_MAX_MS) { + cancelResponseBodyBestEffort(throttle.response); + await sleepWithAbort(throttle.delayMs, ctx.abortSignal); + continue; + } return throttle.response; } if (!throttle || !throttle.transient) { diff --git a/src/providers/kiro-account-state-disk.ts b/src/providers/kiro-account-state-disk.ts index edafa9b9efa..e34c660a888 100644 --- a/src/providers/kiro-account-state-disk.ts +++ b/src/providers/kiro-account-state-disk.ts @@ -17,9 +17,13 @@ export interface KiroPersistedQuota extends ProviderQuota { identity: string; } /** Keep only the closed set emitted by the Kiro parser when disk data is rewritten. */ export function sanitizeKiroQuota(quota: ProviderQuota): ProviderQuota { - const trial = quota.customWindows?.find(window => window.label === "Free trial" + const windows = (quota.customWindows ?? []).filter(window => (window.label === "Free trial" + || window.label === "Bonus credits") && typeof window.percent === "number" && Number.isFinite(window.percent) - && window.percent >= 0 && window.percent <= 100); + && window.percent >= 0 && window.percent <= 100) + .map(window => ({ label: window.label, percent: window.percent, + ...(window.label === "Bonus credits" && typeof window.resetAt === "number" && Number.isFinite(window.resetAt) + ? { resetAt: window.resetAt } : {}) })); return { monthlyPercent: quota.monthlyPercent, ...(typeof quota.kiroCreditsUsed === "number" && Number.isFinite(quota.kiroCreditsUsed) @@ -29,7 +33,7 @@ export function sanitizeKiroQuota(quota: ProviderQuota): ProviderQuota { ...(typeof quota.monthlyResetAt === "number" && Number.isFinite(quota.monthlyResetAt) && Number.isFinite(new Date(quota.monthlyResetAt).getTime()) ? { monthlyResetAt: quota.monthlyResetAt } : {}), - ...(trial ? { customWindows: [{ label: "Free trial", percent: trial.percent }] } : {}), + ...(windows.length > 0 ? { customWindows: windows } : {}), updatedAt: quota.updatedAt, }; } diff --git a/src/providers/kiro-usage.ts b/src/providers/kiro-usage.ts index 4ebd7d15edf..2125580185c 100644 --- a/src/providers/kiro-usage.ts +++ b/src/providers/kiro-usage.ts @@ -122,6 +122,31 @@ function selectBreakdown(list: unknown): Record | null { return null; } +/** + * Bonus pools granted on top of the plan (#9307), e.g. `FIRST_UPGRADE_TRIAL` credits. + * + * Only an ACTIVE pool that has not expired counts: a redeemed-but-expired grant can no longer + * be spent, and counting it would keep a spent account in rotation. + */ +function activeBonusCredits(list: unknown, now: number): { used: number; limit: number; expiresAt?: number } | null { + if (!Array.isArray(list)) return null; + let used = 0; + let limit = 0; + let expiresAt: number | undefined; + for (const row of list.map(asRecord)) { + if (!row || String(row.status ?? "").trim().toUpperCase() !== "ACTIVE") continue; + const expiry = normalizeResetAt(row.expiresAt); + if (expiry !== undefined && expiry <= now) continue; + const rowUsed = preciseNumber(row, "currentUsageWithPrecision", "currentUsage"); + const rowLimit = preciseNumber(row, "usageLimitWithPrecision", "usageLimit"); + if (rowUsed === undefined || rowUsed < 0 || rowLimit === undefined || rowLimit <= 0) continue; + used += Math.min(rowUsed, rowLimit); + limit += rowLimit; + if (expiry !== undefined) expiresAt = Math.min(expiresAt ?? expiry, expiry); + } + return limit > 0 ? { used, limit, ...(expiresAt !== undefined ? { expiresAt } : {}) } : null; +} + function parseKiroUsage(body: unknown): KiroUsageSnapshot | null { const payload = asRecord(body); if (!payload) return null; @@ -133,31 +158,53 @@ function parseKiroUsage(body: unknown): KiroUsageSnapshot | null { if (used === undefined || !Number.isFinite(used) || used < 0 || limit === undefined || !Number.isFinite(limit) || limit <= 0) return null; - const percent = normalizePercent((used / limit) * 100); - if (percent === undefined) return null; - - const nextResetAt = normalizeResetAt(payload.nextDateReset); + const now = Date.now(); + const bonus = activeBonusCredits(breakdown.bonuses, now); const customWindows: ProviderQuotaWindow[] = []; - // A trial allowance is a separate pool: folding it into the plan window would understate - // what the account can actually spend. + // A trial allowance is a separate pool the account can draw on while it is active. const trial = asRecord(breakdown.freeTrialInfo); + let activeTrial: { used: number; limit: number } | null = null; if (trial) { const trialUsed = preciseNumber(trial, "currentUsageWithPrecision", "currentUsage"); const trialLimit = preciseNumber(trial, "usageLimitWithPrecision", "usageLimit"); - if (trialUsed !== undefined && trialLimit !== undefined && trialLimit > 0) { + if (trialUsed !== undefined && trialUsed >= 0 && trialLimit !== undefined && trialLimit > 0) { const trialPercent = normalizePercent((trialUsed / trialLimit) * 100); - if (trialPercent !== undefined) customWindows.push({ label: "Free trial", percent: trialPercent }); + // Like the bonus window below: a spent trial at 100% would park a plan that still has credits. + if (trialPercent !== undefined && trialPercent < 100) customWindows.push({ label: "Free trial", percent: trialPercent }); + const status = String(trial.freeTrialStatus ?? "ACTIVE").trim().toUpperCase(); + const expiry = normalizeResetAt(trial.freeTrialExpiry); + if (status === "ACTIVE" && (expiry === undefined || expiry > now)) + activeTrial = { used: Math.min(trialUsed, trialLimit), limit: trialLimit }; } } + // Routing reads one percentage, so it must describe everything the account can still spend: + // a spent plan with bonus or trial credits left is not 100% used. + const extras = [bonus, activeTrial].filter((pool): pool is { used: number; limit: number } => pool !== null); + const spendable = limit + extras.reduce((sum, pool) => sum + pool.limit, 0); + const spent = Math.min(used, limit) + extras.reduce((sum, pool) => sum + pool.used, 0); + const pooled = extras.length ? (spent / spendable) * 100 : (used / limit) * 100; + const percent = normalizePercent(extras.length && spent < spendable ? Math.min(pooled, 99.99) : pooled); + if (percent === undefined) return null; + + const nextResetAt = normalizeResetAt(payload.nextDateReset); + // Shown only while it can still be spent. A bonus is additive to the plan, but every custom + // window is an independent limit to quota routing, so a spent bonus at 100% would park an + // account whose plan still has credits. + if (bonus && bonus.used < bonus.limit) { + const bonusPercent = normalizePercent(Math.min((bonus.used / bonus.limit) * 100, 99.99)); + if (bonusPercent !== undefined) customWindows.push({ label: "Bonus credits", percent: bonusPercent, + ...(bonus.expiresAt !== undefined ? { resetAt: bonus.expiresAt } : {}) }); + } + const quota: ProviderQuota = { monthlyPercent: percent, kiroCreditsUsed: used, kiroCreditsLimit: limit, ...(nextResetAt !== undefined ? { monthlyResetAt: nextResetAt } : {}), ...(customWindows.length > 0 ? { customWindows } : {}), - updatedAt: Date.now(), + updatedAt: now, }; // Enterprise accounts with overage enabled keep serving past the included limit, so @@ -167,7 +214,9 @@ function parseKiroUsage(body: unknown): KiroUsageSnapshot | null { return { quota, - exhausted: used >= limit && overageStatus === "DISABLED", + // Spent means every pool the account may draw from is spent: plan, active bonuses and an + // active free trial. Overage keeps the account serving past all of them. + exhausted: used >= limit && extras.every(pool => pool.used >= pool.limit) && overageStatus === "DISABLED", ...(nextResetAt !== undefined ? { nextResetAt } : {}), }; } diff --git a/structure/providers/kiro.md b/structure/providers/kiro.md index afe1f2de7dc..9a5e180f7c4 100644 --- a/structure/providers/kiro.md +++ b/structure/providers/kiro.md @@ -108,6 +108,18 @@ It is only consulted when the adapter the failed combo leg resolved is `kiro` (s credential generation and login identity, independently of quota observation time. A completed response from that same live credential clears an older verdict after disk hydration. Suspension is a process-local quarantine; rate refusals use a short cooldown. +Usage parsing counts every pool the account can still spend (#9307): an `ACTIVE` bonus in +`usageBreakdownList[].bonuses` that has not expired, and an active free trial, add to the routed +monthly percentage, which stays below 100 while any of their credit remains. The `Bonus credits` and +`Free trial` windows are emitted only below 100%, because quota routing treats each custom window as +an independent limit. An +account is exhausted only when its plan, active bonuses and an active free trial are all spent with +overage disabled. A pooled request (`kiroPreferAccountFailover`) still retries its own account once +on a burst 429 whose stated delay is at most 5 seconds; it waits that delay itself, outside the +process-wide throttle gate, so requests on other accounts do not queue behind it. A monthly or overage refusal, a longer +delay, or a second 429 hands off to rotation without that retry. +`tests/providers/kiro/kiro-usage-bonus.test.ts` and `tests/providers/kiro/kiro-pooled-throttle.test.ts` +cover both halves. Reactive account rotation is presence-driven even when a proactive preference switch is off. Pre-dispatch exclusion of an already refused account requires effective proactive preference with the provider override taking precedence over the global setting. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 58b49c2efe2..dc82dc7d20f 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1072,14 +1072,14 @@ "kiro-oauth.test.ts": "providers/kiro", "oauth-kiro-refresh-attention.test.ts": "oauth", "kiro-pool-load-settings.test.ts": "providers/kiro", "kiro-pinned-effort-ultra.test.ts": "providers/kiro", "kiro-org-user-identity.test.ts": "providers/kiro", "kiro-content-filter.test.ts": "providers/kiro", "kiro-pool-rank.test.ts": "providers/kiro", "kiro-reasoning-roundtrip.test.ts": "providers/kiro", - "kiro-refusal-failover.test.ts": "providers/kiro", "kiro-refusal.test.ts": "providers/kiro", + "kiro-pooled-throttle.test.ts": "providers/kiro", "kiro-refusal-failover.test.ts": "providers/kiro", "kiro-refusal.test.ts": "providers/kiro", "kiro-remote-image.test.ts": "providers/kiro", "kiro-retry.test.ts": "providers/kiro", "kiro-review-regressions.test.ts": "providers/kiro", "kiro-metering-events.test.ts": "providers/kiro", "kiro-metering-usage.test.ts": "providers/kiro", "kiro-completion-with-real-tools.test.ts": "providers/kiro", "kiro-single-final.test.ts": "providers/kiro", "kiro-structured-output.test.ts": "providers/kiro", "kiro-structured-output-strict.test.ts": "providers/kiro", "kiro-stream.test.ts": "providers/kiro", "kiro-tool-byte-accounting.test.ts": "providers/kiro", "kiro-transport-parity.test.ts": "providers/kiro", "kiro-tool-catalog.test.ts": "providers/kiro", - "kiro-usage-quota.test.ts": "providers/kiro", "kiro-usage-restart.test.ts": "providers/kiro", + "kiro-usage-bonus.test.ts": "providers/kiro", "kiro-usage-quota.test.ts": "providers/kiro", "kiro-usage-restart.test.ts": "providers/kiro", "kiro-windows-cli-db-path.test.ts": "providers/kiro", "kiro-windows-cli-executable-path.test.ts": "providers/kiro", "kiro-wire-estimate.test.ts": "providers/kiro", "lab-activation.test.ts": "lab", "lab-automation-coderabbit-regressions.test.ts": "lab", "lab-automation-final-coderabbit-regressions.test.ts": "lab", diff --git a/tests/providers/kiro/kiro-pooled-throttle.test.ts b/tests/providers/kiro/kiro-pooled-throttle.test.ts new file mode 100644 index 00000000000..b59dd8ec278 --- /dev/null +++ b/tests/providers/kiro/kiro-pooled-throttle.test.ts @@ -0,0 +1,71 @@ +/** + * #9307: a pooled Kiro request keeps its account through a short burst throttle and hands off only + * when the refusal is a real limit: a spent allowance, a long stated delay, or a repeat 429. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import type { AdapterRequest } from "../../../src/adapters/base"; +import { fetchKiroWithRetry, resetKiroThrottleStateForTests } from "../../../src/adapters/kiro-retry"; + +const realFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = realFetch; + resetKiroThrottleStateForTests(); +}); + +const request: AdapterRequest = { url: "https://runtime.us-east-1.kiro.dev/", method: "POST", + headers: { authorization: "Bearer synthetic", accept: "application/vnd.amazon.eventstream" }, body: "{}" }; + +function throttled(body: Record, retryAfter = "0"): Response { + return new Response(JSON.stringify(body), { status: 429, headers: { "Retry-After": retryAfter } }); +} +const burst = () => throttled({ __type: "ThrottlingException", message: "USER_REQUEST_RATE_EXCEEDED" }); + +async function run(responses: Response[]): Promise<{ status: number; calls: number }> { + let calls = 0; + globalThis.fetch = (async () => { calls++; return responses.shift() ?? new Response("ok", { status: 200 }); }) as unknown as typeof fetch; + const response = await fetchKiroWithRetry(request, { kiroPreferAccountFailover: true, returnRawErrors: true }); + return { status: response.status, calls }; +} + +describe("#9307 pooled Kiro throttle", () => { + test("a burst 429 that clears on retry is served by the same account", async () => { + expect(await run([burst(), new Response("ok", { status: 200 })])).toEqual({ status: 200, calls: 2 }); + }); + + test("a second burst 429 hands off to account failover", async () => { + expect(await run([burst(), burst(), new Response("ok", { status: 200 })])).toEqual({ status: 429, calls: 2 }); + }); + + test("a spent monthly or overage allowance hands off without a same-account retry", async () => { + for (const reason of ["MONTHLY_REQUEST_COUNT", "OVERAGE_REQUEST_LIMIT_EXCEEDED"]) { + resetKiroThrottleStateForTests(); + expect(await run([throttled({ reason, message: "rate limit exceeded" }), new Response("ok", { status: 200 })])) + .toEqual({ status: 429, calls: 1 }); + } + }); + + test("a long stated delay hands off immediately rather than parking the request", async () => { + expect(await run([throttled({ __type: "ThrottlingException", message: "USER_REQUEST_RATE_EXCEEDED" }, "30"), + new Response("ok", { status: 200 })])).toEqual({ status: 429, calls: 1 }); + }); + + test("one account's burst retry does not hold back a request on another account", async () => { + const pending: Array> = []; + let calls = 0; + globalThis.fetch = (async (_input: unknown, init?: RequestInit) => { + calls++; + const auth = new Headers(init?.headers).get("authorization"); + if (auth === "Bearer a" && calls === 1) + return throttled({ __type: "ThrottlingException", message: "USER_REQUEST_RATE_EXCEEDED" }, "3"); + return new Response("ok", { status: 200 }); + }) as unknown as typeof fetch; + const as = (token: string): AdapterRequest => ({ ...request, headers: { ...request.headers, authorization: `Bearer ${token}` } }); + const started = Date.now(); + pending.push(fetchKiroWithRetry(as("a"), { kiroPreferAccountFailover: true, returnRawErrors: true })); + await Bun.sleep(50); + const sibling = await fetchKiroWithRetry(as("b"), { kiroPreferAccountFailover: true, returnRawErrors: true }); + expect(sibling.status).toBe(200); + expect(Date.now() - started).toBeLessThan(1_500); + expect((await pending[0]!).status).toBe(200); + }); +}); diff --git a/tests/providers/kiro/kiro-refusal-failover.test.ts b/tests/providers/kiro/kiro-refusal-failover.test.ts index e59fe529e6c..54991b59e9d 100644 --- a/tests/providers/kiro/kiro-refusal-failover.test.ts +++ b/tests/providers/kiro/kiro-refusal-failover.test.ts @@ -156,7 +156,7 @@ describe("Kiro refusal account evidence", () => { expect(refusalAwareInitialKiroAccount(cfg(true), a!.id)).toBeNull(); }); - test("kiro pooled 429 bypasses same-account retry while one-account Kiro keeps it", async () => { + test("kiro pooled burst 429 retries its own account once before handing off, like one-account Kiro (#9307)", async () => { const request: AdapterRequest = { url: "https://runtime.us-east-1.kiro.dev/", method: "POST", headers: { authorization: "Bearer synthetic", accept: "application/vnd.amazon.eventstream" }, body: "{}" }; const responses = () => [new Response(JSON.stringify({ __type: "ThrottlingException", @@ -166,8 +166,8 @@ describe("Kiro refusal account evidence", () => { let sequence = responses(); globalThis.fetch = (async () => { calls++; return sequence.shift()!; }) as typeof fetch; const pooled = await fetchKiroWithRetry(request, { kiroPreferAccountFailover: true, returnRawErrors: true }); - expect(pooled.status).toBe(429); - expect(calls).toBe(1); + expect(pooled.status).toBe(200); + expect(calls).toBe(2); resetKiroThrottleStateForTests(); calls = 0; sequence = responses(); const single = await fetchKiroWithRetry(request, { returnRawErrors: true }); diff --git a/tests/providers/kiro/kiro-usage-bonus.test.ts b/tests/providers/kiro/kiro-usage-bonus.test.ts new file mode 100644 index 00000000000..e1b87d3412f --- /dev/null +++ b/tests/providers/kiro/kiro-usage-bonus.test.ts @@ -0,0 +1,131 @@ +/** + * #9307: Kiro grants bonus pools (e.g. FIRST_UPGRADE_TRIAL) on top of the plan. An account whose + * plan is spent but whose active bonus is not must stay routable and must not read as 100%. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { cachedProviderQuotaIsExhausted } from "../../../src/combos/resolve"; +import { sanitizeKiroQuota } from "../../../src/providers/kiro-account-state-disk"; +import { clearKiroAccountUsageState, fetchKiroUsageSnapshot } from "../../../src/providers/kiro-usage"; + +const realFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = realFetch; + clearKiroAccountUsageState(); +}); + +const context = { accountId: "acct-1", access: "tok-1", + profileArn: "arn:aws:codewhisperer:us-east-1:123456789012:profile/TEST" }; +const nowSec = () => Date.now() / 1000; + +function stub(payload: unknown): void { + globalThis.fetch = (async () => new Response(JSON.stringify(payload), { + status: 200, headers: { "content-type": "application/json" }, + })) as unknown as typeof fetch; +} + +function bonus(extra: Record = {}) { + return { bonusType: "FIRST_UPGRADE_TRIAL", currentUsage: 238.73, usageLimit: 500, status: "ACTIVE", + expiresAt: nowSec() + 30 * 86_400, ...extra }; +} + +/** The shape from the issue: plan 961/961, overage disabled, bonus 238.73/500 still active. */ +function payload(bonuses: unknown[], extra: Record = {}) { + return { + nextDateReset: nowSec() + 10 * 86_400, + overageConfiguration: { overageStatus: "DISABLED" }, + usageBreakdownList: [{ + resourceType: "CREDIT", currentUsage: 961, currentUsageWithPrecision: 961, + usageLimit: 961, usageLimitWithPrecision: 961, bonuses, ...extra, + }], + }; +} + +describe("#9307 Kiro bonus credits", () => { + test("a spent plan with an active bonus left is neither exhausted nor 100%", async () => { + stub(payload([bonus()])); + const snapshot = await fetchKiroUsageSnapshot(context); + expect(snapshot?.exhausted).toBe(false); + expect(snapshot?.quota.monthlyPercent).toBeCloseTo((961 + 238.73) / (961 + 500) * 100, 3); + expect(snapshot?.quota.kiroCreditsUsed).toBe(961); + expect(snapshot?.quota.kiroCreditsLimit).toBe(961); + const window = snapshot?.quota.customWindows?.find(row => row.label === "Bonus credits"); + expect(window?.percent).toBeCloseTo(47.746, 3); + expect(window?.resetAt).toBeGreaterThan(Date.now()); + }); + + test("a nearly spent bonus stays under 100% while any credit remains", async () => { + stub(payload([bonus({ currentUsage: 499.99 })])); + const snapshot = await fetchKiroUsageSnapshot(context); + expect(snapshot?.exhausted).toBe(false); + expect(snapshot!.quota.monthlyPercent!).toBeLessThan(100); + }); + + test("a fully spent bonus leaves the account exhausted", async () => { + stub(payload([bonus({ currentUsage: 500 })])); + const snapshot = await fetchKiroUsageSnapshot(context); + expect(snapshot?.exhausted).toBe(true); + expect(snapshot?.quota.monthlyPercent).toBe(100); + }); + + test("a spent bonus does not gate quota routing while plan credits remain", async () => { + stub(payload([bonus({ currentUsage: 500 })], { currentUsage: 480, currentUsageWithPrecision: 480 })); + const snapshot = await fetchKiroUsageSnapshot(context); + expect(snapshot?.exhausted).toBe(false); + expect(snapshot?.quota.customWindows).toBeUndefined(); + expect(cachedProviderQuotaIsExhausted(snapshot!.quota)).toBe(false); + stub(payload([bonus()])); + expect(cachedProviderQuotaIsExhausted((await fetchKiroUsageSnapshot(context))!.quota)).toBe(false); + }); + + test("an expired or inactive bonus does not count", async () => { + for (const stale of [bonus({ expiresAt: nowSec() - 60 }), bonus({ status: "EXPIRED" }), bonus({ status: undefined })]) { + stub(payload([stale])); + const snapshot = await fetchKiroUsageSnapshot(context); + expect(snapshot?.exhausted).toBe(true); + expect(snapshot?.quota.monthlyPercent).toBe(100); + expect(snapshot?.quota.customWindows).toBeUndefined(); + } + }); + + test("several active bonuses pool together and the earliest expiry is the window's reset", async () => { + const soon = nowSec() + 86_400; + stub(payload([bonus({ currentUsage: 100, usageLimit: 100, expiresAt: soon }), bonus({ currentUsage: 0, usageLimit: 50 })])); + const snapshot = await fetchKiroUsageSnapshot(context); + expect(snapshot?.exhausted).toBe(false); + const window = snapshot?.quota.customWindows?.find(row => row.label === "Bonus credits"); + expect(window?.percent).toBeCloseTo(100 * 100 / 150, 3); + expect(window?.resetAt).toBe(Math.round(soon * 1000)); + }); + + test("an active free trial with credits left also keeps the account out of exhaustion", async () => { + stub(payload([], { freeTrialInfo: { freeTrialStatus: "ACTIVE", currentUsage: 10, usageLimit: 500 } })); + const live = await fetchKiroUsageSnapshot(context); + expect(live?.exhausted).toBe(false); + expect(cachedProviderQuotaIsExhausted(live!.quota)).toBe(false); + stub(payload([], { freeTrialInfo: { freeTrialStatus: "EXPIRED", currentUsage: 10, usageLimit: 500 } })); + const expired = await fetchKiroUsageSnapshot(context); + expect(expired?.exhausted).toBe(true); + expect(cachedProviderQuotaIsExhausted(expired!.quota)).toBe(true); + }); + + test("a spent free trial does not gate quota routing while plan credits remain", async () => { + stub(payload([], { currentUsage: 100, currentUsageWithPrecision: 100, + freeTrialInfo: { freeTrialStatus: "ACTIVE", currentUsage: 500, usageLimit: 500 } })); + const snapshot = await fetchKiroUsageSnapshot(context); + expect(snapshot?.exhausted).toBe(false); + expect(cachedProviderQuotaIsExhausted(snapshot!.quota)).toBe(false); + }); + + test("overage still keeps a fully spent account serving", async () => { + stub({ ...payload([bonus({ currentUsage: 500 })]), overageConfiguration: { overageStatus: "ENABLED" } }); + expect((await fetchKiroUsageSnapshot(context))?.exhausted).toBe(false); + }); + + test("the bonus window survives the persisted-quota sanitizer", async () => { + stub(payload([bonus()])); + const snapshot = await fetchKiroUsageSnapshot(context); + const saved = sanitizeKiroQuota(snapshot!.quota); + expect(saved.customWindows).toEqual(snapshot!.quota.customWindows); + expect(saved.monthlyPercent).toBe(snapshot!.quota.monthlyPercent); + }); +}); diff --git a/tests/server/server-kiro-refusal-e2e.test.ts b/tests/server/server-kiro-refusal-e2e.test.ts index 4a9c2705bec..37904d8d36b 100644 --- a/tests/server/server-kiro-refusal-e2e.test.ts +++ b/tests/server/server-kiro-refusal-e2e.test.ts @@ -204,12 +204,14 @@ describe("Kiro refusal recovery through Responses", () => { ? { __type: "com.amazon.kiro.runtimeservice#ServiceQuotaExceededException", reason, message: "You have reached the limit for overages." } : { reason }; const observed: Array<{ url: string; auth: string | null; profile: string | null }> = []; + // A burst 429 first retries its own account (#9307), so only a repeated one rotates. + const refusals = reason === "USER_REQUEST_RATE_EXCEEDED" ? 2 : 1; globalThis.fetch = (async (input, init) => { const url = input instanceof Request ? input.url : String(input); if (url.startsWith("https://runtime.") && url.endsWith(".kiro.dev/")) { observed.push({ url, auth: new Headers(init?.headers).get("authorization"), profile: new Headers(init?.headers).get("x-amzn-kiro-profile-arn") }); - if (observed.length === 1) return new Response(JSON.stringify(refusalBody), { status }); + if (observed.length <= refusals) return new Response(JSON.stringify(refusalBody), { status }); return answer("served by b"); } return realFetch(input, init); @@ -220,7 +222,8 @@ describe("Kiro refusal recovery through Responses", () => { expect(response.status).toBe(200); expect(await response.text()).toContain("served by b"); expect(observed).toEqual([ - { url: "https://runtime.us-east-1.kiro.dev/", auth: "Bearer access-a", profile: aProfile }, + ...Array.from({ length: refusals }, + () => ({ url: "https://runtime.us-east-1.kiro.dev/", auth: "Bearer access-a", profile: aProfile })), { url: "https://runtime.eu-west-1.kiro.dev/", auth: "Bearer access-b", profile: bProfile }, ]); expect(getAccountSet("kiro")!.activeAccountId).toBe(b!.id); @@ -231,6 +234,30 @@ describe("Kiro refusal recovery through Responses", () => { } } + test("a single burst Kiro 429 is served by the same account and keeps it active (#9307)", async () => { + const [a] = await seed(); + saveConfig(config()); + const auths: Array = []; + globalThis.fetch = (async (input, init) => { + const url = input instanceof Request ? input.url : String(input); + if (url.startsWith("https://runtime.") && url.endsWith(".kiro.dev/")) { + auths.push(new Headers(init?.headers).get("authorization")); + if (auths.length === 1) return new Response(JSON.stringify({ reason: "USER_REQUEST_RATE_EXCEEDED" }), + { status: 429, headers: { "Retry-After": "0" } }); + return answer("served by a"); + } + return realFetch(input, init); + }) as typeof fetch; + const server = startServer(0); + try { + const response = await post(server, false); + expect(response.status).toBe(200); + expect(await response.text()).toContain("served by a"); + expect(auths).toEqual(["Bearer access-a", "Bearer access-a"]); + expect(getAccountSet("kiro")!.activeAccountId).toBe(a!.id); + } finally { await server.stop(true); } + }); + // A 400 the vendor's validator calls improperly formed: account B can serve what A cannot. const IMPROPER = JSON.stringify({ message: "ValidationException: Improperly formed request" }); From 0895d7861b86e2167bdc7f864187f40de669c35a Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:39:25 +0900 Subject: [PATCH 31/50] fix: keep retrying an authoritative pre-output refusal however slow the attempt (carry #9308) (#9317) Carry of #9308: keep retrying authoritative pre-output refusals regardless of slow attempt duration. Co-authored-by: Bezrabotnyi <20128761+megamen32@users.noreply.github.com> --- src/lib/upstream-retry.ts | 19 ++++++++++++- src/server/responses/codex-ws-wire.ts | 2 ++ .../upstream-transient-retry.test.ts | 20 +++++++++++++ .../responses-pool-overload-failover.test.ts | 28 ++++++++++++++++++- 4 files changed, 67 insertions(+), 2 deletions(-) diff --git a/src/lib/upstream-retry.ts b/src/lib/upstream-retry.ts index 92354256d0f..a9d43929d5a 100644 --- a/src/lib/upstream-retry.ts +++ b/src/lib/upstream-retry.ts @@ -55,6 +55,22 @@ export function isNonReplayableResponse(response: Response): boolean { return nonReplayableResponses.has(response); } +/** + * The marker for a gateway status this proxy synthesized from an authoritative upstream refusal + * that ended the turn before any output. Such an attempt is slow only because the upstream + * queued it; the slow-attempt guard exists for the failed attempt that streamed, so it does + * not apply. Replay safety stays the caller's decision, exactly as for any other status. + */ +const authoritativePreOutputRefusals = new WeakSet(); + +export function markAuthoritativePreOutputRefusal(response: Response): void { + authoritativePreOutputRefusals.add(response); +} + +export function isAuthoritativePreOutputRefusal(response: Response): boolean { + return authoritativePreOutputRefusals.has(response); +} + /** * The narrower marker: responses this proxy synthesized as a replay refusal. * @@ -997,7 +1013,8 @@ export async function fetchWithTransientRetry( // thing about its own failure, so the ladder stops and hands the response back untouched. if (res.ok || !isTransientUpstreamStatus(res.status) || isNonReplayableResponse(res) || res.headers.get(REPLAY_REFUSAL_NO_RETRY_HEADER) === REPLAY_REFUSAL_NO_RETRY_VALUE) return res; - if (opts.abortSignal?.aborted || Date.now() - attemptStart > slowAttemptMs) return res; + if (opts.abortSignal?.aborted + || (Date.now() - attemptStart > slowAttemptMs && !isAuthoritativePreOutputRefusal(res))) return res; // A 5xx that says the input does not fit is deterministic: resending the same body is // refused the same way, so it goes back for the caller to classify (#8127). if (await isContextOverflowResponse(res, opts.abortSignal)) return res; diff --git a/src/server/responses/codex-ws-wire.ts b/src/server/responses/codex-ws-wire.ts index e8a2cab3b05..e81dd1cd09f 100644 --- a/src/server/responses/codex-ws-wire.ts +++ b/src/server/responses/codex-ws-wire.ts @@ -10,6 +10,7 @@ import { isRateLimitOrQuotaFailureMessage, recognizedUpstreamError } from "../.. import type { RequestFailureCause, RequestFailureStage } from "../../lib/request-failure-model"; import { packageVersion } from "../../lib/package-version"; import { registerProviderResponseProvenance } from "../../providers/request-pacing"; +import { markAuthoritativePreOutputRefusal } from "../../lib/upstream-retry"; // If the 101 never arrives (network black hole), give SSE a chance well before // the caller's connect timeout (default 200s) would fire. export const UPGRADE_DEADLINE_MS = 10_000; @@ -328,6 +329,7 @@ const preOutputRefusals = new WeakMap(); */ export function markCodexWsPreOutputRefusal(projection: Response, restore: () => Response): void { preOutputRefusals.set(projection, { restore, outcomeRecorded: false }); + markAuthoritativePreOutputRefusal(projection); } export function isCodexWsPreOutputRefusal(response: Response): boolean { diff --git a/tests/providers/upstream-transient-retry.test.ts b/tests/providers/upstream-transient-retry.test.ts index 23f5024fb43..b615622d2c0 100644 --- a/tests/providers/upstream-transient-retry.test.ts +++ b/tests/providers/upstream-transient-retry.test.ts @@ -5,6 +5,7 @@ import { isNonReplayableUpstreamCode, isTransientUpstreamStatus, markResponseNonReplayable, + markAuthoritativePreOutputRefusal, } from "../../src/lib/upstream-retry"; import { transientRetryPolicyFor } from "../../src/providers/key-failover"; import { handleChatCompletions } from "../../src/server/chat-completions"; @@ -216,6 +217,25 @@ describe("fetchWithTransientRetry", () => { expect(first.__wasCancelled()).toBe(true); }); + test("a slow attempt is returned, unless it is an authoritative pre-output refusal", async () => { + const slow = async () => { await new Promise(resolve => setTimeout(resolve, 150)); return bodyResponse(503); }; + let calls = 0; + const slowSend = async () => { calls++; return slow(); }; + const returned = await fetchWithTransientRetry(slowSend, { attempts: 5, slowAttemptMs: 50 }); + expect(returned.status).toBe(503); + expect(calls).toBe(1); + + calls = 0; + const retried = await fetchWithTransientRetry(async () => { + calls++; + const response = await slow(); + if (calls === 1) markAuthoritativePreOutputRefusal(response); + return response; + }, { attempts: 5, slowAttemptMs: 50 }); + expect(retried.status).toBe(503); + expect(calls).toBe(2); + }); + test("exhausts attempts on persistent 502 and returns the final 502 with body intact", async () => { let calls = 0; const res = await fetchWithTransientRetry(async () => { calls++; return bodyResponse(502); }, { slowAttemptMs: 60_000 }); diff --git a/tests/responses/responses-pool-overload-failover.test.ts b/tests/responses/responses-pool-overload-failover.test.ts index 55d28f18fc9..9c0fd0588e0 100644 --- a/tests/responses/responses-pool-overload-failover.test.ts +++ b/tests/responses/responses-pool-overload-failover.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { createHash } from "node:crypto"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -46,6 +46,8 @@ class FakeWebSocket { static instances: FakeWebSocket[] = []; static plan: Step[] = []; static onAbortStep: (() => void) | undefined; + /** Runs just before a refusal frame, e.g. to make the upstream's queueing take time. */ + static beforeRefusal: (() => void) | undefined; url: string; headers: Headers; sent: string[] = []; @@ -106,6 +108,7 @@ class FakeWebSocket { error: { code: "server_is_overloaded", message: "Our servers are currently overloaded." } } }); return; } + FakeWebSocket.beforeRefusal?.(); if (step === "heartbeat-bare-then-refuse") { // The field shape: the sequence marker on the heartbeat, then a refusal whose code alone // identifies the overload with no numeric wrapper status. @@ -183,6 +186,7 @@ beforeEach(() => { FakeWebSocket.instances = []; FakeWebSocket.plan = []; FakeWebSocket.onAbortStep = undefined; + FakeWebSocket.beforeRefusal = undefined; globalThis.WebSocket = FakeWebSocket as unknown as typeof WebSocket; // Every send must ride the WebSocket; an HTTP send here is a failure of the test's premise. globalThis.fetch = (async () => { throw new Error("unexpected HTTP send"); }) as unknown as typeof fetch; @@ -443,6 +447,28 @@ describe("pooled native Codex recovers a pre-output upstream refusal (#6969)", ( expect(failures(WORK)).toBe(1); }); + test("a refusal the upstream queued past the slow-attempt bound still takes the same-account ladder", async () => { + // The slow-attempt guard returns a 5xx that took longer than 15 s. A held pre-output refusal is + // slow only because the upstream queued the turn before refusing it, so it is still resent. + const realNow = Date.now.bind(Date); + let skew = 0; + const clock = spyOn(Date, "now").mockImplementation(() => realNow() + skew); + try { + FakeWebSocket.beforeRefusal = () => { + skew += 16_000; + FakeWebSocket.beforeRefusal = undefined; + }; + FakeWebSocket.plan = ["refuse", "ok"]; + const { response, body } = await send(poolConfig([WORK])); + expect(response.status).toBe(200); + expect(body).toContain("response.completed"); + expect(body).not.toContain("server_is_overloaded"); + expect(sockets()).toEqual(["Bearer work-access", "Bearer work-access"]); + } finally { + clock.mockRestore(); + } + }); + test("a pinned account never moves to another account", async () => { FakeWebSocket.plan = ["refuse", "refuse", "refuse", "ok"]; const { response, body } = await send(poolConfig([WORK, OTHER], { codexAccountNamespaces: { side: WORK } }), From e7ca2f0f7dbd69ca704bc8267e95fc4182d81428 Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:43:57 +0900 Subject: [PATCH 32/50] fix(oauth): keep spent siblings out of account rotation (#9304) (#9313) * fix(oauth): keep spent siblings out of account rotation (#9304) Reactive rotation now drops a sibling whose measured quota is spent until a future reset (or spent on a reading under 30 minutes old) before any strategy picks, so a refused request returns the limit instead of retrying on an account already at 100%. Windows whose reset has passed no longer count as spent, and first-attempt round-robin and fill-first prefer unspent accounts. * fix(oauth): commit round-robin against the same spent-filtered list it proposes from --- scripts/test-layout/layout-providers.json | 1 + src/oauth/account-quota-rank.ts | 96 +++++++--- src/oauth/generic-account-failover.ts | 47 +++-- structure/providers/generic-account-pool.md | 4 + tests/fixtures/test-layout-expected.json | 2 +- .../generic-oauth-exhausted-sibling.test.ts | 179 ++++++++++++++++++ 6 files changed, 294 insertions(+), 35 deletions(-) create mode 100644 tests/oauth/generic-oauth-exhausted-sibling.test.ts diff --git a/scripts/test-layout/layout-providers.json b/scripts/test-layout/layout-providers.json index 2a545688438..cd6dfa9a524 100644 --- a/scripts/test-layout/layout-providers.json +++ b/scripts/test-layout/layout-providers.json @@ -1,4 +1,5 @@ { + "generic-oauth-exhausted-sibling.test.ts": "oauth", "resolved-model-policy-catalog-reuse.test.ts": "providers", "m365-copilot-security.test.ts": "providers", "m365-copilot-executor.test.ts": "providers", diff --git a/src/oauth/account-quota-rank.ts b/src/oauth/account-quota-rank.ts index 6582a29d3b0..65daa40d0c2 100644 --- a/src/oauth/account-quota-rank.ts +++ b/src/oauth/account-quota-rank.ts @@ -78,38 +78,60 @@ interface Ranked { */ const PASSIVE_HEADROOM_MAX_AGE_MS = 60 * 60_000; +/** Reset stamps arrive in seconds or milliseconds; routing compares milliseconds. */ +function resetMs(raw: number | undefined): number | undefined { + if (typeof raw !== "number" || !Number.isFinite(raw)) return undefined; + return raw < 1e11 ? raw * 1000 : raw; +} + +interface RoutingWindow { percent: number; resetAt?: number } + /** - * Remaining headroom across every window the provider reports. + * The windows that still describe the account right now, or null when nothing measured it. * -* The minimum wins: an account at 5% of its five-hour window is unusable right now even if -* its monthly allowance is barely touched. -*/ -function headroomOf(provider: string, accountId: string, requestedModelId?: string | null, account?: ProviderAccount): number | null { + * A window whose reset time has passed has rolled over: its percentage measured an allowance + * that no longer exists, and counting it would park a refilled account until the next probe. + */ +function routingWindowsOf( + provider: string, accountId: string, requestedModelId: string | null | undefined, + account: ProviderAccount | undefined, now: number, +): { windows: RoutingWindow[]; updatedAt: number } | null { const evidence = provider === "kiro" && account ? kiroAccountEvidence(account) : null; const quota = provider === "kiro" - ? evidence?.quotaPercent === undefined ? null : { monthlyPercent: evidence.quotaPercent, updatedAt: Date.now() } + ? evidence?.quotaPercent === undefined ? null : { monthlyPercent: evidence.quotaPercent, updatedAt: now } : getCachedProviderAccountQuota(provider, accountId); if (!quota) return null; // Null, not a low rank: this must reproduce "no evidence" so a stale roster degrades to // the unranked ring rather than to a differently wrong answer. - if (hasPassiveAccountQuota(provider) && Date.now() - quota.updatedAt > PASSIVE_HEADROOM_MAX_AGE_MS) return null; + if (hasPassiveAccountQuota(provider) && now - quota.updatedAt > PASSIVE_HEADROOM_MAX_AGE_MS) return null; const family = classifyModelFamilyForQuota(provider, requestedModelId); - if (family) { - const percents = (quota.customWindows ?? []) - .filter(window => window.modelId === undefined && windowMatchesFamily(window.label, family)) - .map(window => window.percent) - .filter((value): value is number => typeof value === "number"); - if (percents.length === 0) return null; - return 100 - Math.max(...percents); + const custom = (quota.customWindows ?? []).filter(window => window.modelId === undefined + && (!family || windowMatchesFamily(window.label, family))); + const raw: { percent?: number; resetAt?: number }[] = family ? custom : [ + { percent: quota.fiveHourPercent, resetAt: "fiveHourResetAt" in quota ? quota.fiveHourResetAt : undefined }, + { percent: quota.weeklyPercent, resetAt: "weeklyResetAt" in quota ? quota.weeklyResetAt : undefined }, + { percent: quota.monthlyPercent, resetAt: "monthlyResetAt" in quota ? quota.monthlyResetAt : undefined }, + ...custom, + ]; + const windows: RoutingWindow[] = []; + for (const window of raw) { + if (typeof window.percent !== "number") continue; + const resetAt = resetMs(window.resetAt); + if (resetAt !== undefined && resetAt <= now) continue; + windows.push({ percent: window.percent, ...(resetAt === undefined ? {} : { resetAt }) }); } - const percents = [ - quota.fiveHourPercent, - quota.weeklyPercent, - quota.monthlyPercent, - ...(quota.customWindows ?? []).filter(window => window.modelId === undefined).map(window => window.percent), - ].filter((value): value is number => typeof value === "number"); - if (percents.length === 0) return null; - return 100 - Math.max(...percents); + return windows.length ? { windows, updatedAt: quota.updatedAt } : null; +} + +/** + * Remaining headroom across every window the provider reports. + * +* The minimum wins: an account at 5% of its five-hour window is unusable right now even if +* its monthly allowance is barely touched. +*/ +function headroomOf(provider: string, accountId: string, requestedModelId?: string | null, account?: ProviderAccount): number | null { + const measured = routingWindowsOf(provider, accountId, requestedModelId, account, Date.now()); + return measured ? 100 - Math.max(...measured.windows.map(window => window.percent)) : null; } /** @@ -140,6 +162,36 @@ export function isAccountQuotaExhausted( return headroom !== null && headroom <= 0; } +/** + * How long a spent reading with no reset time may keep an account out of rotation. + * + * Matches the last-good display horizon: past it nothing re-measured the account, and refusing + * a request on a reading that old would trade a possible 429 for a certain one. + */ +const SPENT_WITHOUT_RESET_MAX_AGE_MS = 30 * 60_000; + +/** + * Hard exclusion for reactive rotation (#9304): may this sibling be skipped outright? + * + * Stricter than {@link isAccountQuotaExhausted}, which only orders candidates. A spent window + * with a future reset is authoritative until that reset; one without a reset time counts only + * while the reading is fresh, so an account is never skipped forever on evidence nobody renews. + */ +export function isAccountSpentForRotation( + provider: string, + accountId: string, + requestedModelId?: string | null, + account?: ProviderAccount, + now = Date.now(), +): boolean { + if (provider === "kiro") return account ? kiroAccountEvidence(account, now).exhausted === true : false; + const measured = routingWindowsOf(provider, accountId, requestedModelId, account, now); + const spent = measured?.windows.filter(window => window.percent >= 100) ?? []; + if (spent.length === 0) return false; + return spent.some(window => window.resetAt !== undefined) + || now - measured!.updatedAt <= SPENT_WITHOUT_RESET_MAX_AGE_MS; +} + /** * Earliest future reset timestamp (in ms) for the relevant quota window, or null if unknown. * Prefers weekly reset when multiple windows exist so expiring allowance is consumed first. diff --git a/src/oauth/generic-account-failover.ts b/src/oauth/generic-account-failover.ts index 64aaf5d452c..4713d7e9df2 100644 --- a/src/oauth/generic-account-failover.ts +++ b/src/oauth/generic-account-failover.ts @@ -26,6 +26,7 @@ import { exhaustedCooldownMs, hasHeadroomEvidence, isAccountQuotaExhausted, + isAccountSpentForRotation, rankAccountsByHeadroom, rankAccountsByResetFirst, classifyModelFamilyForQuota, @@ -450,8 +451,19 @@ export function hasEligibleGenericOAuthFailoverTarget( // Same model filter rotation applies, so an Antigravity sibling whose roster omits the // model is not advertised as a target rotation would then refuse to pick. const siblings = eligibleIdsIn(set, providerName, now, family).filter(id => id !== failedAccountId); - return (providerName === "google-antigravity" - ? preferKiroModelSupport(providerName, siblings, requestedModelId) : siblings).length > 0; + return withoutSpentAccounts(providerName, providerName === "google-antigravity" + ? preferKiroModelSupport(providerName, siblings, requestedModelId) : siblings, requestedModelId, now).length > 0; +} + +/** + * Siblings that a measured, still-current spent quota does not rule out (#9304). + * + * Rotation after a refusal must not trade one 429 for another: an account already shown at + * 100% until a future reset cannot serve the retry, so returning the limit is the honest answer. + */ +function withoutSpentAccounts(providerName: string, ids: readonly string[], requestedModelId: string | null | undefined, now: number): string[] { + const rows = new Map((getAccountSet(providerName)?.accounts ?? []).map(account => [account.id, account])); + return ids.filter(id => !isAccountSpentForRotation(providerName, id, requestedModelId, rows.get(id), now)); } /** Select a live Antigravity sibling using activation captured before the refused send. */ @@ -621,7 +633,10 @@ function pickFillFirstGenericAccount( return null; } const start = activeId ? stableAll.indexOf(activeId) : -1; - const ring = start >= 0 ? [...stableAll.slice(start + 1), ...stableAll.slice(0, start)] : stableAll; + const walk = start >= 0 ? [...stableAll.slice(start + 1), ...stableAll.slice(0, start)] : stableAll; + // A spent sibling is the last resort, never the next stop on the ring (#9304). + const live = new Set(withoutSpentAccounts(providerName, walk, requestedModelId, now)); + const ring = [...walk.filter(id => live.has(id)), ...walk.filter(id => !live.has(id))]; if (preferBelowThreshold) { const below = ring.find(id => id !== activeId && eligible.has(id) && !isOverAutoSwitchThreshold(providerName, id, threshold, requestedModelId, accountRows?.get(id))); @@ -656,13 +671,7 @@ export function noteGenericPoolSelection( const family = classifyModelFamilyForQuota(providerName, requestedModelId); const poolKey = genericPoolKey(providerName, family); const limit = genericStickyLimit(config, providerName); - const eligible = preferKiroModelSupport( - providerName, - eligibleFailoverAccounts(providerName, Date.now(), family), - requestedModelId, - config, - ); - const picked = pickRoundRobinAccount(poolKey, eligible, limit); + const picked = pickRoundRobinAccount(poolKey, roundRobinCandidates(config, providerName, family, requestedModelId, Date.now()), limit); // The resolver may have admitted a different account than the ring proposed: a removal, a // reauth verdict or a manual selection can land during credential resolution. Realign the // cursor onto what actually served rather than leaving it on a road not taken. @@ -670,6 +679,19 @@ export function noteGenericPoolSelection( notePoolRotationSuccess(poolKey, accountId, limit); } +/** + * The one candidate list round-robin both proposes from and commits against. The ring cursor is + * positional, so a peek and a pick over different lists would land on different accounts. + */ +function roundRobinCandidates( + config: OcxConfig, providerName: string, family: QuotaModelFamily | undefined, + requestedModelId: string | null | undefined, now: number, +): string[] { + const modelReady = preferKiroModelSupport(providerName, + eligibleFailoverAccounts(providerName, now, family), requestedModelId, config); + const live = withoutSpentAccounts(providerName, modelReady, requestedModelId, now); + return live.length ? live : modelReady; +} /** * Cool the account that actually 429'd and name the next eligible one, or null. @@ -752,6 +774,8 @@ export function rotateGenericOAuthAccountOnRefusal( if (withRoom.length > 0) candidates = withRoom; } candidates = preferKiroModelSupport(providerName, candidates, requestedModelId, config); + candidates = withoutSpentAccounts(providerName, candidates, requestedModelId, now); + if (candidates.length === 0) return null; // The 429 path branches too. Leaving it on the quota ranking would make a configured // strategy inert in practice the moment anything actually failed, which is the case the // operator chose the strategy for. @@ -895,8 +919,7 @@ export function preferredInitialAccount( } if (strategy === "round-robin") { const family = classifyModelFamilyForQuota(providerName, requestedModelId); - const eligibleNow = preferKiroModelSupport(providerName, - eligibleFailoverAccounts(providerName, now, family), requestedModelId, config); + const eligibleNow = roundRobinCandidates(config, providerName, family, requestedModelId, now); if (eligibleNow.length === 0) return null; // PEEK, not pick: this proposal is discardable, and advancing the ring for an account the // resolver then rejects would skip a turn for nothing. noteGenericPoolSelection commits. diff --git a/structure/providers/generic-account-pool.md b/structure/providers/generic-account-pool.md index 70137c3028d..650e82313ff 100644 --- a/structure/providers/generic-account-pool.md +++ b/structure/providers/generic-account-pool.md @@ -51,6 +51,10 @@ account's cooldown but passes `commit: false`, so it only peeks at a round-robin sibling does not consume a sticky turn. Dispatching callers retain the default committed pick. `tests/oauth/generic-oauth-combo-account-cooldown.test.ts` covers this distinction. +## Spent siblings + +Reactive rotation (`rotateGenericOAuthAccountOnRefusal`) and `hasEligibleGenericOAuthFailoverTarget` drop a sibling that `isAccountSpentForRotation` in `src/oauth/account-quota-rank.ts` reports as spent before any strategy picks, so a refused request returns the limit instead of retrying on an account already at 100%. A spent window with a future reset is authoritative until that reset; a spent reading without a reset time counts only while it is at most 30 minutes old, and an unmeasured account stays a target. Ranking and exhaustion checks ignore every window whose reset time has passed. First-attempt round-robin and fill-first prefer an unspent account and fall back to a spent one only when nothing else is eligible. `tests/oauth/generic-oauth-exhausted-sibling.test.ts` covers every strategy. + ## Account diagnostics `GET /api/oauth/accounts/diagnostics?provider=` (`src/server/management/account-diagnostics-routes.ts`, loaded on demand by `src/server/management-api.ts`) explains why each account of one OAuth login can or cannot serve now. It runs inside `runPassiveReadSync`, so the credential-store read neither hardens, publishes nor backs up anything. Each row carries the account id, `active`, `paused`, `needsReauth`, `eligible`, `eligibleModels`, `lastRefresh`, `cooldownUntil`, `inFlight` and, for Kiro with `maxConcurrentPerAccount`, `atCapacity`; never an email, label, organization or credential field. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index dc82dc7d20f..0129b05ba5e 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -972,7 +972,7 @@ "server-antigravity-model-roster-routing.test.ts": "server", "antigravity-routing-carry.test.ts": "adapters/google", "server-antigravity-model-denial-recovery.test.ts": "server", - "generic-oauth-combo-account-cooldown.test.ts": "oauth", "generic-oauth-failover.test.ts": "oauth", "generic-oauth-refusal-composition.test.ts": "oauth", + "generic-oauth-combo-account-cooldown.test.ts": "oauth", "generic-oauth-exhausted-sibling.test.ts": "oauth", "generic-oauth-failover.test.ts": "oauth", "generic-oauth-refusal-composition.test.ts": "oauth", "github-copilot-auto.test.ts": "providers/github-copilot", "github-copilot-auto-runtime.test.ts": "providers/github-copilot", "github-copilot-catalog-hints.test.ts": "providers/github-copilot", diff --git a/tests/oauth/generic-oauth-exhausted-sibling.test.ts b/tests/oauth/generic-oauth-exhausted-sibling.test.ts new file mode 100644 index 00000000000..ef7d02c0d0b --- /dev/null +++ b/tests/oauth/generic-oauth-exhausted-sibling.test.ts @@ -0,0 +1,179 @@ +/** + * #9304: reactive rotation must not move a refused request onto a sibling whose measured + * allowance is spent. The limit goes back to the client instead, while a sibling whose window + * has rolled over, or whose spent reading nobody renewed, stays usable. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { isAccountQuotaExhausted, isAccountSpentForRotation } from "../../src/oauth/account-quota-rank"; +import { + clearGenericFailoverHealth, + hasEligibleGenericOAuthFailoverTarget, + noteGenericPoolSelection, + preferredInitialAccount, + rotateGenericOAuthAccountOn429, +} from "../../src/oauth/generic-account-failover"; +import { clearPoolRotationState } from "../../src/oauth/pool-kernel"; +import { getAccountSet, saveCredential, setActiveAccount } from "../../src/oauth/store"; +import { clearAccountQuotaCache, setCachedProviderAccountQuotaForTests } from "../../src/providers/quota"; +import type { ProviderQuota } from "../../src/providers/quota-types"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const originalHome = process.env.OPENCODEX_HOME; +let home: string; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-exhausted-sibling-")); + process.env.OPENCODEX_HOME = home; + clearGenericFailoverHealth(); + clearPoolRotationState(); +}); + +afterEach(() => { + clearGenericFailoverHealth(); + clearPoolRotationState(); + clearAccountQuotaCache("xai"); + if (originalHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = originalHome; + removeTreeWithRetry(home); +}); + +const XAI = { adapter: "openai-chat", baseUrl: "https://api.x.ai/v1", authMode: "oauth" } as unknown as OcxProviderConfig; +const HOUR = 3_600_000; +type Strategy = "quota" | "round-robin" | "fill-first" | "reset-first"; +const STRATEGIES: Strategy[] = ["quota", "round-robin", "fill-first", "reset-first"]; + +function config(strategy: Strategy = "quota", enabled?: boolean): OcxConfig { + return { + providers: { xai: { ...XAI, oauthAccountFailover: { + ...(enabled === undefined ? {} : { enabled }), strategy, autoSwitchThreshold: 80, + } } }, + pool: { kernel: true }, + } as unknown as OcxConfig; +} + +async function seed(count: number): Promise { + for (let i = 0; i < count; i++) { + await saveCredential("xai", { + access: `access-${i}`, refresh: `refresh-${i}`, expires: Date.now() + HOUR, accountId: `uuid-${i}`, + } as never, { addAccount: true }); + } + return getAccountSet("xai")!.accounts.map(account => account.id); +} + +function quota(id: string, row: Omit & { updatedAt?: number }): void { + setCachedProviderAccountQuotaForTests("xai", id, { updatedAt: Date.now(), ...row }); +} + +const spentUntilTomorrow = { weeklyPercent: 100, weeklyResetAt: Date.now() + 24 * HOUR }; + +describe("#9304 rotation leaves a spent sibling out", () => { + test("the reported case: the only sibling is at 100% until its reset, so the limit is returned", async () => { + const [full, serving] = await seed(2); + await setActiveAccount("xai", serving!); + quota(full!, spentUntilTomorrow); + quota(serving!, { weeklyPercent: 40 }); + for (const strategy of STRATEGIES) { + clearGenericFailoverHealth(); + clearPoolRotationState(); + expect(rotateGenericOAuthAccountOn429(config(strategy), "xai", serving!, null)).toBeNull(); + } + expect(hasEligibleGenericOAuthFailoverTarget("xai", serving!)).toBe(false); + }); + + test("every sibling spent, including one reported in a custom window in seconds, returns null", async () => { + const [a, b, c] = await seed(3); + quota(a!, spentUntilTomorrow); + quota(c!, { customWindows: [{ label: "Monthly", percent: 100, resetAt: Math.floor((Date.now() + 48 * HOUR) / 1000) }] }); + for (const strategy of STRATEGIES) { + clearGenericFailoverHealth(); + clearPoolRotationState(); + expect(rotateGenericOAuthAccountOn429(config(strategy), "xai", b!, null)).toBeNull(); + } + }); + + test("with one spent and one healthy sibling, every strategy picks the healthy one", async () => { + const [a, b, c] = await seed(3); + for (const [spent, healthy] of [[a!, c!], [c!, a!]] as const) { + clearAccountQuotaCache("xai"); + quota(spent, spentUntilTomorrow); + quota(healthy, { weeklyPercent: 60 }); + for (const strategy of STRATEGIES) { + clearGenericFailoverHealth(); + clearPoolRotationState(); + expect(rotateGenericOAuthAccountOn429(config(strategy), "xai", b!, null)).toBe(healthy); + } + } + }); + + test("a window whose reset has passed no longer counts as spent", async () => { + const [full, serving] = await seed(2); + quota(full!, { weeklyPercent: 100, weeklyResetAt: Date.now() - 60_000 }); + expect(isAccountQuotaExhausted("xai", full!)).toBe(false); + expect(isAccountSpentForRotation("xai", full!)).toBe(false); + expect(hasEligibleGenericOAuthFailoverTarget("xai", serving!)).toBe(true); + for (const strategy of STRATEGIES) { + clearGenericFailoverHealth(); + clearPoolRotationState(); + expect(rotateGenericOAuthAccountOn429(config(strategy), "xai", serving!, null)).toBe(full!); + } + }); + + test("a spent reading with no reset time excludes only while it is fresh", async () => { + const [full, serving] = await seed(2); + quota(full!, { weeklyPercent: 100 }); + expect(rotateGenericOAuthAccountOn429(config(), "xai", serving!, null)).toBeNull(); + clearGenericFailoverHealth(); + quota(full!, { weeklyPercent: 100, updatedAt: Date.now() - 2 * HOUR }); + expect(isAccountSpentForRotation("xai", full!)).toBe(false); + expect(rotateGenericOAuthAccountOn429(config(), "xai", serving!, null)).toBe(full!); + }); + + test("a sibling with no measurement at all is still a rotation target", async () => { + const [unmeasured, serving] = await seed(2); + quota(serving!, { weeklyPercent: 100, weeklyResetAt: Date.now() + HOUR }); + expect(rotateGenericOAuthAccountOn429(config(), "xai", serving!, null)).toBe(unmeasured!); + }); +}); + +describe("#9304 first-attempt strategies prefer an unspent account", () => { + test("round-robin and fill-first do not propose a spent sibling while a healthy one exists", async () => { + const [a, b, c] = await seed(3); + await setActiveAccount("xai", b!); + quota(b!, { weeklyPercent: 90 }); + for (const [spent, healthy] of [[a!, c!], [c!, a!]] as const) { + clearAccountQuotaCache("xai"); + quota(b!, { weeklyPercent: 90 }); + quota(spent, spentUntilTomorrow); + quota(healthy, { weeklyPercent: 10 }); + clearPoolRotationState(); + expect(preferredInitialAccount(config("fill-first", true), "xai")).toBe(healthy); + for (let turn = 0; turn < 3; turn++) { + expect(preferredInitialAccount(config("round-robin", true), "xai")).not.toBe(spent); + } + } + }); + + test("committed round-robin turns keep rotating across the unspent accounts around a spent one", async () => { + const ids = await seed(4); + const spent = ids[1]!; + quota(spent, spentUntilTomorrow); + for (const id of ids) if (id !== spent) quota(id, { weeklyPercent: 10 }); + const cfg = { ...config("round-robin", true), providers: { xai: { ...XAI, + oauthAccountFailover: { enabled: true, strategy: "round-robin", stickyLimit: 1 } } } } as unknown as OcxConfig; + const served: string[] = []; + let active = ids[0]!; + await setActiveAccount("xai", active); + for (let turn = 0; turn < 6; turn++) { + const chosen = preferredInitialAccount(cfg, "xai", Date.now(), null, active) ?? active; + noteGenericPoolSelection(cfg, "xai", chosen); + served.push(chosen); + active = chosen; + } + expect(served).not.toContain(spent); + expect(new Set(served).size).toBe(3); + }); +}); From 44527209f28c7aea2ea4526d049998ad3000d4b2 Mon Sep 17 00:00:00 2001 From: Arthur tinseau <65445747+atinseau@users.noreply.github.com> Date: Thu, 3 Dec 2026 16:47:04 +0100 Subject: [PATCH 33/50] feat(desktop): keep Codex Desktop Send open while another provider has usage (#9258) * feat(desktop): keep Codex Desktop Send open while another provider has usage Codex Desktop disables Send from the ChatGPT /wham/usage snapshot alone, so an exhausted ChatGPT account blocks turns routed to other OpenCodex providers. - Clear a plain rate_limit_reached rate_limit_reached_type when correcting: Desktop 26.1120 keeps Send disabled while that reason is non-null. - Add the routed-provider-capacity activation scope: a standing policy with account-wide consent that corrects each eligible usage record only while a configured provider other than the native ChatGPT one reports remaining quota, and refreshes usage streams when that capacity changes. - desktopCompatibility.routedProviderUnlock starts it with observation; the runtime route accepts the scope. * fix(desktop): ignore failed capacity reads and report policy start failures apart - A failed routed capacity read is no longer a capacity change, so it does not close bound usage streams; each routed period starts from a fresh baseline (createRoutedCapacityWatch). - A rejected routed-provider activation at startup warns that observation is running and only the policy did not start, with a generic code. * fix(desktop): bind the routed capacity watch to the activation generation The runtime tick samples the mode once, so observe followed by a new routed activation between two ticks reused the previous activation's baseline. The watch now keys its baseline on the routed generation and discards a read that finishes under another generation. --------- Co-authored-by: JUN --- gui/src/desktop-compatibility-api.ts | 6 +- .../desktop-compatibility/routed-capacity.ts | 49 +++++++ src/codex/desktop-compatibility/runtime.ts | 18 ++- .../desktop-compatibility/startup-settings.ts | 2 +- .../desktop-compatibility/usage-activation.ts | 38 ++++-- .../desktop-compatibility/usage-controller.ts | 9 +- .../desktop-compatibility/usage-policy.ts | 5 +- src/config/schema/desktop-compatibility.ts | 10 +- .../index/desktop-compatibility-startup.ts | 8 +- .../desktop-compatibility-runtime-routes.ts | 8 +- src/types/config.ts | 7 +- structure/clients/codex-desktop.md | 30 ++++- ...ktop-compatibility-routed-capacity.test.ts | 127 ++++++++++++++++++ ...sktop-compatibility-runtime-routes.test.ts | 12 +- ...ent-desktop-compatibility-settings.test.ts | 8 ++ ...rver-desktop-compatibility-startup.test.ts | 35 ++++- 16 files changed, 340 insertions(+), 32 deletions(-) create mode 100644 src/codex/desktop-compatibility/routed-capacity.ts create mode 100644 tests/clients/desktop-compatibility-routed-capacity.test.ts diff --git a/gui/src/desktop-compatibility-api.ts b/gui/src/desktop-compatibility-api.ts index 49cd191d9ab..e4212cb9365 100644 --- a/gui/src/desktop-compatibility-api.ts +++ b/gui/src/desktop-compatibility-api.ts @@ -9,7 +9,7 @@ export interface CompatibilityRuntime { supported: boolean; phase: "off" | "starting" | "running" | "stopping" | "cleanup-required"; running: boolean; contextFailure?: "build_unverified" | "native_routing_unverified" | null; buildAssessment?: CompatibilityBuildAssessment | null; - usage?: { mode: "observe" | "apply"; phase: string; outputs: number; appCacheConfirmed: false; + usage?: { mode: "observe" | "apply" | "routed"; phase: string; outputs: number; appCacheConfirmed: false; observation?: { jsonSnapshots: number; streamSnapshots: number; validatedActiveStreams: number; lastSnapshotAt: number | null; sourceProcessVerified: false; composerRecoveryVerified: false } }; } @@ -82,10 +82,10 @@ export function parseCompatibilityRuntime(value: unknown): CompatibilityRuntime } } if (value.usage !== undefined) { - if (!object(value.usage) || typeof value.usage.mode !== "string" || !["observe", "apply"].includes(value.usage.mode) || typeof value.usage.phase !== "string" + if (!object(value.usage) || typeof value.usage.mode !== "string" || !["observe", "apply", "routed"].includes(value.usage.mode) || typeof value.usage.phase !== "string" || !/^[a-z-]{1,80}$/.test(value.usage.phase) || !Number.isSafeInteger(value.usage.outputs) || Number(value.usage.outputs) < 0 || value.usage.appCacheConfirmed !== false) throw new CompatibilityApiError("invalid_runtime_status"); - runtime.usage = { mode: value.usage.mode as "observe" | "apply", phase: value.usage.phase, outputs: value.usage.outputs as number, appCacheConfirmed: false }; + runtime.usage = { mode: value.usage.mode as "observe" | "apply" | "routed", phase: value.usage.phase, outputs: value.usage.outputs as number, appCacheConfirmed: false }; if (value.usage.observation !== undefined) { const observed = value.usage.observation; if (!object(observed) || ![observed.jsonSnapshots, observed.streamSnapshots, observed.validatedActiveStreams].every(n => Number.isSafeInteger(n) && Number(n) >= 0) diff --git a/src/codex/desktop-compatibility/routed-capacity.ts b/src/codex/desktop-compatibility/routed-capacity.ts new file mode 100644 index 00000000000..2edbb04f9f9 --- /dev/null +++ b/src/codex/desktop-compatibility/routed-capacity.ts @@ -0,0 +1,49 @@ +import type { OcxConfig } from "../../types"; +import { loadConfig } from "../../config"; +import { hasOwnProvider } from "../../config/provider-name"; +import { cachedProviderQuotaIsExhausted } from "../../combos/resolve"; +import { fetchProviderQuotaReports } from "../../providers/quota"; +import { isBuiltInChatGptForwardProvider, type ProviderQuotaReport } from "../../providers/quota/report-cache"; + +/** + * Whether a provider other than the native ChatGPT/Codex account can still serve a turn. + * Only a configured, enabled provider with a report that is not exhausted counts; a provider + * without quota evidence is unknown and never unlocks the Desktop composer. + */ +export function routedCapacityFromReports(config: Pick, reports: readonly ProviderQuotaReport[], now: number): boolean { + return reports.some(report => { + if (!hasOwnProvider(config.providers, report.provider)) return false; + const provider = config.providers[report.provider]!; + return provider.disabled !== true + && !isBuiltInChatGptForwardProvider(report.provider, provider) + && !cachedProviderQuotaIsExhausted(report.quota, now); + }); +} + +/** Reads the same provider quota reports as the dashboard (five-minute cache, upstream probe when stale). */ +export async function hasRoutedProviderCapacity(): Promise { + const config = loadConfig(); + const { reports } = await fetchProviderQuotaReports(config); + return routedCapacityFromReports(config, reports, Date.now()); +} + +/** + * Follows routed capacity across runtime ticks and refreshes usage streams only on a real change. + * `period` names the current routed activation (its generation), or null outside routed mode. + * Each activation starts from a fresh baseline, even when the mode changed between two ticks, and + * a failed probe or one that finished under another activation is not a capacity change. + */ +export function createRoutedCapacityWatch(read: () => Promise, refresh: () => Promise, + period: () => number | null, intervalMs = 30000) { + let lastCheck = 0, last: boolean | null = null, lastPeriod: number | null = null; + return async (now: number) => { + const current = period(); + if (current !== lastPeriod) { lastPeriod = current; last = null; lastCheck = 0; } + if (current === null || now - lastCheck < intervalMs) return; + lastCheck = now; + const capacity = await read().catch(() => null); + if (capacity === null || period() !== current) return; + if (last !== null && capacity !== last) await refresh(); + last = capacity; + }; +} diff --git a/src/codex/desktop-compatibility/runtime.ts b/src/codex/desktop-compatibility/runtime.ts index 3a606b3cc9e..2a2a45f5006 100644 --- a/src/codex/desktop-compatibility/runtime.ts +++ b/src/codex/desktop-compatibility/runtime.ts @@ -10,6 +10,8 @@ import { inspectDesktopCompatibilityAuthority, loadDesktopCompatibilityAuthority import { inspectWindowsCertificateTrust } from "./windows-certificate-trust"; import { createNativeIdentityReader } from "./native-identity"; import { UsageRelayController, type UsageIdentity } from "./usage-controller"; +import type { ApplyScope } from "./usage-activation"; +import { createRoutedCapacityWatch, hasRoutedProviderCapacity } from "./routed-capacity"; import { createUsageControlledFetch } from "./usage-controlled-fetch"; import { startDesktopRelay } from "./relay-listener"; import { launchWindowsCodexCompatibilityAsync } from "./windows-package-launch"; @@ -30,6 +32,8 @@ export interface DesktopRuntimeIo { upstreamFetch?: typeof fetch; connectionStore?: DesktopConnectionStore; routingSupported?: () => boolean; + /** Whether another OpenCodex provider still has usage; defaults to the provider quota reports. */ + routedCapacity?: () => Promise; /** Synthetic-test execution is admitted only with explicit fixture identity and CA seams. */ testOnly?: boolean; } @@ -37,6 +41,7 @@ export interface DesktopRuntimeIo { /** Optional runtime. Import/construction/status do not start listeners or touch credentials. */ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) { const platform = io.platform ?? process.platform; + const routedCapacity = io.routedCapacity ?? (() => hasRoutedProviderCapacity()); let buildProbe: ReturnType | undefined; let previousBuildAssessment: DesktopBuildAssessment | null = null; let boundBuild: { probe: ReturnType; revision: number } | null = null; @@ -141,7 +146,7 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) { const account: UsageIdentity | null = await identity.verifyFreshIdentity(); if (!account) throw new Error("desktop_compatibility_native_identity_unverified"); if (didRunOptionalShutdownHooks()) throw new Error("desktop_compatibility_stopping"); - controller = new UsageRelayController(account, identity.readCurrentIdentity, identity.verifyFreshIdentity, Date.now, deadline, 180000, contextValid); + controller = new UsageRelayController(account, identity.readCurrentIdentity, identity.verifyFreshIdentity, Date.now, deadline, 180000, contextValid, routedCapacity); const trialController = controller; invalidateTrial = () => trialController.invalidateContext(); relay = await startDesktopRelay({ leaf: issueServerLeaf(authority.authority, authority.commonName, ["chatgpt.com"]), @@ -159,6 +164,12 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) { if (connection.id !== runId || connection.connectPort !== proxyPort || connection.pacPort !== pac.port) throw new Error("desktop_compatibility_connection_changed"); if (didRunOptionalShutdownHooks()) throw new Error("desktop_compatibility_stopping"); const active = controller; let ticking = false, deadlineHandled = false, lastContextCheck = Date.now(); + // A routed policy follows capacity changes: closing bound usage streams makes the app + // fetch a snapshot that is corrected, or left original, for the current capacity. + const watchCapacity = createRoutedCapacityWatch(routedCapacity, () => active.refreshRouted(), () => { + const usage = active.snapshot(); + return usage.mode === "routed" ? usage.generation : null; + }); timer = setInterval(() => { if (ticking) return; ticking = true; const expired = Date.now() >= deadline; @@ -168,6 +179,7 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) { lastContextCheck = Date.now(); if (!await contextValid() && active.snapshot().mode === "apply") { await active.observeOnly(); return; } } + if (!expired) await watchCapacity(Date.now()); await (expired && !deadlineHandled ? (deadlineHandled = true, active.observeOnly()) : active.expireIfNeeded()); })(); void work.catch(() => {}).finally(() => { ticking = false; }); @@ -194,14 +206,14 @@ export function createDesktopCompatibilityRuntime(io: DesktopRuntimeIo = {}) { throw error; } } - async function apply(accountWideConsent: boolean) { + async function apply(accountWideConsent: boolean, scope: ApplyScope = "account-ui-compatibility") { const current = owned; if (!current || phase !== "running") throw new Error("desktop_compatibility_not_running"); const generation = current.controller.snapshot().generation, valid = await contextValid(); if (owned !== current || phase !== "running") throw new Error("desktop_compatibility_not_running"); if (!valid) { await current.controller.observeOnly(); throw new Error(`desktop_compatibility_${contextFailure}`); } if (generation !== current.controller.snapshot().generation) return { accepted: false, reason: "superseded", ...current.controller.snapshot() }; - const result = await current.controller.activate({ scope: "account-ui-compatibility", accountWideConsent }); + const result = await current.controller.activate({ scope, accountWideConsent }); if (owned !== current || phase !== "running") { await current.controller.observeOnly(); return { ...result, accepted: false, reason: "runtime-stopped" }; } return result; } diff --git a/src/codex/desktop-compatibility/startup-settings.ts b/src/codex/desktop-compatibility/startup-settings.ts index 4ffba406b89..2bb34d3cc97 100644 --- a/src/codex/desktop-compatibility/startup-settings.ts +++ b/src/codex/desktop-compatibility/startup-settings.ts @@ -31,7 +31,7 @@ export function createDesktopStartupSettings(io: SettingsIo = {}) { const current = status(); if (current.revision !== expectedRevision) throw failure("changed"); if (current.startOnProxyStart === startOnProxyStart) return { changed: false, value: startOnProxyStart }; - config.desktopCompatibility = { startOnProxyStart }; + config.desktopCompatibility = { ...config.desktopCompatibility, startOnProxyStart }; return { changed: true, value: startOnProxyStart }; }); } catch (error) { // Publication can succeed before bookkeeping fails. Reconcile a verified disk diff --git a/src/codex/desktop-compatibility/usage-activation.ts b/src/codex/desktop-compatibility/usage-activation.ts index bf090dcf6cd..20ff73ab0fe 100644 --- a/src/codex/desktop-compatibility/usage-activation.ts +++ b/src/codex/desktop-compatibility/usage-activation.ts @@ -1,9 +1,14 @@ /** Account-bound, time-limited compatibility activation; no persistent settings or timers. */ export type Observation = 'exhausted' | 'available' | 'protected'; -export type ApplyScope = 'selected-external-model' | 'account-ui-compatibility'; +/** + * `account-ui-compatibility` is the short trial after a fresh exhaustion observation. + * `routed-provider-capacity` is a standing policy: each response is corrected only while + * another OpenCodex provider reports remaining usage, so it has no trial deadline. + */ +export type ApplyScope = 'selected-external-model' | 'account-ui-compatibility' | 'routed-provider-capacity'; type RefreshResult = {requested:number;closed:number;failed:number}; export class UsageActivation { - private mode: 'observe' | 'apply' = 'observe'; + private mode: 'observe' | 'apply' | 'routed' = 'observe'; private phase = 'observing'; private generation = 0; private latest: { kind:Observation; at:number } | null = null; @@ -35,19 +40,25 @@ export class UsageActivation { return this.refresh(this.binding); } async activate(options:{scope:ApplyScope;accountWideConsent:boolean}) { - if(options.scope!=='account-ui-compatibility')return{accepted:false,reason:'selected-model-scope-unavailable',...this.snapshot()}; + const routed=options.scope==='routed-provider-capacity'; + if(!routed&&options.scope!=='account-ui-compatibility')return{accepted:false,reason:'selected-model-scope-unavailable',...this.snapshot()}; if(!options.accountWideConsent)return{accepted:false,reason:'account-wide-scope-not-accepted',...this.snapshot()}; const beforeVerification=this.generation,binding=this.binding; let verified:string|null; try{verified=await this.verifyIdentity();}catch{verified=null;} if(this.binding!==binding||this.generation!==beforeVerification)return{accepted:false,reason:'identity-not-verified',...this.snapshot()}; if(verified!==binding){this.invalidateIdentity();return{accepted:false,reason:'identity-not-verified',...this.snapshot()};} - if(this.mode==='apply')return{accepted:false,reason:'activation-already-pending',...this.snapshot()}; - const age=this.latest?this.clock()-this.latest.at:Infinity; - if(!this.latest||this.latest.kind!=='exhausted'||age<0||age>300000)return{accepted:false,reason:'no-fresh-eligible-exhaustion',...this.snapshot()}; - // An exhausted observation authorizes one trial, not every retry within its TTL. - this.latest=null; - this.mode='apply';this.phase='awaiting-fresh-usage';this.startedAt=this.clock();this.outputs=0; + if(this.mode!=='observe')return{accepted:false,reason:'activation-already-pending',...this.snapshot()}; + if(routed){ + // The standing policy decides per response, so it neither needs nor consumes an observation. + this.mode='routed';this.phase='routed-awaiting-fresh-usage';this.startedAt=null;this.outputs=0; + } else { + const age=this.latest?this.clock()-this.latest.at:Infinity; + if(!this.latest||this.latest.kind!=='exhausted'||age<0||age>300000)return{accepted:false,reason:'no-fresh-eligible-exhaustion',...this.snapshot()}; + // An exhausted observation authorizes one trial, not every retry within its TTL. + this.latest=null; + this.mode='apply';this.phase='awaiting-fresh-usage';this.startedAt=this.clock();this.outputs=0; + } const generation=++this.generation; let refreshed:RefreshResult; try { refreshed=await this.refresh(this.binding); } @@ -68,10 +79,17 @@ export class UsageActivation { return{accepted:true,reason:'awaiting-new-response',refresh:refreshed,...this.snapshot()}; } recordOutput(binding:string,generation:number) { - if(binding!==this.binding||generation!==this.generation||this.mode!=='apply')return false; + if(binding!==this.binding||generation!==this.generation)return false; + if(this.mode==='routed'){++this.outputs;this.phase='routed-response-produced-app-confirmation-needed';return true;} + if(this.mode!=='apply')return false; if(this.startedAt===null||this.clock()-this.startedAt<0||this.clock()-this.startedAt>=this.timeoutMs)return false; ++this.outputs;this.phase='response-produced-app-confirmation-needed';return true; } + /** Close bound usage streams so the app reads a snapshot that matches current routed capacity. */ + async refreshRouted() { + if(this.mode!=='routed')return null; + return this.refresh(this.binding); + } async expireIfNeeded() { if(this.startedAt===null||this.clock()-this.startedAt=0)return false; await this.reset('expired-awaiting-original-response');return true; diff --git a/src/codex/desktop-compatibility/usage-controller.ts b/src/codex/desktop-compatibility/usage-controller.ts index bc6d43e7551..0314c1e4031 100644 --- a/src/codex/desktop-compatibility/usage-controller.ts +++ b/src/codex/desktop-compatibility/usage-controller.ts @@ -22,7 +22,8 @@ export class UsageRelayController { private lastSnapshotAt: number | null = null; constructor(account: UsageIdentity, private readonly readCurrentIdentity: () => Promise, verifyFreshIdentity: () => Promise, private readonly clock: () => number, - private readonly expiresAt: number, timeoutMs = 180000, private readonly contextValid: () => boolean | Promise = () => true) { + private readonly expiresAt: number, timeoutMs = 180000, private readonly contextValid: () => boolean | Promise = () => true, + private readonly routedCapacity: () => Promise = async () => false) { if (!account.id || !account.userId || !['plus', 'pro'].includes(account.plan) || account.structure !== 'personal' || !Number.isFinite(expiresAt) || expiresAt <= clock()) { throw new Error('A verified supported identity and finite safety deadline are required'); @@ -38,6 +39,7 @@ export class UsageRelayController { validatedActiveStreams: this.refresh.boundSize, lastSnapshotAt: this.lastSnapshotAt, sourceProcessVerified: false as const, composerRecoveryVerified: false as const } }; } private async checkContext() { try { return await this.contextValid(); } catch { return false; } } + private async hasRoutedCapacity() { try { return await this.routedCapacity(); } catch { return false; } } async activate(options: { scope: ApplyScope; accountWideConsent: boolean }) { const generation = this.activation.snapshot().generation, valid = await this.checkContext(); if (generation !== this.activation.snapshot().generation) return { accepted: false, reason: 'superseded', ...this.snapshot() }; @@ -46,6 +48,7 @@ export class UsageRelayController { return this.activation.activate(options); } observeOnly() { return this.activation.observeOnly(); } + refreshRouted() { return this.activation.refreshRouted(); } /** Internal package-proof revocation; synchronous so pending output loses its generation first. */ invalidateContext() { this.activation.invalidateIdentity(); } expireIfNeeded() { return this.activation.expireIfNeeded(); } @@ -97,9 +100,11 @@ export class UsageRelayController { this.activation.observe(this.key, observed.eligible ? 'exhausted' : rate.allowed === true && rate.limit_reached === false ? 'available' : 'protected'); const state = this.activation.snapshot(); - if (state.mode !== 'apply') return null; + if (state.mode === 'observe') return null; const result = evaluateUsageRewrite(original, { ...context, mode: 'apply' }); if (!result.changed) return null; + // The standing policy corrects a record only while another provider still has usage. + if (state.mode === 'routed' && !await this.hasRoutedCapacity()) return null; // Observe and unchanged responses never spawn an installed-package probe. const valid = await this.checkContext(); if (state.generation !== this.activation.snapshot().generation) return null; diff --git a/src/codex/desktop-compatibility/usage-policy.ts b/src/codex/desktop-compatibility/usage-policy.ts index 4cdb1a0ee22..6ba4bdc9d7e 100644 --- a/src/codex/desktop-compatibility/usage-policy.ts +++ b/src/codex/desktop-compatibility/usage-policy.ts @@ -52,8 +52,11 @@ export function evaluateUsageRewrite(value: unknown, context: UsageRewriteContex && additional.some(limit => record(limit) && limit.limit_name === 'gpt-reserve' && record(limit.rate_limit) && limit.rate_limit.allowed === true)) return unchanged('reserve-active'); if (context.mode !== 'apply') return { value, changed: false, eligible: true, reason: 'observe-only' }; + // Codex Desktop 26.1120 also blocks Send while `rate_limit_reached_type` is non-null, even + // when `rate_limit` allows usage. Only the plain quota reason reaches this point. + const clearedReason = reason != null ? { rate_limit_reached_type: null } : {}; return { - value: { ...value, rate_limit: { ...rate, allowed: true, limit_reached: false } }, + value: { ...value, rate_limit: { ...rate, allowed: true, limit_reached: false }, ...clearedReason }, changed: true, eligible: true, reason: 'personal-usage-only', }; } diff --git a/src/config/schema/desktop-compatibility.ts b/src/config/schema/desktop-compatibility.ts index 492404de717..55228de1689 100644 --- a/src/config/schema/desktop-compatibility.ts +++ b/src/config/schema/desktop-compatibility.ts @@ -1,9 +1,13 @@ import * as z from "zod/v4"; -/** Startup resumes observation only. Certificate trust, app launch and Apply are never saved here. */ -export const desktopCompatibilitySchema = z.object({ startOnProxyStart: z.boolean() }).strict(); +/** + * Startup resumes observation. `routedProviderUnlock` additionally starts the standing policy that + * corrects the usage gate only while another provider has usage. Certificate trust, app launch and + * the short account-wide trial are never saved here. + */ +export const desktopCompatibilitySchema = z.object({ startOnProxyStart: z.boolean(), routedProviderUnlock: z.boolean().optional() }).strict(); export function desktopCompatibilityConfigError(value: unknown): string | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const setting = (value as Record).desktopCompatibility; return setting === undefined || desktopCompatibilitySchema.safeParse(setting).success - ? null : "schema_invalid: desktopCompatibility: requires only boolean startOnProxyStart"; + ? null : "schema_invalid: desktopCompatibility: requires boolean startOnProxyStart and optional boolean routedProviderUnlock"; } diff --git a/src/server/index/desktop-compatibility-startup.ts b/src/server/index/desktop-compatibility-startup.ts index a80bf1f5d58..b1da1c3be94 100644 --- a/src/server/index/desktop-compatibility-startup.ts +++ b/src/server/index/desktop-compatibility-startup.ts @@ -47,7 +47,13 @@ export function scheduleDesktopCompatibilityStartup(config: OcxConfig, io: Start } module = await (io.load?.() ?? import("../../codex/desktop-compatibility/service")); if (stopped) return; - await module.getDesktopCompatibilityRuntime().start(); + const runtime = module.getDesktopCompatibilityRuntime(); + await runtime.start(); + if (stopped || config.desktopCompatibility?.routedProviderUnlock !== true) return; + // Observation is running here, so an activation failure must not be reported as a start failure. + const refusal = await runtime.apply(true, "routed-provider-capacity") + .then(activation => activation.accepted ? null : activation.reason, () => "activation-failed"); + if (refusal) (io.warn ?? console.warn)(`Desktop compatibility is observing, but the routed-provider usage policy did not start (${refusal}).`); }).catch(() => { (io.warn ?? console.warn)("Desktop compatibility observation did not start. Inspect Desktop compatibility status; no automatic trust or correction was applied."); }) : Promise.resolve(); return { async shutdown() { stopped = true; cancelReadiness?.(); unbind(); await pending; diff --git a/src/server/management/desktop-compatibility-runtime-routes.ts b/src/server/management/desktop-compatibility-runtime-routes.ts index 24b51dcd2d6..38f4861d013 100644 --- a/src/server/management/desktop-compatibility-runtime-routes.ts +++ b/src/server/management/desktop-compatibility-runtime-routes.ts @@ -14,15 +14,19 @@ export async function handleDesktopCompatibilityRuntimeRoutes(ctx: ManagementCon if (ctx.req.method !== "GET" && ctx.req.method !== "POST") return jsonResponse({ error: "method_not_allowed" }, 405); if (ctx.req.method === "POST") { const denied = requireDesktopAuthorization(ctx); if (denied) return denied; } let action: "start" | "stop" | "observe" | "apply" | "launch" | undefined; + let scope: "account-ui-compatibility" | "routed-provider-capacity" = "account-ui-compatibility"; if (ctx.req.method === "POST") { let body: unknown; try { body = await readManagementJsonBody(ctx.req); } catch (error) { rethrowManagementBodyTooLarge(error); return jsonResponse({ error: "invalid_json" }, 400); } if (!body || typeof body !== "object" || Array.isArray(body)) return jsonResponse({ error: "invalid_request" }, 400); const value = body as Record; - if (Object.keys(value).some(key => !["action", "confirmed", "accountWideConsent"].includes(key)) || value.confirmed !== true + if (Object.keys(value).some(key => !["action", "confirmed", "accountWideConsent", "scope"].includes(key)) || value.confirmed !== true || typeof value.action !== "string" || !["start", "stop", "observe", "apply", "launch"].includes(value.action)) return jsonResponse({ error: "invalid_request" }, 400); if (value.action === "apply" ? value.accountWideConsent !== true : value.accountWideConsent !== undefined) return jsonResponse({ error: "invalid_consent_scope" }, 400); + if (value.scope !== undefined && (value.action !== "apply" + || (value.scope !== "account-ui-compatibility" && value.scope !== "routed-provider-capacity"))) return jsonResponse({ error: "invalid_consent_scope" }, 400); + if (value.scope !== undefined) scope = value.scope as typeof scope; action = value.action as typeof action; } const module = ctx.deps.desktopCompatibilityRuntime ? null : await import("../../codex/desktop-compatibility/service"); @@ -31,7 +35,7 @@ export async function handleDesktopCompatibilityRuntimeRoutes(ctx: ManagementCon if (module) ctx.deps.onDesktopCompatibilityShutdown?.(module.shutdownDesktopCompatibility); try { if (action === "apply") { - const result = await service.apply(true); + const result = await service.apply(true, scope); return jsonResponse({ ok: result.accepted, activation: result, runtime: service.status() }, result.accepted ? 202 : 409); } if (action === "launch") { diff --git a/src/types/config.ts b/src/types/config.ts index f073af25e0a..885e8cd58d3 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -888,8 +888,11 @@ export interface OcxConfig extends OcxLinkHomeConfig, CodexAccountLoginConfig { /** Per-root fan-out ceilings (src/lib/workflow-budget.ts); omitted fields keep 8 / 256 / 64. */ workflowBudget?: { maxConcurrentChildren?: number; maxPhysicalSends?: number; maxDistinctChildren?: number }; routedCatalogDefaults?: import("./routed-catalog-defaults").OcxRoutedCatalogDefaultsConfig; // #6872; provider/model declarations win - /** Explicit opt-in; resumes Observe only using an existing trusted certificate and endpoints. */ - desktopCompatibility?: { startOnProxyStart: boolean }; + /** + * Explicit opt-in; resumes Observe using an existing trusted certificate and endpoints. + * `routedProviderUnlock` then corrects the Desktop usage gate while another provider has usage. + */ + desktopCompatibility?: { startOnProxyStart: boolean; routedProviderUnlock?: boolean }; /** * Destination model for Codex's own memory pipeline, per phase * (src/server/responses/memory-models.ts). diff --git a/structure/clients/codex-desktop.md b/structure/clients/codex-desktop.md index 9ec63e172ff..99d380fa155 100644 --- a/structure/clients/codex-desktop.md +++ b/structure/clients/codex-desktop.md @@ -191,7 +191,9 @@ If both publication and temporary-file cleanup fail, the cleanup-required error `usage-controller.ts`, `usage-activation.ts` and `usage-policy.ts` implement a maximum three-minute, explicitly confirmed account-UI trial after a fresh supported exhaustion snapshot. They cannot assert selected-provider isolation. Two usage gate booleans may -change; quota windows, credits, spending limits and other responses remain original. +change, and a plain `rate_limit_reached` value of `rate_limit_reached_type` becomes `null`, +because Codex Desktop 26.1120 keeps Send disabled while that reason is present; quota windows, +credits, spending limits and other responses remain original. An original available or protected usage record disarms Apply and advances its generation. Available credits, unlimited credits and active Luna Reserve are ineligible for correction even when the ordinary rate limit is exhausted. Their original snapshots disarm Apply too; unknown @@ -219,6 +221,22 @@ They never establish a source PID, authoritative gate coverage or composer recov not advance these counters. Conversation initialization and other non-WHAM endpoints retain their original response bytes, including `blocked_features` and `limits_progress`. +The `routed-provider-capacity` activation scope is a standing alternative to that trial for an +exhausted ChatGPT account whose user routes turns to other OpenCodex providers. It needs the same +account-wide consent and identity check but no exhaustion observation, and it has no trial +deadline. Each eligible record is corrected only while `routed-capacity.ts` finds a configured, +enabled provider other than the native ChatGPT forward provider whose provider quota report is not +exhausted; it reads the dashboard's provider quota reports, so a provider without quota evidence +never counts. Otherwise the original record passes. The runtime rechecks capacity every 30 seconds +and closes bound usage streams when it changes, so the app reads a matching snapshot. A failed +capacity read is not a change. The watch is bound to the activation generation, so each routed +activation starts from a fresh baseline even when observation and a new activation both happen +between two ticks, and a read that finishes under another generation is discarded. Recovery, +protected observations and later exhaustion do not end the policy; observation, Stop, an identity, +package or routing change, and the certificate deadline do. The correction remains account-wide: +GPT turns submitted while it is active still reach the exhausted account and fail upstream. +`tests/clients/desktop-compatibility-routed-capacity.test.ts` covers the policy. + `routing-binding.ts` records the server's actual bound data/companion ports. Shutdown unregisters only its matching owner. `routing-preflight.ts` verifies bounded native root TOML and any selected root profile against those ports, rejecting foreign providers, @@ -301,7 +319,9 @@ a failed cleanup retains ownership and reports `cleanup-required`, never a false current local GUI-session POST start/stop/observe/apply/launch with Desktop scope, explicit confirmation and separate account-wide consent for apply. That session is refused until it consumes a Desktop-purpose grant. No setting, login, quota, automatic startup or dashboard preference is -changed by this API. The separate startup preference below never saves Apply. +changed by this API. The separate startup preference below never saves the short trial. +An `apply` body may name `scope: "routed-provider-capacity"` to start the standing policy; the +default remains the short `account-ui-compatibility` trial. The status CLI verb remains deferred to this integration owner. ## Dashboard controls @@ -343,6 +363,12 @@ When the CLI supplies its readiness gate, observation waits for post-startup nat sync before loading its runtime. A failed sync or a two-minute pending limit leaves observation off with a generic diagnostic; shutdown cancels this optional wait without delaying proxy exit. +`desktopCompatibility.routedProviderUnlock` is a separate opt-in boolean. When it is true and +observation starts, startup activates the `routed-provider-capacity` policy with account-wide +consent; a refusal or activation error leaves observation running and warns that only the policy +did not start, with the refusal reason or a generic `activation-failed` code. It changes +nothing when observation does not start, and the dashboard startup toggle preserves it. + `service.ts` shares one runtime between startup and management. Server shutdown retains the asynchronous teardown, waits for in-flight startup, and prevents a late start after stop. The saved preference does not launch Codex, enroll or renew certificates, or resume a trial. diff --git a/tests/clients/desktop-compatibility-routed-capacity.test.ts b/tests/clients/desktop-compatibility-routed-capacity.test.ts new file mode 100644 index 00000000000..8c63cca8a8f --- /dev/null +++ b/tests/clients/desktop-compatibility-routed-capacity.test.ts @@ -0,0 +1,127 @@ +import { describe, expect, test } from "bun:test"; +import { evaluateUsageRewrite } from "../../src/codex/desktop-compatibility/usage-policy"; +import { UsageActivation } from "../../src/codex/desktop-compatibility/usage-activation"; +import { UsageRelayController, type UsageIdentity } from "../../src/codex/desktop-compatibility/usage-controller"; +import { createRoutedCapacityWatch, routedCapacityFromReports } from "../../src/codex/desktop-compatibility/routed-capacity"; +import { CODEX_FORWARD_BASE_URL } from "../../src/providers/openai-forward-destination"; +import type { ProviderQuotaReport } from "../../src/providers/quota/report-cache"; +import type { OcxProviderConfig } from "../../src/types"; + +const account: UsageIdentity = { id: "fixture-account", userId: "fixture-user", plan: "pro", structure: "personal" }; +// Shape of a real exhausted Pro snapshot as read by Codex Desktop 26.1120. +const usage = { account_id: account.id, user_id: account.userId, plan_type: "pro", + rate_limit: { allowed: false, limit_reached: true, primary_window: { used_percent: 100, reset_at: 123456 } }, + rate_limit_reached_type: { type: "rate_limit_reached", details: "default" }, + spend_control: { reached: false }, credits: { has_credits: false, unlimited: false, overage_limit_reached: false } }; +const exchange = { method: "GET", pathname: "/backend-api/wham/usage", status: 200 }; +const routed = { scope: "routed-provider-capacity" as const, accountWideConsent: true }; +const corrected = { ...usage, rate_limit: { ...usage.rate_limit, allowed: true, limit_reached: false }, rate_limit_reached_type: null }; + +describe("usage gate correction", () => { + test("clears the plain quota reason that the current Desktop gate also reads", () => { + const result = evaluateUsageRewrite(usage, { enabled: true, mode: "apply", status: 200, pathname: exchange.pathname, account }); + expect(result).toMatchObject({ changed: true, value: corrected }); + expect(usage.rate_limit_reached_type).toEqual({ type: "rate_limit_reached", details: "default" }); + }); + test("keeps an absent reason absent and leaves other reasons protected", () => { + const { rate_limit_reached_type: _reason, ...withoutReason } = usage; + const result = evaluateUsageRewrite(withoutReason, { enabled: true, mode: "apply", status: 200, pathname: exchange.pathname, account }); + expect(result.changed).toBe(true); expect("rate_limit_reached_type" in (result.value as object)).toBe(false); + const workspace = { ...usage, rate_limit_reached_type: { type: "workspace_owner_credits_depleted" } }; + expect(evaluateUsageRewrite(workspace, { enabled: true, mode: "apply", status: 200, pathname: exchange.pathname, account }).changed).toBe(false); + }); +}); + +describe("routed provider capacity policy", () => { + test("starts without an exhaustion observation, never expires and survives recovery", async () => { + let now = 1000, refreshes = 0; + const activation = new UsageActivation("account", async () => { refreshes++; return { requested: 1, closed: 1, failed: 0 }; }, + async () => "account", () => now); + expect(await activation.activate({ ...routed, accountWideConsent: false })).toMatchObject({ accepted: false, reason: "account-wide-scope-not-accepted" }); + expect(await activation.activate(routed)).toMatchObject({ accepted: true, mode: "routed" }); expect(refreshes).toBe(1); + expect((await activation.activate(routed)).reason).toBe("activation-already-pending"); + now += 3_600_000; + expect(await activation.expireIfNeeded()).toBe(false); + activation.observe("account", "available"); activation.observe("account", "protected"); + expect(activation.snapshot().mode).toBe("routed"); + expect(activation.recordOutput("account", activation.snapshot().generation)).toBe(true); + await activation.refreshRouted(); expect(refreshes).toBe(2); + await activation.observeOnly(); expect(activation.snapshot().mode).toBe("observe"); + expect(await activation.refreshRouted()).toBeNull(); expect(refreshes).toBe(3); + }); + test("an identity change revokes the standing policy", async () => { + const activation = new UsageActivation("account", async () => ({ requested: 0, closed: 0, failed: 0 }), async () => "account", () => 1000); + await activation.activate(routed); + const generation = activation.snapshot().generation; + activation.invalidateIdentity(); + expect(activation.snapshot().mode).toBe("observe"); expect(activation.recordOutput("account", generation)).toBe(false); + }); + test("corrects a usage record only while another provider has usage", async () => { + let capacity: boolean | Error = true; + const ctl = new UsageRelayController(account, async () => account, async () => account, () => 1000, 10_000_000, 180000, () => true, + async () => { if (capacity instanceof Error) throw capacity; return capacity; }); + expect(await ctl.rewriteJson(JSON.stringify(usage), exchange)).toBeNull(); + expect((await ctl.activate(routed)).accepted).toBe(true); + expect(JSON.parse((await ctl.rewriteJson(JSON.stringify(usage), exchange))!)).toEqual(corrected); + capacity = false; expect(await ctl.rewriteJson(JSON.stringify(usage), exchange)).toBeNull(); + capacity = new Error("quota read failed"); expect(await ctl.rewriteJson(JSON.stringify(usage), exchange)).toBeNull(); + capacity = true; + expect(await ctl.rewriteJson(JSON.stringify({ ...usage, spend_control: { reached: true } }), exchange)).toBeNull(); + expect(ctl.snapshot()).toMatchObject({ mode: "routed", outputs: 1 }); + }); +}); + +describe("routed capacity evidence", () => { + const now = 1_000_000; + const providers: Record = { + openai: { adapter: "openai-responses", authMode: "forward", baseUrl: CODEX_FORWARD_BASE_URL }, + anthropic: { adapter: "anthropic", authMode: "oauth" }, + paused: { adapter: "anthropic", authMode: "oauth", disabled: true }, + } as Record; + const report = (provider: string, weeklyPercent: number): ProviderQuotaReport => ({ provider, label: provider, source: "fixture", + quota: { weeklyPercent, weeklyResetAt: now + 60_000, updatedAt: now }, updatedAt: now }); + test("only an enabled provider other than the native ChatGPT account counts", () => { + expect(routedCapacityFromReports({ providers }, [report("openai", 10)], now)).toBe(false); + expect(routedCapacityFromReports({ providers }, [report("paused", 10)], now)).toBe(false); + expect(routedCapacityFromReports({ providers }, [report("removed", 10)], now)).toBe(false); + expect(routedCapacityFromReports({ providers }, [report("openai", 100), report("anthropic", 47)], now)).toBe(true); + }); + test("an exhausted or unreported provider does not count", () => { + expect(routedCapacityFromReports({ providers }, [report("anthropic", 100)], now)).toBe(false); + expect(routedCapacityFromReports({ providers }, [], now)).toBe(false); + }); +}); + +describe("routed capacity watch", () => { + test("refreshes only on a real change, ignores failed reads and rebaselines each routed period", async () => { + const reads: (boolean | Error)[] = [true, new Error("quota read failed"), true, false, false, true]; + let refreshes = 0, period: number | null = 1; + const watch = createRoutedCapacityWatch(async () => { + const next = reads.shift()!; + if (next instanceof Error) throw next; + return next; + }, async () => { refreshes++; }, () => period, 30); + await watch(100); expect(refreshes).toBe(0); + await watch(110); expect(reads).toHaveLength(5); + await watch(130); expect(refreshes).toBe(0); + await watch(160); expect(refreshes).toBe(0); + await watch(190); expect(refreshes).toBe(1); + period = null; await watch(200); + period = 3; await watch(210); expect(refreshes).toBe(1); + await watch(240); expect(refreshes).toBe(2); + }); + test("a new activation between two ticks, or during a read, never reuses the old baseline", async () => { + let refreshes = 0, period: number | null = 1, capacity = true; + let duringRead: (() => void) | null = null; + const watch = createRoutedCapacityWatch(async () => { duringRead?.(); return capacity; }, async () => { refreshes++; }, () => period, 30); + await watch(100); + capacity = false; period = 3; + await watch(200); expect(refreshes).toBe(0); + capacity = true; duringRead = () => { period = 5; }; + await watch(300); expect(refreshes).toBe(0); + duringRead = null; + await watch(400); capacity = false; + await watch(500); expect(refreshes).toBe(1); + }); +}); + diff --git a/tests/server/management-desktop-compatibility-runtime-routes.test.ts b/tests/server/management-desktop-compatibility-runtime-routes.test.ts index bd97d63b0de..3623ce22b64 100644 --- a/tests/server/management-desktop-compatibility-runtime-routes.test.ts +++ b/tests/server/management-desktop-compatibility-runtime-routes.test.ts @@ -30,10 +30,20 @@ test("remote/admin-token callers and ambiguous scope cannot start or alter runti expect((await handleDesktopCompatibilityRuntimeRoutes(io.ctx))?.status).toBe(403); expect(io.calls).toEqual([]); } for (const body of [{ action: "start" }, { action: ["start"], confirmed: true }, { action: "apply", confirmed: true }, - { action: "start", confirmed: true, accountWideConsent: true }, { action: "start", confirmed: true, model: "fixture" }]) { + { action: "start", confirmed: true, accountWideConsent: true }, { action: "start", confirmed: true, model: "fixture" }, + { action: "start", confirmed: true, scope: "routed-provider-capacity" }, + { action: "apply", confirmed: true, accountWideConsent: true, scope: "selected-external-model" }]) { const io = fixture("POST", body); expect((await handleDesktopCompatibilityRuntimeRoutes(io.ctx))?.status).toBe(400); expect(io.calls).toEqual([]); } }); +test("apply forwards the requested consent scope and defaults to the short trial", async () => { + for (const [scope, expected] of [[undefined, "account-ui-compatibility"], ["routed-provider-capacity", "routed-provider-capacity"]] as const) { + const io = fixture("POST", { action: "apply", confirmed: true, accountWideConsent: true, ...(scope ? { scope } : {}) }); + io.runtime.apply = async (...args) => { io.calls.push(`apply:${args.join(",")}`); return { accepted: true, reason: "fixture" } as Awaited>; }; + expect((await handleDesktopCompatibilityRuntimeRoutes(io.ctx))?.status).toBe(202); + expect(io.calls).toEqual([`apply:true,${expected}`]); + } +}); test("runtime failures report safe codes and never leak subprocess or credential data", async () => { const io = fixture("POST", { action: "start", confirmed: true }); io.runtime.start = async () => { throw new Error("synthetic-private-data"); }; diff --git a/tests/server/management-desktop-compatibility-settings.test.ts b/tests/server/management-desktop-compatibility-settings.test.ts index 8a76e7dc8b6..23b670a6b82 100644 --- a/tests/server/management-desktop-compatibility-settings.test.ts +++ b/tests/server/management-desktop-compatibility-settings.test.ts @@ -79,3 +79,11 @@ test("management dispatcher enforces local confirmation and reads back the saved const response = await handleManagementAPI(ctx.req, ctx.url, ctx.config as OcxConfig, ctx.deps, "gui-session", ctx.sessionControl, { trustedLoopback: true }); expect(response?.status).toBe(200); expect((await response!.json()).settings).toEqual(service.status()); expect(service.status().startOnProxyStart).toBe(true); }); + +test("toggling the startup preference keeps the routed-provider policy preference", () => { + write({ ...initial, desktopCompatibility: { startOnProxyStart: true, routedProviderUnlock: true } }); + const service = createDesktopStartupSettings(); + service.set(false, service.status().revision); + expect(read().desktopCompatibility).toEqual({ startOnProxyStart: false, routedProviderUnlock: true }); +}); + diff --git a/tests/server/server-desktop-compatibility-startup.test.ts b/tests/server/server-desktop-compatibility-startup.test.ts index d479d9dbb6c..d78fe283e55 100644 --- a/tests/server/server-desktop-compatibility-startup.test.ts +++ b/tests/server/server-desktop-compatibility-startup.test.ts @@ -19,7 +19,9 @@ test("startup preference is absent by default, strict for writes and safely disa expect(getDefaultConfig().desktopCompatibility).toBeUndefined(); const valid = { ...getDefaultConfig(), desktopCompatibility: { startOnProxyStart: true } }; expect(validateConfigCandidate(valid).ok).toBe(true); - for (const setting of [{ startOnProxyStart: "true" }, { startOnProxyStart: true, apply: true }, { enabled: true }]) { + expect(validateConfigCandidate({ ...valid, desktopCompatibility: { startOnProxyStart: true, routedProviderUnlock: true } }).ok).toBe(true); + for (const setting of [{ startOnProxyStart: "true" }, { startOnProxyStart: true, apply: true }, { enabled: true }, + { startOnProxyStart: true, routedProviderUnlock: "true" }]) { const value = { ...getDefaultConfig(), desktopCompatibility: setting }; expect(validateConfigCandidate(value).ok).toBe(false); expect(configSchema.parse(value).desktopCompatibility).toBeUndefined(); } @@ -109,3 +111,34 @@ test("failed or timed-out readiness leaves optional observation off", async () = expect(loads).toBe(0); expect(warnings).toHaveLength(1); } }); + +test("the routed-provider preference starts the standing policy after observation", async () => { + for (const routedProviderUnlock of [true, false, undefined]) { + const calls: unknown[][] = [], warnings: string[] = []; + const runtime = createDesktopCompatibilityRuntime({ platform: "linux" }); + runtime.start = async () => { calls.push(["start"]); return runtime.status(); }; + runtime.apply = async (...args) => { calls.push(["apply", ...args]); return { accepted: false, reason: "fixture-refusal" } as Awaited>; }; + const setting = routedProviderUnlock === undefined ? { startOnProxyStart: true } : { startOnProxyStart: true, routedProviderUnlock }; + const handle = scheduleDesktopCompatibilityStartup({ ...getDefaultConfig(), desktopCompatibility: setting }, + { platform: "win32", testGuard: false, sibling: false, warn: text => warnings.push(text), + load: async () => ({ getDesktopCompatibilityRuntime: () => runtime, shutdownDesktopCompatibility: async () => {} }) }); + await new Promise(resolve => setTimeout(resolve, 0)); + await handle.shutdown(); + expect(calls).toEqual(routedProviderUnlock ? [["start"], ["apply", true, "routed-provider-capacity"]] : [["start"]]); + expect(warnings).toEqual(routedProviderUnlock ? [expect.stringContaining("fixture-refusal")] : []); + } +}); +test("a rejected routed-provider activation is reported apart from observation startup", async () => { + const warnings: string[] = []; + const runtime = createDesktopCompatibilityRuntime({ platform: "linux" }); + runtime.start = async () => runtime.status(); + runtime.apply = async () => { throw new Error("fixture-sensitive-error"); }; + const handle = scheduleDesktopCompatibilityStartup({ ...getDefaultConfig(), desktopCompatibility: { startOnProxyStart: true, routedProviderUnlock: true } }, + { platform: "win32", testGuard: false, sibling: false, warn: text => warnings.push(text), + load: async () => ({ getDesktopCompatibilityRuntime: () => runtime, shutdownDesktopCompatibility: async () => {} }) }); + await new Promise(resolve => setTimeout(resolve, 0)); + await handle.shutdown(); + expect(warnings).toEqual([expect.stringContaining("is observing, but the routed-provider usage policy did not start (activation-failed)")]); + expect(warnings[0]).not.toContain("fixture-sensitive-error"); +}); + From b09f88c46e245ec4c432bed74747b4aef254286d Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:47:56 +0900 Subject: [PATCH 34/50] feat(chatgpt): spendCredits lifts the credit-variant limit gates in the app-server shim (carry #9053) (#9320) Carry of #9053: spendCredits lifts credit-variant limit gates in the app-server shim. Co-authored-by: lcxhh <59329914+lcxhh521@users.noreply.github.com> --- .../content/docs/es/guides/chatgpt-desktop.md | 2 +- .../content/docs/guides/chatgpt-desktop.md | 9 +++- .../content/docs/tr/guides/chatgpt-desktop.md | 6 ++- .../app-server-shim/app-server-rewrite.ts | 4 +- src/chatgpt/app-server-shim/filter.ts | 6 ++- src/chatgpt/app-server-shim/gate-rewrite.ts | 45 ++++++++++++------- src/chatgpt/app-server-shim/launcher.ts | 3 +- src/cli/chatgpt-command.ts | 2 +- src/cli/internal-command.ts | 8 ++-- src/config/diagnostics.ts | 9 +++- src/config/schema/chatgpt-desktop.ts | 9 ++-- src/types/config.ts | 2 +- structure/clients/chatgpt-desktop.md | 8 ++-- structure/config.md | 2 +- .../desktop-app-server-shim-launcher.test.ts | 7 +++ tests/clients/desktop-app-server-shim.test.ts | 19 ++++++++ tests/clients/desktop-chatgpt-config.test.ts | 22 +++++++++ 17 files changed, 124 insertions(+), 39 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/chatgpt-desktop.md b/docs-site/src/content/docs/es/guides/chatgpt-desktop.md index 7cde0152166..801523a310c 100644 --- a/docs-site/src/content/docs/es/guides/chatgpt-desktop.md +++ b/docs-site/src/content/docs/es/guides/chatgpt-desktop.md @@ -36,7 +36,7 @@ Si ChatGPT no está instalado (no se encuentra un paquete `com.openai.codex`), ` ## Alcance de la reescritura -Solo se consideran las notificaciones `account/rateLimits/updated` y las respuestas cuyo resultado de nivel superior contiene `rateLimits`, `rateLimitsByLimitId` u `ordinaryUsageAllowed`. Se eliminan los marcadores simples `rate_limit_reached`. Los campos conocidos de bloqueo por cuota (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) solo pasan al estado permitido cuando hay evidencia de que el bloqueo se debe a la cuota general: se ha eliminado un marcador de ese tipo o una ventana de uso alcanza el 100%. Un campo bloqueado por un motivo que no aparece en los datos recibidos permanece bloqueado. Las restricciones del espacio de trabajo, los créditos, los tipos desconocidos de límite alcanzado y los controles de gasto mantienen cerrado el acceso por uso. +Solo se consideran las notificaciones `account/rateLimits/updated` y las respuestas cuyo resultado de nivel superior contiene `rateLimits`, `rateLimitsByLimitId` u `ordinaryUsageAllowed`. Se eliminan los marcadores simples `rate_limit_reached`. Los campos conocidos de bloqueo por cuota (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) solo pasan al estado permitido cuando hay evidencia de que el bloqueo se debe a la cuota general: se ha eliminado un marcador de ese tipo o una ventana de uso alcanza el 100%. Un campo bloqueado por un motivo que no aparece en los datos recibidos permanece bloqueado. Las restricciones del espacio de trabajo, los tipos desconocidos de límite alcanzado y los controles de gasto mantienen cerrado el acceso por uso. Con `chatgptDesktop.spendCredits: true`, las variantes de crédito (`workspace_member_credits_depleted`, `workspace_owner_usage_limit_reached`) se abren igual que la cuota general, así que el escritorio puede usar créditos cuando se agota la cuota de la suscripción. OpenAI factura esos créditos y, de forma predeterminada, un compositor limitado por créditos sigue bloqueado. El uso mostrado conserva los datos reales: porcentajes, fechas de restablecimiento, duración de las ventanas, información del plan y otros campos de presentación se mantienen como se recibieron. Los mensajes JSON-RPC ajenos a este caso, la salida anidada de herramientas, los metadatos que bloquean el envío de conversaciones y las líneas malformadas se transmiten sin cambios. Solo se vuelven a serializar las líneas modificadas; los demás bytes conservan su codificación y sus finales de línea originales. La entrada estándar, la salida de errores y el código de salida del binario real mantienen su conexión directa con la aplicación. diff --git a/docs-site/src/content/docs/guides/chatgpt-desktop.md b/docs-site/src/content/docs/guides/chatgpt-desktop.md index 8f195bfa829..ea824b0703e 100644 --- a/docs-site/src/content/docs/guides/chatgpt-desktop.md +++ b/docs-site/src/content/docs/guides/chatgpt-desktop.md @@ -51,8 +51,13 @@ are eligible. Plain `rate_limit_reached` markers are cleared; known quota gate flags (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) are opened only with plain-quota evidence (a cleared plain reached type or a window at 100%). A flag closed for a reason the payload does not show stays closed. Workspace, -credit, unknown reached-type and spend-control -restrictions keep the usage gate closed. +unknown reached-type and spend-control +restrictions keep the usage gate closed. With +`chatgptDesktop.spendCredits: true` the credit variants +(`workspace_member_credits_depleted`, `workspace_owner_usage_limit_reached`) are +lifted like the plain quota, so the desktop can draw on credits when the +subscription quota is exhausted — credits are billed by OpenAI, and the default +keeps a credit-limited composer locked. Displayed usage stays honest: percentages, reset times, window durations, plan information and other display fields stay as received. Unrelated JSON-RPC diff --git a/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md b/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md index b3dd5372fc3..ce6163d4f50 100644 --- a/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md +++ b/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md @@ -51,7 +51,11 @@ uygundur. Normal `rate_limit_reached` işaretleri temizlenir. Bilinen kota bayra (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) yalnızca normal kota kanıtıyla açılır: temizlenmiş normal sınır türü veya %100 dolmuş pencere. Yükün açıklamadığı bir nedenle kapalı olan bayrak kapalı kalır. Çalışma alanı, -kredi, bilinmeyen sınır türü ve harcama denetimi kısıtlamaları geçidi kapalı tutar. +bilinmeyen sınır türü ve harcama denetimi kısıtlamaları geçidi kapalı tutar. +`chatgptDesktop.spendCredits: true` iken kredi türleri +(`workspace_member_credits_depleted`, `workspace_owner_usage_limit_reached`) +normal kota gibi açılır; abonelik kotası bitince masaüstü krediden çekebilir. +Bu kredileri OpenAI faturalandırır. Varsayılan, kredi sınırındaki composer'ı kilitli tutar. Gösterilen kullanım değişmez: yüzdeler, sıfırlanma zamanları, pencere süreleri, plan bilgileri ve diğer gösterim alanları alındığı gibi kalır. İlgisiz JSON-RPC diff --git a/src/chatgpt/app-server-shim/app-server-rewrite.ts b/src/chatgpt/app-server-shim/app-server-rewrite.ts index ae0d97a82b5..c5ed28a2140 100644 --- a/src/chatgpt/app-server-shim/app-server-rewrite.ts +++ b/src/chatgpt/app-server-shim/app-server-rewrite.ts @@ -31,7 +31,7 @@ function gatePayload(message: unknown): Record | null { * rewrite has nothing to change. Parse failures also return null: the rewrite owns removal of * known-shaped locks, not validation. */ -export function rewriteAppServerLine(line: string): string | null { +export function rewriteAppServerLine(line: string, liftCredits = false): string | null { if (!line.includes("rateLimit") && !line.includes("ordinaryUsageAllowed")) return null; let parsed: unknown; try { @@ -41,5 +41,5 @@ export function rewriteAppServerLine(line: string): string | null { } const payload = gatePayload(parsed); if (payload === null) return null; - return unlockRateLimitGate(payload) ? JSON.stringify(parsed) : null; + return unlockRateLimitGate(payload, { liftCredits }) ? JSON.stringify(parsed) : null; } diff --git a/src/chatgpt/app-server-shim/filter.ts b/src/chatgpt/app-server-shim/filter.ts index df9e88db7fd..a89d53e6eaa 100644 --- a/src/chatgpt/app-server-shim/filter.ts +++ b/src/chatgpt/app-server-shim/filter.ts @@ -137,7 +137,9 @@ export async function runStdoutFilter( } /** Hidden CLI entry; the self-test emits no stdout so the launcher can probe it safely. */ -export async function runChatgptAppServerFilter({ selfTest = false }: { selfTest?: boolean } = {}): Promise { +export async function runChatgptAppServerFilter( + { selfTest = false, spendCredits = false }: { selfTest?: boolean; spendCredits?: boolean } = {}, +): Promise { if (selfTest) { try { const fixture = JSON.stringify({ id: 1, result: { @@ -152,6 +154,6 @@ export async function runChatgptAppServerFilter({ selfTest = false }: { selfTest && result.rateLimits.primary.usedPercent === 100 ? 0 : 1; } catch { return 1; } } - await runStdoutFilter(Bun.stdin.stream(), bytes => Bun.write(Bun.stdout, bytes)); + await runStdoutFilter(Bun.stdin.stream(), bytes => Bun.write(Bun.stdout, bytes), line => rewriteAppServerLine(line, spendCredits)); return 0; } diff --git a/src/chatgpt/app-server-shim/gate-rewrite.ts b/src/chatgpt/app-server-shim/gate-rewrite.ts index 4864a7bece3..ee6d2ba2f2c 100644 --- a/src/chatgpt/app-server-shim/gate-rewrite.ts +++ b/src/chatgpt/app-server-shim/gate-rewrite.ts @@ -1,29 +1,41 @@ -/** Plain-quota gate rewriting; usage display and non-quota restrictions are preserved. */ +/** Reached types that describe a billing state. The plain subscription quota is always lifted; + * the credit variants are lifted only when the operator opts in (`chatgptDesktop.spendCredits`) + * — the desktop may then draw on credits rather than lock the composer. Spend control and any + * other unknown reached type still block (see hasNonQuotaBlock). */ const PLAIN_QUOTA_REACHED_TYPE = "rate_limit_reached"; +const CREDIT_REACHED_TYPES = new Set([ + "workspace_member_credits_depleted", + "workspace_owner_usage_limit_reached", +]); + +function isLiftedReachedType(type: string, liftCredits: boolean): boolean { + return type === PLAIN_QUOTA_REACHED_TYPE || (liftCredits && CREDIT_REACHED_TYPES.has(type)); +} function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); } -function hasNonQuotaBlock(node: unknown): boolean { - if (Array.isArray(node)) return node.some(hasNonQuotaBlock); +function hasNonQuotaBlock(node: unknown, liftCredits: boolean): boolean { + if (Array.isArray(node)) return node.some(item => hasNonQuotaBlock(item, liftCredits)); if (!isRecord(node)) return false; if (node.spendControlReached !== undefined && node.spendControlReached !== null && node.spendControlReached !== false) return true; if (isRecord(node.spend_control) && node.spend_control.reached === true) return true; const reached = node.rate_limit_reached_type; - if (isRecord(reached) && typeof reached.type === "string" && reached.type !== PLAIN_QUOTA_REACHED_TYPE) return true; + if (isRecord(reached) && typeof reached.type === "string" && !isLiftedReachedType(reached.type, liftCredits)) return true; const rpcReached = node.rateLimitReachedType; const rpcType = typeof rpcReached === "string" ? rpcReached : isRecord(rpcReached) ? rpcReached.type : undefined; - if (typeof rpcType === "string" && rpcType !== PLAIN_QUOTA_REACHED_TYPE) return true; - return Object.values(node).some(hasNonQuotaBlock); + if (typeof rpcType === "string" && !isLiftedReachedType(rpcType, liftCredits)) return true; + return Object.values(node).some(child => hasNonQuotaBlock(child, liftCredits)); } -export function unlockRateLimitGate(value: unknown): boolean { +export function unlockRateLimitGate(value: unknown, opts: { liftCredits?: boolean } = {}): boolean { + const liftCredits = opts.liftCredits === true; let changed = false; - const payloadBlocked = hasNonQuotaBlock(value); - // A subtree shows the plain quota as the reason when a plain-quota reached type was removed in - // it or a usage window reads 100%; it stays "blocked" when a non-quota reason (workspace or - // credit reached type, spend control) is still standing in it. + const payloadBlocked = hasNonQuotaBlock(value, liftCredits); + // A subtree shows the plain quota as the reason when a lifted reached type was removed in + // it or a usage window reads 100%; it stays "blocked" when a reason that is not liftable + // (spend control, an unknown reached type) is still standing in it. const visit = (node: unknown): { cleared: boolean; exhausted: boolean; blocked: boolean } => { let cleared = false; let exhausted = false; @@ -45,7 +57,7 @@ export function unlockRateLimitGate(value: unknown): boolean { if (node.spendControlReached !== undefined && node.spendControlReached !== null && node.spendControlReached !== false) blocked = true; if (isRecord(node.spend_control) && node.spend_control.reached === true) blocked = true; const reachedType = node.rate_limit_reached_type; - if (isRecord(reachedType) && reachedType.type === PLAIN_QUOTA_REACHED_TYPE) { + if (isRecord(reachedType) && typeof reachedType.type === "string" && isLiftedReachedType(reachedType.type, liftCredits)) { delete node.rate_limit_reached_type; changed = true; cleared = true; @@ -55,7 +67,7 @@ export function unlockRateLimitGate(value: unknown): boolean { // The app-server's JSON-RPC spelling of the same field: a nullable string. const rpcReached = node.rateLimitReachedType; const rpcType = typeof rpcReached === "string" ? rpcReached : isRecord(rpcReached) ? rpcReached.type : undefined; - if (rpcType === PLAIN_QUOTA_REACHED_TYPE) { + if (typeof rpcType === "string" && isLiftedReachedType(rpcType, liftCredits)) { node.rateLimitReachedType = null; changed = true; cleared = true; @@ -68,9 +80,10 @@ export function unlockRateLimitGate(value: unknown): boolean { exhausted ||= r.exhausted; blocked ||= r.blocked; } - // The rate-limit flags are opened only when the plain quota is the visible reason in this - // subtree and no workspace, credit or spend-control reason stands anywhere in the payload. - // A flag closed for a reason the payload does not show stays as the server sent it. + // The rate-limit flags are opened when a lifted reached type is the visible reason in this + // subtree (plain quota, or a credit variant the operator has opted to spend) and no + // spend-control or unknown reason stands anywhere in the payload. A flag closed for a + // reason the payload does not show stays as the server sent it. const plainQuotaShown = (cleared || exhausted) && !blocked && !payloadBlocked; if (plainQuotaShown) { for (const key of ["rate_limit", "rateLimit"] as const) { diff --git a/src/chatgpt/app-server-shim/launcher.ts b/src/chatgpt/app-server-shim/launcher.ts index 6cddfd97c0f..0ab6fec5138 100644 --- a/src/chatgpt/app-server-shim/launcher.ts +++ b/src/chatgpt/app-server-shim/launcher.ts @@ -97,13 +97,14 @@ export function writeChatgptShimLauncher( configDir = getConfigDir(), real = CHATGPT_APP_CODEX_BINARY, bundleRoot = /^(.*?\.app)\/Contents\//i.exec(real)?.[1], filesystem: Pick | undefined = process.platform === "darwin" ? defaultBundleTrustDeps() : undefined, + spendCredits = false, ): string { if (!bundleRoot || !posix.isAbsolute(bundleRoot) || !real.startsWith(bundleRoot + "/Contents/")) { throw new Error("the app-server launcher requires its discovered bundle root"); } mkdirSync(configDir, { recursive: true }); const path = chatgptShimLauncherPath(configDir); - const argv = [process.execPath, ...selfLaunchArgv(["internal", "chatgpt-app-server-filter"])]; + const argv = [process.execPath, ...selfLaunchArgv(["internal", "chatgpt-app-server-filter", ...(spendCredits ? ["--spend-credits"] : [])])]; const temp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`; let created = false; const assertFilesystem = (file: string, existing: boolean) => { diff --git a/src/cli/chatgpt-command.ts b/src/cli/chatgpt-command.ts index 0436b3033b1..b778de9e7b8 100644 --- a/src/cli/chatgpt-command.ts +++ b/src/cli/chatgpt-command.ts @@ -164,7 +164,7 @@ CODEX_CLI_PATH launcher: ${app.shim === null ? "unknown" : app.shim ? "yes" : "n console.error("ChatGPT process inspection failed; no launcher was changed and no app was opened. Retry after resolving inspection."); return 1; } - if (binary) writeChatgptShimLauncher(undefined, binary, install.root); + if (binary) writeChatgptShimLauncher(undefined, binary, install.root, undefined, config.chatgptDesktop?.spendCredits === true); if (!(await quitApp(install, launcher))) { console.error("ChatGPT exit could not be confirmed; no new app was opened. Check the running app and retry."); return 1; diff --git a/src/cli/internal-command.ts b/src/cli/internal-command.ts index d9d7c2ae9c7..11820286446 100644 --- a/src/cli/internal-command.ts +++ b/src/cli/internal-command.ts @@ -18,7 +18,7 @@ */ import type { CodexExecBoundaryAsyncDeps } from "../codex/exec-boundary"; -const USAGE = "Usage: ocx internal desktop-restart-handoff --plan | chatgpt-app-server-filter [--self-test] | codex-exec-target [--bundle-root ] -- "; +const USAGE = "Usage: ocx internal desktop-restart-handoff --plan | chatgpt-app-server-filter [--self-test] [--spend-credits] | codex-exec-target [--bundle-root ] -- "; function optionValue(args: readonly string[], name: string): string | undefined { const index = args.indexOf(name); @@ -53,12 +53,14 @@ export async function handleInternalCommand(args: readonly string[], execBoundar } } if (sub === "chatgpt-app-server-filter") { - if (args.length > 2 || (args[1] !== undefined && args[1] !== "--self-test")) { + const flags = args.slice(1); + const known = new Set(["--self-test", "--spend-credits"]); + if (flags.length > known.size || new Set(flags).size !== flags.length || flags.some(arg => !known.has(arg))) { console.error(USAGE); return 2; } const { runChatgptAppServerFilter } = await import("../chatgpt/app-server-shim/filter"); - return await runChatgptAppServerFilter({ selfTest: args[1] === "--self-test" }); + return await runChatgptAppServerFilter({ selfTest: args.includes("--self-test"), spendCredits: args.includes("--spend-credits") }); } if (sub !== "desktop-restart-handoff") { console.error(`Unknown internal command: ${sub ?? "(none)"}. ${USAGE}`); diff --git a/src/config/diagnostics.ts b/src/config/diagnostics.ts index f4beaf1a838..fd8a0ae9c32 100644 --- a/src/config/diagnostics.ts +++ b/src/config/diagnostics.ts @@ -775,8 +775,13 @@ export function telemetryConfigError(value: unknown): string | null { export function validateConfigCandidate(value: unknown): { ok: true; config: OcxConfig } | { ok: false; error: string } { const chatgptDesktop = rawConfigRecord(value)?.chatgptDesktop; - if (chatgptDesktop !== undefined && !chatgptDesktopSchema.safeParse(chatgptDesktop).success) { - return { ok: false, error: "schema_invalid: chatgptDesktop: requires an optional boolean appServerShim and no other fields" }; + if (chatgptDesktop !== undefined) { + const parsedDesktop = chatgptDesktopSchema.safeParse(chatgptDesktop); + if (!parsedDesktop.success) { + const issue = parsedDesktop.error.issues[0]; + const field = issue?.path.join("."); + return { ok: false, error: redactSecretString("schema_invalid: chatgptDesktop" + (field ? "." + field : "") + ": " + (issue?.message ?? "invalid configuration")) }; + } } const compactionRouting = rawConfigRecord(value)?.compactionRouting; const reasoningRetention = rawConfigRecord(value)?.reasoningRetention; diff --git a/src/config/schema/chatgpt-desktop.ts b/src/config/schema/chatgpt-desktop.ts index fe1e9ff77bb..92da1b70e3c 100644 --- a/src/config/schema/chatgpt-desktop.ts +++ b/src/config/schema/chatgpt-desktop.ts @@ -1,14 +1,17 @@ import * as z from "zod/v4"; import { redactSecretString } from "../../lib/redact"; -/** Experimental macOS ChatGPT app-server shim; only a strict optional boolean is accepted. */ -export const chatgptDesktopSchema = z.object({ appServerShim: z.boolean().optional() }).strict(); +/** Experimental macOS ChatGPT app-server shim; strict optional booleans are accepted. + * `spendCredits` opts into letting the desktop draw on credits when the subscription quota is + * exhausted: the credit-variant limit gates are lifted like plain-quota ones. Default off — + * credits are real money, so the default keeps a credit-limited composer locked. */ +export const chatgptDesktopSchema = z.object({ appServerShim: z.boolean().optional(), spendCredits: z.boolean().optional() }).strict(); /** * Why a present `chatgptDesktop` block fails the schema, or null when it is valid or absent. The * read path degrades a failing block to absent, so the integration reads as off while the file * still says `appServerShim: true`; this names the field so that is never silent. A leftover key - * from an older or ported config (for example `unblockSend`) is the usual cause. + * from an older config (for example `unblockSend`) is the usual cause. */ export function chatgptDesktopConfigIssue(rawParsed: unknown): string | null { if (!rawParsed || typeof rawParsed !== "object" || Array.isArray(rawParsed)) return null; diff --git a/src/types/config.ts b/src/types/config.ts index 885e8cd58d3..d1702030bd4 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -543,7 +543,7 @@ export interface OcxClientConnectionConfig { export interface OcxConfig extends OcxLinkHomeConfig, CodexAccountLoginConfig { /** Experimental macOS app-server stdout shim; absent or false disables it. */ - chatgptDesktop?: { appServerShim?: boolean }; + chatgptDesktop?: { appServerShim?: boolean; spendCredits?: boolean }; port: number; /** Runtime topology role. Absence preserves the historical standalone behavior. */ runtimeRole?: OcxRuntimeRole; diff --git a/structure/clients/chatgpt-desktop.md b/structure/clients/chatgpt-desktop.md index 3038abdafd1..b9cc6454854 100644 --- a/structure/clients/chatgpt-desktop.md +++ b/structure/clients/chatgpt-desktop.md @@ -3,7 +3,7 @@ The experimental macOS integration is owned by `src/chatgpt/` and exposed through `src/cli/chatgpt-command.ts`. It is default off and requires `chatgptDesktop.appServerShim === true` for an explicit launch. Its config leaf -accepts only an optional boolean; malformed reads disable the leaf, while live +accepts optional booleans `appServerShim` and `spendCredits`; malformed reads disable the leaf, while live writes reject malformed values and unknown fields. The launcher under the config directory re-enters the current CLI using @@ -29,10 +29,12 @@ mid-session closes the server's stdout pipe; the filter's passthrough mode limit to an exit/crash case. The pure gate rewrite changes known plain-quota fields only in eligible JSON-RPC -rate-limit notifications and top-level rate-limit results. Workspace, credit, +rate-limit notifications and top-level rate-limit results. Workspace, unknown reached-type and spend-control restrictions preserve closed gate flags. +Credit-variant reached types stay closed unless `spendCredits` is true. Both the rate-limit flags and `ordinaryUsageAllowed` open only where the subtree shows -plain-quota evidence: a cleared plain reached type or a usage window at 100% (`usedPercent` in the +plain-quota evidence: a cleared plain reached type, a cleared credit reached type when +`spendCredits` is true, or a usage window at 100% (`usedPercent` in the RPC, `used_percent` in the web usage snapshot; every gate field is read in both spellings). Usage percentages, resets and window durations remain accurate. Unrelated messages and malformed lines remain byte-identical; changed lines are reserialized. diff --git a/structure/config.md b/structure/config.md index d0a5940c0f4..fb37ab5b1bf 100644 --- a/structure/config.md +++ b/structure/config.md @@ -596,4 +596,4 @@ so wrong types and unknown nested fields are rejected rather than silently saved `apiSurfaces` and `protocols` on `src/types/config.ts` are parsed by `src/protocols/settings.ts` only; [Protocol Paths](data-planes/protocol-paths.md#settings) owns their schema handling, meaning and the one writer (`PATCH /api/protocols/settings`), including why closing Messages also writes `claudeCode.enabled` through `commitClaudeCodeBlock` (`src/claude/claude-code-block.ts`, the sentinel-stamping block writer every management route uses). The optional boolean `protocols.rollout.geminiNativeAntigravity` defaults off and malformed file policy cannot enable it. See [Native Gemini Inbound](data-planes/gemini-native.md). Stored Direct substitution follows the [credential identity contract](providers/openai-accounts.md#sidecars-management-and-ui): both synchronous and asynchronous materializers discard the caller account header before applying the stored credential; ordinary native Direct passthrough is unchanged. -Proxy activation and credential-safe CLI output follow [Proxy Configuration](config-proxy.md). The experimental `chatgptDesktop` leaf accepts only optional boolean `appServerShim`, default off. Malformed reads disable this leaf; live writes reject malformed values and unknown keys. `src/config/diagnostics.ts` reports the reason a whole `chatgptDesktop` block is dropped on both normal and salvaged reads; salvage retains its fallback source and schema error. Its activation and local executable boundary follow [ChatGPT Desktop](clients/chatgpt-desktop.md). `claudeCode.subagentModelForce` is an optional safe roster-style id. Invalid hand edits degrade with a warning without losing other config; stale but syntactically valid targets remain stored for repair and are skipped at launch. Management force updates are field-scoped against current disk state, preserving concurrent Claude sibling edits. A config absent at request start uses canonical create-only initialization; a racing file or invalid initial state refuses the save, and an existing-file mutation never recreates deleted config. Clearing removes only that leaf. A malformed `asideProfileSync` still loads as `{ allProfiles: false }`, which turns every Aside profile off, so `warnDegradedTopLevelOptIns` in `src/config/load-degrade.ts` now reports it once per load without echoing a key or value. +Proxy activation and credential-safe CLI output follow [Proxy Configuration](config-proxy.md). The experimental `chatgptDesktop` leaf accepts optional booleans `appServerShim` and `spendCredits`, both default off. Malformed reads disable this leaf; live writes reject malformed values and unknown keys. `src/config/diagnostics.ts` reports the reason a whole `chatgptDesktop` block is dropped on both normal and salvaged reads; salvage retains its fallback source and schema error. Its activation and local executable boundary follow [ChatGPT Desktop](clients/chatgpt-desktop.md). `claudeCode.subagentModelForce` is an optional safe roster-style id. Invalid hand edits degrade with a warning without losing other config; stale but syntactically valid targets remain stored for repair and are skipped at launch. Management force updates are field-scoped against current disk state, preserving concurrent Claude sibling edits. A config absent at request start uses canonical create-only initialization; a racing file or invalid initial state refuses the save, and an existing-file mutation never recreates deleted config. Clearing removes only that leaf. A malformed `asideProfileSync` still loads as `{ allProfiles: false }`, which turns every Aside profile off, so `warnDegradedTopLevelOptIns` in `src/config/load-degrade.ts` now reports it once per load without echoing a key or value. diff --git a/tests/clients/desktop-app-server-shim-launcher.test.ts b/tests/clients/desktop-app-server-shim-launcher.test.ts index f26bd6354b1..e252ea20c86 100644 --- a/tests/clients/desktop-app-server-shim-launcher.test.ts +++ b/tests/clients/desktop-app-server-shim-launcher.test.ts @@ -83,6 +83,13 @@ describe("experimental app-server launcher", () => { expect(readFileSync(path, "utf8")).toContain(`REAL='${real}'`); })); + test("spendCredits is the only addition to the generated filter argv", () => withDir(dir => { + const real = "/Volumes/Apps/ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex"; + expect(readFileSync(writeChatgptShimLauncher(dir, real), "utf8")).not.toContain("--spend-credits"); + const enabled = readFileSync(writeChatgptShimLauncher(dir, real, undefined, undefined, true), "utf8"); + expect(enabled).toContain("'chatgpt-app-server-filter' '--spend-credits'"); + })); + const linkTest = process.platform === "win32" ? test.skip : test; linkTest("the writer replaces a symbolic link at the launcher path instead of following it", () => withDir(dir => { const victim = join(dir, "victim.txt"); diff --git a/tests/clients/desktop-app-server-shim.test.ts b/tests/clients/desktop-app-server-shim.test.ts index b801884fbaf..168d6be4abc 100644 --- a/tests/clients/desktop-app-server-shim.test.ts +++ b/tests/clients/desktop-app-server-shim.test.ts @@ -39,6 +39,25 @@ describe("app-server line rewrite", () => { } }); + test("with spendCredits the credit variants are lifted like the plain quota", () => { + for (const type of ["workspace_owner_usage_limit_reached", "workspace_member_credits_depleted"]) { + const line = rpcResult({ ...EXHAUSTED_RATE_LIMITS, rateLimits: { ...EXHAUSTED_RATE_LIMITS.rateLimits, rateLimitReachedType: type }, rateLimitsByLimitId: {} }); + const out = JSON.parse(rewriteAppServerLine(line, true)!); + expect(out.result.ordinaryUsageAllowed).toBe(true); + expect(out.result.rateLimits.rateLimitReachedType).toBeNull(); + } + }); + + test("spend control keeps the usage gate closed even with spendCredits", () => { + const line = rpcResult({ + ordinaryUsageAllowed: false, + rateLimits: { rateLimitReachedType: "workspace_member_credits_depleted" }, + spendControlReached: true, + }); + const out = JSON.parse(rewriteAppServerLine(line, true)!); + expect(out.result.ordinaryUsageAllowed).toBe(false); + }); + test("a plain quota next to a workspace block keeps ordinary usage closed", () => { const line = rpcResult({ ordinaryUsageAllowed: false, diff --git a/tests/clients/desktop-chatgpt-config.test.ts b/tests/clients/desktop-chatgpt-config.test.ts index fb4f94ab22a..28feaa1db04 100644 --- a/tests/clients/desktop-chatgpt-config.test.ts +++ b/tests/clients/desktop-chatgpt-config.test.ts @@ -16,6 +16,26 @@ describe("experimental ChatGPT desktop config", () => { expect(validateConfigCandidate({ ...base, chatgptDesktop: { appServerShim } }).ok).toBe(true); } }); + test("spendCredits is an optional boolean and stays off unless true", () => { + for (const spendCredits of [undefined, false, true]) { + const desktop = { appServerShim: true, spendCredits }; + const parsed = configSchema.parse({ ...base, chatgptDesktop: desktop }); + expect(parsed.chatgptDesktop?.spendCredits === true).toBe(spendCredits === true); + expect(validateConfigCandidate({ ...base, chatgptDesktop: desktop }).ok).toBe(true); + } + const write = validateConfigCandidate({ ...base, chatgptDesktop: { spendCredits: "yes" } }); + expect(write.ok).toBe(false); + if (!write.ok) expect(write.error).toContain("chatgptDesktop.spendCredits"); + }); + test("a secret-shaped unknown desktop key is redacted in the write error", () => { + const secret = "sk-testkey123"; + const write = validateConfigCandidate({ ...base, chatgptDesktop: { [secret]: true } }); + expect(write.ok).toBe(false); + if (!write.ok) { + expect(write.error).toContain("chatgptDesktop"); + expect(write.error).not.toContain(secret); + } + }); test("malformed reads disable only the experimental feature; writes reject unknown and malformed fields", () => { for (const chatgptDesktop of [null, true, [], "yes", { appServerShim: "true" }, { appServerShim: true, unblockSend: true }, { port: 1234 }]) { const candidate = { ...base, port: 12345, chatgptDesktop }; @@ -80,6 +100,8 @@ describe("experimental ChatGPT desktop config", () => { }); test("hidden self-test works and rejects extra options", async () => { expect(await handleInternalCommand(["chatgpt-app-server-filter", "--self-test"])).toBe(0); + expect(await handleInternalCommand(["chatgpt-app-server-filter", "--self-test", "--spend-credits"])).toBe(0); expect(await handleInternalCommand(["chatgpt-app-server-filter", "--invalid"])).toBe(2); + expect(await handleInternalCommand(["chatgpt-app-server-filter", "--spend-credits", "--spend-credits"])).toBe(2); }); }); From 3c3ee29cf2f1b4d230b58ba7af4b5967cce08391 Mon Sep 17 00:00:00 2001 From: JUN Date: Fri, 4 Dec 2026 00:48:06 +0900 Subject: [PATCH 35/50] feat(shadow-call): let helper calls follow the conversation provider (carry #9288) (#9311) Carry of #9288: let shadow helper calls follow the conversation provider, with concurrent refresh race fixed. Closes #9096 Co-authored-by: Pengusto <106893073+pengusto@users.noreply.github.com> --- .../docs/es/reference/configuration/server.md | 29 +- .../docs/es/reference/management-api.md | 2 +- .../docs/reference/configuration/server.md | 35 +- .../content/docs/reference/management-api.md | 2 +- gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/es.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/shadow-follow-copy.ts | 18 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/src/pages/Models.tsx | 2 +- gui/src/pages/models-shared.ts | 3 + .../pages/shadow-call-follow-conversation.tsx | 69 ++++ gui/src/pages/shadow-call-settings-row.tsx | 17 + gui/src/styles-models-workspace.css | 4 + .../shadow-call-follow-conversation.test.tsx | 116 ++++++ scripts/test-layout/layout-responses.json | 1 + .../references/01_surface_providers-models.md | 6 +- src/cli/capabilities-provider-models.ts | 6 +- src/cli/models-runtime.ts | 23 +- src/providers/provider-id-rewrite.ts | 26 ++ src/server/management/config-routes.ts | 15 +- .../provider-gcp-credential-routes.ts | 3 +- .../management/shadow-call-validation.ts | 30 ++ src/server/responses/request-prepare.ts | 30 +- .../responses/shadow-follow-conversation.ts | 142 ++++++++ src/types/config.ts | 6 + structure/transports/responses.md | 2 +- .../cli-capability-provider-workflows.test.ts | 3 + tests/fixtures/test-layout-expected.json | 2 +- tests/helpers/responses-core-source.ts | 1 + .../shadow-follow-conversation.test.ts | 343 ++++++++++++++++++ 39 files changed, 930 insertions(+), 30 deletions(-) create mode 100644 gui/src/i18n/shadow-follow-copy.ts create mode 100644 gui/src/pages/shadow-call-follow-conversation.tsx create mode 100644 gui/tests/shadow-call-follow-conversation.test.tsx create mode 100644 src/server/responses/shadow-follow-conversation.ts create mode 100644 tests/responses/shadow-follow-conversation.test.ts diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index 8885d17a053..a92bbdc87d2 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -57,7 +57,7 @@ La configuración del servidor controla la forma en que el proxy local escucha, | `resetCreditAutoRedeem?` | `{ enabled?: boolean; leadTimeMinutes?: number }` | desactivado | Activación explícita: canjear el crédito de restablecimiento más pronto de la cuenta principal Codex `leadTimeMinutes` (1–60, por defecto 10) antes de que expire. Cada intento vuelve a leer la lista de crédito ascendente primero y se salta cuando el crédito se ha ido (por ejemplo, canjeado a mano); `redeem_request_id` Es journalizado en `$OPENCODEX_HOME/reset-credit-auto-redeem.json` antes de la llamada, por lo que un bloqueo reproduce la misma solicitud idempotente en lugar de gastar un segundo crédito. Los servidores que comparten este directorio de configuración coordinan las reservas y liquidaciones para que un proceso no reemplace el registro de solicitud de otro. Los registros solo llevan una clave de cuenta hash. | | `syncResumeHistory?` | `boolean` | `true` | Compatibilidad reversible con el historial de Codex App. Los metadatos originales se respaldan y se restauran mediante `ocx stop` / `ocx restore`. | | `spendPoolAliases?` | `Record` | Sin configurar | Mapa explícito de alias históricos de grupos, calculados con sal, a proveedores canónicos. Mantenga esta clave en el nivel superior, fuera de `spend`. Véase [Continuidad histórica de los grupos](#historical-pool-continuity). | -| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[] }` | desactivado | Redirige llamadas auxiliares reconocidas de Codex al modelo elegido, conservando su esfuerzo de razonamiento. Los prefijos predeterminados son `gpt-6-luna` y `gpt-5.6-luna`. El panel ofrece un interruptor por origen; las generaciones Terra (`gpt-6.1-terra` y `gpt-5.6-terra`) y el antiguo `gpt-5.4-mini` permanecen desactivados hasta seleccionarlos. Debe quedar al menos un origen activo; desactiva el interruptor principal para detener todas las llamadas de sombra. | +| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[]; followConversation?: Record }` | desactivado | Redirige llamadas auxiliares reconocidas de Codex al modelo elegido, conservando su esfuerzo de razonamiento. Los prefijos predeterminados son `gpt-6-luna` y `gpt-5.6-luna`. El panel ofrece un interruptor por origen; las generaciones Terra (`gpt-6.1-terra` y `gpt-5.6-terra`) y el antiguo `gpt-5.4-mini` permanecen desactivados hasta seleccionarlos. Debe quedar al menos un origen activo; desactiva el interruptor principal para detener todas las llamadas de sombra. | | `memoryModels?` | `{ extract?: { model: string; reasoningEffort?: string }; consolidation?: { model: string; reasoningEffort?: string } }` | desactivado | Enruta las dos fases de memoria de Codex a un modelo elegido, con un esfuerzo de razonamiento opcional por fase. Véase [Enrutamiento de memoria](#memory-routing). | | `webSearchSidecar?` | `OcxWebSearchSidecarConfig` | activado si está disponible | Opciones del asistente de búsqueda web. | | `visionSidecar?` | `OcxVisionSidecarConfig` | activado si está disponible | Opciones del asistente de descripción de imágenes. | @@ -753,6 +753,33 @@ reintentables antes de que empiece la salida. Consulta [Combos](/es/guides/combos/) para la elegibilidad de los objetivos y el [consentimiento de fallback medido](/es/guides/combos/#metered-fallback-consent). +### Seguir al proveedor de la conversación + +`followConversation` asigna un modelo auxiliar a cada id de proveedor. Con este mapa, una llamada +auxiliar interceptada va al modelo asignado al proveedor al que se enrutó el último turno ordinario de la +misma conversación de Codex, identificada por las cabeceras `thread-id` y `session-id`. Un turno +fija el proveedor en cuanto se enruta, así que un turno que luego falla o se cancela también lo cambia. Cada +hilo de subagente guarda su propio registro, así que un turno de un subagente en otro proveedor no cambia +el proveedor que siguen las llamadas auxiliares de su padre. Una +conversación desconocida, un proveedor sin asignación o un modelo asignado que no se resuelve usan +`model` como antes, incluido el rechazo `intercept_target_unavailable`. El registro vive solo en +memoria, guarda como máximo 2048 conversaciones y empieza vacío tras un reinicio. La ruta registra el +motivo `shadow-follow-conversation`. Configúralo con `PUT /api/shadow-call-settings`, +`ocx models shadow set --follow-conversation ` o en la página Modelos. Asignar `openai` a `gpt-6-luna` deja nativas las llamadas auxiliares de esa conversación. + +```json +{ + "shadowCallIntercept": { + "enabled": true, + "model": "gpt-5.5", + "followConversation": { + "anthropic": "anthropic/claude-haiku-5-5", + "openai": "gpt-6-luna" + } + } +} +``` + ### Cuando el objetivo no está disponible diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index b7c3c246240..6dad956dd8f 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -264,7 +264,7 @@ Vea [Codex capas de solicitud](/es/guides/codex-prompt/) para el modelo de capa | `POST /api/update/run` | Comprobar de forma asíncrona una versión nueva e iniciar su actualización, opcionalmente seguida de reinicio | 400 cuerpo inválido; 409 `update_restart_unsupervised` si el proxy se ejecuta dentro de una unidad systemd distinta del servicio de usuario de OpenCodex, o el proceso de actualización no puede salir de su cgroup (con o sin reinicio, porque la actualización detiene primero el proxy); otros estados de conflicto o error del trabajo | | `GET /api/update/status` | Consultar periódicamente un trabajo de actualización por su id | 404 trabajo desconocido | | `GET, PUT /api/sidecar-settings` | Lea o actualice la configuración del modelo/backend del sidecar de la visión y la búsqueda web | 400 forma inválida, backend o límite | -| `GET, PUT /api/shadow-call-settings` | Leer o actualizar la interceptación de llamadas de sombra, incluido `sourceModels`; GET también devuelve el inventario `sourceModelOptions` del entorno | 400 forma o valor inválido, incluidos prefijos vacíos, duplicados, con espacios o proveedor, más de 32 prefijos o más de 128 caracteres por prefijo; los fallos de lista llevan `code: shadow_call_source_invalid` y los conflictos de destino `code: shadow_call_target_invalid` | +| `GET, PUT /api/shadow-call-settings` | Leer o actualizar la interceptación de llamadas de sombra, incluidos `sourceModels` y el mapa proveedor → modelo auxiliar `followConversation` (`null` lo borra); GET también devuelve el inventario `sourceModelOptions` del entorno | 400 forma o valor inválido, incluidos prefijos vacíos, duplicados, con espacios o proveedor, más de 32 prefijos o más de 128 caracteres por prefijo; los fallos de lista llevan `code: shadow_call_source_invalid` y los conflictos de destino `code: shadow_call_target_invalid`, y una entrada `followConversation` inválida `code: shadow_call_follow_invalid` | diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index 326f1b0f1bb..5902bc9e2b0 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -63,7 +63,7 @@ passthrough, including native WebSocket output, retain their existing stop behav | `resetCreditAutoRedeem?` | `{ enabled?: boolean; leadTimeMinutes?: number }` | off | Opt-in: redeem the main Codex account's soonest-expiring reset credit `leadTimeMinutes` (1–60, default 10) before it expires. Every attempt re-reads the upstream credit list first and skips when the credit is gone (for example, redeemed by hand); the `redeem_request_id` is journaled in `$OPENCODEX_HOME/reset-credit-auto-redeem.json` before the call so a crash replays the same idempotent request instead of spending a second credit. Servers sharing this configuration directory coordinate reservations and settlements so one process does not replace another's request record. Logs carry a hashed account key only. | | `syncResumeHistory?` | `boolean` | `true` | Reversible Codex App history compatibility. Original metadata is backed up and restored by `ocx stop` / `ocx restore`. | | `spendPoolAliases?` | `Record` | unset | Explicit historical salted pool-alias to canonical provider mappings. Keep this key at the top level, outside `spend`. See [Historical pool continuity](#historical-pool-continuity). | -| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[] }` | off | Redirect recognized Codex helper/shadow calls to a chosen model while preserving the request's configured reasoning effort. The default source prefixes are `gpt-6-luna` and `gpt-5.6-luna`. The dashboard exposes one toggle per source and keeps both Terra generations (`gpt-6.1-terra` and `gpt-5.6-terra`) and the retired `gpt-5.4-mini` helper off until selected. At least one source must stay enabled; disable the main switch to stop all shadow calls. | +| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[]; followConversation?: Record }` | off | Redirect recognized Codex helper/shadow calls to a chosen model while preserving the request's configured reasoning effort. The default source prefixes are `gpt-6-luna` and `gpt-5.6-luna`. The dashboard exposes one toggle per source and keeps both Terra generations (`gpt-6.1-terra` and `gpt-5.6-terra`) and the retired `gpt-5.4-mini` helper off until selected. At least one source must stay enabled; disable the main switch to stop all shadow calls. | | `memoryModels?` | `{ extract?: { model: string; reasoningEffort?: string }; consolidation?: { model: string; reasoningEffort?: string } }` | off | Route Codex's two memory phases to a chosen model, with an optional reasoning effort per phase. See [Memory routing](#memory-routing). | | `webSearchSidecar?` | `OcxWebSearchSidecarConfig` | on when usable | Web-search sidecar options. | | `visionSidecar?` | `OcxVisionSidecarConfig` | on when usable | Image-description sidecar options. | @@ -1142,6 +1142,39 @@ the combo to allow fallback for other retryable failures before output begins. See [Combos](/guides/combos/) for target eligibility and [metered fallback consent](/guides/combos/#metered-fallback-consent). +### Following the conversation's provider + +`followConversation` maps a provider id to a helper model. With it set, an intercepted helper call +goes to the model mapped to the provider the last ordinary turn of the same Codex conversation was +routed to, identified by the `thread-id` and `session-id` headers both requests carry. A turn sets +the provider once it is routed, so a turn that later fails or is cancelled still moves it. Each +sub-agent thread keeps its own record, so a sub-agent turn on another provider does not change the +provider its parent's helper calls follow. A +helper call in a conversation the proxy has not seen, in a conversation whose provider has no +mapping, or whose mapped model does not resolve uses `model` exactly as before, including the +`intercept_target_unavailable` refusal below. Mapping a provider to a source model such as +`openai` → `gpt-6-luna` leaves that conversation's helper calls native. The record of each +conversation's provider lives in memory only, holds at most 2048 conversations and starts empty +after a restart. Set it with `PUT /api/shadow-call-settings` (`followConversation` object, or +`null` to clear), `ocx models shadow set --follow-conversation `, or the +**Follow the chat's provider** pickers under Shadow Call Intercept on the Models page. A helper call +that went to a followed model shows the route reason `shadow-follow-conversation` in the request +log. Renaming a provider moves its entry and the routes that name it; deleting a provider removes +both. + +```json +{ + "shadowCallIntercept": { + "enabled": true, + "model": "gpt-5.5", + "followConversation": { + "anthropic": "anthropic/claude-haiku-5-5", + "openai": "gpt-6-luna" + } + } +} +``` + ### When the target is unavailable The replacement is the one destination the operator chose, so a target that stops resolving fails diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 4cde47d605e..e5636c729fd 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -289,7 +289,7 @@ See [Codex prompt layers](/guides/codex-prompt/) for the layer model and the key | `POST /api/update/run` | Asynchronously check a fresh package version, then start an update job, optionally followed by restart | 400 invalid body; 409 `update_restart_unsupervised` when the proxy runs inside a systemd unit other than OpenCodex's own user service, or the worker cannot leave the service cgroup (with or without restart, since the update stops the proxy first); job-specific conflict/error status | | `GET /api/update/status` | Poll an update job by id | 404 unknown job | | `GET, PUT /api/sidecar-settings` | Read or update web-search and vision sidecar model/backend settings | 400 invalid shape, backend, or limit | -| `GET, PUT /api/shadow-call-settings` | Read or update shadow-call interception settings, including `sourceModels`; GET also returns the runtime-owned `sourceModelOptions` inventory | 400 invalid shape or value, including an empty, duplicate, whitespace-bearing, or provider-qualified source prefix, or more than 32 prefixes / 128 characters per prefix; source-list failures carry `code: shadow_call_source_invalid`, target conflicts `code: shadow_call_target_invalid` | +| `GET, PUT /api/shadow-call-settings` | Read or update shadow-call interception settings, including `sourceModels` and the `followConversation` provider → helper-model map (`null` clears it); GET also returns the runtime-owned `sourceModelOptions` inventory | 400 invalid shape or value, including an empty, duplicate, whitespace-bearing, or provider-qualified source prefix, or more than 32 prefixes / 128 characters per prefix; source-list failures carry `code: shadow_call_source_invalid`, target conflicts `code: shadow_call_target_invalid`, an invalid or unresolvable `followConversation` entry `code: shadow_call_follow_invalid` | ### Logs, usage, and storage diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index bc189c7593b..d177b5ab92c 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -148,6 +149,7 @@ export const de: Record = { ...connectionsCopy("de"), ...modelsV2Copy("de"), ...modelsOverallCopy("de"), + ...shadowFollowCopy("de"), ...accountsV2Copy("de"), ...subagentsV2Copy("de"), ...usageV2Copy("de"), diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 0e01dd21ce0..33796af73a6 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -149,6 +150,7 @@ export const en = { ...connectionsCopy("en"), ...modelsV2Copy("en"), ...modelsOverallCopy("en"), + ...shadowFollowCopy("en"), ...accountsV2Copy("en"), ...subagentsV2Copy("en"), ...usageV2Copy("en"), diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts index 065fc0c48f8..40395f97f97 100644 --- a/gui/src/i18n/es.ts +++ b/gui/src/i18n/es.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -145,6 +146,7 @@ export const es = { ...connectionsCopy("es"), ...modelsV2Copy("es"), ...modelsOverallCopy("es"), + ...shadowFollowCopy("es"), ...accountsV2Copy("es"), ...subagentsV2Copy("es"), ...usageV2Copy("es"), diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index f4f45638e26..db809cde1ed 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -147,6 +148,7 @@ export const fr: Record = { ...connectionsCopy("fr"), ...modelsV2Copy("fr"), ...modelsOverallCopy("fr"), + ...shadowFollowCopy("fr"), ...accountsV2Copy("fr"), ...subagentsV2Copy("fr"), ...usageV2Copy("fr"), diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 5d8296f0236..c196ca58a9d 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -147,6 +148,7 @@ export const ja: Record = { ...connectionsCopy("ja"), ...modelsV2Copy("ja"), ...modelsOverallCopy("ja"), + ...shadowFollowCopy("ja"), ...accountsV2Copy("ja"), ...subagentsV2Copy("ja"), ...usageV2Copy("ja"), diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 63973e601ce..16296e43fae 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -147,6 +148,7 @@ export const ko: Record = { ...connectionsCopy("ko"), ...modelsV2Copy("ko"), ...modelsOverallCopy("ko"), + ...shadowFollowCopy("ko"), ...accountsV2Copy("ko"), ...subagentsV2Copy("ko"), ...usageV2Copy("ko"), diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 15476c76247..84ecfb78936 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -149,6 +150,7 @@ export const pt: Record = { ...connectionsCopy("pt"), ...modelsV2Copy("pt"), ...modelsOverallCopy("pt"), + ...shadowFollowCopy("pt"), ...accountsV2Copy("pt"), ...subagentsV2Copy("pt"), ...usageV2Copy("pt"), diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 110e6845ac4..2a13f4b0842 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -147,6 +148,7 @@ export const ru: Record = { ...connectionsCopy("ru"), ...modelsV2Copy("ru"), ...modelsOverallCopy("ru"), + ...shadowFollowCopy("ru"), ...accountsV2Copy("ru"), ...subagentsV2Copy("ru"), ...usageV2Copy("ru"), diff --git a/gui/src/i18n/shadow-follow-copy.ts b/gui/src/i18n/shadow-follow-copy.ts new file mode 100644 index 00000000000..43f1809acc7 --- /dev/null +++ b/gui/src/i18n/shadow-follow-copy.ts @@ -0,0 +1,18 @@ +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; + +/** Shadow-call "follow the conversation's provider" copy (#9096), one row per key in `locales` order. */ +const rows = { + "shadowCall.follow": ["Follow the chat's provider", "채팅의 공급자 따르기", "Anbieter des Chats folgen", "Suivre le fournisseur du chat", "跟随对话的供应商", "跟隨對話的供應商", "Следовать провайдеру чата", "チャットのプロバイダーに合わせる", "Sohbetin sağlayıcısını izle", "Theo nhà cung cấp của cuộc trò chuyện", "Seguir o provedor do chat", "Seguir el proveedor del chat"], + "shadowCall.followHint": ["A helper call uses the model chosen for the provider of its chat's last turn. Providers left on the fixed target, and chats not seen since the proxy started, use the replacement model above.", "보조 호출은 해당 채팅의 마지막 턴을 처리한 공급자에 지정된 모델을 사용합니다. 고정 대상으로 둔 공급자와 프록시 시작 이후 보지 못한 채팅은 위의 대체 모델을 사용합니다.", "Ein Hilfsaufruf nutzt das Modell, das für den Anbieter des letzten Turns seines Chats gewählt ist. Anbieter mit festem Ziel und Chats, die der Proxy seit dem Start nicht gesehen hat, nutzen das Ersatzmodell oben.", "Un appel auxiliaire utilise le modèle choisi pour le fournisseur du dernier tour de son chat. Les fournisseurs laissés sur la cible fixe et les chats non vus depuis le démarrage du proxy utilisent le modèle de remplacement ci-dessus.", "辅助调用使用为其对话上一轮所用供应商选择的模型。保留固定目标的供应商,以及代理启动后尚未见过的对话,使用上方的替换模型。", "輔助呼叫使用為其對話上一輪所用供應商選擇的模型。保留固定目標的供應商,以及代理啟動後尚未見過的對話,使用上方的替換模型。", "Вспомогательный вызов использует модель, выбранную для провайдера последнего хода его чата. Провайдеры с фиксированной целью и чаты, не встречавшиеся с запуска прокси, используют модель замены выше.", "補助呼び出しは、そのチャットの直前のターンを処理したプロバイダーに選んだモデルを使います。固定ターゲットのままのプロバイダーと、プロキシ起動後に見ていないチャットは、上の置き換えモデルを使います。", "Yardımcı çağrı, sohbetinin son turunu işleyen sağlayıcı için seçilen modeli kullanır. Sabit hedefte bırakılan sağlayıcılar ve proxy başladığından beri görülmeyen sohbetler yukarıdaki yedek modeli kullanır.", "Lệnh gọi phụ dùng mô hình đã chọn cho nhà cung cấp của lượt cuối trong cuộc trò chuyện. Nhà cung cấp để ở mục tiêu cố định và cuộc trò chuyện chưa gặp từ khi proxy khởi động dùng mô hình thay thế ở trên.", "Uma chamada auxiliar usa o modelo escolhido para o provedor do último turno do chat. Provedores deixados no alvo fixo e chats não vistos desde o início do proxy usam o modelo de substituição acima.", "Una llamada auxiliar usa el modelo elegido para el proveedor del último turno de su chat. Los proveedores que quedan en el destino fijo y los chats no vistos desde que se inició el proxy usan el modelo de reemplazo de arriba."], + "shadowCall.followFixed": ["Fixed target", "고정 대상", "Festes Ziel", "Cible fixe", "固定目标", "固定目標", "Фиксированная цель", "固定ターゲット", "Sabit hedef", "Mục tiêu cố định", "Alvo fixo", "Destino fijo"], + "models.shadowCallFollowInvalid": ["This provider's helper model is not available. Choose another model.", "이 공급자의 보조 모델을 사용할 수 없습니다. 다른 모델을 선택하세요.", "Das Hilfsmodell für diesen Anbieter ist nicht verfügbar. Wähle ein anderes Modell.", "Le modèle auxiliaire de ce fournisseur n'est pas disponible. Choisissez un autre modèle.", "该供应商的辅助模型不可用。请选择其他模型。", "該供應商的輔助模型無法使用。請選擇其他模型。", "Вспомогательная модель этого провайдера недоступна. Выберите другую модель.", "このプロバイダーの補助モデルは利用できません。別のモデルを選んでください。", "Bu sağlayıcının yardımcı modeli kullanılamıyor. Başka bir model seçin.", "Mô hình phụ của nhà cung cấp này không khả dụng. Hãy chọn mô hình khác.", "O modelo auxiliar deste provedor não está disponível. Escolha outro modelo.", "El modelo auxiliar de este proveedor no está disponible. Elige otro modelo."], +} as const satisfies Record; + +export type ShadowFollowCopyKey = keyof typeof rows; + +export function shadowFollowCopy(locale: Locale): Record { + const index = locales.indexOf(locale); + return Object.fromEntries(Object.entries(rows).map(([key, values]) => [key, values[index]!])) as Record; +} diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index cc4fffaede3..beb3ead7bda 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -148,6 +149,7 @@ export const tr: Record = { ...connectionsCopy("tr"), ...modelsV2Copy("tr"), ...modelsOverallCopy("tr"), + ...shadowFollowCopy("tr"), ...accountsV2Copy("tr"), ...subagentsV2Copy("tr"), ...usageV2Copy("tr"), diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index a9f4d1f1af3..c3e532240a3 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -149,6 +150,7 @@ export const vi: Record = { ...connectionsCopy("vi"), ...modelsV2Copy("vi"), ...modelsOverallCopy("vi"), + ...shadowFollowCopy("vi"), ...accountsV2Copy("vi"), ...subagentsV2Copy("vi"), ...usageV2Copy("vi"), diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index b6f48976af7..4425831d563 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -145,6 +146,7 @@ export const zhTW: Record = { ...connectionsCopy("zh-TW"), ...modelsV2Copy("zh-TW"), ...modelsOverallCopy("zh-TW"), + ...shadowFollowCopy("zh-TW"), ...accountsV2Copy("zh-TW"), ...subagentsV2Copy("zh-TW"), ...usageV2Copy("zh-TW"), diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 9a702934ab5..7c162d33e99 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -8,6 +8,7 @@ import { gatewayClientsCopy } from "./gateway-clients-copy"; import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; +import { shadowFollowCopy } from "./shadow-follow-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; import { subagentsV2Copy } from "./v2-pages/subagents-copy"; import { usageV2Copy } from "./v2-pages/usage-copy"; @@ -147,6 +148,7 @@ export const zh: Record = { ...connectionsCopy("zh"), ...modelsV2Copy("zh"), ...modelsOverallCopy("zh"), + ...shadowFollowCopy("zh"), ...accountsV2Copy("zh"), ...subagentsV2Copy("zh"), ...usageV2Copy("zh"), diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx index e7ac6bfd515..3fc7aa68c9b 100644 --- a/gui/src/pages/Models.tsx +++ b/gui/src/pages/Models.tsx @@ -1952,7 +1952,7 @@ export default function Models({ apiBase, restartEpoch = 0, connected = false, c void setDefaultAliases(!aliases.defaults.global)} label={t("models.useDefaultAliasesGlobal")} /> - void saveShadowCall(patch)} /> + void saveShadowCall(patch)} /> ⓘ} busy={!autoReview}> void saveAutoReview({ enabled: !autoReview?.enabled })} disabled={!autoReview || autoReviewSaving} label={t("models.autoReviewOverride")} /> diff --git a/gui/src/pages/models-shared.ts b/gui/src/pages/models-shared.ts index ac54c6c73b7..fff58e8ac9a 100644 --- a/gui/src/pages/models-shared.ts +++ b/gui/src/pages/models-shared.ts @@ -198,6 +198,8 @@ export interface ShadowCallData { sourceModels?: string[]; /** Runtime-owned source inventory; older runtimes omit it. */ sourceModelOptions?: ShadowCallSourceOption[]; + /** Provider id → helper model for helper calls that follow their chat (#9096); `null` clears it on save. */ + followConversation?: Record | null; } /** @@ -212,6 +214,7 @@ export interface ShadowCallData { export function shadowCallSaveErrorKey(code: unknown): TKey { if (code === "shadow_call_target_invalid") return "models.shadowCallTargetInvalid"; if (code === "shadow_call_source_invalid") return "models.shadowCallSourceInvalid"; + if (code === "shadow_call_follow_invalid") return "models.shadowCallFollowInvalid"; return "models.shadowCallSaveFailed"; } diff --git a/gui/src/pages/shadow-call-follow-conversation.tsx b/gui/src/pages/shadow-call-follow-conversation.tsx new file mode 100644 index 00000000000..525ea0d4875 --- /dev/null +++ b/gui/src/pages/shadow-call-follow-conversation.tsx @@ -0,0 +1,69 @@ +import { useId } from "react"; +import { useT } from "../i18n/shared"; +import { Select, type SelectOption } from "../ui"; +import type { ModelInfo } from "./dashboard-shared"; + +/** + * One helper-model choice per provider for `shadowCallIntercept.followConversation` (#9096). + * "Fixed target" removes the provider from the map, so its chats keep the replacement model. + */ +export function ShadowCallFollowConversation({ + followConversation, + models, + modelOptions, + disabled = false, + saving = false, + onChange, +}: { + followConversation?: Record | null; + models: ModelInfo[]; + modelOptions: SelectOption[]; + disabled?: boolean; + saving?: boolean; + onChange: (followConversation: Record | null) => void; +}) { + const t = useT(); + const hintId = useId(); + const current = followConversation ?? {}; + const offered = new Set(modelOptions.map(option => option.value)); + const providers = [...new Set([ + // Combo rows use the synthetic provider "combo"; they stay selectable as values, not as keys. + ...models.filter(model => offered.has(model.namespaced) && model.provider !== "combo").map(model => model.provider), + ...Object.keys(current), + ])].sort((a, b) => a.localeCompare(b)); + if (providers.length === 0) return null; + + const choose = (provider: string, model: string) => { + const next = { ...current }; + if (model === "") delete next[provider]; + else next[provider] = model; + onChange(Object.keys(next).length > 0 ? next : null); + }; + + return ( +
+ {t("shadowCall.follow")} +
+ {providers.map(provider => { + const value = current[provider] ?? ""; + const options = [{ value: "", label: t("shadowCall.followFixed") }, ...modelOptions]; + if (value && !offered.has(value)) options.push({ value, label: value }); + return ( + + {provider} +