From 2dd7b43a1625dc2c24480ae17651564324909413 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 7 Sep 2026 03:34:54 +0000 Subject: [PATCH 001/116] chore(release): open dev at 2.47.0 before releasing 2.46.0 --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bdf30eb215..0b2d5768c1 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@bitkyc08/opencodex", - "version": "2.46.0", + "version": "2.47.0", "description": "Universal provider proxy for OpenAI Codex & Claude Code — use any LLM with Codex CLI/App/SDK and Claude Code", "type": "module", "main": "./bin/package-main.mjs", From ec799db260fd6c2c2db8d2b027bdfd5e3a9a197d Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 14:22:47 +0900 Subject: [PATCH 002/116] docs(devlog): plan code-mode host contract for routed models --- .../000_plan.md | 141 ++++++++++++ .../010_pre_call_contract.md | 139 ++++++++++++ .../020_post_hoc_annotation.md | 208 ++++++++++++++++++ .../030_docs_and_delivery.md | 74 +++++++ 4 files changed, 562 insertions(+) create mode 100644 devlog/_plan/260907_code_mode_host_contract/000_plan.md create mode 100644 devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md create mode 100644 devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md create mode 100644 devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md diff --git a/devlog/_plan/260907_code_mode_host_contract/000_plan.md b/devlog/_plan/260907_code_mode_host_contract/000_plan.md new file mode 100644 index 0000000000..6f85ef9c4d --- /dev/null +++ b/devlog/_plan/260907_code_mode_host_contract/000_plan.md @@ -0,0 +1,141 @@ +# 000 — Code-mode host contract for routed models: plan + +## Loop-spec + +- Loop archetype: satisfy-spec repair (verifier-defined). No optimization loop. +- Trigger: xai/grok-4.6 retrospective (2026-09-07) on a routed native-Responses Codex session. The + model hit four Codex host contracts that OpenCodex neither states before the first call nor + explains after the failure, then abandoned the right tools for shell heredocs and sleep loops. +- Goal: a routed non-OpenAI model in Codex code mode learns the host's exact argument shape and + waiting protocol up front, and when it still trips, the tool result names the rule it broke. +- Non-goals: rewriting model JavaScript; repairing payloads (`apply-patch-envelope.ts`, + `code-mode-helper-compat.ts`, `bridge.ts`, `parser.ts` untouched); changing OpenAI/ChatGPT + destinations or compaction requests; Lab; GUI; release/version bumps. No local test suite, + typecheck, build, or install in this worktree (user instruction). Merge/release out of scope. +- Verifier: hosted `.github/workflows/ci.yml` on the exact PR head (test shards 1-4 + gates: + typecheck, privacy scan). Local: NOT RUN by instruction. Each conditional path names its + activation test in the decade docs; those tests ride the hosted shards. +- Stop condition: PR open against `dev` with exact-head CI green and receipt bound; then DONE. +- Memory artifact: this unit (`devlog/_plan/260907_code_mode_host_contract/`), the bound + goalplan `.codexclaw/goalplans/code-mode-host-contract-for-routed-models-shared/`, PR body. +- Expected terminal outcomes: DONE (PR open, CI green); NOOP if the contract already exists + (ruled out below); BLOCKED if GitHub/CI infrastructure fails after retries; UNSAFE if a change + would rewrite JavaScript or widen a fail-open write; NEEDS_HUMAN for merge. +- Escalation: main reclaims a slice after two distinct agents fail its packet; pushing a slice to + a worker requires a P-phase amendment. Every dispatch uses `gpt-6-astra` reasoning `high`. +- HOTL bounds: write scope is this worktree on `codex/code-mode-host-contract`; tools are + git/gh/rg/read + `tools.apply_patch`; no token or wall-clock budget was set by the user. + +## Incident (what actually broke) + +All four strings below were read from the installed Codex 0.153.2 binaries +(`codex` and `codex-code-mode-host`, `strings -n 8`), so the wording here is the host's, not a guess. + +| # | Model action | Host response | Where OpenCodex says nothing today | +|---|---|---|---| +| 1 | `tools.apply_patch({ input: "..." })` | `\`apply_patch\` expects a string input` | Nudge says "host-executed" and describes markers, never the argument type | +| 2 | patch built in a template literal opening with a newline | `The first line of the patch must be '*** Begin Patch'` (also `The last line of the patch must be '*** End Patch'`) | Nudge says "begin exactly with" but not that leading whitespace/newline counts | +| 3 | `for i in 1..20; sleep 1` inside one `exec_command` | (no error; the turn just blocks) | No sentence about `session_id` + `write_stdin` with empty `chars` | +| 4 | `import x from "..."` inside the isolate | `Unsupported import in exec: ...` | Cursor normalize matches lowercase `unsupported import in exec` only; shared nudge silent | + +After 1 and 2 the model stopped using `apply_patch` entirely. That is the same pattern +`devlog/_fin/260813_260813-nudge-apply-patch-forbid/` recorded: once the tool feels forbidden or +broken, routed models fall back to `python3`/`cat < --exit-status` on the PR head SHA | + +Single PR (one reviewable diff, ~150 source lines + tests); no stack (DEV-STACK-OPT-IN-01). + +## Accept criteria (goalplan c1–c4) + +- c1: pre-call guidance present in all three code-mode injection sites, absent for flat/OpenAI catalogs. +- c2: exec results carrying any of the four host markers are annotated on routed Responses, Kiro, Cursor; non-matching output byte-identical; already-annotated text not doubled. +- c3: PR open against `dev` with the template body; exact-head hosted CI success; receipt bound. +- c4: each A gate has an independent `gpt-6-astra` audit; `structure/04` and docs-site guide updated. + +## Verifiers (PLAN-VERIFIER-REAL-01) + +Local execution is forbidden for this unit, so every row below is NOT RUN locally and observed on +hosted CI. "Reads the target" is proven by import paths in the named test files: + +- `bun test tests/adapters/tool-catalog-nudge.test.ts` — imports `../../src/adapters/tool-catalog-nudge` and `exec-tool-result-normalize` (file lines 2-7). Reads wp1 target. +- `bun test tests/providers/cursor/cursor-tool-definitions.test.ts` — imports `tool-guidance` (line 762-ish `buildCursorToolGuidanceSystemNote`). Reads wp1 Cursor target. +- `bun test tests/responses/openai-responses-passthrough.test.ts` — imports `responses-code-mode` (line 5). Reads wp1+wp2 native target. +- `bun test tests/providers/kiro/kiro-adapter.test.ts` — imports `exec-tool-result-normalize` (line 16) and exercises `createKiroAdapter`. Reads wp1+wp2 Kiro target. +- `bun test tests/providers/cursor/cursor-toolresult-normalize.test.ts` — imports `tool-result-normalize`. Reads wp2 Cursor target. +- `bun test tests/adapters/exec-tool-result-normalize.test.ts` (NEW in wp2) — imports the shared module directly. +- `bun test tests/test-layout-tooling.test.ts` — reads `scripts/test-layout/layout.json` and `tests/fixtures/test-layout-expected.json`; fails if the new file is unregistered. +- `bun run typecheck`, `bun run privacy:scan` — CI `gates` job. + +## Enforcement bypass (PLAN-BYPASS-NAMED-01) + +This unit adds guidance, not enforcement. Tier: none (prose the model may ignore). Executing +surface: request translation in the adapters. Known bypass: the model disregards the sentence; +the host still rejects the call exactly as today. Residual risk: none beyond status quo; the +post-hoc annotation cannot make a failed call succeed. Wording: this is an "early warning", not +enforcement. Final layer: Codex host validation (unchanged). + +## SoT sync targets (SOT-SYNC-01) + +- `structure/04_transports-and-sidecars.md` paragraph at ~line 325 ("Native routed Responses code-mode turns also receive…") — extend with the host contract. +- `docs-site/src/content/docs/guides/codex-integration.md` "Routed local tools" section (~line 315) — one paragraph; translated locales are not edited (they must not contradict, and adding text to English only is additive). + diff --git a/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md b/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md new file mode 100644 index 0000000000..9b41dd1653 --- /dev/null +++ b/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md @@ -0,0 +1,139 @@ +# 010 — wp1: pre-call host contract sentence and its three injection sites + +Depends on 000_plan.md. Class C2 (conventional slice across an existing shared module and its +three known consumers; no new abstraction, no new seam). Loop archetype satisfy-spec. + +## MODIFY `src/adapters/exec-tool-result-normalize.ts` + +Append after `CODE_MODE_RESULT_ECHO_SENTENCE` (line ~117): + +```ts +/** + * The host rules a routed model most often breaks on its first code-mode edit or wait, stated + * BEFORE the call. Wording tracks the Codex host (0.153.2): `apply_patch` rejects a non-string + * argument with "expects a string input" and a body whose first line is not the marker with + * "The first line of the patch must be '*** Begin Patch'"; the isolate rejects ES imports with + * "Unsupported import in exec"; a long command yields a session_id for write_stdin polling. + * Live 2026-09-07: xai/grok-4.6 hit the first two, abandoned apply_patch for heredoc writes, + * blocked a turn in a shell sleep loop, and died once on an import. None of that is a model + * defect the proxy can repair (see devlog/_plan/260905_apply_patch_envelope_gap/010 MODE B); + * it is a contract the proxy had not stated. + */ +export const CODE_MODE_HOST_CONTRACT_SENTENCE = + "Host contract for the nested helpers: `tools.apply_patch(patch)` takes exactly one string, never an object such as `{input: ...}`; the string's first line must be exactly `*** Begin Patch` and its last line `*** End Patch` with no leading newline, indentation, or extra asterisks, so start the literal at the marker. The isolate has no `import`, `require`, or module loader — use only the `tools`, `text`, `notify`, `store`/`load`, and `ALL_TOOLS` globals. For a command that may outlive `yield_time_ms`, let `tools.exec_command` return a `session_id` and poll it with `tools.write_stdin({session_id, chars: \"\"})` on later calls instead of blocking a shell in a sleep loop."; +``` + +## MODIFY `src/adapters/tool-catalog-nudge.ts` + +Line 7 import: `import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE } from "./exec-tool-result-normalize";` + +Line 124 code-mode branch. BEFORE (tail of the string): + +``` +... + CODE_MODE_RESULT_ECHO_SENTENCE + " Nested `tools.apply_patch(input)` is host-executed: ... rejected by Codex before the file is touched." +``` + +AFTER: + +``` +... + CODE_MODE_RESULT_ECHO_SENTENCE + " Nested `tools.apply_patch(input)` is host-executed: ... rejected by Codex before the file is touched. " + CODE_MODE_HOST_CONTRACT_SENTENCE +``` + +The flat-catalog branch (`If a listed tool exposes nested helpers…`) is unchanged: a shell bridge +echoes stdout and has no isolate, so the sentence would be false there. + +## MODIFY `src/adapters/cursor/tool-guidance.ts` + +Line 2 import: add `CODE_MODE_HOST_CONTRACT_SENTENCE`. + +Line 190 (`codeMode ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no \`require\`, …"`). BEFORE: + +```ts +codeMode + ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers." + : undefined, +``` + +AFTER: + +```ts +codeMode + ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers. " + CODE_MODE_HOST_CONTRACT_SENTENCE + : undefined, +``` + +## MODIFY `src/adapters/responses-code-mode.ts` + +Line 3 import: add `CODE_MODE_HOST_CONTRACT_SENTENCE`. + +Instructions (line ~46). BEFORE: + +```ts +instructions: instructions.includes(CODE_MODE_RESULT_ECHO_SENTENCE) + ? instructions : [instructions, CODE_MODE_RESULT_ECHO_SENTENCE].filter(Boolean).join("\n\n"), +``` + +AFTER (idempotent per sentence, so a replayed body that already carries the echo sentence but +not the contract gains only the missing one): + +```ts +instructions: appendMissing(instructions, [CODE_MODE_RESULT_ECHO_SENTENCE, CODE_MODE_HOST_CONTRACT_SENTENCE]), +``` + +with a module-local helper: + +```ts +function appendMissing(instructions: string, sentences: readonly string[]): string { + return sentences.reduce( + (acc, sentence) => acc.includes(sentence) ? acc : [acc, sentence].filter(Boolean).join("\n\n"), + instructions, + ); +} +``` + +The exec `input` parameter description (line 27) keeps only the echo sentence: it is a schema +string, and Kiro-style description limiters bound injected instructions, not parameter text, but +the contract is long and belongs in `instructions` where the existing test already asserts. + +Activation scenario: any routed native Responses request whose visible catalog has a bare freeform +`exec` and no bare shell bridge, to a non-OpenAI destination, not a compaction request — the +exact gate at `responses-code-mode.ts:35-37`. Observable effect: `wire.instructions` ends with the +contract sentence. + +## TESTS (updated in place; no new file in wp1) + +`tests/adapters/tool-catalog-nudge.test.ts` +- In `"defines nested helper names as non-callable unless separately listed"` add: + `expect(note).toContain(CODE_MODE_HOST_CONTRACT_SENTENCE);` and + `expect(note).toContain("write_stdin({session_id, chars: \"\"})");`. +- In `"keeps the generic nested-helper parent-tool rule when exec is not listed"` add + `expect(note).not.toContain("Host contract for the nested helpers");`. +- Import the new constant on line 7. + +`tests/providers/cursor/cursor-tool-definitions.test.ts` +- In `"teaches the nested-helper contract instead of a top-level shell bridge"` (line ~754) add + `expect(note).toContain("takes exactly one string");` and + `expect(note).toContain("write_stdin");`. +- In `"keeps flat-catalog shell-bridge guidance when a bare bridge is advertised"` add + `expect(note).not.toContain("Host contract for the nested helpers");`. + +`tests/responses/openai-responses-passthrough.test.ts` +- `"first native request carries the echo rule…"` line 54 BEFORE: + `expect(wire.instructions).toBe(\`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}\`);` + AFTER: + `expect(wire.instructions).toBe(\`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}\n\n${CODE_MODE_HOST_CONTRACT_SENTENCE}\`);` +- `"does not duplicate instructions…"` already asserts idempotence; add a case where the body's + instructions already contain the echo sentence and assert exactly one contract sentence is appended. +- `"official OpenAI and non-code-mode catalogs remain untouched"`: add + `expect(JSON.stringify(wire)).not.toContain("Host contract for the nested helpers")` inside the native loop. + +`tests/providers/kiro/kiro-adapter.test.ts` +- In `"names ALL_TOOLS when a freeform exec is advertised…"` (line ~1817) add + `expect(content).toContain("Host contract for the nested helpers");` — proves the sentence + survives Kiro's `boundedInjectedInstruction` (16 384 chars) on the real wire prompt. + +## Verification (C, hosted only) + +NOT RUN locally by instruction. Hosted CI shards run the four files above; `gates` runs typecheck +and privacy scan. Evidence: `gh run list --branch codex/code-mode-host-contract` + `gh run view --exit-status`. + diff --git a/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md new file mode 100644 index 0000000000..105a592c2d --- /dev/null +++ b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md @@ -0,0 +1,208 @@ +# 020 — wp2: post-hoc annotation of host failures on exec results + +Depends on 010 (the pre-call sentence names the same rules this half explains after the fact; the +two must share wording, which is why both live in one module). Class C2. + +## MODIFY `src/adapters/exec-tool-result-normalize.ts` + +Append after `CODE_MODE_HOST_CONTRACT_SENTENCE`: + +```ts +/** + * Post-hoc half of the host contract: the four host strings a routed model reads inside a + * non-error exec result, each paired with the rule it broke. Markers are compared + * case-insensitively because the host writes "Unsupported import in exec: " while + * earlier Cursor guidance matched the lowercase form; one table, one owner, so the + * recovery text can never drift from the pre-call sentence above. + */ +export const CODE_MODE_HOST_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; guidance: string }> = [ + { + marker: "expects a string input", + guidance: "tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.", + }, + { + marker: "the first line of the patch must be", + guidance: "The patch string must begin at `*** Begin Patch` with no leading newline, indentation, or extra asterisks; start the literal on the marker line.", + }, + { + marker: "the last line of the patch must be", + guidance: "The patch string must end with `*** End Patch` as its final line, with no trailing text or extra asterisks.", + }, + { + marker: "unsupported import in exec", + guidance: "Imports are not available in this exec context; use the injected globals (tools, text, notify, store, load, ALL_TOOLS) instead.", + }, +]; + +const HOST_FAILURE_RECOVERY_PREFIX = "[recovery: "; + +/** + * Append a one-line recovery hint when an exec-bridge result carries a known host failure string. + * Returns undefined when the result is not an exec-bridge tool, no marker matches, or a recovery + * line is already present, so callers keep their own fallback and never double-annotate. + */ +export function annotateCodeModeHostFailure( + text: string, + options: { toolName?: string; toolNamespace?: string } = {}, +): string | undefined { + if (!isCodexExecBridgeTool(options.toolName, options.toolNamespace)) return undefined; + if (text.includes(HOST_FAILURE_RECOVERY_PREFIX)) return undefined; + const lower = text.toLowerCase(); + const hit = CODE_MODE_HOST_FAILURE_GUIDANCE.find(({ marker }) => lower.includes(marker)); + return hit ? `${text}\n${HOST_FAILURE_RECOVERY_PREFIX}${hit.guidance}]` : undefined; +} +``` + +The Cursor guidance string for the import row is kept byte-identical to today's +(`"Imports are not available in this exec context; use the injected globals instead."` extended with +the global list) so `cursor-toolresult-normalize.test.ts:101` (`"injected globals"`) still matches. + +## MODIFY `src/adapters/responses-code-mode.ts` + +Line 55 BEFORE: + +```ts +const normalized = text === undefined ? undefined : normalizeEmptyExecToolResultText(text, { toolName: "exec" }); +``` + +AFTER: + +```ts +const normalized = text === undefined + ? undefined + : normalizeEmptyExecToolResultText(text, { toolName: "exec" }) + ?? annotateCodeModeHostFailure(text, { toolName: "exec" }); +``` + +Import `annotateCodeModeHostFailure` on line 3. Empty-wrapper first: an empty result can never +carry a marker, so the order is only for clarity. Activation: paired `custom_tool_call_output` +whose text contains e.g. `\`apply_patch\` expects a string input`; observable effect: output ends +with `[recovery: tools.apply_patch takes exactly one string argument…]`, and `input[0]` (the +program) is the same object reference as before. + +## MODIFY `src/adapters/kiro.ts` + +Line 47 import: add `annotateCodeModeHostFailure`. + +Lines 758-762 BEFORE: + +```ts +const normalizedExecText = normalizeEmptyExecToolResultText(text, { + toolName: tr.toolName, + toolNamespace: tr.toolNamespace, +}); +const resultText = normalizedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); +``` + +AFTER: + +```ts +const execOptions = { toolName: tr.toolName, toolNamespace: tr.toolNamespace }; +const normalizedExecText = normalizeEmptyExecToolResultText(text, execOptions) + ?? annotateCodeModeHostFailure(text, execOptions); +const resultText = normalizedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); +``` + +`rawGroupText` (line 774) already keeps `text` whenever `normalizedExecText !== EMPTY_EXEC_OUTPUT_MESSAGE`, +so the adjacent-result grouping path carries the RAW failure text; the annotated text is what the +single-result path emits. Line 774 is changed so a grouped result carries the annotated text too: + +BEFORE: `? text : undefined;` AFTER: `? (normalizedExecText ?? text) : undefined;` + +(For the empty-wrapper case `normalizedExecText === EMPTY_EXEC_OUTPUT_MESSAGE` short-circuits the +outer condition first, so that branch is unchanged.) + +## MODIFY `src/adapters/cursor/tool-result-normalize.ts` + +Import `CODE_MODE_HOST_FAILURE_GUIDANCE` from `../exec-tool-result-normalize`. + +`RUNTIME_FAILURE_GUIDANCE` (lines 50-67): DELETE the `unsupported import in exec` entry and spread +the shared table instead: + +```ts +const RUNTIME_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; guidance: string }> = [ + { marker: "SkyComputerUseError", guidance: "…" }, + { marker: "sky is not defined", guidance: "…" }, + { marker: "has already been declared", guidance: "…" }, + ...CODE_MODE_HOST_FAILURE_GUIDANCE, +]; +``` + +Loop at line 109 BEFORE: `if (text.includes(marker))` AFTER: compare against `text.toLowerCase()` +for the shared rows only — simplest correct form is to lowercase both sides for every row, since the +three Cursor markers contain no case-sensitive collisions (`SkyComputerUseError` lowercased still +matches only itself). Cursor policy (`isError: true` on a match) is unchanged; the shared helper is +not used here because Cursor owns its `isError` decision. + +## NEW `tests/adapters/exec-tool-result-normalize.test.ts` + +```ts +import { describe, expect, test } from "bun:test"; +import { + CODE_MODE_HOST_CONTRACT_SENTENCE, + CODE_MODE_HOST_FAILURE_GUIDANCE, + annotateCodeModeHostFailure, +} from "../../src/adapters/exec-tool-result-normalize"; + +describe("code-mode host failure annotation", () => { + test.each(CODE_MODE_HOST_FAILURE_GUIDANCE.map(row => [row.marker, row.guidance]))( + "annotates an exec result carrying %p", (marker, guidance) => { + const text = `Script failed\nOutput:\nError: ${marker.toUpperCase()}`; + const out = annotateCodeModeHostFailure(text, { toolName: "exec" }); + expect(out).toBe(`${text}\n[recovery: ${guidance}]`); + }); + + test("matches the host's real capitalisation for imports", () => { + const out = annotateCodeModeHostFailure("Unsupported import in exec: node:fs", { toolName: "exec" }); + expect(out).toContain("injected globals"); + }); + + test("leaves non-exec tools, non-matching text and already-annotated text alone", () => { + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "read_file" })).toBeUndefined(); + expect(annotateCodeModeHostFailure("all good", { toolName: "exec" })).toBeUndefined(); + const once = annotateCodeModeHostFailure("expects a string input", { toolName: "exec" })!; + expect(annotateCodeModeHostFailure(once, { toolName: "exec" })).toBeUndefined(); + }); + + test("every failure row is a rule the pre-call sentence already states", () => { + // One owner, two halves: a model must never be told one thing before the call and another after. + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("exactly one string"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("*** Begin Patch"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("*** End Patch"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("no `import`"); + }); +}); +``` + +Register: `scripts/test-layout/layout.json` → `explicit`: `"exec-tool-result-normalize.test.ts": "adapters"` +(alphabetical, after `"exec-…"` neighbours or before `"identity-…"`); same key in +`tests/fixtures/test-layout-expected.json`. `tests/test-layout-tooling.test.ts` names a missing one. + +## Updated tests + +`tests/responses/openai-responses-passthrough.test.ts` — add to the code-mode describe: + +```ts +test("annotates a paired exec result that carries a host failure string", () => { + const failure = "Script failed\nWall time 0.1 seconds\nOutput:\nError: `apply_patch` expects a string input"; + const body = raw(failure); + const wire = JSON.parse(createResponsesPassthroughAdapter(routed).buildRequest(parseRequest(body)).body); + expect(wire.input[1].output).toBe(`${failure}\n[recovery: tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.]`); + expect(JSON.parse(wire.input[0].arguments).input).toBe(body.input[0].input); +}); +``` + +`tests/providers/kiro/kiro-adapter.test.ts` — beside the `EMPTY_EXEC_OUTPUT_MESSAGE` case at +line ~336, add one toolResult with `toolName: "exec"` and content +`"The first line of the patch must be '*** Begin Patch'"`; assert the emitted Kiro tool-result +text ends with `[recovery: The patch string must begin at …]`. + +`tests/providers/cursor/cursor-toolresult-normalize.test.ts` — line 101 row stays; add +`["Unsupported import in exec: node:fs", "injected globals"]` and +`["\`apply_patch\` expects a string input", "exactly one string"]` to the `test.each` table. + +## Verification (C, hosted only) + +NOT RUN locally. Hosted shards run the new and updated files; `tests/test-layout-tooling.test.ts` +proves registration. Activation for each conditional row is the marker-specific test above. + diff --git a/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md new file mode 100644 index 0000000000..8b7a848c69 --- /dev/null +++ b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md @@ -0,0 +1,74 @@ +# 030 — wp3: SoT sync, push, PR, exact-head CI receipt + +Depends on 020. Class C2 for the docs; the push/PR step is external state and is authorized by +the user for this branch only ("no verify로 푸시", "pr올려봐"). Merge is not authorized. + +## MODIFY `structure/04_transports-and-sidecars.md` + +After the paragraph ending "…or reconstruct output that the code-mode host never emitted." (~line 331) +add one paragraph: + +``` +Routed code-mode turns also carry the host contract for the nested helpers, stated in the same three +injection sites as the result-emission rule (shared catalog nudge, Cursor code-mode guidance, native +routed Responses instructions): `tools.apply_patch` takes one string whose first and last lines are +the bare patch markers, the isolate has no `import`/`require`, and a command that outlives +`yield_time_ms` is polled through `write_stdin` with empty `chars` rather than a shell sleep loop. +When a paired exec result still carries one of the host's failure strings ("expects a string +input", "The first line of the patch must be", "The last line of the patch must be", "Unsupported +import in exec"), the routed Responses, Kiro, and Cursor result paths append a one-line recovery +hint naming the broken rule. Both halves live in `src/adapters/exec-tool-result-normalize.ts` so +the pre-call and post-hoc wording cannot drift. Nothing rewrites the model's JavaScript or its +patch payload; the host still rejects the call exactly as before. +``` + +Add a Decision Log entry in the file's existing format (목적과 의도 / 기존 구현 및 제약 조건 / +검토한 주요 대안 / 선택한 방식 / 장점, 단점 및 영향) recording: purpose = stop routed models +abandoning apply_patch after two host rejections; alternatives = repair the argument shape in the +proxy (rejected: MODE B ambiguity, fail-open write), Cursor-only fix (rejected: incident was native +Responses); chosen = shared pair in one module; impact = longer system prompt on code-mode turns +(~600 chars), no behaviour change for OpenAI destinations or flat catalogs. + +## MODIFY `docs-site/src/content/docs/guides/codex-integration.md` + +In "Routed local tools" after the apply_patch conversion paragraph (~line 331) add: + +``` +Routed code-mode turns are also told the host's rules for the nested helpers before the first +call — `tools.apply_patch` takes one string starting at `*** Begin Patch`, the isolate has no +`import`, and long-running commands are polled with `write_stdin` — and when a result still +carries one of the host's failure messages, opencodex appends a one-line hint naming the rule. +The model's code and patch text are never rewritten. +``` + +Translated locales (7 files) are not edited; the English source gains a paragraph they do not +contradict. + +## Delivery steps (t3b) + +1. `git add -A devlog/_plan/260907_code_mode_host_contract src tests scripts structure docs-site` + — inspect `git diff --cached --stat` before every commit; only this unit's paths. +2. Commits already made per work-phase with `--no-verify` (wp0 docs, wp1, wp2, wp3 docs). +3. `git push --no-verify -u origin codex/code-mode-host-contract`. +4. `gh pr create --base dev --title "fix(code-mode): state the host contract for nested helpers and annotate host failures" --body-file .tmp/pr-body.md` + — body follows `.github/PULL_REQUEST_TEMPLATE.md` (Summary / Verification / Checklist), lists + local checks as NOT RUN, names hosted CI as the verifier. No `gui` mention (no screenshot rule). +5. Poll: `gh run list --branch codex/code-mode-host-contract --json databaseId,headSha,status,conclusion` + via `exec_command` short calls (each < 30 s); `gh run watch` is NOT used inside one call. +6. Receipt: at phase C, `cxc receipt test --session --cwd -- gh run view --exit-status` + where `` is the Cross-platform CI run whose `headSha` equals `git rev-parse HEAD`. + If the head moves (review fix), a fresh run and fresh receipt are required. + +## Verification (C) + +- `gh run view --exit-status` exit 0 on the exact head; `gh pr view --json headRefOid` equals HEAD. +- `gh pr checks ` lists test 1/4..4/4, gates, storage policy, api usage as pass. +- Local suite / typecheck / build: NOT RUN (instruction). + +## D record + +Append `040_delivery_record.md` with PR number, head SHA, CI run id, per-job results, what did not +improve (LOOP-PESSIMIST-01: prose cannot force compliance; effect on real Grok defect rate is +unmeasured until a live re-probe), and the residual: Anthropic/Google/OpenAI-chat/command-code +tool-result paths do not annotate host failures because they have no exec-result seam today. + From 041aec04af744c2243be3e67b4e30a64aafa598e Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 14:36:06 +0900 Subject: [PATCH 003/116] docs(devlog): fold audit round 1 into the code-mode host contract roadmap --- .../000_plan.md | 218 +++++++------ .../010_pre_call_contract.md | 206 +++++++----- .../020_post_hoc_annotation.md | 300 ++++++++++++------ .../030_docs_and_delivery.md | 74 +++-- 4 files changed, 481 insertions(+), 317 deletions(-) diff --git a/devlog/_plan/260907_code_mode_host_contract/000_plan.md b/devlog/_plan/260907_code_mode_host_contract/000_plan.md index 6f85ef9c4d..406c2c186d 100644 --- a/devlog/_plan/260907_code_mode_host_contract/000_plan.md +++ b/devlog/_plan/260907_code_mode_host_contract/000_plan.md @@ -1,141 +1,159 @@ # 000 — Code-mode host contract for routed models: plan +Revision 2 after audit round 1 (gpt-6-astra explorer, VERDICT: FAIL, 8 blockers). Synthesis and +dispositions are in the "Audit round 1" section at the end; the body below is the amended plan. + ## Loop-spec - Loop archetype: satisfy-spec repair (verifier-defined). No optimization loop. - Trigger: xai/grok-4.6 retrospective (2026-09-07) on a routed native-Responses Codex session. The - model hit four Codex host contracts that OpenCodex neither states before the first call nor - explains after the failure, then abandoned the right tools for shell heredocs and sleep loops. -- Goal: a routed non-OpenAI model in Codex code mode learns the host's exact argument shape and - waiting protocol up front, and when it still trips, the tool result names the rule it broke. -- Non-goals: rewriting model JavaScript; repairing payloads (`apply-patch-envelope.ts`, - `code-mode-helper-compat.ts`, `bridge.ts`, `parser.ts` untouched); changing OpenAI/ChatGPT - destinations or compaction requests; Lab; GUI; release/version bumps. No local test suite, - typecheck, build, or install in this worktree (user instruction). Merge/release out of scope. -- Verifier: hosted `.github/workflows/ci.yml` on the exact PR head (test shards 1-4 + gates: - typecheck, privacy scan). Local: NOT RUN by instruction. Each conditional path names its - activation test in the decade docs; those tests ride the hosted shards. -- Stop condition: PR open against `dev` with exact-head CI green and receipt bound; then DONE. -- Memory artifact: this unit (`devlog/_plan/260907_code_mode_host_contract/`), the bound - goalplan `.codexclaw/goalplans/code-mode-host-contract-for-routed-models-shared/`, PR body. -- Expected terminal outcomes: DONE (PR open, CI green); NOOP if the contract already exists - (ruled out below); BLOCKED if GitHub/CI infrastructure fails after retries; UNSAFE if a change - would rewrite JavaScript or widen a fail-open write; NEEDS_HUMAN for merge. + model hit Codex host contracts that OpenCodex neither states before the first call nor explains + after the failure, then abandoned the right tools for shell heredocs and sleep loops. +- Goal: a routed non-OpenAI model in Codex code mode learns the host's argument shape and waiting + protocol up front, and when it still trips, the exec result names the rule it broke. +- Non-goals: rewriting model JavaScript; new payload repair (`apply-patch-envelope.ts`, + `code-mode-helper-compat.ts`, `bridge.ts`, `parser.ts` untouched); OpenAI/ChatGPT destinations + or compaction requests; Lab; GUI; version bumps; annotation on Anthropic/Google/OpenAI-chat/ + command-code result paths (they have no exec-result seam today). No local test suite, typecheck, + build, or install in this worktree (user instruction). Merge/release out of scope. +- Verifier: hosted `.github/workflows/ci.yml` on the exact head of each pushed work-phase (PR + `pull_request` trigger; test shards 1-4 + `gates` typecheck/privacy). Local: NOT RUN. +- Stop condition: PR ready-for-review against `dev` with exact-head CI green and receipt bound. +- Memory artifact: this unit, the bound goalplan + `.codexclaw/goalplans/code-mode-host-contract-for-routed-models-shared/`, and the PR body. +- Expected terminal outcomes: DONE (PR open, CI green); NOOP ruled out below; BLOCKED if + GitHub/CI fails after retries; UNSAFE if a change would rewrite JavaScript or widen a fail-open + write; NEEDS_HUMAN for merge. - Escalation: main reclaims a slice after two distinct agents fail its packet; pushing a slice to - a worker requires a P-phase amendment. Every dispatch uses `gpt-6-astra` reasoning `high`. -- HOTL bounds: write scope is this worktree on `codex/code-mode-host-contract`; tools are - git/gh/rg/read + `tools.apply_patch`; no token or wall-clock budget was set by the user. - -## Incident (what actually broke) - -All four strings below were read from the installed Codex 0.153.2 binaries -(`codex` and `codex-code-mode-host`, `strings -n 8`), so the wording here is the host's, not a guess. + a worker requires a P-phase amendment. Every dispatch uses `gpt-6-astra`, reasoning `high`. +- HOTL bounds: write scope is this worktree on `codex/code-mode-host-contract`; push of that branch + and PR creation are authorized by the user; no token or wall-clock budget was set. -| # | Model action | Host response | Where OpenCodex says nothing today | -|---|---|---|---| -| 1 | `tools.apply_patch({ input: "..." })` | `\`apply_patch\` expects a string input` | Nudge says "host-executed" and describes markers, never the argument type | -| 2 | patch built in a template literal opening with a newline | `The first line of the patch must be '*** Begin Patch'` (also `The last line of the patch must be '*** End Patch'`) | Nudge says "begin exactly with" but not that leading whitespace/newline counts | -| 3 | `for i in 1..20; sleep 1` inside one `exec_command` | (no error; the turn just blocks) | No sentence about `session_id` + `write_stdin` with empty `chars` | -| 4 | `import x from "..."` inside the isolate | `Unsupported import in exec: ...` | Cursor normalize matches lowercase `unsupported import in exec` only; shared nudge silent | +## Incident and live host evidence -After 1 and 2 the model stopped using `apply_patch` entirely. That is the same pattern -`devlog/_fin/260813_260813-nudge-apply-patch-forbid/` recorded: once the tool feels forbidden or -broken, routed models fall back to `python3`/`cat <` (host string; capital U) | -`src/adapters/exec-tool-result-normalize.ts` already owns one "pair": a pre-call sentence -(`CODE_MODE_RESULT_ECHO_SENTENCE`) and a post-hoc repair (`EMPTY_EXEC_OUTPUT_MESSAGE`), kept in one -file so the two never drift. The pre-call sentence is injected by three consumers: +So the Grok report's "blank line before the template literal" was not itself the rejection; the +"first line" error fires for a decorated marker, a code fence, prose, or any non-marker first +token. The pre-call sentence and recovery hints below describe exactly that and do not claim the +host rejects surrounding whitespace. -- `src/adapters/tool-catalog-nudge.ts:124` (shared: Anthropic, Google, Kiro, OpenAI-chat, command-code) -- `src/adapters/cursor/tool-guidance.ts:187-190` (Cursor code-mode branch) -- `src/adapters/responses-code-mode.ts:27,47` (native routed Responses instructions + exec input description) +The fourth contract has no error string: a shell `for i in 1..20; sleep 1` inside one +`exec_command` simply blocks the call, while the host's own protocol is to let the call return a +`session_id` and poll with `tools.write_stdin({session_id, chars: ""})`. -and the post-hoc repair runs at: +After the two apply_patch rejections the model stopped using apply_patch entirely — the pattern +`devlog/_fin/260813_260813-nudge-apply-patch-forbid/` recorded: once the tool feels broken, routed +models fall back to `python3`/`cat < --exit-status` on the PR head SHA | +Each implementation phase ends with an authorized `git push --no-verify` and gets exact-head hosted +CI as its C verifier (audit blocker 5). The PR is opened as a draft at wp1 so `pull_request` CI +exists for every later head, and is marked ready in wp3. + +| WP | Doc | Slice | Depends on | C verifier | +|----|-----|-------|------------|-----------| +| wp0 | this file + 010/020/030 | docs-only roadmap | — | audit of the docs | +| wp1 | 010_pre_call_contract.md | shared sentence + three injection sites + tests; push; draft PR | wp0 | exact-head CI on the wp1 head | +| wp2 | 020_post_hoc_annotation.md | shared annotate helper + three result seams + tests; push | wp1 | exact-head CI on the wp2 head | +| wp3 | 030_docs_and_delivery.md | structure + docs-site sync, PR body, ready-for-review, receipt | wp2 | exact-head CI on the final head | -Single PR (one reviewable diff, ~150 source lines + tests); no stack (DEV-STACK-OPT-IN-01). +Single PR; no stack (DEV-STACK-OPT-IN-01). ## Accept criteria (goalplan c1–c4) - c1: pre-call guidance present in all three code-mode injection sites, absent for flat/OpenAI catalogs. -- c2: exec results carrying any of the four host markers are annotated on routed Responses, Kiro, Cursor; non-matching output byte-identical; already-annotated text not doubled. -- c3: PR open against `dev` with the template body; exact-head hosted CI success; receipt bound. +- c2: exec results carrying any of the four host markers are annotated on routed Responses, Kiro (single and grouped), Cursor (text only, `isError` unchanged); non-matching output byte-identical; already-annotated text not doubled on replay. +- c3: PR ready against `dev` with the template body; exact-head hosted CI success; receipt bound. - c4: each A gate has an independent `gpt-6-astra` audit; `structure/04` and docs-site guide updated. ## Verifiers (PLAN-VERIFIER-REAL-01) -Local execution is forbidden for this unit, so every row below is NOT RUN locally and observed on -hosted CI. "Reads the target" is proven by import paths in the named test files: +Local execution is forbidden for this unit, so every row is NOT RUN locally and observed on hosted +CI. "Reads the target" is proven by import chains: -- `bun test tests/adapters/tool-catalog-nudge.test.ts` — imports `../../src/adapters/tool-catalog-nudge` and `exec-tool-result-normalize` (file lines 2-7). Reads wp1 target. -- `bun test tests/providers/cursor/cursor-tool-definitions.test.ts` — imports `tool-guidance` (line 762-ish `buildCursorToolGuidanceSystemNote`). Reads wp1 Cursor target. -- `bun test tests/responses/openai-responses-passthrough.test.ts` — imports `responses-code-mode` (line 5). Reads wp1+wp2 native target. -- `bun test tests/providers/kiro/kiro-adapter.test.ts` — imports `exec-tool-result-normalize` (line 16) and exercises `createKiroAdapter`. Reads wp1+wp2 Kiro target. -- `bun test tests/providers/cursor/cursor-toolresult-normalize.test.ts` — imports `tool-result-normalize`. Reads wp2 Cursor target. -- `bun test tests/adapters/exec-tool-result-normalize.test.ts` (NEW in wp2) — imports the shared module directly. -- `bun test tests/test-layout-tooling.test.ts` — reads `scripts/test-layout/layout.json` and `tests/fixtures/test-layout-expected.json`; fails if the new file is unregistered. +- `tests/adapters/tool-catalog-nudge.test.ts` imports `../../src/adapters/tool-catalog-nudge` (line 2) and `exec-tool-result-normalize` (line 7). wp1 target. +- `tests/providers/cursor/cursor-tool-definitions.test.ts` imports `buildCursorToolGuidanceSystemNote` through `../../../src/adapters/cursor/tool-definitions` (lines 6-22), which re-exports `tool-guidance`. wp1 Cursor target. +- `tests/responses/openai-responses-passthrough.test.ts` imports `responses-code-mode` (line 5). wp1+wp2 native target. +- `tests/providers/kiro/kiro-adapter.test.ts` imports `exec-tool-result-normalize` (line 16) and drives `createKiroAdapter`. wp1+wp2 Kiro target. +- `tests/providers/cursor/cursor-toolresult-normalize.test.ts` imports `tool-result-normalize` (line 5). wp2 Cursor target. +- `tests/adapters/exec-tool-result-normalize.test.ts` (NEW, wp2) imports the shared module. +- `tests/test-layout-tooling.test.ts` reads `scripts/test-layout/layout.json` and `tests/fixtures/test-layout-expected.json`. - `bun run typecheck`, `bun run privacy:scan` — CI `gates` job. ## Enforcement bypass (PLAN-BYPASS-NAMED-01) -This unit adds guidance, not enforcement. Tier: none (prose the model may ignore). Executing -surface: request translation in the adapters. Known bypass: the model disregards the sentence; -the host still rejects the call exactly as today. Residual risk: none beyond status quo; the -post-hoc annotation cannot make a failed call succeed. Wording: this is an "early warning", not -enforcement. Final layer: Codex host validation (unchanged). +Guidance, not enforcement. Tier: none. Executing surface: adapter request translation. Known +bypass: the model ignores the sentence; the host rejects exactly as today. Residual risk: status +quo. Wording: "early warning". Final layer: Codex host validation (unchanged). ## SoT sync targets (SOT-SYNC-01) -- `structure/04_transports-and-sidecars.md` paragraph at ~line 325 ("Native routed Responses code-mode turns also receive…") — extend with the host contract. -- `docs-site/src/content/docs/guides/codex-integration.md` "Routed local tools" section (~line 315) — one paragraph; translated locales are not edited (they must not contradict, and adding text to English only is additive). +- `structure/04_transports-and-sidecars.md` paragraph at ~line 325 ("Native routed Responses code-mode turns also receive…") plus a Decision Log entry (full text in 030). +- `docs-site/src/content/docs/guides/codex-integration.md` "Routed local tools" (~line 331); translated locales untouched. + +## Audit round 1 — synthesis (REVIEW-SYNTHESIS-01) + +| # | Sev | Disposition | +|---|---|---| +| 1 Kiro grouping clobbers raw text | High | Folded: only the host annotation substitutes; grouped activation test added (020). | +| 2 Cursor false positives / case collisions | High | Folded: Cursor table untouched; exec-gated branch via shared helper; benign-content and case controls added (020). | +| 3 Cursor idempotence | Med | Folded: shared `[recovery: ` guard reached from Cursor; replay test with `isError:false` (020). | +| 4 Global whitelist false | Med | Folded: non-exhaustive list deferring to the exec description (010). | +| 5 No CI before wp3 | Med | Folded: push + draft PR at wp1, push at wp2, ready at wp3 (this file, 030). | +| 6 Elided strings | Med | Folded: full hunks and full Decision Log text (010/020/030). | +| 7 Anchor drift | Low | Folded: anchors refreshed against ec799db26; test import chain corrected. | +| 8 Docs overstate | Med | Folded: "this change" scope wording; three result paths named (030). | + +Root cause across 1-3: the roadmap treated "reuse the seam" as "spread into the seam" without +re-reading each seam's own policy. Round 2 re-audits with the same reviewer. diff --git a/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md b/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md index 9b41dd1653..e728a0aa1f 100644 --- a/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md +++ b/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md @@ -1,88 +1,90 @@ # 010 — wp1: pre-call host contract sentence and its three injection sites -Depends on 000_plan.md. Class C2 (conventional slice across an existing shared module and its -three known consumers; no new abstraction, no new seam). Loop archetype satisfy-spec. +Depends on 000_plan.md (rev 2). Class C2. Anchors verified against ec799db26. Ends with an +authorized push and a draft PR so exact-head CI exists for this and later heads. ## MODIFY `src/adapters/exec-tool-result-normalize.ts` -Append after `CODE_MODE_RESULT_ECHO_SENTENCE` (line ~117): +Insert after the `CODE_MODE_RESULT_ECHO_SENTENCE` declaration (its closing `;` is at line 117): ```ts + /** - * The host rules a routed model most often breaks on its first code-mode edit or wait, stated - * BEFORE the call. Wording tracks the Codex host (0.153.2): `apply_patch` rejects a non-string - * argument with "expects a string input" and a body whose first line is not the marker with - * "The first line of the patch must be '*** Begin Patch'"; the isolate rejects ES imports with - * "Unsupported import in exec"; a long command yields a session_id for write_stdin polling. - * Live 2026-09-07: xai/grok-4.6 hit the first two, abandoned apply_patch for heredoc writes, - * blocked a turn in a shell sleep loop, and died once on an import. None of that is a model - * defect the proxy can repair (see devlog/_plan/260905_apply_patch_envelope_gap/010 MODE B); - * it is a contract the proxy had not stated. + * Host rules a routed model most often breaks on its first code-mode edit or wait, stated BEFORE + * the call. Wording tracks the Codex host (0.153.2), probed live on 2026-09-07: a non-string + * argument to `apply_patch` throws "expects a string input"; a body whose first line is not the + * bare marker (decorated `*** Begin Patch ***`, a code fence, prose) throws "The first line of the + * patch must be '*** Begin Patch'" — surrounding newlines are tolerated; ES imports throw + * "Unsupported import in exec"; a command that outlives `yield_time_ms` returns `session_id` for + * `write_stdin` polling. xai/grok-4.6 hit the first two, abandoned apply_patch for heredoc writes, + * blocked a turn in a shell sleep loop, and died once on an import. None of that is repairable in + * the proxy (devlog/_plan/260905_apply_patch_envelope_gap/010 MODE B); it is a contract the proxy + * had not stated. */ export const CODE_MODE_HOST_CONTRACT_SENTENCE = - "Host contract for the nested helpers: `tools.apply_patch(patch)` takes exactly one string, never an object such as `{input: ...}`; the string's first line must be exactly `*** Begin Patch` and its last line `*** End Patch` with no leading newline, indentation, or extra asterisks, so start the literal at the marker. The isolate has no `import`, `require`, or module loader — use only the `tools`, `text`, `notify`, `store`/`load`, and `ALL_TOOLS` globals. For a command that may outlive `yield_time_ms`, let `tools.exec_command` return a `session_id` and poll it with `tools.write_stdin({session_id, chars: \"\"})` on later calls instead of blocking a shell in a sleep loop."; + "Host contract for the nested helpers: `tools.apply_patch(patch)` takes exactly one string, never an object such as `{input: ...}`; that string's first line must be the bare marker `*** Begin Patch` and its last line `*** End Patch`, with no code fence, prose, or extra asterisks around either marker. The isolate has no `import`, `require`, or module loader; use the globals the exec tool description lists (for example `tools`, `text`, `notify`, `store`/`load`, `ALL_TOOLS`). For a command that may outlive `yield_time_ms`, let `tools.exec_command` return a `session_id` and poll it on later calls with `tools.write_stdin({session_id, chars: \"\"})` instead of blocking a shell in a sleep loop."; ``` ## MODIFY `src/adapters/tool-catalog-nudge.ts` -Line 7 import: `import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE } from "./exec-tool-result-normalize";` - -Line 124 code-mode branch. BEFORE (tail of the string): - -``` -... + CODE_MODE_RESULT_ECHO_SENTENCE + " Nested `tools.apply_patch(input)` is host-executed: ... rejected by Codex before the file is touched." +Line 8 BEFORE: +```ts +import { CODE_MODE_RESULT_ECHO_SENTENCE } from "./exec-tool-result-normalize"; ``` - AFTER: +```ts +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE } from "./exec-tool-result-normalize"; +``` +Line 124 is one 1035-byte string ending in `rejected by Codex before the file is touched."`. +BEFORE (tail): +```ts +OpenCodex does not rewrite JavaScript inside exec, so extra asterisks on a marker line are rejected by Codex before the file is touched." ``` -... + CODE_MODE_RESULT_ECHO_SENTENCE + " Nested `tools.apply_patch(input)` is host-executed: ... rejected by Codex before the file is touched. " + CODE_MODE_HOST_CONTRACT_SENTENCE +AFTER (tail): +```ts +OpenCodex does not rewrite JavaScript inside exec, so extra asterisks on a marker line are rejected by Codex before the file is touched. " + CODE_MODE_HOST_CONTRACT_SENTENCE ``` - -The flat-catalog branch (`If a listed tool exposes nested helpers…`) is unchanged: a shell bridge -echoes stdout and has no isolate, so the sentence would be false there. +The flat-catalog branch (`"If a listed tool exposes nested helpers such as a tools.* API…"`) is unchanged. ## MODIFY `src/adapters/cursor/tool-guidance.ts` -Line 2 import: add `CODE_MODE_HOST_CONTRACT_SENTENCE`. - -Line 190 (`codeMode ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no \`require\`, …"`). BEFORE: - +Line 2 BEFORE: ```ts -codeMode - ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers." - : undefined, +import { CODE_MODE_RESULT_ECHO_SENTENCE } from "../exec-tool-result-normalize"; ``` - AFTER: +```ts +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE } from "../exec-tool-result-normalize"; +``` +Lines 189-191 BEFORE (4-space indent as in source): +```ts + codeMode + ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers." + : undefined, +``` +AFTER: ```ts -codeMode - ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers. " + CODE_MODE_HOST_CONTRACT_SENTENCE - : undefined, + codeMode + ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers. " + CODE_MODE_HOST_CONTRACT_SENTENCE + : undefined, ``` ## MODIFY `src/adapters/responses-code-mode.ts` -Line 3 import: add `CODE_MODE_HOST_CONTRACT_SENTENCE`. - -Instructions (line ~46). BEFORE: - +Line 3 BEFORE: ```ts -instructions: instructions.includes(CODE_MODE_RESULT_ECHO_SENTENCE) - ? instructions : [instructions, CODE_MODE_RESULT_ECHO_SENTENCE].filter(Boolean).join("\n\n"), +import { CODE_MODE_RESULT_ECHO_SENTENCE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; ``` - -AFTER (idempotent per sentence, so a replayed body that already carries the echo sentence but -not the contract gains only the missing one): - +AFTER: ```ts -instructions: appendMissing(instructions, [CODE_MODE_RESULT_ECHO_SENTENCE, CODE_MODE_HOST_CONTRACT_SENTENCE]), +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; ``` -with a module-local helper: - +Insert before `/** Native routed Responses needs the same first-call/output contract… */` (line 33): ```ts +/** Append each sentence a replayed instructions string does not already carry, in order. */ function appendMissing(instructions: string, sentences: readonly string[]): string { return sentences.reduce( (acc, sentence) => acc.includes(sentence) ? acc : [acc, sentence].filter(Boolean).join("\n\n"), @@ -91,49 +93,95 @@ function appendMissing(instructions: string, sentences: readonly string[]): stri } ``` -The exec `input` parameter description (line 27) keeps only the echo sentence: it is a schema -string, and Kiro-style description limiters bound injected instructions, not parameter text, but -the contract is long and belongs in `instructions` where the existing test already asserts. +Lines 46-47 BEFORE (4-space indent): +```ts + instructions: instructions.includes(CODE_MODE_RESULT_ECHO_SENTENCE) + ? instructions : [instructions, CODE_MODE_RESULT_ECHO_SENTENCE].filter(Boolean).join("\n\n"), +``` +AFTER: +```ts + instructions: appendMissing(instructions, [CODE_MODE_RESULT_ECHO_SENTENCE, CODE_MODE_HOST_CONTRACT_SENTENCE]), +``` + +The exec `input` parameter description (line 27) keeps only the echo sentence; the contract belongs in +`instructions`, which the existing test asserts byte-exactly. -Activation scenario: any routed native Responses request whose visible catalog has a bare freeform -`exec` and no bare shell bridge, to a non-OpenAI destination, not a compaction request — the -exact gate at `responses-code-mode.ts:35-37`. Observable effect: `wire.instructions` ends with the -contract sentence. +Activation: routed native Responses request whose visible catalog has a bare freeform `exec` and no +bare shell bridge, non-OpenAI destination, not a compaction request (gate at lines 35-37). +Observable: `wire.instructions` ends with the contract sentence. -## TESTS (updated in place; no new file in wp1) +## TESTS (in place; no new file in wp1) `tests/adapters/tool-catalog-nudge.test.ts` -- In `"defines nested helper names as non-callable unless separately listed"` add: - `expect(note).toContain(CODE_MODE_HOST_CONTRACT_SENTENCE);` and - `expect(note).toContain("write_stdin({session_id, chars: \"\"})");`. -- In `"keeps the generic nested-helper parent-tool rule when exec is not listed"` add - `expect(note).not.toContain("Host contract for the nested helpers");`. -- Import the new constant on line 7. +- Line 7 import becomes `import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, EMPTY_EXEC_OUTPUT_MESSAGE } from "../../src/adapters/exec-tool-result-normalize";` +- In `"defines nested helper names as non-callable unless separately listed"` append: +```ts + // The host contract rides the same code-mode branch as the echo rule (Grok 2026-09-07). + expect(note).toContain(CODE_MODE_HOST_CONTRACT_SENTENCE); + expect(note).toContain("takes exactly one string"); + expect(note).toContain("write_stdin({session_id, chars: \"\"})"); +``` +- In `"keeps the generic nested-helper parent-tool rule when exec is not listed"` append: +```ts + expect(note).not.toContain("Host contract for the nested helpers"); +``` `tests/providers/cursor/cursor-tool-definitions.test.ts` -- In `"teaches the nested-helper contract instead of a top-level shell bridge"` (line ~754) add - `expect(note).toContain("takes exactly one string");` and - `expect(note).toContain("write_stdin");`. -- In `"keeps flat-catalog shell-bridge guidance when a bare bridge is advertised"` add - `expect(note).not.toContain("Host contract for the nested helpers");`. +- In `"teaches the nested-helper contract instead of a top-level shell bridge"` (starts line 754) append + after the `"OpenCodex does not rewrite JavaScript inside exec"` assertion: +```ts + expect(note).toContain("Host contract for the nested helpers"); + expect(note).toContain("takes exactly one string"); + expect(note).toContain("write_stdin"); +``` +- In `"keeps flat-catalog shell-bridge guidance when a bare bridge is advertised"` append: +```ts + expect(note).not.toContain("Host contract for the nested helpers"); +``` `tests/responses/openai-responses-passthrough.test.ts` -- `"first native request carries the echo rule…"` line 54 BEFORE: - `expect(wire.instructions).toBe(\`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}\`);` +- Line 6 import adds `CODE_MODE_HOST_CONTRACT_SENTENCE`. +- Line 54 BEFORE: +```ts + expect(wire.instructions).toBe(`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}`); +``` AFTER: - `expect(wire.instructions).toBe(\`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}\n\n${CODE_MODE_HOST_CONTRACT_SENTENCE}\`);` -- `"does not duplicate instructions…"` already asserts idempotence; add a case where the body's - instructions already contain the echo sentence and assert exactly one contract sentence is appended. -- `"official OpenAI and non-code-mode catalogs remain untouched"`: add - `expect(JSON.stringify(wire)).not.toContain("Host contract for the nested helpers")` inside the native loop. +```ts + expect(wire.instructions).toBe(`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}\n\n${CODE_MODE_HOST_CONTRACT_SENTENCE}`); +``` +- New test after `"does not duplicate instructions or explain an unpaired or unrelated result"`: +```ts + test("a replayed body that already carries the echo rule gains only the missing contract sentence", () => { + const body = { ...raw(), instructions: `Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}` }; + const parsed = parseRequest(body); + const first = normalizeResponsesCodeMode(body, parsed, routed) as typeof body; + expect(first.instructions).toBe(`${body.instructions}\n\n${CODE_MODE_HOST_CONTRACT_SENTENCE}`); + expect(first.instructions.split(CODE_MODE_RESULT_ECHO_SENTENCE).length).toBe(2); + const second = normalizeResponsesCodeMode(first, parsed, routed) as typeof body; + expect(second.instructions).toBe(first.instructions); + }); +``` +- In `"official OpenAI and non-code-mode catalogs remain untouched"`, inside the `for (const native…)` loop + append `expect(JSON.stringify(wire)).not.toContain("Host contract for the nested helpers");`. `tests/providers/kiro/kiro-adapter.test.ts` -- In `"names ALL_TOOLS when a freeform exec is advertised…"` (line ~1817) add - `expect(content).toContain("Host contract for the nested helpers");` — proves the sentence - survives Kiro's `boundedInjectedInstruction` (16 384 chars) on the real wire prompt. +- In `"names ALL_TOOLS when a freeform exec is advertised without a bare shell bridge"` (line 1817) append: +```ts + // Survives Kiro's 16 384-char injected-instruction bound on the real wire prompt. + expect(content).toContain("Host contract for the nested helpers"); +``` + +## Delivery for this phase + +`git add` only the files above; `git diff --cached --stat` first; commit `--no-verify`; then +`git push --no-verify -u origin codex/code-mode-host-contract` and +`gh pr create --draft --base dev --title "fix(code-mode): state the host contract for nested helpers and annotate host failures" --body-file .tmp/pr-body.md` +(body per template; Verification section says local checks NOT RUN, hosted CI is the verifier; +wp2/wp3 will extend it). ## Verification (C, hosted only) -NOT RUN locally by instruction. Hosted CI shards run the four files above; `gates` runs typecheck -and privacy scan. Evidence: `gh run list --branch codex/code-mode-host-contract` + `gh run view --exit-status`. +NOT RUN locally by instruction. Poll `gh run list --branch codex/code-mode-host-contract --json databaseId,headSha,status,conclusion,name` +in short `exec_command` calls; when the Cross-platform CI run for `git rev-parse HEAD` completes, +`cxc receipt test --session --cwd -- gh run view --exit-status`. diff --git a/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md index 105a592c2d..b428121f5d 100644 --- a/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md +++ b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md @@ -1,19 +1,19 @@ # 020 — wp2: post-hoc annotation of host failures on exec results -Depends on 010 (the pre-call sentence names the same rules this half explains after the fact; the -two must share wording, which is why both live in one module). Class C2. +Depends on 010 (same module, same wording). Class C2. Anchors verified against ec799db26 plus +the wp1 delta. Ends with an authorized push; the draft PR from wp1 picks up the new head. ## MODIFY `src/adapters/exec-tool-result-normalize.ts` -Append after `CODE_MODE_HOST_CONTRACT_SENTENCE`: +Insert after `CODE_MODE_HOST_CONTRACT_SENTENCE` (added in wp1): ```ts + /** * Post-hoc half of the host contract: the four host strings a routed model reads inside a - * non-error exec result, each paired with the rule it broke. Markers are compared - * case-insensitively because the host writes "Unsupported import in exec: " while - * earlier Cursor guidance matched the lowercase form; one table, one owner, so the - * recovery text can never drift from the pre-call sentence above. + * non-error exec result, each paired with the rule it broke. Matched case-insensitively because + * the host writes "Unsupported import in exec: " while Cursor's earlier marker was + * lowercase; one table, one owner, so this text and the pre-call sentence cannot drift. */ export const CODE_MODE_HOST_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; guidance: string }> = [ { @@ -22,11 +22,11 @@ export const CODE_MODE_HOST_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; gu }, { marker: "the first line of the patch must be", - guidance: "The patch string must begin at `*** Begin Patch` with no leading newline, indentation, or extra asterisks; start the literal on the marker line.", + guidance: "The patch string's first line must be the bare marker `*** Begin Patch` with no code fence, prose, or extra asterisks around it.", }, { marker: "the last line of the patch must be", - guidance: "The patch string must end with `*** End Patch` as its final line, with no trailing text or extra asterisks.", + guidance: "The patch string's last line must be the bare marker `*** End Patch` with no trailing text or extra asterisks.", }, { marker: "unsupported import in exec", @@ -38,8 +38,9 @@ const HOST_FAILURE_RECOVERY_PREFIX = "[recovery: "; /** * Append a one-line recovery hint when an exec-bridge result carries a known host failure string. - * Returns undefined when the result is not an exec-bridge tool, no marker matches, or a recovery - * line is already present, so callers keep their own fallback and never double-annotate. + * Returns undefined when the tool is not an exec bridge, no marker matches, or a recovery line is + * already present (a replayed annotated result must not grow a second one). Never touches error + * status: the host already decided whether the call failed. */ export function annotateCodeModeHostFailure( text: string, @@ -53,86 +54,114 @@ export function annotateCodeModeHostFailure( } ``` -The Cursor guidance string for the import row is kept byte-identical to today's -(`"Imports are not available in this exec context; use the injected globals instead."` extended with -the global list) so `cursor-toolresult-normalize.test.ts:101` (`"injected globals"`) still matches. - ## MODIFY `src/adapters/responses-code-mode.ts` -Line 55 BEFORE: +Line 3 import gains `annotateCodeModeHostFailure`. +Line 55 BEFORE (6-space indent): ```ts -const normalized = text === undefined ? undefined : normalizeEmptyExecToolResultText(text, { toolName: "exec" }); + const normalized = text === undefined ? undefined : normalizeEmptyExecToolResultText(text, { toolName: "exec" }); ``` - AFTER: - ```ts -const normalized = text === undefined - ? undefined - : normalizeEmptyExecToolResultText(text, { toolName: "exec" }) - ?? annotateCodeModeHostFailure(text, { toolName: "exec" }); + const normalized = text === undefined + ? undefined + : normalizeEmptyExecToolResultText(text, { toolName: "exec" }) + ?? annotateCodeModeHostFailure(text, { toolName: "exec" }); ``` - -Import `annotateCodeModeHostFailure` on line 3. Empty-wrapper first: an empty result can never -carry a marker, so the order is only for clarity. Activation: paired `custom_tool_call_output` -whose text contains e.g. `\`apply_patch\` expects a string input`; observable effect: output ends -with `[recovery: tools.apply_patch takes exactly one string argument…]`, and `input[0]` (the -program) is the same object reference as before. +Activation: paired `custom_tool_call_output` whose text contains `\`apply_patch\` expects a string input`; +observable: output ends with the recovery line, `input[0]` is the same object reference. ## MODIFY `src/adapters/kiro.ts` -Line 47 import: add `annotateCodeModeHostFailure`. - -Lines 758-762 BEFORE: - +Line 47 BEFORE: ```ts -const normalizedExecText = normalizeEmptyExecToolResultText(text, { - toolName: tr.toolName, - toolNamespace: tr.toolNamespace, -}); -const resultText = normalizedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); +import { EMPTY_EXEC_OUTPUT_MESSAGE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; ``` - AFTER: - ```ts -const execOptions = { toolName: tr.toolName, toolNamespace: tr.toolNamespace }; -const normalizedExecText = normalizeEmptyExecToolResultText(text, execOptions) - ?? annotateCodeModeHostFailure(text, execOptions); -const resultText = normalizedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); +import { EMPTY_EXEC_OUTPUT_MESSAGE, annotateCodeModeHostFailure, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; ``` -`rawGroupText` (line 774) already keeps `text` whenever `normalizedExecText !== EMPTY_EXEC_OUTPUT_MESSAGE`, -so the adjacent-result grouping path carries the RAW failure text; the annotated text is what the -single-result path emits. Line 774 is changed so a grouped result carries the annotated text too: - -BEFORE: `? text : undefined;` AFTER: `? (normalizedExecText ?? text) : undefined;` - -(For the empty-wrapper case `normalizedExecText === EMPTY_EXEC_OUTPUT_MESSAGE` short-circuits the -outer condition first, so that branch is unchanged.) +Lines 758-771 BEFORE (6-space indent): +```ts + const normalizedExecText = normalizeEmptyExecToolResultText(text, { + toolName: tr.toolName, + toolNamespace: tr.toolNamespace, + }); + const resultText = normalizedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); + const images = extractKiroImages(tr.content); + const toolUseId = normalizeToolId(tr.toolCallId); + const call = priorCalls.get(toolUseId); + if (!call || call.rawId !== tr.toolCallId) { + throw new Error(`Kiro history contains an orphaned tool result for call ${JSON.stringify(tr.toolCallId)}`); + } + // Keep real whitespace and failed wrappers, but no empty-success wrapper boilerplate. + const rawGroupText = text.length > 0 && (!text.trim() || normalizedExecText !== EMPTY_EXEC_OUTPUT_MESSAGE) + ? text : undefined; +``` +AFTER: +```ts + const execOptions = { toolName: tr.toolName, toolNamespace: tr.toolNamespace }; + const normalizedExecText = normalizeEmptyExecToolResultText(text, execOptions); + // A host failure string inside a non-empty exec result gets the rule it broke appended. This + // is the only substitution the grouping path below also carries: whitespace and empty/failed + // wrappers keep their existing raw policy. + const annotatedExecText = normalizedExecText === undefined ? annotateCodeModeHostFailure(text, execOptions) : undefined; + const resultText = normalizedExecText ?? annotatedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); + const images = extractKiroImages(tr.content); + const toolUseId = normalizeToolId(tr.toolCallId); + const call = priorCalls.get(toolUseId); + if (!call || call.rawId !== tr.toolCallId) { + throw new Error(`Kiro history contains an orphaned tool result for call ${JSON.stringify(tr.toolCallId)}`); + } + // Keep real whitespace and failed wrappers, but no empty-success wrapper boilerplate. + const rawGroupText = text.length > 0 && (!text.trim() || normalizedExecText !== EMPTY_EXEC_OUTPUT_MESSAGE) + ? (annotatedExecText ?? text) : undefined; +``` +`annotatedExecText` is defined only when `normalizedExecText` is undefined, i.e. the text is neither an +empty-success nor a failed-empty wrapper, so every existing grouping expectation +(`kiro-adapter.test.ts:1209` whitespace, `1252` raw failed wrapper) is unchanged by construction. ## MODIFY `src/adapters/cursor/tool-result-normalize.ts` -Import `CODE_MODE_HOST_FAILURE_GUIDANCE` from `../exec-tool-result-normalize`. - -`RUNTIME_FAILURE_GUIDANCE` (lines 50-67): DELETE the `unsupported import in exec` entry and spread -the shared table instead: +Imports (lines 12-18) gain `annotateCodeModeHostFailure`. `RUNTIME_FAILURE_GUIDANCE` (lines 50-67) and its +loop (lines 107-113) stay byte-identical: Cursor's marker semantics, case sensitivity and +`isError:true` policy are its own. +Lines 96-105 BEFORE (2-space indent): ```ts -const RUNTIME_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; guidance: string }> = [ - { marker: "SkyComputerUseError", guidance: "…" }, - { marker: "sky is not defined", guidance: "…" }, - { marker: "has already been declared", guidance: "…" }, - ...CODE_MODE_HOST_FAILURE_GUIDANCE, -]; + if (isCodexExecBridgeTool(options.toolName, options.toolNamespace) && isEmptyOrFailedExecWrapper(text.trim())) { + return { + // A `Script failed` wrapper is empty but NOT a success: reporting it as an empty success + // would erase the only failure signal. Text classification stays separate from Cursor's + // isError policy, which the Computer Use branch above owns. + text: isFailedEmptyExecWrapper(text.trim()) ? FAILED_EXEC_OUTPUT_MESSAGE : EMPTY_EXEC_OUTPUT_MESSAGE, + isError: false, + changed: true, + }; + } ``` - -Loop at line 109 BEFORE: `if (text.includes(marker))` AFTER: compare against `text.toLowerCase()` -for the shared rows only — simplest correct form is to lowercase both sides for every row, since the -three Cursor markers contain no case-sensitive collisions (`SkyComputerUseError` lowercased still -matches only itself). Cursor policy (`isError: true` on a match) is unchanged; the shared helper is -not used here because Cursor owns its `isError` decision. +AFTER (append one branch directly after that block): +```ts + if (isCodexExecBridgeTool(options.toolName, options.toolNamespace) && isEmptyOrFailedExecWrapper(text.trim())) { + return { + // A `Script failed` wrapper is empty but NOT a success: reporting it as an empty success + // would erase the only failure signal. Text classification stays separate from Cursor's + // isError policy, which the Computer Use branch above owns. + text: isFailedEmptyExecWrapper(text.trim()) ? FAILED_EXEC_OUTPUT_MESSAGE : EMPTY_EXEC_OUTPUT_MESSAGE, + isError: false, + changed: true, + }; + } + // A host failure string inside an exec-bridge result gets the rule it broke appended. The + // helper is exec-gated and refuses already-annotated text, so a replayed result does not grow + // a second line; Cursor's isError decision is left exactly as the caller passed it. + const hostFailure = annotateCodeModeHostFailure(text, options); + if (hostFailure !== undefined) return { text: hostFailure, isError, changed: true }; +``` +The existing `unsupported import in exec` row in `RUNTIME_FAILURE_GUIDANCE` still serves node_repl / +Computer Use tools; for exec-bridge tools the new branch runs first and carries the shared hint. ## NEW `tests/adapters/exec-tool-result-normalize.test.ts` @@ -144,65 +173,128 @@ import { annotateCodeModeHostFailure, } from "../../src/adapters/exec-tool-result-normalize"; +// Live host strings (Codex 0.153.2, probed 2026-09-07) and the rule each one names. The pre-call +// sentence and these rows are one contract in one module; a model must never be told one thing +// before the call and another after. describe("code-mode host failure annotation", () => { - test.each(CODE_MODE_HOST_FAILURE_GUIDANCE.map(row => [row.marker, row.guidance]))( - "annotates an exec result carrying %p", (marker, guidance) => { - const text = `Script failed\nOutput:\nError: ${marker.toUpperCase()}`; - const out = annotateCodeModeHostFailure(text, { toolName: "exec" }); - expect(out).toBe(`${text}\n[recovery: ${guidance}]`); - }); - - test("matches the host's real capitalisation for imports", () => { - const out = annotateCodeModeHostFailure("Unsupported import in exec: node:fs", { toolName: "exec" }); - expect(out).toContain("injected globals"); + test.each(CODE_MODE_HOST_FAILURE_GUIDANCE.map(row => [row.marker, row.guidance] as const))( + "annotates an exec result carrying %p regardless of case", + (marker, guidance) => { + const text = `Script failed\nWall time 0.1 seconds\nOutput:\nError: ${marker.toUpperCase()}`; + expect(annotateCodeModeHostFailure(text, { toolName: "exec" })).toBe(`${text}\n[recovery: ${guidance}]`); + }, + ); + + test("matches the host's real capitalisation and argument text", () => { + expect(annotateCodeModeHostFailure("Unsupported import in exec: node:fs", { toolName: "exec" })).toContain("injected globals"); + expect(annotateCodeModeHostFailure("Script error:\ntool `apply_patch` expects a string input", { toolName: "exec" })).toContain("exactly one string"); + expect(annotateCodeModeHostFailure( + "apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'", + { toolName: "exec_command" }, + )).toContain("bare marker `*** Begin Patch`"); }); - test("leaves non-exec tools, non-matching text and already-annotated text alone", () => { + test("leaves non-exec tools, non-matching text and already-annotated text byte-identical", () => { expect(annotateCodeModeHostFailure("expects a string input", { toolName: "read_file" })).toBeUndefined(); + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec_command", toolNamespace: "mcp__docker" })).toBeUndefined(); expect(annotateCodeModeHostFailure("all good", { toolName: "exec" })).toBeUndefined(); - const once = annotateCodeModeHostFailure("expects a string input", { toolName: "exec" })!; + const once = annotateCodeModeHostFailure("expects a string input", { toolName: "exec" }); + if (!once) throw new Error("expected one annotation"); expect(annotateCodeModeHostFailure(once, { toolName: "exec" })).toBeUndefined(); }); test("every failure row is a rule the pre-call sentence already states", () => { - // One owner, two halves: a model must never be told one thing before the call and another after. - expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("exactly one string"); - expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("*** Begin Patch"); - expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("*** End Patch"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("takes exactly one string"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("`*** Begin Patch`"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("`*** End Patch`"); expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("no `import`"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("write_stdin"); + // Never shows the decorated marker as a copyable literal (same rule as the nudge tests). + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).not.toContain("*** Begin Patch ***"); }); }); ``` -Register: `scripts/test-layout/layout.json` → `explicit`: `"exec-tool-result-normalize.test.ts": "adapters"` -(alphabetical, after `"exec-…"` neighbours or before `"identity-…"`); same key in -`tests/fixtures/test-layout-expected.json`. `tests/test-layout-tooling.test.ts` names a missing one. +Register in `scripts/test-layout/layout.json` `explicit` between +`"empty-tool-output-annotation.test.ts": "adapters",` (line 620) and its successor: +`"exec-tool-result-normalize.test.ts": "adapters",`; same key/value in +`tests/fixtures/test-layout-expected.json` in alphabetical position. The name matches no regex seed +(`"adapters"` seed is `^(?:bridge\.test\.ts|buffered|identity|run|tool|translator)-`), so the explicit +entry is required and `tests/test-layout-tooling.test.ts` names it if missing. ## Updated tests -`tests/responses/openai-responses-passthrough.test.ts` — add to the code-mode describe: +`tests/responses/openai-responses-passthrough.test.ts` — add inside the code-mode describe: +```ts + test("annotates a paired exec result that carries a host failure string without touching the program", () => { + const failure = "Script failed\nWall time 0.1 seconds\nOutput:\nScript error:\ntool `apply_patch` expects a string input"; + const body = raw(failure); + const wire = JSON.parse(createResponsesPassthroughAdapter(routed).buildRequest(parseRequest(body)).body); + expect(wire.input[1].output).toBe(`${failure}\n[recovery: tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.]`); + expect(JSON.parse(wire.input[0].arguments).input).toBe(body.input[0].input); + // Replayed history already carrying the hint is not annotated twice. + const replayed = raw(wire.input[1].output); + expect(normalizeResponsesCodeMode(replayed, parseRequest(replayed), routed)).toBe(replayed); + }); +``` +`tests/providers/kiro/kiro-adapter.test.ts` +- After `"an empty code-mode exec result carries the actionable reason…"` (line 323) add: ```ts -test("annotates a paired exec result that carries a host failure string", () => { - const failure = "Script failed\nWall time 0.1 seconds\nOutput:\nError: `apply_patch` expects a string input"; - const body = raw(failure); - const wire = JSON.parse(createResponsesPassthroughAdapter(routed).buildRequest(parseRequest(body)).body); - expect(wire.input[1].output).toBe(`${failure}\n[recovery: tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.]`); - expect(JSON.parse(wire.input[0].arguments).input).toBe(body.input[0].input); -}); + test("a code-mode exec result carrying a host failure string names the broken rule", async () => { + const execTool = { name: "exec", description: "Run JavaScript", parameters: { type: "object" } }; + const failure = "apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'"; + const messages = [ + { role: "user", content: "run it" }, + { role: "assistant", content: [{ type: "toolCall", id: "call-x", name: "exec", arguments: {} }] }, + { role: "toolResult", toolCallId: "call-x", toolName: "exec", content: failure, isError: false }, + ]; + const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages, [execTool])); + const resultText = JSON.parse(body).conversationState.currentMessage.userInputMessage + .userInputMessageContext.toolResults[0].content[0].text; + expect(resultText).toBe(`${failure}\n[recovery: The patch string's first line must be the bare marker \`*** Begin Patch\` with no code fence, prose, or extra asterisks around it.]`); + }); +``` +- In the grouped-result table (the `execResult` cases around lines 1195-1262) add one case: +```ts + { + name: "host failure chunk in a multi group carries its recovery line beside raw siblings", + id: "call-host-failure-multi", + results: [execResult("call-host-failure-multi", " "), execResult("call-host-failure-multi", "tool `apply_patch` expects a string input"), execResult("call-host-failure-multi", failedExecWrapper)], + content: [{ text: " " }, { text: "tool `apply_patch` expects a string input\n[recovery: tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.]" }, { text: failedExecWrapper }], + status: "success", + forbidden: [EMPTY_EXEC_OUTPUT_MESSAGE, FAILED_EXEC_OUTPUT_MESSAGE, KIRO_EMPTY_TOOL_RESULT_MESSAGE], + }, +``` + This drives the grouping path with whitespace, an annotated chunk and a raw failed wrapper in one + group — the exact combination blocker 1 said the single-result test could not exercise. + +`tests/providers/cursor/cursor-toolresult-normalize.test.ts` — add after the `test.each` runtime-failure table: +```ts + test("an exec-bridge result carrying a host failure string gains the shared hint and keeps its isError", () => { + const out = normalizeCursorToolResultText("Unsupported import in exec: node:fs", { toolName: "exec" }); + expect(out.changed).toBe(true); + expect(out.isError).toBe(false); + expect(out.text).toContain("[recovery: Imports are not available in this exec context"); + // Replay of the annotated text with isError=false must not grow a second line. + expect(normalizeCursorToolResultText(out.text, { toolName: "exec" }).changed).toBe(false); + }); + + test("a non-exec tool whose successful output merely mentions a host phrase stays byte-identical", () => { + const doc = "The docs say apply_patch expects a string input."; + const out = normalizeCursorToolResultText(doc, { toolName: "read_file" }); + expect(out.changed).toBe(false); + expect(out.isError).toBe(false); + expect(out.text).toBe(doc); + }); ``` -`tests/providers/kiro/kiro-adapter.test.ts` — beside the `EMPTY_EXEC_OUTPUT_MESSAGE` case at -line ~336, add one toolResult with `toolName: "exec"` and content -`"The first line of the patch must be '*** Begin Patch'"`; assert the emitted Kiro tool-result -text ends with `[recovery: The patch string must begin at …]`. +## Delivery for this phase -`tests/providers/cursor/cursor-toolresult-normalize.test.ts` — line 101 row stays; add -`["Unsupported import in exec: node:fs", "injected globals"]` and -`["\`apply_patch\` expects a string input", "exactly one string"]` to the `test.each` table. +Stage only the files above (`git diff --cached --stat` first); commit `--no-verify`; push `--no-verify`. ## Verification (C, hosted only) -NOT RUN locally. Hosted shards run the new and updated files; `tests/test-layout-tooling.test.ts` -proves registration. Activation for each conditional row is the marker-specific test above. +NOT RUN locally. Exact-head Cross-platform CI on the wp2 head; receipt via +`cxc receipt test --session --cwd -- gh run view --exit-status`. diff --git a/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md index 8b7a848c69..e0c0df7990 100644 --- a/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md +++ b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md @@ -1,12 +1,13 @@ -# 030 — wp3: SoT sync, push, PR, exact-head CI receipt +# 030 — wp3: SoT sync, ready-for-review, exact-head CI receipt -Depends on 020. Class C2 for the docs; the push/PR step is external state and is authorized by -the user for this branch only ("no verify로 푸시", "pr올려봐"). Merge is not authorized. +Depends on 020. Class C2 for the docs. Push and PR creation are authorized by the user for this +branch ("no verify로 푸시", "pr올려봐"); the draft PR already exists from wp1. Merge is not authorized. ## MODIFY `structure/04_transports-and-sidecars.md` -After the paragraph ending "…or reconstruct output that the code-mode host never emitted." (~line 331) -add one paragraph: +Insert after the paragraph that ends "…or reconstruct output that the code-mode host never +emitted." (line 331), before the `[Decision Log]` that begins "목적과 의도: Keep Codex hosted web +search usable on xAI's public Responses endpoint…": ``` Routed code-mode turns also carry the host contract for the nested helpers, stated in the same three @@ -14,31 +15,37 @@ injection sites as the result-emission rule (shared catalog nudge, Cursor code-m routed Responses instructions): `tools.apply_patch` takes one string whose first and last lines are the bare patch markers, the isolate has no `import`/`require`, and a command that outlives `yield_time_ms` is polled through `write_stdin` with empty `chars` rather than a shell sleep loop. -When a paired exec result still carries one of the host's failure strings ("expects a string +When an exec-bridge result still carries one of the host's failure strings ("expects a string input", "The first line of the patch must be", "The last line of the patch must be", "Unsupported -import in exec"), the routed Responses, Kiro, and Cursor result paths append a one-line recovery -hint naming the broken rule. Both halves live in `src/adapters/exec-tool-result-normalize.ts` so -the pre-call and post-hoc wording cannot drift. Nothing rewrites the model's JavaScript or its -patch payload; the host still rejects the call exactly as before. +import in exec"), the native routed Responses, Kiro, and Cursor result paths append a one-line +recovery hint naming the broken rule; Cursor's error classification and Kiro's whitespace and +failed-wrapper grouping are unchanged. Both halves live in `src/adapters/exec-tool-result-normalize.ts` +so the pre-call and post-hoc wording cannot drift. This guidance and annotation change rewrites +neither the model's JavaScript nor its patch payload; the existing name-alias delimiter +normalization in `src/responses/code-mode-helper-compat.ts` is unchanged, and the host still rejects a +malformed call exactly as before. Anthropic, Google, OpenAI-chat and command-code result paths +have no exec-result seam today and are not annotated. + +[Decision Log] +- 목적과 의도: Stop routed models from abandoning `apply_patch` after the Codex host rejects an object argument or a decorated marker, and from blocking a turn in a shell sleep loop when the host offers `session_id` polling. +- 기존 구현 및 제약 조건: The shared nudge, Cursor guidance and native Responses instructions already carry the result-emission rule from `exec-tool-result-normalize.ts`, but none stated the helper's argument type, the marker rule, the import ban, or the polling protocol; `260905_apply_patch_envelope_gap` refused to rewrite JavaScript bodies (MODE B), so payload repair is off the table. +- 검토한 주요 대안: Repair the argument shape inside the proxy (rejected: same body ambiguity as MODE B and it turns a rejected write into a performed one); Cursor-only guidance (rejected: the incident was native routed Responses on xAI); annotate every adapter's tool results (rejected: Anthropic/Google/OpenAI-chat/command-code have no exec-result seam and would need a new one). +- 선택한 방식: One pre-call sentence and one marker→recovery table in the module that already owns the echo pair; inject the sentence at the three existing code-mode sites; annotate at the three existing exec-result seams with an exec-gated, idempotent helper that never changes error status. +- 다른 대안 대신 이 방식을 선택한 이유: The safe repair for a host contract the model broke is to state it before the call and name it after the failure; keeping both halves in one file is what keeps them consistent. +- 장점, 단점 및 영향: Code-mode system prompts grow by roughly 600 characters on routed turns; OpenAI destinations, flat catalogs and compaction requests are untouched. An exec result that legitimately prints one of the four phrases gains a recovery line, which is additive text and never an error flip. The effect on the live Grok defect rate is unmeasured until a re-probe. ``` -Add a Decision Log entry in the file's existing format (목적과 의도 / 기존 구현 및 제약 조건 / -검토한 주요 대안 / 선택한 방식 / 장점, 단점 및 영향) recording: purpose = stop routed models -abandoning apply_patch after two host rejections; alternatives = repair the argument shape in the -proxy (rejected: MODE B ambiguity, fail-open write), Cursor-only fix (rejected: incident was native -Responses); chosen = shared pair in one module; impact = longer system prompt on code-mode turns -(~600 chars), no behaviour change for OpenAI destinations or flat catalogs. - ## MODIFY `docs-site/src/content/docs/guides/codex-integration.md` -In "Routed local tools" after the apply_patch conversion paragraph (~line 331) add: +Insert after the paragraph ending "…and unrelated native custom payloads stay unchanged." (line 331): ``` Routed code-mode turns are also told the host's rules for the nested helpers before the first -call — `tools.apply_patch` takes one string starting at `*** Begin Patch`, the isolate has no -`import`, and long-running commands are polled with `write_stdin` — and when a result still -carries one of the host's failure messages, opencodex appends a one-line hint naming the rule. -The model's code and patch text are never rewritten. +call: `tools.apply_patch` takes one string whose first and last lines are the bare patch markers, +the isolate has no `import`, and long-running commands are polled through `write_stdin`. When an +exec result on the native routed Responses, Kiro, or Cursor path still carries one of the host's +failure messages, opencodex appends a one-line hint naming the rule. This change does not rewrite +the model's code or its patch text. ``` Translated locales (7 files) are not edited; the English source gains a paragraph they do not @@ -46,18 +53,17 @@ contradict. ## Delivery steps (t3b) -1. `git add -A devlog/_plan/260907_code_mode_host_contract src tests scripts structure docs-site` - — inspect `git diff --cached --stat` before every commit; only this unit's paths. -2. Commits already made per work-phase with `--no-verify` (wp0 docs, wp1, wp2, wp3 docs). -3. `git push --no-verify -u origin codex/code-mode-host-contract`. -4. `gh pr create --base dev --title "fix(code-mode): state the host contract for nested helpers and annotate host failures" --body-file .tmp/pr-body.md` - — body follows `.github/PULL_REQUEST_TEMPLATE.md` (Summary / Verification / Checklist), lists - local checks as NOT RUN, names hosted CI as the verifier. No `gui` mention (no screenshot rule). -5. Poll: `gh run list --branch codex/code-mode-host-contract --json databaseId,headSha,status,conclusion` - via `exec_command` short calls (each < 30 s); `gh run watch` is NOT used inside one call. -6. Receipt: at phase C, `cxc receipt test --session --cwd -- gh run view --exit-status` - where `` is the Cross-platform CI run whose `headSha` equals `git rev-parse HEAD`. - If the head moves (review fix), a fresh run and fresh receipt are required. +1. Stage only `structure/04_transports-and-sidecars.md`, `docs-site/.../codex-integration.md` and this unit's + devlog; inspect `git diff --cached --stat`; commit `--no-verify`; `git push --no-verify`. +2. Rewrite the PR body (`gh pr edit --body-file .tmp/pr-body.md`) to the final template: Summary + (problem, before/after, the four host strings), Verification (hosted CI run ids per head; local + suite/typecheck/build NOT RUN by instruction), Checklist ticked truthfully. No `gui` mention. +3. Poll `gh run list --branch codex/code-mode-host-contract --json databaseId,headSha,status,conclusion,name` + in short `exec_command` calls (each < 30 s) until the Cross-platform CI run whose `headSha` equals + `git rev-parse HEAD` completes; `gh run watch` is not used inside one call. +4. Receipt at phase C: `cxc receipt test --session --cwd -- gh run view --exit-status`. +5. `gh pr ready ` only after that receipt exists. If the head moves later, a fresh run and fresh + receipt are required before any further ready claim. ## Verification (C) From d375916ee2508cbd390c4edb556aeab65ed6ec42 Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 14:42:10 +0900 Subject: [PATCH 004/116] docs(devlog): fold audit round 2 into the code-mode host contract roadmap --- .../000_plan.md | 29 ++++- .../010_pre_call_contract.md | 9 +- .../020_post_hoc_annotation.md | 105 ++++++++++++------ .../030_docs_and_delivery.md | 19 ++-- 4 files changed, 111 insertions(+), 51 deletions(-) diff --git a/devlog/_plan/260907_code_mode_host_contract/000_plan.md b/devlog/_plan/260907_code_mode_host_contract/000_plan.md index 406c2c186d..91c130df0a 100644 --- a/devlog/_plan/260907_code_mode_host_contract/000_plan.md +++ b/devlog/_plan/260907_code_mode_host_contract/000_plan.md @@ -77,18 +77,26 @@ New exports in `exec-tool-result-normalize.ts` (full text in 010/020): non-exhaustive), `session_id` + `write_stdin` polling. 2. `CODE_MODE_HOST_FAILURE_GUIDANCE` — marker → recovery rows for the four host strings, matched case-insensitively. -3. `annotateCodeModeHostFailure(text, {toolName, toolNamespace})` — gated by - `isCodexExecBridgeTool`, refuses text already carrying `[recovery: `, appends one recovery - line; else `undefined`. Pure, idempotent, byte-identical on the negative path. +3. `annotateCodeModeHostFailure(text, {toolName, toolNamespace})` — gated by a new, narrower + `isCodexCodeModeExecResult` (bare `exec` or its `opencodex-responses` display alias; flat shell + bridges and foreign MCP namespaces excluded because the four strings originate only in the + isolate), refuses text already carrying the exported `CODE_MODE_HOST_RECOVERY_PREFIX`, appends + one recovery line; else `undefined`. Pure, idempotent, byte-identical on the negative path. + The empty-output repair keeps its wider `isCodexExecBridgeTool` gate. Cursor keeps its own `RUNTIME_FAILURE_GUIDANCE` table and its `isError` policy byte-identical; it gains one exec-gated branch that inserts the shared annotation WITHOUT changing `isError` (audit blockers 2 and 3). Kiro substitutes the annotation only where it would otherwise carry the raw text, leaving whitespace and failed-wrapper grouping untouched (blocker 1). -Accepted residual: an exec result that legitimately prints one of the four phrases (e.g. `cat` of -this devlog) gains a recovery line. The line is additive text on an exec result and never changes -error status, and the gate excludes every non-exec tool. +Accepted residual: a code-mode exec result that legitimately prints one of the four phrases (e.g. +`cat` of this devlog) gains a recovery line. The line is additive text and never changes error +status; the gate excludes every non-code-mode tool, shell bridge, and foreign namespace. + +Marker wording: the live probe shows the host tolerates blank lines and indentation around the +markers and rejects a decorated or missing marker. Every sentence, recovery hint and doc paragraph +says "opens/closes with the bare marker line … blank lines or indentation are tolerated" and never +"the first character must be". Why prose and not repair: `devlog/_plan/260905_apply_patch_envelope_gap/010_disposition.md` refused rewriting JavaScript bodies (MODE B). An object argument inside a program has the same @@ -157,3 +165,12 @@ quo. Wording: "early warning". Final layer: Codex host validation (unchanged). Root cause across 1-3: the roadmap treated "reuse the seam" as "spread into the seam" without re-reading each seam's own policy. Round 2 re-audits with the same reviewer. +## Audit round 2 — synthesis + +| # | Sev | Disposition | +|---|---|---| +| 1 Cursor lowercase replay falls through to legacy loop | High | Folded: the exec-gated branch returns early on an already-annotated result; lowercase and capitalised replay tests assert text/isError/changed (020). | +| 2 Namespace-negative test contradicts the predicate; flat shells annotated | Med | Folded: new `isCodexCodeModeExecResult` gate; shell-bridge, foreign-namespace and Cursor-alias tests; docs say flat catalogs untouched and mean it (020/030). | +| 3 Responses replay `toBe(replayed)` cannot hold | Med | Folded: assert output-item and program identity plus deep-equal idempotence of successive passes (020). | +| 4 Marker wording contradicts whitespace probe | Med | Folded: "bare marker line … blank lines or indentation tolerated" in sentence, hints, structure and docs-site text (010/020/030). | +| 5 Off-by-one anchors | Low | Folded: 116, 32, 45-46, 97-106 (010/020). | diff --git a/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md b/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md index e728a0aa1f..c6d7e6b9aa 100644 --- a/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md +++ b/devlog/_plan/260907_code_mode_host_contract/010_pre_call_contract.md @@ -5,7 +5,7 @@ authorized push and a draft PR so exact-head CI exists for this and later heads. ## MODIFY `src/adapters/exec-tool-result-normalize.ts` -Insert after the `CODE_MODE_RESULT_ECHO_SENTENCE` declaration (its closing `;` is at line 117): +Insert after the `CODE_MODE_RESULT_ECHO_SENTENCE` declaration (its closing `;` is at line 116): ```ts @@ -22,7 +22,7 @@ Insert after the `CODE_MODE_RESULT_ECHO_SENTENCE` declaration (its closing `;` i * had not stated. */ export const CODE_MODE_HOST_CONTRACT_SENTENCE = - "Host contract for the nested helpers: `tools.apply_patch(patch)` takes exactly one string, never an object such as `{input: ...}`; that string's first line must be the bare marker `*** Begin Patch` and its last line `*** End Patch`, with no code fence, prose, or extra asterisks around either marker. The isolate has no `import`, `require`, or module loader; use the globals the exec tool description lists (for example `tools`, `text`, `notify`, `store`/`load`, `ALL_TOOLS`). For a command that may outlive `yield_time_ms`, let `tools.exec_command` return a `session_id` and poll it on later calls with `tools.write_stdin({session_id, chars: \"\"})` instead of blocking a shell in a sleep loop."; + "Host contract for the nested helpers: `tools.apply_patch(patch)` takes exactly one string, never an object such as `{input: ...}`; the patch text opens with the bare marker line `*** Begin Patch` and closes with the bare marker line `*** End Patch`, written without a code fence, prose, or extra asterisks on those lines (blank lines or indentation around the markers are tolerated; a decorated or missing marker is rejected). The isolate has no `import`, `require`, or module loader; use the globals the exec tool description lists (for example `tools`, `text`, `notify`, `store`/`load`, `ALL_TOOLS`). For a command that may outlive `yield_time_ms`, let `tools.exec_command` return a `session_id` and poll it on later calls with `tools.write_stdin({session_id, chars: \"\"})` instead of blocking a shell in a sleep loop."; ``` ## MODIFY `src/adapters/tool-catalog-nudge.ts` @@ -82,7 +82,7 @@ AFTER: import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; ``` -Insert before `/** Native routed Responses needs the same first-call/output contract… */` (line 33): +Insert before `/** Native routed Responses needs the same first-call/output contract… */` (line 32): ```ts /** Append each sentence a replayed instructions string does not already carry, in order. */ function appendMissing(instructions: string, sentences: readonly string[]): string { @@ -93,7 +93,7 @@ function appendMissing(instructions: string, sentences: readonly string[]): stri } ``` -Lines 46-47 BEFORE (4-space indent): +Lines 45-46 BEFORE (4-space indent): ```ts instructions: instructions.includes(CODE_MODE_RESULT_ECHO_SENTENCE) ? instructions : [instructions, CODE_MODE_RESULT_ECHO_SENTENCE].filter(Boolean).join("\n\n"), @@ -184,4 +184,3 @@ wp2/wp3 will extend it). NOT RUN locally by instruction. Poll `gh run list --branch codex/code-mode-host-contract --json databaseId,headSha,status,conclusion,name` in short `exec_command` calls; when the Cross-platform CI run for `git rev-parse HEAD` completes, `cxc receipt test --session --cwd -- gh run view --exit-status`. - diff --git a/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md index b428121f5d..4bfa2df82d 100644 --- a/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md +++ b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md @@ -22,11 +22,11 @@ export const CODE_MODE_HOST_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; gu }, { marker: "the first line of the patch must be", - guidance: "The patch string's first line must be the bare marker `*** Begin Patch` with no code fence, prose, or extra asterisks around it.", + guidance: "The patch text must open with the bare marker line `*** Begin Patch`: no code fence, prose, or extra asterisks on that line (blank lines or indentation before it are tolerated).", }, { marker: "the last line of the patch must be", - guidance: "The patch string's last line must be the bare marker `*** End Patch` with no trailing text or extra asterisks.", + guidance: "The patch text must close with the bare marker line `*** End Patch`: no trailing text or extra asterisks on that line (blank lines after it are tolerated).", }, { marker: "unsupported import in exec", @@ -34,11 +34,26 @@ export const CODE_MODE_HOST_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; gu }, ]; -const HOST_FAILURE_RECOVERY_PREFIX = "[recovery: "; +/** Prefix of every recovery line this module appends; callers use it to recognise replayed annotations. */ +export const CODE_MODE_HOST_RECOVERY_PREFIX = "[recovery: "; /** - * Append a one-line recovery hint when an exec-bridge result carries a known host failure string. - * Returns undefined when the tool is not an exec bridge, no marker matches, or a recovery line is + * The code-mode `exec` tool itself — bare, or under Cursor's `opencodex-responses` display namespace. + * The four host strings above originate only in that isolate, so flat shell bridges + * (`exec_command`, `shell`, …) and every foreign MCP namespace (`mcp__docker__exec`) are excluded: an + * unrelated server's output that happens to contain the phrase must not receive Codex guidance. + * Narrower than `isCodexExecBridgeTool` on purpose; the empty-output repair keeps the wider gate. + */ +export function isCodexCodeModeExecResult(toolName?: string, toolNamespace?: string): boolean { + if (!toolName) return false; + const lower = toolName.toLowerCase(); + if (toolNamespace) return toolNamespace.includes("opencodex-responses") && lower === "exec"; + return lower === "exec" || lower === "mcp__opencodex-responses__exec" || lower === "mcp_opencodex-responses_exec"; +} + +/** + * Append a one-line recovery hint when a code-mode exec result carries a known host failure string. + * Returns undefined when the tool is not the code-mode exec, no marker matches, or a recovery line is * already present (a replayed annotated result must not grow a second one). Never touches error * status: the host already decided whether the call failed. */ @@ -46,14 +61,17 @@ export function annotateCodeModeHostFailure( text: string, options: { toolName?: string; toolNamespace?: string } = {}, ): string | undefined { - if (!isCodexExecBridgeTool(options.toolName, options.toolNamespace)) return undefined; - if (text.includes(HOST_FAILURE_RECOVERY_PREFIX)) return undefined; + if (!isCodexCodeModeExecResult(options.toolName, options.toolNamespace)) return undefined; + if (text.includes(CODE_MODE_HOST_RECOVERY_PREFIX)) return undefined; const lower = text.toLowerCase(); const hit = CODE_MODE_HOST_FAILURE_GUIDANCE.find(({ marker }) => lower.includes(marker)); - return hit ? `${text}\n${HOST_FAILURE_RECOVERY_PREFIX}${hit.guidance}]` : undefined; + return hit ? `${text}\n${CODE_MODE_HOST_RECOVERY_PREFIX}${hit.guidance}]` : undefined; } ``` +Flat shell tools are deliberately not annotated: the strings come from the code-mode host, and the +"flat catalogs untouched" statement in the docs is therefore literally true. + ## MODIFY `src/adapters/responses-code-mode.ts` Line 3 import gains `annotateCodeModeHostFailure`. @@ -125,11 +143,12 @@ empty-success nor a failed-empty wrapper, so every existing grouping expectation ## MODIFY `src/adapters/cursor/tool-result-normalize.ts` -Imports (lines 12-18) gain `annotateCodeModeHostFailure`. `RUNTIME_FAILURE_GUIDANCE` (lines 50-67) and its +Imports (lines 12-18) gain `CODE_MODE_HOST_RECOVERY_PREFIX`, `annotateCodeModeHostFailure` and +`isCodexCodeModeExecResult`. `RUNTIME_FAILURE_GUIDANCE` (lines 50-67) and its loop (lines 107-113) stay byte-identical: Cursor's marker semantics, case sensitivity and `isError:true` policy are its own. -Lines 96-105 BEFORE (2-space indent): +Lines 97-106 BEFORE (2-space indent): ```ts if (isCodexExecBridgeTool(options.toolName, options.toolNamespace) && isEmptyOrFailedExecWrapper(text.trim())) { return { @@ -154,14 +173,19 @@ AFTER (append one branch directly after that block): changed: true, }; } - // A host failure string inside an exec-bridge result gets the rule it broke appended. The - // helper is exec-gated and refuses already-annotated text, so a replayed result does not grow - // a second line; Cursor's isError decision is left exactly as the caller passed it. - const hostFailure = annotateCodeModeHostFailure(text, options); - if (hostFailure !== undefined) return { text: hostFailure, isError, changed: true }; + // A host failure string inside a code-mode exec result gets the rule it broke appended, with + // Cursor's isError decision left exactly as the caller passed it. A replayed result that already + // carries a recovery line returns here unchanged: falling through would let the legacy loop + // below match the lowercase import marker a second time and flip isError. + if (isCodexCodeModeExecResult(options.toolName, options.toolNamespace)) { + if (text.includes(CODE_MODE_HOST_RECOVERY_PREFIX)) return { text, isError, changed: false }; + const hostFailure = annotateCodeModeHostFailure(text, options); + if (hostFailure !== undefined) return { text: hostFailure, isError, changed: true }; + } ``` The existing `unsupported import in exec` row in `RUNTIME_FAILURE_GUIDANCE` still serves node_repl / -Computer Use tools; for exec-bridge tools the new branch runs first and carries the shared hint. +Computer Use tools; for the code-mode exec the new branch runs first, carries the shared hint, and +terminates replay before the legacy loop can see it. ## NEW `tests/adapters/exec-tool-result-normalize.test.ts` @@ -190,13 +214,18 @@ describe("code-mode host failure annotation", () => { expect(annotateCodeModeHostFailure("Script error:\ntool `apply_patch` expects a string input", { toolName: "exec" })).toContain("exactly one string"); expect(annotateCodeModeHostFailure( "apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'", - { toolName: "exec_command" }, - )).toContain("bare marker `*** Begin Patch`"); + { toolName: "exec" }, + )).toContain("bare marker line `*** Begin Patch`"); }); - test("leaves non-exec tools, non-matching text and already-annotated text byte-identical", () => { + test("leaves non-exec tools, shell bridges, foreign namespaces, non-matching text and already-annotated text alone", () => { expect(annotateCodeModeHostFailure("expects a string input", { toolName: "read_file" })).toBeUndefined(); - expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec_command", toolNamespace: "mcp__docker" })).toBeUndefined(); + // Flat shell bridges never run the isolate, so the four strings cannot be theirs. + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec_command" })).toBeUndefined(); + // A foreign MCP server's own exec is not Codex's, even when its output quotes the phrase. + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec", toolNamespace: "mcp__docker" })).toBeUndefined(); + // Cursor's display namespace for the same code-mode tool still counts. + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec", toolNamespace: "mcp__opencodex-responses" })).toContain("[recovery:"); expect(annotateCodeModeHostFailure("all good", { toolName: "exec" })).toBeUndefined(); const once = annotateCodeModeHostFailure("expects a string input", { toolName: "exec" }); if (!once) throw new Error("expected one annotation"); @@ -232,9 +261,13 @@ entry is required and `tests/test-layout-tooling.test.ts` names it if missing. const wire = JSON.parse(createResponsesPassthroughAdapter(routed).buildRequest(parseRequest(body)).body); expect(wire.input[1].output).toBe(`${failure}\n[recovery: tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.]`); expect(JSON.parse(wire.input[0].arguments).input).toBe(body.input[0].input); - // Replayed history already carrying the hint is not annotated twice. + // Replayed history already carrying the hint is not annotated twice: the output item and the + // program keep their identity, and a second pass over the normalized body is a deep no-op. const replayed = raw(wire.input[1].output); - expect(normalizeResponsesCodeMode(replayed, parseRequest(replayed), routed)).toBe(replayed); + const once = normalizeResponsesCodeMode(replayed, parseRequest(replayed), routed) as typeof replayed; + expect(once.input[1]).toBe(replayed.input[1]); + expect(once.input[0]).toBe(replayed.input[0]); + expect(normalizeResponsesCodeMode(once, parseRequest(once), routed)).toEqual(once); }); ``` @@ -252,7 +285,7 @@ entry is required and `tests/test-layout-tooling.test.ts` names it if missing. const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages, [execTool])); const resultText = JSON.parse(body).conversationState.currentMessage.userInputMessage .userInputMessageContext.toolResults[0].content[0].text; - expect(resultText).toBe(`${failure}\n[recovery: The patch string's first line must be the bare marker \`*** Begin Patch\` with no code fence, prose, or extra asterisks around it.]`); + expect(resultText).toBe(`${failure}\n[recovery: The patch text must open with the bare marker line \`*** Begin Patch\`: no code fence, prose, or extra asterisks on that line (blank lines or indentation before it are tolerated).]`); }); ``` - In the grouped-result table (the `execResult` cases around lines 1195-1262) add one case: @@ -271,13 +304,24 @@ entry is required and `tests/test-layout-tooling.test.ts` names it if missing. `tests/providers/cursor/cursor-toolresult-normalize.test.ts` — add after the `test.each` runtime-failure table: ```ts - test("an exec-bridge result carrying a host failure string gains the shared hint and keeps its isError", () => { - const out = normalizeCursorToolResultText("Unsupported import in exec: node:fs", { toolName: "exec" }); - expect(out.changed).toBe(true); - expect(out.isError).toBe(false); - expect(out.text).toContain("[recovery: Imports are not available in this exec context"); - // Replay of the annotated text with isError=false must not grow a second line. - expect(normalizeCursorToolResultText(out.text, { toolName: "exec" }).changed).toBe(false); + test.each(["Unsupported import in exec: node:fs", "unsupported import in exec: node:fs"])( + "a code-mode exec result carrying %p gains the shared hint, keeps its isError, and is not re-annotated on replay", + (payload) => { + const out = normalizeCursorToolResultText(payload, { toolName: "exec" }); + expect(out.changed).toBe(true); + expect(out.isError).toBe(false); + expect(out.text).toBe(`${payload}\n[recovery: Imports are not available in this exec context; use the injected globals (tools, text, notify, store, load, ALL_TOOLS) instead.]`); + // Replay through Responses history arrives with isError=false; the legacy lowercase marker + // row must not get a second look at it. + const replay = normalizeCursorToolResultText(out.text, { toolName: "exec", isError: false }); + expect(replay).toEqual({ text: out.text, isError: false, changed: false }); + }, + ); + + test("the legacy node_repl import row keeps its own isError policy", () => { + const out = normalizeCursorToolResultText("unsupported import in exec", { toolName: "js", toolNamespace: "mcp__node_repl" }); + expect(out.isError).toBe(true); + expect(out.text).toContain("injected globals"); }); test("a non-exec tool whose successful output merely mentions a host phrase stays byte-identical", () => { @@ -297,4 +341,3 @@ Stage only the files above (`git diff --cached --stat` first); commit `--no-veri NOT RUN locally. Exact-head Cross-platform CI on the wp2 head; receipt via `cxc receipt test --session --cwd -- gh run view --exit-status`. - diff --git a/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md index e0c0df7990..f3fc8d2eef 100644 --- a/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md +++ b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md @@ -12,14 +12,16 @@ search usable on xAI's public Responses endpoint…": ``` Routed code-mode turns also carry the host contract for the nested helpers, stated in the same three injection sites as the result-emission rule (shared catalog nudge, Cursor code-mode guidance, native -routed Responses instructions): `tools.apply_patch` takes one string whose first and last lines are -the bare patch markers, the isolate has no `import`/`require`, and a command that outlives +routed Responses instructions): `tools.apply_patch` takes one string that opens and closes with the +bare patch marker lines (blank lines or indentation around them are tolerated; a decorated or missing +marker is rejected), the isolate has no `import`/`require`, and a command that outlives `yield_time_ms` is polled through `write_stdin` with empty `chars` rather than a shell sleep loop. -When an exec-bridge result still carries one of the host's failure strings ("expects a string +When a code-mode exec result still carries one of the host's failure strings ("expects a string input", "The first line of the patch must be", "The last line of the patch must be", "Unsupported import in exec"), the native routed Responses, Kiro, and Cursor result paths append a one-line -recovery hint naming the broken rule; Cursor's error classification and Kiro's whitespace and -failed-wrapper grouping are unchanged. Both halves live in `src/adapters/exec-tool-result-normalize.ts` +recovery hint naming the broken rule; flat shell bridges and foreign MCP namespaces are never +annotated, and Cursor's error classification and Kiro's whitespace and failed-wrapper grouping are +unchanged. Both halves live in `src/adapters/exec-tool-result-normalize.ts` so the pre-call and post-hoc wording cannot drift. This guidance and annotation change rewrites neither the model's JavaScript nor its patch payload; the existing name-alias delimiter normalization in `src/responses/code-mode-helper-compat.ts` is unchanged, and the host still rejects a @@ -41,9 +43,9 @@ Insert after the paragraph ending "…and unrelated native custom payloads stay ``` Routed code-mode turns are also told the host's rules for the nested helpers before the first -call: `tools.apply_patch` takes one string whose first and last lines are the bare patch markers, -the isolate has no `import`, and long-running commands are polled through `write_stdin`. When an -exec result on the native routed Responses, Kiro, or Cursor path still carries one of the host's +call: `tools.apply_patch` takes one string that opens and closes with the bare patch marker lines, +the isolate has no `import`, and long-running commands are polled through `write_stdin`. When a +code-mode exec result on the native routed Responses, Kiro, or Cursor path still carries one of the host's failure messages, opencodex appends a one-line hint naming the rule. This change does not rewrite the model's code or its patch text. ``` @@ -77,4 +79,3 @@ Append `040_delivery_record.md` with PR number, head SHA, CI run id, per-job res improve (LOOP-PESSIMIST-01: prose cannot force compliance; effect on real Grok defect rate is unmeasured until a live re-probe), and the residual: Anthropic/Google/OpenAI-chat/command-code tool-result paths do not annotate host failures because they have no exec-result seam today. - From 3bcb9aa453a6567205d38409d955b3141ad977dd Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 14:45:42 +0900 Subject: [PATCH 005/116] docs(devlog): fold audit round 3 into the code-mode host contract roadmap --- .../000_plan.md | 29 +++++++- .../020_post_hoc_annotation.md | 73 +++++++++++++++---- .../030_docs_and_delivery.md | 6 +- 3 files changed, 88 insertions(+), 20 deletions(-) diff --git a/devlog/_plan/260907_code_mode_host_contract/000_plan.md b/devlog/_plan/260907_code_mode_host_contract/000_plan.md index 91c130df0a..0f9a8057fb 100644 --- a/devlog/_plan/260907_code_mode_host_contract/000_plan.md +++ b/devlog/_plan/260907_code_mode_host_contract/000_plan.md @@ -72,9 +72,10 @@ Not a NOOP. New exports in `exec-tool-result-normalize.ts` (full text in 010/020): -1. `CODE_MODE_HOST_CONTRACT_SENTENCE` — pre-call: one string argument, bare markers as first/last - line with nothing before or after them, no `import`/`require` (globals per the exec description, - non-exhaustive), `session_id` + `write_stdin` polling. +1. `CODE_MODE_HOST_CONTRACT_SENTENCE` — pre-call: one string argument; the patch opens and closes + with the bare marker lines (blank lines or indentation around them tolerated; decorated or + missing marker rejected); no `import`/`require` (globals per the exec description, + non-exhaustive); `session_id` + `write_stdin` polling. 2. `CODE_MODE_HOST_FAILURE_GUIDANCE` — marker → recovery rows for the four host strings, matched case-insensitively. 3. `annotateCodeModeHostFailure(text, {toolName, toolNamespace})` — gated by a new, narrower @@ -89,9 +90,21 @@ it gains one exec-gated branch that inserts the shared annotation WITHOUT changi (audit blockers 2 and 3). Kiro substitutes the annotation only where it would otherwise carry the raw text, leaving whitespace and failed-wrapper grouping untouched (blocker 1). +Code-mode context per seam: the native routed Responses seam already runs only after the body-level +code-mode gate (`responses-code-mode.ts:35-37`), so its annotation is exact. Kiro has +`codeModeExecName` in scope at the same call site (`kiro.ts:650`) and additionally requires it, so a +structured `exec` or an `exec` beside a shell bridge is never annotated there. Cursor's +`normalizeCursorToolResultText` is reached from six call sites without catalog context +(`protobuf-request.ts:392,842,1062,1097,1158,1272`); threading code-mode context through them is a +larger refactor than this unit, so Cursor coverage is name-based (exact `exec` under the +`opencodex-responses` provider). That is an accepted residual, recorded here and in the +structure doc: on Cursor a structured tool literally named `exec` whose output quotes one of the +four phrases would gain an additive recovery line with no error flip. + Accepted residual: a code-mode exec result that legitimately prints one of the four phrases (e.g. `cat` of this devlog) gains a recovery line. The line is additive text and never changes error -status; the gate excludes every non-code-mode tool, shell bridge, and foreign namespace. +status; the gate excludes every non-`exec` tool, every shell bridge, and every namespace other than +the exact `opencodex-responses` display aliases. Marker wording: the live probe shows the host tolerates blank lines and indentation around the markers and rejects a decorated or missing marker. Every sentence, recovery hint and doc paragraph @@ -174,3 +187,11 @@ re-reading each seam's own policy. Round 2 re-audits with the same reviewer. | 3 Responses replay `toBe(replayed)` cannot hold | Med | Folded: assert output-item and program identity plus deep-equal idempotence of successive passes (020). | | 4 Marker wording contradicts whitespace probe | Med | Folded: "bare marker line … blank lines or indentation tolerated" in sentence, hints, structure and docs-site text (010/020/030). | | 5 Off-by-one anchors | Low | Folded: 116, 32, 45-46, 97-106 (010/020). | + +## Audit round 3 — synthesis (GO-WITH-FIXES, blockers=3) + +| # | Sev | Disposition | +|---|---|---| +| 1 Bare `exec` name does not prove code mode | Med | Folded for Responses (body gate) and Kiro (`codeModeExecName` gate + structured/shell-bridge negative tests); accepted and narrowed for Cursor (name-based, additive text only) — see "Code-mode context per seam". | +| 2 Namespace `includes` admits foreign tools | Med | Folded: exact equality against `opencodex-responses` / `mcp__opencodex-responses` and the two flattened aliases; `mcp__foreign-opencodex-responses` negative and both flattened positives added (020). | +| 3 Summary retained the rejected whitespace claim | Low | Folded (this file, Design §1). | diff --git a/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md index 4bfa2df82d..86430340c0 100644 --- a/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md +++ b/devlog/_plan/260907_code_mode_host_contract/020_post_hoc_annotation.md @@ -37,18 +37,26 @@ export const CODE_MODE_HOST_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; gu /** Prefix of every recovery line this module appends; callers use it to recognise replayed annotations. */ export const CODE_MODE_HOST_RECOVERY_PREFIX = "[recovery: "; +/** Namespaces under which Cursor displays Codex's own Responses tools (see cursor/tool-naming.ts). */ +const CODEX_RESPONSES_DISPLAY_NAMESPACES: ReadonlySet = new Set(["opencodex-responses", "mcp__opencodex-responses"]); +/** Flattened spellings of the same code-mode exec when a client folds the namespace into the name. */ +const CODEX_CODE_MODE_EXEC_ALIASES: ReadonlySet = new Set(["exec", "mcp__opencodex-responses__exec", "mcp_opencodex-responses_exec"]); + /** - * The code-mode `exec` tool itself — bare, or under Cursor's `opencodex-responses` display namespace. - * The four host strings above originate only in that isolate, so flat shell bridges - * (`exec_command`, `shell`, …) and every foreign MCP namespace (`mcp__docker__exec`) are excluded: an - * unrelated server's output that happens to contain the phrase must not receive Codex guidance. - * Narrower than `isCodexExecBridgeTool` on purpose; the empty-output repair keeps the wider gate. + * The code-mode `exec` tool by NAME — bare, or under Codex's own `opencodex-responses` display + * namespace, matched exactly. The four host strings above originate only in that isolate, so flat + * shell bridges (`exec_command`, `shell`, …) and every other namespace (`mcp__docker`, + * `mcp__foreign-opencodex-responses`) are excluded: an unrelated server's output that quotes the + * phrase must not receive Codex guidance. Narrower than `isCodexExecBridgeTool` on purpose; the + * empty-output repair keeps the wider gate. Callers that KNOW the catalog shape (Kiro's + * `codeModeExecName`, the Responses body gate) add that check on top; this predicate alone cannot + * tell a structured tool named `exec` from the freeform one. */ export function isCodexCodeModeExecResult(toolName?: string, toolNamespace?: string): boolean { if (!toolName) return false; const lower = toolName.toLowerCase(); - if (toolNamespace) return toolNamespace.includes("opencodex-responses") && lower === "exec"; - return lower === "exec" || lower === "mcp__opencodex-responses__exec" || lower === "mcp_opencodex-responses_exec"; + if (toolNamespace !== undefined) return CODEX_RESPONSES_DISPLAY_NAMESPACES.has(toolNamespace) && lower === "exec"; + return CODEX_CODE_MODE_EXEC_ALIASES.has(lower); } /** @@ -122,10 +130,14 @@ AFTER: ```ts const execOptions = { toolName: tr.toolName, toolNamespace: tr.toolNamespace }; const normalizedExecText = normalizeEmptyExecToolResultText(text, execOptions); - // A host failure string inside a non-empty exec result gets the rule it broke appended. This - // is the only substitution the grouping path below also carries: whitespace and empty/failed + // A host failure string inside a non-empty exec result gets the rule it broke appended, but + // only when this request's emitted catalog is genuinely code mode (`codeModeExecName` above): + // a structured tool named exec, or exec beside a shell bridge, never ran the isolate. This is + // the only substitution the grouping path below also carries: whitespace and empty/failed // wrappers keep their existing raw policy. - const annotatedExecText = normalizedExecText === undefined ? annotateCodeModeHostFailure(text, execOptions) : undefined; + const annotatedExecText = normalizedExecText === undefined && codeModeExecName !== undefined + ? annotateCodeModeHostFailure(text, execOptions) + : undefined; const resultText = normalizedExecText ?? annotatedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); const images = extractKiroImages(tr.content); const toolUseId = normalizeToolId(tr.toolCallId); @@ -222,10 +234,19 @@ describe("code-mode host failure annotation", () => { expect(annotateCodeModeHostFailure("expects a string input", { toolName: "read_file" })).toBeUndefined(); // Flat shell bridges never run the isolate, so the four strings cannot be theirs. expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec_command" })).toBeUndefined(); - // A foreign MCP server's own exec is not Codex's, even when its output quotes the phrase. + // A foreign MCP server's own exec is not Codex's, even when its output quotes the phrase, and a + // namespace that merely CONTAINS the provider name is still foreign. expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec", toolNamespace: "mcp__docker" })).toBeUndefined(); - // Cursor's display namespace for the same code-mode tool still counts. - expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec", toolNamespace: "mcp__opencodex-responses" })).toContain("[recovery:"); + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec", toolNamespace: "mcp__foreign-opencodex-responses" })).toBeUndefined(); + // Codex's own display namespaces and flattened aliases for the same code-mode tool still count. + for (const options of [ + { toolName: "exec", toolNamespace: "opencodex-responses" }, + { toolName: "exec", toolNamespace: "mcp__opencodex-responses" }, + { toolName: "mcp__opencodex-responses__exec" }, + { toolName: "mcp_opencodex-responses_exec" }, + ]) { + expect(annotateCodeModeHostFailure("expects a string input", options)).toContain("[recovery:"); + } expect(annotateCodeModeHostFailure("all good", { toolName: "exec" })).toBeUndefined(); const once = annotateCodeModeHostFailure("expects a string input", { toolName: "exec" }); if (!once) throw new Error("expected one annotation"); @@ -275,7 +296,8 @@ entry is required and `tests/test-layout-tooling.test.ts` names it if missing. - After `"an empty code-mode exec result carries the actionable reason…"` (line 323) add: ```ts test("a code-mode exec result carrying a host failure string names the broken rule", async () => { - const execTool = { name: "exec", description: "Run JavaScript", parameters: { type: "object" } }; + // freeform: the Kiro seam annotates only when the emitted catalog is genuinely code mode. + const execTool = { name: "exec", description: "Run JavaScript", freeform: true, parameters: { type: "object" } }; const failure = "apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'"; const messages = [ { role: "user", content: "run it" }, @@ -287,6 +309,29 @@ entry is required and `tests/test-layout-tooling.test.ts` names it if missing. .userInputMessageContext.toolResults[0].content[0].text; expect(resultText).toBe(`${failure}\n[recovery: The patch text must open with the bare marker line \`*** Begin Patch\`: no code fence, prose, or extra asterisks on that line (blank lines or indentation before it are tolerated).]`); }); + + test("a host failure string on a non-code-mode catalog stays raw", async () => { + const failure = "tool `apply_patch` expects a string input"; + const messages = [ + { role: "user", content: "run it" }, + { role: "assistant", content: [{ type: "toolCall", id: "call-x", name: "exec", arguments: {} }] }, + { role: "toolResult", toolCallId: "call-x", toolName: "exec", content: failure, isError: false }, + ]; + for (const tools of [ + // A structured tool that merely shares the name exec. + [{ name: "exec", description: "Run a shell string", parameters: { type: "object" } }], + // Freeform exec beside a bare shell bridge is the flat-catalog shape, not code mode. + [ + { name: "exec", description: "Run JavaScript", freeform: true, parameters: { type: "object" } }, + { name: "exec_command", description: "Run", parameters: { type: "object" } }, + ], + ]) { + const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages, tools)); + const resultText = JSON.parse(body).conversationState.currentMessage.userInputMessage + .userInputMessageContext.toolResults[0].content[0].text; + expect(resultText).toBe(failure); + } + }); ``` - In the grouped-result table (the `execResult` cases around lines 1195-1262) add one case: ```ts diff --git a/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md index f3fc8d2eef..8bd40668e0 100644 --- a/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md +++ b/devlog/_plan/260907_code_mode_host_contract/030_docs_and_delivery.md @@ -20,8 +20,10 @@ When a code-mode exec result still carries one of the host's failure strings ("e input", "The first line of the patch must be", "The last line of the patch must be", "Unsupported import in exec"), the native routed Responses, Kiro, and Cursor result paths append a one-line recovery hint naming the broken rule; flat shell bridges and foreign MCP namespaces are never -annotated, and Cursor's error classification and Kiro's whitespace and failed-wrapper grouping are -unchanged. Both halves live in `src/adapters/exec-tool-result-normalize.ts` +annotated, Responses and Kiro additionally require the request's verified code-mode catalog, Cursor +matches the exact `exec` name under its `opencodex-responses` provider without catalog context, and +Cursor's error classification and Kiro's whitespace and failed-wrapper grouping are unchanged. Both +halves live in `src/adapters/exec-tool-result-normalize.ts` so the pre-call and post-hoc wording cannot drift. This guidance and annotation change rewrites neither the model's JavaScript nor its patch payload; the existing name-alias delimiter normalization in `src/responses/code-mode-helper-compat.ts` is unchanged, and the host still rejects a From 5b70dddb0bdeba8d26b7844df63c70f796b9228c Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 14:46:34 +0900 Subject: [PATCH 006/116] docs(devlog): record live Codex host probe evidence for the code-mode contract --- .../001_host_probe_evidence.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 devlog/_plan/260907_code_mode_host_contract/001_host_probe_evidence.md diff --git a/devlog/_plan/260907_code_mode_host_contract/001_host_probe_evidence.md b/devlog/_plan/260907_code_mode_host_contract/001_host_probe_evidence.md new file mode 100644 index 0000000000..757ae63fe4 --- /dev/null +++ b/devlog/_plan/260907_code_mode_host_contract/001_host_probe_evidence.md @@ -0,0 +1,53 @@ +# 001 — Live host probe evidence (Codex 0.153.2, 2026-09-07) + +Research record backing the incident table in 000_plan.md. Every row was executed from this +session's own code-mode isolate (`custom_exec` → `tools.apply_patch`) against +`/Users/jun/.codex/worktrees/ec3e/opencodex/.tmp/`; scratch files were deleted afterwards. + +## Binary strings + +`strings -n 8` over the installed binaries under +`@openai/codex-darwin-arm64/vendor/aarch64-apple-darwin/bin/`: + +| Binary | String | +|---|---| +| `codex` | `\` expects a string input` (preceded by the tool name) | +| `codex` | `The first line of the patch must be '*** Begin Patch'` | +| `codex` | `The last line of the patch must be '*** End Patch'` | +| `codex` | `Script running with cell ID ` | +| `codex` | `Session identifier to pass to write_stdin when the process is still running.` | +| `codex` | `Bytes to write to stdin. Defaults to empty, which polls without writing.` | +| `codex-code-mode-host` | `Unsupported import in exec: ` and `unsupported import in exec` | + +## apply_patch argument probes + +| Argument passed to `tools.apply_patch` | Result | +|---|---| +| `{ input: "*** Begin Patch\n*** End Patch" }` | throws `tool \`apply_patch\` expects a string input` | +| `"*** Begin Patch ***\n*** Add File: …\n+z\n*** End Patch ***"` | throws `apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'` | +| `"\n*** Begin Patch\n*** Add File: …\n+x\n*** End Patch"` | accepted; file written | +| `"\n\n*** Begin Patch\n…"` | accepted; file written | +| `" *** Begin Patch\n…"` (two-space indent) | accepted; file written | +| `"…*** End Patch\n\n"` | accepted; file written | +| a patch with two operations on the same path | throws `invalid patch: multiple operations target ` | +| two `*** End Patch` lines (envelope pasted twice) | throws `The last line of the patch must be '*** End Patch'` | + +Conclusion carried into the wording: the host strips surrounding whitespace before checking the +marker lines, so "no leading newline" is not a rule. The rule is that the first non-blank line is +exactly `*** Begin Patch` and the last is exactly `*** End Patch`, undecorated. + +## Long-running command protocol + +The `exec_command` schema in this session: `yield_time_ms` "Wait before yielding output. Defaults to +10000 ms; effective range is 250-30000 ms"; `session_id` "Session identifier to pass to write_stdin +when the process is still running". `write_stdin`: `chars` "Defaults to empty, which polls without +writing"; empty polls wait 5000-300000 ms. A shell `for i in 1..20; sleep 1` inside one call +produces no error string; it simply spends the call's yield budget blocked. + +## Isolate globals + +The `exec` description in this session lists `exit`, `text`, `image`, `audio`, `generatedImage`, +`store`/`load`, `notify`, `setTimeout`/`clearTimeout`, `ALL_TOOLS`, `yield_control`, plus `tools.*`. +The list varies by client version, which is why the pre-call sentence names a few examples and +defers to the description rather than enumerating. + From adafd12f7721ba1e64d699caad48e8bdbb544239 Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 14:49:39 +0900 Subject: [PATCH 007/116] fix(code-mode): state the host contract for nested helpers before the first call Routed models in Codex code mode learned apply_patch argument shape, the marker rule, the isolate import ban and session_id polling only by failing (xai/grok-4.6, 2026-09-07). State them once in exec-tool-result-normalize.ts beside the echo rule and inject at the three existing code-mode sites: shared nudge, Cursor guidance, native routed Responses instructions. --- src/adapters/cursor/tool-guidance.ts | 4 ++-- src/adapters/exec-tool-result-normalize.ts | 15 +++++++++++++++ src/adapters/responses-code-mode.ts | 13 ++++++++++--- src/adapters/tool-catalog-nudge.ts | 4 ++-- tests/adapters/tool-catalog-nudge.test.ts | 7 ++++++- .../cursor/cursor-tool-definitions.test.ts | 4 ++++ tests/providers/kiro/kiro-adapter.test.ts | 2 ++ .../openai-responses-passthrough.test.ts | 15 +++++++++++++-- 8 files changed, 54 insertions(+), 10 deletions(-) diff --git a/src/adapters/cursor/tool-guidance.ts b/src/adapters/cursor/tool-guidance.ts index 54ebcc86d1..87e63730ca 100644 --- a/src/adapters/cursor/tool-guidance.ts +++ b/src/adapters/cursor/tool-guidance.ts @@ -1,5 +1,5 @@ import type { OcxRequestOptions, OcxTool } from "../../types"; -import { CODE_MODE_RESULT_ECHO_SENTENCE } from "../exec-tool-result-normalize"; +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE } from "../exec-tool-result-normalize"; import { CODEX_SHELL_BRIDGE_TOOL_NAMES, CODEX_TOOL_SEARCH_TOOL, CODEX_UNIFIED_EXEC_TOOL, clientSemanticToolNameFromCursorWire, cursorRequestAdvertisesApplyPatch, cursorRequestHasExecutionPath, cursorRequestHasShellAlias, cursorRequestUsesCodeMode, cursorToolAllowedByChoice, cursorToolWireName, isCodexShellBridgeToolName, isCursorExecutionPathTool, isCursorStructuredEditToolName } from "./tool-naming"; export const CURSOR_SHELL_ALIAS_SYSTEM_NOTE = @@ -187,7 +187,7 @@ export function buildCursorToolGuidanceSystemNote( ? `\`${CODEX_UNIFIED_EXEC_TOOL}\` is Codex code mode: its body is JavaScript evaluated in a V8 isolate, not a shell command and not Node. Shell, file edits, and MCP are nested helpers called INSIDE that body as \`await tools.(...)\`, for example \`await tools.exec_command({cmd: \"ls\"})\`. Read the tool description and the isolate global \`ALL_TOOLS\` (not \`tools.ALL_TOOLS\`) for helpers this turn provides; absence from the top-level catalog or from \`exec\`'s description is not absence. Those nested helpers are not themselves top-level tools, so do not call \`exec_command\` or \`shell_command\` at the top level here${codeModeOtherTopLevelNames.length > 0 ? `; every other tool this turn lists, including ${quotedNames(codeModeOtherTopLevelNames)}, remains callable at the top level as usual` : ""}. Nested \`tools.apply_patch(input)\` is host-executed: the string must begin exactly with \`*** Begin Patch\` and end with \`*** End Patch\`, each marker line being three asterisks, one space, the two words, then end of line with no further asterisks. OpenCodex does not rewrite JavaScript inside exec, so extra asterisks on a marker line are rejected by Codex before the file is touched.` : undefined, codeMode - ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers." + ? CODE_MODE_RESULT_ECHO_SENTENCE + " There is no `require`, no `module`, and no filesystem or network globals; reach the host only through the nested helpers. " + CODE_MODE_HOST_CONTRACT_SENTENCE : undefined, codeMode ? "NEVER attempt Cursor-native Shell, Read, Grep, List, or any tool absent from the catalog — they are not executed in this environment and every probe wastes a turn. The exec code cell (with its nested helpers) is the ONLY execution surface; go to it directly on the FIRST attempt and do not narrate switching surfaces." diff --git a/src/adapters/exec-tool-result-normalize.ts b/src/adapters/exec-tool-result-normalize.ts index c103808420..ad1969c229 100644 --- a/src/adapters/exec-tool-result-normalize.ts +++ b/src/adapters/exec-tool-result-normalize.ts @@ -115,6 +115,21 @@ export const EMPTY_EXEC_OUTPUT_MESSAGE = export const CODE_MODE_RESULT_ECHO_SENTENCE = "Nothing in the isolate is echoed automatically: a bare trailing `await tools.(...)` or final expression value is DISCARDED, and the cell reports empty output. Pass anything you need to read to `text(...)` (or `notify(...)`) in the same cell — for example `text(JSON.stringify(await tools.exec_command({cmd: 'ls'})))` — and treat an empty result as your own missing `text(...)` call rather than a failed command or lost context."; +/** + * Host rules a routed model most often breaks on its first code-mode edit or wait, stated BEFORE + * the call. Wording tracks the Codex host (0.153.2), probed live on 2026-09-07: a non-string + * argument to `apply_patch` throws "expects a string input"; a body whose first line is not the + * bare marker (decorated `*** Begin Patch ***`, a code fence, prose) throws "The first line of the + * patch must be '*** Begin Patch'" — surrounding newlines are tolerated; ES imports throw + * "Unsupported import in exec"; a command that outlives `yield_time_ms` returns `session_id` for + * `write_stdin` polling. xai/grok-4.6 hit the first two, abandoned apply_patch for heredoc writes, + * blocked a turn in a shell sleep loop, and died once on an import. None of that is repairable in + * the proxy (devlog/_plan/260905_apply_patch_envelope_gap/010 MODE B); it is a contract the proxy + * had not stated. + */ +export const CODE_MODE_HOST_CONTRACT_SENTENCE = + "Host contract for the nested helpers: `tools.apply_patch(patch)` takes exactly one string, never an object such as `{input: ...}`; the patch text opens with the bare marker line `*** Begin Patch` and closes with the bare marker line `*** End Patch`, written without a code fence, prose, or extra asterisks on those lines (blank lines or indentation around the markers are tolerated; a decorated or missing marker is rejected). The isolate has no `import`, `require`, or module loader; use the globals the exec tool description lists (for example `tools`, `text`, `notify`, `store`/`load`, `ALL_TOOLS`). For a command that may outlive `yield_time_ms`, let `tools.exec_command` return a `session_id` and poll it on later calls with `tools.write_stdin({session_id, chars: \"\"})` instead of blocking a shell in a sleep loop."; + /** * Codex exec / shell-bridge tool names (flat and MCP-prefixed display aliases). An empty result * here is almost always a code-mode cell that never called text()/notify(). diff --git a/src/adapters/responses-code-mode.ts b/src/adapters/responses-code-mode.ts index 25e51f204e..ebbab97fd9 100644 --- a/src/adapters/responses-code-mode.ts +++ b/src/adapters/responses-code-mode.ts @@ -1,6 +1,6 @@ import { toolChoiceToolPredicate, type OcxParsedRequest, type OcxProviderConfig } from "../types"; import { isOpenAiOperatedResponsesDestination } from "../providers/openai-tiers"; -import { CODE_MODE_RESULT_ECHO_SENTENCE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; import { isBareShellBridgeTool, isCodexCodeModeExecTool } from "./tool-catalog-nudge"; function record(value: unknown): value is Record { @@ -29,6 +29,14 @@ function withExecInputGuidance(tool: unknown): unknown { } } }; } +/** Append each sentence a replayed instructions string does not already carry, in order. */ +function appendMissing(instructions: string, sentences: readonly string[]): string { + return sentences.reduce( + (acc, sentence) => acc.includes(sentence) ? acc : [acc, sentence].filter(Boolean).join("\n\n"), + instructions, + ); +} + /** Native routed Responses needs the same first-call/output contract as translated adapters. */ export function normalizeResponsesCodeMode(body: unknown, parsed: OcxParsedRequest, provider: OcxProviderConfig): unknown { if (!record(body) || parsed._compactionRequest || isOpenAiOperatedResponsesDestination(provider)) return body; @@ -42,8 +50,7 @@ export function normalizeResponsesCodeMode(body: unknown, parsed: OcxParsedReque .map(item => item.call_id)); return { ...body, - instructions: instructions.includes(CODE_MODE_RESULT_ECHO_SENTENCE) - ? instructions : [instructions, CODE_MODE_RESULT_ECHO_SENTENCE].filter(Boolean).join("\n\n"), + instructions: appendMissing(instructions, [CODE_MODE_RESULT_ECHO_SENTENCE, CODE_MODE_HOST_CONTRACT_SENTENCE]), ...(Array.isArray(body.tools) ? { tools: body.tools.map(withExecInputGuidance) } : {}), ...(input ? { input: input.map(item => { if (!record(item)) return item; diff --git a/src/adapters/tool-catalog-nudge.ts b/src/adapters/tool-catalog-nudge.ts index 6e5659a78f..5b218f27e6 100644 --- a/src/adapters/tool-catalog-nudge.ts +++ b/src/adapters/tool-catalog-nudge.ts @@ -5,7 +5,7 @@ import { type OcxTool, type OcxProviderConfig, } from "../types"; -import { CODE_MODE_RESULT_ECHO_SENTENCE } from "./exec-tool-result-normalize"; +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE } from "./exec-tool-result-normalize"; // Tool names that exist only in OTHER agent harnesses (Claude Code and friends). Naming one // here tells a routed model not to call it unless this turn's catalog really lists it. @@ -121,7 +121,7 @@ export function buildNonOpenAIToolCatalogNudgeFromNames( "Call only listed names with their listed argument keys; do not invent, translate, or rename tools.", "Names mentioned only in instructions, tool descriptions, argument descriptions, or nested helper APIs are not additional top-level tools.", verifiedCodeModeExecName - ? "`" + verifiedCodeModeExecName + "` is Codex code mode: its body is JavaScript evaluated in a V8 isolate. Nested helpers are called INSIDE that body as `await tools.(...)`, for example `await tools.exec_command({cmd: \"ls\"})` or `await tools.codex_app__list_threads({})`. Absence from the top-level catalog or from `" + verifiedCodeModeExecName + "`'s description is not absence: deferred helpers stay callable on `tools.`. Discover them from the isolate global `ALL_TOOLS`, not `tools.ALL_TOOLS`. Do not skip an available nested helper because it is omitted from the listed top-level names. " + CODE_MODE_RESULT_ECHO_SENTENCE + " Nested `tools.apply_patch(input)` is host-executed: the string must begin exactly with `*** Begin Patch` and end with `*** End Patch`, each marker line being three asterisks, one space, the two words, then end of line with no further asterisks. OpenCodex does not rewrite JavaScript inside exec, so extra asterisks on a marker line are rejected by Codex before the file is touched." + ? "`" + verifiedCodeModeExecName + "` is Codex code mode: its body is JavaScript evaluated in a V8 isolate. Nested helpers are called INSIDE that body as `await tools.(...)`, for example `await tools.exec_command({cmd: \"ls\"})` or `await tools.codex_app__list_threads({})`. Absence from the top-level catalog or from `" + verifiedCodeModeExecName + "`'s description is not absence: deferred helpers stay callable on `tools.`. Discover them from the isolate global `ALL_TOOLS`, not `tools.ALL_TOOLS`. Do not skip an available nested helper because it is omitted from the listed top-level names. " + CODE_MODE_RESULT_ECHO_SENTENCE + " Nested `tools.apply_patch(input)` is host-executed: the string must begin exactly with `*** Begin Patch` and end with `*** End Patch`, each marker line being three asterisks, one space, the two words, then end of line with no further asterisks. OpenCodex does not rewrite JavaScript inside exec, so extra asterisks on a marker line are rejected by Codex before the file is touched. " + CODE_MODE_HOST_CONTRACT_SENTENCE : "If a listed tool exposes nested helpers such as a tools.* API, call the listed parent tool and use those helpers only inside that tool's input.", unavailableNeighborNames.length > 0 ? "Do not use neighboring-agent tool names " + quoteNames(unavailableNeighborNames) + " unless this turn's catalog lists those exact names." diff --git a/tests/adapters/tool-catalog-nudge.test.ts b/tests/adapters/tool-catalog-nudge.test.ts index 18fc5a301c..f875113a75 100644 --- a/tests/adapters/tool-catalog-nudge.test.ts +++ b/tests/adapters/tool-catalog-nudge.test.ts @@ -4,7 +4,7 @@ import { buildNonOpenAIToolCatalogNudgeFromNames, shouldInjectNonOpenAIToolCatalogNudge, } from "../../src/adapters/tool-catalog-nudge"; -import { CODE_MODE_RESULT_ECHO_SENTENCE, EMPTY_EXEC_OUTPUT_MESSAGE } from "../../src/adapters/exec-tool-result-normalize"; +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, EMPTY_EXEC_OUTPUT_MESSAGE } from "../../src/adapters/exec-tool-result-normalize"; import type { OcxTool } from "../../src/types"; describe("non-OpenAI tool catalog nudge", () => { @@ -80,6 +80,10 @@ describe("non-OpenAI tool catalog nudge", () => { expect(note).toContain("OpenCodex does not rewrite JavaScript inside exec"); expect(note).toContain("Nested `tools.apply_patch(input)` is host-executed"); expect(note).not.toContain("call the listed parent tool and use those helpers only inside that tool's input"); + // The host contract rides the same code-mode branch as the echo rule (Grok 2026-09-07). + expect(note).toContain(CODE_MODE_HOST_CONTRACT_SENTENCE); + expect(note).toContain("takes exactly one string"); + expect(note).toContain("write_stdin({session_id, chars: \"\"})"); }); test("keeps the generic nested-helper parent-tool rule when exec is not listed", () => { @@ -88,6 +92,7 @@ describe("non-OpenAI tool catalog nudge", () => { expect(note).toContain("call the listed parent tool and use those helpers only inside that tool's input"); expect(note).not.toContain("is Codex code mode"); expect(note).not.toContain("tools.ALL_TOOLS"); + expect(note).not.toContain("Host contract for the nested helpers"); }); test("detects a wire-renamed exec as code mode", () => { diff --git a/tests/providers/cursor/cursor-tool-definitions.test.ts b/tests/providers/cursor/cursor-tool-definitions.test.ts index 852936a2e5..fb15f0e7d6 100644 --- a/tests/providers/cursor/cursor-tool-definitions.test.ts +++ b/tests/providers/cursor/cursor-tool-definitions.test.ts @@ -771,6 +771,9 @@ describe("Cursor code mode tool guidance", () => { expect(note).toContain("no further asterisks"); expect(note).not.toContain("*** Begin Patch ***"); expect(note).toContain("OpenCodex does not rewrite JavaScript inside exec"); + expect(note).toContain("Host contract for the nested helpers"); + expect(note).toContain("takes exactly one string"); + expect(note).toContain("write_stdin"); // The flat-catalog shell-bridge guidance must NOT appear: naming a top-level // `exec_command` in code mode sends the model after a tool that does not exist. @@ -819,6 +822,7 @@ describe("Cursor code mode tool guidance", () => { expect(note).toContain("is the Codex Responses shell bridge for this turn"); expect(note).not.toContain("is Codex code mode"); expect(note).not.toContain("V8 isolate"); + expect(note).not.toContain("Host contract for the nested helpers"); }); }); diff --git a/tests/providers/kiro/kiro-adapter.test.ts b/tests/providers/kiro/kiro-adapter.test.ts index f4a9aa83e6..fbdeec50b2 100644 --- a/tests/providers/kiro/kiro-adapter.test.ts +++ b/tests/providers/kiro/kiro-adapter.test.ts @@ -1823,6 +1823,8 @@ describe("kiro code-mode catalog nudge", () => { // Reaches the ACTUAL Kiro wire prompt, not just the builder: the live 2026-08-28 session that // misread a blank result was a routed Kiro turn. expect(content).toContain("Nothing in the isolate is echoed automatically"); + // Survives Kiro's 16 384-char injected-instruction bound on the real wire prompt. + expect(content).toContain("Host contract for the nested helpers"); // The generic fallback must be gone, not merely accompanied. expect(content).not.toContain("If a listed tool exposes nested helpers such as a tools.* API"); }); diff --git a/tests/responses/openai-responses-passthrough.test.ts b/tests/responses/openai-responses-passthrough.test.ts index 24bc8e0e02..25ee2af5ac 100644 --- a/tests/responses/openai-responses-passthrough.test.ts +++ b/tests/responses/openai-responses-passthrough.test.ts @@ -3,7 +3,7 @@ import { createOpenAIChatAdapter } from "../../src/adapters/openai-chat"; import { createResponsesPassthroughAdapter as createResponsesPassthroughAdapterProduction } from "../../src/adapters/openai-responses"; import { openaiResponsesUrl } from "../../src/adapters/openai-responses-url"; import { normalizeResponsesCodeMode } from "../../src/adapters/responses-code-mode"; -import { CODE_MODE_RESULT_ECHO_SENTENCE, EMPTY_EXEC_OUTPUT_MESSAGE, FAILED_EXEC_OUTPUT_MESSAGE } from "../../src/adapters/exec-tool-result-normalize"; +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, EMPTY_EXEC_OUTPUT_MESSAGE, FAILED_EXEC_OUTPUT_MESSAGE } from "../../src/adapters/exec-tool-result-normalize"; import { chatCompletionsToResponsesBody } from "../../src/chat/inbound"; import { anthropicToResponsesBody } from "../../src/claude/inbound"; import { parseRequest } from "../../src/responses/parser"; @@ -51,7 +51,7 @@ describe("native routed code-mode result visibility", () => { const before = JSON.stringify(body); const request = createResponsesPassthroughAdapter(routed).buildRequest(parseRequest(body)); const wire = JSON.parse(request.body); - expect(wire.instructions).toBe(`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}`); + expect(wire.instructions).toBe(`Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}\n\n${CODE_MODE_HOST_CONTRACT_SENTENCE}`); expect(wire.tools.find((tool: { name: string }) => tool.name === "exec").parameters.properties.input.description) .toContain(CODE_MODE_RESULT_ECHO_SENTENCE); expect(JSON.stringify(body)).toBe(before); @@ -103,6 +103,16 @@ describe("native routed code-mode result visibility", () => { expect(second.instructions).toBe(first.instructions); }); + test("a replayed body that already carries the echo rule gains only the missing contract sentence", () => { + const body = { ...raw(), instructions: `Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}` }; + const parsed = parseRequest(body); + const first = normalizeResponsesCodeMode(body, parsed, routed) as typeof body; + expect(first.instructions).toBe(`${body.instructions}\n\n${CODE_MODE_HOST_CONTRACT_SENTENCE}`); + expect(first.instructions.split(CODE_MODE_RESULT_ECHO_SENTENCE).length).toBe(2); + const second = normalizeResponsesCodeMode(first, parsed, routed) as typeof body; + expect(second.instructions).toBe(first.instructions); + }); + test("official OpenAI and non-code-mode catalogs remain untouched", () => { const body = raw(); for (const native of [provider, { ...routed, baseUrl: "https://api.openai.com/v1" }]) { @@ -110,6 +120,7 @@ describe("native routed code-mode result visibility", () => { const wire = JSON.parse(createResponsesPassthroughAdapter(native).buildRequest(parseRequest(body)).body); expect(wire.instructions).toBe(body.instructions); expect(JSON.stringify(wire.tools)).not.toContain(CODE_MODE_RESULT_ECHO_SENTENCE); + expect(JSON.stringify(wire)).not.toContain("Host contract for the nested helpers"); } for (const tools of [ [{ type: "function", name: "exec", parameters: { type: "object" } }], From 163378050d75bda4bc6eb0821da9382e5a80c67a Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 15:04:40 +0900 Subject: [PATCH 008/116] fix(code-mode): name the broken host rule on exec results that carry a host failure string Post-hoc half of the host contract. Exec-bridge results carrying "expects a string input", "The first/last line of the patch must be", or "Unsupported import in exec" gain one recovery line on the native routed Responses, Kiro and Cursor result paths. Responses and Kiro additionally require the verified code-mode catalog; Cursor matches the exact exec name under its opencodex-responses provider and keeps its isError policy. Flat shell bridges, foreign namespaces, whitespace/failed-wrapper grouping and replayed annotations are untouched. --- scripts/test-layout/layout.json | 1 + src/adapters/cursor/tool-result-normalize.ts | 12 ++++ src/adapters/exec-tool-result-normalize.ts | 67 +++++++++++++++++++ src/adapters/kiro.ts | 20 ++++-- src/adapters/responses-code-mode.ts | 7 +- .../exec-tool-result-normalize.test.ts | 62 +++++++++++++++++ tests/fixtures/test-layout-expected.json | 1 + .../cursor-toolresult-normalize.test.ts | 28 ++++++++ tests/providers/kiro/kiro-adapter.test.ts | 62 +++++++++++++++++ .../openai-responses-passthrough.test.ts | 15 +++++ 10 files changed, 266 insertions(+), 9 deletions(-) create mode 100644 tests/adapters/exec-tool-result-normalize.test.ts diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 65ba23d900..60e0f22a0d 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -618,6 +618,7 @@ "empty-completion-guard.test.ts": "responses", "empty-completion-hardening.test.ts": "responses", "empty-tool-output-annotation.test.ts": "adapters", + "exec-tool-result-normalize.test.ts": "adapters", "ensure-desired-integrations-race.test.ts": "cli", "error-fidelity.test.ts": "server", "errors-adapter-failure.test.ts": "server", diff --git a/src/adapters/cursor/tool-result-normalize.ts b/src/adapters/cursor/tool-result-normalize.ts index fded734b93..edec3a14f4 100644 --- a/src/adapters/cursor/tool-result-normalize.ts +++ b/src/adapters/cursor/tool-result-normalize.ts @@ -10,9 +10,12 @@ */ import { + CODE_MODE_HOST_RECOVERY_PREFIX, EMPTY_EXEC_OUTPUT_MESSAGE, EMPTY_EXEC_OUTPUT_REGEX, FAILED_EXEC_OUTPUT_MESSAGE, + annotateCodeModeHostFailure, + isCodexCodeModeExecResult, isFailedEmptyExecWrapper, isCodexExecBridgeTool, } from "../exec-tool-result-normalize"; @@ -104,6 +107,15 @@ export function normalizeCursorToolResultText( changed: true, }; } + // A host failure string inside a code-mode exec result gets the rule it broke appended, with + // Cursor's isError decision left exactly as the caller passed it. A replayed result that already + // carries a recovery line returns here unchanged: falling through would let the legacy loop + // below match the lowercase import marker a second time and flip isError. + if (isCodexCodeModeExecResult(options.toolName, options.toolNamespace)) { + if (text.includes(CODE_MODE_HOST_RECOVERY_PREFIX)) return { text, isError, changed: false }; + const hostFailure = annotateCodeModeHostFailure(text, options); + if (hostFailure !== undefined) return { text: hostFailure, isError, changed: true }; + } if (!isError) { for (const { marker, guidance } of RUNTIME_FAILURE_GUIDANCE) { if (text.includes(marker)) { diff --git a/src/adapters/exec-tool-result-normalize.ts b/src/adapters/exec-tool-result-normalize.ts index ad1969c229..a6e4a3190a 100644 --- a/src/adapters/exec-tool-result-normalize.ts +++ b/src/adapters/exec-tool-result-normalize.ts @@ -130,6 +130,73 @@ export const CODE_MODE_RESULT_ECHO_SENTENCE = export const CODE_MODE_HOST_CONTRACT_SENTENCE = "Host contract for the nested helpers: `tools.apply_patch(patch)` takes exactly one string, never an object such as `{input: ...}`; the patch text opens with the bare marker line `*** Begin Patch` and closes with the bare marker line `*** End Patch`, written without a code fence, prose, or extra asterisks on those lines (blank lines or indentation around the markers are tolerated; a decorated or missing marker is rejected). The isolate has no `import`, `require`, or module loader; use the globals the exec tool description lists (for example `tools`, `text`, `notify`, `store`/`load`, `ALL_TOOLS`). For a command that may outlive `yield_time_ms`, let `tools.exec_command` return a `session_id` and poll it on later calls with `tools.write_stdin({session_id, chars: \"\"})` instead of blocking a shell in a sleep loop."; +/** + * Post-hoc half of the host contract: the four host strings a routed model reads inside a + * non-error exec result, each paired with the rule it broke. Matched case-insensitively because + * the host writes "Unsupported import in exec: " while Cursor's earlier marker was + * lowercase; one table, one owner, so this text and the pre-call sentence cannot drift. + */ +export const CODE_MODE_HOST_FAILURE_GUIDANCE: ReadonlyArray<{ marker: string; guidance: string }> = [ + { + marker: "expects a string input", + guidance: "tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.", + }, + { + marker: "the first line of the patch must be", + guidance: "The patch text must open with the bare marker line `*** Begin Patch`: no code fence, prose, or extra asterisks on that line (blank lines or indentation before it are tolerated).", + }, + { + marker: "the last line of the patch must be", + guidance: "The patch text must close with the bare marker line `*** End Patch`: no trailing text or extra asterisks on that line (blank lines after it are tolerated).", + }, + { + marker: "unsupported import in exec", + guidance: "Imports are not available in this exec context; use the injected globals (tools, text, notify, store, load, ALL_TOOLS) instead.", + }, +]; + +/** Prefix of every recovery line this module appends; callers use it to recognise replayed annotations. */ +export const CODE_MODE_HOST_RECOVERY_PREFIX = "[recovery: "; + +/** Namespaces under which Cursor displays Codex's own Responses tools (see cursor/tool-naming.ts). */ +const CODEX_RESPONSES_DISPLAY_NAMESPACES: ReadonlySet = new Set(["opencodex-responses", "mcp__opencodex-responses"]); +/** Flattened spellings of the same code-mode exec when a client folds the namespace into the name. */ +const CODEX_CODE_MODE_EXEC_ALIASES: ReadonlySet = new Set(["exec", "mcp__opencodex-responses__exec", "mcp_opencodex-responses_exec"]); + +/** + * The code-mode `exec` tool by NAME — bare, or under Codex's own `opencodex-responses` display + * namespace, matched exactly. The four host strings above originate only in that isolate, so flat + * shell bridges (`exec_command`, `shell`, …) and every other namespace (`mcp__docker`, + * `mcp__foreign-opencodex-responses`) are excluded: an unrelated server's output that quotes the + * phrase must not receive Codex guidance. Narrower than `isCodexExecBridgeTool` on purpose; the + * empty-output repair keeps the wider gate. Callers that KNOW the catalog shape (Kiro's + * `codeModeExecName`, the Responses body gate) add that check on top; this predicate alone cannot + * tell a structured tool named `exec` from the freeform one. + */ +export function isCodexCodeModeExecResult(toolName?: string, toolNamespace?: string): boolean { + if (!toolName) return false; + const lower = toolName.toLowerCase(); + if (toolNamespace !== undefined) return CODEX_RESPONSES_DISPLAY_NAMESPACES.has(toolNamespace) && lower === "exec"; + return CODEX_CODE_MODE_EXEC_ALIASES.has(lower); +} + +/** + * Append a one-line recovery hint when a code-mode exec result carries a known host failure string. + * Returns undefined when the tool is not the code-mode exec, no marker matches, or a recovery line is + * already present (a replayed annotated result must not grow a second one). Never touches error + * status: the host already decided whether the call failed. + */ +export function annotateCodeModeHostFailure( + text: string, + options: { toolName?: string; toolNamespace?: string } = {}, +): string | undefined { + if (!isCodexCodeModeExecResult(options.toolName, options.toolNamespace)) return undefined; + if (text.includes(CODE_MODE_HOST_RECOVERY_PREFIX)) return undefined; + const lower = text.toLowerCase(); + const hit = CODE_MODE_HOST_FAILURE_GUIDANCE.find(({ marker }) => lower.includes(marker)); + return hit ? `${text}\n${CODE_MODE_HOST_RECOVERY_PREFIX}${hit.guidance}]` : undefined; +} + /** * Codex exec / shell-bridge tool names (flat and MCP-prefixed display aliases). An empty result * here is almost always a code-mode cell that never called text()/notify(). diff --git a/src/adapters/kiro.ts b/src/adapters/kiro.ts index 200b1edb77..56ee632343 100644 --- a/src/adapters/kiro.ts +++ b/src/adapters/kiro.ts @@ -44,7 +44,7 @@ import { extractKiroImages, normalizeKiroImages, type KiroImage } from "./kiro-i import { sniffImageDimensions } from "./anthropic-image-guard"; import { fetchKiroWithRetry, noteKiroTransientThrottle } from "./kiro-retry"; import { convertKiroToolContext } from "./kiro-tools"; -import { EMPTY_EXEC_OUTPUT_MESSAGE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; +import { EMPTY_EXEC_OUTPUT_MESSAGE, annotateCodeModeHostFailure, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; import { identifyRoutedModel } from "./identity"; import { buildNonOpenAIToolCatalogNudgeFromNames, isBareShellBridgeTool, isCodexCodeModeExecTool } from "./tool-catalog-nudge"; import { @@ -755,11 +755,17 @@ export function buildKiroPayload( // the task instead of calling text()/notify(). Checked before `text.trim()` because the // wrapper form ("Script completed\nWall time ...\nOutput:\n") is non-blank and would // otherwise pass through as if it were real output. - const normalizedExecText = normalizeEmptyExecToolResultText(text, { - toolName: tr.toolName, - toolNamespace: tr.toolNamespace, - }); - const resultText = normalizedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); + const execOptions = { toolName: tr.toolName, toolNamespace: tr.toolNamespace }; + const normalizedExecText = normalizeEmptyExecToolResultText(text, execOptions); + // A host failure string inside a non-empty exec result gets the rule it broke appended, but + // only when this request's emitted catalog is genuinely code mode (`codeModeExecName` above): + // a structured tool named exec, or exec beside a shell bridge, never ran the isolate. This is + // the only substitution the grouping path below also carries: whitespace and empty/failed + // wrappers keep their existing raw policy. + const annotatedExecText = normalizedExecText === undefined && codeModeExecName !== undefined + ? annotateCodeModeHostFailure(text, execOptions) + : undefined; + const resultText = normalizedExecText ?? annotatedExecText ?? (text.trim() ? text : KIRO_EMPTY_TOOL_RESULT_MESSAGE); const images = extractKiroImages(tr.content); const toolUseId = normalizeToolId(tr.toolCallId); const call = priorCalls.get(toolUseId); @@ -768,7 +774,7 @@ export function buildKiroPayload( } // Keep real whitespace and failed wrappers, but no empty-success wrapper boilerplate. const rawGroupText = text.length > 0 && (!text.trim() || normalizedExecText !== EMPTY_EXEC_OUTPUT_MESSAGE) - ? text : undefined; + ? (annotatedExecText ?? text) : undefined; const last = turns.at(-1); if ( adjacentResult?.rawId === tr.toolCallId diff --git a/src/adapters/responses-code-mode.ts b/src/adapters/responses-code-mode.ts index ebbab97fd9..8e53481fa8 100644 --- a/src/adapters/responses-code-mode.ts +++ b/src/adapters/responses-code-mode.ts @@ -1,6 +1,6 @@ import { toolChoiceToolPredicate, type OcxParsedRequest, type OcxProviderConfig } from "../types"; import { isOpenAiOperatedResponsesDestination } from "../providers/openai-tiers"; -import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; +import { CODE_MODE_HOST_CONTRACT_SENTENCE, CODE_MODE_RESULT_ECHO_SENTENCE, annotateCodeModeHostFailure, normalizeEmptyExecToolResultText } from "./exec-tool-result-normalize"; import { isBareShellBridgeTool, isCodexCodeModeExecTool } from "./tool-catalog-nudge"; function record(value: unknown): value is Record { @@ -59,7 +59,10 @@ export function normalizeResponsesCodeMode(body: unknown, parsed: OcxParsedReque } if ((item.type !== "function_call_output" && item.type !== "custom_tool_call_output") || !execCalls.has(item.call_id)) return item; const text = textOnlyOutput(item.output); - const normalized = text === undefined ? undefined : normalizeEmptyExecToolResultText(text, { toolName: "exec" }); + const normalized = text === undefined + ? undefined + : normalizeEmptyExecToolResultText(text, { toolName: "exec" }) + ?? annotateCodeModeHostFailure(text, { toolName: "exec" }); return normalized === undefined ? item : { ...item, output: normalized }; }) } : {}), }; diff --git a/tests/adapters/exec-tool-result-normalize.test.ts b/tests/adapters/exec-tool-result-normalize.test.ts new file mode 100644 index 0000000000..a685ba6463 --- /dev/null +++ b/tests/adapters/exec-tool-result-normalize.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, test } from "bun:test"; +import { + CODE_MODE_HOST_CONTRACT_SENTENCE, + CODE_MODE_HOST_FAILURE_GUIDANCE, + annotateCodeModeHostFailure, +} from "../../src/adapters/exec-tool-result-normalize"; + +// Live host strings (Codex 0.153.2, probed 2026-09-07) and the rule each one names. The pre-call +// sentence and these rows are one contract in one module; a model must never be told one thing +// before the call and another after. +describe("code-mode host failure annotation", () => { + test.each(CODE_MODE_HOST_FAILURE_GUIDANCE.map(row => [row.marker, row.guidance] as const))( + "annotates an exec result carrying %p regardless of case", + (marker, guidance) => { + const text = `Script failed\nWall time 0.1 seconds\nOutput:\nError: ${marker.toUpperCase()}`; + expect(annotateCodeModeHostFailure(text, { toolName: "exec" })).toBe(`${text}\n[recovery: ${guidance}]`); + }, + ); + + test("matches the host's real capitalisation and argument text", () => { + expect(annotateCodeModeHostFailure("Unsupported import in exec: node:fs", { toolName: "exec" })).toContain("injected globals"); + expect(annotateCodeModeHostFailure("Script error:\ntool `apply_patch` expects a string input", { toolName: "exec" })).toContain("exactly one string"); + expect(annotateCodeModeHostFailure( + "apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'", + { toolName: "exec" }, + )).toContain("bare marker line `*** Begin Patch`"); + }); + + test("leaves non-exec tools, shell bridges, foreign namespaces, non-matching text and already-annotated text alone", () => { + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "read_file" })).toBeUndefined(); + // Flat shell bridges never run the isolate, so the four strings cannot be theirs. + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec_command" })).toBeUndefined(); + // A foreign MCP server's own exec is not Codex's, even when its output quotes the phrase, and a + // namespace that merely CONTAINS the provider name is still foreign. + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec", toolNamespace: "mcp__docker" })).toBeUndefined(); + expect(annotateCodeModeHostFailure("expects a string input", { toolName: "exec", toolNamespace: "mcp__foreign-opencodex-responses" })).toBeUndefined(); + // Codex's own display namespaces and flattened aliases for the same code-mode tool still count. + for (const options of [ + { toolName: "exec", toolNamespace: "opencodex-responses" }, + { toolName: "exec", toolNamespace: "mcp__opencodex-responses" }, + { toolName: "mcp__opencodex-responses__exec" }, + { toolName: "mcp_opencodex-responses_exec" }, + ]) { + expect(annotateCodeModeHostFailure("expects a string input", options)).toContain("[recovery:"); + } + expect(annotateCodeModeHostFailure("all good", { toolName: "exec" })).toBeUndefined(); + const once = annotateCodeModeHostFailure("expects a string input", { toolName: "exec" }); + if (!once) throw new Error("expected one annotation"); + expect(annotateCodeModeHostFailure(once, { toolName: "exec" })).toBeUndefined(); + }); + + test("every failure row is a rule the pre-call sentence already states", () => { + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("takes exactly one string"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("`*** Begin Patch`"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("`*** End Patch`"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("no `import`"); + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).toContain("write_stdin"); + // Never shows the decorated marker as a copyable literal (same rule as the nudge tests). + expect(CODE_MODE_HOST_CONTRACT_SENTENCE).not.toContain("*** Begin Patch ***"); + }); +}); + diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index cb554012ea..fe613ac71f 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -458,6 +458,7 @@ "errors-adapter-failure.test.ts": "server", "eventstream-decoder.test.ts": "responses", "exa-web-search.test.ts": "providers", + "exec-tool-result-normalize.test.ts": "adapters", "expand-user-path.test.ts": "config", "fast-row-ingress.test.ts": "providers", "fast-row-listing.test.ts": "codex-integration", diff --git a/tests/providers/cursor/cursor-toolresult-normalize.test.ts b/tests/providers/cursor/cursor-toolresult-normalize.test.ts index c62ad8e27b..610e5e578e 100644 --- a/tests/providers/cursor/cursor-toolresult-normalize.test.ts +++ b/tests/providers/cursor/cursor-toolresult-normalize.test.ts @@ -106,6 +106,34 @@ describe("normalizeCursorToolResultText (#1920/#1866 unit rows)", () => { expect(out.text).toContain(hint); }); + test.each(["Unsupported import in exec: node:fs", "unsupported import in exec: node:fs"])( + "a code-mode exec result carrying %p gains the shared hint, keeps its isError, and is not re-annotated on replay", + (payload) => { + const out = normalizeCursorToolResultText(payload, { toolName: "exec" }); + expect(out.changed).toBe(true); + expect(out.isError).toBe(false); + expect(out.text).toBe(`${payload}\n[recovery: Imports are not available in this exec context; use the injected globals (tools, text, notify, store, load, ALL_TOOLS) instead.]`); + // Replay through Responses history arrives with isError=false; the legacy lowercase marker + // row must not get a second look at it. + const replay = normalizeCursorToolResultText(out.text, { toolName: "exec", isError: false }); + expect(replay).toEqual({ text: out.text, isError: false, changed: false }); + }, + ); + + test("the legacy node_repl import row keeps its own isError policy", () => { + const out = normalizeCursorToolResultText("unsupported import in exec", { toolName: "js", toolNamespace: "mcp__node_repl" }); + expect(out.isError).toBe(true); + expect(out.text).toContain("injected globals"); + }); + + test("a non-exec tool whose successful output merely mentions a host phrase stays byte-identical", () => { + const doc = "The docs say apply_patch expects a string input."; + const out = normalizeCursorToolResultText(doc, { toolName: "read_file" }); + expect(out.changed).toBe(false); + expect(out.isError).toBe(false); + expect(out.text).toBe(doc); + }); + test("a non-computer-use tool with empty output stays byte-identical", () => { const out = normalizeCursorToolResultText("", { toolName: "read_file" }); expect(out.changed).toBe(false); diff --git a/tests/providers/kiro/kiro-adapter.test.ts b/tests/providers/kiro/kiro-adapter.test.ts index fbdeec50b2..947d6ad740 100644 --- a/tests/providers/kiro/kiro-adapter.test.ts +++ b/tests/providers/kiro/kiro-adapter.test.ts @@ -339,6 +339,68 @@ describe("kiro adapter — buildRequest", () => { } }); + test("a code-mode exec result carrying a host failure string names the broken rule", async () => { + // freeform: the Kiro seam annotates only when the emitted catalog is genuinely code mode. + const execTool = { name: "exec", description: "Run JavaScript", freeform: true, parameters: { type: "object" } }; + const failure = "apply_patch verification failed: invalid patch: The first line of the patch must be '*** Begin Patch'"; + const messages = [ + { role: "user", content: "run it" }, + { role: "assistant", content: [{ type: "toolCall", id: "call-x", name: "exec", arguments: {} }] }, + { role: "toolResult", toolCallId: "call-x", toolName: "exec", content: failure, isError: false }, + ]; + const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages, [execTool])); + const resultText = JSON.parse(body).conversationState.currentMessage.userInputMessage + .userInputMessageContext.toolResults[0].content[0].text; + expect(resultText).toBe(`${failure}\n[recovery: The patch text must open with the bare marker line \`*** Begin Patch\`: no code fence, prose, or extra asterisks on that line (blank lines or indentation before it are tolerated).]`); + }); + + test("a host failure string on a non-code-mode catalog stays raw", async () => { + const failure = "tool `apply_patch` expects a string input"; + const messages = [ + { role: "user", content: "run it" }, + { role: "assistant", content: [{ type: "toolCall", id: "call-x", name: "exec", arguments: {} }] }, + { role: "toolResult", toolCallId: "call-x", toolName: "exec", content: failure, isError: false }, + ]; + for (const tools of [ + // A structured tool that merely shares the name exec. + [{ name: "exec", description: "Run a shell string", parameters: { type: "object" } }], + // Freeform exec beside a bare shell bridge is the flat-catalog shape, not code mode. + [ + { name: "exec", description: "Run JavaScript", freeform: true, parameters: { type: "object" } }, + { name: "exec_command", description: "Run", parameters: { type: "object" } }, + ], + ]) { + const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages, tools)); + const resultText = JSON.parse(body).conversationState.currentMessage.userInputMessage + .userInputMessageContext.toolResults[0].content[0].text; + expect(resultText).toBe(failure); + } + }); + + test("a host failure chunk in a coalesced group carries its recovery line beside raw siblings", async () => { + // Whitespace and a failed-empty wrapper keep their raw grouping policy; only the chunk that + // carries a host failure string is substituted (the exact combination review round 1 named). + const execTool = { name: "exec", description: "Run JavaScript", freeform: true, parameters: { type: "object" } }; + const failedExecWrapper = "Script failed\nWall time 0.1 seconds\nOutput:\n"; + const hostFailure = "tool `apply_patch` expects a string input"; + const result = (content: string) => ({ role: "toolResult", toolCallId: "call-g", toolName: "exec", content, isError: false }); + const messages = [ + { role: "user", content: "run it" }, + { role: "assistant", content: [{ type: "toolCall", id: "call-g", name: "exec", arguments: {} }] }, + result(" "), result(hostFailure), result(failedExecWrapper), + ]; + const { body } = await createKiroAdapter(provider).buildRequest(parsedWith(messages, [execTool])); + const toolResults = JSON.parse(body).conversationState.currentMessage.userInputMessage + .userInputMessageContext.toolResults as Array<{ content: Array<{ text: string }>; status: string }>; + expect(toolResults).toHaveLength(1); + expect(toolResults[0].status).toBe("success"); + expect(toolResults[0].content).toEqual([ + { text: " " }, + { text: `${hostFailure}\n[recovery: tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.]` }, + { text: failedExecWrapper }, + ]); + }); + test("real exec output and empty non-exec results are left alone", async () => { // Review finding (Codex P2): a failed cell with no output is empty but NOT a success. The // success guidance would erase the only failure signal — reachable via Responses history, diff --git a/tests/responses/openai-responses-passthrough.test.ts b/tests/responses/openai-responses-passthrough.test.ts index 25ee2af5ac..df2d064cab 100644 --- a/tests/responses/openai-responses-passthrough.test.ts +++ b/tests/responses/openai-responses-passthrough.test.ts @@ -103,6 +103,21 @@ describe("native routed code-mode result visibility", () => { expect(second.instructions).toBe(first.instructions); }); + test("annotates a paired exec result that carries a host failure string without touching the program", () => { + const failure = "Script failed\nWall time 0.1 seconds\nOutput:\nScript error:\ntool `apply_patch` expects a string input"; + const body = raw(failure); + const wire = JSON.parse(createResponsesPassthroughAdapter(routed).buildRequest(parseRequest(body)).body); + expect(wire.input[1].output).toBe(`${failure}\n[recovery: tools.apply_patch takes exactly one string argument; pass the patch text itself, not an object such as {input: ...}.]`); + expect(JSON.parse(wire.input[0].arguments).input).toBe(body.input[0].input); + // Replayed history already carrying the hint is not annotated twice: the output item and the + // program keep their identity, and a second pass over the normalized body is a deep no-op. + const replayed = raw(wire.input[1].output); + const once = normalizeResponsesCodeMode(replayed, parseRequest(replayed), routed) as typeof replayed; + expect(once.input[1]).toBe(replayed.input[1]); + expect(once.input[0]).toBe(replayed.input[0]); + expect(normalizeResponsesCodeMode(once, parseRequest(once), routed)).toEqual(once); + }); + test("a replayed body that already carries the echo rule gains only the missing contract sentence", () => { const body = { ...raw(), instructions: `Keep this instruction.\n\n${CODE_MODE_RESULT_ECHO_SENTENCE}` }; const parsed = parseRequest(body); From 6bdcba5bff4196debf3cd159c7af3d34e35a24e0 Mon Sep 17 00:00:00 2001 From: JUN <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 15:27:23 +0900 Subject: [PATCH 009/116] docs: record the routed code-mode host contract Document the pre-call nested-helper contract and post-hoc host-failure annotation in the transports SoT and the Codex integration guide. This change does not rewrite model JavaScript or patch payloads. --- .../content/docs/guides/codex-integration.md | 7 +++++ structure/04_transports-and-sidecars.md | 28 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 64466b61a4..7d66e72c3f 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -330,6 +330,13 @@ Codex. Native custom calls and converted function calls use the same completion patch previews are held while their executable form is unresolved. JavaScript that merely contains patch text and unrelated native custom payloads stay unchanged. +Routed code-mode turns are also told the host's rules for the nested helpers before the first +call: `tools.apply_patch` takes one string that opens and closes with the bare patch marker lines, +the isolate has no `import`, and long-running commands are polled through `write_stdin`. When a +code-mode exec result on the native routed Responses, Kiro, or Cursor path still carries one of the host's +failure messages, opencodex appends a one-line hint naming the rule. This change does not rewrite +the model's code or its patch text. + Ordinary routed Responses function calls also use the original declared parameter schema at completion: integral floats in integer fields and integral numbers in string-only fields are normalized, while fractions and numeric unions stay unchanged. An explicitly empty completed diff --git a/structure/04_transports-and-sidecars.md b/structure/04_transports-and-sidecars.md index d27022c2ad..c568bb0151 100644 --- a/structure/04_transports-and-sidecars.md +++ b/structure/04_transports-and-sidecars.md @@ -330,6 +330,34 @@ whole result is examined; populated text, image/file parts, unpaired results, sh compaction and OpenAI-operated destinations are untouched. This does not rewrite valid JavaScript or reconstruct output that the code-mode host never emitted. +Routed code-mode turns also carry the host contract for the nested helpers, stated in the same three +injection sites as the result-emission rule (shared catalog nudge, Cursor code-mode guidance, native +routed Responses instructions): `tools.apply_patch` takes one string that opens and closes with the +bare patch marker lines (blank lines or indentation around them are tolerated; a decorated or missing +marker is rejected), the isolate has no `import`/`require`, and a command that outlives +`yield_time_ms` is polled through `write_stdin` with empty `chars` rather than a shell sleep loop. +When a code-mode exec result still carries one of the host's failure strings ("expects a string +input", "The first line of the patch must be", "The last line of the patch must be", "Unsupported +import in exec"), the native routed Responses, Kiro, and Cursor result paths append a one-line +recovery hint naming the broken rule; flat shell bridges and foreign MCP namespaces are never +annotated, Responses and Kiro additionally require the request's verified code-mode catalog, Cursor +matches the exact `exec` name under its `opencodex-responses` provider without catalog context, and +Cursor's error classification and Kiro's whitespace and failed-wrapper grouping are unchanged. Both +halves live in `src/adapters/exec-tool-result-normalize.ts` +so the pre-call and post-hoc wording cannot drift. This guidance and annotation change rewrites +neither the model's JavaScript nor its patch payload; the existing name-alias delimiter +normalization in `src/responses/code-mode-helper-compat.ts` is unchanged, and the host still rejects a +malformed call exactly as before. Anthropic, Google, OpenAI-chat and command-code result paths +have no exec-result seam today and are not annotated. + +[Decision Log] +- 목적과 의도: Stop routed models from abandoning `apply_patch` after the Codex host rejects an object argument or a decorated marker, and from blocking a turn in a shell sleep loop when the host offers `session_id` polling. +- 기존 구현 및 제약 조건: The shared nudge, Cursor guidance and native Responses instructions already carry the result-emission rule from `exec-tool-result-normalize.ts`, but none stated the helper's argument type, the marker rule, the import ban, or the polling protocol; `260905_apply_patch_envelope_gap` refused to rewrite JavaScript bodies (MODE B), so payload repair is off the table. +- 검토한 주요 대안: Repair the argument shape inside the proxy (rejected: same body ambiguity as MODE B and it turns a rejected write into a performed one); Cursor-only guidance (rejected: the incident was native routed Responses on xAI); annotate every adapter's tool results (rejected: Anthropic/Google/OpenAI-chat/command-code have no exec-result seam and would need a new one). +- 선택한 방식: One pre-call sentence and one marker→recovery table in the module that already owns the echo pair; inject the sentence at the three existing code-mode sites; annotate at the three existing exec-result seams with an exec-gated, idempotent helper that never changes error status. +- 다른 대안 대신 이 방식을 선택한 이유: The safe repair for a host contract the model broke is to state it before the call and name it after the failure; keeping both halves in one file is what keeps them consistent. +- 장점, 단점 및 영향: Code-mode system prompts grow by roughly 600 characters on routed turns; OpenAI destinations, flat catalogs and compaction requests are untouched. An exec result that legitimately prints one of the four phrases gains a recovery line, which is additive text and never an error flip. On Cursor, a structured tool literally named `exec` whose output quotes one of those phrases would also gain that line. The effect on the live Grok defect rate is unmeasured until a re-probe. + [Decision Log] - 목적과 의도: Keep Codex hosted web search usable on xAI's public Responses endpoint without forwarding private OpenAI-only fields that xAI rejects. - 기존 구현 및 제약 조건: Codex emits `external_web_access`, `search_context_size`, `search_content_types`, and `user_location`; xAI documents a live-only `web_search` tool with domain filters and image flags, while Codex cached mode explicitly forbids external access. From f1604c6b26bdb4326ae512f69fb46eb398c977b3 Mon Sep 17 00:00:00 2001 From: Ingwannu Date: Fri, 4 Sep 2026 21:20:40 +0000 Subject: [PATCH 010/116] docs(devlog): make CI completion check fail closed [skip ci] (cherry picked from commit e5bbd79ef70faeb258a8c13a4fc30c3d8bd1d588) Co-authored-by: Ingwannu <186453546+Ingwannu@users.noreply.github.com> --- .../090_outcome.md | 2 +- .../091_post_merge_audit.md | 31 ++++++++++++++++--- 2 files changed, 28 insertions(+), 5 deletions(-) diff --git a/devlog/_fin/260905_always_on_429_failover/090_outcome.md b/devlog/_fin/260905_always_on_429_failover/090_outcome.md index 3de38c8936..07e4399881 100644 --- a/devlog/_fin/260905_always_on_429_failover/090_outcome.md +++ b/devlog/_fin/260905_always_on_429_failover/090_outcome.md @@ -18,7 +18,7 @@ the tree rather than against the plan — the plan's own criteria were satisfied Two were defects the fix itself created (#3499, #3503), three were surfaces still describing the old contract (#3517, #3520, #3523), one closed the structural gap that let this unit ship two subset-rotator loops (#3512), and one cleaned up after a collision with concurrent maintainer -work (#3526). All are recorded in `091`. +work (#3526). The runtime post-merge findings and CI lessons are recorded in `091`. ## What changed diff --git a/devlog/_fin/260905_always_on_429_failover/091_post_merge_audit.md b/devlog/_fin/260905_always_on_429_failover/091_post_merge_audit.md index 490040325d..297213b2a3 100644 --- a/devlog/_fin/260905_always_on_429_failover/091_post_merge_audit.md +++ b/devlog/_fin/260905_always_on_429_failover/091_post_merge_audit.md @@ -67,14 +67,37 @@ The post-merge run on `dev` then showed `ci failure`, which was a genuinely alar out. It turned out to be cancellation by the maintainer's next merge two minutes later, not a real failure — every job read `cancelled`, not `failure`. -**Rule:** verify with the check-runs API and require zero `null` conclusions, not a pass count: +**Rule:** use the exact head SHA, require every expected aggregate or policy gate by name, and +also require zero non-terminal check runs. A missing check is not success. Paginate before treating +the returned set as complete: ```bash -gh api repos///commits//check-runs \ - --jq '[.check_runs[] | .conclusion] | group_by(.) | map({(.[0]//"null"): length}) | add' +set -o pipefail +gh api --paginate repos///commits//check-runs \ + | jq -se ' + [.[].check_runs[]] as $runs + | ["ci", "enforce-target", "hygiene", "react-doctor"] as $expected + | ($expected - [ + $runs[] + | select(.status == "completed" and .conclusion == "success") + | .name + ]) as $missing + | [ + $runs[] + | select(.status != "completed" or .conclusion == null) + | .name + ] as $pending + | if ($missing | length) == 0 and ($pending | length) == 0 + then {ready: true, expected: $expected} + else error("missing=\($missing) pending=\($pending)") + end' ``` -A clean result looks like `{"skipped":3,"success":24}` — no `null` key at all. +A clean result is `{"ready":true,...}` with exit status 0. This does not replace review-policy +checks such as confirming the approval belongs to the same head. Every `$expected` value is an +exact Checks API `.check_runs[].name`, not a workflow title or workflow-run name. If those required +check-run names change, update this list with the policy; silently accepting an absent name +recreates the original bug. The near-miss paid for itself: sweeping `dev` afterwards found a real defect. #3511 and #3513 landed concurrently, one moving `anthropic-quorum-cache.test.ts` into `tests/routing/` and the From 3e4a01c66bba66cf355c4e8562a349cc16a2fffc Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Mon, 7 Sep 2026 10:23:03 +0900 Subject: [PATCH 011/116] fix(kiro): gate request diagnostics behind the debug check [skip ci] `debugProviderDiagnostic` already returns early when provider debug is off, but its argument object is built by the caller first. The Kiro request path therefore ran `new TextEncoder().encode(body).length` over the entire serialized request body on every request, including when diagnostics were disabled, and then discarded the result inside the callee. Wrap the diagnostic call in `isDebugEnabled()` so the details are only constructed when they can actually be emitted. `src/adapters/openai-chat.ts` already guards its diagnostics the same way. The regression asserts that building a request performs no `TextEncoder` encode over the serialized payload while diagnostics are off; it fails without the guard and passes with it. (cherry picked from commit d5d711a7b9897bb8eee8364a5d8765b55206bf6f) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/adapters/kiro.ts | 27 ++++++++++++++---------- tests/providers/kiro/kiro-stream.test.ts | 15 +++++++++++++ 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/src/adapters/kiro.ts b/src/adapters/kiro.ts index 56ee632343..4039142a8b 100644 --- a/src/adapters/kiro.ts +++ b/src/adapters/kiro.ts @@ -1,6 +1,7 @@ import { decodeEventStream } from "../lib/eventstream-decoder"; import { estimateTokens } from "../lib/token-estimate"; import { debugProviderDiagnostic } from "../lib/debug"; +import { isDebugEnabled } from "../lib/debug-settings"; import { resolveKiroApiRegion, resolveKiroRequestProfile } from "../oauth/kiro"; import { KIRO_MODEL_CONTEXT_WINDOWS, normalizeKiroModelId } from "../providers/kiro-models"; import { modelRecordValue } from "../reasoning-effort"; @@ -2120,17 +2121,21 @@ export function createKiroAdapter(provider: OcxProviderConfig): ProviderAdapter const rawContextInputEstimate = estimateKiroPayloadInputTokens(built.payload, parsed.modelId); const contextInputEstimate = calibrateKiroEstimate(built.conversationId, rawContextInputEstimate); const body = JSON.stringify(built.payload); - debugProviderDiagnostic("kiro", "request", { - region, - requestedModel: parsed.modelId, - completionMode: built.completionMode, - bodyBytes: new TextEncoder().encode(body).length, - messageCount: kiroPayloadMessages(parsed).length, - toolCount: parsed.context.tools?.length ?? 0, - hasProfileArn: Boolean(profileArn), - wireClient, - hasPreviousResponseId: Boolean(parsed.previousResponseId), - }); + // Every field below is evaluated before the call, so an unguarded call re-encodes the + // whole request body on each request even when provider debug is off. Gate the details. + if (isDebugEnabled()) { + debugProviderDiagnostic("kiro", "request", { + region, + requestedModel: parsed.modelId, + completionMode: built.completionMode, + bodyBytes: new TextEncoder().encode(body).length, + messageCount: kiroPayloadMessages(parsed).length, + toolCount: parsed.context.tools?.length ?? 0, + hasProfileArn: Boolean(profileArn), + wireClient, + hasPreviousResponseId: Boolean(parsed.previousResponseId), + }); + } return { request: { url: kiroRuntimeEndpoint(provider, region), diff --git a/tests/providers/kiro/kiro-stream.test.ts b/tests/providers/kiro/kiro-stream.test.ts index b85c698ae1..1a9b7a6e02 100644 --- a/tests/providers/kiro/kiro-stream.test.ts +++ b/tests/providers/kiro/kiro-stream.test.ts @@ -196,6 +196,21 @@ describe("kiro adapter — parseStream", () => { expect(providerState).toEqual({ kiro: { conversationId: "returned-conversation-1" } }); }); + test("request diagnostics do not re-encode the body when provider debug is off", async () => { + const encodeSpy = spyOn(TextEncoder.prototype, "encode"); + try { + const adapter = createKiroAdapter(provider); + const before = encodeSpy.mock.calls.length; + await adapter.buildRequest(parsedWith([{ role: "user", content: "hi" }])); + const during = encodeSpy.mock.calls.slice(before); + // The diagnostic argument list is evaluated eagerly, so an unguarded call encodes the + // full serialized request body on every request even with diagnostics disabled. + expect(during.some(([value]) => typeof value === "string" && value.includes("conversationState"))).toBe(false); + } finally { + encodeSpy.mockRestore(); + } + }); + test("invalid returned message metadata cannot poison continuation state", async () => { const adapter = createKiroAdapter(provider); const request = await adapter.buildRequest(parsedWith([{ role: "user", content: "hi" }])); From 98564bdbfe6feace448eaf21cfbf424650c0bbf6 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:17:49 +0900 Subject: [PATCH 012/116] fix(copilot): route Responses-only GPT, Grok and MAI models correctly [skip ci] Carries PR #3840 (head 9a214529d, 5 commits squashed onto current dev): gpt-6-astra, Grok and MAI models on GitHub Copilot default to the Responses wire instead of Chat Completions, which returned unsupported_api_for_model. Docs scope the per-wire model lists and the discovery fallback test covers legacy overrides. (carried from https://github.com/lidge-jun/opencodex/pull/3840) Co-authored-by: chilung-cgu <215337896+chilung-cgu@users.noreply.github.com> --- .../src/content/docs/fr/guides/providers.md | 4 +- .../fr/reference/configuration/providers.md | 2 +- .../src/content/docs/guides/providers.md | 4 +- .../src/content/docs/ja/guides/providers.md | 4 +- .../ja/reference/configuration/providers.md | 2 +- .../src/content/docs/ko/guides/providers.md | 4 +- .../ko/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 2 +- .../src/content/docs/ru/guides/providers.md | 6 +- .../ru/reference/configuration/providers.md | 2 +- .../src/content/docs/tr/guides/providers.md | 4 +- .../tr/reference/configuration/providers.md | 2 +- .../content/docs/zh-cn/guides/providers.md | 4 +- .../reference/configuration/providers.md | 2 +- .../content/docs/zh-tw/guides/providers.md | 4 +- src/providers/registry.ts | 5 ++ .../github-copilot-wire-defaults.test.ts | 76 +++++++++++++++---- 17 files changed, 90 insertions(+), 39 deletions(-) diff --git a/docs-site/src/content/docs/fr/guides/providers.md b/docs-site/src/content/docs/fr/guides/providers.md index 89b3a7c626..6ed7553957 100644 --- a/docs-site/src/content/docs/fr/guides/providers.md +++ b/docs-site/src/content/docs/fr/guides/providers.md @@ -543,8 +543,8 @@ flux d'appareil contre un jeton d'API Copilot de courte durée, et non contre un reste une passerelle à clé ou jeton d'abonnement sur son point de terminaison compatible OpenAI. **Cloudflare AI Gateway** exige que les identifiants de votre compte et de votre passerelle figurent dans l'URL. -Copilot présente un catalogue qui utilise plusieurs protocoles : sa famille GPT-5 (`gpt-5.3-codex`, `gpt-5.4`, -`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`) rejette +Copilot présente un catalogue qui utilise plusieurs protocoles : ces modèles (`gpt-5.3-codex`, `gpt-5.4`, +`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) rejettent `/chat/completions` pour le trafic d'agent. opencodex route donc ces modèles sur l'API Responses par défaut, tandis que tous les autres modèles Copilot restent sur Chat Completions. L'ordre de priorité est le suivant : verrouillage explicite du protocole → entrée [`modelAdapters`](/fr/reference/configuration/providers/) définie diff --git a/docs-site/src/content/docs/fr/reference/configuration/providers.md b/docs-site/src/content/docs/fr/reference/configuration/providers.md index 32b6a28023..96d00e5668 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/fr/reference/configuration/providers.md @@ -116,7 +116,7 @@ sauvegarde dont le contenu diffère, puis réécrit en identifiants sans préfix | `modelReasoningEfforts?` | `Record` | Libellés propres à chaque modèle. Une liste vide masque le contrôle de l'effort. Comme pour `reasoningEfforts`, chaque échelle configurée avec l'adaptateur `google` déclare la capacité `thinkingLevel` ; les requêtes directes et Vertex sans image utilisent le chemin Gemini à plat, tandis que Cloud Code Assist l'envoie dans son enveloppe de requête. | | `modelSupportsReasoningSummaries?` | `Record` | Définissez un modèle sur `false` pour arrêter la publicité des résumés et supprimer les champs de livraison du résumé. | | `modelReasoningSummaryDelivery?` | `Record` | Énumération de livraison des réponses par modèle ; réécrit un champ de livraison existant. | -| `modelAdapters?` | `Record` | Remplacement du protocole `openai-chat` ou `openai-responses` par modèle pour les passerelles multiprotocoles. Les entrées explicites priment sur les valeurs par défaut du registre. Le préréglage OpenCode Go sélectionne Responses pour `gpt-5.6-luna` tout en laissant les modèles apparentés sur leurs protocoles documentés ; DeepSeek peut sélectionner Responses natif pour `deepseek-v4-flash` ; GitHub Copilot déclare des valeurs par défaut limitées à Responses pour sa famille GPT-5 (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`), car ces modèles rejettent `/chat/completions` pour le trafic des agents. Les modèles sans valeur intégrée par défaut, comme `gpt-5.4-nano`, peuvent être activés ici. Les services en amont à protocole unique et le transfert canonique ChatGPT rejettent ces remplacements. | +| `modelAdapters?` | `Record` | Remplacement du protocole `openai-chat` ou `openai-responses` par modèle pour les passerelles multiprotocoles. Les entrées explicites priment sur les valeurs par défaut du registre. Le préréglage OpenCode Go sélectionne Responses pour `gpt-5.6-luna` tout en laissant les modèles apparentés sur leurs protocoles documentés ; DeepSeek peut sélectionner Responses natif pour `deepseek-v4-flash` ; GitHub Copilot déclare des valeurs par défaut limitées à Responses pour ces modèles (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`), car ces modèles rejettent `/chat/completions` pour le trafic des agents. Les modèles sans valeur intégrée par défaut, comme `gpt-5.4-nano`, peuvent être activés ici. Les services en amont à protocole unique et le transfert canonique ChatGPT rejettent ces remplacements. | | Activation Responses xAI (tableau de bord) | interrupteur | Pour `xai` uniquement, définit ou efface atomiquement les entrées `modelAdapters` de `grok-4.5` et `grok-4.6`. Une seule entrée apparaît comme un état mixte jusqu’à la prochaine écriture. Les autres remplacements et le comportement des tiers restent inchangés. | | `xaiResponsesXSearch?` | `boolean` | Désactivé par défaut. Sur une destination xAI Responses, ajoute la déclaration `x_search` hébergée par le fournisseur uniquement lorsqu’un outil `web_search` actif subsiste après la normalisation finale de la requête. Les déclarations existantes ne sont pas dupliquées, les sélecteurs `tool_choice`/`allowed_tools` de l’appelant ne sont jamais élargis, et cette option est distincte des options `search.xSearch` du service auxiliaire de recherche web. | | `modelPreferHostedTools?` | `Record` | Activation explicite par modèle exact pour les passerelles Responses hors transfert qui réservent un espace de noms aux outils hébergés. Seul `["image_generation"]` est actuellement accepté ; le modèle correspondant doit utiliser le protocole `openai-responses` et prendre en charge cet outil hébergé. Le proxy supprime les déclarations clientes `image_gen` en conflit et réécrit leurs sélecteurs afin de préserver le choix d'outil de l'appelant. Pour les modèles virtuels `-pro` de l'API OpenAI, l'identifiant public sélectionné est comparé en premier et l'identifiant résolu du modèle de base sur le protocole sert de repli. `modelAdapters` résout d'abord l'identifiant public, puis celui de base ; la seconde résolution détermine le protocole final. Les autres modèles conservent le comportement normal des alias. | diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index 5e46979816..8a9477a759 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -669,8 +669,8 @@ device-flow login for a short-lived Copilot API token — not a pasted API key. a key/subscription-token gateway on its OpenAI-compatible endpoint. **Cloudflare AI Gateway** needs your account + gateway ids filled into the URL. -Copilot fronts a mixed-wire catalog: its GPT-5 family (`gpt-5.3-codex`, `gpt-5.4`, -`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`) rejects +Copilot fronts a mixed-wire catalog: the following models (`gpt-5.3-codex`, `gpt-5.4`, +`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) reject `/chat/completions` for agent traffic, so opencodex routes those models over the Responses API by built-in default while every other Copilot model stays on chat completions. The precedence is: hard wire pin → your explicit diff --git a/docs-site/src/content/docs/ja/guides/providers.md b/docs-site/src/content/docs/ja/guides/providers.md index ae692e1e2c..db0bdb87b2 100644 --- a/docs-site/src/content/docs/ja/guides/providers.md +++ b/docs-site/src/content/docs/ja/guides/providers.md @@ -384,8 +384,8 @@ Amazon Bedrock ネイティブ API のような、これらの実装のいずれ **サブスクリプショントークン**(通常の API キーではない)で認証します。**Cloudflare AI Gateway** は URL にアカウント + ゲートウェイ ID を埋める必要があります。 -Copilot は混在 wire カタログを提供します。GPT-5 系モデル(`gpt-5.3-codex`、`gpt-5.4`、 -`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`)はエージェント +Copilot は混在 wire カタログを提供します。モデル(`gpt-5.3-codex`、`gpt-5.4`、 +`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)はエージェント 通信の `/chat/completions` を拒否するため、opencodex はこれらのモデルを組み込みデフォルトで Responses API 経由にルーティングし、他の Copilot モデルはすべて chat completions のままです。 優先順位は次のとおりです: ハード wire ピン → 明示的な diff --git a/docs-site/src/content/docs/ja/reference/configuration/providers.md b/docs-site/src/content/docs/ja/reference/configuration/providers.md index ddbb22d666..8938073e6c 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ja/reference/configuration/providers.md @@ -105,7 +105,7 @@ account を削除しても mapping は保持され、同じ id を再追加す | `modelReasoningEfforts?` | `Record` |モデルごとのラベル。空のリストは努力制御を非表示にします。 | | `modelSupportsReasoningSummaries?` | `Record` |モデルを `false` に設定して、概要の広告を停止し、概要配信フィールドを削除します。 | | `modelReasoningSummaryDelivery?` | `Record` |モデルごとの応答配信列挙型。既存の配信フィールドを書き換えます。 | -| `modelAdapters?` | `Record` | 混合配線ゲートウェイのモデルごとの `openai-chat` または `openai-responses` 配線オーバーライド。明示的なエントリはレジストリのデフォルトを破ります。DeepSeek のプリセットは `deepseek-v4-flash` のネイティブ Responses を選択でき、GitHub Copilot は GPT-5 ファミリー (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`) を Responses 専用デフォルトとして宣言します。これらのモデルはエージェント トラフィックで `/chat/completions` を拒否するためです。`gpt-5.4-nano` のようなビルトイン デフォルトのないモデルはここでオプトインできます。単線アップストリーム ピンと正規の ChatGPT 転送はオーバーライドを拒否します。 | +| `modelAdapters?` | `Record` | 混合配線ゲートウェイのモデルごとの `openai-chat` または `openai-responses` 配線オーバーライド。明示的なエントリはレジストリのデフォルトを破ります。DeepSeek のプリセットは `deepseek-v4-flash` のネイティブ Responses を選択でき、GitHub Copilot は モデル (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) を Responses 専用デフォルトとして宣言します。これらのモデルはエージェント トラフィックで `/chat/completions` を拒否するためです。`gpt-5.4-nano` のようなビルトイン デフォルトのないモデルはここでオプトインできます。単線アップストリーム ピンと正規の ChatGPT 転送はオーバーライドを拒否します。 | | xAI Responses オプトイン(ダッシュボード) | スイッチ | `xai` のみで、`grok-4.5` と `grok-4.6` の `modelAdapters` エントリを原子的に設定または削除します。片方だけの場合は、次のスイッチ操作で両方が正規化されるまで混合状態を表示します。他のオーバーライドと tier 動作は変わりません。 | | `xaiResponsesXSearch?` | `boolean` | デフォルトでは無効です。xAI Responses の宛先では、最終的なリクエスト正規化後もライブの `web_search` ツールが残っている場合にのみ、プロバイダーがホストする `x_search` 宣言を追加します。既存の宣言は重複させず、呼び出し元の `tool_choice` / `allowed_tools` セレクターの範囲を拡張することもありません。また、これは `search.xSearch` オプションを持つウェブ検索サイドカーとは別です。 | | `modelPreferHostedTools?` | `Record` | hosted tool namespace を予約する非 forward Responses gateway 向けの完全一致モデル opt-in。現在は `["image_generation"]` のみを受け付けます。一致したモデルは `openai-responses` wire を使い、その hosted tool をサポートする必要があります。競合するクライアント `image_gen` 宣言を除去し、呼び出し元の tool choice を維持するため selector も書き換えます。OpenAI API の仮想 `-pro` モデルでは、まず選択した公開 ID に一致させ、解決後のベース wire-model ID をフォールバックとして使用します。`modelAdapters` は公開 ID、次にベース ID の順に解決し、後者の結果が最終 wire を決めます。未設定のモデルは通常の alias 動作を維持します。 | diff --git a/docs-site/src/content/docs/ko/guides/providers.md b/docs-site/src/content/docs/ko/guides/providers.md index c49ede4ec6..268e6e0cf1 100644 --- a/docs-site/src/content/docs/ko/guides/providers.md +++ b/docs-site/src/content/docs/ko/guides/providers.md @@ -375,8 +375,8 @@ Amazon Bedrock 네이티브 API처럼 이 구현 중 어느 것과도 맞지 않 **구독 토큰**(일반 API 키가 아님)으로 인증합니다. **Cloudflare AI Gateway**는 URL에 계정 + 게이트웨이 id를 채워야 합니다. -Copilot은 혼합 wire 카탈로그를 제공합니다. GPT-5 계열 모델(`gpt-5.3-codex`, `gpt-5.4`, -`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`)은 에이전트 +Copilot은 혼합 wire 카탈로그를 제공합니다. 모델(`gpt-5.3-codex`, `gpt-5.4`, +`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)은 에이전트 트래픽에 대해 `/chat/completions`를 거부하므로 opencodex는 이 모델들을 내장 기본값으로 Responses API를 통해 라우팅하고, 다른 Copilot 모델은 모두 chat completions를 유지합니다. 우선순위는 하드 wire 핀 → 명시적 [`modelAdapters`](/ko/reference/configuration/providers/) diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md index 160d313be3..2dda27e7bf 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md @@ -105,7 +105,7 @@ managed map을 활성화하면 privacy-safe selector를 만들고, 이후 계정 | `modelReasoningEfforts?` | `Record` | 모델별 레이블입니다. 빈 목록이면 effort 제어를 숨깁니다. | | `modelSupportsReasoningSummaries?` | `Record` | 모델을 `false`로 두면 summary 광고를 멈추고 summary 전달 필드를 제거합니다. | | `modelReasoningSummaryDelivery?` | `Record` | 모델별 Responses 전달 enum입니다. 기존 delivery 필드를 다시 씁니다. | -| `modelAdapters?` | `Record` | 혼합 와이어 게이트웨이를 위한 모델별 `openai-chat` 또는 `openai-responses` 와이어 재정의입니다. 명시적 항목이 레지스트리 기본값보다 우선합니다. DeepSeek 프리셋은 `deepseek-v4-flash`에 네이티브 Responses를 선택할 수 있고, GitHub Copilot은 GPT-5 계열(`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`)을 Responses 전용 기본값으로 선언합니다. 이 모델들은 에이전트 트래픽에서 `/chat/completions`를 거부하기 때문입니다. `gpt-5.4-nano`처럼 기본값이 없는 모델은 여기서 직접 옵트인할 수 있습니다. 단일 와이어 상위 항목과 정식 ChatGPT forward는 재정의를 거부합니다. | +| `modelAdapters?` | `Record` | 혼합 와이어 게이트웨이를 위한 모델별 `openai-chat` 또는 `openai-responses` 와이어 재정의입니다. 명시적 항목이 레지스트리 기본값보다 우선합니다. DeepSeek 프리셋은 `deepseek-v4-flash`에 네이티브 Responses를 선택할 수 있고, GitHub Copilot은 모델(`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)을 Responses 전용 기본값으로 선언합니다. 이 모델들은 에이전트 트래픽에서 `/chat/completions`를 거부하기 때문입니다. `gpt-5.4-nano`처럼 기본값이 없는 모델은 여기서 직접 옵트인할 수 있습니다. 단일 와이어 상위 항목과 정식 ChatGPT forward는 재정의를 거부합니다. | | xAI Responses 옵트인(대시보드) | 스위치 | `xai`에서만 `grok-4.5`와 `grok-4.6`의 `modelAdapters` 항목을 원자적으로 설정하거나 지웁니다. 한 항목만 있으면 다음 스위치 쓰기가 둘을 정규화할 때까지 혼합 상태로 표시됩니다. 다른 재정의와 티어 동작은 바뀌지 않습니다. | | `xaiResponsesXSearch?` | `boolean` | 기본적으로 비활성화됩니다. xAI Responses 대상에서는 최종 요청 정규화 후에도 실제 `web_search` 도구가 남아 있을 때만 공급자가 호스팅하는 `x_search` 선언을 추가합니다. 기존 선언은 중복하지 않고, 호출자의 `tool_choice`/`allowed_tools` 선택기 범위를 확장하지 않으며, 웹 검색 사이드카의 `search.xSearch` 옵션과는 별개입니다. | | `modelPreferHostedTools?` | `Record` | hosted tool namespace를 예약하는 non-forward Responses gateway용 정확한 모델 ID opt-in입니다. 현재 `["image_generation"]`만 허용하며, 일치하는 모델은 `openai-responses` wire를 사용하고 해당 hosted tool을 지원해야 합니다. 충돌하는 클라이언트 `image_gen` 선언을 제거하고 호출자의 tool choice를 유지하도록 selector도 다시 씁니다. OpenAI API 가상 `-pro` 모델은 선택한 공개 ID를 먼저 일치시키고, 해석된 기본 wire-model ID를 대체값으로 사용합니다. `modelAdapters`는 공개 ID를 먼저, 그 다음 기본 ID를 해석하며, 두 번째 결과가 최종 wire를 결정합니다. 설정하지 않은 모델은 일반 alias 동작을 유지합니다. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 6aa8c78d00..b0792b7367 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -162,7 +162,7 @@ predictions. Explicit provider/model price overrides still take precedence. | `modelReasoningEfforts?` | `Record` | Per-model labels. An empty list hides effort control. As with `reasoningEfforts`, each configured `google`-adapter ladder asserts `thinkingLevel` capability; direct and Vertex non-image requests use the flat Gemini path, while Cloud Code Assist sends it under its request envelope. | | `modelSupportsReasoningSummaries?` | `Record` | Set a model to `false` to stop advertising summaries and strip summary-delivery fields. | | `modelReasoningSummaryDelivery?` | `Record` | Per-model Responses delivery enum; rewrites an existing delivery field. | -| `modelAdapters?` | `Record` | Per-model `openai-chat` or `openai-responses` wire override for mixed-wire gateways. Explicit entries beat registry defaults. The OpenCode Go preset selects Responses for `gpt-5.6-luna` while leaving sibling models on their documented wires; DeepSeek can select native Responses for `deepseek-v4-flash`; and GitHub Copilot declares Responses-only defaults for its GPT-5 family (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`) because those models reject `/chat/completions` for agent traffic. Models without a built-in default (for example `gpt-5.4-nano`) can be opted in here. Single-wire upstream pins and canonical ChatGPT forward reject overrides. | +| `modelAdapters?` | `Record` | Per-model `openai-chat` or `openai-responses` wire override for mixed-wire gateways. Explicit entries beat registry defaults. The OpenCode Go preset selects Responses for `gpt-5.6-luna` while leaving sibling models on their documented wires; DeepSeek can select native Responses for `deepseek-v4-flash`; and GitHub Copilot declares Responses-only defaults for the following models (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) because those models reject `/chat/completions` for agent traffic. Models without a built-in default (for example `gpt-5.4-nano`) can be opted in here. Single-wire upstream pins and canonical ChatGPT forward reject overrides. | | xAI Chat Completions (dashboard / CLI) | switch | Grok 4.5/4.6 OAuth Responses requests default to Responses. Existing Chat overrides are migrated once on upgrade; later Chat choices are preserved. Turn on to select Chat for both models, off to select Responses. CLI: `ocx provider edit xai --xai-chat on` or `--xai-chat off` (running proxy required). Mixed means only one model currently uses Chat. Other overrides and tier policy stay unchanged. API-key and translated Chat/Anthropic defaults are unchanged. | | `xaiResponsesXSearch?` | `boolean` | Disabled by default. On an xAI Responses destination, append the provider-hosted `x_search` declaration only when a live `web_search` tool survives final request normalization. Existing declarations are not duplicated, caller `tool_choice`/`allowed_tools` selectors are never widened, and this is separate from the web-search sidecar's `search.xSearch` options. | | `modelPreferHostedTools?` | `Record` | Exact-model opt-in for non-forward Responses gateways that reserve a hosted-tool namespace. Currently accepts only `["image_generation"]`; a matching model must use the `openai-responses` wire and support that hosted tool. It removes colliding client `image_gen` declarations and rewrites their selectors to preserve caller tool choice. For OpenAI API virtual `-pro` models, the selected public ID is matched first and the resolved base wire-model ID is a fallback. `modelAdapters` resolves the public ID first, then the base ID; the second resolution determines the final wire. Other models retain normal alias behavior. | diff --git a/docs-site/src/content/docs/ru/guides/providers.md b/docs-site/src/content/docs/ru/guides/providers.md index e680f1bd91..80f00c0d63 100644 --- a/docs-site/src/content/docs/ru/guides/providers.md +++ b/docs-site/src/content/docs/ru/guides/providers.md @@ -416,9 +416,9 @@ Assist), `azure` / `azure-openai`, `kiro` и `cursor`. Проприетарны **GitLab Duo** остаётся шлюзом с ключом/токеном подписки на своей OpenAI-совместимой конечной точке. **Cloudflare AI Gateway** требует подставить в URL id аккаунта и шлюза. -Copilot предоставляет каталог со смешанными проводами: его семейство GPT-5 (`gpt-5.3-codex`, -`gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`) -отклоняет `/chat/completions` для агентного трафика, поэтому opencodex по умолчанию +Copilot предоставляет каталог со смешанными проводами: модели (`gpt-5.3-codex`, +`gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) +отклоняют `/chat/completions` для агентного трафика, поэтому opencodex по умолчанию маршрутизирует эти модели через Responses API, а все остальные модели Copilot остаются на chat completions. Приоритет: жёсткий wire-пин → явная запись [`modelAdapters`](/ru/reference/configuration/providers/) → дефолт реестра → adapter всего diff --git a/docs-site/src/content/docs/ru/reference/configuration/providers.md b/docs-site/src/content/docs/ru/reference/configuration/providers.md index 7279179991..14a8b0a3ce 100644 --- a/docs-site/src/content/docs/ru/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ru/reference/configuration/providers.md @@ -118,7 +118,7 @@ cross-route credential fallback не существует. Строки API GPT- | `modelReasoningEfforts?` | `Record` | Label'ы по отдельным моделям. Пустой список скрывает управление effort. | | `modelSupportsReasoningSummaries?` | `Record` | Установите `false` для модели, чтобы перестать рекламировать summary и вырезать поля доставки summary. | | `modelReasoningSummaryDelivery?` | `Record` | Responses delivery enum по моделям; переписывает уже существующее поле delivery. | -| `modelAdapters?` | `Record` | Wire-override по модели для `openai-chat` или `openai-responses` в gateway с несколькими wire-форматами. Явные записи имеют приоритет над default'ами registry; preset DeepSeek может выбирать native Responses для `deepseek-v4-flash`, а GitHub Copilot объявляет Responses-only default'ы для семейства GPT-5 (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`), потому что эти модели отклоняют `/chat/completions` для агентного трафика. Модели без встроенного default'а (например, `gpt-5.4-nano`) можно включить здесь. Single-wire upstream pin'ы и canonical ChatGPT forward override не принимают. | +| `modelAdapters?` | `Record` | Wire-override по модели для `openai-chat` или `openai-responses` в gateway с несколькими wire-форматами. Явные записи имеют приоритет над default'ами registry; preset DeepSeek может выбирать native Responses для `deepseek-v4-flash`, а GitHub Copilot объявляет Responses-only default'ы для моделей (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`), потому что эти модели отклоняют `/chat/completions` для агентного трафика. Модели без встроенного default'а (например, `gpt-5.4-nano`) можно включить здесь. Single-wire upstream pin'ы и canonical ChatGPT forward override не принимают. | | Opt-in xAI Responses (панель) | переключатель | Только для `xai`: атомарно задаёт или удаляет записи `modelAdapters` для `grok-4.5` и `grok-4.6`. Одна запись отображается как смешанное состояние до следующего переключения. Остальные override и поведение tier не меняются. | | `xaiResponsesXSearch?` | `boolean` | По умолчанию отключено. Для назначения xAI Responses декларация `x_search`, размещённая у провайдера, добавляется только тогда, когда действующий инструмент `web_search` сохраняется после окончательной нормализации запроса. Существующие декларации не дублируются, селекторы вызывающей стороны `tool_choice`/`allowed_tools` никогда не расширяются, и эта настройка не связана с параметрами `search.xSearch` сайдкара веб-поиска. | | `modelPreferHostedTools?` | `Record` | Opt-in для точного model ID в non-forward Responses gateway, который резервирует namespace hosted tool. Сейчас допускается только `["image_generation"]`; совпавшая модель должна использовать wire `openai-responses` и поддерживать этот hosted tool. Прокси удаляет конфликтующие клиентские объявления `image_gen` и переписывает их selectors, сохраняя caller tool choice. Для виртуальных моделей OpenAI API `-pro` сначала сопоставляется выбранный публичный ID, а затем в качестве fallback используется ID базовой wire-модели. `modelAdapters` сначала разрешается по публичному ID, затем по базовому ID; второй результат определяет итоговый wire. Остальные модели сохраняют обычное alias-поведение. | diff --git a/docs-site/src/content/docs/tr/guides/providers.md b/docs-site/src/content/docs/tr/guides/providers.md index 6ff4f1c038..5943758e5a 100644 --- a/docs-site/src/content/docs/tr/guides/providers.md +++ b/docs-site/src/content/docs/tr/guides/providers.md @@ -589,8 +589,8 @@ login github-copilot`). **GitLab Duo**, OpenAI uyumlu uç noktasında bir anahtar/abonelik belirteci ağ geçidi olarak kalır. **Cloudflare AI Gateway**, URL'ye doldurulan hesap + ağ geçidi kimliklerinize ihtiyaç duyar. -Copilot karma hatlı bir katalog sunar: GPT-5 ailesi (`gpt-5.3-codex`, `gpt-5.4`, -`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`) ajan +Copilot karma hatlı bir katalog sunar: modeller (`gpt-5.3-codex`, `gpt-5.4`, +`gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) ajan trafiği için `/chat/completions`'ı reddeder, bu nedenle opencodex yerleşik varsayılan olarak bu modelleri Responses API üzerinden yönlendirirken diğer tüm Copilot modelleri sohbet tamamlamalarında kalır. Öncelik sırası: sabit hat diff --git a/docs-site/src/content/docs/tr/reference/configuration/providers.md b/docs-site/src/content/docs/tr/reference/configuration/providers.md index 91cb923fc3..3e01051010 100644 --- a/docs-site/src/content/docs/tr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/tr/reference/configuration/providers.md @@ -123,7 +123,7 @@ alanlı seçilmiş kimlikleri yalın kimliklere yeniden yazar. | `modelReasoningEfforts?` | `Record` | Model başına etiketler. Boş bir liste çaba denetimini gizler. `reasoningEfforts`'ta olduğu gibi, yapılandırılmış her `google` adaptör merdiveni `thinkingLevel` yeteneğini iddia eder; doğrudan ve Vertex görsel olmayan istekleri düz Gemini yolunu kullanırken, Cloud Code Assist bunu istek zarfı altında gönderir. | | `modelSupportsReasoningSummaries?` | `Record` | Özetlerin bildirilmesini durdurmak ve özet teslim alanlarını kaldırmak için bir modeli `false` olarak ayarlayın. | | `modelReasoningSummaryDelivery?` | `Record` | Model başına Responses teslim enum'ı; mevcut bir teslim alanını yeniden yazar. | -| `modelAdapters?` | `Record` | Karışık hatlı ağ geçitleri için model başına `openai-chat` veya `openai-responses` hat geçersiz kılma. Açık girdiler kayıt defteri varsayılanlarını yener. OpenCode Go önayarı, kardeş modelleri belgelenmiş hatlarında bırakırken `gpt-5.6-luna` için Responses'ı seçer; DeepSeek, `deepseek-v4-flash` için yerel Responses seçebilir; ve GitHub Copilot, GPT-5 ailesi (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`) için yalnızca Responses varsayılanlarını bildirir çünkü bu modeller ajan trafiği için `/chat/completions`'ı reddeder. Yerleşik varsayılanı olmayan modeller (örneğin `gpt-5.4-nano`) burada dahil edilebilir. Tek hatlı yukarı akış pinleri ve kurallı ChatGPT iletme geçersiz kılmaları reddeder. | +| `modelAdapters?` | `Record` | Karışık hatlı ağ geçitleri için model başına `openai-chat` veya `openai-responses` hat geçersiz kılma. Açık girdiler kayıt defteri varsayılanlarını yener. OpenCode Go önayarı, kardeş modelleri belgelenmiş hatlarında bırakırken `gpt-5.6-luna` için Responses'ı seçer; DeepSeek, `deepseek-v4-flash` için yerel Responses seçebilir; ve GitHub Copilot, modeller (`gpt-5.3-codex`, `gpt-5.4`, `gpt-5.4-mini`, `gpt-5.5`, `gpt-5.6-luna`, `gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`) için yalnızca Responses varsayılanlarını bildirir çünkü bu modeller ajan trafiği için `/chat/completions`'ı reddeder. Yerleşik varsayılanı olmayan modeller (örneğin `gpt-5.4-nano`) burada dahil edilebilir. Tek hatlı yukarı akış pinleri ve kurallı ChatGPT iletme geçersiz kılmaları reddeder. | | xAI Responses katılımı (panel) | anahtar | Yalnızca `xai` için `grok-4.5` ve `grok-4.6` `modelAdapters` girdilerini atomik olarak ayarlar veya temizler. Tek girdi, sonraki anahtar yazımı ikisini eşitleyene kadar karma durum olarak görünür. Diğer geçersiz kılmalar ve katman davranışı değişmez. | | `xaiResponsesXSearch?` | `boolean` | Varsayılan olarak devre dışıdır. Bir xAI Responses hedefinde, yalnızca canlı bir `web_search` aracı son istek normalleştirmesinden sağ çıktığında sağlayıcı tarafından barındırılan `x_search` bildirimini ekler. Mevcut bildirimler yinelenmez, çağıranın `tool_choice`/`allowed_tools` seçicileri hiçbir zaman genişletilmez ve bu, web araması yardımcı hizmetinin `search.xSearch` seçeneklerinden ayrıdır. | | `modelPreferHostedTools?` | `Record` | Barındırılan bir araç ad alanı ayıran iletme harici Responses ağ geçitleri için tam model dahil etme. Şu anda yalnızca `["image_generation"]` kabul eder; eşleşen bir model `openai-responses` hattını kullanmalı ve bu barındırılan aracı desteklemelidir. Çakışan istemci `image_gen` bildirimlerini kaldırır ve arayan araç seçimini korumak için seçicilerini yeniden yazar. OpenAI API sanal `-pro` modelleri için önce seçilen genel kimlik eşleştirilir ve çözümlenen temel hat model kimliği bir geri dönüştür. `modelAdapters` önce genel kimliği, ardından temel kimliği çözer; ikinci çözümleme son hattı belirler. Diğer modeller normal takma ad davranışını korur. | diff --git a/docs-site/src/content/docs/zh-cn/guides/providers.md b/docs-site/src/content/docs/zh-cn/guides/providers.md index b4010cdae5..314894c3d1 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -359,8 +359,8 @@ GPT-5.6 Sol/Terra/Luna 会预置在提供商的回退列表中,因此即使实 使用 Bearer **订阅令牌**(而非普通 API 密钥)进行认证。 **Cloudflare AI Gateway** 需要将 account 和 gateway id 填入 URL。 -Copilot 提供混合 wire 目录:其 GPT-5 系列模型(`gpt-5.3-codex`、`gpt-5.4`、 -`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`)会拒绝面向 +Copilot 提供混合 wire 目录:其模型(`gpt-5.3-codex`、`gpt-5.4`、 +`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)会拒绝面向 agent 流量的 `/chat/completions`,因此 opencodex 默认将这些模型路由到 Responses API,而其他 Copilot 模型仍走 chat completions。优先级为:硬 wire 固定 → 显式 [`modelAdapters`](/zh-cn/reference/configuration/providers/) 条目 → 注册表默认值 → 提供商级 diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md index f121d67bc0..32f2b52a69 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md @@ -105,7 +105,7 @@ selector,而不是分配一个新名称。 | `modelReasoningEfforts?` | `Record` | 按模型设置的标签。空列表会隐藏 effort 控件。 | | `modelSupportsReasoningSummaries?` | `Record` | 将某个模型设为 `false`,即可停止暴露摘要并移除摘要交付字段。 | | `modelReasoningSummaryDelivery?` | `Record` | 按模型设置的 Responses 交付枚举;会重写现有的 delivery 字段。 | -| `modelAdapters?` | `Record` | 按模型设置的 `openai-chat` 或 `openai-responses` 线协议覆盖项,用于混合线协议网关。显式条目优先于注册表默认值;DeepSeek 预设可以为 `deepseek-v4-flash` 选择原生 Responses,GitHub Copilot 则为 GPT-5 系列(`gpt-5.3-codex`、`gpt-5.4`、`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`)声明了 Responses 专用默认值,因为这些模型在代理流量下会拒绝 `/chat/completions`。没有内置默认值的模型(例如 `gpt-5.4-nano`)可以在此手动启用。单一线协议上游固定项和规范 ChatGPT forward 会拒绝覆盖。 | +| `modelAdapters?` | `Record` | 按模型设置的 `openai-chat` 或 `openai-responses` 线协议覆盖项,用于混合线协议网关。显式条目优先于注册表默认值;DeepSeek 预设可以为 `deepseek-v4-flash` 选择原生 Responses,GitHub Copilot 则为 模型(`gpt-5.3-codex`、`gpt-5.4`、`gpt-5.4-mini`、`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)声明了 Responses 专用默认值,因为这些模型在代理流量下会拒绝 `/chat/completions`。没有内置默认值的模型(例如 `gpt-5.4-nano`)可以在此手动启用。单一线协议上游固定项和规范 ChatGPT forward 会拒绝覆盖。 | | xAI Responses 启用项(仪表板) | 开关 | 仅用于 `xai`,以原子方式设置或清除 `grok-4.5` 和 `grok-4.6` 的 `modelAdapters` 条目。若只存在一个条目,则显示混合状态,直到下次开关写入将两者统一。其他覆盖项和层级行为不变。 | | `xaiResponsesXSearch?` | `boolean` | 默认禁用。在 xAI Responses 目标上,仅当有效的 `web_search` 工具在最终请求规范化后仍保留时,才附加由提供方托管的 `x_search` 声明。不会重复已有声明,绝不会扩大调用方的 `tool_choice`/`allowed_tools` 选择范围,并且此项独立于网络搜索辅助服务的 `search.xSearch` 选项。 | | `modelPreferHostedTools?` | `Record` | 非 forward Responses gateway 的精确模型 ID opt-in,用于上游预留 hosted tool namespace 的情况。目前只支持 `["image_generation"]`;匹配模型必须使用 `openai-responses` wire 且支持该 hosted 工具。它会移除冲突的客户端 `image_gen` 声明,并改写其 selector 以保持调用方的 tool choice。对于 OpenAI API 的虚拟 `-pro` 模型,先匹配所选公开 ID,未命中时才使用解析出的基础 wire-model ID 作为回退。`modelAdapters` 会先按公开 ID、再按基础 ID 解析;后一次结果决定最终 wire。未配置模型保持普通 alias 行为。 | diff --git a/docs-site/src/content/docs/zh-tw/guides/providers.md b/docs-site/src/content/docs/zh-tw/guides/providers.md index d26d093b7e..a1b4483cf3 100644 --- a/docs-site/src/content/docs/zh-tw/guides/providers.md +++ b/docs-site/src/content/docs/zh-tw/guides/providers.md @@ -460,8 +460,8 @@ Antigravity/Cloud Code Assist 模式)、`azure` / `azure-openai`、`kiro`、 短效 Copilot API token,不是貼上 API key。**GitLab Duo** 仍是使用 OpenAI-compatible endpoint 的 key/subscription-token gateway。**Cloudflare AI Gateway** 需要在 URL 填入 account 與 gateway id。 -Copilot 的 catalog 混合多種 wire:GPT-5 family(`gpt-5.3-codex`、`gpt-5.4`、`gpt-5.4-mini`、 -`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`)會拒絕 agent traffic 的 +Copilot 的 catalog 混合多種 wire:模型(`gpt-5.3-codex`、`gpt-5.4`、`gpt-5.4-mini`、 +`gpt-5.5`、`gpt-5.6-luna`、`gpt-5.6-sol`、`gpt-5.6-terra`、`gpt-6-astra`, `grok-4.5`, `grok-4.6`, `mai-code-1.1-flash`, `mai-code-1-flash-picker`)會拒絕 agent traffic 的 `/chat/completions`,因此 opencodex 會依內建預設把這些模型路由到 Responses API;其他 Copilot 模型 仍使用 chat completions。優先順序為:hard wire pin → 你明確設定的 [`modelAdapters`](/zh-tw/reference/configuration/providers/) → registry default → provider-wide adapter。 diff --git a/src/providers/registry.ts b/src/providers/registry.ts index ef7cb59e00..b1f689a8bd 100644 --- a/src/providers/registry.ts +++ b/src/providers/registry.ts @@ -3081,6 +3081,11 @@ export const PROVIDER_REGISTRY: readonly ProviderRegistryEntry[] = [ "gpt-5.6-luna": "openai-responses", "gpt-5.6-sol": "openai-responses", "gpt-5.6-terra": "openai-responses", + "gpt-6-astra": "openai-responses", + "grok-4.5": "openai-responses", + "grok-4.6": "openai-responses", + "mai-code-1.1-flash": "openai-responses", + "mai-code-1-flash-picker": "openai-responses", }, note: "Experimental unofficial Copilot bridge. Logs in via GitHub device flow using the public VS Code OAuth client id, then exchanges for a short-lived Copilot API token (copilot_internal). Requires an active Copilot subscription. GitHub may tighten or revoke this path; do not send confidential material you would not paste into Copilot Chat.", }, diff --git a/tests/providers/github-copilot/github-copilot-wire-defaults.test.ts b/tests/providers/github-copilot/github-copilot-wire-defaults.test.ts index 29af09048d..50019d02cf 100644 --- a/tests/providers/github-copilot/github-copilot-wire-defaults.test.ts +++ b/tests/providers/github-copilot/github-copilot-wire-defaults.test.ts @@ -8,7 +8,10 @@ * flipped the wire back, so the end-to-end cases assert the captured upstream URL — * the externally observable wire. Pattern mirrors tests/providers/deepseek-inbound-wire.test.ts. */ -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; +import * as oauth from "../../../src/oauth"; +import { fetchProviderModels } from "../../../src/codex/catalog/provider-fetch"; +import { clearModelCache } from "../../../src/codex/model-cache"; import { providerConfigSeed } from "../../../src/providers/derive"; import { getProviderRegistryEntry } from "../../../src/providers/registry"; import { resolveWireProtocolOverride } from "../../../src/server/adapter-resolve"; @@ -23,11 +26,42 @@ const RESPONSES_ONLY = [ "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", + "gpt-6-astra", + "grok-4.5", + "grok-4.6", + "mai-code-1.1-flash", + "mai-code-1-flash-picker", ] as const; const CHAT_SERVED = ["gpt-4o", "gpt-4.1", "gpt-4.1-mini", "claude-sonnet-4", "gemini-2.5-pro", "gpt-5-mini"] as const; const INBOUNDS = ["responses", "chat", "anthropic"] as const; +const DISCOVERY_ONLY = ["gpt-6-astra", "grok-4.5", "grok-4.6", "mai-code-1.1-flash", "mai-code-1-flash-picker"]; + +describe("Copilot discovery-only models do not widen the cold-start seed", () => { + for (const authMode of ["key", "oauth"] as const) { + test(`${authMode} discovery exposes new models but failure retains the configured seed`, async () => { + const auth = spyOn(oauth, "resolveModelsAuthToken").mockResolvedValue("test-token"); + const original = globalThis.fetch; + const provider = { ...providerConfigSeed(getProviderRegistryEntry("github-copilot")!), authMode, apiKey: "test-token" }; + try { + clearModelCache("github-copilot"); + globalThis.fetch = (async () => Response.json({ data: DISCOVERY_ONLY.map(id => ({ id })) })) as typeof fetch; + const live = await fetchProviderModels("github-copilot", { ...provider, fetch: globalThis.fetch } as OcxProviderConfig, 0); + expect(live.map(model => model.id).sort()).toEqual([...DISCOVERY_ONLY].sort()); + clearModelCache("github-copilot"); + globalThis.fetch = (async () => new Response("unavailable", { status: 503 })) as typeof fetch; + const fallback = await fetchProviderModels("github-copilot", { ...provider, fetch: globalThis.fetch } as OcxProviderConfig, 0); + expect(fallback.map(model => model.id).sort()).toEqual([...provider.models!].sort()); + for (const model of DISCOVERY_ONLY) expect(fallback.some(row => row.id === model)).toBe(false); + } finally { + globalThis.fetch = original; + auth.mockRestore(); + clearModelCache("github-copilot"); + } + }); + } +}); function copilotProvider(): OcxProviderConfig { // The entry's allowKeyAuthOverride lets tests use key auth instead of live OAuth. @@ -57,13 +91,15 @@ describe("Copilot chat-served models stay on the provider chat wire", () => { }); describe("explicit modelAdapters beat the registry default in both directions", () => { - test("opt-out: a listed Responses-default model pinned back to chat", () => { - const provider = { ...copilotProvider(), modelAdapters: { "gpt-5.4": "openai-chat" } }; - for (const inbound of INBOUNDS) { - expect(resolveWireProtocolOverride("github-copilot", "gpt-5.4", provider, inbound).adapter) - .toBe("openai-chat"); - } - }); + for (const model of RESPONSES_ONLY) { + test(`opt-out: ${model} pinned back to chat`, () => { + const provider = { ...copilotProvider(), modelAdapters: { [model]: "openai-chat" } }; + for (const inbound of INBOUNDS) { + expect(resolveWireProtocolOverride("github-copilot", model, provider, inbound).adapter) + .toBe("openai-chat"); + } + }); + } test("opt-in: an unlisted model mapped to Responses (the gpt-5.4-nano escape hatch)", () => { const provider = { ...copilotProvider(), modelAdapters: { "gpt-5.4-nano": "openai-responses" } }; @@ -81,13 +117,15 @@ describe("explicit modelAdapters beat the registry default in both directions", }); describe("the registry default is isolated to the copilot provider", () => { - test("a same-named model on another provider is untouched", () => { - const other: OcxProviderConfig = { adapter: "openai-chat", baseUrl: "https://example.com/v1", apiKey: "sk-test" }; - for (const inbound of INBOUNDS) { - expect(resolveWireProtocolOverride("some-custom", "gpt-5.4", other, inbound).adapter) - .toBe("openai-chat"); - } - }); + for (const model of RESPONSES_ONLY) { + test(`${model} on another provider is untouched`, () => { + const other: OcxProviderConfig = { adapter: "openai-chat", baseUrl: "https://example.com/v1", apiKey: "sk-test" }; + for (const inbound of INBOUNDS) { + expect(resolveWireProtocolOverride("some-custom", model, other, inbound).adapter) + .toBe("openai-chat"); + } + }); + } test("resolution preserves credentials and base URL through the copy", () => { const resolved = resolveWireProtocolOverride("github-copilot", "gpt-5.4", copilotProvider(), "responses"); @@ -143,6 +181,14 @@ describe("the wire default survives the handleResponses replay", () => { expect(url).not.toContain("/chat/completions"); }); + for (const model of ["gpt-6-astra", "grok-4.5", "grok-4.6", "mai-code-1.1-flash", "mai-code-1-flash-picker"]) { + for (const inbound of INBOUNDS) { + test(`${model} reaches /responses on ${inbound} inbound replay`, async () => { + expect(await drive(model, inbound)).toBe("https://api.githubcopilot.com/v1/responses"); + }); + } + } + test("gpt-4o still reaches /chat/completions", async () => { expect(await drive("gpt-4o", "responses")).toBe("https://api.githubcopilot.com/chat/completions"); }); From 6061dcce02bb8955dd8c4cfc353af3ed64082301 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:20:21 +0900 Subject: [PATCH 013/116] test(kiro): isolate and restore every debug setting the diagnostics gate reads [skip ci] Resolves the maintainer objection on #3837 (discussion_r3945935220): the shared setup cleared only OCX_DEBUG_FRAMES, so an inherited OCX_DEBUG=1 or a runtime debug override made the encoder-spy test fail legitimately. Snapshot OCX_DEBUG, OCX_DEBUG_FRAMES and the runtime override in beforeEach, clear them, and restore the exact previous values in afterEach. Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- tests/providers/kiro/kiro-stream.test.ts | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/tests/providers/kiro/kiro-stream.test.ts b/tests/providers/kiro/kiro-stream.test.ts index 1a9b7a6e02..47dfaf1833 100644 --- a/tests/providers/kiro/kiro-stream.test.ts +++ b/tests/providers/kiro/kiro-stream.test.ts @@ -16,6 +16,11 @@ import { parseKiroEvent } from "../../../src/adapters/kiro-events"; import { resetKiroThrottleStateForTests } from "../../../src/adapters/kiro-retry"; import { resetKiroCalibration } from "../../../src/adapters/kiro-calibration"; import { buildResponseJSON } from "../../../src/bridge"; +import { + clearDebugSetting, + getDebugSettings, + setDebugSettings, +} from "../../../src/lib/debug-settings"; import { encodeMessage } from "../../../src/lib/eventstream-decoder"; import { estimateTokens } from "../../../src/lib/token-estimate"; import { createTranslatorBudget } from "../../../src/lib/translator-budget"; @@ -34,11 +39,16 @@ const origApiRegion = process.env.KIRO_API_REGION; const origArn = process.env.KIRO_PROFILE_ARN; const origCredsFile = process.env.KIRO_CREDS_FILE; const origCredentialsFile = process.env.KIRO_CREDENTIALS_FILE; -const origDebugFrames = process.env.OCX_DEBUG_FRAMES; +let origDebug: string | undefined; +let origDebugFrames: string | undefined; +let origDebugOverride: boolean | undefined; const realFetch = globalThis.fetch; let tmp: string; beforeEach(() => { + origDebug = process.env.OCX_DEBUG; + origDebugFrames = process.env.OCX_DEBUG_FRAMES; + origDebugOverride = getDebugSettings().runtimeOverride.debug; tmp = mkdtempSync(join(tmpdir(), "kiro-stream-")); process.env.HOME = tmp; process.env.KIRO_REGION = "us-east-1"; @@ -46,7 +56,9 @@ beforeEach(() => { delete process.env.KIRO_PROFILE_ARN; delete process.env.KIRO_CREDS_FILE; delete process.env.KIRO_CREDENTIALS_FILE; + delete process.env.OCX_DEBUG; delete process.env.OCX_DEBUG_FRAMES; + clearDebugSetting("debug"); }); afterEach(() => { globalThis.fetch = realFetch; @@ -57,7 +69,10 @@ afterEach(() => { if (origArn === undefined) delete process.env.KIRO_PROFILE_ARN; else process.env.KIRO_PROFILE_ARN = origArn; if (origCredsFile === undefined) delete process.env.KIRO_CREDS_FILE; else process.env.KIRO_CREDS_FILE = origCredsFile; if (origCredentialsFile === undefined) delete process.env.KIRO_CREDENTIALS_FILE; else process.env.KIRO_CREDENTIALS_FILE = origCredentialsFile; + if (origDebug === undefined) delete process.env.OCX_DEBUG; else process.env.OCX_DEBUG = origDebug; if (origDebugFrames === undefined) delete process.env.OCX_DEBUG_FRAMES; else process.env.OCX_DEBUG_FRAMES = origDebugFrames; + if (origDebugOverride === undefined) clearDebugSetting("debug"); + else setDebugSettings({ debug: origDebugOverride }); removeTreeWithRetry(tmp); }); From 25689e1ec3631ba2ca8735bb41d4fd4d366d44a4 Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Mon, 7 Sep 2026 10:54:56 +0900 Subject: [PATCH 014/116] fix(responses): bound the streaming citation marker span [skip ci] (cherry picked from commit 8ef77f773523ba3ec55202a79f5abad247166026) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/responses/citation-markers.ts | 17 +++++++++++++++++ tests/responses/citation-markers.test.ts | 22 ++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/responses/citation-markers.ts b/src/responses/citation-markers.ts index 5fe58142cf..b65477b66e 100644 --- a/src/responses/citation-markers.ts +++ b/src/responses/citation-markers.ts @@ -68,6 +68,15 @@ export interface CitationMarkerFilter { flush(): string; } +/** + * Upper bound on the text withheld for one unterminated START. + * + * A real span is `cite` plus a few turn-scoped ids, so it is far under this. Without a + * bound, a backend that emits a START and never terminates it makes `held` grow for the + * whole response, and every later delta re-scans that accumulated prefix. + */ +const MAX_STREAMING_MARKER_SPAN_LENGTH = 4_096; + /** * Streaming filter. * @@ -75,6 +84,9 @@ export interface CitationMarkerFilter { * next — so a stateless per-delta strip would emit the tail of a span it never recognized. * This holds back the text from an unterminated START and releases it once the END arrives * (removed) or the stream ends (verbatim, so nothing the model actually said is lost). + * + * A span that grows past `MAX_STREAMING_MARKER_SPAN_LENGTH` is malformed ordinary text, so + * it is released verbatim instead of withheld; a later START can still open a valid span. */ export function createCitationMarkerFilter(): CitationMarkerFilter { // Text from an open START that has not been terminated yet. @@ -87,6 +99,11 @@ export function createCitationMarkerFilter(): CitationMarkerFilter { if (start === -1) return stripCitationMarkers(combined); const endAfterStart = combined.indexOf(CITATION_MARKER_END, start + 1); if (endAfterStart !== -1) return stripCitationMarkers(combined); + // Over the bound: this is not a citation span we will ever close. Emit it verbatim + // so neither the retained text nor the per-delta rescan grows without limit. + if (combined.length - start > MAX_STREAMING_MARKER_SPAN_LENGTH) { + return stripCitationMarkers(combined.slice(0, start)) + combined.slice(start); + } // The trailing span is still open: emit everything before it, hold the rest. held = combined.slice(start); return stripCitationMarkers(combined.slice(0, start)); diff --git a/tests/responses/citation-markers.test.ts b/tests/responses/citation-markers.test.ts index 0c1921750c..6145dbe688 100644 --- a/tests/responses/citation-markers.test.ts +++ b/tests/responses/citation-markers.test.ts @@ -87,4 +87,26 @@ describe("streaming citation marker filter (#3150)", () => { const filter = createCitationMarkerFilter(); expect(filter.push(`visible now ${S}cite`)).toBe("visible now "); }); + + test("an unterminated span past the bound is released instead of retained", () => { + // A backend that opens a span and never closes it must not make the filter accumulate + // the rest of the response, which every later delta would then re-scan. + const filter = createCitationMarkerFilter(); + let out = filter.push(`kept ${S}cite`); + expect(out).toBe("kept "); + for (let i = 0; i < 5_000; i += 1) out += filter.push("x"); + + // Everything after the malformed START is emitted verbatim, so nothing is lost, and + // flush() has nothing left to release. + expect(out).toBe(`kept ${S}cite${"x".repeat(5_000)}`); + expect(filter.flush()).toBe(""); + }); + + test("a later START still opens a valid span after a released malformed one", () => { + const filter = createCitationMarkerFilter(); + let out = filter.push(`a${S}${"y".repeat(5_000)}`); + out += filter.push(`${S}cite${P}turn1view0${E} tail`); + expect(out).toBe(`a${S}${"y".repeat(5_000)} tail`); + expect(filter.flush()).toBe(""); + }); }); From 00b74c7200ea5d33dbe495cc39788a91cbe4fd2b Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:22:45 +0900 Subject: [PATCH 015/116] fix(responses): keep an oversized citation span verbatim before a later marker in the same delta [skip ci] Resolves the unresolved major finding on #3843 (discussion_r3946034145): lastIndexOf selected the later START, its END made the whole-string strip pair the first START with that END, and the malformed text vanished. Walk START-delimited segments independently so a superseded or over-bound span is emitted verbatim and only a bounded trailing span is held for the next delta. Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/responses/citation-markers.ts | 34 +++++++++++++++--------- tests/responses/citation-markers.test.ts | 8 ++++++ 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/src/responses/citation-markers.ts b/src/responses/citation-markers.ts index b65477b66e..3e3943cad5 100644 --- a/src/responses/citation-markers.ts +++ b/src/responses/citation-markers.ts @@ -95,18 +95,29 @@ export function createCitationMarkerFilter(): CitationMarkerFilter { push(delta: string): string { const combined = held + delta; held = ""; - const start = combined.lastIndexOf(CITATION_MARKER_START); - if (start === -1) return stripCitationMarkers(combined); - const endAfterStart = combined.indexOf(CITATION_MARKER_END, start + 1); - if (endAfterStart !== -1) return stripCitationMarkers(combined); - // Over the bound: this is not a citation span we will ever close. Emit it verbatim - // so neither the retained text nor the per-delta rescan grows without limit. - if (combined.length - start > MAX_STREAMING_MARKER_SPAN_LENGTH) { - return stripCitationMarkers(combined.slice(0, start)) + combined.slice(start); + let start = combined.indexOf(CITATION_MARKER_START); + if (start === -1) return combined; + let out = combined.slice(0, start); + // Walk START-delimited segments independently so an earlier malformed START is never + // paired with a later span's END (the whole-string strip would do exactly that). + while (start !== -1) { + const nextStart = combined.indexOf(CITATION_MARKER_START, start + 1); + const segment = combined.slice(start, nextStart === -1 ? combined.length : nextStart); + const end = segment.indexOf(CITATION_MARKER_END, 1); + if (end !== -1) { + // A complete span: drop it, keep whatever trails it inside this segment. + out += segment.slice(end + 1); + } else if (nextStart === -1 && segment.length <= MAX_STREAMING_MARKER_SPAN_LENGTH) { + // Only a bounded trailing span can still be completed by a later delta. + held = segment; + } else { + // Superseded by a later START, or over the bound: ordinary text, emitted verbatim + // so neither the retained text nor the per-delta rescan grows without limit. + out += segment; + } + start = nextStart; } - // The trailing span is still open: emit everything before it, hold the rest. - held = combined.slice(start); - return stripCitationMarkers(combined.slice(0, start)); + return out; }, flush(): string { const rest = held; @@ -115,4 +126,3 @@ export function createCitationMarkerFilter(): CitationMarkerFilter { }, }; } - diff --git a/tests/responses/citation-markers.test.ts b/tests/responses/citation-markers.test.ts index 6145dbe688..dcc7f9abc6 100644 --- a/tests/responses/citation-markers.test.ts +++ b/tests/responses/citation-markers.test.ts @@ -109,4 +109,12 @@ describe("streaming citation marker filter (#3150)", () => { expect(out).toBe(`a${S}${"y".repeat(5_000)} tail`); expect(filter.flush()).toBe(""); }); + + test("an oversized malformed span survives a later valid marker in the same delta", () => { + const filter = createCitationMarkerFilter(); + const malformed = `${S}${"y".repeat(5_000)}`; + expect(filter.push(`a${span}${malformed}${S}cite${P}turn1view0${E} tail`)) + .toBe(`a${malformed} tail`); + expect(filter.flush()).toBe(""); + }); }); From 924b65799d32f22e1ec0bdb8cc216897bc8527ef Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Mon, 7 Sep 2026 11:02:32 +0900 Subject: [PATCH 016/116] fix(providers): refuse keychain restore across provider ownership [skip ci] (cherry picked from commit 73abec9a995d157e3acb55edfd7d8f082cc11aae) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/providers/key-store.ts | 22 +++++++++++++++ tests/providers/provider-key-store.test.ts | 32 +++++++++++++++++++++- 2 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/providers/key-store.ts b/src/providers/key-store.ts index 12e4ce6cb7..614fd3372f 100644 --- a/src/providers/key-store.ts +++ b/src/providers/key-store.ts @@ -64,6 +64,16 @@ function keychainAccount(reference: string): string { return reference.slice(KEYCHAIN_REFERENCE_PREFIX.length); } +/** + * A reference belongs to `name` only when its account is that provider's own active account + * or one of its pool accounts. `storeProviderKeyInKeychain` writes exactly those two shapes, + * so anything else in a provider's config names another provider's secret. + */ +function keychainReferenceBelongsToProvider(reference: string, name: string): boolean { + const account = keychainAccount(reference); + return account === name || account.startsWith(`${name}/`); +} + function readKeychain(account: string): string | undefined { const cached = resolvedCache.get(account); if (cached !== undefined) return cached; @@ -185,6 +195,18 @@ export function restoreProviderKeyFromKeychain(config: OcxConfig, name: string): const pool = provider.apiKeyPool ?? []; const resolved = new Map(); const refs = [provider.apiKey, ...pool.map(e => e.key)].filter(isKeychainReference); + // Restore reads a secret out of the keychain, writes it back to config as plaintext, and then + // DELETES the keychain item. Following a reference to another provider's account would both + // disclose that secret through this provider's config and destroy the real owner's credential, + // so refuse before anything is read or removed. + const foreign = refs.filter(ref => !keychainReferenceBelongsToProvider(ref, name)); + if (foreign.length > 0) { + return { + ok: false, + error: `provider "${name}" references a keychain account it does not own (${foreign.length} reference(s)); config left unchanged`, + status: 400, + }; + } for (const ref of refs) { const account = keychainAccount(ref); if (resolved.has(account)) continue; diff --git a/tests/providers/provider-key-store.test.ts b/tests/providers/provider-key-store.test.ts index 645920e32c..1197a1fea9 100644 --- a/tests/providers/provider-key-store.test.ts +++ b/tests/providers/provider-key-store.test.ts @@ -156,6 +156,37 @@ describe("store / restore", () => { expect(probeProviderKeychain().available).toBe(false); }); + test("restore refuses a reference to another provider's keychain account", () => { + const { store, factory } = fakeKeychain(); + setProviderKeychainEntryFactoryForTests(factory); + const config = loadConfig(); + config.providers.other = { adapter: "openai-chat", baseUrl: "https://other.example/v1", apiKey: POOL_SECRET }; + expect(storeProviderKeyInKeychain(config, "other")).toEqual({ ok: true, moved: 1 }); + expect(config.providers.other!.apiKey).toBe("keychain:other"); + + // Point "relay" at the account "other" owns. Restore would otherwise read that secret, + // write it into relay's config as plaintext, and delete the owner's keychain item. + config.providers.relay!.apiKey = "keychain:other"; + const result = restoreProviderKeyFromKeychain(config, "relay"); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.status).toBe(400); + + expect(config.providers.relay!.apiKey).toBe("keychain:other"); + expect(readFileSync(join(testDir, "config.json"), "utf8")).not.toContain(POOL_SECRET); + // The real owner's secret is still in the keychain and still resolves for that provider. + expect(store.size).toBe(1); + expect(resolveProviderApiKey(config.providers.other!.apiKey)).toBe(POOL_SECRET); + }); + + test("restore still accepts a provider's own active and pool accounts", () => { + const { factory } = fakeKeychain(); + setProviderKeychainEntryFactoryForTests(factory); + const config = loadConfig(); + config.providers.relay!.apiKeyPool = [{ id: "a1", key: SECRET }, { id: "b2", key: POOL_SECRET }]; + expect(storeProviderKeyInKeychain(config, "relay")).toEqual({ ok: true, moved: 2 }); + expect(restoreProviderKeyFromKeychain(config, "relay")).toEqual({ ok: true, restored: 2 }); + }); + test("management route: GET reports store kind, POST store/restore round-trips", async () => { const { factory } = fakeKeychain(); setProviderKeychainEntryFactoryForTests(factory); @@ -192,4 +223,3 @@ describe("store / restore", () => { } }); }); - From 6eadb165873a33d8589e46bf5256a61524d82ec7 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:18:33 +0900 Subject: [PATCH 017/116] fix(management): expose the effective web-search sidecar enabled state GET and PUT /api/sidecar-settings return webSearch.model/backend/stream flags but omitted webSearch.enabled, so the dashboard could not tell whether the sidecar master switch was off. Serialize the effective value (unset reads as enabled) on both responses. Reimplements https://github.com/lidge-jun/opencodex/pull/2033 on current dev (the original branch is 1364 commits behind and its test moved to tests/vision/ under the test-layout split). Co-authored-by: louis-tepe <161487332+louis-tepe@users.noreply.github.com> --- src/server/management/config-routes.ts | 2 ++ .../vision/sidecar-settings-vision-controls.test.ts | 12 ++++++++++++ tests/vision/vision-anthropic.test.ts | 4 ++-- 3 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/server/management/config-routes.ts b/src/server/management/config-routes.ts index 4d551a886d..08f4b85d27 100644 --- a/src/server/management/config-routes.ts +++ b/src/server/management/config-routes.ts @@ -701,6 +701,7 @@ export async function handleConfigRoutes(ctx: ManagementContext): Promise { expect(config.visionSidecar).toEqual({ ...FULL_VISION, enabled: false }); }); + test("GET and PUT expose the effective web-search enabled state", async () => { + const unset = await getSidecarSettings(emptyConfig()); + expect((await unset.json() as { webSearch: { enabled: boolean } }).webSearch.enabled).toBe(true); + + const config = emptyConfig({ webSearchSidecar: { enabled: false } }); + const disabled = await getSidecarSettings(config); + expect((await disabled.json() as { webSearch: { enabled: boolean } }).webSearch.enabled).toBe(false); + + const response = await putSidecarSettings(config, { webSearch: { streamRoutedModelOutput: true } }); + expect((await response.json() as { webSearch: { enabled: boolean } }).webSearch.enabled).toBe(false); + }); + test("timeoutMs validation reuses the runtime bounds rather than a second contract", async () => { expect(resolveVisionTimeoutMs(undefined)).toBe(DEFAULT_VISION_TIMEOUT_MS); expect(resolveVisionTimeoutMs(MIN_VISION_TIMEOUT_MS)).toBe(MIN_VISION_TIMEOUT_MS); diff --git a/tests/vision/vision-anthropic.test.ts b/tests/vision/vision-anthropic.test.ts index ee4b01b421..086e5df7bb 100644 --- a/tests/vision/vision-anthropic.test.ts +++ b/tests/vision/vision-anthropic.test.ts @@ -339,7 +339,7 @@ describe("Anthropic vision planning and management config", () => { config, ); const getBody = await get!.json() as Record; - expect(getBody.webSearch).toEqual({ model: "claude-haiku-4-5", backend: "anthropic", streamRoutedModelOutput: false }); + expect(getBody.webSearch).toEqual({ enabled: true, model: "claude-haiku-4-5", backend: "anthropic", streamRoutedModelOutput: false }); expect(getBody.vision).toEqual({ enabled: true, model: "claude-sonnet-5", @@ -363,7 +363,7 @@ describe("Anthropic vision planning and management config", () => { ); expect(clear.status).toBe(200); const clearBody = await clear.json() as Record; - expect(clearBody.webSearch).toEqual({ model: "gpt-5.6-luna", streamRoutedModelOutput: false }); + expect(clearBody.webSearch).toEqual({ enabled: true, model: "gpt-5.6-luna", streamRoutedModelOutput: false }); expect(clearBody.vision).toEqual({ enabled: true, model: "gpt-5.4-mini", From 61a775ca2dcbe1fd7d7678901abea0351f8ef461 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:23:16 +0900 Subject: [PATCH 018/116] docs: record lane B manual delivery roadmap [skip ci] --- devlog/_plan/260907_release_train_b/000_plan.md | 11 +++++++++++ devlog/_plan/260907_release_train_b/010_carry.md | 3 +++ devlog/_plan/260907_release_train_b/020_carry.md | 3 +++ 3 files changed, 17 insertions(+) create mode 100644 devlog/_plan/260907_release_train_b/000_plan.md create mode 100644 devlog/_plan/260907_release_train_b/010_carry.md create mode 100644 devlog/_plan/260907_release_train_b/020_carry.md diff --git a/devlog/_plan/260907_release_train_b/000_plan.md b/devlog/_plan/260907_release_train_b/000_plan.md new file mode 100644 index 0000000000..be31f8e242 --- /dev/null +++ b/devlog/_plan/260907_release_train_b/000_plan.md @@ -0,0 +1,11 @@ +# Lane B delivery roadmap + +Satisfy-spec HOTL, triggered by delegated release-train packet. Goal: prepare a manual #3856 -> #3849 carry chain for main-session integration. No merges, releases, installs, local tests/typechecks/builds, native stacks, or edits to other lane files. Resources: existing git/gh and astra reviewers; user set no token/cost/time limit. Stop after exact top-head remote CI success, independent security verdicts, and handoff evidence. BLOCKED means a concrete unresolved owner/security/CI condition; #3848 is DEFER until #3856 lands. Main reclaims after two distinct failed leaf packets; new worker scope requires plan amendment. + +Memory/evidence: this neutral roadmap, `.tmp/lane-b/` for all security work notes, `.codexclaw/` for FSM/goalplan. Escalate cross-lane conflicts to main. How-it-works English/ja/ko/ru/zh-cn ownership was explicitly assigned to B by main. No automatic peer writes beyond collision coordination. + +1. Docs-only roadmap audit and lock. +2. Carry quota activation original commits with cherry-pick -x and contributor trailers; inspect default-off, identity and pending-state contracts. Lower layer code verification is deferred to top CI by explicit user instruction; its D certifies carry preparation, not runtime success. +3. Carry Mihomo transport commit plus IPv6-only and canonical NO_PROXY/unsafe companion regressions. Publish manual chain, independently review final implementation, dispatch ci.yml lane=all only on top. Repair lower layers sequentially and cascade with rebase --update-refs. + +Verifier: gh workflow run ci.yml --ref codex/260907-b-mihomo-ipv6 -f lane=all; read exact head SHA and every job including Windows shards. Local product commands NOT RUN by user instruction. Inspect workflow definitions instead of executing local verifiers. No claims of live TUN validation; deterministic resolver/pinned transport tests are remote CI proof. diff --git a/devlog/_plan/260907_release_train_b/010_carry.md b/devlog/_plan/260907_release_train_b/010_carry.md new file mode 100644 index 0000000000..cde8f79785 --- /dev/null +++ b/devlog/_plan/260907_release_train_b/010_carry.md @@ -0,0 +1,3 @@ +# Quota activation carry + +Detailed working plan: `.tmp/lane-b/010_carry.md` (gitignored security work space). Public source and contributor provenance are recorded in the roadmap. Only published outcomes will be added here. diff --git a/devlog/_plan/260907_release_train_b/020_carry.md b/devlog/_plan/260907_release_train_b/020_carry.md new file mode 100644 index 0000000000..10d853e99e --- /dev/null +++ b/devlog/_plan/260907_release_train_b/020_carry.md @@ -0,0 +1,3 @@ +# Mihomo IPv6 carry + +Detailed working plan: `.tmp/lane-b/020_carry.md` (gitignored security work space). Public source and contributor provenance are recorded in the roadmap. Only published outcomes will be added here. From 1386e3d4a04b7a12eacea0ced74ed55307d6dfa3 Mon Sep 17 00:00:00 2001 From: Terry Tan Date: Sun, 6 Sep 2026 23:17:29 -0700 Subject: [PATCH 019/116] fix(codex): sustain quota window activation [skip ci] (cherry picked from commit 0da9f2ce0812c0dbf39d48077bfb038b2c526783) Co-authored-by: terrytan95 <10609214+terrytan95@users.noreply.github.com> --- .../docs/getting-started/how-it-works.mdx | 8 +- src/codex/auth-api.ts | 15 ++ src/codex/quota-auto-refresh-state.ts | 6 + src/codex/quota-auto-refresh.ts | 162 +++++++++++++++--- src/codex/warmup.ts | 4 + src/config.ts | 2 + src/types/config.ts | 3 + structure/08_openai-provider-tiers.md | 7 +- 8 files changed, 178 insertions(+), 29 deletions(-) diff --git a/docs-site/src/content/docs/getting-started/how-it-works.mdx b/docs-site/src/content/docs/getting-started/how-it-works.mdx index 0344037b75..b5995732b6 100644 --- a/docs-site/src/content/docs/getting-started/how-it-works.mdx +++ b/docs-site/src/content/docs/getting-started/how-it-works.mdx @@ -50,7 +50,13 @@ account before the request is forwarded upstream. The rule is intentionally spli its minimal non-stored account warmup request through the exact account whose window is due, coalesces simultaneous windows into one request, and durably persists both reset timestamps to prevent duplicate work after restarts. Paused accounts and accounts - requiring reauthentication are skipped; the next normal quota poll reports the activated window. + requiring reauthentication are skipped. Activation captures successful response quota headers; + opted-in idle accounts also refresh stale quota metadata at most once every five minutes, + without needing an open dashboard. Observed reset boundaries are retained across restarts + until completed, so a moving idle-window timestamp cannot erase a pending activation. + Metadata refresh uses the existing bounded authentication recovery; an inference 401 marks + the rejected credential for reauthentication instead of repeatedly spending retries on it. + Failures log only an opaque account label and a status-only reason. This is separate from reset-window routing: routing chooses an account for incoming work, while activation sends one request to a specific opted-in account only after its own reset is due. diff --git a/src/codex/auth-api.ts b/src/codex/auth-api.ts index 51e3fed303..8ab7f7418f 100644 --- a/src/codex/auth-api.ts +++ b/src/codex/auth-api.ts @@ -1835,6 +1835,21 @@ export async function listCodexAuthAccountsSnapshot( }; } +/** One opted-in account's metadata; reuse the bounded WHAM 401 recovery and generation fence. */ +export async function refreshCodexQuotaForActivation(config: OcxConfig, accountId: string): Promise { + if (accountId === MAIN_CODEX_ACCOUNT_ID) { + await fetchMainAccountInfoAttempt(true, 1, undefined, false, false); + return; + } + const account = configuredPoolAccount(config, accountId); + if (!account) return; + const writerGeneration = captureConfigGeneration(); + const result = await fetchPoolAccountQuota(accountId, true, account.plan); + if (result.needsReauth && result.credentialGeneration !== undefined) { + markAccountNeedsReauth(accountId, writerGeneration, result.credentialGeneration); + } +} + export async function listCodexAuthAccounts(config: OcxConfig, forceRefresh = false): Promise { return (await listCodexAuthAccountsSnapshot(config, forceRefresh)).accounts; } diff --git a/src/codex/quota-auto-refresh-state.ts b/src/codex/quota-auto-refresh-state.ts index 43bb606d63..72b7d5828c 100644 --- a/src/codex/quota-auto-refresh-state.ts +++ b/src/codex/quota-auto-refresh-state.ts @@ -4,13 +4,19 @@ export type CodexQuotaAutoRefreshWindows = { fiveHour?: number; weekly?: number export const completedByAccount = new Map(); export const retryAfterByAccount = new Map(); +export const scheduledByAccount = new Map(); +export const quotaRefreshAfterByAccount = new Map(); export function forgetCodexQuotaAutoRefreshAccount(accountId: string): void { completedByAccount.delete(accountId); retryAfterByAccount.delete(accountId); + scheduledByAccount.delete(accountId); + quotaRefreshAfterByAccount.delete(accountId); } export function resetCodexQuotaAutoRefreshStateForTests(): void { completedByAccount.clear(); retryAfterByAccount.clear(); + scheduledByAccount.clear(); + quotaRefreshAfterByAccount.clear(); } diff --git a/src/codex/quota-auto-refresh.ts b/src/codex/quota-auto-refresh.ts index 88291e0cdd..b61cc1467e 100644 --- a/src/codex/quota-auto-refresh.ts +++ b/src/codex/quota-auto-refresh.ts @@ -1,5 +1,5 @@ import { mutatePersistedConfig } from "../config"; -import { registerStateSweepAfterTick } from "../lib/state-store-sweeper"; +import { captureConfigGeneration, registerStateSweepAfterTick } from "../lib/state-store-sweeper"; import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "../providers/openai-tiers"; import { normalizeResetAt } from "../providers/quota-wire"; import { providerCodexAccountMode } from "../providers/registry"; @@ -7,17 +7,20 @@ import type { OcxConfig } from "../types"; import { isSelectableCodexPoolAccount } from "./account-id"; import { reconcileMainCodexAccountRuntimeState } from "./account-lifecycle"; import { isCodexAccountPaused } from "./account-pause"; -import { isAccountNeedsReauth } from "./account-runtime-state"; -import { getValidCodexToken } from "./account-store"; +import { isAccountNeedsReauth, markAccountNeedsReauth } from "./account-runtime-state"; +import { getValidCodexToken, isCodexAccountGenerationLive } from "./account-store"; +import { codexAccountLogLabel } from "./account-label"; import { getMainAccountToken, getValidMainAccountToken, MAIN_CODEX_ACCOUNT_ID } from "./main-account"; import { isMainAccountHardLocked } from "./main-account-hard-lock"; import { tryAcquireNativeMainProfileClaim } from "./native-main-admission"; import { withNativeMainSharedClaim } from "./native-main-claim"; import { resolveNativeProfileContext } from "./native-profile-store"; -import { getAccountQuota, type StoredAccountQuota } from "./quota"; -import { warmCodexAccount } from "./warmup"; +import { captureMainQuotaWriter } from "./main-account-cache"; +import { applyAccountQuotaFromUpstreamHeaders, getAccountQuota, type StoredAccountQuota } from "./quota"; +import { CodexWarmupError, codexWarmupFailureReason, warmCodexAccount } from "./warmup"; import { - completedByAccount, retryAfterByAccount, resetCodexQuotaAutoRefreshStateForTests, + completedByAccount, retryAfterByAccount, scheduledByAccount, quotaRefreshAfterByAccount, + resetCodexQuotaAutoRefreshStateForTests, type CodexQuotaAutoRefreshWindows, } from "./quota-auto-refresh-state"; export type { CodexQuotaAutoRefreshWindows } from "./quota-auto-refresh-state"; @@ -36,6 +39,7 @@ export interface CodexQuotaAutoRefreshStatus { export interface CodexQuotaAutoRefreshRunDeps { getQuota?: (accountId: string) => StoredAccountQuota | null; + refreshQuota?: (config: OcxConfig, accountId: string) => Promise; /** Only false means skipped; existing void callbacks still report a successful warmup. */ warmAccount?: (config: OcxConfig, accountId: string) => Promise; persistCompleted?: ( @@ -69,29 +73,83 @@ export function dueCodexQuotaAutoRefreshWindows( now: number, completed = completedByAccount.get(accountId), ): CodexQuotaAutoRefreshWindows | null { - if (!quota) return null; const saved = config.codexQuotaAutoRefresh?.[accountId]; + const scheduled = scheduledByAccount.get(accountId) ?? ( + saved?.nextFiveHourResetAt !== undefined || saved?.nextWeeklyResetAt !== undefined + ? { fiveHour: saved.nextFiveHourResetAt, weekly: saved.nextWeeklyResetAt } : undefined + ); const due: CodexQuotaAutoRefreshWindows = {}; - const shortResetAt = normalizeResetAt(quota.shortResetAt); - const weeklyResetAt = normalizeResetAt(quota.weeklyResetAt); + const shortResetAt = normalizeResetAt(scheduled ? scheduled.fiveHour : quota?.shortResetAt); + const weeklyResetAt = normalizeResetAt(scheduled ? scheduled.weekly : quota?.weeklyResetAt); if (saved?.fiveHour === true - && quota.shortWindowSeconds === FIVE_HOUR_WINDOW_SECONDS + && (scheduled?.fiveHour !== undefined || saved.nextFiveHourResetAt !== undefined + || quota?.shortWindowSeconds === FIVE_HOUR_WINDOW_SECONDS) && shortResetAt !== undefined && shortResetAt <= now - && normalizeResetAt(saved.lastFiveHourResetAt) !== shortResetAt - && normalizeResetAt(completed?.fiveHour) !== shortResetAt) { + && shortResetAt > (normalizeResetAt(saved.lastFiveHourResetAt) ?? -1) + && shortResetAt > (normalizeResetAt(completed?.fiveHour) ?? -1)) { due.fiveHour = shortResetAt; } if (saved?.weekly === true && weeklyResetAt !== undefined && weeklyResetAt <= now - && normalizeResetAt(saved.lastWeeklyResetAt) !== weeklyResetAt - && normalizeResetAt(completed?.weekly) !== weeklyResetAt) { + && weeklyResetAt > (normalizeResetAt(saved.lastWeeklyResetAt) ?? -1) + && weeklyResetAt > (normalizeResetAt(completed?.weekly) ?? -1)) { due.weekly = weeklyResetAt; } return due.fiveHour === undefined && due.weekly === undefined ? null : due; } +/** Retain the earliest uncompleted observation, including across process restarts. */ +function rememberWindows(config: OcxConfig, accountId: string, quota: StoredAccountQuota | null): void { + const saved = config.codexQuotaAutoRefresh?.[accountId]; + if (!saved) return; + const completed = completedByAccount.get(accountId); + const previous = scheduledByAccount.get(accountId) ?? { + fiveHour: normalizeResetAt(saved.nextFiveHourResetAt), + weekly: normalizeResetAt(saved.nextWeeklyResetAt), + }; + const next: CodexQuotaAutoRefreshWindows = {}; + for (const window of ["fiveHour", "weekly"] as const) { + if (!saved[window]) continue; + const done = normalizeResetAt(completed?.[window] + ?? (window === "fiveHour" ? saved.lastFiveHourResetAt : saved.lastWeeklyResetAt)); + const observed = normalizeResetAt(window === "fiveHour" + ? quota?.shortWindowSeconds === FIVE_HOUR_WINDOW_SECONDS ? quota.shortResetAt : undefined + : quota?.weeklyResetAt); + const candidates = [normalizeResetAt(previous[window]), observed] + .filter((value): value is number => value !== undefined && (done === undefined || value > done)); + if (candidates.length) next[window] = Math.min(...candidates); + } + scheduledByAccount.set(accountId, next); + if (normalizeResetAt(saved.nextFiveHourResetAt) === next.fiveHour + && normalizeResetAt(saved.nextWeeklyResetAt) === next.weekly) return; + try { + const outcome = mutatePersistedConfig(persisted => { + const current = persisted.codexQuotaAutoRefresh?.[accountId]; + if (!current) return { changed: false, value: null }; + const setting = { ...current }; + // A settings change that raced this sweep remains authoritative. + delete setting.nextFiveHourResetAt; + delete setting.nextWeeklyResetAt; + if (current.fiveHour && next.fiveHour !== undefined) setting.nextFiveHourResetAt = next.fiveHour; + if (current.weekly && next.weekly !== undefined) setting.nextWeeklyResetAt = next.weekly; + persisted.codexQuotaAutoRefresh = { ...persisted.codexQuotaAutoRefresh, [accountId]: setting }; + return { changed: true, value: setting }; + }); + if (outcome.status !== "unavailable" && outcome.value) { + config.codexQuotaAutoRefresh = { ...config.codexQuotaAutoRefresh, [accountId]: outcome.value }; + } + } catch { + // Keep the in-memory deadline and retry its narrow persistence on the next tick. + } +} + +async function refreshQuota(config: OcxConfig, accountId: string): Promise { + const { refreshCodexQuotaForActivation } = await import("./auth-api"); + await refreshCodexQuotaForActivation(config, accountId); +} + function mainWarmupRestricted(config: OcxConfig): boolean { return isMainAccountHardLocked(config) || isCodexAccountPaused(config, MAIN_CODEX_ACCOUNT_ID) @@ -99,8 +157,23 @@ function mainWarmupRestricted(config: OcxConfig): boolean { } async function warmAccount(config: OcxConfig, accountId: string): Promise { + const writerGeneration = captureConfigGeneration(); if (accountId !== MAIN_CODEX_ACCOUNT_ID) { - await warmCodexAccount(await getValidCodexToken(accountId)); + const token = await getValidCodexToken(accountId); + if (isCodexAccountPaused(config, accountId) || isAccountNeedsReauth(accountId)) return false; + try { + await warmCodexAccount({ ...token, onCompleted: headers => { + if (isCodexAccountGenerationLive(accountId, token.generation)) { + applyAccountQuotaFromUpstreamHeaders(accountId, headers, writerGeneration); + } + } }); + } catch (error) { + if (error instanceof CodexWarmupError && error.status === 401) { + markAccountNeedsReauth(accountId, writerGeneration, token.generation); + } + throw error; + } + if (!isCodexAccountGenerationLive(accountId, token.generation)) return false; return; } const lease = tryAcquireNativeMainProfileClaim(); @@ -116,7 +189,18 @@ async function warmAccount(config: OcxConfig, accountId: string): Promise { + if (writer) applyAccountQuotaFromUpstreamHeaders(accountId, headers, writerGeneration, writer); + } }); + } catch (error) { + if (error instanceof CodexWarmupError && error.status === 401 + && getMainAccountToken()?.accessToken === token.accessToken) { + markAccountNeedsReauth(accountId, writerGeneration); + } + throw error; + } }); } finally { lease.release(); @@ -175,30 +259,54 @@ export async function runCodexQuotaAutoRefresh( const quotaFor = deps.getQuota ?? getAccountQuota; const warm = deps.warmAccount ?? warmAccount; const persist = deps.persistCompleted ?? persistCompleted; + const refresh = deps.refreshQuota ?? refreshQuota; inFlight = (async () => { retryPendingMarkers(config, persist); const accountIds = [ MAIN_CODEX_ACCOUNT_ID, ...(config.codexAccounts ?? []).filter(isSelectableCodexPoolAccount).map(account => account.id), ]; - const due = accountIds.flatMap(accountId => { - if (isCodexAccountPaused(config, accountId) - || isAccountNeedsReauth(accountId) - || (accountId === MAIN_CODEX_ACCOUNT_ID && isMainAccountHardLocked(config)) - || (retryAfterByAccount.get(accountId) ?? 0) > now) return []; - const windows = dueCodexQuotaAutoRefreshWindows(config, accountId, quotaFor(accountId), now); - return windows ? [{ accountId, windows }] : []; - }); - for (let index = 0; index < due.length; index += CONCURRENCY) { - await Promise.all(due.slice(index, index + CONCURRENCY).map(async ({ accountId, windows }) => { + const eligible = (accountId: string) => { + const setting = config.codexQuotaAutoRefresh?.[accountId]; + const provider = config.providers[OPENAI_CODEX_PROVIDER_ID]; + return provider?.disabled !== true && isCanonicalOpenAiForwardProvider(provider) + && providerCodexAccountMode(OPENAI_CODEX_PROVIDER_ID, provider) === "pool" + && (accountId === MAIN_CODEX_ACCOUNT_ID || config.codexAccounts?.some( + account => account.id === accountId && isSelectableCodexPoolAccount(account))) + && (setting?.fiveHour === true || setting?.weekly === true) + && !isCodexAccountPaused(config, accountId) && !isAccountNeedsReauth(accountId) + && !(accountId === MAIN_CODEX_ACCOUNT_ID && isMainAccountHardLocked(config)); + }; + for (let index = 0; index < accountIds.length; index += CONCURRENCY) { + await Promise.all(accountIds.slice(index, index + CONCURRENCY).map(async accountId => { + if (!eligible(accountId)) return; + // Capture before WHAM can move an idle window's reset into the future. + rememberWindows(config, accountId, quotaFor(accountId)); + const quota = quotaFor(accountId); + if ((!quota || now - quota.updatedAt >= RETRY_MS) + && (quotaRefreshAfterByAccount.get(accountId) ?? 0) <= now) { + quotaRefreshAfterByAccount.set(accountId, now + RETRY_MS); + try { await refresh(config, accountId); } catch { /* Retry metadata at the bounded cadence. */ } + } + if (!eligible(accountId)) return; + rememberWindows(config, accountId, quotaFor(accountId)); + if ((retryAfterByAccount.get(accountId) ?? 0) > now) return; + const windows = dueCodexQuotaAutoRefreshWindows(config, accountId, quotaFor(accountId), now); + if (!windows) return; try { if (await warm(config, accountId) === false) return; retryAfterByAccount.delete(accountId); const completed = { ...completedByAccount.get(accountId), ...windows }; completedByAccount.set(accountId, completed); persist(config, accountId, completed); - } catch { + rememberWindows(config, accountId, quotaFor(accountId)); + } catch (error) { retryAfterByAccount.set(accountId, now + RETRY_MS); + const account = config.codexAccounts?.find(candidate => candidate.id === accountId); + const label = account ? codexAccountLogLabel(account) : "main"; + console.warn(`[codex-quota-auto-refresh] ${label}: ${codexWarmupFailureReason(error)}; ${ + isAccountNeedsReauth(accountId) ? "reauthentication required" : "retry in five minutes" + }`); } })); } diff --git a/src/codex/warmup.ts b/src/codex/warmup.ts index 51b52ac2ba..cc2f10ac55 100644 --- a/src/codex/warmup.ts +++ b/src/codex/warmup.ts @@ -22,6 +22,8 @@ export interface CodexWarmupOptions { chatgptAccountId: string; model?: string; timeoutMs?: number; + /** Publish quota headers only after a completed inference, never on a failed stream. */ + onCompleted?: (headers: Headers) => void; } const CODEX_RESPONSES_URL = "https://chatgpt.com/backend-api/codex/responses"; @@ -263,6 +265,8 @@ async function tryWarmup(options: CodexWarmupOptions, model: string): Promise {}); diff --git a/src/config.ts b/src/config.ts index d5ef05c33f..d25aa07ad2 100644 --- a/src/config.ts +++ b/src/config.ts @@ -856,6 +856,8 @@ const codexQuotaAutoRefreshEntrySchema = z.object({ weekly: z.boolean().optional(), lastFiveHourResetAt: z.number().finite().nonnegative().optional(), lastWeeklyResetAt: z.number().finite().nonnegative().optional(), + nextFiveHourResetAt: z.number().finite().nonnegative().optional(), + nextWeeklyResetAt: z.number().finite().nonnegative().optional(), }).strict(); const CODEX_QUOTA_AUTO_REFRESH_KEY_ERROR = "quota auto-refresh keys must be a Codex pool-account id or the main Codex account and cannot be reserved JavaScript object keys"; diff --git a/src/types/config.ts b/src/types/config.ts index ee97cdf9ac..31b5a52ceb 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -723,6 +723,9 @@ export interface OcxConfig { /** Upstream reset timestamps already activated, retained across restarts. */ lastFiveHourResetAt?: number; lastWeeklyResetAt?: number; + /** Observed boundaries retained until activation, even if an idle upstream clock moves. */ + nextFiveHourResetAt?: number; + nextWeeklyResetAt?: number; }>; /** * Selection order per account id, higher used earlier; absent = 0. Keyed by id diff --git a/structure/08_openai-provider-tiers.md b/structure/08_openai-provider-tiers.md index 1f838baeb5..834cbd46ee 100644 --- a/structure/08_openai-provider-tiers.md +++ b/structure/08_openai-provider-tiers.md @@ -75,7 +75,12 @@ plan-relevant window is freshly confirmed at exactly 100%; unknown and failed re `codexQuotaAutoRefresh` is a separate default-off spending intent. For each explicitly enabled account/window, the one-minute state sweep compares the cached upstream reset timestamp, sends the existing minimal non-stored warmup through that exact account once the timestamp is due, then -field-patches the completed timestamp; the next normal quota poll reports the activated window. +field-patches the completed timestamp. The next observed reset boundary is also retained in +`nextFiveHourResetAt` / `nextWeeklyResetAt` until completed; later idle-window metadata cannot +postpone it. Successful warmups publish quota headers under the captured credential/identity fence. +For opted-in accounts only, stale metadata is refreshed at most once per five minutes through +the existing WHAM recovery path, independently of dashboard traffic or reset notifications. +Inference 401s quarantine the rejected credential; failures log an opaque label and safe reason. Paused or reauthentication-required accounts are skipped, simultaneous 5-hour/weekly resets share one warmup, transient failures retry after five minutes, and account deletion removes its setting and completion markers. From c38677004f80605dd8628fb109e804169cbc2b7f Mon Sep 17 00:00:00 2001 From: Terry Tan Date: Mon, 7 Sep 2026 00:51:39 -0700 Subject: [PATCH 020/116] test(codex): cover quota activation regressions [skip ci] (cherry picked from commit 5d01860f23cabaedd68dd53a9c8e751a71ca2ba2) Co-authored-by: terrytan95 <10609214+terrytan95@users.noreply.github.com> --- .../docs/getting-started/how-it-works.mdx | 4 + .../docs/ja/getting-started/how-it-works.mdx | 16 +++ .../docs/ko/getting-started/how-it-works.mdx | 16 +++ .../docs/ru/getting-started/how-it-works.mdx | 19 +++ .../zh-cn/getting-started/how-it-works.mdx | 25 ++++ src/codex/quota-auto-refresh-state.ts | 2 + src/codex/quota-auto-refresh.ts | 11 ++ src/codex/warmup.ts | 1 + .../codex-quota-auto-refresh.test.ts | 116 ++++++++++++++++++ tests/codex-integration/codex-warmup.test.ts | 23 ++++ 10 files changed, 233 insertions(+) diff --git a/docs-site/src/content/docs/getting-started/how-it-works.mdx b/docs-site/src/content/docs/getting-started/how-it-works.mdx index b5995732b6..c75ffed90e 100644 --- a/docs-site/src/content/docs/getting-started/how-it-works.mdx +++ b/docs-site/src/content/docs/getting-started/how-it-works.mdx @@ -60,6 +60,10 @@ account before the request is forwarded upstream. The rule is intentionally spli This is separate from reset-window routing: routing chooses an account for incoming work, while activation sends one request to a specific opted-in account only after its own reset is due. +**Downgrade note:** Before running an older version, remove only `nextFiveHourResetAt` and +`nextWeeklyResetAt` from automatic activation settings. Older strict readers reject these new +fields and can disable the entire activation settings block. + ## Sub-agent model selection On a fresh install, `subagentModels` features `gpt-6-astra`, the GPT-5.6 Sol/Terra/Luna trio, and diff --git a/docs-site/src/content/docs/ja/getting-started/how-it-works.mdx b/docs-site/src/content/docs/ja/getting-started/how-it-works.mdx index 0970b0e7c0..2e0e87f1ee 100644 --- a/docs-site/src/content/docs/ja/getting-started/how-it-works.mdx +++ b/docs-site/src/content/docs/ja/getting-started/how-it-works.mdx @@ -39,6 +39,22 @@ Codex は OpenAI **Responses API** を使います。opencodex は HTTP と Serv `GET /api/codex-auth/accounts?refresh=1` でクォータを強制再照会できます。成功した上流 応答はクォータヘッダーを保存し、429 はアカウントをクールダウンに置き、401/403 は再認証必要状態としてマークします。 +- **アイドル状態の利用枠も自動開始できます。** 詳細設定の自動開始はデフォルトでオフです。 + 現在のメインアカウントと追加アカウントが報告する 5 時間枠・週間枠をまとめて切り替えます。 + 新しく追加したアカウントには自動で適用されません。Pool モードでは、期限が来たアカウントへ + 利用枠を消費する最小限の非保存リクエストを送ります。同時に期限が来た枠は 1 回にまとめ、 + 一時停止中・再認証が必要なアカウントやメインアカウントのハードロックは回避しません。 + 完了した応答のクォータヘッダーを保存し、有効なアイドルアカウントの古いメタデータも + 最大 5 分に 1 回更新するため、ダッシュボードを開いておく必要はありません。 + 観測済みの期限は完了まで再起動をまたいで保持し、後の照会で動く時刻に上書きされません。 + メタデータ照会は既存の回数制限付き認証回復を使い、推論の 401 は拒否された認証情報を + 再認証必要として扱います。失敗ログには不透明なアカウントラベルと安全な状態理由だけを記録します。 + これは入力リクエストのアカウント選択とは別の機能です。 + +**旧バージョンへ戻す場合:** 自動開始設定の `nextFiveHourResetAt` と `nextWeeklyResetAt` だけを +削除してから旧バージョンを起動してください。旧版の厳密な設定検証はこれらの新しいフィールドを +受け付けず、自動開始設定全体を無効にする場合があります。 + ## サブエージェントモデルの選択 新規インストールすると `subagentModels` のデフォルトで `gpt-6-astra`、GPT-5.6 Sol/Terra/Luna の 3 モデル、 diff --git a/docs-site/src/content/docs/ko/getting-started/how-it-works.mdx b/docs-site/src/content/docs/ko/getting-started/how-it-works.mdx index e2a75024d1..1538c701b3 100644 --- a/docs-site/src/content/docs/ko/getting-started/how-it-works.mdx +++ b/docs-site/src/content/docs/ko/getting-started/how-it-works.mdx @@ -39,6 +39,22 @@ pool 계정을 고를 수 있습니다. 규칙은 의도적으로 둘로 나뉩 `GET /api/codex-auth/accounts?refresh=1`로 할당량을 강제 재조회할 수 있습니다. 성공한 업스트림 응답은 할당량 헤더를 저장하고, 429는 계정을 cooldown에 넣으며, 401/403은 재인증 필요 상태로 표시합니다. +- **유휴 상태의 할당량 창도 자동으로 활성화할 수 있습니다.** 고급 설정의 자동 활성화는 기본적으로 + 꺼져 있으며 현재 메인 계정과 추가 계정이 보고하는 5시간·주간 창을 함께 제어합니다. + 새로 추가한 계정에는 자동 적용되지 않습니다. Pool 모드에서는 만료된 창의 정확한 계정으로 + 할당량을 소비하는 최소한의 비저장 요청을 보내며, 동시에 만료된 창은 요청 하나로 묶습니다. + 일시 중지 또는 재인증이 필요한 계정은 건너뛰고 메인 계정의 하드록도 준수합니다. + 완료 응답의 할당량 헤더를 반영하고, 활성화 대상인 유휴 계정의 오래된 메타데이터는 최대 5분에 + 한 번 갱신하므로 대시보드를 열어 둘 필요가 없습니다. 관측한 만료 시점은 활성화가 끝날 때까지 + 재시작 후에도 유지되어, 나중의 조회에서 시점이 밀려도 대기 작업을 잃지 않습니다. + 메타데이터 조회에는 기존의 횟수 제한 인증 복구를 사용합니다. 추론 401은 거부된 자격 증명을 + 재인증 필요로 표시하며, 실패 로그에는 불투명한 계정 라벨과 안전한 상태 사유만 기록합니다. + 이 기능은 들어오는 요청의 계정을 선택하는 라우팅과 별개입니다. + +**다운그레이드 안내:** 이전 버전을 실행하기 전에 자동 활성화 설정에서 `nextFiveHourResetAt`과 +`nextWeeklyResetAt`만 제거하세요. 이전 버전의 엄격한 설정 검증은 이 새 필드를 허용하지 않아 +자동 활성화 설정 전체를 비활성화할 수 있습니다. + ## Sub-agent 모델 선택 새로 설치하면 `subagentModels` 기본값으로 `gpt-6-astra`, GPT-5.6 Sol/Terra/Luna 세 모델, diff --git a/docs-site/src/content/docs/ru/getting-started/how-it-works.mdx b/docs-site/src/content/docs/ru/getting-started/how-it-works.mdx index d18b081b12..ceeff22531 100644 --- a/docs-site/src/content/docs/ru/getting-started/how-it-works.mdx +++ b/docs-site/src/content/docs/ru/getting-started/how-it-works.mdx @@ -43,6 +43,25 @@ Codex даже не догадывается, что общается не с Op провайдера сохраняют заголовки квоты, 429 отправляет аккаунт в кулдаун, а 401/403 помечает его как требующий повторной аутентификации. +- **Неиспользуемые окна квоты можно активировать автоматически.** В расширенных настройках эта + функция по умолчанию выключена и управляет доступными 5-часовыми и недельными окнами всех + текущих основных и добавленных аккаунтов. Новые аккаунты не включаются автоматически. + В режиме Pool после наступления срока отправляется минимальный несохраняемый запрос именно + через нужный аккаунт; он расходует квоту. Одновременные сбросы объединяются в один запрос. + Приостановленные аккаунты и аккаунты, требующие повторной аутентификации, пропускаются; + жёсткая блокировка основного аккаунта также соблюдается. Заголовки квоты успешного ответа + обновляют кеш, а устаревшие метаданные включённых подходящих аккаунтов обновляются не чаще + одного раза в пять минут даже без открытой панели. Наблюдаемые сроки сохраняются до завершения + активации, включая перезапуски, поэтому сдвиг времени при следующем опросе не удаляет ожидающую + работу. Опрос использует существующее ограниченное восстановление аутентификации; ответ 401 + на запрос модели помечает отклонённые учётные данные для повторной аутентификации. + В журнал ошибок попадают только непрозрачная метка аккаунта и безопасная причина состояния. + Активация отличается от выбора аккаунта для входящего запроса. + +**Возврат к старой версии:** перед её запуском удалите только `nextFiveHourResetAt` и +`nextWeeklyResetAt` из настроек автоматической активации. Строгий валидатор старой версии +не принимает эти новые поля и может отключить весь блок настроек активации. + ## Выбор модели для подагентов После чистой установки `subagentModels` включает `gpt-6-astra`, тройку GPT-5.6 Sol/Terra/Luna и diff --git a/docs-site/src/content/docs/zh-cn/getting-started/how-it-works.mdx b/docs-site/src/content/docs/zh-cn/getting-started/how-it-works.mdx index e90bcb38b8..d234dd1ff5 100644 --- a/docs-site/src/content/docs/zh-cn/getting-started/how-it-works.mdx +++ b/docs-site/src/content/docs/zh-cn/getting-started/how-it-works.mdx @@ -21,6 +21,31 @@ Codex 使用 OpenAI **Responses API**。opencodex 接收通过 HTTP 与 Server-S └─────────────────────────────────────────────────────────────────────┘ ``` +![Codex 多账号路由:已有线程保持账号绑定,新会话可以查询额度并选择使用量更低的健康账号。](../../../../assets/multi-auth-routing.svg) + +## Codex 认证账号选择 + +当选择的 provider 使用 ChatGPT/Codex 直通时,opencodex 可以在转发请求前从已保存的账号池中选择账号。 + +- **已有线程保持绑定。** 线程绑定到开始时所选的账号代次,长时间运行的 SSH、tmux 或移动端 + Codex 会话不会在正常对话过程中重新分配账号。 +- **新会话可以重新分配。** 新线程按 `accountPoolStrategy` 选择可用账号,默认为 `quota`,也支持 + `round-robin` 和 `fill-first`。`quota` 比较已知的 5 小时、每周和 30 天额度使用量,并在当前账号 + 超过 `autoSwitchThreshold` 时选择使用量更低的账号。冷却中或需要重新认证的账号会被跳过。 +- **额度和失败信号参与路由。** 仪表盘通过 `GET /api/codex-auth/accounts?refresh=1` 强制刷新额度。 + 成功的上游响应会更新额度头信息;429 使账号进入冷却,401/403 会将账号标记为需要重新认证。 +- **空闲额度窗口可以自动激活。** 高级设置中的自动激活默认关闭,统一控制当前主账号和附加账号 + 已报告的 5 小时及每周窗口;新添加账号不会自动启用。在 Pool 模式下,窗口到期后会通过对应账号 + 发送最小化、不保存的请求,并消耗少量额度;同时到期的窗口合并为一次请求。暂停、需要重新认证 + 的账号会被跳过,主账号硬锁限制也会得到遵守。成功响应的额度头会更新缓存;已启用且符合条件的 + 空闲账号还会每隔至少 5 分钟刷新过期的额度元数据,无需保持仪表盘打开。已观察到的到期时间会保留 + 至激活完成,重启或后续查询的时间变化不会丢失待处理窗口。元数据查询复用现有的有次数限制的认证 + 恢复逻辑;推理请求返回 401 时,被拒绝的凭据会标记为需要重新认证。失败日志仅记录不透明账号标签 + 和安全的状态原因。该功能独立于为传入请求选择账号的路由逻辑。 + +**降级说明:** 运行旧版本前,请仅移除自动激活设置中的 `nextFiveHourResetAt` 和 +`nextWeeklyResetAt`。旧版严格校验不接受这两个新字段,可能因此禁用整个自动激活设置块。 + ## Sub-agent 模型选择 全新安装会通过 `subagentModels` 在 Codex 的 sub-agent 选择器中优先显示 `gpt-6-astra`、GPT-5.6 diff --git a/src/codex/quota-auto-refresh-state.ts b/src/codex/quota-auto-refresh-state.ts index 72b7d5828c..75ebe0db64 100644 --- a/src/codex/quota-auto-refresh-state.ts +++ b/src/codex/quota-auto-refresh-state.ts @@ -7,6 +7,7 @@ export const retryAfterByAccount = new Map(); export const scheduledByAccount = new Map(); export const quotaRefreshAfterByAccount = new Map(); +/** Drop every activation record when its account is removed. */ export function forgetCodexQuotaAutoRefreshAccount(accountId: string): void { completedByAccount.delete(accountId); retryAfterByAccount.delete(accountId); @@ -14,6 +15,7 @@ export function forgetCodexQuotaAutoRefreshAccount(accountId: string): void { quotaRefreshAfterByAccount.delete(accountId); } +/** Clear the dependency-free activation bookkeeping for isolated tests. */ export function resetCodexQuotaAutoRefreshStateForTests(): void { completedByAccount.clear(); retryAfterByAccount.clear(); diff --git a/src/codex/quota-auto-refresh.ts b/src/codex/quota-auto-refresh.ts index b61cc1467e..bb3d001e2e 100644 --- a/src/codex/quota-auto-refresh.ts +++ b/src/codex/quota-auto-refresh.ts @@ -51,6 +51,7 @@ export interface CodexQuotaAutoRefreshRunDeps { let inFlight: Promise | null = null; +/** Report upstream window availability separately from persisted spending intent. */ export function codexQuotaAutoRefreshStatus( config: OcxConfig, accountId: string, @@ -66,6 +67,7 @@ export function codexQuotaAutoRefreshStatus( }; } +/** Select retained, enabled boundaries newer than both durable and in-memory completions. */ export function dueCodexQuotaAutoRefreshWindows( config: OcxConfig, accountId: string, @@ -145,17 +147,20 @@ function rememberWindows(config: OcxConfig, accountId: string, quota: StoredAcco } } +/** Load metadata recovery only when an opted-in account actually needs a probe. */ async function refreshQuota(config: OcxConfig, accountId: string): Promise { const { refreshCodexQuotaForActivation } = await import("./auth-api"); await refreshCodexQuotaForActivation(config, accountId); } +/** Keep billable main-account work behind the current pause, reauth and hard-lock policy. */ function mainWarmupRestricted(config: OcxConfig): boolean { return isMainAccountHardLocked(config) || isCodexAccountPaused(config, MAIN_CODEX_ACCOUNT_ID) || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID); } +/** Warm the exact account and fence quota/reauth publication to the dispatched credential. */ async function warmAccount(config: OcxConfig, accountId: string): Promise { const writerGeneration = captureConfigGeneration(); if (accountId !== MAIN_CODEX_ACCOUNT_ID) { @@ -207,6 +212,7 @@ async function warmAccount(config: OcxConfig, accountId: string): Promise, @@ -247,6 +254,7 @@ function retryPendingMarkers( } } +/** Coalesce sweeps, refresh stale metadata and activate due accounts with bounded concurrency. */ export async function runCodexQuotaAutoRefresh( config: OcxConfig, now = Date.now(), @@ -266,6 +274,7 @@ export async function runCodexQuotaAutoRefresh( MAIN_CODEX_ACCOUNT_ID, ...(config.codexAccounts ?? []).filter(isSelectableCodexPoolAccount).map(account => account.id), ]; + /** Recheck spending authorization after asynchronous metadata work. */ const eligible = (accountId: string) => { const setting = config.codexQuotaAutoRefresh?.[accountId]; const provider = config.providers[OPENAI_CODEX_PROVIDER_ID]; @@ -314,6 +323,7 @@ export async function runCodexQuotaAutoRefresh( return inFlight; } +/** Attach activation to the shared minute sweep and return its owner-scoped cleanup. */ export function registerCodexQuotaAutoRefreshWorker(config: OcxConfig): () => void { return registerStateSweepAfterTick({ name: "codex-quota-auto-refresh", @@ -321,6 +331,7 @@ export function registerCodexQuotaAutoRefreshWorker(config: OcxConfig): () => vo }); } +/** Clear scheduling and single-flight state between isolated test cases. */ export function resetCodexQuotaAutoRefreshForTests(): void { inFlight = null; resetCodexQuotaAutoRefreshStateForTests(); diff --git a/src/codex/warmup.ts b/src/codex/warmup.ts index cc2f10ac55..5af42490b4 100644 --- a/src/codex/warmup.ts +++ b/src/codex/warmup.ts @@ -215,6 +215,7 @@ async function drainWarmupSse(body: ReadableStream, signal: AbortSig } } +/** Bound one inference attempt and publish metadata only after a successful terminal event. */ async function tryWarmup(options: CodexWarmupOptions, model: string): Promise { const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS; if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0 || timeoutMs > MAX_TIMEOUT_MS) { diff --git a/tests/codex-integration/codex-quota-auto-refresh.test.ts b/tests/codex-integration/codex-quota-auto-refresh.test.ts index 7bbe2ae73e..e0d765dea3 100644 --- a/tests/codex-integration/codex-quota-auto-refresh.test.ts +++ b/tests/codex-integration/codex-quota-auto-refresh.test.ts @@ -11,6 +11,7 @@ import { } from "../../src/codex/quota-auto-refresh"; import { clearAccountQuota, + getAccountQuota, setAccountQuotaFromParsed, type StoredAccountQuota, } from "../../src/codex/quota"; @@ -18,11 +19,30 @@ import { handleManagementAPI, type ManagementApiDeps } from "../../src/server/ma import { loadConfig, readConfigDiagnostics, validateConfigCandidate } from "../../src/config"; import type { OcxConfig } from "../../src/types"; import { startupHealthFixture } from "../helpers/startup-health"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearAccountNeedsReauth, isAccountNeedsReauth } from "../../src/codex/account-runtime-state"; const NOW = 1_800_000_000_000; const RESET_SECONDS = NOW / 1000; let testHome = ""; let previousHome: string | undefined; +let previousFetch: typeof fetch; + +function writePoolCredential(accessToken = "activation-fixture") { + saveCodexAccountCredential("pool-a", { + accessToken, refreshToken: "activation-refresh-fixture", + expiresAt: NOW + 86_400_000, chatgptAccountId: "activation-workspace-fixture", + }); +} + +function completedWithQuota(resetAt: number) { + return new Response('data: {"type":"response.completed"}\n\n', { headers: { + "content-type": "text/event-stream", + "x-codex-primary-used-percent": "0", + "x-codex-primary-window-minutes": "300", + "x-codex-primary-reset-at": String(resetAt), + } }); +} function config(): OcxConfig { return { @@ -85,6 +105,7 @@ function putSettings(cfg: OcxConfig, value: unknown): Promise { } beforeEach(() => { + previousFetch = globalThis.fetch; previousHome = process.env.OPENCODEX_HOME; testHome = mkdtempSync(join(tmpdir(), "ocx-quota-auto-refresh-")); process.env.OPENCODEX_HOME = testHome; @@ -93,6 +114,8 @@ beforeEach(() => { }); afterEach(() => { + globalThis.fetch = previousFetch; + clearAccountNeedsReauth("pool-a"); clearAccountQuota(); resetCodexQuotaAutoRefreshForTests(); if (previousHome === undefined) delete process.env.OPENCODEX_HOME; @@ -101,6 +124,99 @@ afterEach(() => { }); describe("Codex quota window auto refresh", () => { + test("regression: successive idle windows use completed response quota headers", async () => { + const cfg = config(); + cfg.codexQuotaAutoRefresh = { "pool-a": { fiveHour: true } }; + writeFileSync(join(testHome, "config.json"), JSON.stringify(cfg)); + writePoolCredential(); + setAccountQuotaFromParsed("pool-a", quota({ shortPercent: 100 })); + let calls = 0; + globalThis.fetch = Object.assign(async () => completedWithQuota(RESET_SECONDS + ++calls * 18_000), + { preconnect: previousFetch.preconnect }); + const deps = { refreshQuota: async () => {} }; + await runCodexQuotaAutoRefresh(cfg, NOW, deps); + expect(getAccountQuota("pool-a")).toMatchObject({ shortPercent: 0, shortResetAt: RESET_SECONDS + 18_000 }); + resetCodexQuotaAutoRefreshForTests(); + await runCodexQuotaAutoRefresh(loadConfig(), NOW + 18_000_000, deps); + expect(calls).toBe(2); + expect(loadConfig().codexQuotaAutoRefresh?.["pool-a"]?.lastFiveHourResetAt).toBe(NOW + 18_000_000); + }); + + test("regression: failed windows survive shifted metadata and restart", async () => { + let cfg = config(); + writeFileSync(join(testHome, "config.json"), JSON.stringify(cfg)); + let observed = quota(); + let calls = 0; + const deps = { + getQuota: (id: string) => id === "pool-a" ? observed : null, + refreshQuota: async () => {}, + warmAccount: async () => { if (++calls === 1) throw new Error("fixture failure"); }, + }; + await runCodexQuotaAutoRefresh(cfg, NOW, deps); + expect(loadConfig().codexQuotaAutoRefresh?.["pool-a"]).toMatchObject({ + nextFiveHourResetAt: NOW, nextWeeklyResetAt: NOW, + }); + observed = quota({ shortResetAt: RESET_SECONDS + 18_000, weeklyResetAt: RESET_SECONDS + 604_800 }); + resetCodexQuotaAutoRefreshForTests(); + cfg = loadConfig(); + await runCodexQuotaAutoRefresh(cfg, NOW + 300_000, deps); + expect(calls).toBe(2); + expect(loadConfig().codexQuotaAutoRefresh?.["pool-a"]).toMatchObject({ + lastFiveHourResetAt: NOW, lastWeeklyResetAt: NOW, + }); + await runCodexQuotaAutoRefresh(cfg, NOW + 300_001, deps); + expect(calls).toBe(2); + }); + + test("regression: stale idle metadata refresh is bounded and disabled accounts do not probe", async () => { + const cfg = config(); + let probes = 0; + let warmups = 0; + const deps = { + getQuota: () => null, + refreshQuota: async () => { probes += 1; }, + warmAccount: async () => { warmups += 1; }, + }; + await runCodexQuotaAutoRefresh(cfg, NOW, deps); + await runCodexQuotaAutoRefresh(cfg, NOW + 299_999, deps); + expect(probes).toBe(1); + await runCodexQuotaAutoRefresh(cfg, NOW + 300_000, deps); + expect(probes).toBe(2); + cfg.codexQuotaAutoRefresh = {}; + await runCodexQuotaAutoRefresh(cfg, NOW + 600_000, deps); + expect(probes).toBe(2); + expect(warmups).toBe(0); + }); + + test("regression: inference 401 quarantines a time-valid bearer and stops retries", async () => { + const cfg = config(); + writePoolCredential(); + setAccountQuotaFromParsed("pool-a", quota()); + const request = spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}", { status: 401 })); + try { + const deps = { refreshQuota: async () => {}, persistCompleted: recordMarkers }; + await runCodexQuotaAutoRefresh(cfg, NOW, deps); + expect(isAccountNeedsReauth("pool-a")).toBe(true); + await runCodexQuotaAutoRefresh(cfg, NOW + 300_000, deps); + expect(request).toHaveBeenCalledTimes(1); + expect(cfg.codexQuotaAutoRefresh?.["pool-a"]?.lastWeeklyResetAt).toBeUndefined(); + } finally { request.mockRestore(); } + }); + + test.each([200, 401])("regression: late HTTP %i cannot publish quota or quarantine replacement credentials", async status => { + const cfg = config(); + writePoolCredential(); + setAccountQuotaFromParsed("pool-a", quota({ shortPercent: 90 })); + globalThis.fetch = Object.assign(async () => { + writePoolCredential("replacement-fixture"); + return status === 200 ? completedWithQuota(RESET_SECONDS + 18_000) : new Response("{}", { status }); + }, { preconnect: previousFetch.preconnect }); + await runCodexQuotaAutoRefresh(cfg, NOW, { refreshQuota: async () => {}, persistCompleted: recordMarkers }); + expect(isAccountNeedsReauth("pool-a")).toBe(false); + expect(getAccountQuota("pool-a")).toMatchObject({ shortPercent: 90, shortResetAt: RESET_SECONDS }); + expect(cfg.codexQuotaAutoRefresh?.["pool-a"]?.lastFiveHourResetAt).toBeUndefined(); + }); + test("detects only reported 5-hour and weekly capabilities", () => { const cfg = config(); expect(codexQuotaAutoRefreshStatus(cfg, "pool-a", quota())).toEqual({ diff --git a/tests/codex-integration/codex-warmup.test.ts b/tests/codex-integration/codex-warmup.test.ts index 14dd1455ff..d186fb7221 100644 --- a/tests/codex-integration/codex-warmup.test.ts +++ b/tests/codex-integration/codex-warmup.test.ts @@ -12,6 +12,29 @@ afterEach(() => { }); describe("codex warmup", () => { + test("regression: failed streams never publish completion metadata", async () => { + let publications = 0; + globalThis.fetch = (async () => sseResponse('data: {"type":"response.failed"}\n\n')) as typeof fetch; + await expect(warmCodexAccount({ accessToken: "fixture", chatgptAccountId: "fixture", + onCompleted: () => { publications += 1; }, + })).rejects.toMatchObject({ code: "stream_failed" }); + expect(publications).toBe(0); + }); + + test("regression: metadata publication failure never retries completed inference", async () => { + let requests = 0; + let publications = 0; + globalThis.fetch = (async () => { + requests += 1; + return sseResponse('data: {"type":"response.completed"}\n\n'); + }) as typeof fetch; + await expect(warmCodexAccount({ accessToken: "fixture", chatgptAccountId: "fixture", + onCompleted: () => { publications += 1; throw new Error("fixture metadata failure"); }, + })).resolves.toBeUndefined(); + expect(publications).toBe(1); + expect(requests).toBe(1); + }); + test("posts a minimal gpt-5.4-mini Responses stream request and accepts response.completed", async () => { let body: Record | undefined; let auth: string | null = null; From 6bcf86492502e1db00a6f2888c4669298ee40403 Mon Sep 17 00:00:00 2001 From: yhualin Date: Mon, 7 Sep 2026 11:07:32 +0800 Subject: [PATCH 021/116] fix(transport): admit Mihomo IPv6 fake-IP under TUN transparency exception for canonical URLs (cherry picked from commit 38308625da4d2f88d4f4790c0b8ce0eccda13648) Co-authored-by: hualiny <82697947+hualiny@users.noreply.github.com> --- src/lib/provider-outbound.ts | 15 +++++++-------- tests/providers/provider-account-quota.test.ts | 4 ++-- tests/providers/provider-outbound.test.ts | 17 +++++++++++++++++ tests/providers/provider-quota.test.ts | 2 +- 4 files changed, 27 insertions(+), 11 deletions(-) diff --git a/src/lib/provider-outbound.ts b/src/lib/provider-outbound.ts index 02bdbc2077..95341573d1 100644 --- a/src/lib/provider-outbound.ts +++ b/src/lib/provider-outbound.ts @@ -143,11 +143,12 @@ async function providerOutboundRequest( // below reason about the same value. `null` here means "no proxy fetch would actually use", // even if some other proxy variable is set. const effectiveProxy = effectiveProxyFor(parsed); - const allowMihomoIpv6FakeIp = effectiveProxy !== null && !noProxyMatches(parsed); + const isCanonicalUrl = dependencies.isCanonicalUrl ?? (() => false); + const allowMihomoIpv6FakeIp = (effectiveProxy !== null && !noProxyMatches(parsed)) + || transparentFakeIpException(url, parsed, isCanonicalUrl, name); const resolveAddresses = dependencies.resolveAddresses ?? resolvePublicAddresses; const pinnedGet = dependencies.pinnedGet ?? pinnedHttpGet; const pinnedPost = dependencies.pinnedPost ?? pinnedHttpPost; - const isCanonicalUrl = dependencies.isCanonicalUrl ?? (() => false); const allowPrivate = providerAllowsPrivateNetwork(name, provider); let resolved: Awaited>; try { @@ -169,11 +170,9 @@ async function providerOutboundRequest( // pinned to the registry destination independently. allowBenchmarkAddresses: (proxyConfigured && !noProxyMatches(parsed)) || transparentFakeIpException(url, parsed, isCanonicalUrl, name), - // Mihomo IPv6 fake-IP (fdfe:dcba:9876::/48) answers are admitted on a stricter gate - // than the benchmark range: the proxy must be the one fetch will use for this URL's - // scheme, and the request below is then bound to it explicitly (#3462). A ULA answer - // is otherwise indistinguishable from a real private host, so proxy presence alone - // is not enough. + // Mihomo IPv6 fake-IP (fdfe:dcba:9876::/48) answers are admitted either when bound + // to a scheme-matched proxy (#3462) or under the TUN transparency exception for a + // canonical registry/accounting destination. allowMihomoIpv6FakeIp, }); } catch (error) { @@ -191,7 +190,7 @@ async function providerOutboundRequest( warnProxyBoundaryOnce(); // When the Mihomo exception could have admitted an answer, pin the transport to the // proxy the admission assumed instead of letting fetch re-infer it from the environment. - const proxy = allowMihomoIpv6FakeIp ? effectiveProxy : undefined; + const proxy = (allowMihomoIpv6FakeIp && effectiveProxy) ? effectiveProxy : undefined; return globalThis.fetch(url, { ...init, method, redirect: "manual", ...(proxy ? { proxy } : {}) }); } if (proxyConfigured && resolved.privateNetwork && !noProxyMatches(parsed)) { diff --git a/tests/providers/provider-account-quota.test.ts b/tests/providers/provider-account-quota.test.ts index 1b940d71d0..e8e05de9d6 100644 --- a/tests/providers/provider-account-quota.test.ts +++ b/tests/providers/provider-account-quota.test.ts @@ -796,8 +796,8 @@ describe("google-antigravity per-account quota (#1082)", () => { expect(posted).toHaveLength(urls.length * 2); for (const url of urls) { expect(resolved.filter(row => row.url === url)).toEqual([ - { url, benchmark: true, private: false, mihomo: false }, - { url, benchmark: true, private: false, mihomo: false }, + { url, benchmark: true, private: false, mihomo: true }, + { url, benchmark: true, private: false, mihomo: true }, ]); } for (const [auth, project] of [["Bearer agy-first", "proj-first"], ["Bearer agy-second", "proj-second"]]) { diff --git a/tests/providers/provider-outbound.test.ts b/tests/providers/provider-outbound.test.ts index 2853e0e335..1e80634395 100644 --- a/tests/providers/provider-outbound.test.ts +++ b/tests/providers/provider-outbound.test.ts @@ -501,6 +501,23 @@ describe("#3462 Mihomo IPv6 fake-IP admission is gated on the scheme-matched pro expect(resolveOptions).toEqual([{ allowMihomoIpv6FakeIp: false }]); expect(fetchInits).toHaveLength(0); }); + + test("canonical destination without proxy env: admitted under TUN transparentFakeIpException", async () => { + for (const key of proxyKeys) delete process.env[key]; + const { providerOutboundGet } = await import("../../src/lib/provider-outbound"); + const resolveOptions: Captured[] = []; + const { dependencies, captured } = directDependencies(new Response(null, { status: 200 })); + dependencies.isCanonicalUrl = (name, url) => name === "opencode-go" && url === target; + dependencies.resolveAddresses = mock(async (_url: string, options?: Captured) => { + resolveOptions.push({ allowMihomoIpv6FakeIp: options?.allowMihomoIpv6FakeIp }); + return { hostname: "opencode.ai", addresses: [{ address: ULA, family: 6 }, { address: "198.18.0.1", family: 4 }], privateNetwork: false }; + }) as ProviderOutboundDependencies["resolveAddresses"]; + + const response = await providerOutboundGet("opencode-go", { baseUrl: "https://opencode.ai/zen/v1" }, target, {}, dependencies); + expect(response.status).toBe(200); + expect(resolveOptions).toEqual([{ allowMihomoIpv6FakeIp: true }]); + expect(captured.address).toBe("198.18.0.1"); + }); }); describe("effectiveProxyFor picks the variable Bun fetch actually honours", () => { diff --git a/tests/providers/provider-quota.test.ts b/tests/providers/provider-quota.test.ts index 9c12869b04..a8d4bef728 100644 --- a/tests/providers/provider-quota.test.ts +++ b/tests/providers/provider-quota.test.ts @@ -3159,7 +3159,7 @@ describe("fetchProviderQuotaReports", () => { }); const result = await fetchProviderQuotaReports(config(), true); const urls = fallback ? [summaryUrl, modelsUrl] : [summaryUrl]; - expect(resolved).toEqual(urls.map(url => ({ url, benchmark: true, private: false, mihomo: false }))); + expect(resolved).toEqual(urls.map(url => ({ url, benchmark: true, private: false, mihomo: true }))); expect(posted).toEqual(urls.map(url => ({ url, address: "198.18.56.214", tls: true, auth: "Bearer agy-canonical-access", body: JSON.stringify({ project: "agy-canonical-project" }), signal: true }))); expect(result.reports[0]?.source).toBe(fallback ? "google-antigravity:fetchAvailableModels" : "google-antigravity:retrieveUserQuotaSummary"); expect(result.reports[0]?.quota.customWindows).toEqual([{ label: "Gem", percent: fallback ? 25 : 40 }]); From bdd4e460e6ccede4623996fed74db1d32c786ab3 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:27:46 +0900 Subject: [PATCH 022/116] fix(transport): retain IPv6 pinning across proxy mismatches [skip ci] Co-authored-by: hualiny <82697947+hualiny@users.noreply.github.com> --- src/lib/provider-outbound.ts | 6 +- tests/fixtures/provider-outbound-mihomo.ts | 106 +++++++++++++++++++++ tests/providers/provider-outbound.test.ts | 12 +++ 3 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 tests/fixtures/provider-outbound-mihomo.ts diff --git a/src/lib/provider-outbound.ts b/src/lib/provider-outbound.ts index 95341573d1..334f46dad5 100644 --- a/src/lib/provider-outbound.ts +++ b/src/lib/provider-outbound.ts @@ -42,7 +42,7 @@ function pickPinnedAddress(addresses: Array<{ address: string; family: number }> * * Under TUN mode the packet path intercepts the fake-IP destination itself, so a * canonical registry destination whose local DNS answers include Clash fake-IP - * space (198.18.0.0/15) is reachable by pin-connecting through the TUN — no + * space (198.18.0.0/15 or fdfe:dcba:9876::/48) is reachable by pin-connecting through the TUN — no * outbound HTTP(S) proxy env is required. The exception is deliberately narrow: * * - hostname-only: a literal 198.18.x.x URL never reaches it (the literal gate @@ -186,7 +186,9 @@ async function providerOutboundRequest( warnProxyDnsDegradationOnce(); return globalThis.fetch(url, { ...init, method, redirect: "manual" }); } - if (proxyConfigured && !resolved.privateNetwork) { + // A canonical TUN exception with no scheme-matched proxy must retain the + // validated address, even when an unrelated HTTP_PROXY/ALL_PROXY is present. + if (proxyConfigured && !resolved.privateNetwork && (effectiveProxy !== null || !allowMihomoIpv6FakeIp)) { warnProxyBoundaryOnce(); // When the Mihomo exception could have admitted an answer, pin the transport to the // proxy the admission assumed instead of letting fetch re-infer it from the environment. diff --git a/tests/fixtures/provider-outbound-mihomo.ts b/tests/fixtures/provider-outbound-mihomo.ts new file mode 100644 index 0000000000..25eb6eb68f --- /dev/null +++ b/tests/fixtures/provider-outbound-mihomo.ts @@ -0,0 +1,106 @@ +import assert from "node:assert/strict"; +import { mock } from "bun:test"; +import type { ProviderOutboundDependencies } from "../../src/lib/provider-outbound"; +import { PROXY_ENV_KEYS } from "../../src/lib/proxy-env"; + +// Isolate the DNS module mock from other tests while exercising the real classifier. +let answers: { address: string; family: number }[] = []; +mock.module("node:dns/promises", () => ({ lookup: async () => answers })); +const { providerOutboundGet, providerOutboundPost, ProviderOutboundPolicyError } = await import("../../src/lib/provider-outbound"); +const target = "https://opencode.ai/zen/v1/models"; +const fake = { address: "fdfe:dcba:9876::1", family: 6 }; +const body = '{"project":"mihomo-fixture"}'; +let ipv6Pinned = 0; +let proxyBound = 0; +let denied = 0; + +for (const method of ["GET", "POST"] as const) { + async function attempt( + env: Record, + dns: typeof answers, + expected: "pinned" | "proxy" | "denied", + url = target, + proof: "canonical" | "missing" | "noncanonical" = "canonical", + ) { + for (const key of PROXY_ENV_KEYS.flatMap(key => [key, key.toLowerCase()])) delete process.env[key]; + Object.assign(process.env, env); + answers = dns; + let pinnedCalls = 0; + let fetchCalls = 0; + const originalFetch = globalThis.fetch; + const capture: NonNullable = async (requestUrl, address, _signal, options) => { + pinnedCalls++; + assert.equal(expected, "pinned"); + assert.equal(requestUrl, target); + assert.deepEqual(address, fake); + assert.equal(options?.rejectUnauthorized, true); + assert.equal(new Headers(options?.headers).get("authorization"), "Bearer mihomo-fixture"); + return new Response("pinned"); + }; + const dependencies: ProviderOutboundDependencies = { + ...(proof !== "missing" ? { isCanonicalUrl: (name: string, value: string) => proof === "canonical" && name === "opencode-go" && value === url } : {}), + pinnedGet: capture, + pinnedPost: async (requestUrl, address, requestBody, signal, options) => { + assert.equal(method, "POST"); + assert.equal(requestBody, body); + return capture(requestUrl, address, signal, options); + }, + }; + globalThis.fetch = Object.assign(async (input: Parameters[0], init?: RequestInit & { proxy?: string }) => { + fetchCalls++; + assert.equal(expected, "proxy"); + assert.equal(String(input), target); + assert.equal(init?.proxy, "http://127.0.0.1:7897"); + assert.equal(init?.redirect, "manual"); + assert.equal(init?.method, method); + if (method === "POST") assert.equal(init?.body, body); + return new Response("proxy"); + }, { preconnect: originalFetch.preconnect }); + try { + const provider = { baseUrl: "https://opencode.ai/zen/v1" }; + const init = { headers: { authorization: "Bearer mihomo-fixture" } }; + const request = method === "GET" + ? providerOutboundGet("opencode-go", provider, url, init, dependencies) + : providerOutboundPost("opencode-go", provider, url, { ...init, body }, dependencies); + if (expected === "denied") { + await assert.rejects(request, ProviderOutboundPolicyError); + assert.equal(pinnedCalls, 0); + assert.equal(fetchCalls, 0); + denied++; + } else { + assert.equal(await (await request).text(), expected); + assert.equal(pinnedCalls, expected === "pinned" ? 1 : 0); + assert.equal(fetchCalls, expected === "proxy" ? 1 : 0); + if (expected === "pinned") ipv6Pinned++; + else proxyBound++; + } + } finally { + globalThis.fetch = originalFetch; + } + } + + // TUN handles the validated IPv6 address even if unrelated proxy variables exist. + const directEnvs: Record[] = [{}, { HTTP_PROXY: "http://127.0.0.1:7897" }, { ALL_PROXY: "socks5://127.0.0.1:7891" }]; + for (const env of directEnvs) { + await attempt(env, [fake], "pinned"); + } + await attempt({ HTTPS_PROXY: "http://127.0.0.1:7897" }, [fake], "proxy"); + + for (const noProxy of ["opencode.ai", ".opencode.ai", "*"]) { + const noProxyEnvs: Record[] = [{ NO_PROXY: noProxy }, { NO_PROXY: noProxy, HTTPS_PROXY: "http://127.0.0.1:7897" }]; + for (const env of noProxyEnvs) { + await attempt(env, [fake], "denied"); + } + } + for (const address of ["127.0.0.1", "10.0.0.5", "169.254.169.254", "169.254.1.2", "::1", "fd00::1", "fe80::1", "::", "fdfe:dcba:9877::1"]) { + const unsafe = { address, family: address.includes(":") ? 6 : 4 }; + await attempt({}, [fake, unsafe], "denied"); + await attempt({}, [unsafe, fake], "denied"); + } + await attempt({}, [fake], "denied", target, "missing"); + await attempt({}, [fake], "denied", "https://custom.example/v1/models", "noncanonical"); + // Even an erroneous canonical proof cannot admit a literal fake IP. + await attempt({}, [fake], "denied", "https://[fdfe:dcba:9876::1]/v1/models"); +} + +console.log(JSON.stringify({ ipv6Pinned, proxyBound, denied })); diff --git a/tests/providers/provider-outbound.test.ts b/tests/providers/provider-outbound.test.ts index 1e80634395..dca53eefe4 100644 --- a/tests/providers/provider-outbound.test.ts +++ b/tests/providers/provider-outbound.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import type { ProviderOutboundDependencies } from "../../src/lib/provider-outbound"; import { PROXY_ENV_KEYS } from "../../src/lib/proxy-env"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +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]])); @@ -427,6 +428,17 @@ describe("#3462 Mihomo IPv6 fake-IP admission is gated on the scheme-matched pro const ULA = "fdfe:dcba:9876::7e"; const target = "https://opencode.ai/zen/v1/models"; + test("canonical IPv6-only TUN transport preserves pinning and rejects unsafe DNS answers", async () => { + const child = Bun.spawn([process.execPath, fixturePath("provider-outbound-mihomo.ts")], { + cwd: repoRoot(), stdout: "pipe", stderr: "pipe", + }); + 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}`); + expect(JSON.parse(stdout.trim())).toEqual({ ipv6Pinned: 6, proxyBound: 2, denied: 54 }); + }); + async function run(env: Record, opts: { admit: boolean }) { for (const key of proxyKeys) delete process.env[key]; for (const [k, v] of Object.entries(env)) process.env[k] = v; From a814dd3aadace7d3bd0b8dd02b7e2b2705f5b196 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:40:45 +0900 Subject: [PATCH 023/116] test(transport): run DNS fixture in the Bun test loader [skip ci] Co-authored-by: hualiny <82697947+hualiny@users.noreply.github.com> --- tests/fixtures/provider-outbound-mihomo.ts | 7 ++++-- tests/providers/provider-outbound.test.ts | 29 +++++++++++++++------- 2 files changed, 25 insertions(+), 11 deletions(-) diff --git a/tests/fixtures/provider-outbound-mihomo.ts b/tests/fixtures/provider-outbound-mihomo.ts index 25eb6eb68f..e376d8246b 100644 --- a/tests/fixtures/provider-outbound-mihomo.ts +++ b/tests/fixtures/provider-outbound-mihomo.ts @@ -5,7 +5,8 @@ import { PROXY_ENV_KEYS } from "../../src/lib/proxy-env"; // Isolate the DNS module mock from other tests while exercising the real classifier. let answers: { address: string; family: number }[] = []; -mock.module("node:dns/promises", () => ({ lookup: async () => answers })); +let dnsCalls = 0; +mock.module("node:dns/promises", () => ({ lookup: async () => { dnsCalls++; return answers; } })); const { providerOutboundGet, providerOutboundPost, ProviderOutboundPolicyError } = await import("../../src/lib/provider-outbound"); const target = "https://opencode.ai/zen/v1/models"; const fake = { address: "fdfe:dcba:9876::1", family: 6 }; @@ -25,6 +26,7 @@ for (const method of ["GET", "POST"] as const) { for (const key of PROXY_ENV_KEYS.flatMap(key => [key, key.toLowerCase()])) delete process.env[key]; Object.assign(process.env, env); answers = dns; + dnsCalls = 0; let pinnedCalls = 0; let fetchCalls = 0; const originalFetch = globalThis.fetch; @@ -74,6 +76,7 @@ for (const method of ["GET", "POST"] as const) { if (expected === "pinned") ipv6Pinned++; else proxyBound++; } + assert.equal(dnsCalls, url.startsWith("https://[") ? 0 : 1, "hostname requests must use the isolated DNS mock"); } finally { globalThis.fetch = originalFetch; } @@ -103,4 +106,4 @@ for (const method of ["GET", "POST"] as const) { await attempt({}, [fake], "denied", "https://[fdfe:dcba:9876::1]/v1/models"); } -console.log(JSON.stringify({ ipv6Pinned, proxyBound, denied })); +console.log("MIHOMO_RESULT=" + JSON.stringify({ ipv6Pinned, proxyBound, denied })); diff --git a/tests/providers/provider-outbound.test.ts b/tests/providers/provider-outbound.test.ts index dca53eefe4..9907c23664 100644 --- a/tests/providers/provider-outbound.test.ts +++ b/tests/providers/provider-outbound.test.ts @@ -1,7 +1,8 @@ import { afterEach, describe, expect, mock, test } from "bun:test"; -import { mkdtempSync} from "node:fs"; +import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { pathToFileURL } from "node:url"; import type { ProviderOutboundDependencies } from "../../src/lib/provider-outbound"; import { PROXY_ENV_KEYS } from "../../src/lib/proxy-env"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -429,14 +430,24 @@ describe("#3462 Mihomo IPv6 fake-IP admission is gated on the scheme-matched pro const target = "https://opencode.ai/zen/v1/models"; test("canonical IPv6-only TUN transport preserves pinning and rejects unsafe DNS answers", async () => { - const child = Bun.spawn([process.execPath, fixturePath("provider-outbound-mihomo.ts")], { - cwd: repoRoot(), stdout: "pipe", stderr: "pipe", - }); - 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}`); - expect(JSON.parse(stdout.trim())).toEqual({ ipv6Pinned: 6, proxyBound: 2, denied: 54 }); + 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`); + try { + const child = Bun.spawn([process.execPath, "test", childTest], { + cwd: repoRoot(), stdout: "pipe", stderr: "pipe", + }); + 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}`); + 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 { + removeTreeWithRetry(childDir); + } }); async function run(env: Record, opts: { admit: boolean }) { From 3955e10402dd12298a2fd6bf7cf9040daa02eb44 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:25:42 +0900 Subject: [PATCH 024/116] fix(codex): fence main quota activation recovery [skip ci] Co-authored-by: terrytan95 <10609214+terrytan95@users.noreply.github.com> --- src/codex/auth-api.ts | 23 ++++- src/codex/quota-auto-refresh.ts | 19 +++- ...-quota-auto-refresh-main-admission.test.ts | 91 ++++++++++++++++++- 3 files changed, 126 insertions(+), 7 deletions(-) diff --git a/src/codex/auth-api.ts b/src/codex/auth-api.ts index 8ab7f7418f..6768c4fa09 100644 --- a/src/codex/auth-api.ts +++ b/src/codex/auth-api.ts @@ -1838,7 +1838,28 @@ export async function listCodexAuthAccountsSnapshot( /** One opted-in account's metadata; reuse the bounded WHAM 401 recovery and generation fence. */ export async function refreshCodexQuotaForActivation(config: OcxConfig, accountId: string): Promise { if (accountId === MAIN_CODEX_ACCOUNT_ID) { - await fetchMainAccountInfoAttempt(true, 1, undefined, false, false); + const lease = tryAcquireNativeMainProfileClaim(); + if (!lease) return; + try { + reconcileMainCodexAccountRuntimeState(); + if (isAccountNeedsReauth(accountId)) return; + const identityGeneration = captureMainAccountIdentityGeneration(); + const writerGeneration = captureConfigGeneration(); + try { + // Refresh may need an exclusive claim; prepare before WHAM takes its shared claim. + if (!await getValidMainAccountToken({ preserveReauth: true })) return; + } catch (error) { + if (error instanceof MainAccountTokenRefreshError && error.reason === "reauth" + && isMainAccountIdentityGenerationLive(identityGeneration)) { + markAccountNeedsReauth(accountId, writerGeneration); + } + return; + } + if (isAccountNeedsReauth(accountId)) return; + await fetchMainAccountInfoAttempt(true, 1, lease, false, false); + } finally { + lease.release(); + } return; } const account = configuredPoolAccount(config, accountId); diff --git a/src/codex/quota-auto-refresh.ts b/src/codex/quota-auto-refresh.ts index bb3d001e2e..26b88a886c 100644 --- a/src/codex/quota-auto-refresh.ts +++ b/src/codex/quota-auto-refresh.ts @@ -15,7 +15,7 @@ import { isMainAccountHardLocked } from "./main-account-hard-lock"; import { tryAcquireNativeMainProfileClaim } from "./native-main-admission"; import { withNativeMainSharedClaim } from "./native-main-claim"; import { resolveNativeProfileContext } from "./native-profile-store"; -import { captureMainQuotaWriter } from "./main-account-cache"; +import { getMainQuotaCredentialGeneration, observeMainQuotaCredential } from "./main-account-cache"; import { applyAccountQuotaFromUpstreamHeaders, getAccountQuota, type StoredAccountQuota } from "./quota"; import { CodexWarmupError, codexWarmupFailureReason, warmCodexAccount } from "./warmup"; import { @@ -194,18 +194,29 @@ async function warmAccount(config: OcxConfig, accountId: string): Promise { + reconcileMainCodexAccountRuntimeState(); + const current = getMainAccountToken(); + return current?.accessToken === token.accessToken + && current.chatgptAccountId === token.chatgptAccountId + && getMainQuotaCredentialGeneration() === credentialGeneration; + }; try { await warmCodexAccount({ ...token, onCompleted: headers => { - if (writer) applyAccountQuotaFromUpstreamHeaders(accountId, headers, writerGeneration, writer); + if (writer && credentialStillLive()) { + applyAccountQuotaFromUpstreamHeaders(accountId, headers, writerGeneration, writer); + } } }); } catch (error) { if (error instanceof CodexWarmupError && error.status === 401 - && getMainAccountToken()?.accessToken === token.accessToken) { + && credentialStillLive()) { markAccountNeedsReauth(accountId, writerGeneration); } throw error; } + if (!credentialStillLive()) return false; }); } finally { lease.release(); diff --git a/tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts b/tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts index d676690c09..88080d5a4d 100644 --- a/tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts +++ b/tests/codex-integration/codex-quota-auto-refresh-main-admission.test.ts @@ -10,7 +10,7 @@ import { getMainAccountHardLockStatus } from "../../src/codex/main-account-hard- import { setMainAccountPlan } from "../../src/codex/main-account"; import * as mainAccount from "../../src/codex/main-account"; import * as nativeClaim from "../../src/codex/native-main-claim"; -import { clearAccountQuota, flushQuotaObservationsForTests, setAccountQuotaFromParsed } from "../../src/codex/quota"; +import { clearAccountQuota, flushQuotaObservationsForTests, getAccountQuota, getMainPolicyQuota, setAccountQuotaFromParsed } from "../../src/codex/quota"; import { resetCodexQuotaAutoRefreshForTests, runCodexQuotaAutoRefresh, type CodexQuotaAutoRefreshWindows } from "../../src/codex/quota-auto-refresh"; import { getNativeMainProfileRequestCount, resetLifecycleDrainStateForTests } from "../../src/server/lifecycle"; import { flushConfigDirHardeningForTests } from "../../src/config/paths"; @@ -23,6 +23,7 @@ const RESET_SECONDS = 1_700_000_000; const RESET_MILLISECONDS = 1_700_000_000_000; const responsesUrl = "https://chatgpt.com/backend-api/codex/responses"; const tokenUrl = "https://auth.openai.com/oauth/token"; +const whamUrl = "https://chatgpt.com/backend-api/wham/usage"; let home: string; let previousHome: string | undefined; let previousCodexHome: string | undefined; @@ -71,7 +72,7 @@ function installFetch(handler: (url: string, init?: RequestInit) => Promise[0], init?: RequestInit) => { calls.push(String(input)); - expect([tokenUrl, responsesUrl]).toContain(String(input)); + expect([tokenUrl, responsesUrl, whamUrl]).toContain(String(input)); expect(getNativeMainProfileRequestCount()).toBe(1); return handler(String(input), init); }, { preconnect: previousFetch.preconnect }); @@ -137,6 +138,92 @@ afterEach(async () => { }); describe("quota auto-refresh native-main admission", () => { + test("stale metadata prepares an expired main token before WHAM and activation", async () => { + const cfg = config(); + writeMain(bearer(true)); + const cached = getAccountQuota(MAIN); + if (!cached) throw new Error("Expected cached main quota"); + cached.updatedAt = now - 300_000; + const fresh = bearer(); + const calls = installFetch(async (url, init) => { + if (url === tokenUrl) { + return Response.json({ access_token: fresh, refresh_token: "fixture-rotated", expires_in: 86_400 }); + } + expect(new Headers(init?.headers).get("authorization")).toBe(`Bearer ${fresh}`); + if (url === whamUrl) return Response.json({ plan_type: "plus", rate_limit: { + primary_window: { used_percent: 0, limit_window_seconds: 18_000, reset_at: RESET_SECONDS }, + secondary_window: { used_percent: 0, limit_window_seconds: 604_800, reset_at: RESET_SECONDS }, + } }); + return completedResponse(); + }); + await runCodexQuotaAutoRefresh(cfg, now, { persistCompleted: recordMarkers }); + expect(calls).toEqual([tokenUrl, whamUrl, responsesUrl]); + expect(isAccountNeedsReauth(MAIN)).toBe(false); + expect(cfg.codexQuotaAutoRefresh?.[MAIN]?.lastFiveHourResetAt).toBe(RESET_MILLISECONDS); + expect(getNativeMainProfileRequestCount()).toBe(0); + }); + + test.each(["bearer", "workspace", "missing"] as const)( + "%s replacement during main SSE cannot publish old quota or completion markers", async change => { + const cfg = config(); + const entered = deferred(); + let controller!: ReadableStreamDefaultController; + const calls = installFetch(async () => new Response(new ReadableStream({ + start(value) { controller = value; }, + pull() { entered.resolve(); }, + }), { headers: { + "content-type": "text/event-stream", + "x-codex-primary-used-percent": "0", + "x-codex-primary-window-minutes": "300", + "x-codex-primary-reset-at": String(RESET_SECONDS + 18_000), + } })); + const run = runCodexQuotaAutoRefresh(cfg, now, { persistCompleted: recordMarkers }); + try { + await Promise.race([entered.promise, run.then(() => { throw new Error("SSE was never reached"); })]); + const workspace = change === "workspace" ? "fixture-replacement-workspace" : accountId; + if (change === "missing") writeFileSync(join(home, "auth.json"), "{}"); + else writeMain("fixture-replacement-token", workspace); + reconcileMainCodexAccountRuntimeState(); + const writer = captureMainQuotaWriter(workspace); + if (!writer) throw new Error("Expected current quota owner"); + setAccountQuotaFromParsed(MAIN, { shortPercent: 77, shortWindowSeconds: 18_000, + shortResetAt: RESET_SECONDS + 900 }, undefined, writer); + const quotaBefore = { ...getAccountQuota(MAIN) }; + const policyBefore = { ...getMainPolicyQuota() }; + controller.enqueue(new TextEncoder().encode('data: {"type":"response.completed"}\n\n')); + controller.close(); + await run; + expect(calls).toEqual([responsesUrl]); + expect(getAccountQuota(MAIN)).toEqual(quotaBefore); + expect(getMainPolicyQuota()).toEqual(policyBefore); + expect(cfg.codexQuotaAutoRefresh?.[MAIN]?.lastFiveHourResetAt).toBeUndefined(); + expect(cfg.codexQuotaAutoRefresh?.[MAIN]?.lastWeeklyResetAt).toBeUndefined(); + expect(isAccountNeedsReauth(MAIN)).toBe(false); + expect(getNativeMainProfileRequestCount()).toBe(0); + } finally { + try { controller?.close(); } catch { /* Already closed after completion. */ } + await run; + } + }, + ); + + test("late main 401 cannot quarantine a replacement credential", async () => { + const cfg = config(); + const entered = deferred(); + const response = deferred(); + installFetch(async () => { entered.resolve(); return response.promise; }); + const run = runCodexQuotaAutoRefresh(cfg, now, { persistCompleted: recordMarkers }); + try { + await Promise.race([entered.promise, run.then(() => { throw new Error("Inference was never reached"); })]); + writeMain("fixture-replacement-token"); + response.resolve(new Response("{}", { status: 401 })); + await run; + expect(isAccountNeedsReauth(MAIN)).toBe(false); + expect(cfg.codexQuotaAutoRefresh?.[MAIN]?.lastWeeklyResetAt).toBeUndefined(); + expect(getNativeMainProfileRequestCount()).toBe(0); + } finally { response.resolve(new Response("{}", { status: 401 })); await run; } + }); + test("owned reconciliation activates retained99 before token preparation when current identity was not observed", async () => { const cfg = config(); const writer = captureMainQuotaWriter(accountId); From b67f452c49904dbda2e0be435c2e34d5a064172f Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:06:44 +0900 Subject: [PATCH 025/116] test(transport): pass the test-run lease to the child fixture [skip ci] Co-authored-by: hualiny <82697947+hualiny@users.noreply.github.com> --- tests/providers/provider-outbound.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/providers/provider-outbound.test.ts b/tests/providers/provider-outbound.test.ts index 9907c23664..54c82a5435 100644 --- a/tests/providers/provider-outbound.test.ts +++ b/tests/providers/provider-outbound.test.ts @@ -436,7 +436,7 @@ describe("#3462 Mihomo IPv6 fake-IP admission is gated on the scheme-matched pro writeFileSync(childTest, `import { test } from "bun:test";\ntest("Mihomo matrix", async () => { await import(${JSON.stringify(pathToFileURL(fixturePath("provider-outbound-mihomo.ts")).href)}); });\n`); try { const child = Bun.spawn([process.execPath, "test", childTest], { - cwd: repoRoot(), stdout: "pipe", stderr: "pipe", + cwd: repoRoot(), env: { ...process.env }, stdout: "pipe", stderr: "pipe", }); const [stdout, stderr, exitCode] = await Promise.all([ new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited, From edd396c62ec349fa686309c1ee55e02ebad6b903 Mon Sep 17 00:00:00 2001 From: makesomethingshit Date: Mon, 7 Sep 2026 15:35:53 +0900 Subject: [PATCH 026/116] fix(opencode-go): carry session affinity through Pi native chat [skip ci] (cherry picked from commit fbb214f92a7dc75f89d0d835fdb95136d61f380a) Co-authored-by: makesomethingshit <246213378+makesomethingshit@users.noreply.github.com> (cherry picked from commit 7e45a95f70689dfe1eb313c4af9aecbf2c44cdb6) --- src/clients/config-export.ts | 2 + src/server/chat-completions.ts | 7 +++ src/server/responses/core.ts | 3 +- tests/config/client-config-export.test.ts | 6 ++- .../opencode-go-session-header.test.ts | 52 ++++++++++++++++++- 5 files changed, 67 insertions(+), 3 deletions(-) diff --git a/src/clients/config-export.ts b/src/clients/config-export.ts index 8fb42f311d..e1744c2209 100644 --- a/src/clients/config-export.ts +++ b/src/clients/config-export.ts @@ -695,6 +695,7 @@ export interface PiProviderBlock { baseUrl: string; api: string; apiKey: string; + compat?: { sendSessionAffinityHeaders: boolean }; models: PiModelEntry[]; } @@ -859,6 +860,7 @@ function buildPiClientConfig(ctx: ExportContext): PiGeneratedConfig { baseUrl: ctx.baseUrl, api: PI_API_DIALECT, apiKey: LOOPBACK_API_KEY_PLACEHOLDER, + compat: { sendSessionAffinityHeaders: true }, models, }, }, diff --git a/src/server/chat-completions.ts b/src/server/chat-completions.ts index e7fd04f42d..7e69010636 100644 --- a/src/server/chat-completions.ts +++ b/src/server/chat-completions.ts @@ -25,6 +25,8 @@ import { estimateTokens } from "../lib/token-estimate"; import { NoEligiblePolicyCandidateError, UnknownRoutingPolicyError, routeModel } from "../router"; import { evidenceFromBody } from "../routing/request-evidence"; import { resolveWireProtocolOverride } from "./adapter-resolve"; +import { resolveOpenCodeGoTransport } from "../providers/opencode-go-transport"; +import { normalizeLogConversationId, sessionLaneIdFromRequest } from "./request-log-conversation"; import type { OcxConfig } from "../types"; import { readJsonRequestBody } from "./request-decompress"; import { @@ -136,6 +138,8 @@ async function handleChatCompletionsWithBudget( let chatNativeRoute: ReturnType | null = null; try { const route = routeModel(config, chatBody.model as string, evidenceFromBody(chatBody)); + route.provider = resolveOpenCodeGoTransport(route.provider, + sessionLaneIdFromRequest(req.headers) ?? normalizeLogConversationId(req.headers.get("x-opencode-session"))); // Settle the wire once so every branch below reads the adapter this model will // actually use, not the provider-wide default (#404). route.provider = resolveWireProtocolOverride(route.providerName, route.modelId, route.provider, "chat"); @@ -237,6 +241,9 @@ async function handleChatCompletionsWithBudget( return chatCompletionsErrorResponse(400, CODEX_RESERVE_HELPER_UNSUPPORTED_MESSAGE, "invalid_request_error"); } const headers = new Headers({ "content-type": "application/json" }); + // Internal bridge metadata; the Go resolver scopes and hashes it before upstream use. + const openCodeSession = req.headers.get("x-opencode-session"); + if (openCodeSession) headers.set("x-opencode-session", openCodeSession); for (const name of FORWARD_HEADERS) { if (name === "authorization" && !directRoute) continue; const value = req.headers.get(name); diff --git a/src/server/responses/core.ts b/src/server/responses/core.ts index 312af7ac43..594b444c8b 100644 --- a/src/server/responses/core.ts +++ b/src/server/responses/core.ts @@ -2304,7 +2304,8 @@ async function applyFinalRouteRequestNormalization(args: { // Settle the wire once so logging, fast-mode, auth, and sidecars read the adapter // this request will actually use (#404). - route.provider = resolveOpenCodeGoTransport(route.provider, sessionLaneIdFromRequest(req.headers)); + route.provider = resolveOpenCodeGoTransport(route.provider, + sessionLaneIdFromRequest(req.headers) ?? normalizeLogConversationId(req.headers.get("x-opencode-session"))); route.provider = resolveWireProtocolOverride(route.providerName, route.modelId, route.provider, inboundWire); if (preserveAnthropicResponseModel) parsed._responseModelId = responseModelId; logCtx.model = route.modelId; diff --git a/tests/config/client-config-export.test.ts b/tests/config/client-config-export.test.ts index 6a71813e9f..4d70790403 100644 --- a/tests/config/client-config-export.test.ts +++ b/tests/config/client-config-export.test.ts @@ -315,6 +315,7 @@ describe("Pi serializer (accept criterion 2)", () => { expect(provider.baseUrl).toBe(BASE_URL); expect(provider.api).toBe("openai-completions"); expect(provider.apiKey).toBe(LOOPBACK_API_KEY_PLACEHOLDER); + expect(provider.compat?.sendSessionAffinityHeaders).toBe(true); }); test("cost is omitted on every entry — zeros would assert routed models are free", () => { @@ -899,7 +900,7 @@ describe("EXPORT_CLIENTS registry", () => { `); }); - test("pi bytes are unchanged, to the last newline", () => { + test("pi bytes include session affinity, to the last newline", () => { const built = buildClientConfigText("pi", ctx({ config: cfg() })); expect(built.format).toBe("json"); expect(built.text).toBe(`{ @@ -908,6 +909,9 @@ describe("EXPORT_CLIENTS registry", () => { "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "opencodex-loopback", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", diff --git a/tests/providers/opencode-go-session-header.test.ts b/tests/providers/opencode-go-session-header.test.ts index 00684f065b..9b476760cd 100644 --- a/tests/providers/opencode-go-session-header.test.ts +++ b/tests/providers/opencode-go-session-header.test.ts @@ -3,6 +3,7 @@ import { providerConfigSeed } from "../../src/providers/derive"; import { resolveOpenCodeGoTransport } from "../../src/providers/opencode-go-transport"; import { getProviderRegistryEntry } from "../../src/providers/registry"; import { handleResponses } from "../../src/server/responses/core"; +import { handleChatCompletions } from "../../src/server/chat-completions"; import type { OcxConfig, OcxProviderConfig } from "../../src/types"; const MUSE_MODEL = "muse-spark-1.3-contributor"; @@ -52,6 +53,8 @@ async function captureRequest(input: { model?: string; child?: string; provider?: OcxProviderConfig; + nativeChat?: boolean; + headers?: Record; } = {}): Promise<{ url: string; headers: Headers }> { const providerName = input.providerName ?? "opencode-go"; const model = input.model ?? MUSE_MODEL; @@ -65,7 +68,15 @@ async function captureRequest(input: { const config = { providers: { [providerName]: input.provider ?? opencodeGo() }, } as unknown as OcxConfig; - const response = await handleResponses( + const response = input.nativeChat ? await handleChatCompletions( + new Request("http://localhost/v1/chat/completions", { + method: "POST", + headers: input.headers ?? codexHeaders(input.child), + body: JSON.stringify({ model: `${providerName}/${model}`, messages: [{ role: "user", content: "ping" }], stream: false }), + }), + config, + { model: "", provider: "" }, + ) : await handleResponses( new Request("http://localhost/v1/responses", { method: "POST", headers: codexHeaders(input.child), @@ -77,6 +88,7 @@ async function captureRequest(input: { ); expect(response.status).toBe(200); + await response.text(); expect(requests).toHaveLength(1); return requests[0]!; } @@ -85,6 +97,44 @@ describe("OpenCode Go session affinity (#3344)", () => { const originalFetch = globalThis.fetch; afterEach(() => { globalThis.fetch = originalFetch; }); + test("native Chat ingress preserves stable Go affinity and separates conversations", async () => { + const provider = opencodeGo(); + const input = { nativeChat: true, model: "omen-alpha", provider }; + const first = await captureRequest(input); + const continued = await captureRequest(input); + const sibling = await captureRequest({ ...input, child: "child-thread-b" }); + expect(first.url).toBe("https://opencode.ai/zen/go/v1/chat/completions"); + expect(first.headers.get(SESSION_HEADER)).toMatch(/^ocx_[0-9a-f]{32}$/); + expect(continued.headers.get(SESSION_HEADER)).toBe(first.headers.get(SESSION_HEADER)); + expect(sibling.headers.get(SESSION_HEADER)).not.toBe(first.headers.get(SESSION_HEADER)); + expect(provider.headers?.[SESSION_HEADER]).toBeUndefined(); + }); + + test("native Chat honors configured session headers on renamed Go providers", async () => { + const captured = await captureRequest({ + nativeChat: true, model: "omen-alpha", providerName: "renamed-go", + provider: opencodeGo({ headers: { "X-OpenCode-Session": "operator-session" } }), + }); + expect(captured.headers.get(SESSION_HEADER)).toBe("operator-session"); + }); + + test("uses a Pi session header without Codex headers on native and bridged Chat", async () => { + const headers = { "content-type": "application/json", "x-opencode-session": "pi-conversation-a" }; + const chat = await captureRequest({ nativeChat: true, model: "omen-alpha", headers }); + const bridged = await captureRequest({ nativeChat: true, model: MUSE_MODEL, headers }); + expect(chat.headers.get(SESSION_HEADER)).toMatch(/^ocx_[0-9a-f]{32}$/); + expect(chat.headers.get(SESSION_HEADER)).not.toContain("pi-conversation-a"); + expect(bridged.headers.get(SESSION_HEADER)).toBe(chat.headers.get(SESSION_HEADER)); + }); + + test("native Chat does not send Go affinity to an unrelated destination", async () => { + const captured = await captureRequest({ + nativeChat: true, model: "omen-alpha", providerName: "custom-go", + provider: opencodeGo({ baseUrl: "https://opencode.ai.evil.test/zen/go/v1" }), + }); + expect(captured.headers.has(SESSION_HEADER)).toBe(false); + }); + test("sends one stable opaque session header on Responses and Chat wires", async () => { const responses = await captureRequest({ model: MUSE_MODEL }); const chat = await captureRequest({ model: CHAT_MODEL }); From effba4c646408c8fd4b22936c820de37d370ce9e Mon Sep 17 00:00:00 2001 From: makesomethingshit Date: Mon, 7 Sep 2026 16:11:52 +0900 Subject: [PATCH 027/116] test(opencode-go): define inbound opaque session identity contract [skip ci] (cherry picked from commit 9f15a7c4139de294c5b0d7eddf50d885523f149e) Co-authored-by: makesomethingshit <246213378+makesomethingshit@users.noreply.github.com> (cherry picked from commit 65908008e52c5dca2eb1130d1c0cff0e0732873d) --- .../opencode-go-session-header.test.ts | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/tests/providers/opencode-go-session-header.test.ts b/tests/providers/opencode-go-session-header.test.ts index 9b476760cd..b05e526e1c 100644 --- a/tests/providers/opencode-go-session-header.test.ts +++ b/tests/providers/opencode-go-session-header.test.ts @@ -1,9 +1,10 @@ import { afterEach, describe, expect, test } from "bun:test"; import { providerConfigSeed } from "../../src/providers/derive"; -import { resolveOpenCodeGoTransport } from "../../src/providers/opencode-go-transport"; +import { deriveOpenCodeGoSessionId, resolveOpenCodeGoTransport } from "../../src/providers/opencode-go-transport"; import { getProviderRegistryEntry } from "../../src/providers/registry"; import { handleResponses } from "../../src/server/responses/core"; import { handleChatCompletions } from "../../src/server/chat-completions"; +import { normalizeLogConversationId } from "../../src/server/request-log-conversation"; import type { OcxConfig, OcxProviderConfig } from "../../src/types"; const MUSE_MODEL = "muse-spark-1.3-contributor"; @@ -79,7 +80,7 @@ async function captureRequest(input: { ) : await handleResponses( new Request("http://localhost/v1/responses", { method: "POST", - headers: codexHeaders(input.child), + headers: input.headers ?? codexHeaders(input.child), body: JSON.stringify({ model: `${providerName}/${model}`, input: "ping", stream: false }), }), config, @@ -127,6 +128,27 @@ describe("OpenCode Go session affinity (#3344)", () => { expect(bridged.headers.get(SESSION_HEADER)).toBe(chat.headers.get(SESSION_HEADER)); }); + for (const session of ["client-session-a", "ocx_0123456789abcdef0123456789abcdef"]) { + test(`treats inbound ${session.startsWith("ocx_") ? "ocx-prefixed" : "raw"} identity as client input on every ingress`, async () => { + const headers = { "content-type": "application/json", [SESSION_HEADER]: session }; + const expected = deriveOpenCodeGoSessionId(normalizeLogConversationId(session)!); + const native = await captureRequest({ nativeChat: true, model: "omen-alpha", headers }); + const bridged = await captureRequest({ nativeChat: true, model: MUSE_MODEL, headers }); + const responses = await captureRequest({ model: MUSE_MODEL, headers }); + expect(native.url).toEndWith("/chat/completions"); + expect(bridged.url).toEndWith("/responses"); + for (const request of [native, bridged, responses]) { + expect(request.headers.get(SESSION_HEADER)).toBe(expected); + expect(request.headers.get(SESSION_HEADER)).not.toBe(session); + } + const override = await captureRequest({ + nativeChat: true, model: "omen-alpha", headers, + provider: opencodeGo({ headers: { "X-OpenCode-Session": session } }), + }); + expect(override.headers.get(SESSION_HEADER)).toBe(session); + }); + } + test("native Chat does not send Go affinity to an unrelated destination", async () => { const captured = await captureRequest({ nativeChat: true, model: "omen-alpha", providerName: "custom-go", From 5b3df2ed5a0b69677c739c937ab24f5eb6061f3e Mon Sep 17 00:00:00 2001 From: Ingwannu Date: Mon, 7 Sep 2026 06:35:43 +0000 Subject: [PATCH 028/116] fix: admit reasoning envelope allocations before materialization [skip ci] (cherry picked from commit 9bcb7748facfd5495f641044adcf8e0627f9fb26) Co-authored-by: Ingwannu <186453546+Ingwannu@users.noreply.github.com> --- .../content/docs/reference/proxy-formats.md | 6 + src/claude/inbound.ts | 27 ++++- src/lib/json-byte-size.ts | 61 ++++++++++ src/responses/reasoning-envelope.ts | 72 +++++++++--- src/server/claude-messages.ts | 5 +- structure/04_transports-and-sidecars.md | 17 +++ tests/responses/reasoning-envelope.test.ts | 111 +++++++++++++++++- 7 files changed, 269 insertions(+), 30 deletions(-) create mode 100644 src/lib/json-byte-size.ts diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index cb97ad7076..0c7b8257bc 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -278,6 +278,12 @@ These endpoints speak the Anthropic Messages dialect used by Claude Code and com Most requests are translated to Responses, routed normally, then translated back to Anthropic JSON or Anthropic SSE. +On translated Messages requests, reasoning replay shares the request's translation budget. +Envelope admission includes encoding/decoding copy overhead, not just the original signature +length. Requests exceeding this budget return HTTP 413 with `translation_buffer_limit`; +signatures and opaque reasoning data are never truncated to make a request fit. Native +Anthropic passthrough retains its separate body-size contract. + Base64 and URL image sources are translated in user messages and nested tool results. File-backed images (`source.type: "file"`) require native Anthropic passthrough; translated routes return a fixed HTTP 400 error asking for base64 or URL input. OpenCodex does not resolve another provider's diff --git a/src/claude/inbound.ts b/src/claude/inbound.ts index 5e876ca6cb..c2e3ded9b2 100644 --- a/src/claude/inbound.ts +++ b/src/claude/inbound.ts @@ -18,6 +18,7 @@ import { AnthropicRequestError, isRec, type Rec } from "./inbound-records"; import { resolveInboundModel, effortForThinkingBudget, effortFromOutputConfig, formatFromOutputConfig } from "./inbound-model-options"; import { systemToInstructions, toolsToResponses, toolChoiceToResponses } from "./inbound-content-options"; import { decodeReasoningEnvelope, encodeReasoningEnvelope, OCX_REASONING_PREFIX } from "../responses/reasoning-envelope"; +import { createTranslatorBudget, type TranslatorBudget } from "../lib/translator-budget"; @@ -210,7 +211,7 @@ function userMessageToItems(content: unknown, input: Rec[], elide: SkillElisionC pushUserMessage(input, pending); } -function assistantMessageToItems(content: unknown, input: Rec[]): void { +function assistantMessageToItems(content: unknown, input: Rec[], budget: TranslatorBudget): void { if (typeof content === "string") { if (content.length > 0) input.push({ type: "message", role: "assistant", content: [{ type: "output_text", text: content }] }); return; @@ -240,11 +241,12 @@ function assistantMessageToItems(content: unknown, input: Rec[]): void { const thinking = typeof raw.thinking === "string" ? raw.thinking : ""; const signature = typeof raw.signature === "string" ? raw.signature : ""; if (signature.startsWith(OCX_REASONING_PREFIX)) { - const owned = decodeReasoningEnvelope(signature); + const owned = decodeReasoningEnvelope(signature, budget); if (!owned) throw new AnthropicRequestError("malformed ocxr1 reasoning signature"); if (Object.hasOwn(owned, "sig")) throw new AnthropicRequestError("OpenCodex reasoning continuity cannot be replayed as an Anthropic signature"); } - const encrypted = signature.length === 0 ? undefined : signature.startsWith(OCX_REASONING_PREFIX) ? signature : encodeReasoningEnvelope({ sig: signature }); + const encrypted = signature.length === 0 ? undefined : signature.startsWith(OCX_REASONING_PREFIX) ? signature : encodeReasoningEnvelope({ sig: signature }, budget); + if (encrypted) budget.chargeRetained(2 * encrypted.length, { kind: "reasoning" }); if (thinking.length === 0 && !encrypted) break; input.push({ type: "reasoning", id: `rs_${crypto.randomUUID().replace(/-/g, "")}`, summary: thinking.length > 0 ? [{ type: "summary_text", text: thinking }] : [], ...(encrypted ? { encrypted_content: encrypted } : {}) }); break; @@ -252,7 +254,11 @@ function assistantMessageToItems(content: unknown, input: Rec[]): void { case "redacted_thinking": { flush(); const data = typeof raw.data === "string" ? raw.data : ""; - if (data.length > 0) input.push({ type: "reasoning", id: `rs_${crypto.randomUUID().replace(/-/g, "")}`, summary: [], encrypted_content: encodeReasoningEnvelope({ red: [data] }) }); + if (data.length > 0) { + const encrypted = encodeReasoningEnvelope({ red: [data] }, budget); + budget.chargeRetained(2 * encrypted.length, { kind: "reasoning" }); + input.push({ type: "reasoning", id: `rs_${crypto.randomUUID().replace(/-/g, "")}`, summary: [], encrypted_content: encrypted }); + } break; } default: @@ -294,7 +300,16 @@ export function anthropicToResponsesBody(raw: unknown, cc?: OcxClaudeCodeConfig) * OUT-OF-BODY tuple (audit 133 R3#1 — an in-body marker would leak upstream through * the native Responses forward and 400). */ -export function anthropicToResponsesTranslation(raw: unknown, cc?: OcxClaudeCodeConfig): ClaudeInboundTranslation { +export function anthropicToResponsesTranslation(raw: unknown, cc?: OcxClaudeCodeConfig, budget?: TranslatorBudget): ClaudeInboundTranslation { + const activeBudget = budget ?? createTranslatorBudget(); + try { + return translateAnthropicRequest(raw, cc, activeBudget); + } finally { + if (!budget) activeBudget.dispose(); + } +} + +function translateAnthropicRequest(raw: unknown, cc: OcxClaudeCodeConfig | undefined, budget: TranslatorBudget): ClaudeInboundTranslation { if (!isRec(raw)) throw new AnthropicRequestError("request body must be a JSON object"); if (typeof raw.model !== "string" || raw.model.length === 0) { throw new AnthropicRequestError("model is required"); @@ -315,7 +330,7 @@ export function anthropicToResponsesTranslation(raw: unknown, cc?: OcxClaudeCode for (const msg of raw.messages) { if (!isRec(msg)) throw new AnthropicRequestError("each message must be an object"); if (msg.role === "user") userMessageToItems(msg.content, input, elide); - else if (msg.role === "assistant") assistantMessageToItems(msg.content, input); + else if (msg.role === "assistant") assistantMessageToItems(msg.content, input, budget); else if (msg.role === "system") { const text = systemMessageText(msg.content); if (text.length > 0) systemParts.push(text); diff --git a/src/lib/json-byte-size.ts b/src/lib/json-byte-size.ts new file mode 100644 index 0000000000..d6398718fd --- /dev/null +++ b/src/lib/json-byte-size.ts @@ -0,0 +1,61 @@ +import { TRANSLATOR_MAX_TURN_BYTES, TranslatorBudgetExceededError } from "./translator-budget"; + +/** Measure plain JSON data without allocating its serialized string or UTF-8 copy. */ +export function jsonUtf8Bytes(value: unknown, limit = TRANSLATOR_MAX_TURN_BYTES): number { + let bytes = 0; + const add = (count: number) => { + if (count > limit - bytes) throw new TranslatorBudgetExceededError("request_copies", limit); + bytes += count; + }; + const string = (text: string) => { + // Every UTF-16 code unit needs at least one JSON UTF-8 byte; reject large inputs + // before walking them. Escapes and unpaired surrogates are counted below. + if (text.length + 2 > limit - bytes) throw new TranslatorBudgetExceededError("request_copies", limit); + add(2); + for (let i = 0; i < text.length; i++) { + const code = text.charCodeAt(i); + if (code === 0x22 || code === 0x5c || code === 8 || code === 9 || code === 10 || code === 12 || code === 13) add(2); + else if (code < 0x20) add(6); + else if (code < 0x80) add(1); + else if (code < 0x800) add(2); + else if (code >= 0xd800 && code <= 0xdbff) { + const next = text.charCodeAt(i + 1); + if (next >= 0xdc00 && next <= 0xdfff) { add(4); i++; } + else add(6); + } else if (code >= 0xdc00 && code <= 0xdfff) add(6); + else add(3); + } + }; + const visit = (item: unknown): void => { + if (item === null) { add(4); return; } + if (typeof item === "string") { string(item); return; } + if (typeof item === "boolean") { add(item ? 4 : 5); return; } + if (typeof item === "number") { add(Number.isFinite(item) ? String(item).length : 4); return; } + if (Array.isArray(item)) { + add(2); + for (let i = 0; i < item.length; i++) { + if (i > 0) add(1); + if (item[i] === undefined) add(4); + else visit(item[i]); + } + return; + } + if (typeof item === "object" && item !== null) { + add(2); + let first = true; + for (const key of Object.keys(item)) { + const field = (item as Record)[key]; + if (field === undefined) continue; + if (!first) add(1); + first = false; + string(key); + add(1); + visit(field); + } + return; + } + throw new TypeError("Expected plain JSON data for translation sizing"); + }; + visit(value); + return bytes; +} diff --git a/src/responses/reasoning-envelope.ts b/src/responses/reasoning-envelope.ts index 2a56563578..ba20e800ed 100644 --- a/src/responses/reasoning-envelope.ts +++ b/src/responses/reasoning-envelope.ts @@ -12,6 +12,9 @@ * passthrough scrub strips ocxr1 envelopes before native forwarding. */ +import { createTranslatorBudget, type TranslatorBudget } from "../lib/translator-budget"; +import { jsonUtf8Bytes } from "../lib/json-byte-size"; + export const OCX_REASONING_PREFIX = "ocxr1:"; export interface ReasoningEnvelope { @@ -32,30 +35,61 @@ export interface ReasoningEnvelope { krc?: string; } -export function encodeReasoningEnvelope(envelope: ReasoningEnvelope): string { - return OCX_REASONING_PREFIX + Buffer.from(JSON.stringify(envelope), "utf-8").toString("base64"); +export function encodeReasoningEnvelope(envelope: ReasoningEnvelope, budget?: TranslatorBudget): string { + const activeBudget = budget ?? createTranslatorBudget(); + try { + const jsonBytes = jsonUtf8Bytes(envelope); + const base64Bytes = 4 * Math.ceil(jsonBytes / 3); + // Reserve before materialization: UTF-16 JSON, UTF-8 buffer, base64 string, + // and the prefixed result may coexist. Returned-value ownership stays with + // callers, whose existing retained accounting must not be charged twice here. + const reservation = activeBudget.reserveTransient( + Math.max( + 3 * jsonBytes + 4 * base64Bytes + 2 * OCX_REASONING_PREFIX.length, + 8 * (OCX_REASONING_PREFIX.length + base64Bytes), + ), + { kind: "reasoning" }, + ); + try { + return OCX_REASONING_PREFIX + Buffer.from(JSON.stringify(envelope), "utf-8").toString("base64"); + } finally { + reservation.release(); + } + } finally { + if (!budget) activeBudget.dispose(); + } } /** Decode an ocxr1 envelope; returns null for native (OpenAI-encrypted) blobs or garbage. */ -export function decodeReasoningEnvelope(encryptedContent: string): ReasoningEnvelope | null { +export function decodeReasoningEnvelope(encryptedContent: string, budget?: TranslatorBudget): ReasoningEnvelope | null { if (!encryptedContent.startsWith(OCX_REASONING_PREFIX)) return null; + const activeBudget = budget ?? createTranslatorBudget(); try { - const parsed: unknown = JSON.parse(Buffer.from(encryptedContent.slice(OCX_REASONING_PREFIX.length), "base64").toString("utf-8")); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; - const obj = parsed as { sig?: unknown; red?: unknown }; - const envelope: ReasoningEnvelope = {}; - if (typeof obj.sig === "string") envelope.sig = obj.sig; - if (Array.isArray(obj.red)) { - const red = obj.red.filter((r): r is string => typeof r === "string"); - if (red.length > 0) envelope.red = red; + // Also bound already-encoded replay before slicing, decoding, or parsing it. + // Eight bytes per code unit conservatively covers the string/buffer copies. + const reservation = activeBudget.reserveTransient(8 * encryptedContent.length, { kind: "reasoning" }); + try { + const parsed: unknown = JSON.parse(Buffer.from(encryptedContent.slice(OCX_REASONING_PREFIX.length), "base64").toString("utf-8")); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; + const obj = parsed as { sig?: unknown; red?: unknown }; + const envelope: ReasoningEnvelope = {}; + if (typeof obj.sig === "string") envelope.sig = obj.sig; + if (Array.isArray(obj.red)) { + const red = obj.red.filter((r): r is string => typeof r === "string"); + if (red.length > 0) envelope.red = red; + } + const txt = (parsed as { txt?: unknown }).txt; + const hasTxt = typeof txt === "string"; + if (hasTxt) envelope.txt = txt; + const krc = (parsed as { krc?: unknown }).krc; + if (typeof krc === "string" && krc.length > 0) envelope.krc = krc; + return envelope.sig || envelope.red || hasTxt || envelope.krc ? envelope : null; + } catch { + return null; + } finally { + reservation.release(); } - const txt = (parsed as { txt?: unknown }).txt; - const hasTxt = typeof txt === "string"; - if (hasTxt) envelope.txt = txt; - const krc = (parsed as { krc?: unknown }).krc; - if (typeof krc === "string" && krc.length > 0) envelope.krc = krc; - return envelope.sig || envelope.red || hasTxt || envelope.krc ? envelope : null; - } catch { - return null; + } finally { + if (!budget) activeBudget.dispose(); } } diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index 20bc14e195..a8af8896ff 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -7,6 +7,7 @@ * unchanged. The Responses output (SSE or JSON) is converted back to Anthropic shape. */ import { FORWARD_HEADERS } from "../adapters/openai-responses"; +import { jsonUtf8Bytes } from "../lib/json-byte-size"; import { sseFieldValue } from "../lib/sse-decoder"; import { enforceAnthropicImageLimits, sniffImageDimensions } from "../adapters/anthropic-image-guard"; import { normalizeAnthropicImages } from "../adapters/anthropic-image-normalize"; @@ -753,13 +754,13 @@ async function handleClaudeMessagesWithBudget( }; delete anthropicBody.thinking; } - const translation = anthropicToResponsesTranslation(anthropicBody, config.claudeCode); + const translation = anthropicToResponsesTranslation(anthropicBody, config.claudeCode, translatorBudget); internalBody = translation.body; // The Anthropic translator builds its body from model/input/store/stream plus sampling // fields only, so the caller intent is applied to the TRANSLATED body rather than the // inbound one. if (fastRow) internalBody.service_tier = "priority"; - translatorBudget.chargeRetained(new TextEncoder().encode(JSON.stringify(internalBody)).byteLength, { kind: "request_copies" }); + translatorBudget.chargeRetained(jsonUtf8Bytes(internalBody), { kind: "request_copies" }); cacheKeySource = translation.cacheKeySource; } catch (err) { const overflow = isTranslatorBudgetExceededError(err); diff --git a/structure/04_transports-and-sidecars.md b/structure/04_transports-and-sidecars.md index c568bb0151..256bd1eae5 100644 --- a/structure/04_transports-and-sidecars.md +++ b/structure/04_transports-and-sidecars.md @@ -1480,6 +1480,23 @@ Unsupported constraints remain in `description` as model guidance instead of dis ## Reasoning display parity (hideThinkingSummary) +Reasoning-envelope serialization uses preflight byte sizing and transient reservations before +creating JSON, UTF-8, or base64 copies. Encoding also admits the matching decode projection, so +a successfully encoded standalone envelope fits the standalone decoder's limit. Callers retain +ownership of returned values; the helper releases only its temporary reservation. Inbound +Anthropic translation carries one budget across all assistant blocks and accounts for retained +envelopes until the response lifecycle disposes it. Standalone translation owns a temporary +budget and disposes it on success or failure. Final translated-request sizing uses plain-JSON +measurement rather than allocating a serialized copy just to measure it. + +[Decision Log] +- 목적과 의도: Keep reasoning replay bounded while preserving opaque values exactly. +- 기존 구현 및 제약 조건: Reasoning continuity needs JSON/base64 envelopes, and existing callers already own retained accounting and typed overflow handling. +- 검토한 주요 대안: Per-field truncation, an independent fixed field limit, or shared transient admission plus cumulative inbound ownership. +- 선택한 방식: Reserve conservative copy projections in the envelope helpers and use the existing request budget across inbound blocks. +- 다른 대안 대신 이 방식을 선택한 이유: Truncation changes signed values; one field limit does not describe aggregate ownership. Existing budget errors retain the established HTTP and stream error contracts. +- 장점, 단점 및 영향: Normal replay is unchanged; envelope admission includes copy overhead and is stricter than a raw-string length ceiling. These are translator accounting limits, not a process-wide RSS guarantee. + `hideThinkingSummary` (request reasoning summary absent/"none" — the routed catalog default) is honored by BOTH reasoning paths: anthropic `thinking_delta` AND raw `reasoning_raw_delta` (openai-chat `reasoning_content`, kiro tags). Hidden reasoning emits an envelope-only reasoning diff --git a/tests/responses/reasoning-envelope.test.ts b/tests/responses/reasoning-envelope.test.ts index 2469b8e46b..4a26ce51db 100644 --- a/tests/responses/reasoning-envelope.test.ts +++ b/tests/responses/reasoning-envelope.test.ts @@ -1,7 +1,10 @@ -import { describe, expect, test } from "bun:test"; -import { anthropicToResponsesBody } from "../../src/claude/inbound"; -import { decodeReasoningEnvelope, encodeReasoningEnvelope } from "../../src/responses/reasoning-envelope"; +import { describe, expect, spyOn, test } from "bun:test"; +import { anthropicToResponsesBody, anthropicToResponsesTranslation } from "../../src/claude/inbound"; +import { decodeReasoningEnvelope, encodeReasoningEnvelope, OCX_REASONING_PREFIX, type ReasoningEnvelope } from "../../src/responses/reasoning-envelope"; import { responsesJsonToAnthropicMessage } from "../../src/claude/outbound"; +import { createTranslatorBudget, TranslatorBudgetExceededError, translatorObservedBufferSnapshot } from "../../src/lib/translator-budget"; +import { jsonUtf8Bytes } from "../../src/lib/json-byte-size"; +import * as budgets from "../../src/lib/translator-budget"; describe("reasoning and tool/result envelopes", () => { test("preserves ordered thinking blocks and genuine signatures", () => { @@ -77,3 +80,105 @@ describe("reasoning and tool/result envelopes", () => { expect(message.content).toEqual([{ type: "thinking", thinking: "", signature: "sig-only" }]); }); }); + +describe("reasoning allocation admission", () => { + test.each(["ascii", "\"\\\n\u0000", "한글😀", "\ud800", "\udc00", ""])('sizes JSON strings exactly: %j', value => { + const data = { sig: value, red: [value, ""], txt: value, krc: value, omitted: undefined }; + const expected = Buffer.byteLength(JSON.stringify(data)); + expect(jsonUtf8Bytes(data, expected)).toBe(expected); + expect(() => jsonUtf8Bytes(data, expected - 1)).toThrow(TranslatorBudgetExceededError); + }); + + test("sizes the translated plain-JSON vocabulary", () => { + const data = { arr: [undefined, null, true, false, 0, -0, 1e30, NaN, Infinity, { text: "x" }], absent: undefined }; + expect(jsonUtf8Bytes(data)).toBe(Buffer.byteLength(JSON.stringify(data))); + }); + + test.each([{ sig: "opaque" }, { red: ["one", "two"] }, { txt: "hidden" }, { krc: "opaque" }, { sig: "s", red: ["r"], txt: "t", krc: "k" }])( + "rejects before JSON/Buffer materialization and admits the exact projected boundary: %j", envelope => { + const json = JSON.stringify(envelope); + const size = Buffer.byteLength(json); + const base64Bytes = 4 * Math.ceil(size / 3); + const limit = Math.max(3 * size + 4 * base64Bytes + 2 * OCX_REASONING_PREFIX.length, 8 * (OCX_REASONING_PREFIX.length + base64Bytes)); + const budget = createTranslatorBudget({ maxTurnBytes: limit - 1 }); + const stringify = spyOn(JSON, "stringify"); + const from = spyOn(Buffer, "from"); + let error: unknown; + let serializations = 0; + let allocations = 0; + try { encodeReasoningEnvelope(envelope, budget); } catch (caught) { error = caught; } + finally { + serializations = stringify.mock.calls.length; + allocations = from.mock.calls.length; + stringify.mockRestore(); from.mockRestore(); + } + expect(error).toBeInstanceOf(TranslatorBudgetExceededError); + expect(serializations).toBe(0); + expect(allocations).toBe(0); + expect(budget.snapshot().currentBytes).toBe(0); + budget.dispose(); + const exact = createTranslatorBudget({ maxTurnBytes: limit }); + try { + const encoded = encodeReasoningEnvelope(envelope, exact); + expect(encoded).toBe(OCX_REASONING_PREFIX + Buffer.from(json).toString("base64")); + expect(decodeReasoningEnvelope(encoded, exact)).toEqual(envelope); + expect(exact.snapshot().currentBytes).toBe(0); + } finally { exact.dispose(); } + }, + ); + + test("bounds preencoded replay before decoding and preserves native blobs", () => { + const encoded = encodeReasoningEnvelope({ txt: "" }); + const budget = createTranslatorBudget({ maxTurnBytes: encoded.length * 8 - 1 }); + const from = spyOn(Buffer, "from"); + let error: unknown; + let allocations = 0; + try { decodeReasoningEnvelope(encoded, budget); } catch (caught) { error = caught; } + finally { allocations = from.mock.calls.length; from.mockRestore(); } + expect(error).toBeInstanceOf(TranslatorBudgetExceededError); + expect(allocations).toBe(0); + expect(decodeReasoningEnvelope("native-opaque", budget)).toBeNull(); + expect(budget.snapshot().currentBytes).toBe(0); + budget.dispose(); + const exact = createTranslatorBudget({ maxTurnBytes: encoded.length * 8 }); + try { expect(decodeReasoningEnvelope(encoded, exact)).toEqual({ txt: "" }); } + finally { exact.dispose(); } + }); + + test.each(["thinking", "redacted_thinking", "owned"])('accounts cumulatively for %s blocks across messages', type => { + const before = translatorObservedBufferSnapshot().currentBytes; + const block = type === "redacted_thinking" ? { type, data: "r" } + : { type: "thinking", thinking: "", signature: type === "owned" ? encodeReasoningEnvelope({ txt: "t" }) : "s" }; + const budget = createTranslatorBudget({ maxTurnBytes: 256 }); + try { + expect(() => anthropicToResponsesTranslation({ model: "m", messages: Array.from({ length: 8 }, () => ({ role: "assistant", content: [block] })) }, undefined, budget)) + .toThrow(TranslatorBudgetExceededError); + expect(budget.snapshot().highWaterBytes).toBeLessThanOrEqual(256); + } finally { budget.dispose(); } + expect(translatorObservedBufferSnapshot().currentBytes).toBe(before); + }); + + test.each(["thinking", "redacted_thinking", "owned"])("handler maps %s admission failure to 413 without dispatch and disposes its budget", async type => { + const { handleClaudeMessages } = await import("../../src/server/claude-messages"); + const signature = type === "owned" ? encodeReasoningEnvelope({ txt: "fixture" }) : "fixture"; + const content = type === "redacted_thinking" ? { type, data: "fixture" } + : { type: "thinking", thinking: "", signature }; + const request = new Request("http://localhost/v1/messages", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture/model", messages: [{ role: "assistant", content: [content] }] }), + }); + const beforeBytes = budgets.translatorObservedBufferSnapshot().currentBytes; + const beforeCount = budgets.translatorLiveBudgetCountForTests(); + const create = budgets.createTranslatorBudget; + const factory = spyOn(budgets, "createTranslatorBudget").mockImplementation(() => create({ maxTurnBytes: 64 })); + const upstream = spyOn(globalThis, "fetch").mockImplementation(async () => { throw new Error("unexpected upstream dispatch"); }); + try { + const response = await handleClaudeMessages(request, { port: 0, providers: {} }, { model: "", provider: "" }); + expect(response.status).toBe(413); + expect(await response.json()).toMatchObject({ type: "error", error: { type: "request_too_large", code: "translation_buffer_limit" } }); + expect(upstream).not.toHaveBeenCalled(); + expect(budgets.translatorObservedBufferSnapshot().currentBytes).toBe(beforeBytes); + expect(budgets.translatorLiveBudgetCountForTests()).toBe(beforeCount); + } finally { factory.mockRestore(); upstream.mockRestore(); } + }); +}); From eb8cc9ab735a3c2396cb5393bbf62dc473d5716e Mon Sep 17 00:00:00 2001 From: makesomethingshit Date: Mon, 7 Sep 2026 16:24:45 +0900 Subject: [PATCH 029/116] fix(pi): scope generated session affinity to the Pi client [skip ci] (cherry picked from commit 23d869350e9a90359f65624e41ae8e93797ae398) Co-authored-by: makesomethingshit <246213378+makesomethingshit@users.noreply.github.com> (cherry picked from commit 1e65ffd4bc9ba8befdf6e3546643b428106f4650) --- src/clients/config-export.ts | 8 ++++---- tests/clients/prime-client.test.ts | 20 ++++++++------------ tests/config/client-config-export.test.ts | 2 ++ 3 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/clients/config-export.ts b/src/clients/config-export.ts index e1744c2209..6a94b74d70 100644 --- a/src/clients/config-export.ts +++ b/src/clients/config-export.ts @@ -817,7 +817,7 @@ export interface GajaeGeneratedConfig { * model. The rest of this contract (omitting `cost`) is still ours rather than * a claim about Pi's acceptance. */ -function buildPiClientConfig(ctx: ExportContext): PiGeneratedConfig { +function buildPiClientConfig(ctx: ExportContext, sendSessionAffinityHeaders = false): PiGeneratedConfig { const models: PiModelEntry[] = []; for (const model of normalizeExportModels(ctx.models)) { // Text is the one modality every routed model supports; anything richer must come @@ -860,7 +860,7 @@ function buildPiClientConfig(ctx: ExportContext): PiGeneratedConfig { baseUrl: ctx.baseUrl, api: PI_API_DIALECT, apiKey: LOOPBACK_API_KEY_PLACEHOLDER, - compat: { sendSessionAffinityHeaders: true }, + ...(sendSessionAffinityHeaders ? { compat: { sendSessionAffinityHeaders: true } } : {}), models, }, }, @@ -1033,7 +1033,7 @@ function buildOpencodeContribution(ctx: ExportContext): ManagedContribution { } function buildPiContribution(ctx: ExportContext): ManagedContribution { - const doc = buildPiClientConfig(ctx); + const doc = buildPiClientConfig(ctx, true); return singleFragment("pi", ["providers", OPENCODE_PROVIDER_ID], doc.providers[OPENCODE_PROVIDER_ID]); } @@ -1129,7 +1129,7 @@ export const EXPORT_CLIENTS: Record = { destination: env => piConfigPath(env), apiKeyEnv: "", exportHint: "Pi reads a non-secret placeholder from models.json; loopback needs no key.", - build: buildPiClientConfig, + build: ctx => buildPiClientConfig(ctx, true), format: "json", summarize: summarizePi, buildContribution: buildPiContribution, diff --git a/tests/clients/prime-client.test.ts b/tests/clients/prime-client.test.ts index c88c77508a..6c7c0a2f76 100644 --- a/tests/clients/prime-client.test.ts +++ b/tests/clients/prime-client.test.ts @@ -37,18 +37,14 @@ function context(): ExportContext { } describe("Prime Agent client config", () => { - /** - * The load-bearing claim of this client: Prime Agent is the pi coding agent - * under a different brand, so it reads the SAME models.json contract rather - * than a lookalike. Locking the two documents together is what keeps that - * claim true — if a future Pi-only change diverges, this fails here instead - * of silently shipping Prime users a config their agent rejects. - */ - test("generates byte-for-byte the document Pi generates", () => { - const prime = buildClientConfigText("prime", context()); - const pi = buildClientConfigText("pi", context()); - expect(prime.format).toBe("json"); - expect(prime.text).toBe(pi.text); + test("shares Pi's model contract without opting Prime into session headers", () => { + const prime = buildClientConfig("prime", context()) as PiGeneratedConfig; + const pi = buildClientConfig("pi", context()) as PiGeneratedConfig; + expect(pi.providers[OPENCODE_PROVIDER_ID]!.compat).toEqual({ sendSessionAffinityHeaders: true }); + delete pi.providers[OPENCODE_PROVIDER_ID]!.compat; + expect(prime).toEqual(pi); + expect(buildClientContribution("prime", context()).fragments[0]!.value) + .toEqual(prime.providers[OPENCODE_PROVIDER_ID]); }); test("adds only providers.opencodex, wired to the loopback proxy", () => { diff --git a/tests/config/client-config-export.test.ts b/tests/config/client-config-export.test.ts index 4d70790403..c5a5840b82 100644 --- a/tests/config/client-config-export.test.ts +++ b/tests/config/client-config-export.test.ts @@ -11,6 +11,7 @@ import { LOOPBACK_API_KEY_PLACEHOLDER, SCHEMA_REQUIRED_OUTPUT_BUDGET, buildClientConfig, + buildClientContribution, buildClientConfigText, isExportClientId, normalizeExportModels, @@ -316,6 +317,7 @@ describe("Pi serializer (accept criterion 2)", () => { expect(provider.api).toBe("openai-completions"); expect(provider.apiKey).toBe(LOOPBACK_API_KEY_PLACEHOLDER); expect(provider.compat?.sendSessionAffinityHeaders).toBe(true); + expect(buildClientContribution("pi", ctx()).fragments[0]!.value).toEqual(provider); }); test("cost is omitted on every entry — zeros would assert routed models are free", () => { From 75415170ba2e03398baa569972c4c444683e67fe Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:27:41 +0900 Subject: [PATCH 030/116] fix: admit final Claude request copies before serialization [skip ci] Co-authored-by: Ingwannu <186453546+Ingwannu@users.noreply.github.com> --- src/server/claude-messages.ts | 26 +++++++++---- tests/responses/reasoning-envelope.test.ts | 44 ++++++++++++++++++++-- 2 files changed, 59 insertions(+), 11 deletions(-) diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index a8af8896ff..c5c929c519 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -863,13 +863,25 @@ async function handleClaudeMessagesWithBudget( headers.set("session_id", uuidFromHex(internalBody.prompt_cache_key)); } } - const internalBodyJson = JSON.stringify(internalBody); - translatorBudget.chargeRetained(new TextEncoder().encode(internalBodyJson).byteLength, { kind: "request_copies" }); - const internalReq = new Request("http://localhost/v1/responses", { - method: "POST", - headers, - body: internalBodyJson, - }); + let internalReq: Request; + try { + // The UTF-16 JSON string and the Request's UTF-8 body coexist until dispatch. + const reservation = translatorBudget.reserveTransient(3 * jsonUtf8Bytes(internalBody), { kind: "request_copies" }); + try { + internalReq = new Request("http://localhost/v1/responses", { + method: "POST", + headers, + body: JSON.stringify(internalBody), + }); + reservation.commitRetained(); + } finally { + reservation.release(); + } + } catch (err) { + if (!isTranslatorBudgetExceededError(err)) throw err; + if (logIds) addFinalRequestLog(logIds.requestId, logIds.start, logCtx, 413, { closeReason: "non_stream" }); + return anthropicErrorResponse(413, "request translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit"); + } // Request-log wiring mirrors the /v1/responses route: native passthrough finalizes // via the terminal callbacks; routed streams get the Responses-vocabulary log tap diff --git a/tests/responses/reasoning-envelope.test.ts b/tests/responses/reasoning-envelope.test.ts index 4a26ce51db..27e21d5cff 100644 --- a/tests/responses/reasoning-envelope.test.ts +++ b/tests/responses/reasoning-envelope.test.ts @@ -160,8 +160,9 @@ describe("reasoning allocation admission", () => { test.each(["thinking", "redacted_thinking", "owned"])("handler maps %s admission failure to 413 without dispatch and disposes its budget", async type => { const { handleClaudeMessages } = await import("../../src/server/claude-messages"); - const signature = type === "owned" ? encodeReasoningEnvelope({ txt: "fixture" }) : "fixture"; - const content = type === "redacted_thinking" ? { type, data: "fixture" } + const payload = "fixture".repeat(128); + const signature = type === "owned" ? encodeReasoningEnvelope({ txt: payload }) : payload; + const content = type === "redacted_thinking" ? { type, data: payload } : { type: "thinking", thinking: "", signature }; const request = new Request("http://localhost/v1/messages", { method: "POST", headers: { "content-type": "application/json" }, @@ -170,15 +171,50 @@ describe("reasoning allocation admission", () => { const beforeBytes = budgets.translatorObservedBufferSnapshot().currentBytes; const beforeCount = budgets.translatorLiveBudgetCountForTests(); const create = budgets.createTranslatorBudget; - const factory = spyOn(budgets, "createTranslatorBudget").mockImplementation(() => create({ maxTurnBytes: 64 })); + const budget = create({ maxTurnBytes: 4096 }); + const reserve = spyOn(budget, "reserveTransient"); + const charge = spyOn(budget, "chargeRetained"); + const factory = spyOn(budgets, "createTranslatorBudget").mockReturnValue(budget); const upstream = spyOn(globalThis, "fetch").mockImplementation(async () => { throw new Error("unexpected upstream dispatch"); }); try { const response = await handleClaudeMessages(request, { port: 0, providers: {} }, { model: "", provider: "" }); expect(response.status).toBe(413); expect(await response.json()).toMatchObject({ type: "error", error: { type: "request_too_large", code: "translation_buffer_limit" } }); expect(upstream).not.toHaveBeenCalled(); + expect(reserve.mock.calls.some(([, scope]) => scope.kind === "reasoning")).toBe(true); + expect(charge.mock.calls.filter(([, scope]) => scope.kind === "request_copies")).toHaveLength(0); expect(budgets.translatorObservedBufferSnapshot().currentBytes).toBe(beforeBytes); expect(budgets.translatorLiveBudgetCountForTests()).toBe(beforeCount); - } finally { factory.mockRestore(); upstream.mockRestore(); } + } finally { factory.mockRestore(); upstream.mockRestore(); reserve.mockRestore(); charge.mockRestore(); budget.dispose(); } }); + test("final request-copy admission returns 413 before serialization and disposes the budget", async () => { + const { handleClaudeMessages } = await import("../../src/server/claude-messages"); + const request = new Request("http://localhost/v1/messages", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture/model", messages: [{ role: "user", content: "x".repeat(200) }] }), + }); + const beforeBytes = budgets.translatorObservedBufferSnapshot().currentBytes; + const beforeCount = budgets.translatorLiveBudgetCountForTests(); + const budget = budgets.createTranslatorBudget({ maxTurnBytes: 512 }); + const reserve = spyOn(budget, "reserveTransient"); + const charge = spyOn(budget, "chargeRetained"); + const factory = spyOn(budgets, "createTranslatorBudget").mockReturnValue(budget); + const stringify = spyOn(JSON, "stringify"); + const upstream = spyOn(globalThis, "fetch").mockImplementation(async () => { throw new Error("unexpected upstream dispatch"); }); + try { + const response = await handleClaudeMessages(request, { port: 0, providers: {} }, { model: "", provider: "" }); + expect(response.status).toBe(413); + expect(await response.json()).toMatchObject({ type: "error", error: { type: "request_too_large", code: "translation_buffer_limit" } }); + expect(charge.mock.calls.filter(([, scope]) => scope.kind === "request_copies")).toHaveLength(1); + expect(reserve.mock.calls.filter(([, scope]) => scope.kind === "request_copies")).toHaveLength(1); + expect(stringify.mock.calls.some(([value]) => value && typeof value === "object" && "input" in value)).toBe(false); + expect(upstream).not.toHaveBeenCalled(); + expect(budgets.translatorObservedBufferSnapshot().currentBytes).toBe(beforeBytes); + expect(budgets.translatorLiveBudgetCountForTests()).toBe(beforeCount); + } finally { + factory.mockRestore(); stringify.mockRestore(); upstream.mockRestore(); + reserve.mockRestore(); charge.mockRestore(); budget.dispose(); + } + }); + }); From 697a500339f323157ff20370e6be6bb65803e318 Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:29:47 +0900 Subject: [PATCH 031/116] test: pin Go affinity identity and header precedence [skip ci] Co-authored-by: makesomethingshit <246213378+makesomethingshit@users.noreply.github.com> --- .../opencode-go-session-header.test.ts | 27 ++++++++++++++++--- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/tests/providers/opencode-go-session-header.test.ts b/tests/providers/opencode-go-session-header.test.ts index b05e526e1c..ab28c8475f 100644 --- a/tests/providers/opencode-go-session-header.test.ts +++ b/tests/providers/opencode-go-session-header.test.ts @@ -1,10 +1,9 @@ import { afterEach, describe, expect, test } from "bun:test"; import { providerConfigSeed } from "../../src/providers/derive"; -import { deriveOpenCodeGoSessionId, resolveOpenCodeGoTransport } from "../../src/providers/opencode-go-transport"; +import { resolveOpenCodeGoTransport } from "../../src/providers/opencode-go-transport"; import { getProviderRegistryEntry } from "../../src/providers/registry"; import { handleResponses } from "../../src/server/responses/core"; import { handleChatCompletions } from "../../src/server/chat-completions"; -import { normalizeLogConversationId } from "../../src/server/request-log-conversation"; import type { OcxConfig, OcxProviderConfig } from "../../src/types"; const MUSE_MODEL = "muse-spark-1.3-contributor"; @@ -128,10 +127,13 @@ describe("OpenCode Go session affinity (#3344)", () => { expect(bridged.headers.get(SESSION_HEADER)).toBe(chat.headers.get(SESSION_HEADER)); }); - for (const session of ["client-session-a", "ocx_0123456789abcdef0123456789abcdef"]) { + // Fixed vectors independently calculated with SHA-256, including the domain separator. + for (const [session, expected] of [ + ["client-session-a", "ocx_516d593899f34b7baca2db37c7b0c8c5"], + ["ocx_0123456789abcdef0123456789abcdef", "ocx_60bcbfb9a85d3dc23b9b2b1cef3b0882"], + ] as const) { test(`treats inbound ${session.startsWith("ocx_") ? "ocx-prefixed" : "raw"} identity as client input on every ingress`, async () => { const headers = { "content-type": "application/json", [SESSION_HEADER]: session }; - const expected = deriveOpenCodeGoSessionId(normalizeLogConversationId(session)!); const native = await captureRequest({ nativeChat: true, model: "omen-alpha", headers }); const bridged = await captureRequest({ nativeChat: true, model: MUSE_MODEL, headers }); const responses = await captureRequest({ model: MUSE_MODEL, headers }); @@ -149,6 +151,23 @@ describe("OpenCode Go session affinity (#3344)", () => { }); } + test("operator override precedes the Codex lane, which precedes client fallback on every ingress", async () => { + const headers = { ...codexHeaders(), [SESSION_HEADER]: "different-client-fallback" }; + for (const ingress of [ + { nativeChat: true, model: "omen-alpha" }, + { nativeChat: true, model: MUSE_MODEL }, + { model: MUSE_MODEL }, + ]) { + const codex = await captureRequest({ ...ingress, headers }); + expect(codex.headers.get(SESSION_HEADER)).toBe("ocx_67b70584fb755130286eff5488a3be9d"); + const operator = await captureRequest({ + ...ingress, headers, + provider: opencodeGo({ headers: { "X-OpenCode-Session": "different-operator-override" } }), + }); + expect(operator.headers.get(SESSION_HEADER)).toBe("different-operator-override"); + } + }); + test("native Chat does not send Go affinity to an unrelated destination", async () => { const captured = await captureRequest({ nativeChat: true, model: "omen-alpha", providerName: "custom-go", From e0e8d26bb86927fac378d88807f191843a9cf339 Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:31:24 +0900 Subject: [PATCH 032/116] fix: fall back from native compact 404 to routed compaction [skip ci] Reimplements only the residual compaction portion of #3769; quota attribution remains the implementation already landed through #3791. Co-authored-by: ideabib <221318067+ideabib@users.noreply.github.com> --- .../content/docs/reference/proxy-formats.md | 7 + src/server/responses/compact.ts | 5 +- .../responses-compaction-routing.test.ts | 141 ++++++++++++++++++ 3 files changed, 151 insertions(+), 2 deletions(-) diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 0c7b8257bc..593c8ae7a3 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -405,6 +405,13 @@ conversation. | Canonical ChatGPT or official OpenAI route | Forwards the request to the native `/responses/compact` endpoint with the resolved account and model authentication | | Other routed model | Runs an internal, non-streaming, no-tools compaction turn with a `compaction_trigger`; requires exactly one synthetic `compaction` item whose `encrypted_content` is an `ocx1:` envelope; decodes that summary into v1 replacement history | +If the native compact endpoint returns HTTP 404, OpenCodex retries compaction through a regular +Responses turn with the same model selector and session headers. Canonical ChatGPT fallback +turns use upstream SSE; the compact caller still receives JSON. A completed native opaque +compaction item is preserved, while an `ocx1:` summary is decoded into replacement user history. +Failed or incomplete fallback turns return an error instead of replacement history. Other +native compact statuses retain their existing handling. + Codex names a bare OpenAI-family model (for example `gpt-5.6-sol`) for its compaction turns regardless of which provider the operator routes ordinary turns to. Ordinary requests reserve such ids for the canonical `openai` provider. On the compaction surface only — `POST diff --git a/src/server/responses/compact.ts b/src/server/responses/compact.ts index c914dcb4b2..4e7481bb2e 100644 --- a/src/server/responses/compact.ts +++ b/src/server/responses/compact.ts @@ -1094,7 +1094,8 @@ export async function handleResponsesCompact( } } } - return buffered; + // A native compact 404 falls back to a regular Responses compaction turn. + if (buffered.status !== 404) return buffered; } finally { releaseUpstreamHostAdmission(compactHostAdmissionLease); releaseCodexAuthContextProbeLease(authCtx); @@ -1111,7 +1112,7 @@ export async function handleResponsesCompact( // the completed event back into the v1 compact JSON contract below. Combo-dispatched // turns also go out as SSE: failover can land on a canonical child that rejects a // non-streaming turn, and every combo-capable provider already serves streaming traffic. - stream: accountGatedCompactWireModel || route.combo ? true : false, + stream: isCanonicalOpenAiForwardProvider(route.provider) || accountGatedCompactWireModel || route.combo ? true : false, input: [...inputItems, { type: "compaction_trigger" }], }; const internalHeaders = new Headers({ "content-type": "application/json" }); diff --git a/tests/responses/responses-compaction-routing.test.ts b/tests/responses/responses-compaction-routing.test.ts index a787024d95..2a1f69be1e 100644 --- a/tests/responses/responses-compaction-routing.test.ts +++ b/tests/responses/responses-compaction-routing.test.ts @@ -9,6 +9,7 @@ import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { handleResponses, handleResponsesCompact } from "../../src/server/responses"; +import { OPAQUE_COMPACTION_NOTE, SUMMARY_PREFIX } from "../../src/responses/compaction"; import { looksLikeBackendCiphertext } from "../../src/server/responses/encrypted-payload"; import * as adapterResolveModule from "../../src/server/adapter-resolve"; import * as visionModule from "../../src/vision"; @@ -948,6 +949,146 @@ describe("compact alternate-account attempt (#913)", () => { }); } + for (const [model, account] of [["gpt-5.5", "pool-a"], ["side/gpt-5.5", "pool-b"]] as const) { + test(`native 404 falls back to canonical SSE with ${model} account and session identity`, async () => { + await withPoolEnv("ocx-compact-404-canonical-", async config => { + config.codexAccountNamespaces = { side: "pool-b" }; + const item = { type: "compaction", id: "cmp_native_3769", encrypted_content: "native-opaque-3769" }; + const calls: Array<{ url: string; headers: Headers; body: Record }> = []; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const request = new Request(input, init); + calls.push({ url: request.url, headers: request.headers, body: await request.json() as Record }); + if (request.url.endsWith("/responses/compact")) return Response.json({ detail: "Not Found" }, { status: 404 }); + return sseResponse([{ type: "response.completed", response: { + id: "resp_compact_3769", status: "completed", output: [item], + } }]); + }) as typeof fetch; + const headers = { "session-id": "compact-3769-session", "thread-id": `compact-3769-${account}`, "x-codex-parent-thread-id": "compact-3769-parent" }; + const response = await handleResponsesCompact(compactionRequest({ + model, input: [{ role: "user", content: "retain this history" }], + }, undefined, headers), config, { model: "", provider: "" }); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toContain("application/json"); + expect(await response.json()).toEqual({ output: [item] }); + expect(calls.map(call => call.url)).toEqual([ + "https://chatgpt.com/backend-api/codex/responses/compact", + "https://chatgpt.com/backend-api/codex/responses", + ]); + expect(calls[1]!.body.stream).toBe(true); + expect(calls[1]!.body.model).toBe("gpt-5.5"); + expect((calls[1]!.body.input as Array<{ type?: string }>).filter(value => value.type === "compaction_trigger")).toHaveLength(1); + for (const call of calls) { + expect(call.headers.get("authorization")).toBe(`Bearer ${account}-access-token`); + expect(call.headers.get("chatgpt-account-id")).toBe(account === "pool-a" ? "pool_acc_a" : "pool_acc_b"); + for (const [name, value] of Object.entries(headers)) expect(call.headers.get(name)).toBe(value); + } + }); + }); + } + + test("official key-auth native 404 decodes synthetic fallback into replacement user history", async () => { + const config = { providers: { "openai-apikey": { + adapter: "openai-responses", baseUrl: "https://api.openai.com/v1", authMode: "key", apiKey: "test-key", + } } } as OcxConfig; + const calls: Array<{ url: string; body: Record }> = []; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const request = new Request(input, init); + calls.push({ url: request.url, body: await request.json() as Record }); + return request.url.endsWith("/responses/compact") + ? Response.json({ detail: "Not Found" }, { status: 404 }) + : jsonResponse(completedPayload("handoff-3769")); + }) as typeof fetch; + const response = await handleResponsesCompact(compactionRequest({ + model: "openai-apikey/gpt-5.5", input: [{ role: "user", content: "retain-3769" }], + tools: [{ type: "function", name: "shell", parameters: { type: "object" } }], + }), config, { model: "", provider: "" }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ output: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "retain-3769" }] }, + { type: "message", role: "user", content: [{ type: "input_text", text: `${SUMMARY_PREFIX}\nhandoff-3769` }] }, + ] }); + expect(calls.map(call => call.url)).toEqual(["https://api.openai.com/v1/responses/compact", "https://api.openai.com/v1/responses"]); + expect(calls[1]!.body.tools).toBeUndefined(); + expect(JSON.stringify(calls[1]!.body.input)).not.toContain("compaction_trigger"); + expect(JSON.stringify(calls[1]!.body.input)).toContain("CONTEXT CHECKPOINT COMPACTION"); + }); + + for (const status of [200, 400]) { + test(`native compact ${status} retains its body without the 404 fallback`, async () => { + await withPoolEnv("ocx-compact-404-control-", async config => { + const payload = status === 200 ? { output: [{ type: "compaction", encrypted_content: "native-control" }] } : { error: { message: "invalid compact" } }; + const urls: string[] = []; + globalThis.fetch = (async (input: string | URL | Request) => { + urls.push(typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url); + return Response.json(payload, { status }); + }) as typeof fetch; + const response = await handleResponsesCompact(compactionRequest({ model: "gpt-5.5", input: [] }), config, { model: "", provider: "" }); + expect(response.status).toBe(status); + expect(await response.json()).toEqual(payload); + expect(urls).toEqual(["https://chatgpt.com/backend-api/codex/responses/compact"]); + }); + }); + } + + for (const status of ["failed", "incomplete"] as const) { + test(`native 404 followed by ${status} SSE does not install replacement history`, async () => { + await withPoolEnv("ocx-compact-404-terminal-", async config => { + let calls = 0; + globalThis.fetch = (async () => { + calls++; + if (calls === 1) return Response.json({ detail: "Not Found" }, { status: 404 }); + return sseResponse([{ type: `response.${status}`, response: { + id: "resp_compact_rejected_3769", status, output: [], + } }]); + }) as typeof fetch; + const response = await handleResponsesCompact(compactionRequest({ model: "gpt-5.5", input: [] }), config, { model: "", provider: "" }); + expect(response.status).toBe(502); + const payload = await response.json() as { output?: unknown; error?: unknown }; + expect(payload.output).toBeUndefined(); + expect(payload.error).toBeDefined(); + expect(calls).toBe(2); + }); + }); + } + + test("404 fallback records the compaction serving account for subsequent opaque replay", async () => { + await withPoolEnv("ocx-compact-404-replay-", async config => { + config.codexAccountNamespaces = { side: "pool-b", first: "pool-a" }; + const headers = { "thread-id": `compact-replay-${crypto.randomUUID()}` }; + const item = { type: "compaction", encrypted_content: "native-account-b-3769" }; + const calls: Array<{ body: Record; headers: Headers }> = []; + let compacting = false; + globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => { + const request = new Request(input, init); + if (request.url.endsWith("/responses/compact")) return Response.json({ detail: "Not Found" }, { status: 404 }); + calls.push({ body: await request.json() as Record, headers: request.headers }); + return sseResponse([{ type: "response.completed", response: compacting + ? { id: "resp_identity_compact_3769", status: "completed", output: [item] } + : completedPayload("ordinary turn") }]); + }) as typeof fetch; + const turn = async (model: string, input: unknown[]) => { + const response = await handleResponses(compactionRequest({ model, input, stream: true, store: false }, undefined, headers), config, { model: "", provider: "" }); + expect(response.status).toBe(200); + await response.text(); + }; + await turn("first/gpt-5.5", [{ role: "user", content: "seed account A" }]); + compacting = true; + const compact = await handleResponsesCompact(compactionRequest({ model: "side/gpt-5.5", input: [{ role: "user", content: "compact on B" }] }, undefined, headers), config, { model: "", provider: "" }); + expect(compact.status).toBe(200); + const output = (await compact.json() as { output: unknown[] }).output; + expect(output).toEqual([item]); + compacting = false; + await turn("side/gpt-5.5", [...output, { role: "user", content: "continue on B" }]); + expect(calls.at(-1)!.headers.get("authorization")).toBe("Bearer pool-b-access-token"); + expect(JSON.stringify(calls.at(-1)!.body.input)).toContain("native-account-b-3769"); + await turn("first/gpt-5.5", [...output, { role: "user", content: "switch back to A" }]); + expect(calls.at(-1)!.headers.get("authorization")).toBe("Bearer pool-a-access-token"); + expect(JSON.stringify(calls.at(-1)!.body.input)).not.toContain("native-account-b-3769"); + expect(JSON.stringify(calls.at(-1)!.body.input)).toContain(OPAQUE_COMPACTION_NOTE); + expect(calls).toHaveLength(4); + }); + }); + test("native compact headers followed by a stalled body return 504 without retry and release account cleanup", async () => { await withPoolEnv("ocx-compact-body-deadline-", async config => { config.stallTimeoutSec = 2; From d8b18b1ecb013f46585c9e6dadac0b95caa49836 Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:49:44 +0900 Subject: [PATCH 033/116] fix: share envelope admission budgets and release transient request copies [skip ci] Thread live budgets through bridge and outbound callers, keep abnormal bridge cleanup on the typed overflow path, and retain only the constructed request body after serialization. Sync the authorized adapter and reference locale contracts. Co-authored-by: Ingwannu <186453546+Ingwannu@users.noreply.github.com> --- .../docs/ja/reference/proxy-formats.md | 5 + .../docs/ko/reference/proxy-formats.md | 5 + .../src/content/docs/reference/adapters.md | 4 + .../docs/ru/reference/proxy-formats.md | 6 + .../docs/zh-cn/reference/proxy-formats.md | 4 + src/bridge.ts | 64 ++++--- src/claude/outbound.ts | 10 +- src/server/claude-messages.ts | 13 +- tests/responses/reasoning-envelope.test.ts | 163 +++++++++++++++++- 9 files changed, 241 insertions(+), 33 deletions(-) diff --git a/docs-site/src/content/docs/ja/reference/proxy-formats.md b/docs-site/src/content/docs/ja/reference/proxy-formats.md index 68d7ce5c75..8f0a03bc09 100644 --- a/docs-site/src/content/docs/ja/reference/proxy-formats.md +++ b/docs-site/src/content/docs/ja/reference/proxy-formats.md @@ -131,6 +131,11 @@ WebSocket が無効になっている場合、アップグレード試行では これらのエンドポイントは、Claude Code および互換性のあるクライアントによって使用される Anthropic Messages 言語を話します。ほとんどのリクエストはレスポンスに変換され、通常どおりルーティングされてから、Anthropic JSON または Anthropic SSE に変換されます。 +変換される Messages リクエストでは、推論の再送もリクエスト共通の変換バジェットを使います。 +この制限にはエンコード・デコード時のコピー分も含まれます。超過時は +`translation_buffer_limit` を伴う HTTP 413 を返し、署名や不透明な推論データを切り詰めません。 +ネイティブ Anthropic パススルーには、別の本文サイズ制限が適用されます。 + ネイティブ Anthropic パススルーは、次のすべてが当てはまる場合にのみ適格です。 - ネイティブ パススルーはクロード コード設定で無効になっていません。 diff --git a/docs-site/src/content/docs/ko/reference/proxy-formats.md b/docs-site/src/content/docs/ko/reference/proxy-formats.md index f7ff7f5f27..7837ae4d22 100644 --- a/docs-site/src/content/docs/ko/reference/proxy-formats.md +++ b/docs-site/src/content/docs/ko/reference/proxy-formats.md @@ -174,6 +174,11 @@ SSE 객체, choice delta, `finish_reason`이 있는 종료 choice, `data: [DONE] 이 엔드포인트는 Claude Code와 호환 클라이언트가 사용하는 Anthropic Messages 방언을 말합니다. 대부분의 요청은 Responses로 변환되어 일반적으로 라우팅된 뒤, Anthropic JSON 또는 Anthropic SSE로 다시 변환됩니다. +변환되는 Messages 요청의 reasoning 재전송은 요청 전체의 번역 예산을 공유합니다. 이 예산에는 +인코딩·디코딩 과정에서 생기는 복사본도 포함됩니다. 한도를 초과하면 `translation_buffer_limit`과 +HTTP 413을 반환하며, 한도에 맞추려고 서명이나 불투명 reasoning 데이터를 자르지 않습니다. +네이티브 Anthropic passthrough에는 별도의 본문 크기 제한이 적용됩니다. + 네이티브 Anthropic passthrough는 다음이 모두 참일 때만 적용됩니다. - Claude Code 설정에서 native passthrough가 비활성화되어 있지 않습니다. diff --git a/docs-site/src/content/docs/reference/adapters.md b/docs-site/src/content/docs/reference/adapters.md index 03c56f329b..b1d6029ca9 100644 --- a/docs-site/src/content/docs/reference/adapters.md +++ b/docs-site/src/content/docs/reference/adapters.md @@ -195,6 +195,10 @@ header and does not guarantee a provider cache hit. **Auth:** `key` (`x-api-key` by default, or `Authorization: Bearer` with `apiKeyTransport: "bearer"`) or `oauth` (Bearer + `anthropic-beta`, for Claude Pro/Max). - Converts messages to Anthropic content blocks (text, base64 image, `tool_use`, `thinking`). +- Translated Anthropic Messages reasoning replay shares the request translation budget, including + encoding/decoding copy overhead. Requests exceeding it return HTTP 413 with + `translation_buffer_limit`; signatures and opaque reasoning data are never truncated to fit. + Native Anthropic passthrough uses its separate body-size contract. - **Extended thinking math:** Anthropic requires `max_tokens > thinking.budget_tokens`. The adapter maps reasoning effort to a budget (minimal 1024 … max 32000), then computes a safe `max_tokens` with output headroom, and **drops `temperature`/`top_p`** when thinking is enabled (Anthropic forbids diff --git a/docs-site/src/content/docs/ru/reference/proxy-formats.md b/docs-site/src/content/docs/ru/reference/proxy-formats.md index 26d4db5709..a3ef007784 100644 --- a/docs-site/src/content/docs/ru/reference/proxy-formats.md +++ b/docs-site/src/content/docs/ru/reference/proxy-formats.md @@ -179,6 +179,12 @@ adapter, вместо тихого изменения смысла вернёт клиенты. Большинство запросов переводится в Responses, маршрутизируется обычным образом, а затем обратно в Anthropic JSON или Anthropic SSE. +Повторная передача reasoning в преобразуемых запросах Messages использует общий бюджет +преобразования запроса, включая копии при кодировании и декодировании. При превышении лимита +возвращается HTTP 413 с `translation_buffer_limit`; подписи и непрозрачные данные reasoning +не обрезаются для соблюдения лимита. Для нативного Anthropic passthrough действует отдельный +контракт ограничения размера тела. + Нативный Anthropic passthrough допустим только когда одновременно выполняются все условия: - native passthrough не отключён в конфигурации Claude Code; diff --git a/docs-site/src/content/docs/zh-cn/reference/proxy-formats.md b/docs-site/src/content/docs/zh-cn/reference/proxy-formats.md index 21948d6264..9736aeaff9 100644 --- a/docs-site/src/content/docs/zh-cn/reference/proxy-formats.md +++ b/docs-site/src/content/docs/zh-cn/reference/proxy-formats.md @@ -149,6 +149,10 @@ choice 增量、带 `finish_reason` 的终止 choice,以及 `data: [DONE]`。 这些端点使用 Claude Code 和兼容客户端所采用的 Anthropic Messages 方言。大多数请求会被转换为 Responses,按常规路由,然后再转换回 Anthropic JSON 或 Anthropic SSE。 +转换后的 Messages 请求在重放推理数据时共享整个请求的转换预算,其中包含编码和解码产生的副本开销。 +超出预算时返回 HTTP 413 和 `translation_buffer_limit`,不会为了满足限制而截断签名或不透明推理数据。 +原生 Anthropic 透传使用独立的请求体大小限制。 + 只有在满足以下全部条件时,原生 Anthropic 透传才有资格启用: - Claude Code 配置中尚未禁用原生透传; diff --git a/src/bridge.ts b/src/bridge.ts index ff044a5e52..20e7c3fe09 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -493,7 +493,7 @@ export function bridgeToResponsesSSE( const previousBytes = pendingSignatureBytes + pendingRedacted.reduce((sum, value) => sum + bytesOf(value), 0) + (hiddenText ? hiddenThinkingBytes : 0); - const encoded = encodeReasoningEnvelope(envelope); + const encoded = encodeReasoningEnvelope(envelope, budget); const reservation = budget?.reserveTransient(bytesOf(encoded), { kind: "reasoning" }); pendingSignature = undefined; pendingSignatureBytes = 0; @@ -533,7 +533,7 @@ export function bridgeToResponsesSSE( if (!hiddenRawReasoningText) return; rawReasoningForNextToolCall = hiddenRawReasoningText; const previousBytes = hiddenRawReasoningBytes; - const encrypted = encodeReasoningEnvelope({ txt: hiddenRawReasoningText }); + const encrypted = encodeReasoningEnvelope({ txt: hiddenRawReasoningText }, budget); const reservation = budget?.reserveTransient(bytesOf(encrypted), { kind: "reasoning" }); hiddenRawReasoningText = ""; hiddenRawReasoningBytes = 0; @@ -556,7 +556,7 @@ export function bridgeToResponsesSSE( const flushKiroRedactedReasoning = () => { if (!pendingKiroRedacted) return; const previousBytes = pendingKiroRedactedBytes; - const encrypted = encodeReasoningEnvelope({ krc: pendingKiroRedacted }); + const encrypted = encodeReasoningEnvelope({ krc: pendingKiroRedacted }, budget); const reservation = budget?.reserveTransient(bytesOf(encrypted), { kind: "reasoning" }); pendingKiroRedacted = undefined; pendingKiroRedactedBytes = 0; @@ -902,6 +902,16 @@ export function bridgeToResponsesSSE( gated = true; stepping = false; }; + const attemptTerminationCleanup = (action: () => void): boolean => { + try { + action(); + return !terminated && !closed; + } catch (error) { + if (!isTranslatorBudgetExceededError(error)) throw error; + terminateForTranslatorOverflow(error); + return false; + } + }; const step = async () => { if (stepping || closed) return; stepping = true; @@ -1415,10 +1425,12 @@ export function bridgeToResponsesSSE( return; } if (!terminated) { - flushHiddenRawReasoning(); - if (currentToolCall) failCurrentToolCall(); - if (currentWebSearch) closeCurrentWebSearch("failed", []); - releasePendingWebSources(); + if (!attemptTerminationCleanup(() => { + flushHiddenRawReasoning(); + if (currentToolCall) failCurrentToolCall(); + if (currentWebSearch) closeCurrentWebSearch("failed", []); + releasePendingWebSources(); + })) return; const failure = responseError( 500, "proxy_error", @@ -1448,13 +1460,15 @@ export function bridgeToResponsesSSE( if (!terminated) { // The adapter generator ended without an explicit done/error event. Mark as incomplete // rather than completed so Codex can distinguish a clean finish from a truncated stream. - if (currentMsg) closeCurrentMessage(); - if (currentReasoning) closeCurrentReasoning(); - if (currentRawReasoning) closeCurrentRawReasoning(); - flushHiddenRawReasoning(); - if (currentToolCall) failCurrentToolCall(); - if (currentWebSearch) closeCurrentWebSearch("failed", []); - releasePendingWebSources(); + if (!attemptTerminationCleanup(() => { + if (currentMsg) closeCurrentMessage(); + if (currentReasoning) closeCurrentReasoning(); + if (currentRawReasoning) closeCurrentRawReasoning(); + flushHiddenRawReasoning(); + if (currentToolCall) failCurrentToolCall(); + if (currentWebSearch) closeCurrentWebSearch("failed", []); + releasePendingWebSources(); + })) return; options?.onUsage?.(undefined); await awaitThoughtSignatureDurability(); emit("response.incomplete", { @@ -1493,13 +1507,15 @@ export function bridgeToResponsesSSE( upstreamActivity = false; stallTicks = 0; } else if (++stallTicks >= maxStallTicks) { - if (currentMsg) closeCurrentMessage(); - if (currentReasoning) closeCurrentReasoning(); - if (currentRawReasoning) closeCurrentRawReasoning(); - flushHiddenRawReasoning(); - if (currentToolCall) failCurrentToolCall(); - if (currentWebSearch) closeCurrentWebSearch("failed", []); - releasePendingWebSources(); + if (!attemptTerminationCleanup(() => { + if (currentMsg) closeCurrentMessage(); + if (currentReasoning) closeCurrentReasoning(); + if (currentRawReasoning) closeCurrentRawReasoning(); + flushHiddenRawReasoning(); + if (currentToolCall) failCurrentToolCall(); + if (currentWebSearch) closeCurrentWebSearch("failed", []); + releasePendingWebSources(); + })) return; // #1926 gap 2 residual: this beat callback is synchronous, so the durability // barrier is not awaited on the stall-timeout kill path. The in-memory store is // already updated; only a crash between here and the queued write loses it, @@ -1728,7 +1744,7 @@ function buildResponseJSONWithBudget( if (batchRedacted.length > 0) envelope.red = batchRedacted; const hidden = options?.hideThinkingSummary === true; if (hidden && currentSummaryReasoning && (envelope.sig || envelope.red)) envelope.txt = currentSummaryReasoning; - const encrypted = envelope.sig || envelope.red || envelope.txt ? encodeReasoningEnvelope(envelope) : undefined; + const encrypted = envelope.sig || envelope.red || envelope.txt ? encodeReasoningEnvelope(envelope, budget) : undefined; const sourceBytes = currentSummaryReasoningBytes + batchSignatureBytes + batchRedactedBytes; batchSignature = undefined; batchSignatureBytes = 0; @@ -1756,7 +1772,7 @@ function buildResponseJSONWithBudget( // Same contract as the streaming path: no visible reasoning, txt-only envelope round-trip. pushOutput({ type: "reasoning", id: `rs_${uuid()}`, summary: [], - encrypted_content: encodeReasoningEnvelope({ txt: currentRawReasoning }), + encrypted_content: encodeReasoningEnvelope({ txt: currentRawReasoning }, budget), }, currentRawReasoningBytes, "reasoning"); currentRawReasoning = ""; currentRawReasoningBytes = 0; @@ -2044,7 +2060,7 @@ function buildResponseJSONWithBudget( // pushOutput reserves the item itself and releases the retained raw blob it replaces. pushOutput({ type: "reasoning", id: `rs_${uuid()}`, summary: [], - encrypted_content: encodeReasoningEnvelope({ krc: batchKiroRedacted }), + encrypted_content: encodeReasoningEnvelope({ krc: batchKiroRedacted }, budget), }, batchKiroRedactedBytes, "reasoning"); batchKiroRedacted = undefined; batchKiroRedactedBytes = 0; diff --git a/src/claude/outbound.ts b/src/claude/outbound.ts index ac06afac2d..1975d5b390 100644 --- a/src/claude/outbound.ts +++ b/src/claude/outbound.ts @@ -308,7 +308,7 @@ export function responsesSseToAnthropicSse( open.webSearchArgsEmitted = true; } if (open.kind === "thinking") { - const signature = open.reasoningSig ?? encodeReasoningEnvelope({ txt: open.thinkingBuf ?? "" }); + const signature = open.reasoningSig ?? encodeReasoningEnvelope({ txt: open.thinkingBuf ?? "" }, translatorBudget); emit("content_block_delta", { type: "content_block_delta", index: open.index, delta: { type: "signature_delta", signature }, @@ -561,7 +561,7 @@ export function responsesSseToAnthropicSse( else if (open && open.kind === "text" && item.type === "message") closeOpenBlock(); else if (item.type === "reasoning") { const encrypted = typeof item.encrypted_content === "string" ? item.encrypted_content : ""; - const env = encrypted ? decodeReasoningEnvelope(encrypted) : null; + const env = encrypted ? decodeReasoningEnvelope(encrypted, translatorBudget) : null; const red = env?.red ?? []; if (env?.sig && open?.kind !== "thinking") ensureBlock("thinking"); if (open?.kind === "thinking") { @@ -785,7 +785,7 @@ export function responsesSseToAnthropicSse( } /** Non-streaming: /v1/responses JSON -> Anthropic message JSON. */ -export function responsesJsonToAnthropicMessage(json: unknown, model: string): Rec { +export function responsesJsonToAnthropicMessage(json: unknown, model: string, translatorBudget?: TranslatorBudget): Rec { const body = isRec(json) ? json : {}; const output = Array.isArray(body.output) ? body.output : []; const content: Rec[] = []; @@ -817,14 +817,14 @@ export function responsesJsonToAnthropicMessage(json: unknown, model: string): R } } const encrypted = typeof raw.encrypted_content === "string" ? raw.encrypted_content : ""; - const env = encrypted ? decodeReasoningEnvelope(encrypted) : null; + const env = encrypted ? decodeReasoningEnvelope(encrypted, translatorBudget) : null; // Legacy combined envelopes place redacted blocks before the signed block, // matching the Anthropic adapter. New bridge output uses separate items. for (const data of env?.red ?? []) content.push({ type: "redacted_thinking", data }); // env.txt may be locally hidden text. Do not expose it here or manufacture // a new signed continuity carrier; hidden-summary replay remains limited. if (parts.length > 0 || env?.sig) { - content.push({ type: "thinking", thinking: parts.join("\n\n"), signature: env?.sig ?? encodeReasoningEnvelope({ txt: parts.join("\n\n") }) }); + content.push({ type: "thinking", thinking: parts.join("\n\n"), signature: env?.sig ?? encodeReasoningEnvelope({ txt: parts.join("\n\n") }, translatorBudget) }); } break; } diff --git a/src/server/claude-messages.ts b/src/server/claude-messages.ts index c5c929c519..f6906de7e0 100644 --- a/src/server/claude-messages.ts +++ b/src/server/claude-messages.ts @@ -866,17 +866,18 @@ async function handleClaudeMessagesWithBudget( let internalReq: Request; try { // The UTF-16 JSON string and the Request's UTF-8 body coexist until dispatch. - const reservation = translatorBudget.reserveTransient(3 * jsonUtf8Bytes(internalBody), { kind: "request_copies" }); + const bodyBytes = jsonUtf8Bytes(internalBody); + const reservation = translatorBudget.reserveTransient(3 * bodyBytes, { kind: "request_copies" }); try { internalReq = new Request("http://localhost/v1/responses", { method: "POST", headers, body: JSON.stringify(internalBody), }); - reservation.commitRetained(); } finally { reservation.release(); } + translatorBudget.chargeRetained(bodyBytes, { kind: "request_copies" }); } catch (err) { if (!isTranslatorBudgetExceededError(err)) throw err; if (logIds) addFinalRequestLog(logIds.requestId, logIds.start, logCtx, 413, { closeReason: "non_stream" }); @@ -1019,7 +1020,13 @@ async function handleClaudeMessagesWithBudget( } return anthropicErrorResponse(502, error?.message ?? "upstream request failed", "api_error"); } - const message = responsesJsonToAnthropicMessage(json, requestedModel); + let message: Rec; + try { + message = responsesJsonToAnthropicMessage(json, requestedModel, translatorBudget); + } catch (err) { + if (!isTranslatorBudgetExceededError(err)) throw err; + return anthropicErrorResponse(413, "upstream translation buffer exceeded the safe limit", "request_too_large", "translation_buffer_limit"); + } if ((message as Rec).type === "error") { return new Response(JSON.stringify(message), { status: 529, diff --git a/tests/responses/reasoning-envelope.test.ts b/tests/responses/reasoning-envelope.test.ts index 27e21d5cff..6ffc2d750f 100644 --- a/tests/responses/reasoning-envelope.test.ts +++ b/tests/responses/reasoning-envelope.test.ts @@ -1,7 +1,9 @@ import { describe, expect, spyOn, test } from "bun:test"; +import { bridgeToResponsesSSE, buildResponseJSON } from "../../src/bridge"; +import type { AdapterEvent } from "../../src/types"; import { anthropicToResponsesBody, anthropicToResponsesTranslation } from "../../src/claude/inbound"; import { decodeReasoningEnvelope, encodeReasoningEnvelope, OCX_REASONING_PREFIX, type ReasoningEnvelope } from "../../src/responses/reasoning-envelope"; -import { responsesJsonToAnthropicMessage } from "../../src/claude/outbound"; +import { responsesJsonToAnthropicMessage, responsesSseToAnthropicSse } from "../../src/claude/outbound"; import { createTranslatorBudget, TranslatorBudgetExceededError, translatorObservedBufferSnapshot } from "../../src/lib/translator-budget"; import { jsonUtf8Bytes } from "../../src/lib/json-byte-size"; import * as budgets from "../../src/lib/translator-budget"; @@ -217,4 +219,163 @@ describe("reasoning allocation admission", () => { } }); + test("successful Request construction retains only its UTF-8 body after releasing temporary copies", async () => { + const { handleClaudeMessages } = await import("../../src/server/claude-messages"); + const request = new Request("http://localhost/v1/messages", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture/model", messages: [{ role: "user", content: "hello" }] }), + }); + const budget = budgets.createTranslatorBudget({ maxTurnBytes: 4096 }); + const originalCharge = budget.chargeRetained.bind(budget); + const copies: Array<{ bytes: number; before: number; after: number }> = []; + const charge = spyOn(budget, "chargeRetained").mockImplementation((bytes, scope) => { + const before = budget.snapshot().currentBytes; + originalCharge(bytes, scope); + if (scope.kind === "request_copies") copies.push({ bytes, before, after: budget.snapshot().currentBytes }); + }); + const reserve = spyOn(budget, "reserveTransient"); + const factory = spyOn(budgets, "createTranslatorBudget").mockReturnValue(budget); + const stringify = spyOn(JSON, "stringify"); + try { + const response = await handleClaudeMessages(request, { port: 0, providers: {} }, { model: "", provider: "" }); + expect(response.status).toBe(404); // Serialization succeeded; the synthetic model is deliberately absent. + await response.text(); + const serialized = stringify.mock.calls.find(([value]) => value && typeof value === "object" && "input" in value)?.[0]; + expect(serialized).toBeDefined(); + const expected = Buffer.byteLength(JSON.stringify(serialized)); + expect(copies).toHaveLength(2); + expect(copies[1]!.bytes).toBe(expected); + expect(copies[1]!.before).toBe(copies[0]!.after); + expect(reserve.mock.calls.filter(([, scope]) => scope.kind === "request_copies").map(([bytes]) => bytes)).toEqual([3 * expected]); + expect(budget.snapshot().currentBytes).toBe(0); + } finally { stringify.mockRestore(); factory.mockRestore(); reserve.mockRestore(); charge.mockRestore(); budget.dispose(); } + }); + + for (const event of [ + { type: "thinking_signature", signature: "r".repeat(256) }, + { type: "redacted_thinking", data: "r".repeat(256) }, + { type: "reasoning_raw_delta", text: "r".repeat(256) }, + { type: "kiro_redacted_reasoning", data: "r".repeat(256) }, + ] as const) { + for (const mode of ["batch", "stream"] as const) { + test(`${mode} ${event.type} admits envelope copies against the already charged turn`, async () => { + const budget = createTranslatorBudget({ maxTurnBytes: 4096 }); + budget.chargeRetained(2048, { kind: "request_copies" }); + const stringify = spyOn(JSON, "stringify"); + try { + const events: AdapterEvent[] = [event, { type: "done" }]; + if (mode === "batch") { + expect(() => buildResponseJSON(events, "fixture/model", { translatorBudget: budget, hideThinkingSummary: true })) + .toThrow(TranslatorBudgetExceededError); + } else { + async function* source() { yield* events; } + const wire = await new Response(bridgeToResponsesSSE(source(), "fixture/model", undefined, undefined, undefined, undefined, undefined, + { translatorBudget: budget, hideThinkingSummary: true })).text(); + expect(wire).toContain('"code":"translation_buffer_limit"'); + expect(wire).not.toContain('event: response.completed'); + } + expect(stringify.mock.calls.some(([value]) => value && typeof value === "object" + && ("sig" in value || "txt" in value || "red" in value || "krc" in value))).toBe(false); + } finally { stringify.mockRestore(); budget.dispose(); } + }); + } + } + + for (const encoded of [false, true]) { + test(`JSON outbound ${encoded ? "decoding" : "encoding"} uses the caller budget before allocation`, () => { + const item = encoded + ? { type: "reasoning", encrypted_content: encodeReasoningEnvelope({ sig: "r".repeat(256) }), summary: [] } + : { type: "reasoning", summary: [{ type: "summary_text", text: "r".repeat(256) }] }; + const budget = createTranslatorBudget({ maxTurnBytes: 4096 }); + budget.chargeRetained(2048, { kind: "request_copies" }); + const from = spyOn(Buffer, "from"); + try { + expect(() => responsesJsonToAnthropicMessage({ output: [item] }, "fixture/model", budget)).toThrow(TranslatorBudgetExceededError); + expect(from).not.toHaveBeenCalled(); + } finally { from.mockRestore(); budget.dispose(); } + }); + } + + for (const ending of ["throw", "eof", "stall"] as const) { + for (const overflow of [false, true]) { + test(`hidden reasoning ${ending} cleanup ${overflow ? "reports one budget failure" : "preserves its admitted terminal"}`, async () => { + const budget = createTranslatorBudget({ maxTurnBytes: overflow ? 4096 : 65536 }); + budget.chargeRetained(2048, { kind: "request_copies" }); + const accumulated = Promise.withResolvers(); + const pending = Promise.withResolvers>(); + let reads = 0; + let returns = 0; + let cancelled = 0; + let clears = 0; + let beat = () => {}; + const source: AsyncIterableIterator = { + [Symbol.asyncIterator]() { return this; }, + async next() { + if (++reads === 1) return { done: false, value: { type: "reasoning_raw_delta", text: "r".repeat(256) } }; + accumulated.resolve(); + if (ending === "throw") throw new Error("synthetic generator failure"); + if (ending === "eof") return { done: true, value: undefined }; + return pending.promise; + }, + async return() { returns++; pending.resolve({ done: true, value: undefined }); return { done: true, value: undefined }; }, + }; + const stringify = spyOn(JSON, "stringify"); + try { + const stream = bridgeToResponsesSSE(source, "fixture/model", undefined, undefined, undefined, + () => { cancelled++; }, 500, { + translatorBudget: budget, hideThinkingSummary: true, stallTimeoutSec: 1, + timers: { setInterval(callback) { beat = callback; return 1; }, clearInterval() { clears++; beat = () => {}; } }, + }); + const result = new Response(stream).text(); + await accumulated.promise; + if (ending === "stall") { beat(); beat(); beat(); } + const wire = await result; + const envelopes = stringify.mock.calls.filter(([value]) => value && typeof value === "object" && "txt" in value); + expect(wire.match(/data: \[DONE\]/g)).toHaveLength(1); + expect(wire).not.toContain("event: response.completed"); + expect(clears).toBe(1); + if (overflow) { + expect(envelopes).toHaveLength(0); + expect(wire.match(/event: response.failed/g)).toHaveLength(1); + expect(wire).toContain('"code":"translation_buffer_limit"'); + expect(wire).not.toContain("event: response.incomplete"); + expect(cancelled).toBe(1); + expect(returns).toBe(1); + } else { + expect(envelopes).toHaveLength(1); + expect(wire).not.toContain("translation_buffer_limit"); + expect(wire.match(new RegExp(`event: response.${ending === "throw" ? "failed" : "incomplete"}`, "g"))).toHaveLength(1); + expect(cancelled).toBe(ending === "eof" ? 0 : 1); + } + } finally { stringify.mockRestore(); pending.resolve({ done: true, value: undefined }); budget.dispose(); } + }); + } + } + + for (const encoded of [false, true]) { + test(`SSE outbound ${encoded ? "decoding" : "encoding"} admits against its live turn budget`, async () => { + const text = "r".repeat(512); + const events = encoded ? [{ type: "response.output_item.done", item: { + type: "reasoning", encrypted_content: encodeReasoningEnvelope({ sig: text }), summary: [], + } }] : [ + { type: "response.reasoning_summary_text.delta", delta: text }, + { type: "response.completed", response: { status: "completed", output: [] } }, + ]; + const frames = events.map(event => new TextEncoder().encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`)); + const budget = createTranslatorBudget({ maxTurnBytes: 8192 }); + budget.chargeRetained(4096, { kind: "request_copies" }); + const reserve = spyOn(budget, "reserveTransient"); + const from = spyOn(Buffer, "from"); + try { + const upstream = new ReadableStream({ start(controller) { frames.forEach(frame => controller.enqueue(frame)); controller.close(); } }); + const wire = await new Response(responsesSseToAnthropicSse(upstream, "fixture/model", { translatorBudget: budget, pingIntervalMs: 0 })).text(); + expect(reserve.mock.calls.some(([bytes, scope]) => scope.kind === "reasoning" && bytes > 4096)).toBe(true); + expect(from).not.toHaveBeenCalled(); + expect(wire.match(/event: error/g)).toHaveLength(1); + expect(wire).toContain('"code":"translation_buffer_limit"'); + expect(wire).not.toContain("event: message_stop"); + } finally { reserve.mockRestore(); from.mockRestore(); budget.dispose(); } + }); + } + }); From feb1855df91e5db351699d959d88d7e6c21c0f93 Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:59:23 +0900 Subject: [PATCH 034/116] docs: include Pi session affinity in every guide example [skip ci] Co-authored-by: makesomethingshit <246213378+makesomethingshit@users.noreply.github.com> --- docs-site/src/content/docs/fr/guides/pi.md | 5 +++++ docs-site/src/content/docs/guides/pi.md | 5 +++++ docs-site/src/content/docs/ja/guides/pi.md | 5 +++++ docs-site/src/content/docs/ko/guides/pi.md | 5 +++++ docs-site/src/content/docs/ru/guides/pi.md | 5 +++++ docs-site/src/content/docs/tr/guides/pi.md | 5 +++++ docs-site/src/content/docs/zh-cn/guides/pi.md | 5 +++++ docs-site/src/content/docs/zh-tw/guides/pi.md | 5 +++++ 8 files changed, 40 insertions(+) diff --git a/docs-site/src/content/docs/fr/guides/pi.md b/docs-site/src/content/docs/fr/guides/pi.md index eab8960063..030d91679c 100644 --- a/docs-site/src/content/docs/fr/guides/pi.md +++ b/docs-site/src/content/docs/fr/guides/pi.md @@ -27,6 +27,9 @@ d’exportation de la variable d’environnement et le nombre de modèles dotés "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -41,6 +44,8 @@ d’exportation de la variable d’environnement et le nombre de modèles dotés } ``` +Les fournisseurs Pi générés activent `compat.sendSessionAffinityHeaders`. Conservez ce réglage lors de la fusion ou de la modification manuelle du fournisseur : Pi transmet un identifiant de session stable, dont OpenCodex dérive l’affinité pour la destination canonique OpenCode Go. Pi peut omettre cet identifiant lorsque `cacheRetention` vaut `none`. + Les identifiants de modèle sont les sélecteurs canoniques du proxy : les modèles routés apparaissent donc sous la forme `provider/model` (`anthropic/claude-opus-5`) et les slugs natifs OpenAI restent sans préfixe (`gpt-5.6-sol`). Le `name` suffixe — `(anthropic)`, `(native)`, `(routed)` — permet de distinguer, dans le sélecteur de Pi, deux modèles de même nom diff --git a/docs-site/src/content/docs/guides/pi.md b/docs-site/src/content/docs/guides/pi.md index c44b97f12a..f44e4be381 100644 --- a/docs-site/src/content/docs/guides/pi.md +++ b/docs-site/src/content/docs/guides/pi.md @@ -27,6 +27,9 @@ export line, and how many models carry authoritative context limits. "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -41,6 +44,8 @@ export line, and how many models carry authoritative context limits. } ``` +Generated Pi providers enable `compat.sendSessionAffinityHeaders`. Keep this flag when merging or manually editing the provider: Pi supplies a stable session identity and OpenCodex derives canonical OpenCode Go affinity from it. Pi may omit the identity when `cacheRetention` is `none`. + Model ids are the proxy's canonical selectors, so routed models appear as `provider/model` (`anthropic/claude-opus-5`) and native OpenAI slugs stay unprefixed (`gpt-5.6-sol`). The `name` suffix — `(anthropic)`, `(native)`, `(routed)` — is what makes two same-named models from diff --git a/docs-site/src/content/docs/ja/guides/pi.md b/docs-site/src/content/docs/ja/guides/pi.md index 788fe48c60..9b637e84e4 100644 --- a/docs-site/src/content/docs/ja/guides/pi.md +++ b/docs-site/src/content/docs/ja/guides/pi.md @@ -23,6 +23,9 @@ ocx export --client pi "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -37,6 +40,8 @@ ocx export --client pi } ``` +生成される Pi プロバイダーでは `compat.sendSessionAffinityHeaders` が有効です。設定をマージしたり手動で編集したりする際も、このフラグを保持してください。Pi が送る安定したセッション識別子から、OpenCodex が正規の OpenCode Go 接続先用の affinity を生成します。`cacheRetention` が `none` の場合、Pi は識別子を送信しないことがあります。 + モデル ID はプロキシの正規セレクターであるため、ルーティングされたモデルは `provider/model` (`anthropic/claude-opus-5`) として表示され、ネイティブ OpenAI スラグはプレフィックスなし (`gpt-5.6-sol`) のままになります。 `name` サフィックス (`(anthropic)`、`(native)`、`(routed)`) により、異なるアップストリームの 2 つの同じ名前のモデルが Pi のピッカーで区別できるようになります。 ## どこへ行くのか diff --git a/docs-site/src/content/docs/ko/guides/pi.md b/docs-site/src/content/docs/ko/guides/pi.md index 648d71060e..6bda9c2b36 100644 --- a/docs-site/src/content/docs/ko/guides/pi.md +++ b/docs-site/src/content/docs/ko/guides/pi.md @@ -27,6 +27,9 @@ ocx export --client pi "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -41,6 +44,8 @@ ocx export --client pi } ``` +생성된 Pi provider에는 `compat.sendSessionAffinityHeaders`가 활성화됩니다. provider를 병합하거나 직접 수정할 때 이 설정을 유지하세요. Pi가 안정적인 세션 식별자를 보내면 OpenCodex가 이를 바탕으로 정규 OpenCode Go 대상의 affinity를 계산합니다. `cacheRetention`이 `none`이면 Pi가 식별자를 보내지 않을 수 있습니다. + 모델 id는 프록시의 정규 선택자이므로, 라우팅된 모델은 `provider/model` (`anthropic/claude-opus-5`) 형태로 나타나고, 네이티브 OpenAI slug는 접두사 없이 (`gpt-5.6-sol`) 유지됩니다. `name` 접미사인 `(anthropic)`, `(native)`, `(routed)`는 diff --git a/docs-site/src/content/docs/ru/guides/pi.md b/docs-site/src/content/docs/ru/guides/pi.md index 0960ecf49a..e36a73da7e 100644 --- a/docs-site/src/content/docs/ru/guides/pi.md +++ b/docs-site/src/content/docs/ru/guides/pi.md @@ -27,6 +27,9 @@ ocx export --client pi "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -41,6 +44,8 @@ ocx export --client pi } ``` +В создаваемой конфигурации Pi включён `compat.sendSessionAffinityHeaders`. Сохраняйте этот флаг при объединении или ручном редактировании провайдера: Pi передаёт стабильный идентификатор сессии, из которого OpenCodex формирует affinity для канонического OpenCode Go. При `cacheRetention: none` Pi может не передавать идентификатор. + Id моделей — это канонические селекторы прокси, поэтому маршрутизируемые модели появляются как `provider/model` (`anthropic/claude-opus-5`), а нативные slug OpenAI остаются без префикса (`gpt-5.6-sol`). Суффикс в `name` — `(anthropic)`, `(native)`, `(routed)` — как раз и позволяет diff --git a/docs-site/src/content/docs/tr/guides/pi.md b/docs-site/src/content/docs/tr/guides/pi.md index 0741f7be51..fe6044de28 100644 --- a/docs-site/src/content/docs/tr/guides/pi.md +++ b/docs-site/src/content/docs/tr/guides/pi.md @@ -31,6 +31,9 @@ export line, and how many models carry authoritative context limits. "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -45,6 +48,8 @@ export line, and how many models carry authoritative context limits. } ``` +Oluşturulan Pi sağlayıcılarında `compat.sendSessionAffinityHeaders` etkinleştirilir. Sağlayıcıyı birleştirirken veya elle düzenlerken bu ayarı koruyun: Pi sabit bir oturum kimliği gönderir ve OpenCodex bu kimlikten kanonik OpenCode Go hedefi için oturum yakınlığı üretir. `cacheRetention` değeri `none` olduğunda Pi kimliği göndermeyebilir. + Model ids are the proxy's canonical selectors, so routed models appear as `provider/model` (`anthropic/claude-opus-5`) and native OpenAI slugs stay unprefixed diff --git a/docs-site/src/content/docs/zh-cn/guides/pi.md b/docs-site/src/content/docs/zh-cn/guides/pi.md index ad868e3194..c9ebf7b4a6 100644 --- a/docs-site/src/content/docs/zh-cn/guides/pi.md +++ b/docs-site/src/content/docs/zh-cn/guides/pi.md @@ -23,6 +23,9 @@ ocx export --client pi "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -37,6 +40,8 @@ ocx export --client pi } ``` +生成的 Pi 提供方配置启用了 `compat.sendSessionAffinityHeaders`。合并或手动编辑提供方时请保留该设置:Pi 提供稳定的会话标识,OpenCodex 据此为规范的 OpenCode Go 目标生成会话亲和标识。`cacheRetention` 为 `none` 时,Pi 可能不发送会话标识。 + 模型 id 是代理的规范选择器,因此已路由模型会显示为 `provider/model`(`anthropic/claude-opus-5`),而原生 OpenAI slug 会保持不带前缀(`gpt-5.6-sol`)。`name` 后缀 - `(anthropic)`、`(native)`、`(routed)` - 负责让两个同名但来自不同上游的模型在 Pi 的选择器中可区分。 ## 放置位置 diff --git a/docs-site/src/content/docs/zh-tw/guides/pi.md b/docs-site/src/content/docs/zh-tw/guides/pi.md index 0353338574..d8e9b62510 100644 --- a/docs-site/src/content/docs/zh-tw/guides/pi.md +++ b/docs-site/src/content/docs/zh-tw/guides/pi.md @@ -23,6 +23,9 @@ ocx export --client pi "baseUrl": "http://127.0.0.1:10100/v1", "api": "openai-completions", "apiKey": "$OPENCODEX_API_KEY", + "compat": { + "sendSessionAffinityHeaders": true + }, "models": [ { "id": "anthropic/claude-opus-5", @@ -37,6 +40,8 @@ ocx export --client pi } ``` +產生的 Pi 供應商設定會啟用 `compat.sendSessionAffinityHeaders`。合併或手動編輯供應商時請保留此設定:Pi 提供穩定的工作階段識別碼,OpenCodex 據此為標準 OpenCode Go 目標產生工作階段親和識別碼。當 `cacheRetention` 為 `none` 時,Pi 可能不傳送識別碼。 + 模型 id 是代理的規範選擇器,因此路由模型顯示為 `provider/model`(`anthropic/claude-opus-5`),而原生 OpenAI slug 保持無前綴(`gpt-5.6-sol`)。`name` 後綴 — `(anthropic)`、`(native)`、`(routed)` — 正是讓來自不同上游的兩個同名模型在 Pi 的 picker 中可區分的關鍵。 ## 放置位置 From c84cc3b3e076b6c49cf93a6ca267f6303a698f5b Mon Sep 17 00:00:00 2001 From: lidge-jun <243035832+lidge-jun@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:33:18 +0900 Subject: [PATCH 035/116] docs: describe native compact 404 fallback in route table [skip ci] Co-authored-by: ideabib <221318067+ideabib@users.noreply.github.com> --- docs-site/src/content/docs/reference/proxy-formats.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 593c8ae7a3..1f2e589252 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -402,7 +402,7 @@ conversation. | Route type | Behavior | | --- | --- | -| Canonical ChatGPT or official OpenAI route | Forwards the request to the native `/responses/compact` endpoint with the resolved account and model authentication | +| Canonical ChatGPT or official OpenAI route | Tries the native `/responses/compact` endpoint with the resolved account and model authentication; HTTP 404 falls back to a regular Responses compaction turn | | Other routed model | Runs an internal, non-streaming, no-tools compaction turn with a `compaction_trigger`; requires exactly one synthetic `compaction` item whose `encrypted_content` is an `ocx1:` envelope; decodes that summary into v1 replacement history | If the native compact endpoint returns HTTP 404, OpenCodex retries compaction through a regular From e96b5c52e05e9fd6f5b9cb4aedc96b171f4a4872 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:19:06 +0900 Subject: [PATCH 036/116] fix(responses): make whole-string citation stripping agree with the streaming filter After #3868 the streaming filter keeps a malformed START verbatim when a later START opens a real span, but stripCitationMarkers still paired the first START with that later span's END and deleted everything between. bridge.ts re-strips the accumulated text for output_text.done and output_item.done, so the terminal text disagreed with the concatenated deltas. Walk START-delimited segments in the whole-string path too, and share the 4096 span bound with the whole-string path (an over-bound span that is terminated late is malformed text in both), and assert delta-vs-whole equality across several chunkings. Found by the lane A fresh-base composition audit on dev d00615d56. Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/responses/citation-markers.ts | 53 +++++++++++++----------- tests/responses/citation-markers.test.ts | 33 +++++++++++++++ 2 files changed, 62 insertions(+), 24 deletions(-) diff --git a/src/responses/citation-markers.ts b/src/responses/citation-markers.ts index 3e3943cad5..9c56c7a197 100644 --- a/src/responses/citation-markers.ts +++ b/src/responses/citation-markers.ts @@ -42,23 +42,24 @@ export function hasCitationMarker(text: string): boolean { */ export function stripCitationMarkers(text: string): string { if (!text.includes(CITATION_MARKER_START)) return text; - let out = ""; - let index = 0; - for (;;) { - const start = text.indexOf(CITATION_MARKER_START, index); - if (start === -1) { - out += text.slice(index); - return out; - } - const end = text.indexOf(CITATION_MARKER_END, start + 1); - if (end === -1) { - // Unterminated: keep the rest verbatim. - out += text.slice(index); - return out; - } - out += text.slice(index, start); - index = end + 1; + // Walk START-delimited segments exactly like the streaming filter below: a START whose + // own segment (up to the next START) contains an END within the span bound is a span and + // is removed; a START that is superseded by another START before any END, or whose span + // exceeds MAX_CITATION_SPAN_LENGTH, is malformed text and stays verbatim. Pairing an + // earlier malformed START with a later span's END would delete real answer text and, + // worse, disagree with what the streaming deltas already emitted (#3843). The bound is + // shared with the streaming filter for the same reason: a span it has already released + // as over-bound must not be swallowed here when the END finally arrives. + let start = text.indexOf(CITATION_MARKER_START); + let out = text.slice(0, start); + while (start !== -1) { + const nextStart = text.indexOf(CITATION_MARKER_START, start + 1); + const segment = text.slice(start, nextStart === -1 ? text.length : nextStart); + const end = segment.indexOf(CITATION_MARKER_END, 1); + out += end === -1 || end + 1 > MAX_CITATION_SPAN_LENGTH ? segment : segment.slice(end + 1); + start = nextStart; } + return out; } export interface CitationMarkerFilter { @@ -69,13 +70,16 @@ export interface CitationMarkerFilter { } /** - * Upper bound on the text withheld for one unterminated START. + * Upper bound on the length of a citation span (START through END inclusive), and therefore + * on the text the streaming filter withholds for one unterminated START. * * A real span is `cite` plus a few turn-scoped ids, so it is far under this. Without a * bound, a backend that emits a START and never terminates it makes `held` grow for the - * whole response, and every later delta re-scans that accumulated prefix. + * whole response, and every later delta re-scans that accumulated prefix. The whole-string + * strip applies the same bound so both paths classify a span identically regardless of how + * the text was chunked. */ -const MAX_STREAMING_MARKER_SPAN_LENGTH = 4_096; +const MAX_CITATION_SPAN_LENGTH = 4_096; /** * Streaming filter. @@ -85,7 +89,7 @@ const MAX_STREAMING_MARKER_SPAN_LENGTH = 4_096; * This holds back the text from an unterminated START and releases it once the END arrives * (removed) or the stream ends (verbatim, so nothing the model actually said is lost). * - * A span that grows past `MAX_STREAMING_MARKER_SPAN_LENGTH` is malformed ordinary text, so + * A span that grows past `MAX_CITATION_SPAN_LENGTH` is malformed ordinary text, so * it is released verbatim instead of withheld; a later START can still open a valid span. */ export function createCitationMarkerFilter(): CitationMarkerFilter { @@ -104,15 +108,16 @@ export function createCitationMarkerFilter(): CitationMarkerFilter { const nextStart = combined.indexOf(CITATION_MARKER_START, start + 1); const segment = combined.slice(start, nextStart === -1 ? combined.length : nextStart); const end = segment.indexOf(CITATION_MARKER_END, 1); - if (end !== -1) { + if (end !== -1 && end + 1 <= MAX_CITATION_SPAN_LENGTH) { // A complete span: drop it, keep whatever trails it inside this segment. out += segment.slice(end + 1); - } else if (nextStart === -1 && segment.length <= MAX_STREAMING_MARKER_SPAN_LENGTH) { + } else if (end === -1 && nextStart === -1 && segment.length <= MAX_CITATION_SPAN_LENGTH) { // Only a bounded trailing span can still be completed by a later delta. held = segment; } else { - // Superseded by a later START, or over the bound: ordinary text, emitted verbatim - // so neither the retained text nor the per-delta rescan grows without limit. + // Superseded by a later START, or over the bound (with or without a late END): + // ordinary text, emitted verbatim so neither the retained text nor the per-delta + // rescan grows without limit. out += segment; } start = nextStart; diff --git a/tests/responses/citation-markers.test.ts b/tests/responses/citation-markers.test.ts index dcc7f9abc6..b0d92d0fad 100644 --- a/tests/responses/citation-markers.test.ts +++ b/tests/responses/citation-markers.test.ts @@ -52,6 +52,15 @@ describe("citation marker stripping (#3150)", () => { expect(stripCitationMarkers(`a${P}b`)).toBe(`a${P}b`); expect(stripCitationMarkers(`a${E}b`)).toBe(`a${E}b`); }); + + test("a malformed START before a later valid span is kept, not paired with that span's END", () => { + // Whole-string stripping must agree with the streaming filter: the malformed prefix + // survives and only the real span is removed (bridge re-strips the accumulated text + // for output_text.done, so any disagreement would make done != concatenated deltas). + const malformed = `${S}${"y".repeat(5_000)}`; + expect(stripCitationMarkers(`a${malformed}${S}cite${P}turn1view0${E} tail`)).toBe(`a${malformed} tail`); + expect(stripCitationMarkers(`a${S}cite${S}cite${P}turn1view0${E}b`)).toBe(`a${S}citeb`); + }); }); describe("streaming citation marker filter (#3150)", () => { @@ -117,4 +126,28 @@ describe("streaming citation marker filter (#3150)", () => { .toBe(`a${malformed} tail`); expect(filter.flush()).toBe(""); }); + + test("concatenated streaming output equals whole-string stripping for every chunking", () => { + // The bridge emits deltas through the filter and then re-strips the accumulated text for + // output_text.done / output_item.done, so the two contracts must produce identical text. + const malformed = `${S}${"y".repeat(5_000)}`; + const inputs = [ + `a${span}${malformed}${S}cite${P}turn1view0${E} tail`, + `kept ${S}cite${"x".repeat(5_000)}`, + `a${S}cite${S}cite${P}turn1view0${E}b`, + `a${span}b${S}cite${P}turn2view0${E}c`, + // An over-bound span that is eventually terminated: the streaming filter has already + // released it verbatim, so whole-string stripping must keep it too. + `late ${S}${"z".repeat(4_096)}${E} end`, + // Exactly at the bound (4096 chars START..END inclusive) is still a span. + `edge ${S}${"z".repeat(4_094)}${E} end`, + ]; + for (const input of inputs) { + for (const size of [1, 7, 4_097, input.length]) { + const chunks: string[] = []; + for (let i = 0; i < input.length; i += size) chunks.push(input.slice(i, i + size)); + expect(drain(chunks)).toBe(stripCitationMarkers(input)); + } + } + }); }); From 413600dc79817a34d141d5f8037fc1495b456aa1 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 20:04:47 +0900 Subject: [PATCH 037/116] docs(providers): describe OpenCode Go session affinity and the Pi compat flag [skip ci] Docs hunk from the #3858 carry (#3880) that lane A handed off because guides/providers.md is owned by the main lane in this train. Co-authored-by: makesomethingshit <246213378+makesomethingshit@users.noreply.github.com> --- docs-site/src/content/docs/guides/providers.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index 8a9477a759..7ac2e4502b 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -379,6 +379,22 @@ free-experimentation model. | Cloudflare AI Gateway | `https://gateway.ai.cloudflare.com/v1/{account-id}/{gateway}/anthropic` | | …and more | opencode zen, Vercel AI Gateway, Venice, NanoGPT, Synthetic, Qianfan, Alibaba, Parallel, ZenMux, LiteLLM | +**OpenCode Go** requires a stable session identifier for routing. OpenCodex derives +its Go session header from Codex thread/session headers, or from a client's +`x-opencode-session` header when Codex headers are absent. This applies to direct +Chat Completions requests and requests bridged to Responses. Even an `ocx_`-prefixed +inbound value is treated as client input and +hashed into Go affinity; the internal bridge carries the original value, so native +Chat, bridged Chat, and Responses derive the same result. Explicit provider-config +session headers are operator overrides and are sent unchanged. Clients must keep the +identifier stable within a conversation and distinct across conversations; requests +without a session identifier cannot receive automatic session affinity. +Generated Pi provider configurations enable `compat.sendSessionAffinityHeaders` +so Pi sends its per-session identity to the proxy. Existing manually managed Pi +configurations can set this option on their `opencodex` provider as well. +Pi can omit session affinity when `cacheRetention` is `none`; enable cache retention +when a stable upstream session is required. + **OpenCode Zen** (`opencode-zen`) and the keyless **OpenCode Free** preset share `https://opencode.ai/zen/v1`. Free models on that gateway often hit a short-window burst limit around 15–20 requests/minute (community-measured; OpenCode does not publish RPM). From 451fbffb02407cd73e9cf62bff6c40ad09ba3e12 Mon Sep 17 00:00:00 2001 From: x3M3x Date: Wed, 2 Sep 2026 03:42:09 +0400 Subject: [PATCH 038/116] feat gui: expose subagent fallback settings [skip ci] (cherry picked from commit b0d86fa3be8aec324974dc4471d5a98b35102459) Co-authored-by: x3M3x <98298256+x3M3x@users.noreply.github.com> --- .../SubagentDelegationSection.tsx | 33 ++++++++++++ .../SubagentsWorkspace.tsx | 14 +++++ gui/src/i18n/de.ts | 6 +++ gui/src/i18n/en.ts | 6 +++ gui/src/i18n/fr.ts | 6 +++ gui/src/i18n/ja.ts | 6 +++ gui/src/i18n/ko.ts | 6 +++ gui/src/i18n/ru.ts | 6 +++ gui/src/i18n/tr.ts | 6 +++ gui/src/i18n/zh-TW.ts | 6 +++ gui/src/i18n/zh.ts | 6 +++ gui/src/pages/Subagents.tsx | 53 ++++++++++++++++--- 12 files changed, 147 insertions(+), 7 deletions(-) diff --git a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx index 46c0447a7c..7c3b0e9425 100644 --- a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx +++ b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx @@ -28,6 +28,13 @@ export interface SubagentDelegationSectionProps { onUltraModeSave: (patch: UltraModePatch) => void; ultraLoadFailed: boolean; onUltraModeRetry: () => void; + fallback: string[]; + fallbackPollMs: number; + fallbackBusy: boolean; + availableModels: string[]; + onFallbackChange: (models: string[]) => void; + onFallbackPollMsChange: (pollMs: number) => void; + onFallbackSave: () => void; } export default function SubagentDelegationSection({ @@ -44,6 +51,7 @@ export default function SubagentDelegationSection({ onUltraModeSave, ultraLoadFailed, onUltraModeRetry, + fallback, fallbackPollMs, fallbackBusy, availableModels, onFallbackChange, onFallbackPollMsChange, onFallbackSave, }: SubagentDelegationSectionProps) { const t = useT(); // A present empty/whitespace hint is an upstream override that suppresses the @@ -97,6 +105,31 @@ export default function SubagentDelegationSection({ +
+
+
{t("sub.fallbackLabel")}
+
{t("sub.fallbackHint")}
+
+
+ {fallback.map((modelName, index) => ( +
+ {index + 1}. {modelName} + + + +
+ ))} + + + +
+
+
{t("dash.syncCodexSubagentDefaults")}
diff --git a/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx b/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx index a22bd2a305..30b722b2bf 100644 --- a/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx +++ b/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx @@ -37,6 +37,12 @@ export interface SubagentsWorkspaceProps { onToggle: (m: string) => void; onMove: (i: number, dir: -1 | 1) => void; onSave: () => void; + fallback: string[]; + fallbackPollMs: number; + fallbackBusy: boolean; + onFallbackChange: (models: string[]) => void; + onFallbackPollMsChange: (pollMs: number) => void; + onFallbackSave: () => void; delegation: { model: string; effort: string; @@ -63,6 +69,7 @@ export default function SubagentsWorkspace({ onToggle, onMove, onSave, + fallback, fallbackPollMs, fallbackBusy, onFallbackChange, onFallbackPollMsChange, onFallbackSave, delegation, }: SubagentsWorkspaceProps) { const t = useT(); @@ -237,6 +244,13 @@ export default function SubagentsWorkspace({ onUltraModeSave={delegation.onUltraModeSave} ultraLoadFailed={delegation.ultraLoadFailed} onUltraModeRetry={delegation.onUltraModeRetry} + fallback={fallback} + fallbackPollMs={fallbackPollMs} + fallbackBusy={fallbackBusy} + availableModels={available} + onFallbackChange={onFallbackChange} + onFallbackPollMsChange={onFallbackPollMsChange} + onFallbackSave={onFallbackSave} />
diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 74533a04d3..8985d342a0 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -686,6 +686,12 @@ export const de: Record = { "sub.ultraModeLoadFail": "Ultra-Modus-Einstellungen konnten nicht geladen werden — läuft der Proxy?", "sub.ultraModeSaveFail": "Ultra-Modus-Einstellungen konnten nicht gespeichert werden", "sub.ultraModeSaved": "Ultra-Modus gespeichert. Gilt für neue Codex-Sitzungen.", + "sub.fallbackLabel": "Fallback-Kette für Sub-Agenten", + "sub.fallbackHint": "Geordnete Modelle, die versucht werden, wenn ein Sub-Agent-Modell nicht verfügbar ist oder fehlschlägt.", + "sub.fallbackAdd": "Fallback-Modell hinzufügen…", + "sub.fallbackPoll": "Intervall der Verfügbarkeitsprüfung", + "sub.fallbackSaved": "Fallback-Einstellungen für Sub-Agenten gespeichert.", + "sub.fallbackSaveFailed": "Fallback-Einstellungen konnten nicht gespeichert werden", "logs.title": "Anfrage-Protokolle", "logs.tabLogs": "Protokolle", "logs.tabDebug": "Diagnose", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 2197dcb735..a33c195e82 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -329,6 +329,12 @@ export const en = { "dash.visionTimeout": "Timeout", "dash.visionTimeoutInvalid": "Enter an integer from {min} to {max} milliseconds.", "dash.visionAdvancedPopover": "Advanced vision settings", + "sub.fallbackLabel": "Sub-agent fallback chain", + "sub.fallbackHint": "Ordered models tried when a sub-agent model is unavailable or fails.", + "sub.fallbackAdd": "Add fallback model…", + "sub.fallbackPoll": "Availability check interval", + "sub.fallbackSaved": "Sub-agent fallback settings saved.", + "sub.fallbackSaveFailed": "Failed to save fallback settings", "dash.shadowCallIntercept": "Shadow Call Intercept", "dash.shadowCallInterceptHint": "Intercepts Codex App's background helper calls ({models}) for title generation and commit messages and redirects them to your chosen model.", "dash.shadowCallWarning": "⚠ When enabled, ALL requests for {models} will be replaced with the selected model.", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index cca4b70347..fa32925c02 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -319,6 +319,12 @@ export const fr: Record = { "dash.visionTimeout": "Délai d’expiration", "dash.visionTimeoutInvalid": "Saisissez un entier compris entre {min} et {max} millisecondes.", "dash.visionAdvancedPopover": "Paramètres de vision avancés", + "sub.fallbackLabel": "Chaîne de secours des sous-agents", + "sub.fallbackHint": "Modèles essayés dans l’ordre lorsqu’un modèle de sous-agent est indisponible ou échoue.", + "sub.fallbackAdd": "Ajouter un modèle de secours…", + "sub.fallbackPoll": "Intervalle de vérification de disponibilité", + "sub.fallbackSaved": "Paramètres de secours des sous-agents enregistrés.", + "sub.fallbackSaveFailed": "Échec de l’enregistrement des paramètres de secours", "dash.shadowCallIntercept": "Interception des appels fantômes", "dash.shadowCallInterceptHint": "Intercepte les appels auxiliaires en arrière-plan de l’application Codex ({models}) pour générer les titres et les messages de commit, puis les redirige vers le modèle choisi.", "dash.shadowCallWarning": "⚠ Lorsque cette option est activée, TOUTES les requêtes destinées à {models} sont remplacées par le modèle sélectionné.", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 97aa85a6fb..81cd40bca9 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -646,6 +646,12 @@ export const ja: Record = { "sub.ultraModeLoadFail": "ウルトラモード設定を読み込めませんでした — プロキシは実行中ですか?", "sub.ultraModeSaveFail": "ウルトラモード設定の保存に失敗しました", "sub.ultraModeSaved": "ウルトラモードを保存しました。新しい Codex セッションから適用されます。", + "sub.fallbackLabel": "サブエージェントのフォールバックチェーン", + "sub.fallbackHint": "サブエージェントモデルが利用できないか失敗した場合に順番に試すモデルです。", + "sub.fallbackAdd": "フォールバックモデルを追加…", + "sub.fallbackPoll": "利用可能性チェック間隔", + "sub.fallbackSaved": "サブエージェントのフォールバック設定を保存しました。", + "sub.fallbackSaveFailed": "フォールバック設定の保存に失敗しました", // logs "logs.title": "リクエストログ", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 4e66544528..35a726e6ba 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -703,6 +703,12 @@ export const ko: Record = { "sub.ultraModeLoadFail": "울트라 모드 설정을 불러오지 못했습니다 — 프록시가 실행 중인가요?", "sub.ultraModeSaveFail": "울트라 모드 설정 저장에 실패했습니다", "sub.ultraModeSaved": "울트라 모드가 저장되었습니다. 새 Codex 세션부터 적용됩니다.", + "sub.fallbackLabel": "서브에이전트 폴백 체인", + "sub.fallbackHint": "서브에이전트 모델을 사용할 수 없거나 실패할 때 순서대로 시도할 모델입니다.", + "sub.fallbackAdd": "폴백 모델 추가…", + "sub.fallbackPoll": "가용성 확인 간격", + "sub.fallbackSaved": "서브에이전트 폴백 설정을 저장했습니다.", + "sub.fallbackSaveFailed": "폴백 설정을 저장하지 못했습니다", // logs "logs.title": "요청 로그", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index e7f199a06a..a7cc5f72e8 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -701,6 +701,12 @@ export const ru: Record = { "sub.ultraModeLoadFail": "Не удалось загрузить настройки ультра-режима — работает ли прокси?", "sub.ultraModeSaveFail": "Не удалось сохранить настройки ультра-режима", "sub.ultraModeSaved": "Ультра-режим сохранён. Применяется к новым сеансам Codex.", + "sub.fallbackLabel": "Цепочка резервных моделей субагента", + "sub.fallbackHint": "Модели, которые последовательно пробуются, если модель субагента недоступна или завершается ошибкой.", + "sub.fallbackAdd": "Добавить резервную модель…", + "sub.fallbackPoll": "Интервал проверки доступности", + "sub.fallbackSaved": "Настройки резервных моделей субагента сохранены.", + "sub.fallbackSaveFailed": "Не удалось сохранить настройки резервных моделей", // logs "logs.title": "Журнал запросов", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 8c8f9ff802..5c0ade9077 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -708,6 +708,12 @@ export const tr: Record = { "sub.ultraModeLoadFail": "Ultra modu ayarları yüklenemedi — proxy çalışıyor mu?", "sub.ultraModeSaveFail": "Ultra modu ayarları kaydedilemedi", "sub.ultraModeSaved": "Ultra modu kaydedildi. Yeni Codex oturumlarına uygulanır.", + "sub.fallbackLabel": "Alt ajan yedek zinciri", + "sub.fallbackHint": "Alt ajan modeli kullanılamadığında veya başarısız olduğunda sırayla denenecek modeller.", + "sub.fallbackAdd": "Yedek model ekle…", + "sub.fallbackPoll": "Kullanılabilirlik kontrol aralığı", + "sub.fallbackSaved": "Alt ajan yedek ayarları kaydedildi.", + "sub.fallbackSaveFailed": "Yedek ayarlar kaydedilemedi", // logs "logs.title": "İstek Günlükleri", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index eeec289911..cae0175057 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -555,6 +555,12 @@ export const zhTW: Record = { "sub.ultraModeLoadFail": "無法載入超級模式設定 — 代理是否在執行?", "sub.ultraModeSaveFail": "儲存超級模式設定失敗", "sub.ultraModeSaved": "超級模式已儲存。適用於新的 Codex 會話。", + "sub.fallbackLabel": "子代理備援鏈", + "sub.fallbackHint": "子代理模型無法使用或失敗時,依序嘗試的模型。", + "sub.fallbackAdd": "新增備援模型…", + "sub.fallbackPoll": "可用性檢查間隔", + "sub.fallbackSaved": "子代理備援設定已儲存。", + "sub.fallbackSaveFailed": "備援設定儲存失敗", "logs.title": "請求日誌", "logs.tabLogs": "日誌", "logs.tabDebug": "除錯", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index a62e9b2d6b..ce44edc693 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -696,6 +696,12 @@ export const zh: Record = { "sub.ultraModeLoadFail": "无法加载超级模式设置 — 代理是否在运行?", "sub.ultraModeSaveFail": "保存超级模式设置失败", "sub.ultraModeSaved": "超级模式已保存。适用于新的 Codex 会话。", + "sub.fallbackLabel": "子代理回退链", + "sub.fallbackHint": "子代理模型不可用或失败时按顺序尝试的模型。", + "sub.fallbackAdd": "添加回退模型…", + "sub.fallbackPoll": "可用性检查间隔", + "sub.fallbackSaved": "子代理回退设置已保存。", + "sub.fallbackSaveFailed": "保存回退设置失败", // logs "logs.title": "请求日志", diff --git a/gui/src/pages/Subagents.tsx b/gui/src/pages/Subagents.tsx index 6b54d39ffd..299c9306fe 100644 --- a/gui/src/pages/Subagents.tsx +++ b/gui/src/pages/Subagents.tsx @@ -8,7 +8,7 @@ import { useDataSurface } from "../data-surface"; import { DataSurfaceSkeleton } from "../components/data-surface"; import { useSubagentDelegation, type UltraModePatch, type UltraModeState } from "./use-subagent-delegation"; -type CachedSubagents = { available: string[]; chosen: string[] }; +type CachedSubagents = { available: string[]; chosen: string[]; fallback: string[]; pollMs: number }; function seedSubagents(cacheKey: string): CachedSubagents | null { return readSessionListCache(cacheKey); @@ -19,6 +19,9 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const cacheKey = `ocx.subagents.v1:${apiBase}`; const cached = seedSubagents(cacheKey); const [chosen, setChosen] = useState(() => cached?.chosen ?? []); + const [fallback, setFallback] = useState(() => cached?.fallback ?? []); + const [fallbackPollMs, setFallbackPollMs] = useState(() => cached?.pollMs ?? 60000); + const [fallbackBusy, setFallbackBusy] = useState(false); const [status, setStatus] = useState(""); const [ok, setOk] = useState(false); const [busy, setBusy] = useState(false); @@ -117,16 +120,24 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const loadSubagents = useCallback(async (signal?: AbortSignal): Promise => { // The resource layer's deadline abort must reach the wire — a signal dropped // here is a store that can only settle by race timeout. - const res = await fetch(`${apiBase}/api/subagent-models`, { signal }); - const response = await readJsonOrThrow<{ available?: string[]; chosen?: string[] }>(res, t("sub.loadFail")); - if (!response) throw new Error(t("sub.loadFail")); - const available = response.available ?? []; + const [rosterRes, fallbackRes] = await Promise.all([ + fetch(`${apiBase}/api/subagent-models`, { signal }), + fetch(`${apiBase}/api/subagent-model-fallback`, { signal }), + ]); + const response = await readJsonOrThrow<{ available?: string[]; chosen?: string[] }>(rosterRes, t("sub.loadFail")); + const fallbackResponse = await readJsonOrThrow<{ available?: string[]; models?: string[]; pollMs?: number }>(fallbackRes, t("sub.loadFail")); + if (!response || !fallbackResponse) throw new Error(t("sub.loadFail")); + const available = response.available ?? fallbackResponse.available ?? []; const availableSet = new Set(available); const next = { available, chosen: (response.chosen ?? []).filter(model => availableSet.has(model)), + fallback: (fallbackResponse.models ?? []).filter(model => availableSet.has(model)), + pollMs: fallbackResponse.pollMs ?? 60000, }; setChosen(next.chosen); + setFallback(next.fallback); + setFallbackPollMs(next.pollMs); writeSessionListCache(cacheKey, next); return next; }, [apiBase, cacheKey, t]); @@ -174,7 +185,7 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const d = await readJsonOrThrow<{ applied?: string[] }>(r, t("sub.saveFailed")); const applied = d?.applied ?? chosen; if (d?.applied) setChosen(d.applied); - writeSessionListCache(cacheKey, { available, chosen: applied }); + writeSessionListCache(cacheKey, { available, chosen: applied, fallback, pollMs: fallbackPollMs }); setOk(true); setStatus(t("sub.saved", { n: applied.length, cmd: "ocx sync" })); } catch (error) { @@ -186,6 +197,28 @@ export default function Subagents({ apiBase }: { apiBase: string }) { } }; + const saveFallback = async () => { + if (fallbackBusy) return; + setFallbackBusy(true); + try { + const r = await fetch(`${apiBase}/api/subagent-model-fallback`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ models: fallback, pollMs: fallbackPollMs }), + }); + const d = await readJsonOrThrow<{ models?: string[]; pollMs?: number }>(r, t("sub.fallbackSaveFailed")); + if (d?.models) setFallback(d.models); + if (d?.pollMs) setFallbackPollMs(d.pollMs); + setOk(true); + setStatus(t("sub.fallbackSaved")); + } catch (error) { + setOk(false); + setStatus(error instanceof Error && error.message ? error.message : t("sub.networkError")); + } finally { + setFallbackBusy(false); + } + }; + // The skeleton owns the live region while this resource has no content yet. if (state.showSkeleton && !snapshot) { return ; @@ -214,7 +247,13 @@ export default function Subagents({ apiBase }: { apiBase: string }) { busy={busy} onToggle={toggle} onMove={move} - onSave={() => { void save(); }} + onSave={() => { void save(); }} + fallback={fallback} + fallbackPollMs={fallbackPollMs} + fallbackBusy={fallbackBusy} + onFallbackChange={setFallback} + onFallbackPollMsChange={setFallbackPollMs} + onFallbackSave={() => { void saveFallback(); }} delegation={{ model: delegation.model, effort: delegation.effort, From 2e6ef45530353cdf78d08b39cc3d914ea0139ed9 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:22:48 +0900 Subject: [PATCH 039/116] docs: record lane C manual-chain roadmap [skip ci] --- devlog/_plan/260907_lane_c/000_plan.md | 7 + devlog/_plan/260907_lane_c/010_web_search.md | 155 +++++++ devlog/_plan/260907_lane_c/020_vision.md | 135 +++++++ devlog/_plan/260907_lane_c/030_health.md | 119 ++++++ devlog/_plan/260907_lane_c/040_desktop.md | 404 +++++++++++++++++++ devlog/_plan/260907_lane_c/050_fallback.md | 368 +++++++++++++++++ 6 files changed, 1188 insertions(+) create mode 100644 devlog/_plan/260907_lane_c/000_plan.md create mode 100644 devlog/_plan/260907_lane_c/010_web_search.md create mode 100644 devlog/_plan/260907_lane_c/020_vision.md create mode 100644 devlog/_plan/260907_lane_c/030_health.md create mode 100644 devlog/_plan/260907_lane_c/040_desktop.md create mode 100644 devlog/_plan/260907_lane_c/050_fallback.md diff --git a/devlog/_plan/260907_lane_c/000_plan.md b/devlog/_plan/260907_lane_c/000_plan.md new file mode 100644 index 0000000000..d26120ae29 --- /dev/null +++ b/devlog/_plan/260907_lane_c/000_plan.md @@ -0,0 +1,7 @@ +# Lane C release train roadmap + +Satisfy-spec HOTL, explicitly delegated by release-train main task. Goal: prepare five manual dependent PRs for main-session landing. No merge/release/publish/main/preview changes; no local tests, typecheck, build or install. All such checks NOT RUN. Remote Cross-platform CI dispatch lane=all at top head is the verifier. Stop after exact-head green CI, Astra review verdicts, screenshots, credit and SHA handoff; unresolved material blockers are reported with evidence. No user-specified token/cost/time bound. Tools: local scoped git/files, gh read/PR/push/CI, Astra explorer audits and browser inspection. New security findings stay in .tmp/lane-c. Main owns config-routes.ts; no edits there. Escalate cross-owner collisions; reclaim delegated slices after two distinct worker failures. + +Dependency order: roadmap → 3839 → 3841 → 3863 → 3860 → 3252/1533 → top CI and handoff. Lower-layer commit subjects include [skip ci]; stack:null. Every carry uses cherry-pick -x and source PR author Co-authored-by. Existing configuration field contracts are reused. Rollback is revert of a layer with descendant cascade, within main-authorized integration. Current source and read-only git/gh are evidence; no claimed local execution of product verifiers. Public original diffs are recorded in decade documents; private audit notes stay in scratch. + +Main steering: all gui/src/i18n/*.ts are append-only multiwriter; C adds namespaced keys at feature-section ends, never edits/deletes existing keys. Final cascade resolves append collisions. diff --git a/devlog/_plan/260907_lane_c/010_web_search.md b/devlog/_plan/260907_lane_c/010_web_search.md new file mode 100644 index 0000000000..ccb7217ea3 --- /dev/null +++ b/devlog/_plan/260907_lane_c/010_web_search.md @@ -0,0 +1,155 @@ +# 3839 implementation contract + +Carry public source patch with -x. Add deterministic 64KiB SSE and HTTP error-body regressions including cancel that never settles. Preserve complete prefix frames and discard incomplete tail. Tests use public run/parse APIs and controlled byte streams. + +Validation: local tests/typecheck/build/install NOT RUN by instruction. Read diff and source; top remote CI exercises changed test paths. Each conditional branch listed above is exercised by controlled fixtures; screenshot inspects GUI state. No new enforcement layer; existing API guards remain authoritative. + +## Public source diff (MODIFY/NEW paths) + +```diff +diff --git a/src/web-search/anthropic-executor.ts b/src/web-search/anthropic-executor.ts +index 1eb206afa..cd3893900 100644 +--- a/src/web-search/anthropic-executor.ts ++++ b/src/web-search/anthropic-executor.ts +@@ -5,7 +5,11 @@ import { CLAUDE_CODE_HEADERS, claudeCodeSessionId } from "../adapters/client-fin + import { signalWithTimeout, cancelBodyOnAbort } from "../lib/abort"; + import { sidecarEnter } from "../lib/sidecar-tracker"; + import { applyUpstreamRecoveryInit, fetchWithResetRetry } from "../lib/upstream-retry"; +-import type { WebSearchSource } from "./parse"; ++import { ++ MAX_SIDECAR_RESPONSE_BYTES, ++ cancelReaderWithoutWaiting, ++ type WebSearchSource, ++} from "./parse"; + import { BASE_INSTRUCTION, IMAGE_INSTRUCTION, type SidecarOutcome, type SidecarSettings } from "./executor"; + + /** Hardcoded per-turn search bound handed to the server tool (mirrors the loop's maxSearches intent). */ +@@ -17,6 +21,33 @@ function isRec(v: unknown): v is Record { + return !!v && typeof v === "object" && !Array.isArray(v); + } + ++/** Read at most `MAX_SIDECAR_RESPONSE_BYTES` of an untrusted upstream body, then stop reading. */ ++async function readBoundedText(res: Response): Promise { ++ if (!res.body) return ""; ++ const reader = res.body.getReader(); ++ const decoder = new TextDecoder(); ++ let out = ""; ++ let seen = 0; ++ try { ++ for (;;) { ++ const { done, value } = await reader.read(); ++ if (done) break; ++ const remaining = MAX_SIDECAR_RESPONSE_BYTES - seen; ++ const accepted = value.byteLength <= remaining ? value : value.subarray(0, remaining); ++ seen += accepted.byteLength; ++ out += decoder.decode(accepted, { stream: true }); ++ if (seen >= MAX_SIDECAR_RESPONSE_BYTES) { ++ cancelReaderWithoutWaiting(reader, "sidecar error body byte limit reached"); ++ break; ++ } ++ } ++ out += decoder.decode(); ++ } catch { ++ /* a failed error-body read must not mask the HTTP status we are about to report */ ++ } ++ return out; ++} ++ + /** + * Fold an Anthropic Messages SSE stream (a web_search_20250305 turn) into a WebSearchResult. + * +@@ -41,6 +72,7 @@ export async function parseAnthropicSidecarSSE(res: Response): Promise): void => { + const type = typeof data.type === "string" ? data.type : ""; +@@ -82,15 +114,27 @@ export async function parseAnthropicSidecarSSE(res: Response): Promise= MAX_SIDECAR_RESPONSE_BYTES) { ++ // Keep the frames already folded above, drop the unterminated tail, and do not wait on ++ // upstream teardown. ++ cancelReaderWithoutWaiting(reader, "sidecar response byte limit reached"); ++ buffer = ""; ++ break; ++ } + } + // Flush the decoder and process any final unterminated frame (a stream that ends without \n\n). + buffer = (buffer + decoder.decode()).replace(/\r\n/g, "\n"); +@@ -177,7 +221,9 @@ export async function runAnthropicWebSearch( + // (found investigating #1419). + const detachBodyGuard = cancelBodyOnAbort(res.body, linkedSignal.signal); + if (!res.ok) { +- const t = await res.text().catch(() => ""); ++ // Untrusted upstream error bodies are only used for an auth-failure message, so read a ++ // bounded prefix instead of buffering an arbitrarily large response. ++ const t = await readBoundedText(res); + detachBodyGuard(); + console.warn(`[web-search] anthropic sidecar HTTP ${res.status} for query "${query.slice(0, 80)}" (${Date.now() - t0}ms)`); + if (res.status === 401) { +diff --git a/src/web-search/parse.ts b/src/web-search/parse.ts +index 757c309f3..7ba5d2607 100644 +--- a/src/web-search/parse.ts ++++ b/src/web-search/parse.ts +@@ -193,7 +193,7 @@ function fromOutputArray(output: OutputItem[], seen: Set): WebSearchResu + return { text, sources }; + } + +-function cancelReaderWithoutWaiting( ++export function cancelReaderWithoutWaiting( + reader: ReadableStreamDefaultReader, + reason: string, + ): void { +diff --git a/tests/web-search/web-search-anthropic.test.ts b/tests/web-search/web-search-anthropic.test.ts +index f5b7f1df2..33f2616cc 100644 +--- a/tests/web-search/web-search-anthropic.test.ts ++++ b/tests/web-search/web-search-anthropic.test.ts +@@ -130,6 +130,27 @@ describe("parseAnthropicSidecarSSE", () => { + expect(out.error).toBeDefined(); + }); + ++ test("an unterminated frame cannot buffer the stream without bound", async () => { ++ // A sidecar that never emits a frame separator: without a cap the parser would accumulate ++ // the whole stream in memory before it could fold anything. ++ let produced = 0; ++ let cancelled = false; ++ const chunk = new TextEncoder().encode(`data: {"filler":"${"x".repeat(64 * 1024)}"}`); ++ const body = new ReadableStream({ ++ pull(c) { ++ if (produced > 8 * 1024 * 1024) { c.close(); return; } ++ produced += chunk.byteLength; ++ c.enqueue(chunk); ++ }, ++ cancel() { cancelled = true; }, ++ }); ++ const out = await parseAnthropicSidecarSSE(new Response(body, { status: 200 })); ++ expect(cancelled).toBe(true); ++ // The cap stops the read long before the producer would have finished on its own. ++ expect(produced).toBeLessThan(1024 * 1024); ++ expect(out.text).toBe(""); ++ }); ++ + test("empty results (content:[]) with answer text is a success, not an error", async () => { + const res = sseResponse([ + { type: "content_block_start", index: 0, content_block: { type: "web_search_tool_result", tool_use_id: "srvtoolu_3", content: [] } }, + +``` diff --git a/devlog/_plan/260907_lane_c/020_vision.md b/devlog/_plan/260907_lane_c/020_vision.md new file mode 100644 index 0000000000..9dab5d18e2 --- /dev/null +++ b/devlog/_plan/260907_lane_c/020_vision.md @@ -0,0 +1,135 @@ +# 3841 implementation contract + +Carry public source patch with -x. Add 64KiB HTTP error-body and non-settling cancel regressions. Preserve complete description frames before cap; discard unfinished frame even at exact cap; retain downstream clamp. No credential-policy changes. + +Validation: local tests/typecheck/build/install NOT RUN by instruction. Read diff and source; top remote CI exercises changed test paths. Each conditional branch listed above is exercised by controlled fixtures; screenshot inspects GUI state. No new enforcement layer; existing API guards remain authoritative. + +## Public source diff (MODIFY/NEW paths) + +```diff +diff --git a/src/vision/anthropic-describe.ts b/src/vision/anthropic-describe.ts +index 4f41017ef..280096f03 100644 +--- a/src/vision/anthropic-describe.ts ++++ b/src/vision/anthropic-describe.ts +@@ -10,6 +10,8 @@ import type { DescribeOutcome, VisionSettings } from "./describe"; + const ANTHROPIC_VISION_MAX_TOKENS = 1024; + const ALLOWED_IMAGE_MIME = new Set(["image/png", "image/jpeg", "image/jpg", "image/webp", "image/gif"]); + const MAX_IMAGE_BYTES = 20 * 1024 * 1024; ++/** Bound the sidecar SSE stream and its untrusted error body; the description is clamped downstream. */ ++const MAX_SIDECAR_RESPONSE_BYTES = 64 * 1024; + const DESCRIBE_INSTRUCTION = + "You are a vision describer for a text-only model that cannot see the image. Describe the image " + + "thoroughly and factually so that model can fully reason about it: transcribe any visible text " + +@@ -43,6 +45,34 @@ function buildImageBlock(imageUrl: string): { block?: AnthropicImageBlock; error + return { error: "unsupported image URL scheme (expected data: or https:)" }; + } + ++/** Read at most `MAX_SIDECAR_RESPONSE_BYTES` of an untrusted upstream body, then stop reading. */ ++async function readBoundedText(res: Response): Promise { ++ if (!res.body) return ""; ++ const reader = res.body.getReader(); ++ const decoder = new TextDecoder(); ++ let out = ""; ++ let seen = 0; ++ try { ++ for (;;) { ++ const { done, value } = await reader.read(); ++ if (done) break; ++ const remaining = MAX_SIDECAR_RESPONSE_BYTES - seen; ++ const accepted = value.byteLength <= remaining ? value : value.subarray(0, remaining); ++ seen += accepted.byteLength; ++ out += decoder.decode(accepted, { stream: true }); ++ if (seen >= MAX_SIDECAR_RESPONSE_BYTES) { ++ try { void reader.cancel("vision sidecar error body byte limit reached").catch(() => undefined); } ++ catch { /* best-effort body teardown */ } ++ break; ++ } ++ } ++ out += decoder.decode(); ++ } catch { ++ /* a failed error-body read must not mask the HTTP status we are about to report */ ++ } ++ return out; ++} ++ + /** Fold Anthropic Messages text deltas into one description. Malformed frames are ignored. */ + export async function parseAnthropicVisionSSE(res: Response): Promise { + if (!res.body) return { text: "", error: "anthropic vision sidecar returned no response body" }; +@@ -52,6 +82,7 @@ export async function parseAnthropicVisionSSE(res: Response): Promise { + let dataLine = ""; +@@ -76,12 +107,24 @@ export async function parseAnthropicVisionSSE(res: Response): Promise= MAX_SIDECAR_RESPONSE_BYTES) { ++ // Keep the frames folded above, drop the unterminated tail, and do not wait on teardown. ++ try { void reader.cancel("vision sidecar response byte limit reached").catch(() => undefined); } ++ catch { /* best-effort body teardown */ } ++ buffer = ""; ++ break; ++ } + } + buffer = (buffer + decoder.decode()).replace(/\r\n/g, "\n"); + if (buffer.trim()) processFrame(buffer); +@@ -164,7 +207,8 @@ export async function describeImageAnthropic( + { abortSignal: linkedSignal.signal, label: "vision-sidecar-anthropic" }, + ); + if (!res.ok) { +- const responseText = await res.text().catch(() => ""); ++ // The body is untrusted and only feeds one auth-failure message, so read a bounded prefix. ++ const responseText = await readBoundedText(res); + console.warn(`[vision] anthropic sidecar HTTP ${res.status} (${Date.now() - startedAt}ms)`); + if (res.status === 401) { + return { text: "", error: `anthropic vision sidecar auth failed: ${publicOAuthAuthenticationErrorMessage(new Error(responseText))}` }; +diff --git a/tests/vision/vision-anthropic.test.ts b/tests/vision/vision-anthropic.test.ts +index ee4b01b42..30ed17af9 100644 +--- a/tests/vision/vision-anthropic.test.ts ++++ b/tests/vision/vision-anthropic.test.ts +@@ -225,6 +225,27 @@ describe("Anthropic vision executor", () => { + expect(result).toEqual({ text: "first second" }); + }); + ++ test("an unterminated frame cannot buffer the stream without bound", async () => { ++ // A sidecar that never emits a frame separator: without a cap the parser accumulates the ++ // whole response in memory before it can fold anything. ++ let produced = 0; ++ let cancelled = false; ++ const chunk = new TextEncoder().encode(`data: {"filler":"${"x".repeat(64 * 1024)}"}`); ++ const body = new ReadableStream({ ++ pull(c) { ++ if (produced > 8 * 1024 * 1024) { c.close(); return; } ++ produced += chunk.byteLength; ++ c.enqueue(chunk); ++ }, ++ cancel() { cancelled = true; }, ++ }); ++ const out = await parseAnthropicVisionSSE(new Response(body, { status: 200 })); ++ expect(cancelled).toBe(true); ++ // The cap stops the read long before the producer would have finished on its own. ++ expect(produced).toBeLessThan(1024 * 1024); ++ expect(out.text).toBe(""); ++ }); ++ + test("malformed and terminal-error streams degrade to explicit errors", async () => { + const malformed = await parseAnthropicVisionSSE(sseResponse(["{not-json", { type: "message_stop" }])); + expect(malformed.text).toBe(""); + +``` diff --git a/devlog/_plan/260907_lane_c/030_health.md b/devlog/_plan/260907_lane_c/030_health.md new file mode 100644 index 0000000000..2e01551e34 --- /dev/null +++ b/devlog/_plan/260907_lane_c/030_health.md @@ -0,0 +1,119 @@ +# 3863 implementation contract + +Carry with -x excluding config-routes.ts. getStartupHealthSnapshot returns fresh cached value unchanged; stale/empty read schedules refresh and returns immediately. Catch rejected or synchronously thrown detached probe and retain stale conservative health; invalidation generation cannot overwrite newer reading. Replace 100ms production settings assertion with controlled probe fixtures. Exact route wiring remains main responsibility. + +Validation: local tests/typecheck/build/install NOT RUN by instruction. Read diff and source; top remote CI exercises changed test paths. Each conditional branch listed above is exercised by controlled fixtures; screenshot inspects GUI state. No new enforcement layer; existing API guards remain authoritative. + +## Public source diff (MODIFY/NEW paths) + +```diff +diff --git a/src/server/management/config-routes.ts b/src/server/management/config-routes.ts +index 4d551a886..9ddd02300 100644 +--- a/src/server/management/config-routes.ts ++++ b/src/server/management/config-routes.ts +@@ -107,7 +107,7 @@ import type { PersistedUsageAttempt } from "../../usage/log"; + import { isAllowedRequestOrigin, jsonResponse, providerManagementConfigError, publicProviderBaseUrl, safeConfigDTO } from "../auth-cors"; + import { withProviderServiceTierDTO } from "./provider-capability-config"; + import { applySystemEnvToggle } from "../system-env"; +-import { getCachedStartupHealth, invalidateStartupHealthCache } from "../startup-health-cache"; ++import { getCachedStartupHealth, getStartupHealthSnapshot, invalidateStartupHealthCache } from "../startup-health-cache"; + import { runWindowsTrayAction } from "../windows-tray-control"; + import { runStartupInstallAction, type StartupInstallAction } from "../startup-action-control"; + import { displayCodexRuntimePath, effortClampAppliesToRuntime, loadLastEffortClamp, resolveCodexRuntime } from "../../codex/runtime"; +@@ -329,7 +329,9 @@ export async function handleConfigRoutes(ctx: ManagementContext): Promise Promise; + } + ++/** ++ * Return the last completed probe immediately and refresh it in the background. ++ * ++ * Settings are consumed by several dashboard controls. They must not block on a ++ * Windows service-manager probe; the dedicated /api/startup-health route owns ++ * the fresh, bounded diagnostic read. ++ */ ++export function getStartupHealthSnapshot( ++ config: Pick, ++ deps: StartupHealthCacheDeps = {}, ++): StartupHealth { ++ const now = deps.now ?? Date.now; ++ if (!cached || now() - cached.timestamp >= CACHE_TTL_MS) refreshInBackground(config, deps); ++ return cached ? markStartupHealthDiagnosticStale(cached.value) : conservativeFallback(config); ++} ++ + export function markStartupHealthDiagnosticStale(value: StartupHealth): StartupHealth { + if (!value.localRoutingDependency) return { ...value, diagnosticStale: true }; + return { +diff --git a/tests/service/autostart-health.test.ts b/tests/service/autostart-health.test.ts +index 639f1b34c..48bb7b539 100644 +--- a/tests/service/autostart-health.test.ts ++++ b/tests/service/autostart-health.test.ts +@@ -3,7 +3,7 @@ import { deriveStartupHealth, formatStartupRoutingDetail, startupHealthSummary } + import { unusedProxyWarningLines } from "../../src/cli/status"; + import { classifyCodexRouting, hasInjectedCodexRouting } from "../../src/codex/inject"; + import { handleManagementAPI } from "../../src/server/management-api"; +-import { getCachedStartupHealth, invalidateStartupHealthCache, markStartupHealthDiagnosticStale } from "../../src/server/startup-health-cache"; ++import { getCachedStartupHealth, getStartupHealthSnapshot, invalidateStartupHealthCache, markStartupHealthDiagnosticStale } from "../../src/server/startup-health-cache"; + import type { OcxConfig } from "../../src/types"; + + const base = { +@@ -277,6 +277,43 @@ describe("Codex startup health", () => { + await pendingProbe; + invalidateStartupHealthCache(); + }); ++ ++ test("settings snapshot starts a probe without waiting for it", async () => { ++ invalidateStartupHealthCache(); ++ let releaseProbe!: (value: ReturnType) => void; ++ const pendingProbe = new Promise>(resolve => { ++ releaseProbe = resolve; ++ }); ++ ++ const health = getStartupHealthSnapshot( ++ { codexAutoStart: true }, ++ { probe: async () => pendingProbe }, ++ ); ++ ++ expect(health.diagnosticStale).toBe(true); ++ releaseProbe(deriveStartupHealth({ ...base, routingKind: "native" })); ++ await pendingProbe; ++ invalidateStartupHealthCache(); ++ }); ++ ++ test("settings GET uses the non-blocking startup-health snapshot in production", async () => { ++ invalidateStartupHealthCache(); ++ const url = new URL("http://localhost/api/settings"); ++ ++ const response = await Promise.race([ ++ handleManagementAPI( ++ new Request(url), ++ url, ++ { port: 10100, providers: {}, defaultProvider: "openai", codexAutoStart: true } as OcxConfig, ++ ), ++ new Promise(resolve => setTimeout(() => resolve(null), 100)), ++ ]); ++ ++ expect(response?.status).toBe(200); ++ const body = await response!.json() as { startupHealth?: { diagnosticStale?: boolean } }; ++ expect(body.startupHealth?.diagnosticStale).toBe(true); ++ invalidateStartupHealthCache(); ++ }); + }); + import { ManagementRequest as Request } from "../helpers/management-auth"; + + +``` diff --git a/devlog/_plan/260907_lane_c/040_desktop.md b/devlog/_plan/260907_lane_c/040_desktop.md new file mode 100644 index 0000000000..ad7fb60177 --- /dev/null +++ b/devlog/_plan/260907_lane_c/040_desktop.md @@ -0,0 +1,404 @@ +# 3860 implementation contract + +Carry source patch plus skipped-sync correction with -x. Default false/absent OFF, true remains true; persist preference before sync and surface sync failures. All nine locales and existing screenshot. Independent auth boundary review confirms remote admission/upstream credentials unchanged. + +Validation: local tests/typecheck/build/install NOT RUN by instruction. Read diff and source; top remote CI exercises changed test paths. Each conditional branch listed above is exercised by controlled fixtures; screenshot inspects GUI state. No new enforcement layer; existing API guards remain authoritative. + +## Public source diff (MODIFY/NEW paths) + +```diff +diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md +index 7d66e72c3..ff2df04fd 100644 +--- a/docs-site/src/content/docs/guides/codex-integration.md ++++ b/docs-site/src/content/docs/guides/codex-integration.md +@@ -215,6 +215,15 @@ HTTP/SSE. + + ### Authless Codex Desktop (opt-in) + ++In **Dashboard → Overview**, **Open Codex without signing in** controls this existing ++opt-in preference. The switch defaults to **off** when the setting is absent or false; ++an existing explicit `codexDesktopAuthless: true` stays enabled. The dashboard saves ++the preference and runs a full sync. Restart Codex Desktop after changing it. ++If synchronization fails, the saved preference remains and the dashboard shows the error; ++retry **Sync** before restarting. Account-gated Desktop features may be unavailable ++when enabled. Upstream credentials, local eligibility, remote admission authentication ++and user-owned gateway settings retain their existing requirements. ++ + Codex Desktop shows its ChatGPT login screen whenever the active provider requires OpenAI auth. If + your OpenCodex setup never uses ChatGPT credentials (routed providers only, or a blocked + `chatgpt.com`), you can opt out of that gate: +diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts +index 5faab4b35..495104bd4 100644 +--- a/gui/src/i18n/de.ts ++++ b/gui/src/i18n/de.ts +@@ -299,6 +299,8 @@ export const de: Record = { + "models.staleBanner": "Codex zeigt eine ältere Modellliste als dieser Katalog. Starte Codex neu, um sie neu zu laden.", + "dash.codexAutoStart": "opencodex mit Codex starten", + "dash.codexAutoStartHint": "Erlaubt einem installierten Launcher-Shim, ocx ensure auszuführen. Diese Einstellung installiert keinen Neustartschutz; prüfe den effektiven Zustand unter Startsicherheit.", ++ "dash.codexDesktopAuthless": "Codex ohne Anmeldung öffnen", ++ "dash.codexDesktopAuthlessHint": "Standardmäßig aus. Überspringt die separate Desktop-Anmeldung bei geeigneten lokalen Verbindungen. Zugangsdaten für den Anbieter bleiben erforderlich. Codex nach einer Änderung neu starten. Kontogebundene Desktop-Funktionen können fehlen.", + "dash.searchModel": "Such-Sidecar-Modell", + "dash.searchModelHint": "Modell für web_search bei nicht über OpenAI gerouteten Modellen. Erfordert ChatGPT-Login.", + "dash.searchReasoning": "Such-Reasoning-Aufwand", +diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts +index c71208942..22a380785 100644 +--- a/gui/src/i18n/en.ts ++++ b/gui/src/i18n/en.ts +@@ -311,6 +311,8 @@ export const en = { + "models.staleBanner": "Codex is showing an older model list than this catalog. Restart Codex to reload it.", + "dash.codexAutoStart": "Start opencodex with Codex", + "dash.codexAutoStartHint": "Allows an installed launcher shim to run ocx ensure. This setting does not install restart protection; check Startup safety for the effective state.", ++ "dash.codexDesktopAuthless": "Open Codex without signing in", ++ "dash.codexDesktopAuthlessHint": "Off by default. Skip the separate Desktop sign-in for eligible local connections. Upstream credentials are still required. Restart Codex after changing this setting. Account-gated Desktop features may be unavailable.", + "dash.searchModel": "Search sidecar model", + "dash.searchModelHint": "Model used for web_search on non-OpenAI routed models. Requires ChatGPT login.", + "dash.searchReasoning": "Search reasoning effort", +diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts +index e1b3519ef..9f0f26517 100644 +--- a/gui/src/i18n/fr.ts ++++ b/gui/src/i18n/fr.ts +@@ -301,6 +301,8 @@ export const fr: Record = { + "models.staleBanner": "Codex affiche une liste de modèles plus ancienne que ce catalogue. Redémarrez Codex pour la recharger.", + "dash.codexAutoStart": "Démarrer opencodex avec Codex", + "dash.codexAutoStartHint": "Permet à un mécanisme de lancement installé d’exécuter ocx ensure. Ce réglage n’installe pas de protection au redémarrage ; consultez Sécurité du démarrage pour connaître l’état effectif.", ++ "dash.codexDesktopAuthless": "Ouvrir Codex sans se connecter", ++ "dash.codexDesktopAuthlessHint": "Désactivé par défaut. Ignore la connexion Desktop séparée pour les connexions locales admissibles. Les identifiants du fournisseur restent nécessaires. Redémarrez Codex après toute modification. Certaines fonctions Desktop liées au compte peuvent être indisponibles.", + "dash.searchModel": "Modèle auxiliaire de recherche", + "dash.searchModelHint": "Modèle utilisé pour web_search sur les modèles routés autres qu’OpenAI. Nécessite une connexion à ChatGPT.", + "dash.searchReasoning": "Effort de raisonnement pour la recherche", +diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts +index cf9483158..55a6fe249 100644 +--- a/gui/src/i18n/ja.ts ++++ b/gui/src/i18n/ja.ts +@@ -308,6 +308,8 @@ export const ja: Record = { + "models.staleBanner": "Codex はこのカタログより古いモデル一覧を表示しています。Codex を再起動すると読み直されます。", + "dash.codexAutoStart": "Codex と一緒に opencodex を起動", + "dash.codexAutoStartHint": "インストール済み launcher shim に ocx ensure の実行を許可します。この設定だけでは再起動保護はインストールされません。起動安全性で実際の状態を確認してください。", ++ "dash.codexDesktopAuthless": "ログインせずに Codex を開く", ++ "dash.codexDesktopAuthlessHint": "既定ではオフです。対象のローカル接続で Desktop の個別ログインを省略します。上流プロバイダーの認証情報は引き続き必要です。変更後は Codex を再起動してください。アカウントに依存する Desktop 機能が利用できない場合があります。", + "dash.searchModel": "検索サイドカーモデル", + "dash.searchModelHint": "非 OpenAI ルーティングモデルで web_search に使うモデル。ChatGPT ログインが必要です。", + "dash.searchReasoning": "検索の推論負荷", +diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts +index c1959482b..19285b150 100644 +--- a/gui/src/i18n/ko.ts ++++ b/gui/src/i18n/ko.ts +@@ -303,6 +303,8 @@ export const ko: Record = { + "models.staleBanner": "Codex가 이 카탈로그보다 오래된 모델 목록을 보여주고 있습니다. Codex를 재시작하면 새로 읽습니다.", + "dash.codexAutoStart": "Codex 실행 시 opencodex 시작", + "dash.codexAutoStartHint": "설치된 launcher shim이 ocx ensure를 실행하도록 허용합니다. 이 설정은 재부팅 보호를 설치하지 않으므로 시작 안전성에서 실제 상태를 확인하세요.", ++ "dash.codexDesktopAuthless": "로그인 없이 Codex 열기", ++ "dash.codexDesktopAuthlessHint": "기본값은 꺼짐입니다. 지원되는 로컬 연결에서 별도의 Desktop 로그인을 건너뜁니다. 업스트림 인증 정보는 여전히 필요합니다. 변경 후 Codex를 다시 시작하세요. 계정에 연결된 Desktop 기능을 사용하지 못할 수 있습니다.", + "dash.searchModel": "서치 사이드카 모델", + "dash.searchModelHint": "비-OpenAI 라우팅 모델의 web_search에 사용되는 모델입니다. ChatGPT 로그인 필요.", + "dash.searchReasoning": "서치 추론 강도", +diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts +index 0109f5ebd..87704912a 100644 +--- a/gui/src/i18n/ru.ts ++++ b/gui/src/i18n/ru.ts +@@ -308,6 +308,8 @@ export const ru: Record = { + "models.staleBanner": "Codex показывает список моделей старее этого каталога. Перезапустите Codex, чтобы перечитать его.", + "dash.codexAutoStart": "Запускать opencodex вместе с Codex", + "dash.codexAutoStartHint": "Разрешает установленному launcher shim выполнять ocx ensure. Эта настройка не устанавливает защиту перезапуска; проверьте фактическое состояние в разделе безопасности запуска.", ++ "dash.codexDesktopAuthless": "Открывать Codex без входа", ++ "dash.codexDesktopAuthlessHint": "По умолчанию выключено. Пропускает отдельный вход в Desktop для допустимых локальных подключений. Учётные данные провайдера по-прежнему нужны. После изменения перезапустите Codex. Функции Desktop, связанные с аккаунтом, могут быть недоступны.", + "dash.searchModel": "Модель сайдкара поиска", + "dash.searchModelHint": "Модель, используемая для web_search на маршрутизируемых моделях, отличных от OpenAI. Требуется вход в аккаунт ChatGPT.", + "dash.searchReasoning": "Уровень рассуждений для поиска", +diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts +index fa8b8e9c2..807eeae32 100644 +--- a/gui/src/i18n/tr.ts ++++ b/gui/src/i18n/tr.ts +@@ -309,6 +309,8 @@ export const tr: Record = { + "models.staleBanner": "Codex, bu katalogdan daha eski bir model listesi gösteriyor. Yeniden okumak için Codex'i yeniden başlatın.", + "dash.codexAutoStart": "opencodex'i Codex ile başlat", + "dash.codexAutoStartHint": "Yüklü bir shim'in ocx ensure çalıştırmasına izin verir. Arka plan servisi veya yeniden başlatma koruması kurmaz; sistem durumu için Başlatma Güvenliği'ne bakın.", ++ "dash.codexDesktopAuthless": "Codex’i oturum açmadan başlat", ++ "dash.codexDesktopAuthlessHint": "Varsayılan olarak kapalıdır. Uygun yerel bağlantılarda ayrı Desktop oturum açma adımını atlar. Sağlayıcı kimlik bilgileri yine gereklidir. Değişiklikten sonra Codex’i yeniden başlatın. Hesaba bağlı Desktop özellikleri kullanılamayabilir.", + "dash.searchModel": "Arama yan araç modeli", + "dash.searchModelHint": "OpenAI dışı yönlendirilen modellerde web_search için kullanılan model. ChatGPT girişi gerektirir.", + "dash.searchReasoning": "Arama akıl yürütme çabası", +diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts +index 3bc246543..62e1f0711 100644 +--- a/gui/src/i18n/zh-TW.ts ++++ b/gui/src/i18n/zh-TW.ts +@@ -200,6 +200,8 @@ export const zhTW: Record = { + "models.staleBanner": "Codex 顯示的模型清單比目前的目錄舊。重新啟動 Codex 即可重新讀取。", + "dash.codexAutoStart": "隨 Codex 啟動 opencodex", + "dash.codexAutoStartHint": "允許已安裝的 launcher shim 執行 ocx ensure。此設定不會安裝重新啟動保護;請在啟動安全中檢查實際狀態。", ++ "dash.codexDesktopAuthless": "無需登入即可開啟 Codex", ++ "dash.codexDesktopAuthlessHint": "預設關閉。為符合條件的本機連線略過獨立的 Desktop 登入。仍需上游供應商憑證。變更後請重新啟動 Codex。依賴帳戶的 Desktop 功能可能無法使用。", + "dash.searchModel": "搜尋附屬模型", + "dash.searchModelHint": "用於非 OpenAI 路由模型的 web_search 的模型。需要 ChatGPT 登入。", + "dash.searchReasoning": "搜尋推理強度", +diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts +index b10c48688..994691442 100644 +--- a/gui/src/i18n/zh.ts ++++ b/gui/src/i18n/zh.ts +@@ -303,6 +303,8 @@ export const zh: Record = { + "models.staleBanner": "Codex 显示的模型列表比当前目录旧。重启 Codex 即可重新读取。", + "dash.codexAutoStart": "随 Codex 启动 opencodex", + "dash.codexAutoStartHint": "允许已安装的 launcher shim 运行 ocx ensure。此设置不会安装重启保护;请在启动安全中检查实际状态。", ++ "dash.codexDesktopAuthless": "无需登录即可打开 Codex", ++ "dash.codexDesktopAuthlessHint": "默认关闭。为符合条件的本地连接跳过单独的 Desktop 登录。仍需上游提供商凭据。更改后请重启 Codex。依赖账户的 Desktop 功能可能不可用。", + "dash.searchModel": "搜索附属模型", + "dash.searchModelHint": "用于非 OpenAI 路由模型的 web_search 的模型。需要 ChatGPT 登录。", + "dash.searchReasoning": "搜索推理强度", +diff --git a/gui/src/pages/dashboard-overview-sections.tsx b/gui/src/pages/dashboard-overview-sections.tsx +index 8da531f97..6606c4f56 100644 +--- a/gui/src/pages/dashboard-overview-sections.tsx ++++ b/gui/src/pages/dashboard-overview-sections.tsx +@@ -163,7 +163,7 @@ export function DashboardInjectionPanel({ d }: { apiBase: string; d: Dash }) { + + export function DashboardMaintenancePanel({ d }: { d: Dash }) { + const { +- t, runSync, syncing, updateTriggerRef, openUpdateDialog, updateLoading, updateOpen, ++ t, runSync, syncing, settingsSaving, updateTriggerRef, openUpdateDialog, updateLoading, updateOpen, + syncResult, syncError, updateJob, reconnecting, clearSyncFeedback, + } = d; + const syncHoldsWarning = !!syncResult && ( +@@ -211,7 +211,7 @@ export function DashboardMaintenancePanel({ d }: { d: Dash }) { +
{t("dash.syncModelsHint")}
+
+
+- +
+ + ++
++
++
++
{t("dash.codexDesktopAuthless")}
++
{t("dash.codexDesktopAuthlessHint")}
++ {settings?.catalogRefreshPending &&
{t("codexAuth.catalogRefreshPending")}
} ++
++ ++
++
++ +
+ {/* Both sidecar cards wear the DashboardInjectionPanel shell: the PANEL is + the flex row, copy left, controls right. */} +diff --git a/gui/src/pages/dashboard-shared.ts b/gui/src/pages/dashboard-shared.ts +index 0793a7def..d24051028 100644 +--- a/gui/src/pages/dashboard-shared.ts ++++ b/gui/src/pages/dashboard-shared.ts +@@ -48,6 +48,8 @@ export interface ProviderInfo { name: string; adapter: string; baseUrl: string; + export interface ModelInfo { id: string; provider: string; namespaced: string; owned_by?: string; reasoningEfforts?: string[] } + export interface SettingsData { + codexAutoStart: boolean; ++ codexDesktopAuthless?: boolean; ++ catalogRefreshPending?: boolean; + /** Whether a login may open a browser on the machine running the proxy. */ + oauthOpenBrowser?: boolean; + port: number; +diff --git a/gui/src/pages/use-dashboard-data.ts b/gui/src/pages/use-dashboard-data.ts +index 6f84950ce..6da776ea1 100644 +--- a/gui/src/pages/use-dashboard-data.ts ++++ b/gui/src/pages/use-dashboard-data.ts +@@ -607,23 +607,24 @@ export function useDashboardData(apiBase: string) { + finally { setInjectionSaving(false); } + }; + +- const toggleCodexAutoStart = async () => { +- if (!settings || settingsSaving) return; +- const next = !settings.codexAutoStart; ++ const toggleCodexSetting = async (key: "codexAutoStart" | "codexDesktopAuthless") => { ++ if (!settings || settingsSaving || syncing) return; ++ const next = !(settings[key] ?? (key === "codexAutoStart")); + setSettingsSaving(true); + settingsMutationInFlightRef.current = true; +- setSettings({ ...settings, codexAutoStart: next }); ++ setSettings({ ...settings, [key]: next }); + try { + const res = await fetch(`${apiBase}/api/settings`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, +- body: JSON.stringify({ codexAutoStart: next }), ++ body: JSON.stringify({ [key]: next }), + }); +- const data = await requireJson<{ codexAutoStart: boolean; startupHealth?: SettingsData["startupHealth"] }>(res, "save failed"); ++ const data = await requireJson(res, "save failed"); + settingsMutationEpochRef.current += 1; +- setSettings(prev => prev ? { ...prev, codexAutoStart: data.codexAutoStart, startupHealth: data.startupHealth ?? prev.startupHealth } : prev); ++ setSettings(prev => prev ? { ...prev, [key]: data[key], catalogRefreshPending: key === "codexDesktopAuthless" ? data.catalogRefreshPending : prev.catalogRefreshPending, startupHealth: data.startupHealth ?? prev.startupHealth } : prev); ++ if (key === "codexDesktopAuthless") await runSync(); + } catch { +- setSettings(prev => prev ? { ...prev, codexAutoStart: !next } : prev); ++ setSettings(prev => prev ? { ...prev, [key]: !next } : prev); + setError(true); + } finally { + settingsMutationInFlightRef.current = false; +@@ -631,6 +632,9 @@ export function useDashboardData(apiBase: string) { + } + }; + ++ const toggleCodexAutoStart = () => toggleCodexSetting("codexAutoStart"); ++ const toggleCodexDesktopAuthless = () => toggleCodexSetting("codexDesktopAuthless"); ++ + // Clears the sync result/error in this hook. The dashboard toast owns its own dismissal + // timer but must publish the dismissal here: syncResult/syncError live above the dashboard + // tabs, so a component-local flag alone would let a stale result remount as a fresh toast +@@ -649,6 +653,7 @@ export function useDashboardData(apiBase: string) { + const res = await fetch(`${apiBase}/api/sync`, { method: "POST" }); + const data = await requireJson(res, "sync failed"); + setSyncResult(data); ++ setSettings(prev => prev ? { ...prev, catalogRefreshPending: false } : prev); + if (data.projectConfigGrouped) setProjectConfigWarnings(data.projectConfigGrouped); + } catch (err) { + setSyncError(err instanceof Error ? err.message : String(err)); +@@ -789,7 +794,7 @@ export function useDashboardData(apiBase: string) { + effortCapHelpTriggerRef, updateTriggerRef, maHelpTriggerRef, shadowCallHelpTriggerRef, + effortCapHelpDialogRef, updateDialogRef, maHelpDialogRef, shadowCallHelpDialogRef, + filteredGroups, sidecarModels, visionModels, +- saveSidecar, saveShadowCall, switchMaMode, toggleCodexAutoStart, runSync, clearSyncFeedback, ++ saveSidecar, saveShadowCall, switchMaMode, toggleCodexAutoStart, toggleCodexDesktopAuthless, runSync, clearSyncFeedback, + fetchUpdateCheck, closeUpdateDialog, openUpdateDialog, changeUpdateChannel, runUpdate, + }; + } +diff --git a/gui/tests/vision-sidecar-dashboard.test.tsx b/gui/tests/vision-sidecar-dashboard.test.tsx +index dc762de58..994a40912 100644 +--- a/gui/tests/vision-sidecar-dashboard.test.tsx ++++ b/gui/tests/vision-sidecar-dashboard.test.tsx +@@ -12,7 +12,7 @@ import { LanguageProvider } from "../src/i18n/provider"; + import { DashboardSidecarPanels } from "../src/pages/dashboard-overview-sections"; + import type { SidecarData, SidecarPatch } from "../src/pages/dashboard-shared"; + import { mergeSidecarSetting } from "../src/pages/dashboard-shared"; +-import type { useDashboardData } from "../src/pages/use-dashboard-data"; ++import { useDashboardData } from "../src/pages/use-dashboard-data"; + + const globals = ["document", "window", "navigator", "IS_REACT_ACT_ENVIRONMENT"] as const; + let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; +@@ -382,4 +382,79 @@ test("model and reasoning saves still omit enabled, limit, and timeout", async ( + expect(patches).toHaveLength(2); + expect(patches[1]).toEqual({ vision: { reasoning: "high" } }); + assertVisionControlFieldsOmitted(patches[1]!); +-}); +\ No newline at end of file ++}); ++ ++test("Desktop login switch defaults off, preserves explicit opt-in, and disables while saving", async () => { ++ const { d } = harness(); ++ let clicks = 0; ++ d.toggleCodexDesktopAuthless = async () => { clicks += 1; }; ++ d.settings = { codexAutoStart: true, port: 10100, hostname: "127.0.0.1" }; ++ await mount(d); ++ const toggle = () => host.querySelector(`button[aria-label="${en["dash.codexDesktopAuthless"]}"]`)!; ++ expect(toggle().getAttribute("aria-pressed")).toBe("false"); ++ d.settings.codexDesktopAuthless = true; ++ await mount(d); ++ expect(toggle().getAttribute("aria-pressed")).toBe("true"); ++ await act(async () => { toggle().click(); }); ++ expect(clicks).toBe(1); ++ d.settings.codexDesktopAuthless = false; ++ d.settings.catalogRefreshPending = true; ++ d.settingsSaving = true; ++ await mount(d); ++ expect(toggle().getAttribute("aria-pressed")).toBe("false"); ++ expect(toggle().disabled).toBe(true); ++ expect(host.textContent).toContain(en["codexAuth.catalogRefreshPending"]); ++}); ++ ++ ++test.each([undefined, false, true])("Desktop login preference %s persists before full sync; sync failure keeps the saved preference", async (initial) => { ++ const originalFetch = globalThis.fetch; ++ const writes: Array<{ path: string; body: unknown }> = []; ++ let latest: Dash | undefined; ++ let saved = initial; ++ const apiBase = `/authless-test-${String(initial)}`; ++ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { ++ const path = String(input); ++ if (init?.method === "PUT") { ++ const body = JSON.parse(String(init.body)); ++ writes.push({ path, body }); ++ if (body.codexDesktopAuthless !== undefined) { ++ saved = body.codexDesktopAuthless; ++ return Response.json({ codexDesktopAuthless: saved, catalogRefreshPending: true }); ++ } ++ return Response.json({ codexAutoStart: body.codexAutoStart, catalogRefreshPending: false }); ++ } ++ if (path.endsWith("/api/sync")) { ++ writes.push({ path, body: null }); ++ return Response.json({ error: "sync unavailable" }, { status: 503 }); ++ } ++ if (path.endsWith("/api/settings")) { ++ return Response.json({ codexAutoStart: true, codexDesktopAuthless: saved, port: 10100, hostname: "127.0.0.1" }); ++ } ++ return Response.json({}, { status: 503 }); ++ }) as typeof fetch; ++ function Harness() { latest = useDashboardData(apiBase); return null; } ++ try { ++ const { createRoot } = await import("react-dom/client"); ++ await act(async () => { ++ root = createRoot(host); ++ root.render(); ++ }); ++ expect(latest?.settings?.codexDesktopAuthless).toBe(initial); ++ await act(async () => { await latest!.toggleCodexDesktopAuthless(); }); ++ expect(writes).toEqual([ ++ { path: `${apiBase}/api/settings`, body: { codexDesktopAuthless: !initial } }, ++ { path: `${apiBase}/api/sync`, body: null }, ++ ]); ++ expect(latest?.settings?.codexDesktopAuthless).toBe(!initial); ++ expect(latest?.syncError).toBe("sync unavailable"); ++ expect(latest?.settings?.catalogRefreshPending).toBe(true); ++ await act(async () => { await latest!.toggleCodexAutoStart(); }); ++ expect(latest?.settings?.codexAutoStart).toBe(false); ++ expect(latest?.settings?.catalogRefreshPending).toBe(true); ++ } finally { ++ await act(async () => { root?.unmount(); }); ++ root = null; ++ globalThis.fetch = originalFetch; ++ } ++}); +diff --git a/tests/codex-integration/codex-inject.test.ts b/tests/codex-integration/codex-inject.test.ts +index 84ac5f67b..b6be3c2f6 100644 +--- a/tests/codex-integration/codex-inject.test.ts ++++ b/tests/codex-integration/codex-inject.test.ts +@@ -31,8 +31,8 @@ describe("Codex config injection", () => { + }); + + describe("authless Codex Desktop opt-in (#1107)", () => { +- test("default target on loopback stays Design B and byte-identical", () => { +- const target = standaloneCodexRoutingTarget(10100, {}); ++ test.each([undefined, false])("disabled preference %s on loopback stays Design B and byte-identical", (codexDesktopAuthless) => { ++ const target = standaloneCodexRoutingTarget(10100, { codexDesktopAuthless }); + expect(target.desktopAuthless).toBeUndefined(); + expect(buildProfileFile(target, null)).toBe(buildProfileFile(10100, null)); + expect(buildProviderTableBlock(target)).toContain("requires_openai_auth = true"); + +``` + +Audit amendment: clear catalogRefreshPending only if sync status is affirmative success, not HTTP 200 skipped. Add skipped/no-write regression. diff --git a/devlog/_plan/260907_lane_c/050_fallback.md b/devlog/_plan/260907_lane_c/050_fallback.md new file mode 100644 index 0000000000..6bf165a96c --- /dev/null +++ b/devlog/_plan/260907_lane_c/050_fallback.md @@ -0,0 +1,368 @@ +# 3252 implementation contract + +Carry source commits with -x. Preserve configured fallback models absent from availability. Add focused GUI tests for add/remove/reorder/save and unavailable model round-trip. Reuse existing /api/v2 (enabled, multiAgentMode, keepNativeChatGptOnV1) and report recovery enabled/eligibility as unknown when the server does not expose it, never fabricate recovery settings state for contextual native-parent/routed-child V2 guidance. Never infer all workflows are native; warn conditionally, show disabled/eligible/experimental/unknown state truthfully, link issue 92. No roster-reuse switch. Update all locales and codex-integration docs; actual UI screenshot. New PR body is valid Markdown, removes unsupported roster-switch claims. + +Validation: local tests/typecheck/build/install NOT RUN by instruction. Read diff and source; top remote CI exercises changed test paths. Each conditional branch listed above is exercised by controlled fixtures; screenshot inspects GUI state. No new enforcement layer; existing API guards remain authoritative. + +## Public source diff (MODIFY/NEW paths) + +```diff +diff --git a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx +index 46c0447a7..7c3b0e942 100644 +--- a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx ++++ b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx +@@ -28,6 +28,13 @@ export interface SubagentDelegationSectionProps { + onUltraModeSave: (patch: UltraModePatch) => void; + ultraLoadFailed: boolean; + onUltraModeRetry: () => void; ++ fallback: string[]; ++ fallbackPollMs: number; ++ fallbackBusy: boolean; ++ availableModels: string[]; ++ onFallbackChange: (models: string[]) => void; ++ onFallbackPollMsChange: (pollMs: number) => void; ++ onFallbackSave: () => void; + } + + export default function SubagentDelegationSection({ +@@ -44,6 +51,7 @@ export default function SubagentDelegationSection({ + onUltraModeSave, + ultraLoadFailed, + onUltraModeRetry, ++ fallback, fallbackPollMs, fallbackBusy, availableModels, onFallbackChange, onFallbackPollMsChange, onFallbackSave, + }: SubagentDelegationSectionProps) { + const t = useT(); + // A present empty/whitespace hint is an upstream override that suppresses the +@@ -97,6 +105,31 @@ export default function SubagentDelegationSection({ +
+ + ++
++
++
{t("sub.fallbackLabel")}
++
{t("sub.fallbackHint")}
++
++
++ {fallback.map((modelName, index) => ( ++
++ {index + 1}. {modelName} ++ ++ ++ ++
++ ))} ++ ++ ++ ++
++
++ +
+
+
{t("dash.syncCodexSubagentDefaults")}
+diff --git a/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx b/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx +index a22bd2a30..30b722b2b 100644 +--- a/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx ++++ b/gui/src/components/subagents-workspace/SubagentsWorkspace.tsx +@@ -37,6 +37,12 @@ export interface SubagentsWorkspaceProps { + onToggle: (m: string) => void; + onMove: (i: number, dir: -1 | 1) => void; + onSave: () => void; ++ fallback: string[]; ++ fallbackPollMs: number; ++ fallbackBusy: boolean; ++ onFallbackChange: (models: string[]) => void; ++ onFallbackPollMsChange: (pollMs: number) => void; ++ onFallbackSave: () => void; + delegation: { + model: string; + effort: string; +@@ -63,6 +69,7 @@ export default function SubagentsWorkspace({ + onToggle, + onMove, + onSave, ++ fallback, fallbackPollMs, fallbackBusy, onFallbackChange, onFallbackPollMsChange, onFallbackSave, + delegation, + }: SubagentsWorkspaceProps) { + const t = useT(); +@@ -237,6 +244,13 @@ export default function SubagentsWorkspace({ + onUltraModeSave={delegation.onUltraModeSave} + ultraLoadFailed={delegation.ultraLoadFailed} + onUltraModeRetry={delegation.onUltraModeRetry} ++ fallback={fallback} ++ fallbackPollMs={fallbackPollMs} ++ fallbackBusy={fallbackBusy} ++ availableModels={available} ++ onFallbackChange={onFallbackChange} ++ onFallbackPollMsChange={onFallbackPollMsChange} ++ onFallbackSave={onFallbackSave} + /> + +
+diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts +index 429379396..2bb0b10c1 100644 +--- a/gui/src/i18n/de.ts ++++ b/gui/src/i18n/de.ts +@@ -672,6 +672,12 @@ export const de: Record = { + "sub.ultraModeLoadFail": "Ultra-Modus-Einstellungen konnten nicht geladen werden — läuft der Proxy?", + "sub.ultraModeSaveFail": "Ultra-Modus-Einstellungen konnten nicht gespeichert werden", + "sub.ultraModeSaved": "Ultra-Modus gespeichert. Gilt für neue Codex-Sitzungen.", ++ "sub.fallbackLabel": "Fallback-Kette für Sub-Agenten", ++ "sub.fallbackHint": "Geordnete Modelle, die versucht werden, wenn ein Sub-Agent-Modell nicht verfügbar ist oder fehlschlägt.", ++ "sub.fallbackAdd": "Fallback-Modell hinzufügen…", ++ "sub.fallbackPoll": "Intervall der Verfügbarkeitsprüfung", ++ "sub.fallbackSaved": "Fallback-Einstellungen für Sub-Agenten gespeichert.", ++ "sub.fallbackSaveFailed": "Fallback-Einstellungen konnten nicht gespeichert werden", + "logs.title": "Anfrage-Protokolle", + "logs.tabLogs": "Protokolle", + "logs.tabDebug": "Diagnose", +diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts +index 9cbf8699f..e1346616a 100644 +--- a/gui/src/i18n/en.ts ++++ b/gui/src/i18n/en.ts +@@ -315,6 +315,12 @@ export const en = { + "dash.visionTimeout": "Timeout", + "dash.visionTimeoutInvalid": "Enter an integer from {min} to {max} milliseconds.", + "dash.visionAdvancedPopover": "Advanced vision settings", ++ "sub.fallbackLabel": "Sub-agent fallback chain", ++ "sub.fallbackHint": "Ordered models tried when a sub-agent model is unavailable or fails.", ++ "sub.fallbackAdd": "Add fallback model…", ++ "sub.fallbackPoll": "Availability check interval", ++ "sub.fallbackSaved": "Sub-agent fallback settings saved.", ++ "sub.fallbackSaveFailed": "Failed to save fallback settings", + "dash.shadowCallIntercept": "Shadow Call Intercept", + "dash.shadowCallInterceptHint": "Intercepts Codex App's background helper calls ({models}) for title generation and commit messages and redirects them to your chosen model.", + "dash.shadowCallWarning": "⚠ When enabled, ALL requests for {models} will be replaced with the selected model.", +diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts +index ec171e627..d5d29b0be 100644 +--- a/gui/src/i18n/fr.ts ++++ b/gui/src/i18n/fr.ts +@@ -305,6 +305,12 @@ export const fr: Record = { + "dash.visionTimeout": "Délai d’expiration", + "dash.visionTimeoutInvalid": "Saisissez un entier compris entre {min} et {max} millisecondes.", + "dash.visionAdvancedPopover": "Paramètres de vision avancés", ++ "sub.fallbackLabel": "Chaîne de secours des sous-agents", ++ "sub.fallbackHint": "Modèles essayés dans l’ordre lorsqu’un modèle de sous-agent est indisponible ou échoue.", ++ "sub.fallbackAdd": "Ajouter un modèle de secours…", ++ "sub.fallbackPoll": "Intervalle de vérification de disponibilité", ++ "sub.fallbackSaved": "Paramètres de secours des sous-agents enregistrés.", ++ "sub.fallbackSaveFailed": "Échec de l’enregistrement des paramètres de secours", + "dash.shadowCallIntercept": "Interception des appels fantômes", + "dash.shadowCallInterceptHint": "Intercepte les appels auxiliaires en arrière-plan de l’application Codex ({models}) pour générer les titres et les messages de commit, puis les redirige vers le modèle choisi.", + "dash.shadowCallWarning": "⚠ Lorsque cette option est activée, TOUTES les requêtes destinées à {models} sont remplacées par le modèle sélectionné.", +diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts +index c71bd7a04..747438bdc 100644 +--- a/gui/src/i18n/ja.ts ++++ b/gui/src/i18n/ja.ts +@@ -632,6 +632,12 @@ export const ja: Record = { + "sub.ultraModeLoadFail": "ウルトラモード設定を読み込めませんでした — プロキシは実行中ですか?", + "sub.ultraModeSaveFail": "ウルトラモード設定の保存に失敗しました", + "sub.ultraModeSaved": "ウルトラモードを保存しました。新しい Codex セッションから適用されます。", ++ "sub.fallbackLabel": "サブエージェントのフォールバックチェーン", ++ "sub.fallbackHint": "サブエージェントモデルが利用できないか失敗した場合に順番に試すモデルです。", ++ "sub.fallbackAdd": "フォールバックモデルを追加…", ++ "sub.fallbackPoll": "利用可能性チェック間隔", ++ "sub.fallbackSaved": "サブエージェントのフォールバック設定を保存しました。", ++ "sub.fallbackSaveFailed": "フォールバック設定の保存に失敗しました", + + // logs + "logs.title": "リクエストログ", +diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts +index 63ac30442..ecc0e4560 100644 +--- a/gui/src/i18n/ko.ts ++++ b/gui/src/i18n/ko.ts +@@ -689,6 +689,12 @@ export const ko: Record = { + "sub.ultraModeLoadFail": "울트라 모드 설정을 불러오지 못했습니다 — 프록시가 실행 중인가요?", + "sub.ultraModeSaveFail": "울트라 모드 설정 저장에 실패했습니다", + "sub.ultraModeSaved": "울트라 모드가 저장되었습니다. 새 Codex 세션부터 적용됩니다.", ++ "sub.fallbackLabel": "서브에이전트 폴백 체인", ++ "sub.fallbackHint": "서브에이전트 모델을 사용할 수 없거나 실패할 때 순서대로 시도할 모델입니다.", ++ "sub.fallbackAdd": "폴백 모델 추가…", ++ "sub.fallbackPoll": "가용성 확인 간격", ++ "sub.fallbackSaved": "서브에이전트 폴백 설정을 저장했습니다.", ++ "sub.fallbackSaveFailed": "폴백 설정을 저장하지 못했습니다", + + // logs + "logs.title": "요청 로그", +diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts +index 9f220ba2b..852eb4467 100644 +--- a/gui/src/i18n/ru.ts ++++ b/gui/src/i18n/ru.ts +@@ -687,6 +687,12 @@ export const ru: Record = { + "sub.ultraModeLoadFail": "Не удалось загрузить настройки ультра-режима — работает ли прокси?", + "sub.ultraModeSaveFail": "Не удалось сохранить настройки ультра-режима", + "sub.ultraModeSaved": "Ультра-режим сохранён. Применяется к новым сеансам Codex.", ++ "sub.fallbackLabel": "Цепочка резервных моделей субагента", ++ "sub.fallbackHint": "Модели, которые последовательно пробуются, если модель субагента недоступна или завершается ошибкой.", ++ "sub.fallbackAdd": "Добавить резервную модель…", ++ "sub.fallbackPoll": "Интервал проверки доступности", ++ "sub.fallbackSaved": "Настройки резервных моделей субагента сохранены.", ++ "sub.fallbackSaveFailed": "Не удалось сохранить настройки резервных моделей", + + // logs + "logs.title": "Журнал запросов", +diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts +index aee152cd3..71d9e7313 100644 +--- a/gui/src/i18n/tr.ts ++++ b/gui/src/i18n/tr.ts +@@ -694,6 +694,12 @@ export const tr: Record = { + "sub.ultraModeLoadFail": "Ultra modu ayarları yüklenemedi — proxy çalışıyor mu?", + "sub.ultraModeSaveFail": "Ultra modu ayarları kaydedilemedi", + "sub.ultraModeSaved": "Ultra modu kaydedildi. Yeni Codex oturumlarına uygulanır.", ++ "sub.fallbackLabel": "Alt ajan yedek zinciri", ++ "sub.fallbackHint": "Alt ajan modeli kullanılamadığında veya başarısız olduğunda sırayla denenecek modeller.", ++ "sub.fallbackAdd": "Yedek model ekle…", ++ "sub.fallbackPoll": "Kullanılabilirlik kontrol aralığı", ++ "sub.fallbackSaved": "Alt ajan yedek ayarları kaydedildi.", ++ "sub.fallbackSaveFailed": "Yedek ayarlar kaydedilemedi", + + // logs + "logs.title": "İstek Günlükleri", +diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts +index 39c9e2f0b..50659c2e6 100644 +--- a/gui/src/i18n/zh-TW.ts ++++ b/gui/src/i18n/zh-TW.ts +@@ -541,6 +541,12 @@ export const zhTW: Record = { + "sub.ultraModeLoadFail": "無法載入超級模式設定 — 代理是否在執行?", + "sub.ultraModeSaveFail": "儲存超級模式設定失敗", + "sub.ultraModeSaved": "超級模式已儲存。適用於新的 Codex 會話。", ++ "sub.fallbackLabel": "子代理備援鏈", ++ "sub.fallbackHint": "子代理模型無法使用或失敗時,依序嘗試的模型。", ++ "sub.fallbackAdd": "新增備援模型…", ++ "sub.fallbackPoll": "可用性檢查間隔", ++ "sub.fallbackSaved": "子代理備援設定已儲存。", ++ "sub.fallbackSaveFailed": "備援設定儲存失敗", + "logs.title": "請求日誌", + "logs.tabLogs": "日誌", + "logs.tabDebug": "除錯", +diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts +index 1ba4cabfa..ded94d699 100644 +--- a/gui/src/i18n/zh.ts ++++ b/gui/src/i18n/zh.ts +@@ -682,6 +682,12 @@ export const zh: Record = { + "sub.ultraModeLoadFail": "无法加载超级模式设置 — 代理是否在运行?", + "sub.ultraModeSaveFail": "保存超级模式设置失败", + "sub.ultraModeSaved": "超级模式已保存。适用于新的 Codex 会话。", ++ "sub.fallbackLabel": "子代理回退链", ++ "sub.fallbackHint": "子代理模型不可用或失败时按顺序尝试的模型。", ++ "sub.fallbackAdd": "添加回退模型…", ++ "sub.fallbackPoll": "可用性检查间隔", ++ "sub.fallbackSaved": "子代理回退设置已保存。", ++ "sub.fallbackSaveFailed": "保存回退设置失败", + + // logs + "logs.title": "请求日志", +diff --git a/gui/src/pages/Subagents.tsx b/gui/src/pages/Subagents.tsx +index 6b54d39ff..299c9306f 100644 +--- a/gui/src/pages/Subagents.tsx ++++ b/gui/src/pages/Subagents.tsx +@@ -8,7 +8,7 @@ import { useDataSurface } from "../data-surface"; + import { DataSurfaceSkeleton } from "../components/data-surface"; + import { useSubagentDelegation, type UltraModePatch, type UltraModeState } from "./use-subagent-delegation"; + +-type CachedSubagents = { available: string[]; chosen: string[] }; ++type CachedSubagents = { available: string[]; chosen: string[]; fallback: string[]; pollMs: number }; + + function seedSubagents(cacheKey: string): CachedSubagents | null { + return readSessionListCache(cacheKey); +@@ -19,6 +19,9 @@ export default function Subagents({ apiBase }: { apiBase: string }) { + const cacheKey = `ocx.subagents.v1:${apiBase}`; + const cached = seedSubagents(cacheKey); + const [chosen, setChosen] = useState(() => cached?.chosen ?? []); ++ const [fallback, setFallback] = useState(() => cached?.fallback ?? []); ++ const [fallbackPollMs, setFallbackPollMs] = useState(() => cached?.pollMs ?? 60000); ++ const [fallbackBusy, setFallbackBusy] = useState(false); + const [status, setStatus] = useState(""); + const [ok, setOk] = useState(false); + const [busy, setBusy] = useState(false); +@@ -117,16 +120,24 @@ export default function Subagents({ apiBase }: { apiBase: string }) { + const loadSubagents = useCallback(async (signal?: AbortSignal): Promise => { + // The resource layer's deadline abort must reach the wire — a signal dropped + // here is a store that can only settle by race timeout. +- const res = await fetch(`${apiBase}/api/subagent-models`, { signal }); +- const response = await readJsonOrThrow<{ available?: string[]; chosen?: string[] }>(res, t("sub.loadFail")); +- if (!response) throw new Error(t("sub.loadFail")); +- const available = response.available ?? []; ++ const [rosterRes, fallbackRes] = await Promise.all([ ++ fetch(`${apiBase}/api/subagent-models`, { signal }), ++ fetch(`${apiBase}/api/subagent-model-fallback`, { signal }), ++ ]); ++ const response = await readJsonOrThrow<{ available?: string[]; chosen?: string[] }>(rosterRes, t("sub.loadFail")); ++ const fallbackResponse = await readJsonOrThrow<{ available?: string[]; models?: string[]; pollMs?: number }>(fallbackRes, t("sub.loadFail")); ++ if (!response || !fallbackResponse) throw new Error(t("sub.loadFail")); ++ const available = response.available ?? fallbackResponse.available ?? []; + const availableSet = new Set(available); + const next = { + available, + chosen: (response.chosen ?? []).filter(model => availableSet.has(model)), ++ fallback: (fallbackResponse.models ?? []).filter(model => availableSet.has(model)), ++ pollMs: fallbackResponse.pollMs ?? 60000, + }; + setChosen(next.chosen); ++ setFallback(next.fallback); ++ setFallbackPollMs(next.pollMs); + writeSessionListCache(cacheKey, next); + return next; + }, [apiBase, cacheKey, t]); +@@ -174,7 +185,7 @@ export default function Subagents({ apiBase }: { apiBase: string }) { + const d = await readJsonOrThrow<{ applied?: string[] }>(r, t("sub.saveFailed")); + const applied = d?.applied ?? chosen; + if (d?.applied) setChosen(d.applied); +- writeSessionListCache(cacheKey, { available, chosen: applied }); ++ writeSessionListCache(cacheKey, { available, chosen: applied, fallback, pollMs: fallbackPollMs }); + setOk(true); + setStatus(t("sub.saved", { n: applied.length, cmd: "ocx sync" })); + } catch (error) { +@@ -186,6 +197,28 @@ export default function Subagents({ apiBase }: { apiBase: string }) { + } + }; + ++ const saveFallback = async () => { ++ if (fallbackBusy) return; ++ setFallbackBusy(true); ++ try { ++ const r = await fetch(`${apiBase}/api/subagent-model-fallback`, { ++ method: "PUT", ++ headers: { "Content-Type": "application/json" }, ++ body: JSON.stringify({ models: fallback, pollMs: fallbackPollMs }), ++ }); ++ const d = await readJsonOrThrow<{ models?: string[]; pollMs?: number }>(r, t("sub.fallbackSaveFailed")); ++ if (d?.models) setFallback(d.models); ++ if (d?.pollMs) setFallbackPollMs(d.pollMs); ++ setOk(true); ++ setStatus(t("sub.fallbackSaved")); ++ } catch (error) { ++ setOk(false); ++ setStatus(error instanceof Error && error.message ? error.message : t("sub.networkError")); ++ } finally { ++ setFallbackBusy(false); ++ } ++ }; ++ + // The skeleton owns the live region while this resource has no content yet. + if (state.showSkeleton && !snapshot) { + return ; +@@ -214,7 +247,13 @@ export default function Subagents({ apiBase }: { apiBase: string }) { + busy={busy} + onToggle={toggle} + onMove={move} +- onSave={() => { void save(); }} ++ onSave={() => { void save(); }} ++ fallback={fallback} ++ fallbackPollMs={fallbackPollMs} ++ fallbackBusy={fallbackBusy} ++ onFallbackChange={setFallback} ++ onFallbackPollMsChange={setFallbackPollMs} ++ onFallbackSave={() => { void saveFallback(); }} + delegation={{ + model: delegation.model, + effort: delegation.effort, + +``` + +Audit amendment: cache server-confirmed fallback values after fallback Save; roster Save preserves committed fallback snapshot, never draft. Add independent-save and remount regressions. Existing dashboard density, CSS tokens, Select and icon library retained; no concept art needed for utility editor. From eb5ff6c582d694db96e94e5d0a58ed5dbc6843f3 Mon Sep 17 00:00:00 2001 From: Robin Bially <7304732+RobinBially@users.noreply.github.com> Date: Mon, 7 Sep 2026 09:57:05 +0200 Subject: [PATCH 040/116] feat(gui): add opt-in Codex Desktop sign-in toggle [skip ci] (cherry picked from commit 0f21769f346e64c2c6b2a03ff8d09b3deaab9562) Co-authored-by: RobinBially <7304732+RobinBially@users.noreply.github.com> --- .../content/docs/guides/codex-integration.md | 9 ++ docs/pr-assets/codex-desktop-opt-in.jpg | Bin 0 -> 29051 bytes gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/src/pages/dashboard-overview-sections.tsx | 28 ++++++- gui/src/pages/dashboard-shared.ts | 2 + gui/src/pages/use-dashboard-data.ts | 23 +++-- gui/tests/vision-sidecar-dashboard.test.tsx | 79 +++++++++++++++++- tests/codex-integration/codex-inject.test.ts | 4 +- 16 files changed, 146 insertions(+), 17 deletions(-) create mode 100644 docs/pr-assets/codex-desktop-opt-in.jpg diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 7d66e72c3f..ff2df04fdd 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -215,6 +215,15 @@ HTTP/SSE. ### Authless Codex Desktop (opt-in) +In **Dashboard → Overview**, **Open Codex without signing in** controls this existing +opt-in preference. The switch defaults to **off** when the setting is absent or false; +an existing explicit `codexDesktopAuthless: true` stays enabled. The dashboard saves +the preference and runs a full sync. Restart Codex Desktop after changing it. +If synchronization fails, the saved preference remains and the dashboard shows the error; +retry **Sync** before restarting. Account-gated Desktop features may be unavailable +when enabled. Upstream credentials, local eligibility, remote admission authentication +and user-owned gateway settings retain their existing requirements. + Codex Desktop shows its ChatGPT login screen whenever the active provider requires OpenAI auth. If your OpenCodex setup never uses ChatGPT credentials (routed providers only, or a blocked `chatgpt.com`), you can opt out of that gate: diff --git a/docs/pr-assets/codex-desktop-opt-in.jpg b/docs/pr-assets/codex-desktop-opt-in.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d06203e7113cc54e87b1272e272d8f943c5b4805 GIT binary patch literal 29051 zcmce;30#ut`ZrGdl$p~^+N7Ch(pI;V3r=a;a@5Rmv;|afIc07TFs8UGO*6J==AmXRs%n4K3TJ7_3AYn)~#Fn$;J&E zHyUg(FfiQo*{6n^Hg7U8_|)Xn&7W^EHa6a9wDk*X zViEBP*u>-@qvpr0Puki$ zo_0R#>mT3?244&bhhLAp86A83ZhT^TMmak-uUb$qE{|&kXw|R70)GEGu>Wpcn}Kny zT)leL>UGQGTCp+-xK?dmz2?gUYd<@BYTdcG&v!a}_sN!Hx9`>ed%dOO=_%v$mwGpt zSUC;vnqD5-hmrly4eZMQ(#U=v*dOB(f;O&N0W99C%^(lZLRfaBanF&(eLn?QZxF}s zEkmq)-0OG$@XpQbGvhy9-g`gWV8h<~mp@)RimUFqo;te1b4$ST z6?DpT%jUmT_V1eoD%%1&P1&`-XJ!BRPm7?v-wXs4S6O9jIdx~?*ar&~^Wg0?J1x?i?=w*;E`g0Td`R%5m;fgaG7Kq=Mc7W(5ROCUMTZ^UB`%uzV6 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YFl&QoN|m5BnA5Y z_ikY*4n?Gkp;>!3T-@BE`+ zXXg7XxG4^prvmnWzcHS9F%i zKVUsm)=+2U;n^H)zcktoLaf8PBhNQ4lIlzmO6X#pu^h$&Vn#sc{Acm8f?f%UW%ua1 zlt9is_rCP_sOL{q5bfo&Sb4s!1@tGhA7A2ZW_p;f4J(J=7uE|8BHT)|^Wric5CGgW z0L<^%K@7QUU?*_1xCU`xlpq`xBu=a}a`~Q*2%f2O4i5z;x0G=CrElRSA#&kdsxBqY zw8_1HcoP*|)@PUqcwIkor$$RT_=P|oej?6H3Wl5z$p zVpkH%d5SEQ>(=-SlCRHAg}oQLWWJ$5hMt2Et7f5RkDeWpZ1u+NX~*eS)&|^*t$TRmZ+2zv+b9w3=lfOn0{G%*$oz9=AlRZ&aZ?!XeuhJIXa=ylIsoVfv zBn4GwXu#d@rMOG9)bJhHcq0q1=1h2Wh&z!#)^sM@%v`{s2G=PKY-9y}?*6e+_ui%< zMXc9D>``?FPLoZyq@7BNGyELOsOl%|npZAB6O8{(UxMIShEv zU-OP&)JVeevn{_mPUt}TVGpDqLqPhG^c!UoZTX+Ce4cpVcz5zAx2%2tPLrHGmG_D} zXKKp<8>@f!?Ean4|My=u0dMh-nkiT%t1#5hHkK z`n$*f_uc;;jsO4V#^M_nXCY{Yhb?`@jL$(L4uG%u)n?*1^$4r3mAe7|HJwiohIa%k zKKsQg76vTr1k87qEHLp20VX?t(R*vlWfluz1@g`Hch4)OKy-Q2i|{Ys83A11c+G!( zPw+qeW7F411poYGJ-8gk*a<3Erdm&e_aO0wBkGiec15t ofBo-Z*>-{`cn)f)U_nmCbf~TDpW!JW8xQ{f(wqLJ`j?6S17XEC8UO$Q literal 0 HcmV?d00001 diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 5faab4b356..495104bd42 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -299,6 +299,8 @@ export const de: Record = { "models.staleBanner": "Codex zeigt eine ältere Modellliste als dieser Katalog. Starte Codex neu, um sie neu zu laden.", "dash.codexAutoStart": "opencodex mit Codex starten", "dash.codexAutoStartHint": "Erlaubt einem installierten Launcher-Shim, ocx ensure auszuführen. Diese Einstellung installiert keinen Neustartschutz; prüfe den effektiven Zustand unter Startsicherheit.", + "dash.codexDesktopAuthless": "Codex ohne Anmeldung öffnen", + "dash.codexDesktopAuthlessHint": "Standardmäßig aus. Überspringt die separate Desktop-Anmeldung bei geeigneten lokalen Verbindungen. Zugangsdaten für den Anbieter bleiben erforderlich. Codex nach einer Änderung neu starten. Kontogebundene Desktop-Funktionen können fehlen.", "dash.searchModel": "Such-Sidecar-Modell", "dash.searchModelHint": "Modell für web_search bei nicht über OpenAI gerouteten Modellen. Erfordert ChatGPT-Login.", "dash.searchReasoning": "Such-Reasoning-Aufwand", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index c71208942f..22a3807858 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -311,6 +311,8 @@ export const en = { "models.staleBanner": "Codex is showing an older model list than this catalog. Restart Codex to reload it.", "dash.codexAutoStart": "Start opencodex with Codex", "dash.codexAutoStartHint": "Allows an installed launcher shim to run ocx ensure. This setting does not install restart protection; check Startup safety for the effective state.", + "dash.codexDesktopAuthless": "Open Codex without signing in", + "dash.codexDesktopAuthlessHint": "Off by default. Skip the separate Desktop sign-in for eligible local connections. Upstream credentials are still required. Restart Codex after changing this setting. Account-gated Desktop features may be unavailable.", "dash.searchModel": "Search sidecar model", "dash.searchModelHint": "Model used for web_search on non-OpenAI routed models. Requires ChatGPT login.", "dash.searchReasoning": "Search reasoning effort", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index e1b3519ef1..9f0f265173 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -301,6 +301,8 @@ export const fr: Record = { "models.staleBanner": "Codex affiche une liste de modèles plus ancienne que ce catalogue. Redémarrez Codex pour la recharger.", "dash.codexAutoStart": "Démarrer opencodex avec Codex", "dash.codexAutoStartHint": "Permet à un mécanisme de lancement installé d’exécuter ocx ensure. Ce réglage n’installe pas de protection au redémarrage ; consultez Sécurité du démarrage pour connaître l’état effectif.", + "dash.codexDesktopAuthless": "Ouvrir Codex sans se connecter", + "dash.codexDesktopAuthlessHint": "Désactivé par défaut. Ignore la connexion Desktop séparée pour les connexions locales admissibles. Les identifiants du fournisseur restent nécessaires. Redémarrez Codex après toute modification. Certaines fonctions Desktop liées au compte peuvent être indisponibles.", "dash.searchModel": "Modèle auxiliaire de recherche", "dash.searchModelHint": "Modèle utilisé pour web_search sur les modèles routés autres qu’OpenAI. Nécessite une connexion à ChatGPT.", "dash.searchReasoning": "Effort de raisonnement pour la recherche", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index cf94831583..55a6fe2495 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -308,6 +308,8 @@ export const ja: Record = { "models.staleBanner": "Codex はこのカタログより古いモデル一覧を表示しています。Codex を再起動すると読み直されます。", "dash.codexAutoStart": "Codex と一緒に opencodex を起動", "dash.codexAutoStartHint": "インストール済み launcher shim に ocx ensure の実行を許可します。この設定だけでは再起動保護はインストールされません。起動安全性で実際の状態を確認してください。", + "dash.codexDesktopAuthless": "ログインせずに Codex を開く", + "dash.codexDesktopAuthlessHint": "既定ではオフです。対象のローカル接続で Desktop の個別ログインを省略します。上流プロバイダーの認証情報は引き続き必要です。変更後は Codex を再起動してください。アカウントに依存する Desktop 機能が利用できない場合があります。", "dash.searchModel": "検索サイドカーモデル", "dash.searchModelHint": "非 OpenAI ルーティングモデルで web_search に使うモデル。ChatGPT ログインが必要です。", "dash.searchReasoning": "検索の推論負荷", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index c1959482b7..19285b150e 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -303,6 +303,8 @@ export const ko: Record = { "models.staleBanner": "Codex가 이 카탈로그보다 오래된 모델 목록을 보여주고 있습니다. Codex를 재시작하면 새로 읽습니다.", "dash.codexAutoStart": "Codex 실행 시 opencodex 시작", "dash.codexAutoStartHint": "설치된 launcher shim이 ocx ensure를 실행하도록 허용합니다. 이 설정은 재부팅 보호를 설치하지 않으므로 시작 안전성에서 실제 상태를 확인하세요.", + "dash.codexDesktopAuthless": "로그인 없이 Codex 열기", + "dash.codexDesktopAuthlessHint": "기본값은 꺼짐입니다. 지원되는 로컬 연결에서 별도의 Desktop 로그인을 건너뜁니다. 업스트림 인증 정보는 여전히 필요합니다. 변경 후 Codex를 다시 시작하세요. 계정에 연결된 Desktop 기능을 사용하지 못할 수 있습니다.", "dash.searchModel": "서치 사이드카 모델", "dash.searchModelHint": "비-OpenAI 라우팅 모델의 web_search에 사용되는 모델입니다. ChatGPT 로그인 필요.", "dash.searchReasoning": "서치 추론 강도", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 0109f5ebdc..87704912ac 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -308,6 +308,8 @@ export const ru: Record = { "models.staleBanner": "Codex показывает список моделей старее этого каталога. Перезапустите Codex, чтобы перечитать его.", "dash.codexAutoStart": "Запускать opencodex вместе с Codex", "dash.codexAutoStartHint": "Разрешает установленному launcher shim выполнять ocx ensure. Эта настройка не устанавливает защиту перезапуска; проверьте фактическое состояние в разделе безопасности запуска.", + "dash.codexDesktopAuthless": "Открывать Codex без входа", + "dash.codexDesktopAuthlessHint": "По умолчанию выключено. Пропускает отдельный вход в Desktop для допустимых локальных подключений. Учётные данные провайдера по-прежнему нужны. После изменения перезапустите Codex. Функции Desktop, связанные с аккаунтом, могут быть недоступны.", "dash.searchModel": "Модель сайдкара поиска", "dash.searchModelHint": "Модель, используемая для web_search на маршрутизируемых моделях, отличных от OpenAI. Требуется вход в аккаунт ChatGPT.", "dash.searchReasoning": "Уровень рассуждений для поиска", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index fa8b8e9c25..807eeae32b 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -309,6 +309,8 @@ export const tr: Record = { "models.staleBanner": "Codex, bu katalogdan daha eski bir model listesi gösteriyor. Yeniden okumak için Codex'i yeniden başlatın.", "dash.codexAutoStart": "opencodex'i Codex ile başlat", "dash.codexAutoStartHint": "Yüklü bir shim'in ocx ensure çalıştırmasına izin verir. Arka plan servisi veya yeniden başlatma koruması kurmaz; sistem durumu için Başlatma Güvenliği'ne bakın.", + "dash.codexDesktopAuthless": "Codex’i oturum açmadan başlat", + "dash.codexDesktopAuthlessHint": "Varsayılan olarak kapalıdır. Uygun yerel bağlantılarda ayrı Desktop oturum açma adımını atlar. Sağlayıcı kimlik bilgileri yine gereklidir. Değişiklikten sonra Codex’i yeniden başlatın. Hesaba bağlı Desktop özellikleri kullanılamayabilir.", "dash.searchModel": "Arama yan araç modeli", "dash.searchModelHint": "OpenAI dışı yönlendirilen modellerde web_search için kullanılan model. ChatGPT girişi gerektirir.", "dash.searchReasoning": "Arama akıl yürütme çabası", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 3bc246543a..62e1f07110 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -200,6 +200,8 @@ export const zhTW: Record = { "models.staleBanner": "Codex 顯示的模型清單比目前的目錄舊。重新啟動 Codex 即可重新讀取。", "dash.codexAutoStart": "隨 Codex 啟動 opencodex", "dash.codexAutoStartHint": "允許已安裝的 launcher shim 執行 ocx ensure。此設定不會安裝重新啟動保護;請在啟動安全中檢查實際狀態。", + "dash.codexDesktopAuthless": "無需登入即可開啟 Codex", + "dash.codexDesktopAuthlessHint": "預設關閉。為符合條件的本機連線略過獨立的 Desktop 登入。仍需上游供應商憑證。變更後請重新啟動 Codex。依賴帳戶的 Desktop 功能可能無法使用。", "dash.searchModel": "搜尋附屬模型", "dash.searchModelHint": "用於非 OpenAI 路由模型的 web_search 的模型。需要 ChatGPT 登入。", "dash.searchReasoning": "搜尋推理強度", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index b10c48688d..9946914426 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -303,6 +303,8 @@ export const zh: Record = { "models.staleBanner": "Codex 显示的模型列表比当前目录旧。重启 Codex 即可重新读取。", "dash.codexAutoStart": "随 Codex 启动 opencodex", "dash.codexAutoStartHint": "允许已安装的 launcher shim 运行 ocx ensure。此设置不会安装重启保护;请在启动安全中检查实际状态。", + "dash.codexDesktopAuthless": "无需登录即可打开 Codex", + "dash.codexDesktopAuthlessHint": "默认关闭。为符合条件的本地连接跳过单独的 Desktop 登录。仍需上游提供商凭据。更改后请重启 Codex。依赖账户的 Desktop 功能可能不可用。", "dash.searchModel": "搜索附属模型", "dash.searchModelHint": "用于非 OpenAI 路由模型的 web_search 的模型。需要 ChatGPT 登录。", "dash.searchReasoning": "搜索推理强度", diff --git a/gui/src/pages/dashboard-overview-sections.tsx b/gui/src/pages/dashboard-overview-sections.tsx index 8da531f97c..6606c4f560 100644 --- a/gui/src/pages/dashboard-overview-sections.tsx +++ b/gui/src/pages/dashboard-overview-sections.tsx @@ -163,7 +163,7 @@ export function DashboardInjectionPanel({ d }: { apiBase: string; d: Dash }) { export function DashboardMaintenancePanel({ d }: { d: Dash }) { const { - t, runSync, syncing, updateTriggerRef, openUpdateDialog, updateLoading, updateOpen, + t, runSync, syncing, settingsSaving, updateTriggerRef, openUpdateDialog, updateLoading, updateOpen, syncResult, syncError, updateJob, reconnecting, clearSyncFeedback, } = d; const syncHoldsWarning = !!syncResult && ( @@ -211,7 +211,7 @@ export function DashboardMaintenancePanel({ d }: { d: Dash }) {
{t("dash.syncModelsHint")}
-
+
+
+
+
{t("dash.codexDesktopAuthless")}
+
{t("dash.codexDesktopAuthlessHint")}
+ {settings?.catalogRefreshPending &&
{t("codexAuth.catalogRefreshPending")}
} +
+ +
+
+
{/* Both sidecar cards wear the DashboardInjectionPanel shell: the PANEL is the flex row, copy left, controls right. */} diff --git a/gui/src/pages/dashboard-shared.ts b/gui/src/pages/dashboard-shared.ts index 0793a7def2..d240510286 100644 --- a/gui/src/pages/dashboard-shared.ts +++ b/gui/src/pages/dashboard-shared.ts @@ -48,6 +48,8 @@ export interface ProviderInfo { name: string; adapter: string; baseUrl: string; export interface ModelInfo { id: string; provider: string; namespaced: string; owned_by?: string; reasoningEfforts?: string[] } export interface SettingsData { codexAutoStart: boolean; + codexDesktopAuthless?: boolean; + catalogRefreshPending?: boolean; /** Whether a login may open a browser on the machine running the proxy. */ oauthOpenBrowser?: boolean; port: number; diff --git a/gui/src/pages/use-dashboard-data.ts b/gui/src/pages/use-dashboard-data.ts index 6f84950ce1..6da776ea18 100644 --- a/gui/src/pages/use-dashboard-data.ts +++ b/gui/src/pages/use-dashboard-data.ts @@ -607,23 +607,24 @@ export function useDashboardData(apiBase: string) { finally { setInjectionSaving(false); } }; - const toggleCodexAutoStart = async () => { - if (!settings || settingsSaving) return; - const next = !settings.codexAutoStart; + const toggleCodexSetting = async (key: "codexAutoStart" | "codexDesktopAuthless") => { + if (!settings || settingsSaving || syncing) return; + const next = !(settings[key] ?? (key === "codexAutoStart")); setSettingsSaving(true); settingsMutationInFlightRef.current = true; - setSettings({ ...settings, codexAutoStart: next }); + setSettings({ ...settings, [key]: next }); try { const res = await fetch(`${apiBase}/api/settings`, { method: "PUT", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ codexAutoStart: next }), + body: JSON.stringify({ [key]: next }), }); - const data = await requireJson<{ codexAutoStart: boolean; startupHealth?: SettingsData["startupHealth"] }>(res, "save failed"); + const data = await requireJson(res, "save failed"); settingsMutationEpochRef.current += 1; - setSettings(prev => prev ? { ...prev, codexAutoStart: data.codexAutoStart, startupHealth: data.startupHealth ?? prev.startupHealth } : prev); + setSettings(prev => prev ? { ...prev, [key]: data[key], catalogRefreshPending: key === "codexDesktopAuthless" ? data.catalogRefreshPending : prev.catalogRefreshPending, startupHealth: data.startupHealth ?? prev.startupHealth } : prev); + if (key === "codexDesktopAuthless") await runSync(); } catch { - setSettings(prev => prev ? { ...prev, codexAutoStart: !next } : prev); + setSettings(prev => prev ? { ...prev, [key]: !next } : prev); setError(true); } finally { settingsMutationInFlightRef.current = false; @@ -631,6 +632,9 @@ export function useDashboardData(apiBase: string) { } }; + const toggleCodexAutoStart = () => toggleCodexSetting("codexAutoStart"); + const toggleCodexDesktopAuthless = () => toggleCodexSetting("codexDesktopAuthless"); + // Clears the sync result/error in this hook. The dashboard toast owns its own dismissal // timer but must publish the dismissal here: syncResult/syncError live above the dashboard // tabs, so a component-local flag alone would let a stale result remount as a fresh toast @@ -649,6 +653,7 @@ export function useDashboardData(apiBase: string) { const res = await fetch(`${apiBase}/api/sync`, { method: "POST" }); const data = await requireJson(res, "sync failed"); setSyncResult(data); + setSettings(prev => prev ? { ...prev, catalogRefreshPending: false } : prev); if (data.projectConfigGrouped) setProjectConfigWarnings(data.projectConfigGrouped); } catch (err) { setSyncError(err instanceof Error ? err.message : String(err)); @@ -789,7 +794,7 @@ export function useDashboardData(apiBase: string) { effortCapHelpTriggerRef, updateTriggerRef, maHelpTriggerRef, shadowCallHelpTriggerRef, effortCapHelpDialogRef, updateDialogRef, maHelpDialogRef, shadowCallHelpDialogRef, filteredGroups, sidecarModels, visionModels, - saveSidecar, saveShadowCall, switchMaMode, toggleCodexAutoStart, runSync, clearSyncFeedback, + saveSidecar, saveShadowCall, switchMaMode, toggleCodexAutoStart, toggleCodexDesktopAuthless, runSync, clearSyncFeedback, fetchUpdateCheck, closeUpdateDialog, openUpdateDialog, changeUpdateChannel, runUpdate, }; } diff --git a/gui/tests/vision-sidecar-dashboard.test.tsx b/gui/tests/vision-sidecar-dashboard.test.tsx index dc762de58f..994a409126 100644 --- a/gui/tests/vision-sidecar-dashboard.test.tsx +++ b/gui/tests/vision-sidecar-dashboard.test.tsx @@ -12,7 +12,7 @@ import { LanguageProvider } from "../src/i18n/provider"; import { DashboardSidecarPanels } from "../src/pages/dashboard-overview-sections"; import type { SidecarData, SidecarPatch } from "../src/pages/dashboard-shared"; import { mergeSidecarSetting } from "../src/pages/dashboard-shared"; -import type { useDashboardData } from "../src/pages/use-dashboard-data"; +import { useDashboardData } from "../src/pages/use-dashboard-data"; const globals = ["document", "window", "navigator", "IS_REACT_ACT_ENVIRONMENT"] as const; let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; @@ -382,4 +382,79 @@ test("model and reasoning saves still omit enabled, limit, and timeout", async ( expect(patches).toHaveLength(2); expect(patches[1]).toEqual({ vision: { reasoning: "high" } }); assertVisionControlFieldsOmitted(patches[1]!); -}); \ No newline at end of file +}); + +test("Desktop login switch defaults off, preserves explicit opt-in, and disables while saving", async () => { + const { d } = harness(); + let clicks = 0; + d.toggleCodexDesktopAuthless = async () => { clicks += 1; }; + d.settings = { codexAutoStart: true, port: 10100, hostname: "127.0.0.1" }; + await mount(d); + const toggle = () => host.querySelector(`button[aria-label="${en["dash.codexDesktopAuthless"]}"]`)!; + expect(toggle().getAttribute("aria-pressed")).toBe("false"); + d.settings.codexDesktopAuthless = true; + await mount(d); + expect(toggle().getAttribute("aria-pressed")).toBe("true"); + await act(async () => { toggle().click(); }); + expect(clicks).toBe(1); + d.settings.codexDesktopAuthless = false; + d.settings.catalogRefreshPending = true; + d.settingsSaving = true; + await mount(d); + expect(toggle().getAttribute("aria-pressed")).toBe("false"); + expect(toggle().disabled).toBe(true); + expect(host.textContent).toContain(en["codexAuth.catalogRefreshPending"]); +}); + + +test.each([undefined, false, true])("Desktop login preference %s persists before full sync; sync failure keeps the saved preference", async (initial) => { + const originalFetch = globalThis.fetch; + const writes: Array<{ path: string; body: unknown }> = []; + let latest: Dash | undefined; + let saved = initial; + const apiBase = `/authless-test-${String(initial)}`; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const path = String(input); + if (init?.method === "PUT") { + const body = JSON.parse(String(init.body)); + writes.push({ path, body }); + if (body.codexDesktopAuthless !== undefined) { + saved = body.codexDesktopAuthless; + return Response.json({ codexDesktopAuthless: saved, catalogRefreshPending: true }); + } + return Response.json({ codexAutoStart: body.codexAutoStart, catalogRefreshPending: false }); + } + if (path.endsWith("/api/sync")) { + writes.push({ path, body: null }); + return Response.json({ error: "sync unavailable" }, { status: 503 }); + } + if (path.endsWith("/api/settings")) { + return Response.json({ codexAutoStart: true, codexDesktopAuthless: saved, port: 10100, hostname: "127.0.0.1" }); + } + return Response.json({}, { status: 503 }); + }) as typeof fetch; + function Harness() { latest = useDashboardData(apiBase); return null; } + try { + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(host); + root.render(); + }); + expect(latest?.settings?.codexDesktopAuthless).toBe(initial); + await act(async () => { await latest!.toggleCodexDesktopAuthless(); }); + expect(writes).toEqual([ + { path: `${apiBase}/api/settings`, body: { codexDesktopAuthless: !initial } }, + { path: `${apiBase}/api/sync`, body: null }, + ]); + expect(latest?.settings?.codexDesktopAuthless).toBe(!initial); + expect(latest?.syncError).toBe("sync unavailable"); + expect(latest?.settings?.catalogRefreshPending).toBe(true); + await act(async () => { await latest!.toggleCodexAutoStart(); }); + expect(latest?.settings?.codexAutoStart).toBe(false); + expect(latest?.settings?.catalogRefreshPending).toBe(true); + } finally { + await act(async () => { root?.unmount(); }); + root = null; + globalThis.fetch = originalFetch; + } +}); diff --git a/tests/codex-integration/codex-inject.test.ts b/tests/codex-integration/codex-inject.test.ts index 84ac5f67b6..b6be3c2f69 100644 --- a/tests/codex-integration/codex-inject.test.ts +++ b/tests/codex-integration/codex-inject.test.ts @@ -31,8 +31,8 @@ describe("Codex config injection", () => { }); describe("authless Codex Desktop opt-in (#1107)", () => { - test("default target on loopback stays Design B and byte-identical", () => { - const target = standaloneCodexRoutingTarget(10100, {}); + test.each([undefined, false])("disabled preference %s on loopback stays Design B and byte-identical", (codexDesktopAuthless) => { + const target = standaloneCodexRoutingTarget(10100, { codexDesktopAuthless }); expect(target.desktopAuthless).toBeUndefined(); expect(buildProfileFile(target, null)).toBe(buildProfileFile(10100, null)); expect(buildProviderTableBlock(target)).toContain("requires_openai_auth = true"); From 2b14053ff625e1750583269829bbbecf0a100b6c Mon Sep 17 00:00:00 2001 From: x3M3x Date: Wed, 2 Sep 2026 09:49:07 +0400 Subject: [PATCH 041/116] docs: add subagent fallback settings screenshot [skip ci] (cherry picked from commit aba57a074941b7cdae3074eca9a0256d0621eb22) Co-authored-by: x3M3x <98298256+x3M3x@users.noreply.github.com> --- .../subagent-fallback-settings.png | Bin 0 -> 215189 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 docs-site/public/pr-screenshots/subagent-fallback-settings.png diff --git a/docs-site/public/pr-screenshots/subagent-fallback-settings.png b/docs-site/public/pr-screenshots/subagent-fallback-settings.png new file mode 100644 index 0000000000000000000000000000000000000000..04f72f140cd0d904d63ff72f9da7e0a0300e1a5e GIT binary patch literal 215189 zcmXtTw}o+chfur}ic1Mj(ck)K z*V$+7HP?LR-cibm-!Re0&|qL-FlD4ARAFEc^Pt}s6gcQF`tcBa7#JKF83|E!udEXT z#0~Pk*}&v56ugf}sCdj_8>)g|^FLbG!XctbM%(2Vy~+ls@T*!ohY;B0H46}=;)IAZ z2Ge~-h{SDrTw7f^jccoIZ|}4Sco{k!Z}Yyk^w3;$Tp#sFAgS z*Oss)x0HV^muq@!^dBd!INU9upg&c24I@e2{mRHR)soJj+FY!PH}ZpQ$-K6bc@}fF zE^Erj_G6N^3~c`_UDe}?Y1I_(~|H2>`diTXzQRLF-za{!Og*kP=B^q zy_;lTqM$M{GwLUEx!wV;#!_J{@>O08i=_}^^XtuI!iT0^+ow8~J;BRngD40q7HnQ? zk4}WRxUkbi0OGC2_sOa5-Ix%U%2R>xc{!~v!DsKrp`KAg2|P2NF$VE{j&BCc&k?Rq zm1eu|_ASaS>eD5bWdv%U&2?InvOaS5*cb9e3rR5j8aHpa%<4FD8RTX!r~dAfuc?rl z*&k#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rh)^Be+NG*#wa(WeMKtnT=n zdFXK|ZolSL<{$b$Je2o&5=i!-Tf$UE@dX2sDv}Y5?@R2CR?MRICz6dtujk?pY^^sc z?p*#BVD+wbnbmpwQI45zqRdv?8P~?C0j4(M4s{h_+Bf?1vN2;3+_4=2clJHJTQf*HoDX#KdCFyPCF**9}vfS4rTyP%q@9*m! zqs((%*m+VXGLqULPsCi#2DW;D&gXJ)BnFLU&*mBoyRXPxCDEg2|EJbzugAlJ`YI8f zB%2w!+^@e;+B5Y&A<5wPIVC_-OkVT#CHqKTd}6YS5;Z8i|BHRo#>+F Date: Mon, 7 Sep 2026 10:34:15 +0900 Subject: [PATCH 042/116] fix(web-search): bound the Anthropic sidecar SSE and error bodies [skip ci] `parseAnthropicSidecarSSE` folded frames only when it found a `\n\n` separator, and appended every decoded chunk to `buffer` until then. An upstream that streams without ever emitting a separator therefore grew the buffer for the whole response. The non-OK branch had the same shape: it read the untrusted error body with an unbounded `res.text()` just to build one auth-failure message. Reuse the existing `MAX_SIDECAR_RESPONSE_BYTES` cap and the reader-cancel helper that `parseSidecarSSE` already applies in the same folder, so both paths stop reading at the same 64 KiB bound. Frames folded before the cap are kept; only the unterminated tail is dropped. `cancelReaderWithoutWaiting` is exported for this, unchanged. The regression drives a stream that never terminates a frame and asserts the read is cancelled well before the producer finishes. It fails without the cap and passes with it. (cherry picked from commit c25bdab6dd955bc2ccfb9f952403009ac560b13e) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/web-search/anthropic-executor.ts | 52 +++++++++++++++++-- src/web-search/parse.ts | 2 +- tests/web-search/web-search-anthropic.test.ts | 21 ++++++++ 3 files changed, 71 insertions(+), 4 deletions(-) diff --git a/src/web-search/anthropic-executor.ts b/src/web-search/anthropic-executor.ts index 1eb206afa8..cd3893900c 100644 --- a/src/web-search/anthropic-executor.ts +++ b/src/web-search/anthropic-executor.ts @@ -5,7 +5,11 @@ import { CLAUDE_CODE_HEADERS, claudeCodeSessionId } from "../adapters/client-fin import { signalWithTimeout, cancelBodyOnAbort } from "../lib/abort"; import { sidecarEnter } from "../lib/sidecar-tracker"; import { applyUpstreamRecoveryInit, fetchWithResetRetry } from "../lib/upstream-retry"; -import type { WebSearchSource } from "./parse"; +import { + MAX_SIDECAR_RESPONSE_BYTES, + cancelReaderWithoutWaiting, + type WebSearchSource, +} from "./parse"; import { BASE_INSTRUCTION, IMAGE_INSTRUCTION, type SidecarOutcome, type SidecarSettings } from "./executor"; /** Hardcoded per-turn search bound handed to the server tool (mirrors the loop's maxSearches intent). */ @@ -17,6 +21,33 @@ function isRec(v: unknown): v is Record { return !!v && typeof v === "object" && !Array.isArray(v); } +/** Read at most `MAX_SIDECAR_RESPONSE_BYTES` of an untrusted upstream body, then stop reading. */ +async function readBoundedText(res: Response): Promise { + if (!res.body) return ""; + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let out = ""; + let seen = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + const remaining = MAX_SIDECAR_RESPONSE_BYTES - seen; + const accepted = value.byteLength <= remaining ? value : value.subarray(0, remaining); + seen += accepted.byteLength; + out += decoder.decode(accepted, { stream: true }); + if (seen >= MAX_SIDECAR_RESPONSE_BYTES) { + cancelReaderWithoutWaiting(reader, "sidecar error body byte limit reached"); + break; + } + } + out += decoder.decode(); + } catch { + /* a failed error-body read must not mask the HTTP status we are about to report */ + } + return out; +} + /** * Fold an Anthropic Messages SSE stream (a web_search_20250305 turn) into a WebSearchResult. * @@ -41,6 +72,7 @@ export async function parseAnthropicSidecarSSE(res: Response): Promise): void => { const type = typeof data.type === "string" ? data.type : ""; @@ -82,15 +114,27 @@ export async function parseAnthropicSidecarSSE(res: Response): Promise= MAX_SIDECAR_RESPONSE_BYTES) { + // Keep the frames already folded above, drop the unterminated tail, and do not wait on + // upstream teardown. + cancelReaderWithoutWaiting(reader, "sidecar response byte limit reached"); + buffer = ""; + break; + } } // Flush the decoder and process any final unterminated frame (a stream that ends without \n\n). buffer = (buffer + decoder.decode()).replace(/\r\n/g, "\n"); @@ -177,7 +221,9 @@ export async function runAnthropicWebSearch( // (found investigating #1419). const detachBodyGuard = cancelBodyOnAbort(res.body, linkedSignal.signal); if (!res.ok) { - const t = await res.text().catch(() => ""); + // Untrusted upstream error bodies are only used for an auth-failure message, so read a + // bounded prefix instead of buffering an arbitrarily large response. + const t = await readBoundedText(res); detachBodyGuard(); console.warn(`[web-search] anthropic sidecar HTTP ${res.status} for query "${query.slice(0, 80)}" (${Date.now() - t0}ms)`); if (res.status === 401) { diff --git a/src/web-search/parse.ts b/src/web-search/parse.ts index 757c309f3e..7ba5d2607c 100644 --- a/src/web-search/parse.ts +++ b/src/web-search/parse.ts @@ -193,7 +193,7 @@ function fromOutputArray(output: OutputItem[], seen: Set): WebSearchResu return { text, sources }; } -function cancelReaderWithoutWaiting( +export function cancelReaderWithoutWaiting( reader: ReadableStreamDefaultReader, reason: string, ): void { diff --git a/tests/web-search/web-search-anthropic.test.ts b/tests/web-search/web-search-anthropic.test.ts index f5b7f1df26..33f2616cc2 100644 --- a/tests/web-search/web-search-anthropic.test.ts +++ b/tests/web-search/web-search-anthropic.test.ts @@ -130,6 +130,27 @@ describe("parseAnthropicSidecarSSE", () => { expect(out.error).toBeDefined(); }); + test("an unterminated frame cannot buffer the stream without bound", async () => { + // A sidecar that never emits a frame separator: without a cap the parser would accumulate + // the whole stream in memory before it could fold anything. + let produced = 0; + let cancelled = false; + const chunk = new TextEncoder().encode(`data: {"filler":"${"x".repeat(64 * 1024)}"}`); + const body = new ReadableStream({ + pull(c) { + if (produced > 8 * 1024 * 1024) { c.close(); return; } + produced += chunk.byteLength; + c.enqueue(chunk); + }, + cancel() { cancelled = true; }, + }); + const out = await parseAnthropicSidecarSSE(new Response(body, { status: 200 })); + expect(cancelled).toBe(true); + // The cap stops the read long before the producer would have finished on its own. + expect(produced).toBeLessThan(1024 * 1024); + expect(out.text).toBe(""); + }); + test("empty results (content:[]) with answer text is a success, not an error", async () => { const res = sseResponse([ { type: "content_block_start", index: 0, content_block: { type: "web_search_tool_result", tool_use_id: "srvtoolu_3", content: [] } }, From c1f96f0a5af6bf98e663d287eeffaabcdb0d0028 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:25:44 +0900 Subject: [PATCH 043/116] fix(gui): retain pending Desktop preference when sync is skipped [skip ci] Co-authored-by: RobinBially <7304732+RobinBially@users.noreply.github.com> --- gui/src/i18n/de.ts | 4 +-- gui/src/i18n/en.ts | 4 +-- gui/src/i18n/fr.ts | 4 +-- gui/src/i18n/ja.ts | 4 +-- gui/src/i18n/ko.ts | 4 +-- gui/src/i18n/ru.ts | 4 +-- gui/src/i18n/tr.ts | 4 +-- gui/src/i18n/zh-TW.ts | 4 +-- gui/src/i18n/zh.ts | 4 +-- gui/src/pages/dashboard-shared.ts | 1 + gui/src/pages/use-dashboard-data.ts | 4 ++- gui/tests/vision-sidecar-dashboard.test.tsx | 27 +++++++++++++++++++++ 12 files changed, 49 insertions(+), 19 deletions(-) diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 495104bd42..74533a04d3 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -299,8 +299,6 @@ export const de: Record = { "models.staleBanner": "Codex zeigt eine ältere Modellliste als dieser Katalog. Starte Codex neu, um sie neu zu laden.", "dash.codexAutoStart": "opencodex mit Codex starten", "dash.codexAutoStartHint": "Erlaubt einem installierten Launcher-Shim, ocx ensure auszuführen. Diese Einstellung installiert keinen Neustartschutz; prüfe den effektiven Zustand unter Startsicherheit.", - "dash.codexDesktopAuthless": "Codex ohne Anmeldung öffnen", - "dash.codexDesktopAuthlessHint": "Standardmäßig aus. Überspringt die separate Desktop-Anmeldung bei geeigneten lokalen Verbindungen. Zugangsdaten für den Anbieter bleiben erforderlich. Codex nach einer Änderung neu starten. Kontogebundene Desktop-Funktionen können fehlen.", "dash.searchModel": "Such-Sidecar-Modell", "dash.searchModelHint": "Modell für web_search bei nicht über OpenAI gerouteten Modellen. Erfordert ChatGPT-Login.", "dash.searchReasoning": "Such-Reasoning-Aufwand", @@ -2471,6 +2469,8 @@ export const de: Record = { "dash.visionTimeout": "Timeout", "dash.visionTimeoutInvalid": "Geben Sie eine ganze Zahl von {min} bis {max} Millisekunden ein.", "dash.visionAdvancedPopover": "Erweiterte Vision-Einstellungen", + "dash.codexDesktopAuthless": "Codex ohne Anmeldung öffnen", + "dash.codexDesktopAuthlessHint": "Standardmäßig aus. Überspringt die separate Desktop-Anmeldung bei geeigneten lokalen Verbindungen. Zugangsdaten für den Anbieter bleiben erforderlich. Codex nach einer Änderung neu starten. Kontogebundene Desktop-Funktionen können fehlen.", "models.newPolicyGlobal": "Neue Modelle zunächst deaktivieren", "models.newPolicyProvider": "Richtlinie für neue Modelle", "models.newPolicy_inherit": "Übernehmen", "models.newPolicy_off": "Aus", "models.newPolicy_on": "An", "models.newBadge": "NEU", "models.newCount": "{count} neu, aus", "models.aliases": "Aliase", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 22a3807858..2197dcb735 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -311,8 +311,6 @@ export const en = { "models.staleBanner": "Codex is showing an older model list than this catalog. Restart Codex to reload it.", "dash.codexAutoStart": "Start opencodex with Codex", "dash.codexAutoStartHint": "Allows an installed launcher shim to run ocx ensure. This setting does not install restart protection; check Startup safety for the effective state.", - "dash.codexDesktopAuthless": "Open Codex without signing in", - "dash.codexDesktopAuthlessHint": "Off by default. Skip the separate Desktop sign-in for eligible local connections. Upstream credentials are still required. Restart Codex after changing this setting. Account-gated Desktop features may be unavailable.", "dash.searchModel": "Search sidecar model", "dash.searchModelHint": "Model used for web_search on non-OpenAI routed models. Requires ChatGPT login.", "dash.searchReasoning": "Search reasoning effort", @@ -577,6 +575,8 @@ export const en = { "models.keepNativeOnV1Hint": "ChatGPT encrypts v2 child tasks only when a ChatGPT-native parent stays on v2, so Grok and Claude cannot read them. Turn this on to keep Sol/Terra on v1 and avoid that encryption. Routed parents keep v2.", "models.v2Help": "Controls the multi-agent surface for all models.\n\nv1: Classic single-thread agent. Every model uses the v1 collab surface.\nbase: Upstream defaults — sol/terra use v2, luna uses v1, others follow the codex feature flag.\nv2: Multi-thread agent with spawn_agent. Every model uses the v2 collab surface.\n\nOn v2, Keep ChatGPT on v1 leaves Sol/Terra on the v1 surface so they can still spawn Grok or Claude. ChatGPT encrypts v2 child tasks; routed models cannot read them. Routed parents stay on v2.\n\nChanges apply to new sessions.", "dash.multiAgent": "Sub-agent", + "dash.codexDesktopAuthless": "Open Codex without signing in", + "dash.codexDesktopAuthlessHint": "Off by default. Skip the separate Desktop sign-in for eligible local connections. Upstream credentials are still required. Restart Codex after changing this setting. Account-gated Desktop features may be unavailable.", "models.v2Conflict": "[agents] max_threads is set — codex will refuse to start; remove it from config.toml", "models.v2Applied": "Sub-agent mode updated — applies to new sessions (restart the Codex app to refresh the picker)", "models.v2ThreadsLabel": "Max threads", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 9f0f265173..cca4b70347 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -301,8 +301,6 @@ export const fr: Record = { "models.staleBanner": "Codex affiche une liste de modèles plus ancienne que ce catalogue. Redémarrez Codex pour la recharger.", "dash.codexAutoStart": "Démarrer opencodex avec Codex", "dash.codexAutoStartHint": "Permet à un mécanisme de lancement installé d’exécuter ocx ensure. Ce réglage n’installe pas de protection au redémarrage ; consultez Sécurité du démarrage pour connaître l’état effectif.", - "dash.codexDesktopAuthless": "Ouvrir Codex sans se connecter", - "dash.codexDesktopAuthlessHint": "Désactivé par défaut. Ignore la connexion Desktop séparée pour les connexions locales admissibles. Les identifiants du fournisseur restent nécessaires. Redémarrez Codex après toute modification. Certaines fonctions Desktop liées au compte peuvent être indisponibles.", "dash.searchModel": "Modèle auxiliaire de recherche", "dash.searchModelHint": "Modèle utilisé pour web_search sur les modèles routés autres qu’OpenAI. Nécessite une connexion à ChatGPT.", "dash.searchReasoning": "Effort de raisonnement pour la recherche", @@ -562,6 +560,8 @@ export const fr: Record = { "models.keepNativeOnV1Hint": "ChatGPT chiffre les tâches enfants v2 uniquement lorsqu’un parent natif ChatGPT reste sur v2, de sorte que Grok et Claude ne peuvent pas les lire. Activez cette option pour garder Sol/Terra sur v1 et éviter ce chiffrement. Les parents routés restent sur v2.", "models.v2Help": "Contrôle l’interface multi-agent pour tous les modèles.\n\nv1 : agent classique à fil unique. Tous les modèles utilisent l’interface collab v1.\nbase : valeurs par défaut en amont — sol/terra utilisent v2, luna utilise v1 et les autres suivent l’indicateur de fonctionnalité codex.\nv2 : agent multifil avec spawn_agent. Tous les modèles utilisent l’interface collab v2.\n\nEn v2, « Garder ChatGPT sur v1 » laisse Sol/Terra sur l’interface v1 afin qu’ils puissent encore lancer Grok ou Claude. ChatGPT chiffre les tâches enfants v2 ; les modèles routés ne peuvent pas les lire. Les parents routés restent sur v2.\n\nLes modifications s’appliquent aux nouvelles sessions.", "dash.multiAgent": "Sous-agent", + "dash.codexDesktopAuthless": "Ouvrir Codex sans se connecter", + "dash.codexDesktopAuthlessHint": "Désactivé par défaut. Ignore la connexion Desktop séparée pour les connexions locales admissibles. Les identifiants du fournisseur restent nécessaires. Redémarrez Codex après toute modification. Certaines fonctions Desktop liées au compte peuvent être indisponibles.", "models.v2Conflict": "[agents] max_threads est défini — codex refusera de démarrer ; supprimez-le de config.toml", "models.v2Applied": "Mode sous-agent mis à jour — s’applique aux nouvelles sessions (redémarrez l’application Codex pour actualiser le sélecteur)", "models.v2ThreadsLabel": "Nombre maximal de fils", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 55a6fe2495..97aa85a6fb 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -308,8 +308,6 @@ export const ja: Record = { "models.staleBanner": "Codex はこのカタログより古いモデル一覧を表示しています。Codex を再起動すると読み直されます。", "dash.codexAutoStart": "Codex と一緒に opencodex を起動", "dash.codexAutoStartHint": "インストール済み launcher shim に ocx ensure の実行を許可します。この設定だけでは再起動保護はインストールされません。起動安全性で実際の状態を確認してください。", - "dash.codexDesktopAuthless": "ログインせずに Codex を開く", - "dash.codexDesktopAuthlessHint": "既定ではオフです。対象のローカル接続で Desktop の個別ログインを省略します。上流プロバイダーの認証情報は引き続き必要です。変更後は Codex を再起動してください。アカウントに依存する Desktop 機能が利用できない場合があります。", "dash.searchModel": "検索サイドカーモデル", "dash.searchModelHint": "非 OpenAI ルーティングモデルで web_search に使うモデル。ChatGPT ログインが必要です。", "dash.searchReasoning": "検索の推論負荷", @@ -2492,6 +2490,8 @@ export const ja: Record = { "dash.visionTimeout": "タイムアウト", "dash.visionTimeoutInvalid": "{min} から {max} ミリ秒の整数を入力してください。", "dash.visionAdvancedPopover": "詳細なビジョン設定", + "dash.codexDesktopAuthless": "ログインせずに Codex を開く", + "dash.codexDesktopAuthlessHint": "既定ではオフです。対象のローカル接続で Desktop の個別ログインを省略します。上流プロバイダーの認証情報は引き続き必要です。変更後は Codex を再起動してください。アカウントに依存する Desktop 機能が利用できない場合があります。", "models.newPolicyGlobal": "新しいモデルを無効で追加", "models.newPolicyProvider": "新しいモデルのポリシー", "models.newPolicy_inherit": "継承", "models.newPolicy_off": "オフ", "models.newPolicy_on": "オン", "models.newBadge": "新着", "models.newCount": "新着 {count} 件、オフ", "models.aliases": "エイリアス", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 19285b150e..4e66544528 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -303,8 +303,6 @@ export const ko: Record = { "models.staleBanner": "Codex가 이 카탈로그보다 오래된 모델 목록을 보여주고 있습니다. Codex를 재시작하면 새로 읽습니다.", "dash.codexAutoStart": "Codex 실행 시 opencodex 시작", "dash.codexAutoStartHint": "설치된 launcher shim이 ocx ensure를 실행하도록 허용합니다. 이 설정은 재부팅 보호를 설치하지 않으므로 시작 안전성에서 실제 상태를 확인하세요.", - "dash.codexDesktopAuthless": "로그인 없이 Codex 열기", - "dash.codexDesktopAuthlessHint": "기본값은 꺼짐입니다. 지원되는 로컬 연결에서 별도의 Desktop 로그인을 건너뜁니다. 업스트림 인증 정보는 여전히 필요합니다. 변경 후 Codex를 다시 시작하세요. 계정에 연결된 Desktop 기능을 사용하지 못할 수 있습니다.", "dash.searchModel": "서치 사이드카 모델", "dash.searchModelHint": "비-OpenAI 라우팅 모델의 web_search에 사용되는 모델입니다. ChatGPT 로그인 필요.", "dash.searchReasoning": "서치 추론 강도", @@ -2493,6 +2491,8 @@ export const ko: Record = { "dash.visionTimeout": "제한 시간", "dash.visionTimeoutInvalid": "{min}에서 {max} 밀리초 사이의 정수를 입력하세요.", "dash.visionAdvancedPopover": "고급 비전 설정", + "dash.codexDesktopAuthless": "로그인 없이 Codex 열기", + "dash.codexDesktopAuthlessHint": "기본값은 꺼짐입니다. 지원되는 로컬 연결에서 별도의 Desktop 로그인을 건너뜁니다. 업스트림 인증 정보는 여전히 필요합니다. 변경 후 Codex를 다시 시작하세요. 계정에 연결된 Desktop 기능을 사용하지 못할 수 있습니다.", "models.newPolicyGlobal": "새 모델을 비활성화 상태로 추가", "models.newPolicyProvider": "새 모델 정책", "models.newPolicy_inherit": "상속", "models.newPolicy_off": "끔", "models.newPolicy_on": "켬", "models.newBadge": "신규", "models.newCount": "신규 {count}개, 꺼짐", "models.aliases": "별칭", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 87704912ac..e7f199a06a 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -308,8 +308,6 @@ export const ru: Record = { "models.staleBanner": "Codex показывает список моделей старее этого каталога. Перезапустите Codex, чтобы перечитать его.", "dash.codexAutoStart": "Запускать opencodex вместе с Codex", "dash.codexAutoStartHint": "Разрешает установленному launcher shim выполнять ocx ensure. Эта настройка не устанавливает защиту перезапуска; проверьте фактическое состояние в разделе безопасности запуска.", - "dash.codexDesktopAuthless": "Открывать Codex без входа", - "dash.codexDesktopAuthlessHint": "По умолчанию выключено. Пропускает отдельный вход в Desktop для допустимых локальных подключений. Учётные данные провайдера по-прежнему нужны. После изменения перезапустите Codex. Функции Desktop, связанные с аккаунтом, могут быть недоступны.", "dash.searchModel": "Модель сайдкара поиска", "dash.searchModelHint": "Модель, используемая для web_search на маршрутизируемых моделях, отличных от OpenAI. Требуется вход в аккаунт ChatGPT.", "dash.searchReasoning": "Уровень рассуждений для поиска", @@ -2494,6 +2492,8 @@ export const ru: Record = { "dash.visionTimeout": "Таймаут", "dash.visionTimeoutInvalid": "Введите целое число от {min} до {max} миллисекунд.", "dash.visionAdvancedPopover": "Дополнительные настройки изображений", + "dash.codexDesktopAuthless": "Открывать Codex без входа", + "dash.codexDesktopAuthlessHint": "По умолчанию выключено. Пропускает отдельный вход в Desktop для допустимых локальных подключений. Учётные данные провайдера по-прежнему нужны. После изменения перезапустите Codex. Функции Desktop, связанные с аккаунтом, могут быть недоступны.", "models.newPolicyGlobal": "Добавлять новые модели выключенными", "models.newPolicyProvider": "Политика новых моделей", "models.newPolicy_inherit": "Наследовать", "models.newPolicy_off": "Выкл.", "models.newPolicy_on": "Вкл.", "models.newBadge": "НОВАЯ", "models.newCount": "Новых: {count}, выкл.", "models.aliases": "Псевдонимы", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 807eeae32b..8c8f9ff802 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -309,8 +309,6 @@ export const tr: Record = { "models.staleBanner": "Codex, bu katalogdan daha eski bir model listesi gösteriyor. Yeniden okumak için Codex'i yeniden başlatın.", "dash.codexAutoStart": "opencodex'i Codex ile başlat", "dash.codexAutoStartHint": "Yüklü bir shim'in ocx ensure çalıştırmasına izin verir. Arka plan servisi veya yeniden başlatma koruması kurmaz; sistem durumu için Başlatma Güvenliği'ne bakın.", - "dash.codexDesktopAuthless": "Codex’i oturum açmadan başlat", - "dash.codexDesktopAuthlessHint": "Varsayılan olarak kapalıdır. Uygun yerel bağlantılarda ayrı Desktop oturum açma adımını atlar. Sağlayıcı kimlik bilgileri yine gereklidir. Değişiklikten sonra Codex’i yeniden başlatın. Hesaba bağlı Desktop özellikleri kullanılamayabilir.", "dash.searchModel": "Arama yan araç modeli", "dash.searchModelHint": "OpenAI dışı yönlendirilen modellerde web_search için kullanılan model. ChatGPT girişi gerektirir.", "dash.searchReasoning": "Arama akıl yürütme çabası", @@ -2494,6 +2492,8 @@ export const tr: Record = { "dash.visionTimeout": "Zaman aşımı", "dash.visionTimeoutInvalid": "{min} ile {max} milisaniye arasında bir tam sayı girin.", "dash.visionAdvancedPopover": "Gelişmiş görsel ayarları", + "dash.codexDesktopAuthless": "Codex’i oturum açmadan başlat", + "dash.codexDesktopAuthlessHint": "Varsayılan olarak kapalıdır. Uygun yerel bağlantılarda ayrı Desktop oturum açma adımını atlar. Sağlayıcı kimlik bilgileri yine gereklidir. Değişiklikten sonra Codex’i yeniden başlatın. Hesaba bağlı Desktop özellikleri kullanılamayabilir.", "models.newPolicyGlobal": "Yeni modeller devre dışı başlasın", "models.newPolicyProvider": "Yeni model ilkesi", "models.newPolicy_inherit": "Devral", "models.newPolicy_off": "Kapalı", "models.newPolicy_on": "Açık", "models.newBadge": "YENİ", "models.newCount": "{count} yeni, kapalı", "models.aliases": "Takma adlar", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 62e1f07110..eeec289911 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -200,8 +200,6 @@ export const zhTW: Record = { "models.staleBanner": "Codex 顯示的模型清單比目前的目錄舊。重新啟動 Codex 即可重新讀取。", "dash.codexAutoStart": "隨 Codex 啟動 opencodex", "dash.codexAutoStartHint": "允許已安裝的 launcher shim 執行 ocx ensure。此設定不會安裝重新啟動保護;請在啟動安全中檢查實際狀態。", - "dash.codexDesktopAuthless": "無需登入即可開啟 Codex", - "dash.codexDesktopAuthlessHint": "預設關閉。為符合條件的本機連線略過獨立的 Desktop 登入。仍需上游供應商憑證。變更後請重新啟動 Codex。依賴帳戶的 Desktop 功能可能無法使用。", "dash.searchModel": "搜尋附屬模型", "dash.searchModelHint": "用於非 OpenAI 路由模型的 web_search 的模型。需要 ChatGPT 登入。", "dash.searchReasoning": "搜尋推理強度", @@ -2456,6 +2454,8 @@ export const zhTW: Record = { "dash.visionTimeout": "逾時", "dash.visionTimeoutInvalid": "請輸入 {min} 到 {max} 毫秒之間的整數。", "dash.visionAdvancedPopover": "進階視覺設定", + "dash.codexDesktopAuthless": "無需登入即可開啟 Codex", + "dash.codexDesktopAuthlessHint": "預設關閉。為符合條件的本機連線略過獨立的 Desktop 登入。仍需上游供應商憑證。變更後請重新啟動 Codex。依賴帳戶的 Desktop 功能可能無法使用。", "models.newPolicyGlobal": "新模型預設停用", "models.newPolicyProvider": "新模型策略", "models.newPolicy_inherit": "繼承", "models.newPolicy_off": "關閉", "models.newPolicy_on": "開啟", "models.newBadge": "新增", "models.newCount": "{count} 個新增,已關閉", "models.aliases": "別名", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 9946914426..a62e9b2d6b 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -303,8 +303,6 @@ export const zh: Record = { "models.staleBanner": "Codex 显示的模型列表比当前目录旧。重启 Codex 即可重新读取。", "dash.codexAutoStart": "随 Codex 启动 opencodex", "dash.codexAutoStartHint": "允许已安装的 launcher shim 运行 ocx ensure。此设置不会安装重启保护;请在启动安全中检查实际状态。", - "dash.codexDesktopAuthless": "无需登录即可打开 Codex", - "dash.codexDesktopAuthlessHint": "默认关闭。为符合条件的本地连接跳过单独的 Desktop 登录。仍需上游提供商凭据。更改后请重启 Codex。依赖账户的 Desktop 功能可能不可用。", "dash.searchModel": "搜索附属模型", "dash.searchModelHint": "用于非 OpenAI 路由模型的 web_search 的模型。需要 ChatGPT 登录。", "dash.searchReasoning": "搜索推理强度", @@ -2492,6 +2490,8 @@ export const zh: Record = { "dash.visionTimeout": "超时", "dash.visionTimeoutInvalid": "请输入 {min} 到 {max} 毫秒之间的整数。", "dash.visionAdvancedPopover": "高级视觉设置", + "dash.codexDesktopAuthless": "无需登录即可打开 Codex", + "dash.codexDesktopAuthlessHint": "默认关闭。为符合条件的本地连接跳过单独的 Desktop 登录。仍需上游提供商凭据。更改后请重启 Codex。依赖账户的 Desktop 功能可能不可用。", "models.newPolicyGlobal": "新模型默认停用", "models.newPolicyProvider": "新模型策略", "models.newPolicy_inherit": "继承", "models.newPolicy_off": "关闭", "models.newPolicy_on": "开启", "models.newBadge": "新增", "models.newCount": "{count} 个新增,已关闭", "models.aliases": "别名", diff --git a/gui/src/pages/dashboard-shared.ts b/gui/src/pages/dashboard-shared.ts index d240510286..b6914586b6 100644 --- a/gui/src/pages/dashboard-shared.ts +++ b/gui/src/pages/dashboard-shared.ts @@ -128,6 +128,7 @@ export type Installer = "npm" | "bun" | "source"; export type UpdateJobStatus = "running" | "restarting" | "succeeded" | "failed"; export interface SyncResult { ok: boolean; + status?: "applied" | "skipped" | "catalog-only" | "refused"; added: number; catalogPath: string | null; catalogExists: boolean; diff --git a/gui/src/pages/use-dashboard-data.ts b/gui/src/pages/use-dashboard-data.ts index 6da776ea18..e87e6494bd 100644 --- a/gui/src/pages/use-dashboard-data.ts +++ b/gui/src/pages/use-dashboard-data.ts @@ -653,7 +653,9 @@ export function useDashboardData(apiBase: string) { const res = await fetch(`${apiBase}/api/sync`, { method: "POST" }); const data = await requireJson(res, "sync failed"); setSyncResult(data); - setSettings(prev => prev ? { ...prev, catalogRefreshPending: false } : prev); + if (data.ok && data.status === "applied") { + setSettings(prev => prev ? { ...prev, catalogRefreshPending: false } : prev); + } if (data.projectConfigGrouped) setProjectConfigWarnings(data.projectConfigGrouped); } catch (err) { setSyncError(err instanceof Error ? err.message : String(err)); diff --git a/gui/tests/vision-sidecar-dashboard.test.tsx b/gui/tests/vision-sidecar-dashboard.test.tsx index 994a409126..386196cc77 100644 --- a/gui/tests/vision-sidecar-dashboard.test.tsx +++ b/gui/tests/vision-sidecar-dashboard.test.tsx @@ -458,3 +458,30 @@ test.each([undefined, false, true])("Desktop login preference %s persists before globalThis.fetch = originalFetch; } }); + + +test.each(["skipped", "catalog-only", "applied"])("Desktop preference pending state follows %s sync application evidence", async (syncStatus) => { + const originalFetch = globalThis.fetch; + let latest: Dash | undefined; + const apiBase = `/authless-sync-${syncStatus}`; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const path = String(input); + if (init?.method === "PUT") return Response.json({ codexDesktopAuthless: true, catalogRefreshPending: true }); + if (path.endsWith("/api/sync")) return Response.json({ ok: true, status: syncStatus, message: syncStatus }); + if (path.endsWith("/api/settings")) return Response.json({ codexAutoStart: true, codexDesktopAuthless: false, port: 10100, hostname: "127.0.0.1" }); + return Response.json({}, { status: 503 }); + }) as typeof fetch; + function Harness() { latest = useDashboardData(apiBase); return null; } + try { + const { createRoot } = await import("react-dom/client"); + await act(async () => { root = createRoot(host); root.render(); }); + await act(async () => { await latest!.toggleCodexDesktopAuthless(); }); + expect(latest?.settings?.codexDesktopAuthless).toBe(true); + expect(latest?.settings?.catalogRefreshPending).toBe(syncStatus !== "applied"); + expect(latest?.syncResult?.status).toBe(syncStatus); + } finally { + await act(async () => { root?.unmount(); }); + root = null; + globalThis.fetch = originalFetch; + } +}); From f8d3545a0d77ab625f090e6e13f7924760e098d5 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:30:58 +0900 Subject: [PATCH 044/116] fix(gui): preserve fallback choices and explain native-parent V2 compatibility [skip ci] Co-authored-by: x3M3x <98298256+x3M3x@users.noreply.github.com> --- .../content/docs/guides/codex-integration.md | 7 + .../SubagentDelegationSection.tsx | 53 ++- gui/src/i18n/de.ts | 18 +- gui/src/i18n/en.ts | 18 +- gui/src/i18n/fr.ts | 18 +- gui/src/i18n/ja.ts | 18 +- gui/src/i18n/ko.ts | 6 + gui/src/i18n/ru.ts | 18 +- gui/src/i18n/tr.ts | 6 + gui/src/i18n/zh-TW.ts | 18 +- gui/src/i18n/zh.ts | 18 +- gui/src/pages/Subagents.tsx | 29 +- gui/src/pages/use-subagent-delegation.ts | 2 + gui/src/styles-subagents-workspace.css | 13 + gui/tests/multi-agent-guidance.test.tsx | 9 +- gui/tests/subagents-fallback.test.tsx | 422 ++++++++++++++++++ 16 files changed, 613 insertions(+), 60 deletions(-) create mode 100644 gui/tests/subagents-fallback.test.tsx diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index ff2df04fdd..f5592c0a72 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -586,3 +586,10 @@ ocx restore back # point plain Codex at the running proxy again When opencodex runs as a managed [background service](/reference/cli/#ocx-service), it sets `OCX_SERVICE=1` so a service-driven restart does **not** thrash the Codex config — only an explicit `ocx stop` / `ocx service stop` restores native Codex. + + +### Sub-agent fallback and V2 compatibility + +In **Subagents → Delegation settings**, edit the ordered fallback chain and its availability polling interval (5000–600000 ms), then save it separately from the featured roster. A configured target that is no longer advertised remains in the chain until you remove it. The roster and fallback chain are separate settings; this editor does not make the roster replace the fallback policy. + +When a routed preferred model may receive V2 work from a native ChatGPT parent, the panel explains the upstream encrypted-task limitation. Readable tasks from routed parents are unaffected. The guidance uses `/api/v2` mode and native V1 pin state; the current API does not expose recovery activation or request-specific eligibility, so the panel reports those as unknown. V1/plaintext-compatible delegation remains an alternative. Experimental V2 recovery, where eligible and explicitly enabled, adds quota usage, latency, backend dependence and possible fidelity loss; it does not repair the upstream protocol. See [sub-agent surfaces](/guides/sub-agent-surface/) and [the upstream limitation](https://github.com/lidge-jun/opencodex/issues/92). diff --git a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx index 7c3b0e9425..dbbbd99948 100644 --- a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx +++ b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx @@ -8,7 +8,7 @@ */ import { useState } from "react"; import { Select, Tooltip } from "../../ui"; -import { IconInfo } from "../../icons"; +import { IconArrowDown, IconArrowUp, IconInfo, IconX } from "../../icons"; import { useT, type TKey } from "../../i18n/shared"; import { formatNamespacedModelId } from "../../provider-icons"; import type { DelegationPatch, DelegationModelOption } from "../../pages/use-subagent-delegation"; @@ -58,6 +58,19 @@ export default function SubagentDelegationSection({ // Proactive message, so it must render as OFF (and the toggle can install the // preset). Only a nonblank hint is "on". const ultraOn = (ultraMode.hintText ?? "").trim().length > 0; + const routedPreferred = available.some(option => option.namespaced === model + && !(option.provider === "openai" && option.namespaced === option.model)); + const nativeMayUseV2 = ultraMode.enabled || (ultraMode.multiAgentMode !== "v1" + && !(ultraMode.multiAgentMode === "v2" && ultraMode.keepNativeChatGptOnV1)); + const showV2Compatibility = !ultraLoadFailed && ultraMode.loaded === true && routedPreferred && nativeMayUseV2; + const validPollMs = Number.isInteger(fallbackPollMs) && fallbackPollMs >= 5000 && fallbackPollMs <= 600000; + const moveFallback = (index: number, direction: -1 | 1) => { + const next = [...fallback]; + const target = index + direction; + if (fallbackBusy || target < 0 || target >= next.length) return; + [next[index], next[target]] = [next[target], next[index]]; + onFallbackChange(next); + }; return (

@@ -105,6 +118,17 @@ export default function SubagentDelegationSection({
+ {showV2Compatibility && ( +
+
+
{t("sub.v2Compatibility.title")}
+

{t("sub.v2Compatibility.risk")}

+

{t("sub.v2Compatibility.recoveryUnknown")}

+ {t("sub.v2Compatibility.details")} +
+
+ )} +
{t("sub.fallbackLabel")}
@@ -112,21 +136,26 @@ export default function SubagentDelegationSection({
{fallback.map((modelName, index) => ( -
- {index + 1}. {modelName} - - - +
+ {index + 1}. {modelName} + {!availableModels.includes(modelName) && {t("sub.fallbackUnavailable")}} + + + + + +
))} - + onFallbackPollMsChange(Number(e.target.value) || 60000)} disabled={fallbackBusy} /> ms + onFallbackPollMsChange(Number(e.target.value))} disabled={fallbackBusy} aria-invalid={!validPollMs} /> ms - + {!validPollMs &&
{t("sub.fallbackPollInvalid")}
} +
diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 8985d342a0..4145cb8032 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -686,12 +686,6 @@ export const de: Record = { "sub.ultraModeLoadFail": "Ultra-Modus-Einstellungen konnten nicht geladen werden — läuft der Proxy?", "sub.ultraModeSaveFail": "Ultra-Modus-Einstellungen konnten nicht gespeichert werden", "sub.ultraModeSaved": "Ultra-Modus gespeichert. Gilt für neue Codex-Sitzungen.", - "sub.fallbackLabel": "Fallback-Kette für Sub-Agenten", - "sub.fallbackHint": "Geordnete Modelle, die versucht werden, wenn ein Sub-Agent-Modell nicht verfügbar ist oder fehlschlägt.", - "sub.fallbackAdd": "Fallback-Modell hinzufügen…", - "sub.fallbackPoll": "Intervall der Verfügbarkeitsprüfung", - "sub.fallbackSaved": "Fallback-Einstellungen für Sub-Agenten gespeichert.", - "sub.fallbackSaveFailed": "Fallback-Einstellungen konnten nicht gespeichert werden", "logs.title": "Anfrage-Protokolle", "logs.tabLogs": "Protokolle", "logs.tabDebug": "Diagnose", @@ -2414,6 +2408,18 @@ export const de: Record = { "sub.sections": "Subagent-Abschnitte", "sub.delegation.model": "Zuerst aufgerufenes Modell", "sub.delegation.modelHint": "Das Modell, zu dem Codex zuerst greift, wenn es Arbeit übergibt. Oben steht, wen es überhaupt aufrufen darf; hier wählst du den Ersten davon.", + "sub.fallbackLabel": "Fallback-Kette für Sub-Agenten", + "sub.fallbackHint": "Geordnete Modelle, die versucht werden, wenn ein Sub-Agent-Modell nicht verfügbar ist oder fehlschlägt.", + "sub.fallbackAdd": "Fallback-Modell hinzufügen…", + "sub.fallbackPoll": "Intervall der Verfügbarkeitsprüfung", + "sub.fallbackSaved": "Fallback-Einstellungen für Sub-Agenten gespeichert.", + "sub.fallbackSaveFailed": "Fallback-Einstellungen konnten nicht gespeichert werden", + "sub.fallbackUnavailable": "Derzeit nicht gelistet; bleibt in der Kette.", + "sub.fallbackPollInvalid": "Eine ganze Zahl von 5000 bis 600000 ms eingeben.", + "sub.v2Compatibility.title": "V2-Kompatibilität nativer Eltern", + "sub.v2Compatibility.risk": "Delegiert ein nativer ChatGPT-Elternagent über V2 an dieses geroutete Modell, kann die Aufgabe verschlüsselt sein und vor der Ausführung scheitern. Lesbare Aufgaben gerouteter Eltern sind nicht betroffen.", + "sub.v2Compatibility.recoveryUnknown": "Dieser Server meldet weder Aktivierung noch Eignung der Wiederherstellung. V1/Klartext verwenden oder experimentelle V2-Wiederherstellung nur bei Eignung aktivieren. Sie kostet Kontingent und Latenz, hängt vom Backend ab und kann Wiedergabetreue verlieren; das Upstream-Protokoll bleibt unverändert.", + "sub.v2Compatibility.details": "Details zur Kompatibilität", "dash.syncModelsHint": "Schreibt Codex' Modellkatalog anhand deiner verbundenen Provider neu.", "dash.syncRun": "Jetzt synchronisieren", "lab.title": "Kompatibilitäts-Labor", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index a33c195e82..2a31ec7947 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -329,12 +329,6 @@ export const en = { "dash.visionTimeout": "Timeout", "dash.visionTimeoutInvalid": "Enter an integer from {min} to {max} milliseconds.", "dash.visionAdvancedPopover": "Advanced vision settings", - "sub.fallbackLabel": "Sub-agent fallback chain", - "sub.fallbackHint": "Ordered models tried when a sub-agent model is unavailable or fails.", - "sub.fallbackAdd": "Add fallback model…", - "sub.fallbackPoll": "Availability check interval", - "sub.fallbackSaved": "Sub-agent fallback settings saved.", - "sub.fallbackSaveFailed": "Failed to save fallback settings", "dash.shadowCallIntercept": "Shadow Call Intercept", "dash.shadowCallInterceptHint": "Intercepts Codex App's background helper calls ({models}) for title generation and commit messages and redirects them to your chosen model.", "dash.shadowCallWarning": "⚠ When enabled, ALL requests for {models} will be replaced with the selected model.", @@ -725,6 +719,18 @@ export const en = { "sub.workspace.selectModel": "Select a model", "sub.workspace.selectModelDesc": "Pick a model from the list to see details and feature it for spawn_agent.", "sub.workspace.selector": "Public selector", + "sub.fallbackLabel": "Sub-agent fallback chain", + "sub.fallbackHint": "Ordered models tried when a sub-agent model is unavailable or fails.", + "sub.fallbackAdd": "Add fallback model…", + "sub.fallbackPoll": "Availability check interval", + "sub.fallbackSaved": "Sub-agent fallback settings saved.", + "sub.fallbackSaveFailed": "Failed to save fallback settings", + "sub.fallbackUnavailable": "Not currently advertised; kept in the chain.", + "sub.fallbackPollInvalid": "Enter an integer from 5000 to 600000 ms.", + "sub.v2Compatibility.title": "Native-parent V2 compatibility", + "sub.v2Compatibility.risk": "If a native ChatGPT parent delegates to this routed model using V2, its task may be encrypted and fail before execution. Readable tasks from routed parents are unaffected.", + "sub.v2Compatibility.recoveryUnknown": "Recovery enabled/eligibility state is not exposed by this server. Use V1/plaintext-compatible delegation, or enable experimental V2 recovery only if eligible. Recovery adds quota, latency, backend dependence and possible fidelity loss; it does not fix the upstream protocol.", + "sub.v2Compatibility.details": "Compatibility details", // logs "logs.title": "Request Logs", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index fa32925c02..753982c1bf 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -319,12 +319,6 @@ export const fr: Record = { "dash.visionTimeout": "Délai d’expiration", "dash.visionTimeoutInvalid": "Saisissez un entier compris entre {min} et {max} millisecondes.", "dash.visionAdvancedPopover": "Paramètres de vision avancés", - "sub.fallbackLabel": "Chaîne de secours des sous-agents", - "sub.fallbackHint": "Modèles essayés dans l’ordre lorsqu’un modèle de sous-agent est indisponible ou échoue.", - "sub.fallbackAdd": "Ajouter un modèle de secours…", - "sub.fallbackPoll": "Intervalle de vérification de disponibilité", - "sub.fallbackSaved": "Paramètres de secours des sous-agents enregistrés.", - "sub.fallbackSaveFailed": "Échec de l’enregistrement des paramètres de secours", "dash.shadowCallIntercept": "Interception des appels fantômes", "dash.shadowCallInterceptHint": "Intercepte les appels auxiliaires en arrière-plan de l’application Codex ({models}) pour générer les titres et les messages de commit, puis les redirige vers le modèle choisi.", "dash.shadowCallWarning": "⚠ Lorsque cette option est activée, TOUTES les requêtes destinées à {models} sont remplacées par le modèle sélectionné.", @@ -708,6 +702,18 @@ export const fr: Record = { "sub.workspace.selectModel": "Sélectionner un modèle", "sub.workspace.selectModelDesc": "Choisissez un modèle dans la liste pour afficher ses détails et le mettre à la une pour spawn_agent.", "sub.workspace.selector": "Sélecteur public", + "sub.fallbackLabel": "Chaîne de secours des sous-agents", + "sub.fallbackHint": "Modèles essayés dans l’ordre lorsqu’un modèle de sous-agent est indisponible ou échoue.", + "sub.fallbackAdd": "Ajouter un modèle de secours…", + "sub.fallbackPoll": "Intervalle de vérification de disponibilité", + "sub.fallbackSaved": "Paramètres de secours des sous-agents enregistrés.", + "sub.fallbackSaveFailed": "Échec de l’enregistrement des paramètres de secours", + "sub.fallbackUnavailable": "Absent du catalogue actuel ; conservé dans la chaîne.", + "sub.fallbackPollInvalid": "Saisissez un entier de 5000 à 600000 ms.", + "sub.v2Compatibility.title": "Compatibilité V2 du parent natif", + "sub.v2Compatibility.risk": "Si un parent ChatGPT natif délègue à ce modèle routé via V2, la tâche peut être chiffrée et échouer avant son exécution. Les tâches lisibles des parents routés ne sont pas affectées.", + "sub.v2Compatibility.recoveryUnknown": "Ce serveur ne fournit pas l’activation ni l’éligibilité de la récupération. Utilisez V1/texte clair, ou activez la récupération V2 expérimentale uniquement si éligible. Elle ajoute quota, latence, dépendance au backend et risque de perte de fidélité ; elle ne corrige pas le protocole amont.", + "sub.v2Compatibility.details": "Détails de compatibilité", "logs.title": "Journaux des requêtes", "logs.tabLogs": "Journaux", "logs.tabDebug": "Débogage", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 81cd40bca9..300d1f8c51 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -646,12 +646,6 @@ export const ja: Record = { "sub.ultraModeLoadFail": "ウルトラモード設定を読み込めませんでした — プロキシは実行中ですか?", "sub.ultraModeSaveFail": "ウルトラモード設定の保存に失敗しました", "sub.ultraModeSaved": "ウルトラモードを保存しました。新しい Codex セッションから適用されます。", - "sub.fallbackLabel": "サブエージェントのフォールバックチェーン", - "sub.fallbackHint": "サブエージェントモデルが利用できないか失敗した場合に順番に試すモデルです。", - "sub.fallbackAdd": "フォールバックモデルを追加…", - "sub.fallbackPoll": "利用可能性チェック間隔", - "sub.fallbackSaved": "サブエージェントのフォールバック設定を保存しました。", - "sub.fallbackSaveFailed": "フォールバック設定の保存に失敗しました", // logs "logs.title": "リクエストログ", @@ -2435,6 +2429,18 @@ export const ja: Record = { "sub.sections": "サブエージェントのセクション", "sub.delegation.model": "最初に呼ぶモデル", "sub.delegation.modelHint": "Codex が作業を任せるとき、最初に呼ぶモデルです。上のおすすめが呼べる候補で、ここで選んだものがその中の第一候補になります。", + "sub.fallbackLabel": "サブエージェントのフォールバックチェーン", + "sub.fallbackHint": "サブエージェントモデルが利用できないか失敗した場合に順番に試すモデルです。", + "sub.fallbackAdd": "フォールバックモデルを追加…", + "sub.fallbackPoll": "利用可能性チェック間隔", + "sub.fallbackSaved": "サブエージェントのフォールバック設定を保存しました。", + "sub.fallbackSaveFailed": "フォールバック設定の保存に失敗しました", + "sub.fallbackUnavailable": "現在の一覧にはありませんが、チェーンに保持されます。", + "sub.fallbackPollInvalid": "5000〜600000 ms の整数を入力してください。", + "sub.v2Compatibility.title": "ネイティブ親の V2 互換性", + "sub.v2Compatibility.risk": "ネイティブ ChatGPT 親が V2 でこのルーティングモデルに委任すると、タスクが暗号化され実行前に失敗する場合があります。ルーティング親からの読み取り可能なタスクは影響を受けません。", + "sub.v2Compatibility.recoveryUnknown": "このサーバーは復旧の有効状態や適格性を公開していません。V1・平文互換の委任を使うか、適格な場合のみ実験的 V2 復旧を有効にしてください。復旧にはクォータ、遅延、バックエンド依存、忠実度低下の可能性があり、上流プロトコルは修正されません。", + "sub.v2Compatibility.details": "互換性の詳細", "dash.syncModelsHint": "接続済みのプロバイダーをもとに Codex のモデルカタログを書き直します。", "dash.syncRun": "今すぐ同期", "lab.title": "Compatibility Lab", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 35a726e6ba..42c000c6bb 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -709,6 +709,12 @@ export const ko: Record = { "sub.fallbackPoll": "가용성 확인 간격", "sub.fallbackSaved": "서브에이전트 폴백 설정을 저장했습니다.", "sub.fallbackSaveFailed": "폴백 설정을 저장하지 못했습니다", + "sub.fallbackUnavailable": "현재 목록에 없지만 체인에 유지됩니다.", + "sub.fallbackPollInvalid": "5000~600000ms 범위의 정수를 입력하세요.", + "sub.v2Compatibility.title": "네이티브 부모의 V2 호환성", + "sub.v2Compatibility.risk": "네이티브 ChatGPT 부모가 V2로 이 라우팅 모델에 위임하면 작업이 암호화되어 실행 전에 실패할 수 있습니다. 라우팅 부모가 보내는 읽을 수 있는 작업에는 영향이 없습니다.", + "sub.v2Compatibility.recoveryUnknown": "이 서버는 복구 활성화 여부와 사용 가능 상태를 제공하지 않습니다. V1·평문 호환 위임을 사용하거나, 조건을 충족할 때만 실험적 V2 복구를 켜세요. 복구에는 할당량·지연·백엔드 의존성과 원문 충실도 손실 가능성이 따르며, 업스트림 프로토콜을 고치지는 않습니다.", + "sub.v2Compatibility.details": "호환성 자세히 보기", // logs "logs.title": "요청 로그", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index a7cc5f72e8..51fcaef210 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -701,12 +701,6 @@ export const ru: Record = { "sub.ultraModeLoadFail": "Не удалось загрузить настройки ультра-режима — работает ли прокси?", "sub.ultraModeSaveFail": "Не удалось сохранить настройки ультра-режима", "sub.ultraModeSaved": "Ультра-режим сохранён. Применяется к новым сеансам Codex.", - "sub.fallbackLabel": "Цепочка резервных моделей субагента", - "sub.fallbackHint": "Модели, которые последовательно пробуются, если модель субагента недоступна или завершается ошибкой.", - "sub.fallbackAdd": "Добавить резервную модель…", - "sub.fallbackPoll": "Интервал проверки доступности", - "sub.fallbackSaved": "Настройки резервных моделей субагента сохранены.", - "sub.fallbackSaveFailed": "Не удалось сохранить настройки резервных моделей", // logs "logs.title": "Журнал запросов", @@ -2437,6 +2431,18 @@ export const ru: Record = { "sub.sections": "Разделы подагентов", "sub.delegation.model": "Модель, которую вызывать первой", "sub.delegation.modelHint": "Модель, к которой Codex обращается первой, когда передаёт работу. Список выше — кого он вообще может вызвать, а здесь выбирается первый в очереди.", + "sub.fallbackLabel": "Цепочка резервных моделей субагента", + "sub.fallbackHint": "Модели, которые последовательно пробуются, если модель субагента недоступна или завершается ошибкой.", + "sub.fallbackAdd": "Добавить резервную модель…", + "sub.fallbackPoll": "Интервал проверки доступности", + "sub.fallbackSaved": "Настройки резервных моделей субагента сохранены.", + "sub.fallbackSaveFailed": "Не удалось сохранить настройки резервных моделей", + "sub.fallbackUnavailable": "Сейчас отсутствует в каталоге; сохранена в цепочке.", + "sub.fallbackPollInvalid": "Введите целое число от 5000 до 600000 мс.", + "sub.v2Compatibility.title": "Совместимость V2 с нативным родителем", + "sub.v2Compatibility.risk": "Если нативный родитель ChatGPT делегирует этой маршрутизируемой модели через V2, задача может быть зашифрована и завершиться ошибкой до выполнения. Читаемые задачи маршрутизируемых родителей не затрагиваются.", + "sub.v2Compatibility.recoveryUnknown": "Сервер не сообщает, включено ли восстановление и доступно ли оно. Используйте V1/открытый текст или включите экспериментальное восстановление V2 только при соответствии условиям. Оно расходует квоту, увеличивает задержку, зависит от бэкенда и может снизить точность; исходный протокол не исправляется.", + "sub.v2Compatibility.details": "Подробнее о совместимости", "dash.syncModelsHint": "Перезаписывает каталог моделей Codex по подключённым провайдерам.", "dash.syncRun": "Синхронизировать", "lab.title": "Compatibility Lab", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 5c0ade9077..c764bf11ca 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -714,6 +714,12 @@ export const tr: Record = { "sub.fallbackPoll": "Kullanılabilirlik kontrol aralığı", "sub.fallbackSaved": "Alt ajan yedek ayarları kaydedildi.", "sub.fallbackSaveFailed": "Yedek ayarlar kaydedilemedi", + "sub.fallbackUnavailable": "Şu anda listelenmiyor; zincirde korunur.", + "sub.fallbackPollInvalid": "5000–600000 ms arasında bir tam sayı girin.", + "sub.v2Compatibility.title": "Yerel üst ajanın V2 uyumluluğu", + "sub.v2Compatibility.risk": "Yerel ChatGPT üst ajanı V2 ile bu yönlendirilmiş modele görev verirse görev şifrelenmiş olabilir ve yürütülmeden başarısız olabilir. Yönlendirilmiş üst ajanların okunabilir görevleri etkilenmez.", + "sub.v2Compatibility.recoveryUnknown": "Bu sunucu kurtarmanın etkinliğini veya uygunluğunu bildirmez. V1/düz metin kullanın ya da deneysel V2 kurtarmayı yalnızca uygunsa açın. Kurtarma kota, gecikme, arka uç bağımlılığı ve aslına uygunluk kaybı getirebilir; üst sistem protokolünü düzeltmez.", + "sub.v2Compatibility.details": "Uyumluluk ayrıntıları", // logs "logs.title": "İstek Günlükleri", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index cae0175057..ab6aedd67a 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -555,12 +555,6 @@ export const zhTW: Record = { "sub.ultraModeLoadFail": "無法載入超級模式設定 — 代理是否在執行?", "sub.ultraModeSaveFail": "儲存超級模式設定失敗", "sub.ultraModeSaved": "超級模式已儲存。適用於新的 Codex 會話。", - "sub.fallbackLabel": "子代理備援鏈", - "sub.fallbackHint": "子代理模型無法使用或失敗時,依序嘗試的模型。", - "sub.fallbackAdd": "新增備援模型…", - "sub.fallbackPoll": "可用性檢查間隔", - "sub.fallbackSaved": "子代理備援設定已儲存。", - "sub.fallbackSaveFailed": "備援設定儲存失敗", "logs.title": "請求日誌", "logs.tabLogs": "日誌", "logs.tabDebug": "除錯", @@ -1972,6 +1966,18 @@ export const zhTW: Record = { "sub.sections": "子代理分區", "sub.delegation.model": "優先調用的模型", "sub.delegation.modelHint": "Codex 分派工作時最先調用的模型。上面的推薦是可調用的名單,這裡選的是其中第一順位。", + "sub.fallbackLabel": "子代理備援鏈", + "sub.fallbackHint": "子代理模型無法使用或失敗時,依序嘗試的模型。", + "sub.fallbackAdd": "新增備援模型…", + "sub.fallbackPoll": "可用性檢查間隔", + "sub.fallbackSaved": "子代理備援設定已儲存。", + "sub.fallbackSaveFailed": "備援設定儲存失敗", + "sub.fallbackUnavailable": "目前未列出,仍保留在回退鏈中。", + "sub.fallbackPollInvalid": "請輸入 5000 到 600000 ms 之間的整數。", + "sub.v2Compatibility.title": "原生父代理的 V2 相容性", + "sub.v2Compatibility.risk": "原生 ChatGPT 父代理透過 V2 委派給此路由模型時,任務可能被加密並在執行前失敗。路由父代理傳送的可讀任務不受影響。", + "sub.v2Compatibility.recoveryUnknown": "此伺服器未提供復原功能的啟用或適用狀態。請使用 V1/明文相容委派,或僅在符合條件時啟用實驗性 V2 復原。復原會增加配額消耗、延遲、後端依賴及保真度損失風險,並不修復上游協定。", + "sub.v2Compatibility.details": "相容性詳情", "debug.loadFailed": "無法載入偵錯設定。", "provider.name.volcengine": "Volcengine Ark", "provider.name.volcengineCodingPlan": "Volcengine Ark Coding Plan", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index ce44edc693..052f449855 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -696,12 +696,6 @@ export const zh: Record = { "sub.ultraModeLoadFail": "无法加载超级模式设置 — 代理是否在运行?", "sub.ultraModeSaveFail": "保存超级模式设置失败", "sub.ultraModeSaved": "超级模式已保存。适用于新的 Codex 会话。", - "sub.fallbackLabel": "子代理回退链", - "sub.fallbackHint": "子代理模型不可用或失败时按顺序尝试的模型。", - "sub.fallbackAdd": "添加回退模型…", - "sub.fallbackPoll": "可用性检查间隔", - "sub.fallbackSaved": "子代理回退设置已保存。", - "sub.fallbackSaveFailed": "保存回退设置失败", // logs "logs.title": "请求日志", @@ -2435,6 +2429,18 @@ export const zh: Record = { "sub.sections": "子代理分区", "sub.delegation.model": "优先调用的模型", "sub.delegation.modelHint": "Codex 分派工作时最先调用的模型。上面的推荐是可调用的名单,这里选的是其中第一顺位。", + "sub.fallbackLabel": "子代理回退链", + "sub.fallbackHint": "子代理模型不可用或失败时按顺序尝试的模型。", + "sub.fallbackAdd": "添加回退模型…", + "sub.fallbackPoll": "可用性检查间隔", + "sub.fallbackSaved": "子代理回退设置已保存。", + "sub.fallbackSaveFailed": "保存回退设置失败", + "sub.fallbackUnavailable": "当前未列出,仍保留在回退链中。", + "sub.fallbackPollInvalid": "请输入 5000 到 600000 ms 之间的整数。", + "sub.v2Compatibility.title": "原生父代理的 V2 兼容性", + "sub.v2Compatibility.risk": "原生 ChatGPT 父代理通过 V2 委派给此路由模型时,任务可能被加密并在执行前失败。路由父代理发送的可读任务不受影响。", + "sub.v2Compatibility.recoveryUnknown": "此服务器未提供恢复功能的启用或适用状态。请使用 V1/明文兼容委派,或仅在符合条件时启用实验性 V2 恢复。恢复会增加配额消耗、延迟、后端依赖及保真度损失风险,并不修复上游协议。", + "sub.v2Compatibility.details": "兼容性详情", "dash.syncModelsHint": "按已连接的提供商重写 Codex 的模型目录。", "dash.syncRun": "立即同步", "lab.title": "Compatibility Lab", diff --git a/gui/src/pages/Subagents.tsx b/gui/src/pages/Subagents.tsx index 299c9306fe..cbdb138e33 100644 --- a/gui/src/pages/Subagents.tsx +++ b/gui/src/pages/Subagents.tsx @@ -22,6 +22,8 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const [fallback, setFallback] = useState(() => cached?.fallback ?? []); const [fallbackPollMs, setFallbackPollMs] = useState(() => cached?.pollMs ?? 60000); const [fallbackBusy, setFallbackBusy] = useState(false); + const fallbackSaveInFlight = useRef(false); + const committed = useRef(cached); const [status, setStatus] = useState(""); const [ok, setOk] = useState(false); const [busy, setBusy] = useState(false); @@ -49,12 +51,15 @@ export default function Subagents({ apiBase }: { apiBase: string }) { enabled?: boolean; multiAgentMode?: "v1" | "default" | "v2"; multiAgentModeHintText?: string | null; + keepNativeChatGptOnV1?: boolean; }>(res, t("sub.ultraModeLoadFail")); if (!data) return false; if (signal?.aborted || generation !== ultraLoadGeneration.current || currentUltraApiBase.current !== apiBase) return false; setUltraLoadFailed(false); setUltraMode({ enabled: data.enabled ?? false, + loaded: true, + keepNativeChatGptOnV1: data.keepNativeChatGptOnV1 === true, hintText: data.multiAgentModeHintText ?? null, // Ultra mode replaces Codex's effort-derived policy for every model. The // `default` surface still preserves upstream V1 pins (for example luna), @@ -132,9 +137,12 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const next = { available, chosen: (response.chosen ?? []).filter(model => availableSet.has(model)), - fallback: (fallbackResponse.models ?? []).filter(model => availableSet.has(model)), + // Configured targets remain editable even when discovery no longer advertises them. + fallback: fallbackResponse.models ?? [], pollMs: fallbackResponse.pollMs ?? 60000, }; + if (signal?.aborted) throw signal.reason; + committed.current = next; setChosen(next.chosen); setFallback(next.fallback); setFallbackPollMs(next.pollMs); @@ -185,7 +193,9 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const d = await readJsonOrThrow<{ applied?: string[] }>(r, t("sub.saveFailed")); const applied = d?.applied ?? chosen; if (d?.applied) setChosen(d.applied); - writeSessionListCache(cacheKey, { available, chosen: applied, fallback, pollMs: fallbackPollMs }); + const next = { available, chosen: applied, fallback: committed.current?.fallback ?? [], pollMs: committed.current?.pollMs ?? 60000 }; + committed.current = next; + writeSessionListCache(cacheKey, next); setOk(true); setStatus(t("sub.saved", { n: applied.length, cmd: "ocx sync" })); } catch (error) { @@ -198,8 +208,11 @@ export default function Subagents({ apiBase }: { apiBase: string }) { }; const saveFallback = async () => { - if (fallbackBusy) return; + if (fallbackSaveInFlight.current || !Number.isInteger(fallbackPollMs) || fallbackPollMs < 5000 || fallbackPollMs > 600000) return; + fallbackSaveInFlight.current = true; + const requestApiBase = apiBase; setFallbackBusy(true); + setStatus(""); try { const r = await fetch(`${apiBase}/api/subagent-model-fallback`, { method: "PUT", @@ -207,14 +220,20 @@ export default function Subagents({ apiBase }: { apiBase: string }) { body: JSON.stringify({ models: fallback, pollMs: fallbackPollMs }), }); const d = await readJsonOrThrow<{ models?: string[]; pollMs?: number }>(r, t("sub.fallbackSaveFailed")); - if (d?.models) setFallback(d.models); - if (d?.pollMs) setFallbackPollMs(d.pollMs); + if (currentUltraApiBase.current !== requestApiBase) return; + if (!d || !Array.isArray(d.models) || typeof d.pollMs !== "number") throw new Error(t("sub.fallbackSaveFailed")); + setFallback(d.models); + setFallbackPollMs(d.pollMs); + const next = { available, chosen: committed.current?.chosen ?? [], fallback: d.models, pollMs: d.pollMs }; + committed.current = next; + writeSessionListCache(cacheKey, next); setOk(true); setStatus(t("sub.fallbackSaved")); } catch (error) { setOk(false); setStatus(error instanceof Error && error.message ? error.message : t("sub.networkError")); } finally { + fallbackSaveInFlight.current = false; setFallbackBusy(false); } }; diff --git a/gui/src/pages/use-subagent-delegation.ts b/gui/src/pages/use-subagent-delegation.ts index 716eb11482..9baa5baa9a 100644 --- a/gui/src/pages/use-subagent-delegation.ts +++ b/gui/src/pages/use-subagent-delegation.ts @@ -21,6 +21,8 @@ export type DelegationPatch = { /** Ultra mode (Proactive delegation for every model/effort) via /api/v2. */ export type UltraModeState = { + loaded?: boolean; + keepNativeChatGptOnV1?: boolean; enabled: boolean; hintText: string | null; multiAgentV2Enabled: boolean; diff --git a/gui/src/styles-subagents-workspace.css b/gui/src/styles-subagents-workspace.css index c6292077b7..a9f9466ce7 100644 --- a/gui/src/styles-subagents-workspace.css +++ b/gui/src/styles-subagents-workspace.css @@ -575,3 +575,16 @@ } } } + + +/* Fallback targets keep their identifiers readable next to row actions. */ +.swi-fallback-controls { display: flex; flex-direction: column; align-items: stretch; gap: var(--space-2); flex: 1 1 55%; min-width: 0; } +.swi-fallback-row { display: flex; align-items: center; justify-content: space-between; gap: var(--space-2); } +.swi-fallback-model { min-width: 0; overflow-wrap: anywhere; } +.swi-fallback-model .setting-hint { display: block; } +.swi-fallback-actions { display: inline-flex; flex-shrink: 0; } +.swi-fallback-controls > .btn { align-self: flex-end; } +@media (max-width: 640px) { + .swi-fallback-editor { flex-direction: column; } + .swi-fallback-controls { width: 100%; } +} diff --git a/gui/tests/multi-agent-guidance.test.tsx b/gui/tests/multi-agent-guidance.test.tsx index 16470385b8..8907406f0e 100644 --- a/gui/tests/multi-agent-guidance.test.tsx +++ b/gui/tests/multi-agent-guidance.test.tsx @@ -65,7 +65,14 @@ function props(overrides: Partial = {}): Props { guidanceEnabled: false, syncCodexDefaults: true, onSave: (patch) => { requests.push(patch); }, - ultraMode: { enabled: false, hintText: null, multiAgentV2Enabled: false }, + ultraMode: { enabled: false, hintText: null, multiAgentV2Enabled: false, multiAgentMode: "default" }, + fallback: [], + fallbackPollMs: 60000, + fallbackBusy: false, + availableModels: [], + onFallbackChange: () => {}, + onFallbackPollMsChange: () => {}, + onFallbackSave: () => {}, ultraSaving: false, onUltraModeSave: () => {}, ultraLoadFailed: false, diff --git a/gui/tests/subagents-fallback.test.tsx b/gui/tests/subagents-fallback.test.tsx new file mode 100644 index 0000000000..20badc4980 --- /dev/null +++ b/gui/tests/subagents-fallback.test.tsx @@ -0,0 +1,422 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { clearClientResourceStoresForTests } from "../src/client-resource"; +import { en } from "../src/i18n/en"; +import { LanguageProvider } from "../src/i18n/provider"; +import Subagents from "../src/pages/Subagents"; +import { readSessionListCache } from "../src/session-list-cache"; + +const CACHE_KEY = "ocx.subagents.v1:"; +const FALLBACK_PATH = "/api/subagent-model-fallback"; +const ROSTER_PATH = "/api/subagent-models"; +const UNAVAILABLE_MODEL = "retired-provider/configured-model"; +const globals = [ + "document", "window", "navigator", "localStorage", "sessionStorage", "fetch", "IS_REACT_ACT_ENVIRONMENT", +] as const; + +type CachedSubagents = { available: string[]; chosen: string[]; fallback: string[]; pollMs: number }; +type FallbackSettings = { models: string[]; pollMs: number }; +type SentRequest = { path: string; method: string; init?: RequestInit }; +type V2Settings = { + enabled: boolean; + multiAgentMode: "v1" | "default" | "v2"; + multiAgentModeHintText: string | null; + keepNativeChatGptOnV1: boolean; +}; + +let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; +let testWindow: Window; +let container: HTMLElement; +let root: Root | null = null; +let requests: SentRequest[]; +let available: string[]; +let chosen: string[]; +let fallbackSettings: FallbackSettings; +let failFallbackPut: boolean; +let v2Settings: V2Settings; +let preferredModel: string | null; +let fallbackGetGate: Promise | null; + +beforeEach(() => { + clearClientResourceStoresForTests(); + previousGlobals = Object.fromEntries(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])) as typeof previousGlobals; + testWindow = new Window({ url: "http://localhost/" }); + Object.defineProperty(testWindow.navigator, "language", { configurable: true, value: "en-US" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + sessionStorage: { configurable: true, value: testWindow.sessionStorage }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + + requests = []; + available = ["a-1", "a-2", "a-3"]; + chosen = ["a-1"]; + fallbackSettings = { models: ["a-2"], pollMs: 45_000 }; + failFallbackPut = false; + v2Settings = { enabled: true, multiAgentMode: "v2", multiAgentModeHintText: null, keepNativeChatGptOnV1: false }; + preferredModel = null; + fallbackGetGate = null; + Object.defineProperty(globalThis, "fetch", { + configurable: true, + value: async (input: RequestInfo | URL, init?: RequestInit) => { + const path = new URL(String(input), "http://localhost/").pathname; + const method = init?.method ?? "GET"; + requests.push({ path, method, init }); + // Match agent-settings-routes: fallback uses models, roster uses chosen/applied. + if (path === FALLBACK_PATH && method === "GET") { + if (fallbackGetGate) await fallbackGetGate; + return Response.json({ ...fallbackSettings, available }); + } + if (path === FALLBACK_PATH && method === "PUT") { + if (failFallbackPut) return Response.json({ error: "Fallback settings could not be persisted" }, { status: 500 }); + fallbackSettings = JSON.parse(String(init?.body)) as FallbackSettings; + return Response.json({ ok: true, ...fallbackSettings }); + } + if (path === ROSTER_PATH && method === "GET") return Response.json({ available, chosen }); + if (path === ROSTER_PATH && method === "PUT") { + chosen = (JSON.parse(String(init?.body)) as { models: string[] }).models; + return Response.json({ applied: chosen }); + } + if (path === "/api/v2" && method === "GET") { + return Response.json(v2Settings); + } + if (path === "/api/injection-model" && method === "GET") { + return Response.json({ + model: preferredModel, + effort: null, + available: [ + { provider: "openai", model: "gpt-5.4", namespaced: "gpt-5.4" }, + { provider: "anthropic", model: "claude-sonnet-4-6", namespaced: "anthropic/claude-sonnet-4-6" }, + ], + efforts: [], + }); + } + throw new Error(`Unexpected request: ${method} ${path}`); + }, + }); + container = testWindow.document.createElement("div") as unknown as HTMLElement; + testWindow.document.body.appendChild(container); +}); + +afterEach(async () => { + try { + if (root) { + const current = root; + await act(async () => { current.unmount(); }); + root = null; + } + } finally { + clearClientResourceStoresForTests(); + testWindow.close(); + for (const key of globals) { + const descriptor = previousGlobals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + } +}); + +async function mount() { + // Match sibling input tests: initialize ReactDOM's event support after installing the DOM. + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(container); + root.render(); + }); + expect(requests.some(request => request.path === FALLBACK_PATH && request.method === "GET")).toBe(true); + expect(editor()).toBeTruthy(); +} + +function editor(): HTMLElement { + const element = container.querySelector(".swi-fallback-editor"); + if (!element) throw new Error("Fallback editor not found"); + return element; +} + +function rows(): HTMLElement[] { + return Array.from(editor().querySelectorAll(".swi-fallback-row")); +} + +function expectOrder(models: string[]) { + expect(rows()).toHaveLength(models.length); + models.forEach((model, index) => { + // The model span can also contain the unavailable-model warning. + expect(rows()[index]?.querySelector("span")?.textContent?.trim().startsWith(`${index + 1}. ${model}`)).toBe(true); + expect(rowButton(index, "sub.removeAria", model)).toBeTruthy(); + }); +} + +function labelledButton(scope: ParentNode, label: string): HTMLButtonElement { + const button = Array.from(scope.querySelectorAll("button")) + .find(candidate => candidate.getAttribute("aria-label") === label); + if (!button) throw new Error(`Button not found: ${label}`); + return button; +} + +function rowButton(index: number, key: "sub.moveUp" | "sub.moveDown" | "sub.removeAria", model: string) { + const row = rows()[index]; + if (!row) throw new Error(`Fallback row not found: ${index}`); + return labelledButton(row, en[key].replace("{m}", model)); +} + +function saveButton(scope: ParentNode = editor()): HTMLButtonElement { + const button = Array.from(scope.querySelectorAll("button")) + .find(candidate => candidate.textContent?.trim() === en["common.save"]); + if (!button) throw new Error("Save button not found"); + return button; +} + +async function click(button: HTMLButtonElement) { + expect(button.disabled).toBe(false); + await act(async () => { button.click(); }); +} + +async function addFallback(model: string) { + const trigger = labelledButton(editor(), en["sub.fallbackAdd"]); + expect(trigger.getAttribute("role")).toBe("combobox"); + await click(trigger); + // Select portals its listbox into document.body, outside the page container. + const listbox = testWindow.document.getElementById(trigger.getAttribute("aria-controls") ?? ""); + if (!listbox) throw new Error("Fallback model listbox not found"); + const option = Array.from(listbox.querySelectorAll('[role="option"]')) + .find(candidate => candidate.textContent?.trim() === model); + if (!option) throw new Error(`Fallback option not found: ${model}`); + await click(option as unknown as HTMLButtonElement); + expect(trigger.getAttribute("aria-expanded")).toBe("false"); +} + +function pollInput(): HTMLInputElement { + const input = editor().querySelector('input[type="number"]'); + if (!input) throw new Error("Fallback polling interval input not found"); + return input; +} + +async function changePollMs(value: number) { + await act(async () => { + const input = pollInput(); + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!.call(input, String(value)); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + input.dispatchEvent(new testWindow.Event("change", { bubbles: true })); + }); +} + +function putBodies(path = FALLBACK_PATH): unknown[] { + return requests.filter(request => request.path === path && request.method === "PUT") + .map(request => JSON.parse(String(request.init?.body)) as unknown); +} + +function cached(): CachedSubagents | null { + return readSessionListCache(CACHE_KEY); +} + +test("preserves an unavailable configured fallback ID on load and save", async () => { + fallbackSettings = { models: [UNAVAILABLE_MODEL, "a-2"], pollMs: 45_000 }; + expect(available).not.toContain(UNAVAILABLE_MODEL); + await mount(); + + expectOrder([UNAVAILABLE_MODEL, "a-2"]); + expect(rows()[0]?.textContent).toContain(en["sub.fallbackUnavailable"]); + expect(rows()[1]?.textContent).not.toContain(en["sub.fallbackUnavailable"]); + expect(cached()?.fallback).toEqual([UNAVAILABLE_MODEL, "a-2"]); + await click(saveButton()); + expect(putBodies()).toEqual([{ models: [UNAVAILABLE_MODEL, "a-2"], pollMs: 45_000 }]); + expectOrder([UNAVAILABLE_MODEL, "a-2"]); + expect(container.textContent).toContain(en["sub.fallbackSaved"]); +}); + +test("adds, reorders in both directions, and removes fallback models before saving their exact order", async () => { + await mount(); + await addFallback("a-3"); + expectOrder(["a-2", "a-3"]); + expect(rowButton(0, "sub.moveUp", "a-2").disabled).toBe(true); + expect(rowButton(1, "sub.moveDown", "a-3").disabled).toBe(true); + + await click(rowButton(1, "sub.moveUp", "a-3")); + expectOrder(["a-3", "a-2"]); + await click(rowButton(0, "sub.moveDown", "a-3")); + expectOrder(["a-2", "a-3"]); + await addFallback("a-1"); + await click(rowButton(0, "sub.removeAria", "a-2")); + expectOrder(["a-3", "a-1"]); + expect(putBodies()).toEqual([]); + + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-3", "a-1"], pollMs: 45_000 }]); + expect(putBodies(ROSTER_PATH)).toEqual([]); +}); + +test("removes only the selected duplicate fallback occurrence by index", async () => { + fallbackSettings.models = ["a-2", "a-1", "a-2", "a-3"]; + await mount(); + expectOrder(["a-2", "a-1", "a-2", "a-3"]); + + await click(rowButton(2, "sub.removeAria", "a-2")); + expectOrder(["a-2", "a-1", "a-3"]); + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-2", "a-1", "a-3"], pollMs: 45_000 }]); +}); + +test("a failed fallback PUT retains the editable draft and leaves the committed cache unchanged", async () => { + await mount(); + const committed = cached(); + expect(committed).toEqual({ available, chosen: ["a-1"], fallback: ["a-2"], pollMs: 45_000 }); + await addFallback("a-3"); + await changePollMs(90_000); + failFallbackPut = true; + await click(saveButton()); + + expect(putBodies()).toEqual([{ models: ["a-2", "a-3"], pollMs: 90_000 }]); + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("90000"); + expect(container.textContent).toContain("Fallback settings could not be persisted"); + expect(container.textContent).not.toContain(en["sub.fallbackSaved"]); + expect(saveButton().disabled).toBe(false); + expect(cached()).toEqual(committed); + + failFallbackPut = false; + await click(saveButton()); + expect(putBodies()).toEqual([ + { models: ["a-2", "a-3"], pollMs: 90_000 }, + { models: ["a-2", "a-3"], pollMs: 90_000 }, + ]); + expect(cached()?.fallback).toEqual(["a-2", "a-3"]); + expect(cached()?.pollMs).toBe(90_000); +}); + +test("a successful fallback save updates committed session data without committing a roster draft", async () => { + await mount(); + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + await addFallback("a-3"); + await changePollMs(120_000); + await click(saveButton()); + + expect(putBodies()).toEqual([{ models: ["a-2", "a-3"], pollMs: 120_000 }]); + expect(putBodies(ROSTER_PATH)).toEqual([]); + expect(cached()).toEqual({ available, chosen: ["a-1"], fallback: ["a-2", "a-3"], pollMs: 120_000 }); + expectOrder(["a-2", "a-3"]); + expect(container.querySelectorAll(".swi-featured-row").length).toBe(2); +}); + +test("independent roster Save never caches an unsaved fallback draft", async () => { + await mount(); + await addFallback("a-3"); + await changePollMs(90_000); + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + const rosterSaveRow = container.querySelector(".swi-save-row"); + if (!rosterSaveRow) throw new Error("Roster Save row not found"); + await click(saveButton(rosterSaveRow)); + + expect(putBodies(ROSTER_PATH)).toEqual([{ models: ["a-1", "a-3"] }]); + expect(putBodies()).toEqual([]); + expect(cached()).toEqual({ available, chosen: ["a-1", "a-3"], fallback: ["a-2"], pollMs: 45_000 }); + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("90000"); + + // Saving the fallback afterward must retain the already committed roster. + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-2", "a-3"], pollMs: 90_000 }]); + expect(cached()).toEqual({ available, chosen: ["a-1", "a-3"], fallback: ["a-2", "a-3"], pollMs: 90_000 }); +}); + +test("remount shows the committed fallback and roster while a fresh fallback GET is pending", async () => { + await mount(); + await addFallback("a-3"); + await changePollMs(120_000); + await click(saveButton()); + + // A later roster save must not commit these newer fallback edits. + await click(rowButton(0, "sub.removeAria", "a-2")); + await changePollMs(90_000); + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + const rosterSaveRow = container.querySelector(".swi-save-row"); + if (!rosterSaveRow) throw new Error("Roster Save row not found"); + await click(saveButton(rosterSaveRow)); + expectOrder(["a-3"]); + expect(pollInput().value).toBe("90000"); + + const current = root!; + await act(async () => { current.unmount(); }); + root = null; + // Keep sessionStorage, but discard the resource store so it cannot mask a stale session seed. + clearClientResourceStoresForTests(); + const getsBefore = requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET").length; + let releaseGet!: () => void; + fallbackGetGate = new Promise(resolve => { releaseGet = resolve; }); + try { + await mount(); + expect(requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET")).toHaveLength(getsBefore + 1); + // These assertions run before the fresh GET can return any data. + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("120000"); + expect(Array.from(container.querySelectorAll(".swi-featured-name"), node => node.textContent?.trim())) + .toEqual(["a-1", "a-3"]); + expect(cached()).toEqual({ available, chosen: ["a-1", "a-3"], fallback: ["a-2", "a-3"], pollMs: 120_000 }); + } finally { + await act(async () => { releaseGet(); }); + fallbackGetGate = null; + } + expectOrder(["a-2", "a-3"]); + expect(pollInput().value).toBe("120000"); +}); + +test("invalid polling intervals disable Save without a PUT or cache mutation, and a valid interval recovers", async () => { + await mount(); + const committed = cached(); + for (const interval of [0, 4_999, 600_001, 5_000.5]) { + await changePollMs(interval); + expect(pollInput().getAttribute("aria-invalid")).toBe("true"); + expect(editor().querySelector('[role="alert"]')?.textContent).toContain(en["sub.fallbackPollInvalid"]); + expect(saveButton().disabled).toBe(true); + await act(async () => { saveButton().click(); }); + expect(putBodies()).toEqual([]); + expect(cached()).toEqual(committed); + } + + await changePollMs(5_000); + expect(pollInput().getAttribute("aria-invalid")).toBe("false"); + expect(editor().querySelector('[role="alert"]')).toBeNull(); + await click(saveButton()); + expect(putBodies()).toEqual([{ models: ["a-2"], pollMs: 5_000 }]); + expect(cached()?.pollMs).toBe(5_000); +}); + +const compatibilityCases: Array<{ + name: string; + model: string; + enabled: boolean; + mode: V2Settings["multiAgentMode"]; + keepNative: boolean; + warning: boolean; +}> = [ + { name: "native preferred model", model: "gpt-5.4", enabled: true, mode: "v2", keepNative: false, warning: false }, + { name: "routed preferred model on the default surface", model: "anthropic/claude-sonnet-4-6", enabled: false, mode: "default", keepNative: false, warning: true }, + { name: "routed preferred model on V1", model: "anthropic/claude-sonnet-4-6", enabled: false, mode: "v1", keepNative: false, warning: false }, + { name: "forced V2 preserving native V1 with global V2 disabled", model: "anthropic/claude-sonnet-4-6", enabled: false, mode: "v2", keepNative: true, warning: false }, + { name: "global V2 enabled despite native V1 preservation", model: "anthropic/claude-sonnet-4-6", enabled: true, mode: "v2", keepNative: true, warning: true }, +]; + +test.each(compatibilityCases)("V2 compatibility guidance: $name", async ({ model, enabled, mode, keepNative, warning }) => { + preferredModel = model; + v2Settings = { enabled, multiAgentMode: mode, multiAgentModeHintText: null, keepNativeChatGptOnV1: keepNative }; + await mount(); + + const note = container.querySelector('.swi-v2-compatibility[role="note"]'); + if (warning) { + expect(note).toBeTruthy(); + expect(note?.textContent).toContain(en["sub.v2Compatibility.title"]); + expect(note?.textContent).toContain(en["sub.v2Compatibility.risk"]); + // The response exposes no recovery state: guidance must explicitly say it is unknown. + expect(note?.textContent).toContain(en["sub.v2Compatibility.recoveryUnknown"]); + expect(note?.querySelector("a")?.getAttribute("href")).toBe("https://github.com/lidge-jun/opencodex/issues/92"); + expect(note?.querySelector('[role="switch"], [aria-pressed], input[type="checkbox"]')).toBeNull(); + } else { + expect(note).toBeNull(); + expect(container.textContent).not.toContain(en["sub.v2Compatibility.recoveryUnknown"]); + } + expect(requests.filter(request => request.method !== "GET")).toEqual([]); +}); From 71315281bdbb3131104911508d1cce0f70a8e7d3 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:23:15 +0900 Subject: [PATCH 045/116] docs: pin lane C health wiring handoff [skip ci] --- devlog/_plan/260907_lane_c/030_health.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/devlog/_plan/260907_lane_c/030_health.md b/devlog/_plan/260907_lane_c/030_health.md index 2e01551e34..eaeb4bbcd6 100644 --- a/devlog/_plan/260907_lane_c/030_health.md +++ b/devlog/_plan/260907_lane_c/030_health.md @@ -117,3 +117,7 @@ index 639f1b34c..48bb7b539 100644 ``` + +## Main-owned route handoff + +At current dev, settings GET uses `startupHealth: await readStartupHealth(config)` at `src/server/management/config-routes.ts:332`. M changes only this settings read to the exported immediate snapshot and retains the dedicated `/api/startup-health` bounded read. Settings PUT at line 625 is separately present; it must remain reviewed explicitly rather than blindly replaced. C does not modify either call site. From 2b158e9bada538a6f3779ae47154ba150554218b Mon Sep 17 00:00:00 2001 From: luvs01 <27862058+luvs01@users.noreply.github.com> Date: Mon, 7 Sep 2026 10:50:46 +0900 Subject: [PATCH 046/116] fix(vision): bound the Anthropic vision sidecar SSE and error bodies [skip ci] (cherry picked from commit 55b009bdec123a79924a9c40c97f94bf49e62591) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- src/vision/anthropic-describe.ts | 48 +++++++++++++++++++++++++-- tests/vision/vision-anthropic.test.ts | 21 ++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) diff --git a/src/vision/anthropic-describe.ts b/src/vision/anthropic-describe.ts index 4f41017ef5..280096f033 100644 --- a/src/vision/anthropic-describe.ts +++ b/src/vision/anthropic-describe.ts @@ -10,6 +10,8 @@ import type { DescribeOutcome, VisionSettings } from "./describe"; const ANTHROPIC_VISION_MAX_TOKENS = 1024; const ALLOWED_IMAGE_MIME = new Set(["image/png", "image/jpeg", "image/jpg", "image/webp", "image/gif"]); const MAX_IMAGE_BYTES = 20 * 1024 * 1024; +/** Bound the sidecar SSE stream and its untrusted error body; the description is clamped downstream. */ +const MAX_SIDECAR_RESPONSE_BYTES = 64 * 1024; const DESCRIBE_INSTRUCTION = "You are a vision describer for a text-only model that cannot see the image. Describe the image " + "thoroughly and factually so that model can fully reason about it: transcribe any visible text " + @@ -43,6 +45,34 @@ function buildImageBlock(imageUrl: string): { block?: AnthropicImageBlock; error return { error: "unsupported image URL scheme (expected data: or https:)" }; } +/** Read at most `MAX_SIDECAR_RESPONSE_BYTES` of an untrusted upstream body, then stop reading. */ +async function readBoundedText(res: Response): Promise { + if (!res.body) return ""; + const reader = res.body.getReader(); + const decoder = new TextDecoder(); + let out = ""; + let seen = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + const remaining = MAX_SIDECAR_RESPONSE_BYTES - seen; + const accepted = value.byteLength <= remaining ? value : value.subarray(0, remaining); + seen += accepted.byteLength; + out += decoder.decode(accepted, { stream: true }); + if (seen >= MAX_SIDECAR_RESPONSE_BYTES) { + try { void reader.cancel("vision sidecar error body byte limit reached").catch(() => undefined); } + catch { /* best-effort body teardown */ } + break; + } + } + out += decoder.decode(); + } catch { + /* a failed error-body read must not mask the HTTP status we are about to report */ + } + return out; +} + /** Fold Anthropic Messages text deltas into one description. Malformed frames are ignored. */ export async function parseAnthropicVisionSSE(res: Response): Promise { if (!res.body) return { text: "", error: "anthropic vision sidecar returned no response body" }; @@ -52,6 +82,7 @@ export async function parseAnthropicVisionSSE(res: Response): Promise { let dataLine = ""; @@ -76,12 +107,24 @@ export async function parseAnthropicVisionSSE(res: Response): Promise= MAX_SIDECAR_RESPONSE_BYTES) { + // Keep the frames folded above, drop the unterminated tail, and do not wait on teardown. + try { void reader.cancel("vision sidecar response byte limit reached").catch(() => undefined); } + catch { /* best-effort body teardown */ } + buffer = ""; + break; + } } buffer = (buffer + decoder.decode()).replace(/\r\n/g, "\n"); if (buffer.trim()) processFrame(buffer); @@ -164,7 +207,8 @@ export async function describeImageAnthropic( { abortSignal: linkedSignal.signal, label: "vision-sidecar-anthropic" }, ); if (!res.ok) { - const responseText = await res.text().catch(() => ""); + // The body is untrusted and only feeds one auth-failure message, so read a bounded prefix. + const responseText = await readBoundedText(res); console.warn(`[vision] anthropic sidecar HTTP ${res.status} (${Date.now() - startedAt}ms)`); if (res.status === 401) { return { text: "", error: `anthropic vision sidecar auth failed: ${publicOAuthAuthenticationErrorMessage(new Error(responseText))}` }; diff --git a/tests/vision/vision-anthropic.test.ts b/tests/vision/vision-anthropic.test.ts index 086e5df7bb..05df35662e 100644 --- a/tests/vision/vision-anthropic.test.ts +++ b/tests/vision/vision-anthropic.test.ts @@ -225,6 +225,27 @@ describe("Anthropic vision executor", () => { expect(result).toEqual({ text: "first second" }); }); + test("an unterminated frame cannot buffer the stream without bound", async () => { + // A sidecar that never emits a frame separator: without a cap the parser accumulates the + // whole response in memory before it can fold anything. + let produced = 0; + let cancelled = false; + const chunk = new TextEncoder().encode(`data: {"filler":"${"x".repeat(64 * 1024)}"}`); + const body = new ReadableStream({ + pull(c) { + if (produced > 8 * 1024 * 1024) { c.close(); return; } + produced += chunk.byteLength; + c.enqueue(chunk); + }, + cancel() { cancelled = true; }, + }); + const out = await parseAnthropicVisionSSE(new Response(body, { status: 200 })); + expect(cancelled).toBe(true); + // The cap stops the read long before the producer would have finished on its own. + expect(produced).toBeLessThan(1024 * 1024); + expect(out.text).toBe(""); + }); + test("malformed and terminal-error streams degrade to explicit errors", async () => { const malformed = await parseAnthropicVisionSSE(sseResponse(["{not-json", { type: "message_stop" }])); expect(malformed.text).toBe(""); From 9d8d11abdee0151c2a283ff4c3ace728a02a0455 Mon Sep 17 00:00:00 2001 From: x3M3x <98298256+x3M3x@users.noreply.github.com> Date: Mon, 7 Sep 2026 18:24:13 +0900 Subject: [PATCH 047/116] fix(service): carry startup-health cache portion of #3863 [skip ci] Path-filtered source commit: 960621616c439e69b967981c290f2377ba9465fa. Config-route wiring excluded under lane ownership. Co-authored-by: x3M3x <98298256+x3M3x@users.noreply.github.com> (cherry picked from commit 197bf2e2bff362b9a135389741f1acf91670ded0) --- src/server/startup-health-cache.ts | 16 +++++++++++ tests/service/autostart-health.test.ts | 39 +++++++++++++++++++++++++- 2 files changed, 54 insertions(+), 1 deletion(-) diff --git a/src/server/startup-health-cache.ts b/src/server/startup-health-cache.ts index 70380eb4ed..571d81b549 100644 --- a/src/server/startup-health-cache.ts +++ b/src/server/startup-health-cache.ts @@ -50,6 +50,22 @@ export interface StartupHealthCacheDeps { ) => Promise; } +/** + * Return the last completed probe immediately and refresh it in the background. + * + * Settings are consumed by several dashboard controls. They must not block on a + * Windows service-manager probe; the dedicated /api/startup-health route owns + * the fresh, bounded diagnostic read. + */ +export function getStartupHealthSnapshot( + config: Pick, + deps: StartupHealthCacheDeps = {}, +): StartupHealth { + const now = deps.now ?? Date.now; + if (!cached || now() - cached.timestamp >= CACHE_TTL_MS) refreshInBackground(config, deps); + return cached ? markStartupHealthDiagnosticStale(cached.value) : conservativeFallback(config); +} + export function markStartupHealthDiagnosticStale(value: StartupHealth): StartupHealth { if (!value.localRoutingDependency) return { ...value, diagnosticStale: true }; return { diff --git a/tests/service/autostart-health.test.ts b/tests/service/autostart-health.test.ts index 639f1b34c3..48bb7b5395 100644 --- a/tests/service/autostart-health.test.ts +++ b/tests/service/autostart-health.test.ts @@ -3,7 +3,7 @@ import { deriveStartupHealth, formatStartupRoutingDetail, startupHealthSummary } import { unusedProxyWarningLines } from "../../src/cli/status"; import { classifyCodexRouting, hasInjectedCodexRouting } from "../../src/codex/inject"; import { handleManagementAPI } from "../../src/server/management-api"; -import { getCachedStartupHealth, invalidateStartupHealthCache, markStartupHealthDiagnosticStale } from "../../src/server/startup-health-cache"; +import { getCachedStartupHealth, getStartupHealthSnapshot, invalidateStartupHealthCache, markStartupHealthDiagnosticStale } from "../../src/server/startup-health-cache"; import type { OcxConfig } from "../../src/types"; const base = { @@ -277,6 +277,43 @@ describe("Codex startup health", () => { await pendingProbe; invalidateStartupHealthCache(); }); + + test("settings snapshot starts a probe without waiting for it", async () => { + invalidateStartupHealthCache(); + let releaseProbe!: (value: ReturnType) => void; + const pendingProbe = new Promise>(resolve => { + releaseProbe = resolve; + }); + + const health = getStartupHealthSnapshot( + { codexAutoStart: true }, + { probe: async () => pendingProbe }, + ); + + expect(health.diagnosticStale).toBe(true); + releaseProbe(deriveStartupHealth({ ...base, routingKind: "native" })); + await pendingProbe; + invalidateStartupHealthCache(); + }); + + test("settings GET uses the non-blocking startup-health snapshot in production", async () => { + invalidateStartupHealthCache(); + const url = new URL("http://localhost/api/settings"); + + const response = await Promise.race([ + handleManagementAPI( + new Request(url), + url, + { port: 10100, providers: {}, defaultProvider: "openai", codexAutoStart: true } as OcxConfig, + ), + new Promise(resolve => setTimeout(() => resolve(null), 100)), + ]); + + expect(response?.status).toBe(200); + const body = await response!.json() as { startupHealth?: { diagnosticStale?: boolean } }; + expect(body.startupHealth?.diagnosticStale).toBe(true); + invalidateStartupHealthCache(); + }); }); import { ManagementRequest as Request } from "../helpers/management-auth"; From 734d41c528039a29b4002d455405afacfecf922c Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:31:54 +0900 Subject: [PATCH 048/116] fix(gui): retain unapplied Desktop status across settings polls [skip ci] Co-authored-by: RobinBially <7304732+RobinBially@users.noreply.github.com> --- gui/src/pages/use-dashboard-data.ts | 7 ++++++- gui/tests/vision-sidecar-dashboard.test.tsx | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/gui/src/pages/use-dashboard-data.ts b/gui/src/pages/use-dashboard-data.ts index e87e6494bd..8634e7caa8 100644 --- a/gui/src/pages/use-dashboard-data.ts +++ b/gui/src/pages/use-dashboard-data.ts @@ -361,7 +361,12 @@ export function useDashboardData(apiBase: string) { useEffect(() => { const data = settingsPoll.data; if (!data) return; - if (data.settings !== undefined) setSettings(data.settings); + if (data.settings !== undefined) { + const next = data.settings; + // GET settings does not report application receipts. Keep a saved preference's + // pending indication until an affirmative sync result clears it. + setSettings(prev => ({ ...next, catalogRefreshPending: prev?.catalogRefreshPending === true || next.catalogRefreshPending })); + } // Latest-wins: only seed from settings when no newer dedicated probe has committed // while this settings poll was in flight. Always merge against the live ref. if ( diff --git a/gui/tests/vision-sidecar-dashboard.test.tsx b/gui/tests/vision-sidecar-dashboard.test.tsx index 386196cc77..738ed866e6 100644 --- a/gui/tests/vision-sidecar-dashboard.test.tsx +++ b/gui/tests/vision-sidecar-dashboard.test.tsx @@ -13,6 +13,7 @@ import { DashboardSidecarPanels } from "../src/pages/dashboard-overview-sections import type { SidecarData, SidecarPatch } from "../src/pages/dashboard-shared"; import { mergeSidecarSetting } from "../src/pages/dashboard-shared"; import { useDashboardData } from "../src/pages/use-dashboard-data"; +import { setClientResourceData } from "../src/client-resource"; const globals = ["document", "window", "navigator", "IS_REACT_ACT_ENVIRONMENT"] as const; let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; @@ -479,6 +480,14 @@ test.each(["skipped", "catalog-only", "applied"])("Desktop preference pending st expect(latest?.settings?.codexDesktopAuthless).toBe(true); expect(latest?.settings?.catalogRefreshPending).toBe(syncStatus !== "applied"); expect(latest?.syncResult?.status).toBe(syncStatus); + // A fresh settings poll has no application receipt and cannot erase pending. + await act(async () => { + setClientResourceData(`dashboard-settings:${apiBase}`, { + settings: { codexAutoStart: true, codexDesktopAuthless: true, port: 10100, hostname: "127.0.0.1" }, + }); + }); + expect(latest?.settings?.codexDesktopAuthless).toBe(true); + expect(latest?.settings?.catalogRefreshPending === true).toBe(syncStatus !== "applied"); } finally { await act(async () => { root?.unmount(); }); root = null; From ffcd7abbaa210fad6ab235047d190248c5d6d52d Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:36:13 +0900 Subject: [PATCH 049/116] fix(gui): guard fallback hydration races and preserve row focus [skip ci] Co-authored-by: x3M3x <98298256+x3M3x@users.noreply.github.com> --- .../SubagentDelegationSection.tsx | 40 ++++- gui/src/pages/Subagents.tsx | 42 +++-- gui/tests/subagents-fallback.test.tsx | 151 +++++++++++++++++- 3 files changed, 214 insertions(+), 19 deletions(-) diff --git a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx index dbbbd99948..6fe043461c 100644 --- a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx +++ b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx @@ -6,7 +6,7 @@ * better next to the roster it affects: the roster picks who may be called, this picks who * gets called first. */ -import { useState } from "react"; +import { useLayoutEffect, useRef, useState } from "react"; import { Select, Tooltip } from "../../ui"; import { IconArrowDown, IconArrowUp, IconInfo, IconX } from "../../icons"; import { useT, type TKey } from "../../i18n/shared"; @@ -63,12 +63,36 @@ export default function SubagentDelegationSection({ const nativeMayUseV2 = ultraMode.enabled || (ultraMode.multiAgentMode !== "v1" && !(ultraMode.multiAgentMode === "v2" && ultraMode.keepNativeChatGptOnV1)); const showV2Compatibility = !ultraLoadFailed && ultraMode.loaded === true && routedPreferred && nativeMayUseV2; + const fallbackControlsRef = useRef(null); + const nextRowId = useRef(0); + const rowIdentity = useRef>([]); + // Reuse each configured occurrence across reorder; duplicates have distinct IDs. + if (rowIdentity.current.length !== fallback.length || rowIdentity.current.some((row, i) => row.model !== fallback[i])) { + const remaining = [...rowIdentity.current]; + rowIdentity.current = fallback.map(modelName => { + const old = remaining.findIndex(row => row.model === modelName); + return old >= 0 ? remaining.splice(old, 1)[0] : { model: modelName, id: nextRowId.current++ }; + }); + } + const pendingFocus = useRef<{ row: number; action: string } | null>(null); + useLayoutEffect(() => { + const target = pendingFocus.current; + if (!target) return; + pendingFocus.current = null; + const row = fallbackControlsRef.current?.querySelectorAll(".swi-fallback-row")[target.row]; + const action = row?.querySelector(`button[data-action="${target.action}"]:not(:disabled)`) + ?? row?.querySelector("button:not(:disabled)") + ?? fallbackControlsRef.current?.querySelector('button[role="combobox"]'); + action?.focus(); + }, [fallback]); const validPollMs = Number.isInteger(fallbackPollMs) && fallbackPollMs >= 5000 && fallbackPollMs <= 600000; const moveFallback = (index: number, direction: -1 | 1) => { const next = [...fallback]; const target = index + direction; if (fallbackBusy || target < 0 || target >= next.length) return; [next[index], next[target]] = [next[target], next[index]]; + [rowIdentity.current[index], rowIdentity.current[target]] = [rowIdentity.current[target], rowIdentity.current[index]]; + pendingFocus.current = { row: target, action: direction === -1 ? "up" : "down" }; onFallbackChange(next); }; @@ -134,16 +158,20 @@ export default function SubagentDelegationSection({
{t("sub.fallbackLabel")}
{t("sub.fallbackHint")}
-
+
{fallback.map((modelName, index) => ( -
+
{index + 1}. {modelName} {!availableModels.includes(modelName) && {t("sub.fallbackUnavailable")}} - - - + + +
))} diff --git a/gui/src/pages/Subagents.tsx b/gui/src/pages/Subagents.tsx index cbdb138e33..cf9f1b33d0 100644 --- a/gui/src/pages/Subagents.tsx +++ b/gui/src/pages/Subagents.tsx @@ -8,7 +8,7 @@ import { useDataSurface } from "../data-surface"; import { DataSurfaceSkeleton } from "../components/data-surface"; import { useSubagentDelegation, type UltraModePatch, type UltraModeState } from "./use-subagent-delegation"; -type CachedSubagents = { available: string[]; chosen: string[]; fallback: string[]; pollMs: number }; +type CachedSubagents = { available: string[]; chosen: string[]; fallback?: string[]; pollMs?: number }; function seedSubagents(cacheKey: string): CachedSubagents | null { return readSessionListCache(cacheKey); @@ -22,6 +22,9 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const [fallback, setFallback] = useState(() => cached?.fallback ?? []); const [fallbackPollMs, setFallbackPollMs] = useState(() => cached?.pollMs ?? 60000); const [fallbackBusy, setFallbackBusy] = useState(false); + const [fallbackLoaded, setFallbackLoaded] = useState(() => Array.isArray(cached?.fallback) && Number.isInteger(cached?.pollMs)); + const fallbackRevision = useRef(0); + const rosterRevision = useRef(0); const fallbackSaveInFlight = useRef(false); const committed = useRef(cached); const [status, setStatus] = useState(""); @@ -125,6 +128,8 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const loadSubagents = useCallback(async (signal?: AbortSignal): Promise => { // The resource layer's deadline abort must reach the wire — a signal dropped // here is a store that can only settle by race timeout. + const rosterReadRevision = rosterRevision.current; + const fallbackReadRevision = fallbackRevision.current; const [rosterRes, fallbackRes] = await Promise.all([ fetch(`${apiBase}/api/subagent-models`, { signal }), fetch(`${apiBase}/api/subagent-model-fallback`, { signal }), @@ -134,18 +139,23 @@ export default function Subagents({ apiBase }: { apiBase: string }) { if (!response || !fallbackResponse) throw new Error(t("sub.loadFail")); const available = response.available ?? fallbackResponse.available ?? []; const availableSet = new Set(available); + const rosterCurrent = rosterReadRevision === rosterRevision.current && !saveInFlight.current; + const fallbackCurrent = fallbackReadRevision === fallbackRevision.current && !fallbackSaveInFlight.current; const next = { available, - chosen: (response.chosen ?? []).filter(model => availableSet.has(model)), + chosen: rosterCurrent ? (response.chosen ?? []).filter(model => availableSet.has(model)) : committed.current?.chosen ?? [], // Configured targets remain editable even when discovery no longer advertises them. - fallback: fallbackResponse.models ?? [], - pollMs: fallbackResponse.pollMs ?? 60000, + fallback: fallbackCurrent ? fallbackResponse.models ?? [] : committed.current?.fallback ?? [], + pollMs: fallbackCurrent ? fallbackResponse.pollMs ?? 60000 : committed.current?.pollMs ?? 60000, }; if (signal?.aborted) throw signal.reason; committed.current = next; - setChosen(next.chosen); - setFallback(next.fallback); - setFallbackPollMs(next.pollMs); + if (rosterCurrent) setChosen(next.chosen); + if (fallbackCurrent) { + setFallback(next.fallback); + setFallbackPollMs(next.pollMs); + setFallbackLoaded(true); + } writeSessionListCache(cacheKey, next); return next; }, [apiBase, cacheKey, t]); @@ -166,10 +176,12 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const toggle = (m: string) => { if (busy) return; setStatus(""); + rosterRevision.current += 1; setChosen(prev => prev.includes(m) ? prev.filter(x => x !== m) : (prev.length >= FEATURED_MAX ? prev : [...prev, m])); }; const move = (i: number, dir: -1 | 1) => { if (busy) return; + rosterRevision.current += 1; setChosen(prev => { const next = [...prev]; const j = i + dir; @@ -182,6 +194,7 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const save = async () => { if (busy || saveInFlight.current) return; saveInFlight.current = true; + rosterRevision.current += 1; setBusy(true); setStatus(""); try { @@ -191,9 +204,11 @@ export default function Subagents({ apiBase }: { apiBase: string }) { body: JSON.stringify({ models: chosen }), }); const d = await readJsonOrThrow<{ applied?: string[] }>(r, t("sub.saveFailed")); + rosterRevision.current += 1; const applied = d?.applied ?? chosen; if (d?.applied) setChosen(d.applied); - const next = { available, chosen: applied, fallback: committed.current?.fallback ?? [], pollMs: committed.current?.pollMs ?? 60000 }; + // A legacy roster-only seed does not prove that an empty fallback was loaded. + const next = { ...committed.current, available, chosen: applied }; committed.current = next; writeSessionListCache(cacheKey, next); setOk(true); @@ -208,8 +223,9 @@ export default function Subagents({ apiBase }: { apiBase: string }) { }; const saveFallback = async () => { - if (fallbackSaveInFlight.current || !Number.isInteger(fallbackPollMs) || fallbackPollMs < 5000 || fallbackPollMs > 600000) return; + if (!fallbackLoaded || fallbackSaveInFlight.current || !Number.isInteger(fallbackPollMs) || fallbackPollMs < 5000 || fallbackPollMs > 600000) return; fallbackSaveInFlight.current = true; + fallbackRevision.current += 1; const requestApiBase = apiBase; setFallbackBusy(true); setStatus(""); @@ -222,6 +238,7 @@ export default function Subagents({ apiBase }: { apiBase: string }) { const d = await readJsonOrThrow<{ models?: string[]; pollMs?: number }>(r, t("sub.fallbackSaveFailed")); if (currentUltraApiBase.current !== requestApiBase) return; if (!d || !Array.isArray(d.models) || typeof d.pollMs !== "number") throw new Error(t("sub.fallbackSaveFailed")); + fallbackRevision.current += 1; setFallback(d.models); setFallbackPollMs(d.pollMs); const next = { available, chosen: committed.current?.chosen ?? [], fallback: d.models, pollMs: d.pollMs }; @@ -260,6 +277,7 @@ export default function Subagents({ apiBase }: { apiBase: string }) {
{status && {status}} {state.showError && {t("sub.loadFail")}} + {!fallbackLoaded && state.showError && } { void save(); }} fallback={fallback} fallbackPollMs={fallbackPollMs} - fallbackBusy={fallbackBusy} - onFallbackChange={setFallback} - onFallbackPollMsChange={setFallbackPollMs} + fallbackBusy={fallbackBusy || !fallbackLoaded} + onFallbackChange={models => { fallbackRevision.current += 1; setFallback(models); }} + onFallbackPollMsChange={pollMs => { fallbackRevision.current += 1; setFallbackPollMs(pollMs); }} onFallbackSave={() => { void saveFallback(); }} delegation={{ model: delegation.model, diff --git a/gui/tests/subagents-fallback.test.tsx b/gui/tests/subagents-fallback.test.tsx index 20badc4980..ad794b8261 100644 --- a/gui/tests/subagents-fallback.test.tsx +++ b/gui/tests/subagents-fallback.test.tsx @@ -16,7 +16,7 @@ const globals = [ "document", "window", "navigator", "localStorage", "sessionStorage", "fetch", "IS_REACT_ACT_ENVIRONMENT", ] as const; -type CachedSubagents = { available: string[]; chosen: string[]; fallback: string[]; pollMs: number }; +type CachedSubagents = { available: string[]; chosen: string[]; fallback?: string[]; pollMs?: number }; type FallbackSettings = { models: string[]; pollMs: number }; type SentRequest = { path: string; method: string; init?: RequestInit }; type V2Settings = { @@ -38,6 +38,7 @@ let failFallbackPut: boolean; let v2Settings: V2Settings; let preferredModel: string | null; let fallbackGetGate: Promise | null; +let pendingFallbackResponse: Promise | null; beforeEach(() => { clearClientResourceStoresForTests(); @@ -61,6 +62,7 @@ beforeEach(() => { v2Settings = { enabled: true, multiAgentMode: "v2", multiAgentModeHintText: null, keepNativeChatGptOnV1: false }; preferredModel = null; fallbackGetGate = null; + pendingFallbackResponse = null; Object.defineProperty(globalThis, "fetch", { configurable: true, value: async (input: RequestInfo | URL, init?: RequestInit) => { @@ -69,6 +71,11 @@ beforeEach(() => { requests.push({ path, method, init }); // Match agent-settings-routes: fallback uses models, roster uses chosen/applied. if (path === FALLBACK_PATH && method === "GET") { + if (pendingFallbackResponse) { + const pending = pendingFallbackResponse; + pendingFallbackResponse = null; + return pending; + } if (fallbackGetGate) await fallbackGetGate; return Response.json({ ...fallbackSettings, available }); } @@ -250,6 +257,51 @@ test("adds, reorders in both directions, and removes fallback models before savi expect(putBodies(ROSTER_PATH)).toEqual([]); }); +test("keyboard moves retain row focus and removal moves focus to the next row or add control", async () => { + fallbackSettings.models = ["a-1", "a-2", "a-3"]; + await mount(); + + const activateWithEnter = async (button: HTMLButtonElement) => { + expect(button.disabled).toBe(false); + await act(async () => { + button.focus(); + expect(testWindow.document.activeElement).toBe(button); + button.dispatchEvent(new testWindow.KeyboardEvent("keydown", { key: "Enter", code: "Enter", bubbles: true })); + // happy-dom does not synthesize native button activation from Enter. Supply the + // keyboard-generated click (detail 0) explicitly; this test covers focus restoration. + button.dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true, detail: 0 })); + button.dispatchEvent(new testWindow.KeyboardEvent("keyup", { key: "Enter", code: "Enter", bubbles: true })); + }); + }; + + const middleRow = rows()[1]; + await activateWithEnter(rowButton(1, "sub.moveDown", "a-2")); + expectOrder(["a-1", "a-3", "a-2"]); + expect(rows()[2]).toBe(middleRow); + expect(rowButton(2, "sub.moveDown", "a-2").disabled).toBe(true); + // The requested direction is disabled at the boundary; focus an enabled action + // in the moved row, rather than the neighboring row or document.body. + expect(testWindow.document.activeElement).toBe(rowButton(2, "sub.moveUp", "a-2")); + + await activateWithEnter(rowButton(2, "sub.moveUp", "a-2")); + expectOrder(["a-1", "a-2", "a-3"]); + expect(rows()[1]).toBe(middleRow); + expect(testWindow.document.activeElement).toBe(rowButton(1, "sub.moveUp", "a-2")); + + await activateWithEnter(rowButton(1, "sub.removeAria", "a-2")); + expectOrder(["a-1", "a-3"]); + expect(testWindow.document.activeElement).toBe(rowButton(1, "sub.removeAria", "a-3")); + + await activateWithEnter(rowButton(1, "sub.removeAria", "a-3")); + expectOrder(["a-1"]); + expect(testWindow.document.activeElement).toBe(rowButton(0, "sub.removeAria", "a-1")); + + await activateWithEnter(rowButton(0, "sub.removeAria", "a-1")); + expectOrder([]); + expect(testWindow.document.activeElement).toBe(labelledButton(editor(), en["sub.fallbackAdd"])); + expect(putBodies()).toEqual([]); +}); + test("removes only the selected duplicate fallback occurrence by index", async () => { fallbackSettings.models = ["a-2", "a-1", "a-2", "a-3"]; await mount(); @@ -364,6 +416,103 @@ test("remount shows the committed fallback and roster while a fresh fallback GET expect(pollInput().value).toBe("120000"); }); +test("a legacy cache keeps fallback disabled through GET failure, roster Save, and remount", async () => { + const legacyCache = { available, chosen: ["a-1"] }; + testWindow.sessionStorage.setItem(CACHE_KEY, JSON.stringify(legacyCache)); + let releaseGet!: (response: Response) => void; + pendingFallbackResponse = new Promise(resolve => { releaseGet = resolve; }); + + const assertBlocked = async (expectedCache = legacyCache) => { + expect(labelledButton(editor(), en["sub.fallbackAdd"]).disabled).toBe(true); + expect(pollInput().disabled).toBe(true); + expect(saveButton().disabled).toBe(true); + expect(Array.from(editor().querySelectorAll("input, button")) + .every(control => control.disabled)).toBe(true); + await act(async () => { saveButton().click(); }); + expect(putBodies()).toEqual([]); + expect(cached()).toEqual(expectedCache); + expect(cached()).not.toHaveProperty("fallback"); + expect(cached()).not.toHaveProperty("pollMs"); + // A failed read must never turn the page's empty placeholder into a saved empty chain. + expect(fallbackSettings).toEqual({ models: ["a-2"], pollMs: 45_000 }); + }; + + try { + await mount(); + expect(rows()).toHaveLength(0); + expect(pendingFallbackResponse).toBeNull(); + await assertBlocked(); + } finally { + await act(async () => { + releaseGet(Response.json({ error: "Fallback discovery failed" }, { status: 503 })); + }); + } + expect(container.textContent).toContain(en["sub.loadFail"]); + await assertBlocked(); + + await click(labelledButton(container, en["sub.workspace.addToFeatured"].replace("{m}", "a-3"))); + const rosterSaveRow = container.querySelector(".swi-save-row"); + if (!rosterSaveRow) throw new Error("Roster Save row not found"); + await click(saveButton(rosterSaveRow)); + const savedRosterCache = { available, chosen: ["a-1", "a-3"] }; + expect(putBodies(ROSTER_PATH)).toEqual([{ models: ["a-1", "a-3"] }]); + await assertBlocked(savedRosterCache); + + const current = root!; + await act(async () => { current.unmount(); }); + root = null; + clearClientResourceStoresForTests(); + const getsBefore = requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET").length; + pendingFallbackResponse = new Promise(resolve => { releaseGet = resolve; }); + try { + await mount(); + expect(requests.filter(request => request.path === FALLBACK_PATH && request.method === "GET")).toHaveLength(getsBefore + 1); + expect(pendingFallbackResponse).toBeNull(); + await assertBlocked(savedRosterCache); + } finally { + await act(async () => { + releaseGet(Response.json({ error: "Fallback discovery still unavailable" }, { status: 503 })); + }); + } + expect(container.textContent).toContain(en["sub.loadFail"]); + await assertBlocked(savedRosterCache); + expect(putBodies(ROSTER_PATH)).toEqual([{ models: ["a-1", "a-3"] }]); +}); + +test.each([false, true])("a captured old fallback GET cannot overwrite a newer draft or save (saved=%s)", async (saveNewer) => { + const committedA = { available, chosen: ["a-1"], fallback: ["a-2"], pollMs: 45_000 }; + testWindow.sessionStorage.setItem(CACHE_KEY, JSON.stringify(committedA)); + // Serialize A before any edit or PUT. Reading mutable fallbackSettings after the gate + // would accidentally return B and let the stale-response regression pass. + const capturedOldResponse = Response.json({ models: ["a-2"], pollMs: 45_000, available }); + let releaseGet!: (response: Response) => void; + pendingFallbackResponse = new Promise(resolve => { releaseGet = resolve; }); + const committedB = { available, chosen: ["a-1"], fallback: ["a-3"], pollMs: 90_000 }; + + try { + await mount(); + expect(pendingFallbackResponse).toBeNull(); + expectOrder(["a-2"]); + await addFallback("a-3"); + await click(rowButton(0, "sub.removeAria", "a-2")); + await changePollMs(90_000); + if (saveNewer) await click(saveButton()); + expectOrder(["a-3"]); + expect(pollInput().value).toBe("90000"); + expect(cached()).toEqual(saveNewer ? committedB : committedA); + } finally { + await act(async () => { releaseGet(capturedOldResponse); }); + } + + // The delayed GET has now settled; both UI fields and the committed session seed + // must retain their respective newer-draft / newer-save semantics. + expect(capturedOldResponse.bodyUsed).toBe(true); + expectOrder(["a-3"]); + expect(pollInput().value).toBe("90000"); + expect(cached()).toEqual(saveNewer ? committedB : committedA); + expect(putBodies()).toEqual(saveNewer ? [{ models: ["a-3"], pollMs: 90_000 }] : []); +}); + test("invalid polling intervals disable Save without a PUT or cache mutation, and a valid interval recovers", async () => { await mount(); const committed = cached(); From 51b44371860b2ec933d66de1b68ca790be3b81fb Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:23:39 +0900 Subject: [PATCH 050/116] test(web-search): cover bounded partial frames and detached cancellation [skip ci] Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- tests/web-search/web-search-anthropic.test.ts | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/tests/web-search/web-search-anthropic.test.ts b/tests/web-search/web-search-anthropic.test.ts index 33f2616cc2..980eacddaa 100644 --- a/tests/web-search/web-search-anthropic.test.ts +++ b/tests/web-search/web-search-anthropic.test.ts @@ -193,6 +193,26 @@ describe("parseAnthropicSidecarSSE", () => { }); }); +describe("Anthropic sidecar byte boundaries", () => { + test.each([64 * 1024, 80 * 1024])("preserves complete prefix frames at %i bytes without awaiting cancel", async (size) => { + const prefix = `data: ${JSON.stringify({ type: "content_block_delta", delta: { type: "text_delta", text: "prefix 한글" } })}\n\n`; + const tail = `data: ${JSON.stringify({ type: "content_block_delta", delta: { type: "text_delta", text: "discard" } })}`; + const encoder = new TextEncoder(); + // The final unterminated frame is syntactically valid exactly at the cap. + // EOF flush must not fold it after cancellation. + const body = prefix + ":" + "x".repeat(64 * 1024 - encoder.encode(prefix + "\n\n" + tail).length - 1) + "\n\n" + tail; + const bytes = encoder.encode(body + "z".repeat(size - 64 * 1024)); + let cancelled = false; + const res = new Response(new ReadableStream({ + start(controller) { controller.enqueue(bytes); }, + cancel() { cancelled = true; return new Promise(() => {}); }, + }, { highWaterMark: 0 })); + const out = await parseAnthropicSidecarSSE(res); + expect(cancelled).toBe(true); + expect(out).toEqual({ text: "prefix 한글", sources: [] }); + }); +}); + describe("runAnthropicWebSearch request shape", () => { const originalFetch = globalThis.fetch; afterEach(() => { @@ -200,6 +220,21 @@ describe("runAnthropicWebSearch request shape", () => { oauthAccessError = undefined; }); + test.each([401, 503])("bounds HTTP %i error bodies and never awaits non-settling cancellation", async (status) => { + let reads = 0; + let cancelled = false; + globalThis.fetch = (async () => new Response(new ReadableStream({ + pull(controller) { reads += 1; controller.enqueue(new Uint8Array(4096).fill(120)); }, + cancel() { cancelled = true; return new Promise(() => {}); }, + }, { highWaterMark: 0 }), { status })) as typeof fetch; + const out = await runAnthropicWebSearch("bounded fixture", "anthropic", anthropicProvider, + { model: "claude-sonnet-5", reasoning: "low", timeoutMs: 5000, describeImages: false }); + expect(reads).toBe(16); + expect(cancelled).toBe(true); + expect(out.error).toBe(status === 401 + ? `anthropic sidecar auth failed: ${PUBLIC_OAUTH_ERROR}` : "sidecar HTTP 503"); + }); + test("projects OAuth, upstream-auth, and transport failures onto safe public errors", async () => { oauthAccessError = new Error(`credential read failed at ${AUTH_ERROR_CANARY}`); const credentialFailure = await runAnthropicWebSearch( From 8eaa5641902b84bec6c97a94de6c2fe6d810c31d Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:24:12 +0900 Subject: [PATCH 051/116] test(vision): pin capped descriptions and non-settling error-body cancel [skip ci] Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> --- tests/vision/vision-anthropic.test.ts | 28 +++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/vision/vision-anthropic.test.ts b/tests/vision/vision-anthropic.test.ts index 05df35662e..0c0ef3c095 100644 --- a/tests/vision/vision-anthropic.test.ts +++ b/tests/vision/vision-anthropic.test.ts @@ -73,6 +73,34 @@ describe("Anthropic vision executor", () => { oauthAccessError = undefined; }); + test.each([64 * 1024, 80 * 1024])("keeps only complete partial description frames at %i bytes without waiting for cancel", async (size) => { + const prefix = `data: ${JSON.stringify({ type: "content_block_delta", delta: { type: "text_delta", text: "partial 한글" } })}\n\n`; + const tail = `data: ${JSON.stringify({ type: "content_block_delta", delta: { type: "text_delta", text: "discard" } })}`; + const encoder = new TextEncoder(); + const body = prefix + ":" + "x".repeat(64 * 1024 - encoder.encode(prefix + "\n\n" + tail).length - 1) + "\n\n" + tail; + let cancelled = false; + const out = await parseAnthropicVisionSSE(new Response(new ReadableStream({ + start(controller) { controller.enqueue(encoder.encode(body + "z".repeat(size - 64 * 1024))); }, + cancel() { cancelled = true; return new Promise(() => {}); }, + }, { highWaterMark: 0 }))); + expect(cancelled).toBe(true); + expect(out).toEqual({ text: "partial 한글" }); + }); + + test.each([401, 503])("bounds HTTP %i error bodies even when cancellation never settles", async (status) => { + let reads = 0; + let cancelled = false; + globalThis.fetch = (async () => new Response(new ReadableStream({ + pull(controller) { reads += 1; controller.enqueue(new Uint8Array(4096).fill(120)); }, + cancel() { cancelled = true; return new Promise(() => {}); }, + }, { highWaterMark: 0 }), { status })) as typeof fetch; + const out = await describeImageAnthropic(DATA_IMAGE, "high", "", "anthropic-vision-test", anthropicProvider, settings); + expect(reads).toBe(16); + expect(cancelled).toBe(true); + expect(out.error).toBe(status === 401 + ? `anthropic vision sidecar auth failed: ${PUBLIC_OAUTH_ERROR}` : "anthropic vision sidecar HTTP 503"); + }); + test("projects OAuth, upstream-auth, and transport failures onto safe replacement errors", async () => { oauthAccessError = new Error(`credential read failed at ${AUTH_ERROR_CANARY}`); const credentialFailure = await describeImageAnthropic( From 91b54b79bc780011031b00354621cc9fcaef360e Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:25:01 +0900 Subject: [PATCH 052/116] fix(service): preserve fresh health and contain detached probe failures [skip ci] Co-authored-by: x3M3x <98298256+x3M3x@users.noreply.github.com> --- src/server/startup-health-cache.ts | 26 ++++++---- tests/service/autostart-health.test.ts | 72 +++++++++++++++++++++----- 2 files changed, 75 insertions(+), 23 deletions(-) diff --git a/src/server/startup-health-cache.ts b/src/server/startup-health-cache.ts index 571d81b549..2c12e0bbc3 100644 --- a/src/server/startup-health-cache.ts +++ b/src/server/startup-health-cache.ts @@ -62,7 +62,8 @@ export function getStartupHealthSnapshot( deps: StartupHealthCacheDeps = {}, ): StartupHealth { const now = deps.now ?? Date.now; - if (!cached || now() - cached.timestamp >= CACHE_TTL_MS) refreshInBackground(config, deps); + if (cached && now() - cached.timestamp < CACHE_TTL_MS) return cached.value; + refreshInBackground(config, deps); return cached ? markStartupHealthDiagnosticStale(cached.value) : conservativeFallback(config); } @@ -150,15 +151,20 @@ function refreshInBackground( ): void { if (inflight) return; const startedGeneration = generation; - const probe = (deps.probe ?? runProbe)(config).then(value => { - if (startedGeneration === generation) { - cached = { timestamp: (deps.now ?? Date.now)(), value }; - } - return value; - }); - inflight = probe.finally(() => { - if (inflight === probe || startedGeneration === generation) inflight = null; - }); + const probe: Promise = Promise.resolve() + .then(() => (deps.probe ?? runProbe)(config)) + .then(value => { + if (startedGeneration === generation) { + cached = { timestamp: (deps.now ?? Date.now)(), value }; + } + return value; + }) + .catch(() => cached ? markStartupHealthDiagnosticStale(cached.value) : conservativeFallback(config)) + .finally(() => { + // An invalidated probe must never clear the newer generation's flight. + if (inflight === probe) inflight = null; + }); + inflight = probe; } /** Stale-while-revalidate: service-manager probes never hold open a model/UI request. */ diff --git a/tests/service/autostart-health.test.ts b/tests/service/autostart-health.test.ts index 48bb7b5395..213a118e2b 100644 --- a/tests/service/autostart-health.test.ts +++ b/tests/service/autostart-health.test.ts @@ -296,22 +296,68 @@ describe("Codex startup health", () => { invalidateStartupHealthCache(); }); - test("settings GET uses the non-blocking startup-health snapshot in production", async () => { + test("snapshot preserves fresh protection and returns expired protection before a controlled probe settles", async () => { invalidateStartupHealthCache(); - const url = new URL("http://localhost/api/settings"); + let now = 1_000; + const config = { codexAutoStart: true }; + const protectedHealth = deriveStartupHealth({ ...base, serviceInstalled: true, serviceViable: true, serviceEnabled: true, serviceRunning: true }); + await getCachedStartupHealth(config, { now: () => now, probe: async () => protectedHealth, waitForProbe: probe => probe }); + let calls = 0; + let release!: (value: typeof protectedHealth) => void; + const pending = new Promise(resolve => { release = resolve; }); + const deps = { now: () => now, probe: () => { calls += 1; return pending; }, waitForProbe: (probe: Promise) => probe }; + expect(getStartupHealthSnapshot(config, deps)).toBe(protectedHealth); + expect(calls).toBe(0); + now += 30_000; + const snapshot = getStartupHealthSnapshot(config, deps); + expect(snapshot).toMatchObject({ diagnosticStale: true, status: "at-risk", rebootSafe: false }); + // Snapshot has returned while the manually controlled probe remains unresolved. + expect(getStartupHealthSnapshot(config, deps)).toEqual(snapshot); + const fresh = getCachedStartupHealth(config, deps); + const replacement = deriveStartupHealth({ ...base, routingKind: "custom-remote" }); + release(replacement); + expect(await fresh).toBe(replacement); + expect(calls).toBe(1); + invalidateStartupHealthCache(); + }); - const response = await Promise.race([ - handleManagementAPI( - new Request(url), - url, - { port: 10100, providers: {}, defaultProvider: "openai", codexAutoStart: true } as OcxConfig, - ), - new Promise(resolve => setTimeout(() => resolve(null), 100)), - ]); + test.each(["reject", "throw"])("detached snapshot probe handles %s and permits a later retry", async (failure) => { + invalidateStartupHealthCache(); + const config = { codexAutoStart: true }; + const failed = getStartupHealthSnapshot(config, { probe: () => { + if (failure === "throw") throw new Error("controlled probe failure"); + return Promise.reject(new Error("controlled probe failure")); + } }); + expect(failed.diagnosticStale).toBe(true); + const settled = await getCachedStartupHealth(config, { waitForProbe: probe => probe }); + expect(settled.diagnosticStale).toBe(true); + const replacement = deriveStartupHealth({ ...base, routingKind: "native" }); + expect(await getCachedStartupHealth(config, { probe: async () => replacement, waitForProbe: probe => probe })).toBe(replacement); + invalidateStartupHealthCache(); + }); - expect(response?.status).toBe(200); - const body = await response!.json() as { startupHealth?: { diagnosticStale?: boolean } }; - expect(body.startupHealth?.diagnosticStale).toBe(true); + test("invalidated probe cannot replace or clear a newer flight", async () => { + invalidateStartupHealthCache(); + const config = { codexAutoStart: true }; + type Health = ReturnType; + let oldRelease!: (value: Health) => void; + let newRelease!: (value: Health) => void; + const oldProbe = new Promise(resolve => { oldRelease = resolve; }); + const newProbe = new Promise(resolve => { newRelease = resolve; }); + getStartupHealthSnapshot(config, { probe: () => oldProbe }); + const oldWait = getCachedStartupHealth(config, { waitForProbe: probe => probe }); + invalidateStartupHealthCache(); + getStartupHealthSnapshot(config, { probe: () => newProbe }); + const newer = getCachedStartupHealth(config, { waitForProbe: probe => probe }); + oldRelease(deriveStartupHealth(base)); + await oldWait; + let spuriousCalls = 0; + getStartupHealthSnapshot(config, { probe: async () => { spuriousCalls += 1; return deriveStartupHealth(base); } }); + const expected = deriveStartupHealth({ ...base, routingKind: "native" }); + newRelease(expected); + expect(await newer).toBe(expected); + expect(getStartupHealthSnapshot(config)).toBe(expected); + expect(spuriousCalls).toBe(0); invalidateStartupHealthCache(); }); }); From abbdb227f385443228656c8440282187cb5dec75 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:07:56 +0900 Subject: [PATCH 053/116] docs: translate code-mode host rules; docs handoff from lane E [skip ci] --- devlog/_plan/260907_lane_c/040_desktop.md | 4 ++++ docs-site/src/content/docs/fr/guides/codex-integration.md | 8 ++++++++ docs-site/src/content/docs/ja/guides/codex-integration.md | 8 ++++++++ docs-site/src/content/docs/ko/guides/codex-integration.md | 7 +++++++ docs-site/src/content/docs/ru/guides/codex-integration.md | 8 ++++++++ docs-site/src/content/docs/tr/guides/codex-integration.md | 8 ++++++++ .../src/content/docs/zh-cn/guides/codex-integration.md | 6 ++++++ .../src/content/docs/zh-tw/guides/codex-integration.md | 6 ++++++ 8 files changed, 55 insertions(+) diff --git a/devlog/_plan/260907_lane_c/040_desktop.md b/devlog/_plan/260907_lane_c/040_desktop.md index ad7fb60177..4eb4ebffd5 100644 --- a/devlog/_plan/260907_lane_c/040_desktop.md +++ b/devlog/_plan/260907_lane_c/040_desktop.md @@ -402,3 +402,7 @@ index 84ac5f67b..b6be3c2f6 100644 ``` Audit amendment: clear catalogRefreshPending only if sync status is affirmative success, not HTTP 200 skipped. Add skipped/no-write regression. + +## Lane E documentation handoff + +After run 34106956362 reported a GUI lint failure, include the separately prepared code-mode host-rule translations in the seven fr/ja/ko/ru/tr/zh-cn/zh-tw Codex integration guides. The patch adds 51 documentation lines matching the existing English paragraph; it does not modify runtime code or provider guides. Apply on the Desktop layer, record `docs handoff from lane E` and `[skip ci]` in its own commit, then cascade the fallback layer and dispatch the top CI again. Local documentation install/build remains NOT RUN. diff --git a/docs-site/src/content/docs/fr/guides/codex-integration.md b/docs-site/src/content/docs/fr/guides/codex-integration.md index 02ffa8a211..a351adeae5 100644 --- a/docs-site/src/content/docs/fr/guides/codex-integration.md +++ b/docs-site/src/content/docs/fr/guides/codex-integration.md @@ -233,6 +233,14 @@ opencodex encode cette déclaration et son historique sous forme d'outil de fonc cycle de vie diffusé de l'appel de fonction en `custom_tool_call` avant que Codex ne le reçoive. Le routage natif par transfert OpenAI et l'outil personnalisé `apply_patch`, qui est pris en charge, restent inchangés. +Avant le premier appel, les tours routés en mode code reçoivent aussi les règles de l'hôte pour les +outils auxiliaires imbriqués : `tools.apply_patch` prend une seule chaîne qui commence et se termine +par les lignes de marqueur de patch seules, sans habillage ; l'isolate ne dispose pas de `import`, +et les commandes longues sont interrogées via `write_stdin`. Lorsqu'un résultat exec en mode code +sur le chemin natif Responses routé, Kiro ou Cursor contient encore l'un des messages d'échec de +l'hôte, opencodex ajoute une indication d'une ligne qui nomme la règle. Cette modification ne +réécrit ni le code du modèle ni le texte de son patch. + Le fournisseur sélectionné doit prendre en charge les appels de fonctions ou d'outils. Un fournisseur purement textuel dépourvu de cette prise en charge ne peut pas utiliser `exec`, Browser ni Computer Use. Les lignes OpenAI natives conservent leur mode d'outil en amont. diff --git a/docs-site/src/content/docs/ja/guides/codex-integration.md b/docs-site/src/content/docs/ja/guides/codex-integration.md index d1d977b35c..46c33320f2 100644 --- a/docs-site/src/content/docs/ja/guides/codex-integration.md +++ b/docs-site/src/content/docs/ja/guides/codex-integration.md @@ -147,6 +147,14 @@ Codex の `exec` custom-tool grammar を受け付けない key-auth Responses pr `custom_tool_call` へ復元します。ネイティブ OpenAI の forward routing と、対応済みの `apply_patch` custom tool は 変更されません。 +ルーティングされた code-mode のターンには、最初の呼び出し前に、ネストされたヘルパーに関する +ホストの規則も伝えられます。`tools.apply_patch` は、装飾を付けないパッチマーカー行で始まり、 +同様のマーカー行で終わる単一の文字列を受け取ります。isolate では `import` を使用できず、 +長時間実行されるコマンドは `write_stdin` でポーリングします。ネイティブのルーティング済み Responses、 +Kiro、または Cursor の経路で、code-mode の exec 結果にホストの失敗メッセージがまだ含まれている場合、 +opencodex は該当する規則を示す 1 行のヒントを追加します。この変更でモデルのコードやパッチのテキストを +書き換えることはありません。 + 選択した provider は function/tool calling をサポートしている必要があります。tool call に対応しない text-only provider では `exec`、Browser、Computer Use は使用できません。ネイティブ OpenAI の項目は上流の tool mode を そのまま維持します。 diff --git a/docs-site/src/content/docs/ko/guides/codex-integration.md b/docs-site/src/content/docs/ko/guides/codex-integration.md index 44551de837..1f324adaf2 100644 --- a/docs-site/src/content/docs/ko/guides/codex-integration.md +++ b/docs-site/src/content/docs/ko/guides/codex-integration.md @@ -149,6 +149,13 @@ history를 업스트림 function tool로 인코딩한 다음 스트리밍된 fun `custom_tool_call`로 복원합니다. 네이티브 OpenAI forward routing과 지원되는 `apply_patch` custom tool은 변경되지 않습니다. +라우팅된 code-mode 턴에는 첫 호출 전에 중첩 helper에 대한 호스트 규칙도 전달됩니다. +`tools.apply_patch`는 별도 장식 없이 패치 마커만 있는 줄로 시작하고 끝나는 하나의 문자열을 받습니다. +isolate에서는 `import`를 사용할 수 없으며, 오래 실행되는 명령은 `write_stdin`으로 폴링합니다. +네이티브 라우팅 Responses, Kiro 또는 Cursor 경로의 code-mode exec 결과에 호스트의 실패 메시지 중 +하나가 여전히 포함되어 있으면, opencodex는 해당 규칙을 명시하는 한 줄짜리 힌트를 덧붙입니다. +이 변경은 모델의 코드나 패치 텍스트를 다시 작성하지 않습니다. + 선택한 provider는 function/tool calling을 지원해야 합니다. tool call을 지원하지 않는 text-only provider에서는 `exec`, Browser 또는 Computer Use를 사용할 수 없습니다. 네이티브 OpenAI 항목은 업스트림 tool mode를 그대로 유지합니다. diff --git a/docs-site/src/content/docs/ru/guides/codex-integration.md b/docs-site/src/content/docs/ru/guides/codex-integration.md index 9707a3ea44..23581e56f6 100644 --- a/docs-site/src/content/docs/ru/guides/codex-integration.md +++ b/docs-site/src/content/docs/ru/guides/codex-integration.md @@ -224,6 +224,14 @@ opencodex кодирует объявление и историю как functio потоковый lifecycle function call в `custom_tool_call` до передачи в Codex. Нативная forward- маршрутизация OpenAI и поддерживаемый custom tool `apply_patch` остаются без изменений. +Перед первым вызовом маршрутизируемые ходы в code-mode также получают правила хоста для вложенных +вспомогательных инструментов: `tools.apply_patch` принимает одну строку, которая начинается и +заканчивается отдельными строками маркеров патча без дополнительного оформления; в isolate нет +`import`, а длительные команды опрашиваются через `write_stdin`. Если результат exec в code-mode +на нативном маршрутизируемом пути Responses, Kiro или Cursor всё ещё содержит одно из сообщений +хоста об ошибке, opencodex добавляет однострочную подсказку с указанием правила. Это изменение +не переписывает код модели или текст её патча. + Выбранный provider должен поддерживать function/tool calling. Text-only provider без tool calls не может использовать `exec`, Browser или Computer Use. Нативные записи OpenAI сохраняют свой upstream tool mode без изменений. diff --git a/docs-site/src/content/docs/tr/guides/codex-integration.md b/docs-site/src/content/docs/tr/guides/codex-integration.md index 02fae0f468..d13af52274 100644 --- a/docs-site/src/content/docs/tr/guides/codex-integration.md +++ b/docs-site/src/content/docs/tr/guides/codex-integration.md @@ -262,6 +262,14 @@ fonksiyon aracı olarak kodlar, ardından akışlı fonksiyon çağrısı yaşam Codex görmeden önce `custom_tool_call`'a geri yükler. Yerel OpenAI iletme yönlendirmesi ve desteklenen `apply_patch` özel aracı değişmeden kalır. +Yönlendirilen code-mode turlarına, ilk çağrıdan önce iç içe geçmiş yardımcılar için geçerli olan +ana makine kuralları da bildirilir: `tools.apply_patch`, yalnızca yama işaretçilerinden oluşan +satırlarla başlayan ve biten tek bir dize alır; isolate içinde `import` yoktur ve uzun süren +komutlar `write_stdin` üzerinden yoklanır. Yerel yönlendirilmiş Responses, Kiro veya Cursor yolundaki +bir code-mode exec sonucu hâlâ ana makinenin hata mesajlarından birini içeriyorsa opencodex, +ilgili kuralı belirten tek satırlık bir ipucu ekler. Bu değişiklik modelin kodunu veya yama metnini +yeniden yazmaz. + Seçilen sağlayıcı fonksiyon/araç çağrısını desteklemelidir. Araç çağrısı desteği olmayan salt metin bir sağlayıcı `exec`, Tarayıcı veya Bilgisayar Kullanımını kullanamaz. Yerel OpenAI satırları yukarı akış araç modunu değiştirmeden tutar. diff --git a/docs-site/src/content/docs/zh-cn/guides/codex-integration.md b/docs-site/src/content/docs/zh-cn/guides/codex-integration.md index 552c0c3f53..0c3df0c0e2 100644 --- a/docs-site/src/content/docs/zh-cn/guides/codex-integration.md +++ b/docs-site/src/content/docs/zh-cn/guides/codex-integration.md @@ -196,6 +196,12 @@ Codex 显示的模型来自一个磁盘上的 catalog(默认是 `$CODEX_HOME/o 历史记录编码成上游 function tool,再在 Codex 收到结果前,把流式 function-call lifecycle 还原成 `custom_tool_call`。原生 OpenAI forward routing 和已支持的 `apply_patch` custom tool 保持不变。 +路由的 code-mode 轮次还会在首次调用前收到宿主对嵌套辅助工具的规则:`tools.apply_patch` +接收一个字符串,首尾必须是没有额外包装的独立补丁标记行;isolate 中没有 `import`,长时间运行的 +命令通过 `write_stdin` 轮询。如果原生路由 Responses、Kiro 或 Cursor 路径上的 code-mode exec +结果仍包含宿主的某条失败消息,opencodex 会追加一行提示,指出对应规则。此变更不会重写模型的 +代码或补丁文本。 + 所选 provider 必须支持 function/tool calling。不支持 tool call 的 text-only provider 无法使用 `exec`、 Browser 或 Computer Use。原生 OpenAI 条目会保持其上游 tool mode 不变。 diff --git a/docs-site/src/content/docs/zh-tw/guides/codex-integration.md b/docs-site/src/content/docs/zh-tw/guides/codex-integration.md index f371457be9..44ee5bbb3b 100644 --- a/docs-site/src/content/docs/zh-tw/guides/codex-integration.md +++ b/docs-site/src/content/docs/zh-tw/guides/codex-integration.md @@ -201,6 +201,12 @@ metadata,使用 Codex 的 `low | medium | high | xhigh | max | ultra` 檔位 歷史編碼成上游 function tool,再於 Codex 看見前將串流 function-call lifecycle 還原成 `custom_tool_call`。原生 OpenAI forward 路由與受支援的 `apply_patch` custom tool 維持不變。 +路由的 code-mode 回合也會在首次呼叫前收到主機對巢狀輔助工具的規則:`tools.apply_patch` +接收一個字串,開頭與結尾必須是沒有額外包裝的獨立補丁標記行;isolate 中沒有 `import`,長時間執行的 +命令透過 `write_stdin` 輪詢。如果原生路由 Responses、Kiro 或 Cursor 路徑上的 code-mode exec +結果仍包含主機的某則失敗訊息,opencodex 會附加一行提示,指出對應規則。這項變更不會重寫模型的 +程式碼或補丁文字。 + 所選 provider 必須支援 function/tool calling。不支援 tool call 的純文字 provider 無法使用 `exec`、 Browser 或 Computer Use。原生 OpenAI 列保留上游 tool mode 不變。 From f1b8f2d2f1edee55b68202469f86a5334710688d Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:07:57 +0900 Subject: [PATCH 054/116] fix(gui): keep fallback render identities in state [skip ci] CI 34106956362 gates101697798420: remove render-time ref access and dynamic selector construction while preserving occurrence identity and keyboard focus. Co-authored-by: x3M3x <98298256+x3M3x@users.noreply.github.com> --- .../SubagentDelegationSection.tsx | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx index 6fe043461c..a1b405c2d9 100644 --- a/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx +++ b/gui/src/components/subagents-workspace/SubagentDelegationSection.tsx @@ -64,15 +64,22 @@ export default function SubagentDelegationSection({ && !(ultraMode.multiAgentMode === "v2" && ultraMode.keepNativeChatGptOnV1)); const showV2Compatibility = !ultraLoadFailed && ultraMode.loaded === true && routedPreferred && nativeMayUseV2; const fallbackControlsRef = useRef(null); - const nextRowId = useRef(0); - const rowIdentity = useRef>([]); - // Reuse each configured occurrence across reorder; duplicates have distinct IDs. - if (rowIdentity.current.length !== fallback.length || rowIdentity.current.some((row, i) => row.model !== fallback[i])) { - const remaining = [...rowIdentity.current]; - rowIdentity.current = fallback.map(modelName => { + const [identity, setIdentity] = useState(() => ({ + models: fallback, + rows: fallback.map((rowModel, id) => ({ model: rowModel, id })), + nextId: fallback.length, + })); + let rows = identity.rows; + // Keys are render state. Guarded prop reconciliation retains each occurrence; + // event handlers move the same identities with their corresponding models. + if (identity.models !== fallback) { + const remaining = [...identity.rows]; + let nextId = identity.nextId; + rows = fallback.map(modelName => { const old = remaining.findIndex(row => row.model === modelName); - return old >= 0 ? remaining.splice(old, 1)[0] : { model: modelName, id: nextRowId.current++ }; + return old >= 0 ? remaining.splice(old, 1)[0] : { model: modelName, id: nextId++ }; }); + setIdentity({ models: fallback, rows, nextId }); } const pendingFocus = useRef<{ row: number; action: string } | null>(null); useLayoutEffect(() => { @@ -80,7 +87,8 @@ export default function SubagentDelegationSection({ if (!target) return; pendingFocus.current = null; const row = fallbackControlsRef.current?.querySelectorAll(".swi-fallback-row")[target.row]; - const action = row?.querySelector(`button[data-action="${target.action}"]:not(:disabled)`) + const enabledActions = row?.querySelectorAll("button[data-action]:not(:disabled)"); + const action = Array.from(enabledActions ?? []).find(button => button.dataset.action === target.action) ?? row?.querySelector("button:not(:disabled)") ?? fallbackControlsRef.current?.querySelector('button[role="combobox"]'); action?.focus(); @@ -91,7 +99,9 @@ export default function SubagentDelegationSection({ const target = index + direction; if (fallbackBusy || target < 0 || target >= next.length) return; [next[index], next[target]] = [next[target], next[index]]; - [rowIdentity.current[index], rowIdentity.current[target]] = [rowIdentity.current[target], rowIdentity.current[index]]; + const nextRows = [...rows]; + [nextRows[index], nextRows[target]] = [nextRows[target], nextRows[index]]; + setIdentity({ ...identity, models: next, rows: nextRows }); pendingFocus.current = { row: target, action: direction === -1 ? "up" : "down" }; onFallbackChange(next); }; @@ -160,7 +170,7 @@ export default function SubagentDelegationSection({
{fallback.map((modelName, index) => ( -
+
{index + 1}. {modelName} {!availableModels.includes(modelName) && {t("sub.fallbackUnavailable")}} @@ -168,9 +178,10 @@ export default function SubagentDelegationSection({
From 1ca1a56615e779407e85bcda93f2e27f280d8a26 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:24:07 +0900 Subject: [PATCH 055/116] fix(release): recover registry reads after acknowledged publication [skip ci] --- .github/workflows/release.yml | 40 ++++++--- tests/ci-workflows/ci-workflows.test.ts | 105 ++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 12 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 685a13876b..339de6d9ea 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -334,40 +334,56 @@ jobs: } - name: Publish (or dry-run) + id: publication env: DRY_RUN: ${{ inputs.dry-run }} NPM_DIST_TAG: ${{ inputs.tag }} run: | + set -euo pipefail if [ "$DRY_RUN" = "true" ]; then echo "::notice::DRY RUN — building + packing, not publishing" npm run prepublishOnly npm pack --dry-run else npm publish --tag "$NPM_DIST_TAG" --access public + echo "published=true" >> "$GITHUB_OUTPUT" fi - # Confirm the registry actually has the new version (real publishes only). + # Publication is acknowledged before registry reads, which can lag or fail. + # Recover only observation failures in this run; never retry npm publish. - name: Post-publish registry smoke - if: ${{ inputs.dry-run != true }} + id: registry-smoke + if: ${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }} env: RELEASE_VERSION: ${{ inputs.version }} + PUBLISHED: ${{ steps.publication.outputs.published }} run: | - for attempt in $(seq 1 30); do - if VERSION=$(npm view "@bitkyc08/opencodex@${RELEASE_VERSION}" version 2>/dev/null); then + set -euo pipefail + test "$PUBLISHED" = "true" || { + echo "::error::No successful publication receipt; refusing registry recovery" + exit 1 + } + for attempt in $(seq 1 6); do + if VERSION=$(timeout --kill-after=2s 10s npm view "@bitkyc08/opencodex@${RELEASE_VERSION}" version --fetch-retries=0 --fetch-timeout=8000 2>/dev/null); then + if [ "$VERSION" != "$RELEASE_VERSION" ]; then + echo "::error::Registry returned an unexpected version; refusing to create a release" + exit 1 + fi echo "registry version=$VERSION" - test "$VERSION" = "$RELEASE_VERSION" - npm dist-tag ls @bitkyc08/opencodex + echo "verification=verified" >> "$GITHUB_OUTPUT" + echo "Registry verified @bitkyc08/opencodex@${RELEASE_VERSION}." >> "$GITHUB_STEP_SUMMARY" + timeout --kill-after=2s 10s npm dist-tag ls @bitkyc08/opencodex --fetch-retries=0 --fetch-timeout=8000 || echo "::warning::Could not read npm dist-tags; exact version was verified" exit 0 fi - echo "::notice::@bitkyc08/opencodex@${RELEASE_VERSION} not visible in npm registry yet (attempt $attempt/30)" - sleep 10 + echo "::notice::Registry lookup not confirmed (attempt $attempt/6)" + if [ "$attempt" -lt 6 ]; then sleep 5; fi done - echo "::error::npm registry smoke failed after 30 attempts" - npm view @bitkyc08/opencodex versions dist-tags --json || true - exit 1 + echo "verification=pending" >> "$GITHUB_OUTPUT" + echo "::warning::npm publish succeeded, but registry verification remains pending; continuing GitHub release creation without republishing" + echo "Publication acknowledged for @bitkyc08/opencodex@${RELEASE_VERSION}; registry verification pending after bounded reads. Inspect the registry before announcing availability. Do not republish this version." >> "$GITHUB_STEP_SUMMARY" - name: Create GitHub release - if: ${{ inputs.dry-run != true }} + if: ${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }} env: GH_TOKEN: ${{ github.token }} RELEASE_VERSION: ${{ inputs.version }} diff --git a/tests/ci-workflows/ci-workflows.test.ts b/tests/ci-workflows/ci-workflows.test.ts index c967f9d4c0..d2bef0d24f 100644 --- a/tests/ci-workflows/ci-workflows.test.ts +++ b/tests/ci-workflows/ci-workflows.test.ts @@ -1,5 +1,8 @@ import { describe, expect, test } from "bun:test"; import { fileURLToPath } from "node:url"; +import { mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { SCRIPT_BINDINGS, callsTo, @@ -5514,3 +5517,105 @@ describe("gui exhaustive-deps suppression stays scoped and effective", () => { expect(models).not.toContain("react-doctor-disable-next-line"); }); }); + + +interface PublicationStep { name: string; id?: string; if?: string; run?: string } +async function publicationSteps(): Promise { + const yaml = Bun.YAML.parse(await readText(".github/workflows/release.yml")) as { + jobs: { publish: { steps: PublicationStep[] } }; + }; + return yaml.jobs.publish.steps; +} + +test("release recovery requires same-run publication and preserves successful-step gating", async () => { + const steps = await publicationSteps(); + const publish = steps.find(step => step.name === "Publish (or dry-run)")!; + const smoke = steps.find(step => step.name === "Post-publish registry smoke")!; + const release = steps.find(step => step.name === "Create GitHub release")!; + expect(publish.id).toBe("publication"); + expect(smoke.id).toBe("registry-smoke"); + for (const step of [smoke, release]) { + expect(step.if).toBe("${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }}"); + } + expect(steps.indexOf(publish)).toBeLessThan(steps.indexOf(smoke)); + expect(steps.indexOf(smoke)).toBeLessThan(steps.indexOf(release)); +}); + +// This executes the ubuntu-latest release job's Bash, not the Windows runtime. +// Structural workflow guards above still execute on every platform. +test.skipIf(process.platform === "win32")("release shell recovers only unverified reads after acknowledged publication", async () => { + const steps = await publicationSteps(); + const publish = steps.find(step => step.name === "Publish (or dry-run)")!.run!; + const smoke = steps.find(step => step.name === "Post-publish registry smoke")!.run!; + const scenarios = [ + { mode: "match", dry: false, status: 0, receipt: true, verification: "verified", reads: 1 }, + { mode: "delayed", dry: false, status: 0, receipt: true, verification: "verified", reads: 3 }, + { mode: "unavailable", dry: false, status: 0, receipt: true, verification: "pending", reads: 6 }, + { mode: "timeout", dry: false, status: 0, receipt: true, verification: "pending", reads: 6 }, + { mode: "wrong", dry: false, status: 1, receipt: true, verification: "", reads: 1 }, + { mode: "empty", dry: false, status: 1, receipt: true, verification: "", reads: 1 }, + { mode: "dist-failure", dry: false, status: 0, receipt: true, verification: "verified", reads: 1 }, + { mode: "publish-failure", dry: false, status: 23, receipt: false, verification: "", reads: 0 }, + { mode: "match", dry: true, status: 0, receipt: false, verification: "", reads: 0 }, + { mode: "missing-receipt", dry: false, status: 1, receipt: false, verification: "", reads: 0 }, + ]; + for (const scenario of scenarios) { + const dir = mkdtempSync(join(tmpdir(), "ocx-publication-")); + const output = join(dir, "output"); + const summary = join(dir, "summary"); + const calls = join(dir, "calls"); + for (const path of [output, summary, calls]) writeFileSync(path, ""); + const prelude = String.raw` + npm() { + echo "$*" >> "$CALLS" + case "$1" in + publish) [ "$SCENARIO" != "publish-failure" ] || return 23 ;; + view) + count=$(cat "$COUNTER" 2>/dev/null || echo 0) + count=$((count + 1)); echo "$count" > "$COUNTER" + case "$SCENARIO" in + unavailable) return 1 ;; + timeout) return 124 ;; + delayed) [ "$count" -ge 3 ] || return 1 ;; + wrong) echo 0.0.0; return 0 ;; + empty) return 0 ;; + esac + echo "$RELEASE_VERSION" ;; + dist-tag) [ "$SCENARIO" != "dist-failure" ] || return 1 ;; + esac + } + timeout() { + # The wrapper is stubbed, but its production process bounds are asserted. + [ "$1" = "--kill-after=2s" ] && [ "$2" = "10s" ] || return 99 + shift 2; "$@" + } + sleep() { echo "sleep $*" >> "$CALLS"; } + `; + try { + const script = prelude + (scenario.mode === "missing-receipt" ? "" : publish) + '\n' + + (scenario.dry ? "" : `PUBLISHED=$(sed -n 's/^published=//p' "$GITHUB_OUTPUT")\n${smoke}`); + const child = Bun.spawn(["bash", "--noprofile", "--norc", "-e", "-o", "pipefail", "-c", script], { + env: { ...process.env, SCENARIO: scenario.mode, DRY_RUN: String(scenario.dry), + NPM_DIST_TAG: "latest", RELEASE_VERSION: "9.8.7", GITHUB_OUTPUT: output, + GITHUB_STEP_SUMMARY: summary, CALLS: calls, COUNTER: join(dir, "counter") }, + stdin: "ignore", stdout: "pipe", stderr: "pipe", + }); + const [status, stdout, stderr] = await Promise.all([ + child.exited, new Response(child.stdout).text(), new Response(child.stderr).text(), + ]); + expect({ scenario: scenario.mode, status, stderr }).toEqual({ scenario: scenario.mode, status: scenario.status, stderr: "" }); + const receipt = readFileSync(output, "utf8"); + const log = readFileSync(calls, "utf8").trim().split("\n"); + expect(receipt.includes("published=true")).toBe(scenario.receipt); + expect(receipt.includes("verification=")).toBe(scenario.verification !== ""); + if (scenario.verification) expect(receipt).toContain(`verification=${scenario.verification}`); + expect(log.filter(line => line.startsWith("view "))).toHaveLength(scenario.reads); + expect(log.filter(line => line.startsWith("publish "))).toHaveLength(scenario.dry || scenario.mode === "missing-receipt" ? 0 : 1); + if (scenario.verification === "pending") { + expect(stdout).toContain("::warning::npm publish succeeded"); + expect(readFileSync(summary, "utf8")).toContain("registry verification pending"); + expect(log.filter(line => line === "sleep 5")).toHaveLength(5); + } + } finally { rmSync(dir, { recursive: true, force: true }); } + } +}); From 56f356d65f153533164e52c549e77baa0e7a8650 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:07:45 +0900 Subject: [PATCH 056/116] fix(release): bind registry checks to package metadata [skip ci] --- .github/workflows/release.yml | 9 +++++---- tests/ci-workflows/ci-workflows.test.ts | 11 +++++++++-- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 339de6d9ea..7b565b6800 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -363,16 +363,17 @@ jobs: echo "::error::No successful publication receipt; refusing registry recovery" exit 1 } + pkg_name="$(node -p "require('./package.json').name")" for attempt in $(seq 1 6); do - if VERSION=$(timeout --kill-after=2s 10s npm view "@bitkyc08/opencodex@${RELEASE_VERSION}" version --fetch-retries=0 --fetch-timeout=8000 2>/dev/null); then + if VERSION=$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" version --fetch-retries=0 --fetch-timeout=8000 2>/dev/null); then if [ "$VERSION" != "$RELEASE_VERSION" ]; then echo "::error::Registry returned an unexpected version; refusing to create a release" exit 1 fi echo "registry version=$VERSION" echo "verification=verified" >> "$GITHUB_OUTPUT" - echo "Registry verified @bitkyc08/opencodex@${RELEASE_VERSION}." >> "$GITHUB_STEP_SUMMARY" - timeout --kill-after=2s 10s npm dist-tag ls @bitkyc08/opencodex --fetch-retries=0 --fetch-timeout=8000 || echo "::warning::Could not read npm dist-tags; exact version was verified" + echo "Registry verified ${pkg_name}@${RELEASE_VERSION}." >> "$GITHUB_STEP_SUMMARY" + timeout --kill-after=2s 10s npm dist-tag ls "$pkg_name" --fetch-retries=0 --fetch-timeout=8000 || echo "::warning::Could not read npm dist-tags; exact version was verified" exit 0 fi echo "::notice::Registry lookup not confirmed (attempt $attempt/6)" @@ -380,7 +381,7 @@ jobs: done echo "verification=pending" >> "$GITHUB_OUTPUT" echo "::warning::npm publish succeeded, but registry verification remains pending; continuing GitHub release creation without republishing" - echo "Publication acknowledged for @bitkyc08/opencodex@${RELEASE_VERSION}; registry verification pending after bounded reads. Inspect the registry before announcing availability. Do not republish this version." >> "$GITHUB_STEP_SUMMARY" + echo "Publication acknowledged for ${pkg_name}@${RELEASE_VERSION}; registry verification pending after bounded reads. Inspect the registry before announcing availability. Do not republish this version." >> "$GITHUB_STEP_SUMMARY" - name: Create GitHub release if: ${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }} diff --git a/tests/ci-workflows/ci-workflows.test.ts b/tests/ci-workflows/ci-workflows.test.ts index d2bef0d24f..b098220521 100644 --- a/tests/ci-workflows/ci-workflows.test.ts +++ b/tests/ci-workflows/ci-workflows.test.ts @@ -5519,7 +5519,7 @@ describe("gui exhaustive-deps suppression stays scoped and effective", () => { }); -interface PublicationStep { name: string; id?: string; if?: string; run?: string } +interface PublicationStep { name: string; id?: string; if?: string; run?: string; env?: Record } async function publicationSteps(): Promise { const yaml = Bun.YAML.parse(await readText(".github/workflows/release.yml")) as { jobs: { publish: { steps: PublicationStep[] } }; @@ -5534,6 +5534,7 @@ test("release recovery requires same-run publication and preserves successful-st const release = steps.find(step => step.name === "Create GitHub release")!; expect(publish.id).toBe("publication"); expect(smoke.id).toBe("registry-smoke"); + expect(smoke.env?.PUBLISHED).toBe("${{ steps.publication.outputs.published }}"); for (const step of [smoke, release]) { expect(step.if).toBe("${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }}"); } @@ -5566,6 +5567,7 @@ test.skipIf(process.platform === "win32")("release shell recovers only unverifie const calls = join(dir, "calls"); for (const path of [output, summary, calls]) writeFileSync(path, ""); const prelude = String.raw` + node() { echo "@fixture/renamed"; } npm() { echo "$*" >> "$CALLS" case "$1" in @@ -5609,7 +5611,12 @@ test.skipIf(process.platform === "win32")("release shell recovers only unverifie expect(receipt.includes("published=true")).toBe(scenario.receipt); expect(receipt.includes("verification=")).toBe(scenario.verification !== ""); if (scenario.verification) expect(receipt).toContain(`verification=${scenario.verification}`); - expect(log.filter(line => line.startsWith("view "))).toHaveLength(scenario.reads); + const reads = log.filter(line => line.startsWith("view ")); + expect(reads).toHaveLength(scenario.reads); + for (const read of reads) expect(read).toBe("view @fixture/renamed@9.8.7 version --fetch-retries=0 --fetch-timeout=8000"); + const tags = log.filter(line => line.startsWith("dist-tag ")); + expect(tags).toEqual(scenario.verification === "verified" + ? ["dist-tag ls @fixture/renamed --fetch-retries=0 --fetch-timeout=8000"] : []); expect(log.filter(line => line.startsWith("publish "))).toHaveLength(scenario.dry || scenario.mode === "missing-receipt" ? 0 : 1); if (scenario.verification === "pending") { expect(stdout).toContain("::warning::npm publish succeeded"); From 609105cf9148ca18decfc81e8d1859e30af3aff9 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:22:37 +0900 Subject: [PATCH 057/116] docs: plan lane D manual release chain [skip ci] --- devlog/_plan/260907_lane_d/000_plan.md | 32 +++++++++++++++++++ devlog/_plan/260907_lane_d/010_thinking.md | 24 ++++++++++++++ devlog/_plan/260907_lane_d/020_receipt.md | 12 +++++++ .../_plan/260907_lane_d/030_account_prices.md | 13 ++++++++ .../_plan/260907_lane_d/040_price_editor.md | 23 +++++++++++++ .../_plan/260907_lane_d/050_usage_ranges.md | 30 +++++++++++++++++ 6 files changed, 134 insertions(+) create mode 100644 devlog/_plan/260907_lane_d/000_plan.md create mode 100644 devlog/_plan/260907_lane_d/010_thinking.md create mode 100644 devlog/_plan/260907_lane_d/020_receipt.md create mode 100644 devlog/_plan/260907_lane_d/030_account_prices.md create mode 100644 devlog/_plan/260907_lane_d/040_price_editor.md create mode 100644 devlog/_plan/260907_lane_d/050_usage_ranges.md diff --git a/devlog/_plan/260907_lane_d/000_plan.md b/devlog/_plan/260907_lane_d/000_plan.md new file mode 100644 index 0000000000..97f6761463 --- /dev/null +++ b/devlog/_plan/260907_lane_d/000_plan.md @@ -0,0 +1,32 @@ +# Lane D release-train roadmap + +Satisfy-spec HOTL for delegated recommendations #16 → #17 → #15 → #21 → #25. +Goal: independently audited manual dependent PRs ready for main-session integration. +Scope: Claude outbound, display-name dialog, usage costs/overlays/summary, usage GUI, +plus directly required CLI/API/tests/docs. i18n files are append-only shared per main's +2026-09-07 correction. No other lane-owned files; no merge/release/main/preview. +No local test/typecheck/build/install. Remote ci.yml lane=all at final top SHA is +sole product verifier. Local source and diff checks are not execution evidence. +No user token or wall-clock bound supplied. Use existing repo/GitHub authorization. +Stop: top-head green with reviewer verdicts and layer PR/SHA evidence; otherwise +record exact DEFER/BLOCKED reasons without claiming implementation passes. +Memory/evidence: this unit plus .tmp/lane-d for review drafts. Unpublished security +material stays in scratch. Reclaim failed delegated work after two distinct agents; +other-lane file collision requires main coordination. + +## Dependency and publication map + +| Phase | Item | Outcome | Branch | +|---|---|---|---| +| 0 | Roadmap | Lock all diff plans before code | first layer docs | +| 1 | #3719 slice | Legacy redacted-before-signed SSE/JSON parity | codex/260907-d1-thinking | +| 2 | receipt guard | Prevent new intent while recovery is pending | codex/260907-d2-receipt | +| 3 | #3817 | Exact account identity resolves provider overlays | codex/260907-d3-account-prices | +| 4 | #3667 | Price editor + CLI + authoritative explicit zero | codex/260907-d4-price-editor | +| 5 | #3379 slice / #2956 | Inclusive custom usage bounds + GUI | codex/260907-d5-usage-ranges | +| 6 | readiness | Fresh top CI, screenshots and implementation audits | top branch | + +All lower subjects include [skip ci]; every push uses --no-verify. Native stack null. +Only phase 6 dispatches ci.yml lane=all; failures get Astra-high exact-log diagnosis, +fixes on their owning layer and rebase --update-refs cascade. Main alone merges. +#3719 and #3379 stay open. #2956 credit uses verified GitHub author identity. diff --git a/devlog/_plan/260907_lane_d/010_thinking.md b/devlog/_plan/260907_lane_d/010_thinking.md new file mode 100644 index 0000000000..e321ac03ce --- /dev/null +++ b/devlog/_plan/260907_lane_d/010_thinking.md @@ -0,0 +1,24 @@ +# 010 Thinking ordering +MODIFY src/claude/outbound.ts ensureBlock/closeOpenBlock and reasoning done. +Before: thinking start/deltas are emitted immediately; done closes thinking then red. +After: retain already-budgeted thinking text, defer its start/index/delta until close; +reasoning done emits red blocks before flushing pending signed thinking. Preserve text +and tool order, hidden env.txt non-disclosure, genuine signature and budget release. +MODIFY tests/claude-integration/claude-outbound.test.ts: compare collected SSE against +literal expected content and JSON for combined envelopes with preceding deltas, +multiple summary parts/red blocks, text prefix, signed-only, red-only. Check sequential +non-overlapping block indices and cancellation/overflow existing assertions. +Independent Astra audit must resolve streaming latency and allocation implications. + +Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. + +## A audit fold-back +Astra Dirac found two blockers: unmatched-item reordering and closure memory overlap. +Track bounded reasoningItemKey separately from part identity; flush on changed explicit +item identity, and close unrelated pending thinking before another item's red blocks. +Only same identity (including both omitted) reorders red before pending thinking. +Release retained thinkingBuf after text frame enqueue, before signature frame enqueue; +queued frame budget stays authoritative, never weakened. Add near-limit valid control, +shared-budget collector control, overflow/cancel regressions. Deferred thinking is an +accepted visible-latency tradeoff; text/tool frames remain live with incremental-reader +coverage. Late done after a different emitted block cannot reorder earlier content. diff --git a/devlog/_plan/260907_lane_d/020_receipt.md b/devlog/_plan/260907_lane_d/020_receipt.md new file mode 100644 index 0000000000..7b710df91e --- /dev/null +++ b/devlog/_plan/260907_lane_d/020_receipt.md @@ -0,0 +1,12 @@ +# 020 Display-name receipt recovery +MODIFY gui/src/components/ModelDisplayNameDialog.tsx. +Before: input/reset enabled whenever saving=false; input onEdit clears recovery. +After: new mutationOutcomeUnknown prop from Models.tsx recovery.confirmed===false +disables draft editing and reset, submit retains +read/retry action. Handler guards prevent synthetic events bypassing disabled controls. +Close/cancel stays available. This is bounded UI recovery, not server request ordering. +MODIFY gui/tests/models-display-name-editor.test.tsx: unknown receipt cannot replace intent; retry recovers; confirmed saved:true +and ordinary validation error remain +editable. Screenshot changed disabled input/reset with retry available. + +Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. diff --git a/devlog/_plan/260907_lane_d/030_account_prices.md b/devlog/_plan/260907_lane_d/030_account_prices.md new file mode 100644 index 0000000000..4806657cdb --- /dev/null +++ b/devlog/_plan/260907_lane_d/030_account_prices.md @@ -0,0 +1,13 @@ +# 030 Account price identity +MODIFY src/usage/user-cost-overlays.ts registry refresh and signature/version. +Before: configured provider set and overlay rows only. +After: exact account identifiers/log labels from config mapped to established provider +identity. Include mapping in signature for memo and aggregate cache invalidation. +MODIFY src/usage/cost.ts resolveMatchedPrice: exact configured namespace and exact +user overlay precede account identity; unresolved suffix is never guessed/stripped. +MODIFY tests/usage/usage-cost.test.ts or existing provider-overlay tests: custom account +id, qualified id, stable log label, configured collision, unrelated hyphenated provider, +account rename/removal invalidation. Account aliases never become identity authority. +Audit determines precise supported historical labels from actual producer evidence. + +Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. diff --git a/devlog/_plan/260907_lane_d/040_price_editor.md b/devlog/_plan/260907_lane_d/040_price_editor.md new file mode 100644 index 0000000000..4628710d0d --- /dev/null +++ b/devlog/_plan/260907_lane_d/040_price_editor.md @@ -0,0 +1,23 @@ +# 040 Manual price editor +MODIFY src/usage/cost.ts userOverlayMatch: valid operator all-zero row returns user +price, while generated catalog zeros keep unknown/fallback semantics. +MODIFY src/server/management/model-routes.ts: exact-provider model-costs GET/PUT, +validate four finite nonnegative bounded rates or null reset, preserve siblings, +rollback on persist failure, no routing/catalog mutation required for price-only edits. +MODIFY src/cli/models-runtime.ts, models-runtime-subcommands.ts and capabilities.ts: +models set-price provider/model --input N --output N [--cache-read N --cache-write N] +or --auto. GET for show and PUT for set/reset through existing management client. +ADD gui/src/components/ModelPriceDialog.tsx; MODIFY Models.tsx and models-shared.ts +only as needed: edit action, load exact saved override, inputs 4 rates USD/1M, +save/reset and manual indicator. Reuse dialog/fetch/i18n patterns. All locale keys +append-only pricing.override.*. Add endpoint, CLI, estimator and GUI regressions; +register new test files in both append-only layout manifests. Public docs and generated +CLI surface map mirror actual capability entries; source-generation commands NOT RUN +locally so map is updated by its source contract without claiming verification. + +Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. + +A fold-back: add GET/PUT entries in src/server/management/route-registry.ts. +Reuse providerModelCostsConfigError. GET returns sanitized per-provider modelCosts map; +Models owns a typed map loaded with catalog or dedicated GET, so manual badges survive +reload. CLI omitted cache-read/cache-write rates default to zero, explicitly documented. diff --git a/devlog/_plan/260907_lane_d/050_usage_ranges.md b/devlog/_plan/260907_lane_d/050_usage_ranges.md new file mode 100644 index 0000000000..35b6758a76 --- /dev/null +++ b/devlog/_plan/260907_lane_d/050_usage_ranges.md @@ -0,0 +1,30 @@ +# 050 Custom usage windows +REIMPLEMENT range slice from PR #2956 with Manson2438 credit; do not carry offline reports. +ADD src/usage/time-range.ts strict timestamp parser and inclusive since/until bounds; +MODIFY summary.ts accumulator interface to support bounded windows without poisoning +preset daily aggregates. Use stream ledger filtering for partial days if compact daily +partitions cannot answer exact boundaries. Reject malformed/reversed bounds at API/CLI. +MODIFY src/server/management/logs-usage-routes.ts custom-window path before preset cache, +stream/filter into isolated accumulator preserving surface/provider/model and truncation +metadata. Do not persist normalized ledger rows. Include bounds in response. +MODIFY CLI observe/capabilities usage flags and GUI Usage.tsx custom datetime inputs, +independent draft/applied bounds, cache key includes bounds, grid anchored to effective +window, clear returns to preset. All locale keys append-only usage.range.*. +Tests: inclusive boundaries, partial same-day, reversed/invalid, empty ledger, existing +provider/model/surface filters, preset cache after custom query; GUI apply/clear/errors. +Public API/CLI docs describe epoch/ISO contract and local datetime conversion. + +Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. + +A fold-back: immutable window option on createUsageSummaryAccumulator; add() checks +inclusive bounds AFTER recording whole-scan snapshot timestamps but BEFORE partitioning. +clone preserves window. summarize uses window endpoint for grid, actual now for generatedAt; +retain 366-day grid cap. Custom queries use isolated row-unique accumulator via existing +getFilteredUsageAggregate with window in key. Reuse overlay/timezone revision restart +and scanner identity controls. Preserve apiKeyId and current filter echo alongside all +other filters. USAGE_RANGES remains preset-only; response range stays selected preset +with customWindow:true, since/until explicit bounds (bounds override preset). API accepts +integer epoch milliseconds or full ISO-8601 with timezone only; require both bounds; +reject negative/unsafe/date-invalid/reversed, never normalize overflow dates. +MODIFY src/cli/usage-report.ts heading prints since/until for customWindow responses. +GUI datetime values become epoch ms locally; end selected minute includes 59.999s. From b462cc54f223a34a10003873870dcc0aa92353b9 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:23:28 +0900 Subject: [PATCH 058/116] docs: record lane D roadmap audit decisions [skip ci] --- devlog/_plan/260907_lane_d/001_roadmap_audit.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 devlog/_plan/260907_lane_d/001_roadmap_audit.md diff --git a/devlog/_plan/260907_lane_d/001_roadmap_audit.md b/devlog/_plan/260907_lane_d/001_roadmap_audit.md new file mode 100644 index 0000000000..c14a08d2da --- /dev/null +++ b/devlog/_plan/260907_lane_d/001_roadmap_audit.md @@ -0,0 +1,16 @@ +# Roadmap audit resolution + +Astra Herschel (01a07b2b-5148-73c0-a067-a13485ab32c9) returned +GO-WITH-FIXES with four bounded roadmap corrections. All are incorporated in +040_price_editor.md and 050_usage_ranges.md: register management routes; persist +manual-price display state; filter individual ledger entries before daily aggregation; +preserve apiKeyId and scan consistency; define milliseconds and explicit window bounds. + +Astra Dirac identified two thinking design blockers, recorded in 010 for re-audit: +item ownership and simultaneous reasoning/frame retention. Astra Ohm limits the account +mapping to evidenced Codex identities and requires consistent tier-namespace resolution. +The first implementation phase must finish those fold-backs before code changes. + +Only documentation has changed. Source references were inspected; product tests, +typecheck, builds and installs are NOT RUN by delegation instruction. Product acceptance +remains open until top-head Cross-platform CI executes lane=all. From bf1536607a3036285939f7d2915fb5533f32a53b Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:35:28 +0900 Subject: [PATCH 059/116] fix(usage): resolve account prices through provider identity [skip ci] Apply base provider overlays to exact configured Codex account identities without widening arbitrary suffix matching. Preserve pricing namespaces, cache invalidation and tier parity. Refs #3817. Co-authored-by: rrmlima <137737127+rrmlima@users.noreply.github.com> --- .../_plan/260907_lane_d/030_account_prices.md | 14 ++ src/usage/cost.ts | 48 +++-- src/usage/user-cost-overlays.ts | 38 +++- tests/usage/usage-cost.test.ts | 178 ++++++++++++++++++ 4 files changed, 249 insertions(+), 29 deletions(-) diff --git a/devlog/_plan/260907_lane_d/030_account_prices.md b/devlog/_plan/260907_lane_d/030_account_prices.md index 4806657cdb..2ac6e9ccf4 100644 --- a/devlog/_plan/260907_lane_d/030_account_prices.md +++ b/devlog/_plan/260907_lane_d/030_account_prices.md @@ -11,3 +11,17 @@ account rename/removal invalidation. Account aliases never become identity autho Audit determines precise supported historical labels from actual producer evidence. Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. + +Astra Ohm audit corrections: config-only identity mapping supports selectable Codex +accounts, effective codexAccountLogLabel, exact ID compatibility aliases, and built-in +main/__main__. Generic OAuth stores are separate and excluded; no free-form inference. +Use exact configured provider before canonical account identity, exact override first. +Apply same namespace for context/priority/lower-bound modifiers, preserving attribution. +Include sorted mapping in version signature, but aliases/plan/reordering stay no-ops. + +Implementation: exact selectable account IDs, effective labels and main forms are resolved +from config at overlay refresh. Only identity changes bump cache versions. Exact configured +providers and explicit user rows remain isolated; context/Fast/lower-bound use the selected +price namespace while request attribution is unchanged. Existing memo fast path is retained. +Regression fixtures cover mappings, collisions, ignored aliases/invalid rows, add/remove/ +label invalidation, presentation no-ops, estimate/attempt/combo and tier parity. diff --git a/src/usage/cost.ts b/src/usage/cost.ts index f7004634c9..2a3b2ae6d3 100644 --- a/src/usage/cost.ts +++ b/src/usage/cost.ts @@ -16,10 +16,10 @@ import { } from "../generated/model-metadata"; import type { AttemptTierOutcome, OcxUsage } from "../types"; import { canonicalFastTierMarker } from "../providers/fastwire"; -import { baseProviderLabel, canonicalUsageProviderLabel } from "../providers/label"; +import { baseProviderLabel } from "../providers/label"; import type { PersistedUsageAttempt, UsageStatus } from "./log"; import { canonicalAntigravityUsageModel } from "../providers/antigravity-models"; -import { activeConfiguredProviders, activeUserCostOverlays, userCostOverlayVersion } from "./user-cost-overlays"; +import { activeAccountPricingProviders, activeConfiguredProviders, activeUserCostOverlays, userCostOverlayVersion } from "./user-cost-overlays"; import { EXPECTED_PRICE_OVERLAYS, findExpectedPriceOverlay, @@ -187,21 +187,18 @@ export function resolveMatchedPrice( userOverlays: readonly ExpectedPriceOverlay[] = activeUserCostOverlays(), options: PriceResolutionOptions = {}, ): MatchedPrice | null { - // User-configured overlays are keyed by the EXACT configured provider name. - // A provider that literally exists in config.providers keeps its own pricing - // namespace: a real custom provider can legitimately end with a label-shaped - // suffix (e.g. acme-pabcdef) and must not inherit the base provider's user - // overlay. Only NON-configured names (generated account log labels) collapse - // to their label base. chatgpt/openai-multi are the same OpenAI usage surface - // and always canonicalize to openai. - const collapsed = baseProviderLabel(provider); - if (collapsed !== provider && (canonicalUsageProviderLabel(provider) !== provider || !activeConfiguredProviders().has(provider))) { + // Literal configured providers win over account identities. Only then use + // config-owned Codex identities, followed by the existing historical suffix + // grammar. Never infer an account by stripping an arbitrary suffix. + const namespace = activeConfiguredProviders().has(provider) + ? provider + : activeAccountPricingProviders().get(provider) ?? baseProviderLabel(provider); + if (namespace !== provider) { + // An exact override (including caller-supplied rows) owns its namespace. + // Unchanged names use the memoized inner lookup's existing user-first order. const exactUserOverlay = userOverlayMatch(provider, modelId, userOverlays); if (exactUserOverlay) return exactUserOverlay; - // Pool/account log suffixes (e.g. google-antigravity-p442fff) must collapse - // before the compiled/overlay lookup; configured providers keep their own - // namespace above. - provider = collapsed; + provider = namespace; } // Memoize by (provider, model): usage summaries iterate hundreds of thousands of // rows that share a handful of provider/model keys, so resolving each time would @@ -466,7 +463,7 @@ function applyContextTier( tier?: ServiceTierInput, ): [Cost4, ContextTierName | undefined, boolean] { if (rawInputTokens === undefined) return [cost4, undefined, false]; - const rule = findContextTier(baseProviderLabel(provider), modelId); + const rule = findContextTier(provider, modelId); if (!rule || !isLongContext(rule, rawInputTokens)) return [cost4, undefined, false]; const confirmedFast = isConfirmedFast(tier); if (confirmedFast && rule.confirmedPriorityRelation === "exclusive") { @@ -494,9 +491,8 @@ function applyPriorityMultiplier( contextTier?: ContextTierName, ): [Cost4, number] { if (canonicalFastTierMarker(tierScalar(serviceTier)) !== "priority") return [cost4, 1]; - const base = baseProviderLabel(provider); - if (contextTier && findContextTier(base, modelId)?.confirmedPriorityRelation !== "stack") return [cost4, 1]; - const rule = findPriorityPricingRule(base, modelId); + if (contextTier && findContextTier(provider, modelId)?.confirmedPriorityRelation !== "stack") return [cost4, 1]; + const rule = findPriorityPricingRule(provider, modelId); if (rule?.requiresResponseConfirmation && !isConfirmedFast(serviceTier)) return [cost4, 1]; const multiplier = rule?.multiplier ?? 1; if (multiplier === 1) return [cost4, 1]; @@ -524,7 +520,7 @@ function isOpenRouterPriorityLowerBound( provider: string, outcome: AttemptTierOutcome | undefined, ): boolean { - return baseProviderLabel(provider) === "openrouter" + return provider === "openrouter" && outcome?.canonical === "priority" && outcome.fastOutcome === "applied" && (outcome.confirmation === "confirmed" || outcome.confirmation === "assumed"); @@ -550,13 +546,13 @@ export function estimateAttemptCost( ? serviceTierContextFromOutcome(attempt.tierOutcome) : serviceTier; const [tieredCost4, contextTier, contextPriorityLowerBound] = applyContextTier( - price.cost4, attempt.provider, attempt.model, attempt.usage.inputTokens, attemptServiceTier, + price.cost4, price.provider, attempt.model, attempt.usage.inputTokens, attemptServiceTier, ); const [effectiveCost4, multiplier] = applyPriorityMultiplier( - tieredCost4, attempt.provider, attempt.model, attemptServiceTier, contextTier, + tieredCost4, price.provider, attempt.model, attemptServiceTier, contextTier, ); const priorityLowerBound = contextPriorityLowerBound - || isOpenRouterPriorityLowerBound(attempt.provider, attempt.tierOutcome); + || isOpenRouterPriorityLowerBound(price.provider, attempt.tierOutcome); return { ordinal: attempt.ordinal, provider: attempt.provider, @@ -635,13 +631,13 @@ export function estimateRequestCost( const price = resolveMatchedPrice(input.provider, input.model, overlays, userOverlays, input); if (!price) return null; const [tieredCost4, contextTier, contextPriorityLowerBound] = applyContextTier( - price.cost4, input.provider, input.model, input.usage.inputTokens, input.serviceTier, + price.cost4, price.provider, input.model, input.usage.inputTokens, input.serviceTier, ); const [effectiveCost4, multiplier] = applyPriorityMultiplier( - tieredCost4, input.provider, input.model, input.serviceTier, contextTier, + tieredCost4, price.provider, input.model, input.serviceTier, contextTier, ); const priorityLowerBound = contextPriorityLowerBound || isOpenRouterPriorityLowerBound( - input.provider, + price.provider, typeof input.serviceTier === "object" ? input.serviceTier.tierOutcome : undefined, ); return { diff --git a/src/usage/user-cost-overlays.ts b/src/usage/user-cost-overlays.ts index 22af57e87a..6024e17596 100644 --- a/src/usage/user-cost-overlays.ts +++ b/src/usage/user-cost-overlays.ts @@ -13,19 +13,23 @@ * must not churn the version (see refreshUserCostOverlays). The configured * provider-name set is part of the change identity: adding or removing a * provider changes which names may collapse to a label base in the resolver, - * so it bumps the version even when no overlay row changed. + * so it bumps the version even when no overlay row changed. Exact selectable + * Codex IDs and effective log labels also participate in that identity. * * Display-time estimation only — these rows never affect billing. */ import type { OcxConfig, OcxProviderConfig, ProviderCostOverlay } from "../types"; import { MAX_COST4_RATE, type ExpectedPriceOverlay } from "./expected-prices"; import { redactSecretString } from "../lib/redact"; +import { isSelectableCodexPoolAccount, MAIN_CODEX_ACCOUNT_ID } from "../codex/account-id"; +import { codexAccountLogLabel } from "../codex/account-label"; const EMPTY: readonly ExpectedPriceOverlay[] = []; let active: readonly ExpectedPriceOverlay[] = EMPTY; let activeSignature = ""; let activeConfigured = new Set(); +let activeAccountProviders = codexAccountProviders([]); let version = 0; let preservedDiskOnlyProviders: Record | null = null; @@ -54,6 +58,24 @@ function providerNames(config: OcxConfig): Set { return new Set(Object.keys(config.providers ?? {})); } +/** Exact config-owned identities only; aliases and generic OAuth stores are not authority. */ +function codexAccountProviders(accounts: OcxConfig["codexAccounts"]): Map { + const identities = new Set(["main", MAIN_CODEX_ACCOUNT_ID]); + for (const account of accounts ?? []) { + if (!isSelectableCodexPoolAccount(account)) continue; + identities.add(account.id); + identities.add(codexAccountLogLabel(account)); + } + const mapping = new Map(); + for (const identity of identities) { + mapping.set(identity, "openai"); + for (const provider of ["openai", "chatgpt", "openai-multi"]) { + mapping.set(`${provider}-${identity}`, "openai"); + } + } + return mapping; +} + /** Register one active live-config owner. Multiple server leases may share one config object. */ export function registerPreservedProviderOwner(config: OcxConfig): void { const tagged = config as PreservationTaggedConfig; @@ -289,12 +311,17 @@ export function refreshUserCostOverlays(config: OcxConfig): void { // removing a provider (even one without an overlay) changes which names are // allowed to collapse to a label base, so the resolver memo and the // /api/usage summary cache must be invalidated on that change as well. + // Sort effective account identities so account order, aliases and plan + // metadata do not churn caches; add/remove/label changes still invalidate. const configuredNames = Object.keys(providers ?? {}).sort(); - const signature = `${JSON.stringify(configuredNames)}\u0000${JSON.stringify(rows)}`; + const accountProviders = codexAccountProviders(config.codexAccounts); + const accountEntries = [...accountProviders].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0); + const signature = `${JSON.stringify(configuredNames)}\u0000${JSON.stringify(rows)}\u0000${JSON.stringify(accountEntries)}`; if (signature === activeSignature) return; activeSignature = signature; active = rows; activeConfigured = new Set(configuredNames); + activeAccountProviders = accountProviders; version++; } @@ -303,7 +330,7 @@ export function activeUserCostOverlays(): readonly ExpectedPriceOverlay[] { return active; } -/** Monotonic version bumped on every refresh; used by the estimator memo key. */ +/** Monotonic version bumped on pricing-identity changes; used by the estimator memo key. */ export function userCostOverlayVersion(): number { return version; } @@ -312,3 +339,8 @@ export function userCostOverlayVersion(): number { export function activeConfiguredProviders(): ReadonlySet { return activeConfigured; } + +/** Account pricing identities built at refresh, without reading credential stores. */ +export function activeAccountPricingProviders(): ReadonlyMap { + return activeAccountProviders; +} diff --git a/tests/usage/usage-cost.test.ts b/tests/usage/usage-cost.test.ts index 387ed3c01d..e21c4276e9 100644 --- a/tests/usage/usage-cost.test.ts +++ b/tests/usage/usage-cost.test.ts @@ -1327,6 +1327,184 @@ describe("provider cost overlay (user-configured)", () => { }); }); +describe("Codex account pricing identity", () => { + const modelId = "wp3-synthetic-account-model"; + const account = { id: "cost-account", logLabel: "p123abc", alias: "display-name", email: "fixture@example.invalid", isMain: false }; + const row: ExpectedPriceOverlay = { + provider: "openai", modelId, cost4: RATE, + source: "fixture", verifiedAt: "2026-09-07", status: "verified", + }; + const config = (accounts = [account], providers = {}) => ({ + providers, codexAccounts: accounts, + }) as unknown as OcxConfig; + const forms = (id: string) => [id, ...["openai", "chatgpt", "openai-multi"].map(provider => `${provider}-${id}`)]; + + afterEach(() => refreshUserCostOverlays(config([]))); + + test("exact selectable IDs, effective labels and built-in main forms resolve without model fallback", () => { + refreshUserCostOverlays(config([ + account, + // SHA-256('abc') begins ba7816: an invalid stored label must use the producer's fallback. + { ...account, id: "abc", logLabel: "invalid-label" }, + ])); + for (const id of [account.id, account.logLabel, "abc", "pba7816", "main", "__main__"]) { + for (const provider of forms(id)) { + expect(resolveMatchedPrice(provider, modelId, [row], [], { allowModelLevelFallback: false })) + .toMatchObject({ provider: "openai", cost4: RATE, source: "expected" }); + } + } + }); + + test("aliases, email, invalid rows, unknown IDs, case variants and non-Codex identities stay unmapped", () => { + refreshUserCostOverlays(config([ + account, + { ...account, id: "invalid/id", logLabel: "p111aaa" }, + { ...account, id: "constructor", logLabel: "p222aaa" }, + { ...account, id: "desktop-row", logLabel: "p333aaa", isMain: true }, + { ...account, id: "abc", logLabel: "invalid-label" }, + ])); + for (const provider of [ + ...forms("unknown-account"), ...forms(account.alias), ...forms(account.email), + ...forms("Cost-account"), ...forms("invalid-label"), ...forms("invalid/id"), + "constructor", "desktop-row", "p111aaa", "p222aaa", "p333aaa", "p123abC", + "Openai-cost-account", "openai-cost-account-extra", "anthropic-cost-account", + "xai-cost-account", "oauth-account", "o123abc", "xai-o123abc", "unrelated-hyphen-provider", + ]) { + expect(resolveMatchedPrice(provider, modelId, [row], [], { allowModelLevelFallback: false })).toBeNull(); + } + }); + + test("configured literal namespaces beat account mapping and historical collapse", () => { + const names = [...forms(account.id), ...forms(account.logLabel), ...forms("main"), ...forms("__main__"), "chatgpt", "openai-multi"]; + refreshUserCostOverlays(config([account], Object.fromEntries(names.map(name => [name, {}])))); + for (const provider of names) { + expect(resolveMatchedPrice(provider, modelId, [row], [])).toBeNull(); + const literal = { ...row, provider, cost4: { ...RATE, input: 7 } }; + expect(resolveMatchedPrice(provider, modelId, [row, literal], [])) + .toMatchObject({ provider, cost4: literal.cost4 }); + } + }); + + test("caller-supplied exact user rows beat both canonical user and compiled rows", () => { + refreshUserCostOverlays(config()); + for (const provider of [...forms(account.id), ...forms(account.logLabel)]) { + const canonicalUser = { ...row, cost4: { ...RATE, input: 11 } }; + const exactUser = { ...row, provider, cost4: { ...RATE, input: 17 } }; + expect(resolveMatchedPrice(provider, modelId, [row], [canonicalUser, exactUser])) + .toMatchObject({ provider, source: "user", cost4: exactUser.cost4 }); + } + }); + + test("only recognized historical phex and main suffixes retain the existing fallback", () => { + refreshUserCostOverlays(config([])); + const custom = { ...row, provider: "legacy" }; + for (const provider of ["legacy-pabcdef", "legacy-main"]) { + expect(resolveMatchedPrice(provider, modelId, [custom], [])?.cost4).toEqual(RATE); + } + for (const provider of ["legacy-unknown", "legacy-pABCDEF", "legacy-pabcde", "legacy-oabcdef", "legacy-__main__"]) { + expect(resolveMatchedPrice(provider, modelId, [custom], [])).toBeNull(); + } + }); + + test("account add, effective-label change and removal invalidate memo; presentation and order do not", () => { + const providers = { openai: { modelCosts: { [modelId]: RATE } } }; + refreshUserCostOverlays(config([], providers)); + expect(resolveMatchedPrice(account.id, modelId)).toBeNull(); + expect(resolveMatchedPrice(account.logLabel, modelId)).toBeNull(); + const before = userCostOverlayVersion(); + const second = { ...account, id: "other-account", logLabel: "p456def" }; + refreshUserCostOverlays(config([account, second], providers)); + expect(userCostOverlayVersion()).toBe(before + 1); + for (const provider of [...forms(account.id), account.logLabel]) { + expect(resolveMatchedPrice(provider, modelId)?.cost4).toEqual(RATE); + } + const rows = activeUserCostOverlays(); + const memo = resolveMatchedPrice(account.id, modelId); + const renamed = { ...account, alias: "new-display", email: "new@example.invalid", plan: "pro" }; + refreshUserCostOverlays(config([second, renamed], providers)); + expect(userCostOverlayVersion()).toBe(before + 1); + expect(activeUserCostOverlays()).toBe(rows); + expect(resolveMatchedPrice(account.id, modelId)).toBe(memo); + refreshUserCostOverlays(config([{ ...renamed, logLabel: "p789abc" }, second], providers)); + expect(userCostOverlayVersion()).toBe(before + 2); + expect(resolveMatchedPrice(account.logLabel, modelId)).toBeNull(); + expect(resolveMatchedPrice("p789abc", modelId)?.cost4).toEqual(RATE); + refreshUserCostOverlays(config([second], providers)); + expect(userCostOverlayVersion()).toBe(before + 3); + for (const provider of [...forms(account.id), "p789abc"]) { + expect(resolveMatchedPrice(provider, modelId)).toBeNull(); + } + }); + + test("mapped accounts share request, attempt and combo long-context/Fast pricing with original attribution", () => { + refreshUserCostOverlays(config()); + const usage = { inputTokens: 300_000, outputTokens: 10_000 }; + for (const provider of [...forms(account.id), ...forms(account.logLabel), ...forms("__main__")]) { + for (const serviceTier of [undefined, { responseServiceTier: "priority" }, { responseServiceTier: "default", requestedServiceTier: "priority" }]) { + const input = { provider, model: "gpt-6-astra", usageStatus: "reported" as const, usage, serviceTier }; + const request = estimateRequestCost(input)!; + const attempt = estimateAttemptCost({ ...input, ordinal: 1 }, undefined, serviceTier)!; + const combo = estimateComboCost([{ ...input, ordinal: 1 }, { ...input, ordinal: 2 }], undefined, serviceTier)!; + // 300k * $20/M input + 10k * $75/M output; Fast doubles both. + const expected = serviceTier?.responseServiceTier === "priority" ? 13.5 : 6.75; + expect(request.cost.total).toBeCloseTo(expected, 9); + expect(request.contextTier).toBe("long"); + expect(request.priorityMultiplier).toBe(expected === 13.5 ? 2 : undefined); + expect(attempt.cost).toEqual(request.cost); + expect(attempt.contextTier).toBe(request.contextTier); + expect(attempt.priorityMultiplier).toBe(request.priorityMultiplier); + expect(attempt.provider).toBe(provider); + expect(combo.cost.total).toBeCloseTo(expected * 2, 9); + expect(combo.attempts?.map(entry => entry.provider)).toEqual([provider, provider]); + } + } + }); + + test("literal and direct override namespaces do not inherit OpenAI context or Fast modifiers", () => { + const provider = "openai-p123abc"; + const input = { provider, model: "gpt-6-astra", usageStatus: "reported" as const, + usage: { inputTokens: 300_000, outputTokens: 10_000 }, serviceTier: "priority" }; + const literal = { ...row, provider, modelId: input.model }; + refreshUserCostOverlays(config([account], { [provider]: {} })); + for (const estimate of [estimateRequestCost(input, [literal], []), estimateAttemptCost({ ...input, ordinal: 1 }, [literal], "priority", [])]) { + expect(estimate?.cost.total).toBeCloseTo(1.05, 9); + expect(estimate?.contextTier).toBeUndefined(); + expect(estimate?.priorityMultiplier).toBeUndefined(); + } + refreshUserCostOverlays(config()); + const direct = estimateRequestCost(input, [], [literal]); + expect(direct?.cost.total).toBeCloseTo(1.05, 9); + expect(direct?.contextTier).toBeUndefined(); + expect(direct?.priorityMultiplier).toBeUndefined(); + const combo = estimateComboCost([{ ...input, ordinal: 1 }], [], "priority", [literal]); + expect(combo?.cost.total).toBeCloseTo(1.05, 9); + expect(combo?.contextTier).toBeUndefined(); + expect(combo?.priorityMultiplier).toBeUndefined(); + }); + + test("OpenRouter lower-bound uses the selected namespace, including Codex-name collisions", () => { + const provider = "openrouter-p123abc"; + const tracker = createAdapterTierMetadata({ capability: true, eligibility: "eligible", + fastWire: { kind: "service-tier", canonicalToWire: { priority: "priority" }, foreignCallerTiers: "verbatim" }, + demandDecision: "force-fast" }, { kind: "set", value: "priority" }, "service-tier", "priority")!; + tracker.observeResponseServiceTier("priority"); + const input = { provider, model: modelId, usageStatus: "reported" as const, + usage: { inputTokens: 100, outputTokens: 10 }, ordinal: 1, tierOutcome: tracker.outcome }; + const router = { ...row, provider: "openrouter" }; + refreshUserCostOverlays(config([])); + expect(estimateAttemptCost(input, [router], undefined, [])?.priorityLowerBound).toBe(true); + refreshUserCostOverlays(config([{ ...account, id: provider }])); + expect(estimateAttemptCost(input, [row, router], undefined, [])?.priorityLowerBound).toBeUndefined(); + refreshUserCostOverlays(config([], { [provider]: {} })); + const literal = { ...row, provider }; + const request = estimateRequestCost({ ...input, serviceTier: { tierOutcome: tracker.outcome } }, [literal], []); + expect(request).not.toBeNull(); + expect(request?.priorityLowerBound).toBeUndefined(); + expect(estimateAttemptCost(input, [literal], undefined, [])?.priorityLowerBound).toBeUndefined(); + expect(estimateComboCost([input], [literal], undefined, [])?.priorityLowerBound).toBeUndefined(); + }); +}); + describe("aggregator vendor-prefixed model ids (#3136)", () => { test("restricted resolution partitions memoization and only removes vendor fallback", () => { const model = "anthropic/claude-3-haiku-20240307"; From c35b5a6e504a4513ad59957f5c81b7db45f8bec6 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:29:46 +0900 Subject: [PATCH 060/116] fix(claude): preserve legacy thinking block order [skip ci] Defer item-bound thinking emission until its envelope can place redacted blocks first. Preserve budget enforcement and live text/tool output. Refs #3719; replay/cache acceptance remains open. Co-authored-by: lidge-jun <243035832+lidge-jun@users.noreply.github.com> --- devlog/_plan/260907_lane_d/010_thinking.md | 4 +- src/claude/outbound.ts | 59 ++-- .../claude-outbound.test.ts | 306 +++++++++++++++++- 3 files changed, 343 insertions(+), 26 deletions(-) diff --git a/devlog/_plan/260907_lane_d/010_thinking.md b/devlog/_plan/260907_lane_d/010_thinking.md index e321ac03ce..f2bb7e18bf 100644 --- a/devlog/_plan/260907_lane_d/010_thinking.md +++ b/devlog/_plan/260907_lane_d/010_thinking.md @@ -17,8 +17,10 @@ Astra Dirac found two blockers: unmatched-item reordering and closure memory ove Track bounded reasoningItemKey separately from part identity; flush on changed explicit item identity, and close unrelated pending thinking before another item's red blocks. Only same identity (including both omitted) reorders red before pending thinking. -Release retained thinkingBuf after text frame enqueue, before signature frame enqueue; +Retain thinkingBuf through signature emission as before; queued frame budget stays authoritative, never weakened. Add near-limit valid control, shared-budget collector control, overflow/cancel regressions. Deferred thinking is an accepted visible-latency tradeoff; text/tool frames remain live with incremental-reader coverage. Late done after a different emitted block cannot reorder earlier content. + +Re-audit Dirac: VERDICT PASS, blockers=0. Accept tight artificial budget capacity reduction; retain original overflow assertions and production limits. diff --git a/src/claude/outbound.ts b/src/claude/outbound.ts index 1975d5b390..d4e7758ee0 100644 --- a/src/claude/outbound.ts +++ b/src/claude/outbound.ts @@ -215,6 +215,8 @@ interface OpenBlock { callId?: string; /** Last fixed-size reasoning identity (item + summary/content index) seen by this block. */ reasoningPartKey?: string; + /** Fixed-size item identity; missing IDs only match other missing IDs. */ + reasoningItemKey?: string; thinkingBuf?: string; thinkingBufBytes?: number; reasoningSig?: string; @@ -308,6 +310,20 @@ export function responsesSseToAnthropicSse( open.webSearchArgsEmitted = true; } if (open.kind === "thinking") { + // Delay the index and all thinking frames until closure so a matching + // done envelope can put its redacted blocks first. The existing buffer + // remains charged through signature emission, including queued frames. + open.index = blockIndex++; + emit("content_block_start", { + type: "content_block_start", index: open.index, + content_block: { type: "thinking", thinking: "", signature: "" }, + }); + if (open.thinkingBuf) { + emit("content_block_delta", { + type: "content_block_delta", index: open.index, + delta: { type: "thinking_delta", thinking: open.thinkingBuf }, + }); + } const signature = open.reasoningSig ?? encodeReasoningEnvelope({ txt: open.thinkingBuf ?? "" }, translatorBudget); emit("content_block_delta", { type: "content_block_delta", index: open.index, @@ -323,12 +339,13 @@ export function responsesSseToAnthropicSse( ensureStarted(); if (open && open.kind === kind) return; closeOpenBlock(); + if (kind === "thinking") { + open = { kind, index: -1, thinkingBuf: "", thinkingBufBytes: 0 }; + return; + } const index = blockIndex++; - const contentBlock: Rec = kind === "text" - ? { type: "text", text: "" } - : { type: "thinking", thinking: "", signature: "" }; - emit("content_block_start", { type: "content_block_start", index, content_block: contentBlock }); - open = { kind, index, thinkingBuf: "", thinkingBufBytes: 0 }; + emit("content_block_start", { type: "content_block_start", index, content_block: { type: "text", text: "" } }); + open = { kind, index }; }; const finish = (stopReason: string, usage: unknown) => { if (terminated) return; @@ -405,11 +422,13 @@ export function responsesSseToAnthropicSse( case "response.reasoning_summary_text.delta": case "response.reasoning_text.delta": { if (typeof data.delta !== "string" || data.delta.length === 0) break; + const itemKey = boundedReasoningIdentity(data.item_id); + if (open?.kind === "thinking" && open.reasoningItemKey !== itemKey) closeOpenBlock(); ensureBlock("thinking"); const active = open; if (!active || active.kind !== "thinking") break; // The JSON path joins reasoning summary/content parts with "\n\n" - // (responsesJsonToAnthropicMessage); mirror that at part and item boundaries + // (responsesJsonToAnthropicMessage); mirror that at part boundaries // so multi-part summaries do not glue into one run-on paragraph. Frames // without part indices produce a constant key and never get a separator. const slot = eventName === "response.reasoning_summary_text.delta" @@ -418,7 +437,7 @@ export function responsesSseToAnthropicSse( // Upstream string metadata can be arbitrarily large. Hash strings into fixed-size // components while retaining item and part equality, rather than dropping item_id and // accidentally joining distinct malformed reasoning items. - const partKey = `${boundedReasoningIdentity(data.item_id)}:${slot}`; + const partKey = `${itemKey}:${slot}`; const needsPartSeparator = active.reasoningPartKey !== undefined && active.reasoningPartKey !== partKey; const appended = `${needsPartSeparator ? "\n\n" : ""}${data.delta}`; @@ -436,17 +455,8 @@ export function responsesSseToAnthropicSse( reservation.release(); throw error; } - if (needsPartSeparator) { - emit("content_block_delta", { - type: "content_block_delta", index: active.index, - delta: { type: "thinking_delta", thinking: "\n\n" }, - }); - } + active.reasoningItemKey = itemKey; active.reasoningPartKey = partKey; - emit("content_block_delta", { - type: "content_block_delta", index: active.index, - delta: { type: "thinking_delta", thinking: data.delta }, - }); break; } case "response.output_item.added": { @@ -563,20 +573,27 @@ export function responsesSseToAnthropicSse( const encrypted = typeof item.encrypted_content === "string" ? item.encrypted_content : ""; const env = encrypted ? decodeReasoningEnvelope(encrypted, translatorBudget) : null; const red = env?.red ?? []; - if (env?.sig && open?.kind !== "thinking") ensureBlock("thinking"); - if (open?.kind === "thinking") { - if (env?.sig) open.reasoningSig = env.sig; + const itemKey = boundedReasoningIdentity(item.id); + // A late/unrelated done cannot reorder or sign another item's text. + if (open?.kind === "thinking" && open.reasoningItemKey !== itemKey) { closeOpenBlock(); } if (red.length > 0) { ensureStarted(); - closeOpenBlock(); + if (open?.kind !== "thinking") closeOpenBlock(); } for (const data of red) { const idx = blockIndex++; emit("content_block_start", { type: "content_block_start", index: idx, content_block: { type: "redacted_thinking", data } }); emit("content_block_stop", { type: "content_block_stop", index: idx }); } + if (env?.sig && open?.kind !== "thinking") { + ensureBlock("thinking"); + } + if (open?.kind === "thinking") { + if (env?.sig) open.reasoningSig = env.sig; + closeOpenBlock(); + } } break; } diff --git a/tests/claude-integration/claude-outbound.test.ts b/tests/claude-integration/claude-outbound.test.ts index 67380bb44a..72f7a22bdf 100644 --- a/tests/claude-integration/claude-outbound.test.ts +++ b/tests/claude-integration/claude-outbound.test.ts @@ -483,8 +483,8 @@ describe("claude outbound SSE", () => { responsesSseToAnthropicSse(streamFromChunks([upstream]), "m"), "m", ) as Record; - expect(msg.content.find((b: Record) => b.type === "thinking").thinking) - .toBe("AB\n\nC\n\nD"); + expect(msg.content.filter((b: Record) => b.type === "thinking") + .map((b: Record) => b.thinking)).toEqual(["AB", "C\n\nD"]); }); test("malformed array reasoning identities retain distinct boundaries", async () => { @@ -505,8 +505,8 @@ describe("claude outbound SSE", () => { responsesSseToAnthropicSse(streamFromChunks([upstream]), "m"), "m", ) as Record; - expect(msg.content.find((b: Record) => b.type === "thinking").thinking) - .toBe("A\n\nB"); + expect(msg.content.filter((b: Record) => b.type === "thinking") + .map((b: Record) => b.thinking)).toEqual(["A", "B"]); }); test("data-only Responses frames infer event names from payload types", async () => { @@ -1304,3 +1304,301 @@ describe("sanitizeWebSearchInput (#381)", () => { expect(events[3].data.delta).toEqual({ type: "signature_delta", signature: "sig-only" }); }); }); + +describe("deferred Claude thinking order", () => { + const fixtures = [ + { + name: "combined envelope with preceding multipart deltas", + envelope: { sig: "signed-visible", red: ["opaque-1", "opaque-2"], txt: "hidden-only" }, + deltas: [ + sse("response.reasoning_summary_text.delta", { item_id: "rs", summary_index: 0, delta: "Fir" }), + sse("response.reasoning_summary_text.delta", { item_id: "rs", summary_index: 0, delta: "st" }), + sse("response.reasoning_summary_text.delta", { item_id: "rs", summary_index: 1, delta: "Second" }), + sse("response.reasoning_text.delta", { item_id: "rs", content_index: 0, delta: "Third" }), + ], + summary: [{ text: "First" }, { text: "Second" }], + content: [{ text: "Third" }], + expected: [ + { type: "text", text: "prefix" }, + { type: "redacted_thinking", data: "opaque-1" }, + { type: "redacted_thinking", data: "opaque-2" }, + { type: "thinking", thinking: "First\n\nSecond\n\nThird", signature: "signed-visible" }, + ], + }, + { + name: "combined envelope without deltas keeps signed thinking empty", + envelope: { sig: "signed-empty", red: ["opaque-1", "opaque-2"], txt: "hidden-only" }, + deltas: [], summary: [], content: [], + expected: [ + { type: "text", text: "prefix" }, + { type: "redacted_thinking", data: "opaque-1" }, + { type: "redacted_thinking", data: "opaque-2" }, + { type: "thinking", thinking: "", signature: "signed-empty" }, + ], + }, + { + name: "signed-only envelope", + envelope: { sig: "signed-only", txt: "hidden-only" }, + deltas: [], summary: [], content: [], + expected: [ + { type: "text", text: "prefix" }, + { type: "thinking", thinking: "", signature: "signed-only" }, + ], + }, + { + name: "red-only envelope", + envelope: { red: ["opaque-1", "opaque-2"], txt: "hidden-only" }, + deltas: [], summary: [], content: [], + expected: [ + { type: "text", text: "prefix" }, + { type: "redacted_thinking", data: "opaque-1" }, + { type: "redacted_thinking", data: "opaque-2" }, + ], + }, + ]; + + for (const fixture of fixtures) { + test(`${fixture.name}: JSON and collected SSE match literal content`, async () => { + const item = { + type: "reasoning", id: "rs", summary: fixture.summary, content: fixture.content, + encrypted_content: encodeReasoningEnvelope(fixture.envelope), + }; + const frames = [ + sse("response.output_text.delta", { delta: "prefix" }), + ...fixture.deltas, + sse("response.output_item.done", { item }), + sse("response.completed", { response: { status: "completed" } }), + ]; + const json = responsesJsonToAnthropicMessage({ status: "completed", output: [ + { type: "message", content: [{ type: "output_text", text: "prefix" }] }, item, + ] }, "m"); + const message = await collectAnthropicMessage( + responsesSseToAnthropicSse(streamFromChunks(frames), "m", { pingIntervalMs: 0 }), "m", + ); + expect(json.content).toEqual(fixture.expected); + expect(message.content).toEqual(fixture.expected); + expect(JSON.stringify(message)).not.toContain("hidden-only"); + expect(message.stop_reason).toBe("end_turn"); + + const events = await collectEvents(responsesSseToAnthropicSse(streamFromChunks(frames), "m", { pingIntervalMs: 0 })); + let active: number | null = null; + let next = 0; + for (const event of events) { + if (event.name === "content_block_start") { + expect(active).toBeNull(); + expect(event.data.index).toBe(next); + active = next++; + } else if (event.name === "content_block_delta" || event.name === "content_block_stop") { + expect(active).not.toBeNull(); + expect(event.data.index).toBe(active); + if (event.name === "content_block_stop") active = null; + } + } + expect(active).toBeNull(); + expect(next).toBe(fixture.expected.length); + expect(events.at(-1)?.name).toBe("message_stop"); + }); + } + + for (const [deltaId, doneId, matching] of [ + ["a", "a", true], ["a", "b", false], + [undefined, undefined, true], ["a", undefined, false], [undefined, "b", false], + ] as const) { + test(`done item boundary ${String(deltaId)} -> ${String(doneId)}`, async () => { + const message = await collectAnthropicMessage(responsesSseToAnthropicSse(streamFromChunks([ + sse("response.reasoning_text.delta", { item_id: deltaId, delta: "A" }), + sse("response.output_item.done", { item: { + type: "reasoning", id: doneId, + encrypted_content: encodeReasoningEnvelope({ sig: "done-signature", red: ["done-red"] }), + } }), + sse("response.completed", { response: { status: "completed" } }), + ]), "m", { pingIntervalMs: 0 }), "m"); + expect(message.content).toEqual(matching ? [ + { type: "redacted_thinking", data: "done-red" }, + { type: "thinking", thinking: "A", signature: "done-signature" }, + ] : [ + { type: "thinking", thinking: "A", signature: "ocxr1:eyJ0eHQiOiJBIn0=" }, + { type: "redacted_thinking", data: "done-red" }, + { type: "thinking", thinking: "", signature: "done-signature" }, + ]); + }); + } + + for (const [firstId, secondId] of [["a", "b"], ["a", undefined], [undefined, "b"]] as const) { + test(`delta item boundary ${String(firstId)} -> ${String(secondId)} flushes first`, async () => { + const message = await collectAnthropicMessage(responsesSseToAnthropicSse(streamFromChunks([ + sse("response.reasoning_text.delta", { item_id: firstId, delta: "A" }), + sse("response.reasoning_text.delta", { item_id: secondId, delta: "B" }), + sse("response.output_item.done", { item: { + type: "reasoning", id: secondId, + encrypted_content: encodeReasoningEnvelope({ sig: "second-signature", red: ["second-red"] }), + } }), + sse("response.completed", { response: { status: "completed" } }), + ]), "m", { pingIntervalMs: 0 }), "m"); + expect(message.content).toEqual([ + { type: "thinking", thinking: "A", signature: "ocxr1:eyJ0eHQiOiJBIn0=" }, + { type: "redacted_thinking", data: "second-red" }, + { type: "thinking", thinking: "B", signature: "second-signature" }, + ]); + }); + } + + test("separate red and signed items preserve their stream order", async () => { + const items = [ + { type: "reasoning", id: "red", encrypted_content: encodeReasoningEnvelope({ red: ["first-red"] }) }, + { type: "reasoning", id: "signed", summary: [{ text: "A" }], encrypted_content: encodeReasoningEnvelope({ sig: "sig-A" }) }, + { type: "reasoning", id: "red-last", encrypted_content: encodeReasoningEnvelope({ red: ["last-red"] }) }, + ]; + const message = await collectAnthropicMessage(responsesSseToAnthropicSse(streamFromChunks([ + sse("response.output_item.done", { item: items[0] }), + sse("response.reasoning_text.delta", { item_id: "signed", delta: "A" }), + sse("response.output_item.done", { item: items[1] }), + sse("response.output_item.done", { item: items[2] }), + sse("response.completed", { response: { status: "completed" } }), + ]), "m", { pingIntervalMs: 0 }), "m"); + const expected = [ + { type: "redacted_thinking", data: "first-red" }, + { type: "thinking", thinking: "A", signature: "sig-A" }, + { type: "redacted_thinking", data: "last-red" }, + ]; + expect(message.content).toEqual(expected); + expect(responsesJsonToAnthropicMessage({ output: items }, "m").content).toEqual(expected); + }); + + for (const genuineSignature of [false, true]) { + for (const buffered of [false, true]) { + test(`near-limit valid thinking: ${genuineSignature ? "genuine" : "fallback"}, ${buffered ? "shared collector" : "stream"}`, async () => { + // The live collector also retains the emitted content/signature, unlike + // the stream-only near-limit control. Both use one budget throughout. + // Shared encoding admission needs ~254 KiB for the 20 KiB fallback + // including source and queued text; genuine signatures bypass encoding. + const maxTurnBytes = (genuineSignature ? (buffered ? 128 : 70) : (buffered ? 320 : 280)) * 1024; + const budget = createTestTranslatorBudget({ maxTurnBytes }); + const text = "x".repeat((genuineSignature ? 32 : 20) * 1024); + const frames = Array.from({ length: text.length / 256 }, () => sse("response.reasoning_text.delta", { + item_id: "rs_control", content_index: 0, delta: text.slice(0, 256), + })); + frames.push(sse("response.output_item.done", { item: { + type: "reasoning", id: "rs_control", + ...(genuineSignature ? { encrypted_content: encodeReasoningEnvelope({ sig: "control-signature", red: ["control-red"] }) } : {}), + } })); + frames.push(sse("response.completed", { response: { status: "completed" } })); + const stream = responsesSseToAnthropicSse(streamFromChunks(frames), "m", { + translatorBudget: budget, pingIntervalMs: 0, + }); + if (buffered) { + // Collect live with the exact translator budget; no capture/reset/new budget. + const message = await collectAnthropicMessage(stream, "m", budget); + expect(message.type).toBe("message"); + const content = message.content as Record[]; + expect(content.map(block => block.type)).toEqual(genuineSignature + ? ["redacted_thinking", "thinking"] : ["thinking"]); + const thinking = content.at(-1)!; + expect(thinking.thinking).toBe(text); + if (genuineSignature) expect(thinking.signature).toBe("control-signature"); + else expect(decodeReasoningEnvelope(thinking.signature as string)?.txt).toBe(text); + expect(message.stop_reason).toBe("end_turn"); + } else { + const events = await collectEvents(stream); + expect(events.filter(event => event.data.delta?.type === "thinking_delta") + .map(event => event.data.delta.thinking).join("")).toBe(text); + const signature = events.find(event => event.data.delta?.type === "signature_delta")?.data.delta.signature; + if (genuineSignature) expect(signature).toBe("control-signature"); + else expect(decodeReasoningEnvelope(signature)?.txt).toBe(text); + expect(events.at(-1)?.name).toBe("message_stop"); + expect(events.some(event => event.name === "error")).toBe(false); + } + expect(budget.snapshot().overflows).toBe(0); + expect(budget.snapshot().highWaterBytes).toBeGreaterThan(60 * 1024); + expect(budget.snapshot().highWaterBytes).toBeLessThanOrEqual(maxTurnBytes); + }); + } + } + + test("cancelling deferred thinking releases its buffer and cancels upstream", async () => { + const budget = createTestTranslatorBudget(); + const text = "pending".repeat(1024); + let signalConsumed!: () => void; + const consumed = new Promise(resolve => { signalConsumed = resolve; }); + let sent = false; + let cancelReason: unknown; + const upstream = new ReadableStream({ + pull(controller) { + if (sent) { + // A second read proves the first delta has passed through handleFrame. + signalConsumed(); + return; + } + sent = true; + controller.enqueue(new TextEncoder().encode(sse("response.reasoning_text.delta", { + item_id: "pending", delta: text, + }))); + }, + cancel(reason) { cancelReason = reason; }, + }, { highWaterMark: 0 }); + const stream = responsesSseToAnthropicSse(upstream, "m", { translatorBudget: budget, pingIntervalMs: 0 }); + await consumed; + expect(budget.snapshot().currentBytes).toBeGreaterThanOrEqual(text.length); + await stream.cancel("client cancelled"); + expect(cancelReason).toBe("client cancelled"); + expect(budget.snapshot().currentBytes).toBe(0); + expect(budget.snapshot().overflows).toBe(0); + }); + + test("thinking waits for closure while text and tool arguments remain incremental; late done stays late", async () => { + let controller!: ReadableStreamDefaultController; + const upstream = new ReadableStream({ start(value) { controller = value; } }); + const reader = responsesSseToAnthropicSse(upstream, "m", { pingIntervalMs: 0 }).getReader(); + const send = (name: string, data: Record) => controller.enqueue(new TextEncoder().encode(sse(name, data))); + const next = async () => { + const { done, value } = await reader.read(); + expect(done).toBe(false); + return JSON.parse(new TextDecoder().decode(value).split("\ndata: ")[1]!.trim()) as Record; + }; + try { + send("response.reasoning_text.delta", { item_id: "early", delta: "A" }); + expect(await next()).toMatchObject({ type: "message_start" }); + expect(await next()).toEqual({ type: "ping" }); + // An explicit transport checkpoint proves no thinking start/index/text escaped. + send("response.heartbeat", {}); + expect(await next()).toEqual({ type: "ping" }); + + send("response.output_text.delta", { delta: "live-1" }); + expect(await next()).toMatchObject({ type: "content_block_start", index: 0, content_block: { type: "thinking" } }); + expect(await next()).toEqual({ type: "content_block_delta", index: 0, delta: { type: "thinking_delta", thinking: "A" } }); + expect(await next()).toEqual({ type: "content_block_delta", index: 0, delta: { type: "signature_delta", signature: "ocxr1:eyJ0eHQiOiJBIn0=" } }); + expect(await next()).toEqual({ type: "content_block_stop", index: 0 }); + expect(await next()).toMatchObject({ type: "content_block_start", index: 1, content_block: { type: "text" } }); + expect(await next()).toEqual({ type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "live-1" } }); + send("response.output_text.delta", { delta: "live-2" }); + expect(await next()).toEqual({ type: "content_block_delta", index: 1, delta: { type: "text_delta", text: "live-2" } }); + + send("response.output_item.added", { item: { type: "function_call", id: "fc", call_id: "call", name: "Read" } }); + expect(await next()).toEqual({ type: "content_block_stop", index: 1 }); + expect(await next()).toMatchObject({ type: "content_block_start", index: 2, content_block: { type: "tool_use", name: "Read" } }); + for (const fragment of ['{"path":', '"/x"}']) { + send("response.function_call_arguments.delta", { item_id: "fc", delta: fragment }); + expect(await next()).toEqual({ type: "content_block_delta", index: 2, delta: { type: "input_json_delta", partial_json: fragment } }); + } + send("response.output_item.done", { item: { type: "function_call", id: "fc" } }); + expect(await next()).toEqual({ type: "content_block_stop", index: 2 }); + + send("response.output_item.done", { item: { + type: "reasoning", id: "early", encrypted_content: encodeReasoningEnvelope({ sig: "late-sig", red: ["late-red"] }), + } }); + expect(await next()).toEqual({ type: "content_block_start", index: 3, content_block: { type: "redacted_thinking", data: "late-red" } }); + expect(await next()).toEqual({ type: "content_block_stop", index: 3 }); + expect(await next()).toEqual({ type: "content_block_start", index: 4, content_block: { type: "thinking", thinking: "", signature: "" } }); + expect(await next()).toEqual({ type: "content_block_delta", index: 4, delta: { type: "signature_delta", signature: "late-sig" } }); + expect(await next()).toEqual({ type: "content_block_stop", index: 4 }); + send("response.completed", { response: { status: "completed" } }); + controller.close(); + expect(await next()).toMatchObject({ type: "message_delta", delta: { stop_reason: "tool_use" } }); + expect(await next()).toEqual({ type: "message_stop" }); + expect((await reader.read()).done).toBe(true); + } finally { + await reader.cancel(); + reader.releaseLock(); + } + }); +}); From c5fb7e3332432c6546bffa9990bce5b971653139 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:30:46 +0900 Subject: [PATCH 061/116] fix(models): guard edits during unknown receipt recovery [skip ci] Co-authored-by: lidge-jun <243035832+lidge-jun@users.noreply.github.com> --- devlog/_plan/260907_lane_d/020_receipt.md | 5 +++++ gui/src/components/ModelDisplayNameDialog.tsx | 20 +++++++++++++------ gui/src/pages/Models.tsx | 1 + gui/tests/models-display-name-editor.test.tsx | 12 +++++++++-- 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/devlog/_plan/260907_lane_d/020_receipt.md b/devlog/_plan/260907_lane_d/020_receipt.md index 7b710df91e..97568c39a8 100644 --- a/devlog/_plan/260907_lane_d/020_receipt.md +++ b/devlog/_plan/260907_lane_d/020_receipt.md @@ -10,3 +10,8 @@ and ordinary validation error remain editable. Screenshot changed disabled input/reset with retry available. Verification: NOT RUN locally by user instruction; focused tests execute in final top-head Cross-platform CI. + +Implementation: unknown outcome guards input/reset handlers and submit, and focuses Retry +when saving fails without a receipt. Saved:true remains editable. Transport/body failure +matrix attempts a replacement intent and asserts no second PUT before read-only retry. +Astra Herschel plan verdict PASS. Screenshots and product execution await top CI artifact. diff --git a/gui/src/components/ModelDisplayNameDialog.tsx b/gui/src/components/ModelDisplayNameDialog.tsx index 2a57ff8279..09854e104d 100644 --- a/gui/src/components/ModelDisplayNameDialog.tsx +++ b/gui/src/components/ModelDisplayNameDialog.tsx @@ -10,6 +10,7 @@ interface ModelDisplayNameDialogProps { saving: boolean; requestError: string | null; currentNamePending?: boolean; + mutationOutcomeUnknown?: boolean; onRetry?: () => void; onEdit?: () => void; onSave: (displayName: string) => void; @@ -28,6 +29,7 @@ export default function ModelDisplayNameDialog({ saving, requestError, currentNamePending = false, + mutationOutcomeUnknown = false, onRetry, onEdit, onSave, @@ -37,6 +39,7 @@ export default function ModelDisplayNameDialog({ const t = useT(); const dialogRef = useRef(null); const inputRef = useRef(null); + const submitRef = useRef(null); const wasSavingRef = useRef(saving); const titleId = useId(); const helpId = useId(); @@ -55,8 +58,11 @@ export default function ModelDisplayNameDialog({ useEffect(() => { const saveFailed = wasSavingRef.current && !saving && Boolean(requestError); wasSavingRef.current = saving; - if (saveFailed) inputRef.current?.focus(); - }, [requestError, saving]); + if (saveFailed) { + if (mutationOutcomeUnknown) submitRef.current?.focus(); + else inputRef.current?.focus(); + } + }, [requestError, saving, mutationOutcomeUnknown]); // Parent replaces this snapshot only after a confirmed mutation, not typing or polling. // Adjust before committing children, preserving the mounted dialog and its focus refs. @@ -102,6 +108,7 @@ export default function ModelDisplayNameDialog({ event.preventDefault(); if (saving) return; if (onRetry) { onRetry(); return; } + if (mutationOutcomeUnknown) return; const nextValidationKey = modelDisplayNameValidationKey(draft); setValidationKey(nextValidationKey); if (!nextValidationKey) onSave(draft.trim()); @@ -137,8 +144,9 @@ export default function ModelDisplayNameDialog({ placeholder={t("models.displayNamePlaceholder")} aria-describedby={`${helpId}${visibleError ? ` ${errorId}` : ""}`} aria-invalid={validationError ? true : undefined} - disabled={saving} + disabled={saving || mutationOutcomeUnknown} onChange={event => { + if (saving || mutationOutcomeUnknown) return; onEdit?.(); setDraft(event.target.value); setValidationKey(null); @@ -157,15 +165,15 @@ export default function ModelDisplayNameDialog({ -
diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx index c342866d7e..fc8db5626e 100644 --- a/gui/src/pages/Models.tsx +++ b/gui/src/pages/Models.tsx @@ -2643,6 +2643,7 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; saving={displayNameSaving} requestError={displayNameRequestError} currentNamePending={displayNameCurrentPending} + mutationOutcomeUnknown={displayNameRecovery?.confirmed === false} onRetry={displayNameRecovery ? () => void saveDisplayName(displayNameRecovery.value) : undefined} onEdit={() => setDisplayNameRecovery(null)} onSave={value => void saveDisplayName(value)} diff --git a/gui/tests/models-display-name-editor.test.tsx b/gui/tests/models-display-name-editor.test.tsx index b0656391ed..9d67f986e0 100644 --- a/gui/tests/models-display-name-editor.test.tsx +++ b/gui/tests/models-display-name-editor.test.tsx @@ -448,8 +448,16 @@ describe("Models dashboard discovered display name integration", () => { expect(currentNameText()).toContain("Current name unavailable until refresh"); expect(currentNameText()).not.toContain("Your name"); expect(container.textContent).toContain("The change may have been saved"); + expect(dialogInput().disabled).toBe(true); + expect(dialogButton("Reset name").disabled).toBe(true); expect(dialogButton("Retry").disabled).toBe(false); expect(dialogButton("Cancel").disabled).toBe(false); + await act(async () => { + setInputValue(dialogInput(), "Replacement intent"); + dialogButton("Reset name").dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true })); + }); + expect(dialogButton("Retry").disabled).toBe(false); + expect(mutationBodies).toHaveLength(1); await act(async () => container.querySelector("dialog form")!.dispatchEvent( new testWindow.Event("submit", { bubbles: true, cancelable: true }), )); @@ -522,12 +530,12 @@ describe("Models dashboard discovered display name integration", () => { if (stage === "reload") expect(seenSignals[1]).toBe(seenSignals[0]); await act(async () => deadline.abort(new DOMException("Timed out", "TimeoutError"))); await flush(); - expect(dialogInput().disabled).toBe(false); + expect(dialogInput().disabled).toBe(stage === "mutation"); expect(dialogButton("Cancel").disabled).toBe(false); expect(dialogInput().value).toBe("Possibly saved"); expect(container.textContent).toContain(stage === "mutation" ? "The change may have been saved" : "The change was saved"); - expect(testWindow.document.activeElement).toBe(dialogInput()); + expect(testWindow.document.activeElement).toBe(stage === "mutation" ? dialogButton("Retry") : dialogInput()); stall = false; if (descriptor) Object.defineProperty(AbortSignal, "timeout", descriptor); await act(async () => dialogButton("Retry").click()); From c44c6de87389a95ab798b648659fbc0838af170b Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:11:13 +0900 Subject: [PATCH 062/116] test(usage): use approved synthetic email domains [skip ci] Exact top CI logs on macOS and Windows identified the same privacy-scan fixture rejection. Keep scanner rules and assertions unchanged. Co-authored-by: rrmlima <137737127+rrmlima@users.noreply.github.com> --- tests/usage/usage-cost.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/usage/usage-cost.test.ts b/tests/usage/usage-cost.test.ts index e21c4276e9..f234622e07 100644 --- a/tests/usage/usage-cost.test.ts +++ b/tests/usage/usage-cost.test.ts @@ -1329,7 +1329,7 @@ describe("provider cost overlay (user-configured)", () => { describe("Codex account pricing identity", () => { const modelId = "wp3-synthetic-account-model"; - const account = { id: "cost-account", logLabel: "p123abc", alias: "display-name", email: "fixture@example.invalid", isMain: false }; + const account = { id: "cost-account", logLabel: "p123abc", alias: "display-name", email: "fixture@example.test", isMain: false }; const row: ExpectedPriceOverlay = { provider: "openai", modelId, cost4: RATE, source: "fixture", verifiedAt: "2026-09-07", status: "verified", @@ -1420,7 +1420,7 @@ describe("Codex account pricing identity", () => { } const rows = activeUserCostOverlays(); const memo = resolveMatchedPrice(account.id, modelId); - const renamed = { ...account, alias: "new-display", email: "new@example.invalid", plan: "pro" }; + const renamed = { ...account, alias: "new-display", email: "new@example.test", plan: "pro" }; refreshUserCostOverlays(config([second, renamed], providers)); expect(userCostOverlayVersion()).toBe(before + 1); expect(activeUserCostOverlays()).toBe(rows); From 341d71dd553fdf65dde3e52038a0327a96e56354 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:45:22 +0900 Subject: [PATCH 063/116] feat(models): edit manual token prices and preserve explicit zero [skip ci] Expose modelCosts via the Models editor and models price/set-price CLI. Preserve sibling prices, support automatic reset, and treat explicit zero user rates as known-zero display estimates. Refs #3667. Co-authored-by: nordz0r <6949669+nordz0r@users.noreply.github.com> --- .../_plan/260907_lane_d/040_price_editor.md | 21 + .../fr/reference/configuration/providers.md | 2 +- .../ja/reference/configuration/providers.md | 2 +- .../ko/reference/configuration/providers.md | 2 +- .../docs/reference/cli/providers-accounts.md | 2 + .../docs/reference/configuration/providers.md | 2 +- .../content/docs/reference/management-api.md | 23 + .../ru/reference/configuration/providers.md | 2 +- .../tr/reference/configuration/providers.md | 2 +- .../reference/configuration/providers.md | 2 +- gui/src/components/ModelPriceDialog.tsx | 235 ++++++++++ gui/src/i18n/de.ts | 24 + gui/src/i18n/en.ts | 24 + gui/src/i18n/fr.ts | 24 + gui/src/i18n/ja.ts | 24 + gui/src/i18n/ko.ts | 24 + gui/src/i18n/ru.ts | 24 + gui/src/i18n/tr.ts | 24 + gui/src/i18n/zh-TW.ts | 24 + gui/src/i18n/zh.ts | 24 + gui/src/pages/Models.tsx | 35 ++ gui/src/pages/models-shared.ts | 1 + gui/tests/models-price-editor.test.tsx | 427 ++++++++++++++++++ scripts/test-layout/layout.json | 4 +- .../ocx/references/01_management_surface.md | 41 +- src/cli/capabilities.ts | 25 + src/cli/models-runtime-subcommands.ts | 2 + src/cli/models-runtime.ts | 68 ++- src/server/management/model-routes.ts | 59 ++- src/server/management/model-rows.ts | 5 + src/server/management/route-registry.ts | 2 + src/usage/cost.ts | 10 +- tests/cli/cli-models-price.test.ts | 153 +++++++ tests/cli/cli-models-runtime-dispatch.test.ts | 17 +- tests/fixtures/test-layout-expected.json | 4 +- .../server/model-costs-management-api.test.ts | 270 +++++++++++ tests/usage/usage-cost.test.ts | 25 +- 37 files changed, 1627 insertions(+), 32 deletions(-) create mode 100644 gui/src/components/ModelPriceDialog.tsx create mode 100644 gui/tests/models-price-editor.test.tsx create mode 100644 tests/cli/cli-models-price.test.ts create mode 100644 tests/server/model-costs-management-api.test.ts diff --git a/devlog/_plan/260907_lane_d/040_price_editor.md b/devlog/_plan/260907_lane_d/040_price_editor.md index 4628710d0d..8d79b2160e 100644 --- a/devlog/_plan/260907_lane_d/040_price_editor.md +++ b/devlog/_plan/260907_lane_d/040_price_editor.md @@ -21,3 +21,24 @@ A fold-back: add GET/PUT entries in src/server/management/route-registry.ts. Reuse providerModelCostsConfigError. GET returns sanitized per-provider modelCosts map; Models owns a typed map loaded with catalog or dedicated GET, so manual badges survive reload. CLI omitted cache-read/cache-write rates default to zero, explicitly documented. + +P revalidation/API contract: GET /api/providers/{provider}/model-costs returns +{provider,modelCosts}; PUT accepts {modelId,cost:Cost4|null}, returns +{ok:true,provider,modelId,cost}. Null deletes only that model key. Models API adds +manualPricing boolean on applicable rows so badges survive reload, while the dialog +GET owns editable rates. CLI models price reads; models set-price writes/resets. +Same C2 phase splits disjoint workers: backend API/CLI/model-row/tests; frontend dialog/ +Models/types/i18n/tests; main owns explicit-zero cost semantics, docs and manifests. +No worker commits/pushes/runs local checks. Main integrates once both return. +Main granted D exactly the zero sentence in all seven translated providers config +reference pages; leave all other sections to E/M. New i18n keys are append-only. + +Implementation checkpoint: GET/PUT editor and two CLI verbs share the four-rate store; +manualPricing is emitted only for exact stored overrides. All-zero user prices are +known-zero estimates while catalog zero fallbacks remain unchanged. API/CLI and dialog +regressions cover persistence, reset, sibling isolation, invalid input and unknown receipts. +All 9 locale catalogs gained matching append-only keys. Seven existing configuration +rows (English plus six translations) had only the zero sentence updated; zh-tw has no +modelCosts row on this baseline and was left untouched. CLI surface regenerated by its +own generator, not a build or test. New backend test names appended to both manifests. +Local suites/typecheck/build/install NOT RUN; final top CI and screenshot remain open. diff --git a/docs-site/src/content/docs/fr/reference/configuration/providers.md b/docs-site/src/content/docs/fr/reference/configuration/providers.md index 96d00e5668..1d043fc7fd 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/fr/reference/configuration/providers.md @@ -104,7 +104,7 @@ sauvegarde dont le contenu diffère, puis réécrit en identifiants sans préfix | `modelAutoCompactTokenLimits?` | `Record` | Budgets souples de compactage automatique par modèle, sous forme d'entiers sûrs positifs. Ils peuvent uniquement abaisser l'enveloppe effective de 90 % du contexte ou de l'entrée maximale et sont omis lorsqu'aucune fenêtre de contexte faisant autorité n'est connue. Pour le fournisseur canonique `openai`, les clés doivent être les identifiants exacts de modèles natifs pris en charge, sans préfixe de fournisseur ni de sélecteur de compte. PATCH fusionne les entrées ; `null` supprime une clé, tandis que `null` pour le champ entier efface la table. Ces marqueurs `null` sont réservés à PATCH. | | `defaultMaxOutputTokens?` | `number` | Solution de secours `openai-chat` à l’échelle du fournisseur lorsque le client omet `max_output_tokens`. | | `modelMaxOutputTokens?` | `Record` | Budgets de repli `openai-chat` positifs par modèle ; les correspondances exactes ou par motif priment sur la valeur par défaut du fournisseur. | -| `modelCosts?` | `Record` | Prix affichés par modèle (USD par 1M de jetons), indexés par l'identifiant exact du modèle en amont de ce fournisseur — et non par un identifiant de fournisseur ni par une étiquette routée `provider/model`, par exemple `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`. Tout identifiant de modèle constitue une clé valide : les fournisseurs personnalisés peuvent cibler n'importe quel point de terminaison compatible avec OpenAI au moyen de l'adaptateur `openai-chat`, et les identifiants de fournisseur locaux ou internes fonctionnent même s'ils sont absents des catalogues intégrés. Les prix configurés par l'utilisateur priment sur les catalogues intégrés dans les estimations des pages Journaux (`~$`) et Utilisation. Les entrées historiques sont recalculées à partir de la surcharge actuelle ; modifier un prix peut donc changer les totaux antérieurs. L'ordre de repli est le suivant : `modelCosts` défini par l'utilisateur → catalogue jawcode → surcharge des prix attendus → repli propre au fournisseur au niveau du modèle. Une entrée entièrement nulle passe à la source suivante. Chaque tarif doit être un nombre fini positif ou nul, inférieur ou égal à 1 000 000 (USD par 1M de jetons) ; les lignes hors plage sont rejetées par l'interface de gestion et ignorées au chargement. Ces valeurs servent uniquement à l'estimation lors de l'affichage : les surcharges n'affectent jamais le routage, la sélection des comptes, les quotas ni la facturation. | +| `modelCosts?` | `Record` | Prix affichés par modèle (USD par 1M de jetons), indexés par l'identifiant exact du modèle en amont de ce fournisseur — et non par un identifiant de fournisseur ni par une étiquette routée `provider/model`, par exemple `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`. Tout identifiant de modèle constitue une clé valide : les fournisseurs personnalisés peuvent cibler n'importe quel point de terminaison compatible avec OpenAI au moyen de l'adaptateur `openai-chat`, et les identifiants de fournisseur locaux ou internes fonctionnent même s'ils sont absents des catalogues intégrés. Les prix configurés par l'utilisateur priment sur les catalogues intégrés dans les estimations des pages Journaux (`~$`) et Utilisation. Les entrées historiques sont recalculées à partir de la surcharge actuelle ; modifier un prix peut donc changer les totaux antérieurs. L'ordre de repli est le suivant : `modelCosts` défini par l'utilisateur → catalogue jawcode → surcharge des prix attendus → repli propre au fournisseur au niveau du modèle. Une surcharge utilisateur explicitement définie à zéro produit une estimation nulle connue ; supprimez cette entrée pour rétablir la tarification automatique. Les prix de catalogue entièrement nuls restent soumis au repli. Chaque tarif doit être un nombre fini positif ou nul, inférieur ou égal à 1 000 000 (USD par 1M de jetons) ; les lignes hors plage sont rejetées par l'interface de gestion et ignorées au chargement. Ces valeurs servent uniquement à l'estimation lors de l'affichage : les surcharges n'affectent jamais le routage, la sélection des comptes, les quotas ni la facturation. | | `headers?` | `Record` | En-têtes supplémentaires en amont. L'autorisation, les cookies, les en-têtes de clé API, les nouvelles lignes intégrées et les noms invalides sont rejetés. | | `openRouterRouting?` | `OpenRouterProviderRouting` | Préférences OpenRouter `order`, `only` et `allowFallbacks` par défaut ; valable uniquement pour les OpenRouter canoniques avec `openai-chat`. | | `modelOpenRouterRouting?` | `Record` | Remplacements exacts de l'ID de modèle qui remplacent la préférence OpenRouter à l'échelle du fournisseur. | diff --git a/docs-site/src/content/docs/ja/reference/configuration/providers.md b/docs-site/src/content/docs/ja/reference/configuration/providers.md index 8938073e6c..e298d36559 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ja/reference/configuration/providers.md @@ -93,7 +93,7 @@ account を削除しても mapping は保持され、同じ id を再追加す | `modelAutoCompactTokenLimits?` | `Record` | モデルごとの正の安全な整数によるソフト自動圧縮予算。実効値であるコンテキストまたは最大入力の 90% の上限を下げることだけができ、信頼できるコンテキストウィンドウが不明な場合は出力されません。canonical `openai` では、キーは provider や account-selector の接頭辞を含まない、サポート対象の正確なネイティブモデル ID でなければなりません。provider PATCH はエントリをマージし、キーを `null` にするとそのキーを削除し、フィールド全体を `null` にするとマップを消去します。これらの `null` tombstone は PATCH 専用です。 | | `defaultMaxOutputTokens?` | `number` |クライアントが `max_output_tokens` を省略した場合の、プロバイダー全体の `openai-chat` フォールバック。 | | `modelMaxOutputTokens?` | `Record` |モデルごとの `openai-chat` フォールバック バジェットがプラスになります。正確な/パターン一致はプロバイダーのデフォルトを上回ります。 | -| `modelCosts?` | `Record` | モデルごとの表示価格(100万トークンあたりの米ドル)。そのプロバイダーの正確なアップストリーム モデル ID をキーにします(プロバイダー識別子やルーティングされた `provider/model` ラベルではありません)。値は `input`, `output`, `cacheRead`, `cacheWrite` の 4 フィールドです(例: `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`)。組み込みカタログにないモデル ID も、任意の OpenAI 互換エンドポイントを対象とするカスタムプロバイダーや、ローカル・内部プロバイダーで有効です。ユーザー設定の価格は Logs の `~$` と Usage の見積もりで組み込みカタログより優先されます。過去のエントリも現在のオーバーレイで再計算されるため、価格を編集すると過去の合計が変わることがあります(フォールバック順: ユーザー設定 → jawcode カタログ → expected-price オーバーレイ → モデル別ベンダー価格)。全ゼロのエントリは次のソースにフォールバックします。各レートは 0 以上の有限数で、最大 1,000,000(100万トークンあたりの米ドル)です。範囲外の行は管理境界で拒否され、読み込み時に破棄されます。表示専用の見積もりであり、ルーティング・アカウント選択・クォータ・請求には影響しません。 | +| `modelCosts?` | `Record` | モデルごとの表示価格(100万トークンあたりの米ドル)。そのプロバイダーの正確なアップストリーム モデル ID をキーにします(プロバイダー識別子やルーティングされた `provider/model` ラベルではありません)。値は `input`, `output`, `cacheRead`, `cacheWrite` の 4 フィールドです(例: `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`)。組み込みカタログにないモデル ID も、任意の OpenAI 互換エンドポイントを対象とするカスタムプロバイダーや、ローカル・内部プロバイダーで有効です。ユーザー設定の価格は Logs の `~$` と Usage の見積もりで組み込みカタログより優先されます。過去のエントリも現在のオーバーレイで再計算されるため、価格を編集すると過去の合計が変わることがあります(フォールバック順: ユーザー設定 → jawcode カタログ → expected-price オーバーレイ → モデル別ベンダー価格)。ユーザーが明示的に全レートを 0 にした場合は、既知のゼロ料金として見積もります。自動料金に戻すにはそのモデルの設定を削除してください。カタログの全ゼロ料金は引き続きフォールバックします。各レートは 0 以上の有限数で、最大 1,000,000(100万トークンあたりの米ドル)です。範囲外の行は管理境界で拒否され、読み込み時に破棄されます。表示専用の見積もりであり、ルーティング・アカウント選択・クォータ・請求には影響しません。 | | `headers?` | `Record` |追加の上流ヘッダー。認証、Cookie、API キー ヘッダー、埋め込まれた改行、および無効な名前は拒否されます。 | | `openRouterRouting?` | `OpenRouterProviderRouting` |デフォルトの OpenRouter `order`、`only`、および `allowFallbacks` 設定。 `openai-chat` を持つ正規 OpenRouter に対してのみ有効です。 | | `modelOpenRouterRouting?` | `Record` |プロバイダー全体の OpenRouter 設定を置き換える正確なモデル ID のオーバーライド。 | diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md index 2dda27e7bf..c37191745d 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md @@ -93,7 +93,7 @@ managed map을 활성화하면 privacy-safe selector를 만들고, 이후 계정 | `modelAutoCompactTokenLimits?` | `Record` | 모델별 양의 안전 정수형 소프트 자동 압축 예산입니다. 유효한 컨텍스트 또는 최대 입력의 90% 한도를 낮출 수만 있으며, 신뢰할 수 있는 컨텍스트 창을 알 수 없으면 내보내지 않습니다. canonical `openai`에서는 키가 공급자나 계정 선택자 접두사가 없는 정확한 지원 네이티브 모델 ID여야 합니다. 공급자 PATCH는 항목을 병합하며, 키를 `null`로 지정하면 해당 키를 삭제하고 필드 전체를 `null`로 지정하면 맵을 지웁니다. 이 `null` tombstone은 PATCH에서만 사용할 수 있습니다. | | `defaultMaxOutputTokens?` | `number` | 클라이언트가 `max_output_tokens`를 생략했을 때 쓰는 공급자 전반의 `openai-chat` 폴백입니다. | | `modelMaxOutputTokens?` | `Record` | 양수 모델별 `openai-chat` 폴백 예산입니다. 정확한 일치와 패턴 일치가 공급자 기본값보다 우선합니다. | -| `modelCosts?` | `Record` | 모델별 표시 가격(100만 토큰당 USD). 해당 공급자의 정확한 업스트림 모델 ID를 키로 사용하며(공급자 식별자나 라우팅된 `provider/model` 레이블이 아님) 값은 `input`, `output`, `cacheRead`, `cacheWrite` 네 필드입니다(예: `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`). 커스텀 공급자는 `openai-chat` 어댑터로 임의의 OpenAI 호환 엔드포인트를 대상으로 할 수 있으며, 내장 카탈로그에 없는 로컬·내부 공급자 ID도 유효합니다. 사용자 구성 가격은 Logs `~$` 및 Usage 추정에서 내장 카탈로그보다 우선합니다. 기존 항목도 현재 오버레이로 다시 계산되므로 가격을 편집하면 과거 합계가 바뀔 수 있습니다(폴백 순서: 사용자 설정 → jawcode 카탈로그 → expected-price 오버레이 → 모델별 벤더 가격). 전부 0인 항목은 다음 소스로 폴백합니다. 각 요율은 0 이상의 유한한 숫자이며 최대 1,000,000(100만 토큰당 USD)입니다. 범위를 벗어난 행은 관리 경계에서 거부되고 로드 시 삭제됩니다. 표시 전용 추정이며 라우팅·계정 선택·할당량·청구에는 영향을 주지 않습니다. | +| `modelCosts?` | `Record` | 모델별 표시 가격(100만 토큰당 USD). 해당 공급자의 정확한 업스트림 모델 ID를 키로 사용하며(공급자 식별자나 라우팅된 `provider/model` 레이블이 아님) 값은 `input`, `output`, `cacheRead`, `cacheWrite` 네 필드입니다(예: `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`). 커스텀 공급자는 `openai-chat` 어댑터로 임의의 OpenAI 호환 엔드포인트를 대상으로 할 수 있으며, 내장 카탈로그에 없는 로컬·내부 공급자 ID도 유효합니다. 사용자 구성 가격은 Logs `~$` 및 Usage 추정에서 내장 카탈로그보다 우선합니다. 기존 항목도 현재 오버레이로 다시 계산되므로 가격을 편집하면 과거 합계가 바뀔 수 있습니다(폴백 순서: 사용자 설정 → jawcode 카탈로그 → expected-price 오버레이 → 모델별 벤더 가격). 사용자가 모든 요율을 명시적으로 0으로 설정하면 비용을 0으로 추정합니다. 자동 가격으로 되돌리려면 해당 모델 항목을 삭제하세요. 카탈로그의 전부 0인 요율은 계속 다음 소스로 폴백합니다. 각 요율은 0 이상의 유한한 숫자이며 최대 1,000,000(100만 토큰당 USD)입니다. 범위를 벗어난 행은 관리 경계에서 거부되고 로드 시 삭제됩니다. 표시 전용 추정이며 라우팅·계정 선택·할당량·청구에는 영향을 주지 않습니다. | | `headers?` | `Record` | 추가 상위 헤더입니다. Authorization, cookies, API-key 헤더, 내장 개행, 잘못된 이름은 허용하지 않습니다. | | `openRouterRouting?` | `OpenRouterProviderRouting` | 기본 OpenRouter `order`, `only`, `allowFallbacks` 선호도입니다. 정식 OpenRouter와 `openai-chat`에서만 유효합니다. | | `modelOpenRouterRouting?` | `Record` | 공급자 전반의 OpenRouter 선호도를 덮어쓰는 정확한 모델 id별 재정의입니다. | diff --git a/docs-site/src/content/docs/reference/cli/providers-accounts.md b/docs-site/src/content/docs/reference/cli/providers-accounts.md index 3d602799bb..e92bf67874 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -508,6 +508,8 @@ proxy to be running (`ocx start`, or an installed service). | --- | --- | --- | | `list` (default) | `--provider `, `--json` | List models seeded in configured providers. | | `live` | `--provider `, `--json` | Read the running catalog, including models discovered at runtime. Rows are flagged `native`/`routed`, `custom`, and `enabled`/`disabled`. | +| `price ` | `--json` | Read the model's saved manual price override; no override means automatic pricing. | +| `set-price ` | `--input `, `--output `, `--cache-read `, `--cache-write `, `--auto`, `--json` | Set display prices in USD per 1M tokens. Input/output are required when setting; omitted cache rates become zero. `--auto` removes only this model's override. | | `add ` | `--display-name `, `--context-window `, `--modalities ` | Register a model the provider catalog does not advertise. | | `edit ` | `--model-id `, `--display-name `, `--context-window `, `--modalities `, `--json` | Edit a custom model. `-` clears a field; `0` clears the context window. | | `remove ` | `--yes` | Delete a custom model. Requires `--yes` when stdin is not an interactive terminal. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index b0792b7367..0deb12616f 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -149,7 +149,7 @@ predictions. Explicit provider/model price overrides still take precedence. | `modelAutoCompactTokenLimits?` | `Record` | Positive safe-integer per-model soft auto-compaction budgets. Values can only lower the effective 90%-of-context/max-input envelope and are omitted when no authoritative context window is known. For canonical `openai`, keys must be exact supported native model IDs without provider or account-selector prefixes. Provider PATCH merges entries; set a key to `null` to delete it or the whole field to `null` to clear the map. These `null` tombstones are PATCH-only. | | `defaultMaxOutputTokens?` | `number` | Provider-wide `openai-chat` fallback when the client omits `max_output_tokens`. | | `modelMaxOutputTokens?` | `Record` | Positive per-model `openai-chat` fallback budgets; exact/pattern matches beat the provider default. | -| `modelCosts?` | `Record` | Per-model display prices (USD per 1M tokens), keyed by that provider's exact upstream model id — not a provider identifier or a routed `provider/model` label, e.g. `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`. Any model id is a valid key — custom providers may target any OpenAI-compatible endpoint through the `openai-chat` adapter, and local or internal provider ids work even when they are absent from the built-in catalogs. User-configured prices win over the built-in catalogs in the Logs `~$` and Usage estimates; historical entries are repriced from the current overlay, so editing a price can move past totals. The fallback order is user `modelCosts` → exact official correction → jawcode catalog → expected-price overlay → model-level vendor fallback, and an all-zero entry falls through to the next source in that sequence. Each rate must be a non-negative finite number at most 1,000,000 (USD per 1M tokens); out-of-range rows are rejected by the management boundary and dropped on load. Display-time estimation only: overlays never affect routing, account selection, quotas, or billing. | +| `modelCosts?` | `Record` | Per-model display prices (USD per 1M tokens), keyed by that provider's exact upstream model id — not a provider identifier or a routed `provider/model` label, e.g. `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`. Any model id is a valid key — custom providers may target any OpenAI-compatible endpoint through the `openai-chat` adapter, and local or internal provider ids work even when they are absent from the built-in catalogs. User-configured prices win over the built-in catalogs in the Logs `~$` and Usage estimates; historical entries are repriced from the current overlay, so editing a price can move past totals. The fallback order is user `modelCosts` → exact official correction → jawcode catalog → expected-price overlay → model-level vendor fallback, and an explicit all-zero user entry means a known-zero estimate; delete that model entry to restore automatic pricing. All-zero catalog metadata still falls through. Each rate must be a non-negative finite number at most 1,000,000 (USD per 1M tokens); out-of-range rows are rejected by the management boundary and dropped on load. Display-time estimation only: overlays never affect routing, account selection, quotas, or billing. | | `headers?` | `Record` | Extra upstream headers. Authorization, cookies, API-key headers, embedded newlines, and invalid names are rejected. | | `openRouterRouting?` | `OpenRouterProviderRouting` | Default OpenRouter `order`, `only`, and `allowFallbacks` preferences; valid only for canonical OpenRouter with `openai-chat`. | | `modelOpenRouterRouting?` | `Record` | Exact model-id overrides that replace the provider-wide OpenRouter preference. | diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index a4ea3ad3d9..0b3598eac8 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -228,6 +228,29 @@ re-estimated from the pricing active when the summary is read. This is an API-eq not a subscription charge. New main-pool requests use the reserved `main` label; legacy bare `openai` rows remain in an ambiguous bucket instead of being reassigned from current configuration. +Manual model prices can also be edited from **Models → Price**. A manual-pricing badge survives +catalog reloads. Prices are stored in `providers..modelCosts` and survive catalog sync. +Explicit all-zero user rates mean a known-zero estimate; **Reset to automatic** removes the +override and restores the usual catalog fallback. These remain display estimates, not bills. + +`GET /api/providers/{provider}/model-costs` returns `{ provider, modelCosts }`, with sanitized +four-rate entries keyed by exact upstream model ID. `PUT` on the same route accepts +`{ modelId, cost }`, where `cost` is `{ input, output, cacheRead, cacheWrite }` or `null` to reset. +All four rates must be finite numbers from 0 through 1,000,000, in USD per 1M tokens. +Unknown fields and malformed rates are rejected. A write preserves other models' overrides +and returns `{ ok: true, provider, modelId, cost }`; reset returns `cost: null`. + +```bash +ocx models price ollama/custom-model --json +ocx models set-price ollama/custom-model --input 0.50 --output 1.50 +ocx models set-price ollama/custom-model --input 0 --output 0 +ocx models set-price ollama/custom-model --auto +``` + +Omitted CLI cache-read/cache-write rates default to zero. Use `--cache-read` and `--cache-write` +to set them explicitly. A provider name remains an exact configuration identity; account display +labels are not editable provider names. + Rows in `models`, `providers`, and `days[].models` also carry `cacheHitRate`: the share of input tokens served from the provider's prompt cache, clamped to `[0, 1]`. It is `null` — never `0` — when the provider reported no cache telemetry or the row has no input tokens, because "no cache diff --git a/docs-site/src/content/docs/ru/reference/configuration/providers.md b/docs-site/src/content/docs/ru/reference/configuration/providers.md index 14a8b0a3ce..7704a9cbda 100644 --- a/docs-site/src/content/docs/ru/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ru/reference/configuration/providers.md @@ -106,7 +106,7 @@ cross-route credential fallback не существует. Строки API GPT- | `modelAutoCompactTokenLimits?` | `Record` | Мягкие бюджеты автосжатия по моделям в виде положительных безопасных целых чисел. Они могут только уменьшать эффективную границу в 90 % контекста или максимального ввода и не выдаются, если авторитетное окно контекста неизвестно. Для канонического `openai` ключами могут быть только точные поддерживаемые ID нативных моделей без префиксов провайдера или селектора аккаунта. PATCH провайдера объединяет записи: `null` для ключа удаляет его, а `null` для всего поля очищает карту. Такие маркеры `null` допустимы только в PATCH. | | `defaultMaxOutputTokens?` | `number` | Provider-wide fallback для `openai-chat`, когда клиент не передал `max_output_tokens`. | | `modelMaxOutputTokens?` | `Record` | Положительные fallback-budget'ы `openai-chat` по моделям; exact/pattern-match имеет приоритет над provider-default. | -| `modelCosts?` | `Record` | Отображаемые цены по моделям (USD за 1M токенов), ключ — точный upstream id модели этого провайдера (не идентификатор провайдера и не маршрутизируемая метка `provider/model`), значение — четыре поля: `input`, `output`, `cacheRead`, `cacheWrite` (пример: `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`). Любой id допустим — кастомный провайдер может указывать на любой OpenAI-совместимый endpoint через адаптер `openai-chat`, а локальные и внутренние провайдеры работают даже без строки во встроенных каталогах. Пользовательские цены имеют приоритет над встроенными каталогами в оценках `~$` в Logs и Usage; исторические записи пересчитываются по текущему оверлею, поэтому изменение цены может сдвинуть прошлые суммы (порядок: пользователь → каталог jawcode → expected-price overlay → вендорская цена модели); полностью нулевая запись переходит к следующему источнику. Каждая ставка должна быть неотрицательным конечным числом не более 1 000 000 (USD за 1M токенов); строки вне диапазона отклоняются на управляющей границе и отбрасываются при загрузке. Только оценка для отображения: оверлеи не влияют на маршрутизацию, выбор аккаунта, квоты или биллинг. | +| `modelCosts?` | `Record` | Отображаемые цены по моделям (USD за 1M токенов), ключ — точный upstream id модели этого провайдера (не идентификатор провайдера и не маршрутизируемая метка `provider/model`), значение — четыре поля: `input`, `output`, `cacheRead`, `cacheWrite` (пример: `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`). Любой id допустим — кастомный провайдер может указывать на любой OpenAI-совместимый endpoint через адаптер `openai-chat`, а локальные и внутренние провайдеры работают даже без строки во встроенных каталогах. Пользовательские цены имеют приоритет над встроенными каталогами в оценках `~$` в Logs и Usage; исторические записи пересчитываются по текущему оверлею, поэтому изменение цены может сдвинуть прошлые суммы (порядок: пользователь → каталог jawcode → expected-price overlay → вендорская цена модели); явно заданный пользователем набор нулевых ставок означает известную нулевую оценку; удалите запись модели, чтобы восстановить автоматическую цену. Нулевые цены каталога по-прежнему переходят к следующему источнику. Каждая ставка должна быть неотрицательным конечным числом не более 1 000 000 (USD за 1M токенов); строки вне диапазона отклоняются на управляющей границе и отбрасываются при загрузке. Только оценка для отображения: оверлеи не влияют на маршрутизацию, выбор аккаунта, квоты или биллинг. | | `headers?` | `Record` | Дополнительные upstream-header'ы. Заголовки авторизации, cookie, API-key-header'ы, встроенные переводы строк и невалидные имена отклоняются. | | `openRouterRouting?` | `OpenRouterProviderRouting` | Предпочтения по умолчанию для OpenRouter (`order`, `only`, `allowFallbacks`); валидно только для канонического OpenRouter с `openai-chat`. | | `modelOpenRouterRouting?` | `Record` | Exact override по model id, которые полностью заменяют provider-wide preference для OpenRouter. | diff --git a/docs-site/src/content/docs/tr/reference/configuration/providers.md b/docs-site/src/content/docs/tr/reference/configuration/providers.md index 3e01051010..65d0d7eca7 100644 --- a/docs-site/src/content/docs/tr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/tr/reference/configuration/providers.md @@ -111,7 +111,7 @@ alanlı seçilmiş kimlikleri yalın kimliklere yeniden yazar. | `modelAutoCompactTokenLimits?` | `Record` | Model başına pozitif güvenli tamsayı biçiminde yumuşak otomatik sıkıştırma bütçeleri. Değerler yalnızca bağlamın veya maksimum girdinin etkin %90 zarfını düşürebilir ve yetkili bir bağlam penceresi bilinmiyorsa yayımlanmaz. Canonical `openai` için anahtarlar, sağlayıcı veya hesap seçici öneki olmadan desteklenen tam yerel model kimlikleri olmalıdır. Sağlayıcı PATCH girdileri birleştirir; bir anahtarı `null` yapmak o anahtarı siler, alanın tamamını `null` yapmak haritayı temizler. Bu `null` silme işaretleri yalnızca PATCH içindir. | | `defaultMaxOutputTokens?` | `number` | İstemci `max_output_tokens` değerini atladığında sağlayıcı genelinde `openai-chat` geri dönüşü. | | `modelMaxOutputTokens?` | `Record` | Pozitif model başına `openai-chat` geri dönüş bütçeleri; tam/kalıp eşleşmeleri sağlayıcı varsayılanını yener. | -| `modelCosts?` | `Record` | Sağlayıcının tam yukarı akış model kimliğine göre anahtarlanan model başına görüntüleme fiyatları (1M token başına USD) — bir sağlayıcı tanımlayıcısı veya yönlendirilen `provider/model` etiketi değil, örn. `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`. Herhangi bir model kimliği geçerli bir anahtardır — özel sağlayıcılar `openai-chat` adaptörü aracılığıyla herhangi bir OpenAI uyumlu uç noktayı hedefleyebilir ve yerel veya dahili sağlayıcı kimlikleri yerleşik kataloglarda bulunmasalar bile çalışır. Kullanıcı tarafından yapılandırılan fiyatlar Günlükler `~$` ve Kullanım tahminlerinde yerleşik katalogları yener; geçmiş girdiler geçerli katmandan yeniden fiyatlandırılır, bu nedenle bir fiyatı düzenlemek geçmiş toplamları değiştirebilir. Geri dönüş sırası: kullanıcı `modelCosts` → jawcode kataloğu → beklenen fiyat katmanı → model düzeyinde satıcı geri dönüşü ve tamamen sıfır bir girdi bu dizideki bir sonraki kaynağa düşer. Her oran en fazla 1.000.000 (1M token başına USD) olan negatif olmayan sonlu bir sayı olmalıdır; aralık dışı satırlar yönetim sınırı tarafından reddedilir ve yükleme sırasında bırakılır. Yalnızca görüntüleme zamanı tahmini: katmanlar yönlendirmeyi, hesap seçimini, kotaları veya faturalandırmayı asla etkilemez. | +| `modelCosts?` | `Record` | Sağlayıcının tam yukarı akış model kimliğine göre anahtarlanan model başına görüntüleme fiyatları (1M token başına USD) — bir sağlayıcı tanımlayıcısı veya yönlendirilen `provider/model` etiketi değil, örn. `{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`. Herhangi bir model kimliği geçerli bir anahtardır — özel sağlayıcılar `openai-chat` adaptörü aracılığıyla herhangi bir OpenAI uyumlu uç noktayı hedefleyebilir ve yerel veya dahili sağlayıcı kimlikleri yerleşik kataloglarda bulunmasalar bile çalışır. Kullanıcı tarafından yapılandırılan fiyatlar Günlükler `~$` ve Kullanım tahminlerinde yerleşik katalogları yener; geçmiş girdiler geçerli katmandan yeniden fiyatlandırılır, bu nedenle bir fiyatı düzenlemek geçmiş toplamları değiştirebilir. Geri dönüş sırası: kullanıcı `modelCosts` → jawcode kataloğu → beklenen fiyat katmanı → model düzeyinde satıcı geri dönüşü ve kullanıcının açıkça sıfır olarak belirlediği oranlar bilinen sıfır maliyetli bir tahmin üretir; otomatik fiyatlandırmaya dönmek için model girdisini silin. Tamamen sıfır katalog fiyatları bir sonraki kaynağa geçmeye devam eder. Her oran en fazla 1.000.000 (1M token başına USD) olan negatif olmayan sonlu bir sayı olmalıdır; aralık dışı satırlar yönetim sınırı tarafından reddedilir ve yükleme sırasında bırakılır. Yalnızca görüntüleme zamanı tahmini: katmanlar yönlendirmeyi, hesap seçimini, kotaları veya faturalandırmayı asla etkilemez. | | `headers?` | `Record` | Ek yukarı akış başlıkları. Yetkilendirme, çerezler, API anahtarı başlıkları, gömülü yeni satırlar ve geçersiz adlar reddedilir. | | `openRouterRouting?` | `OpenRouterProviderRouting` | Varsayılan OpenRouter `order`, `only` ve `allowFallbacks` tercihleri; yalnızca `openai-chat` ile kurallı OpenRouter için geçerlidir. | | `modelOpenRouterRouting?` | `Record` | Sağlayıcı genelindeki OpenRouter tercihinin yerini alan tam model kimliği geçersiz kılmaları. | diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md index 32f2b52a69..e01ab6f51a 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md @@ -93,7 +93,7 @@ selector,而不是分配一个新名称。 | `modelAutoCompactTokenLimits?` | `Record` | 按模型设置的正安全整数软自动压缩预算。该值只能降低“上下文或最大输入的 90%”这一有效上限;没有已知的权威上下文窗口时不会输出。对于规范 `openai`,键必须是受支持的精确原生模型 ID,且不得包含提供者或账户选择器前缀。提供者 PATCH 会合并条目;将某个键设为 `null` 会删除该键,将整个字段设为 `null` 会清空映射。这些 `null` 删除标记仅适用于 PATCH。 | | `defaultMaxOutputTokens?` | `number` | 当客户端省略 `max_output_tokens` 时,`openai-chat` 的提供者级回退值。 | | `modelMaxOutputTokens?` | `Record` | 正数型、按模型设置的 `openai-chat` 回退预算;精确/模式匹配优先于提供者默认值。 | -| `modelCosts?` | `Record` | 按模型设置的显示价格(每 100 万 token 的美元数),以该提供者的精确上游模型 ID 为键(不是提供者标识符或路由后的 `provider/model` 标签),值为四个字段:`input`、`output`、`cacheRead`、`cacheWrite`(示例:`{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`)。任何模型 ID 都是有效键——自定义提供者可以通过 `openai-chat` 适配器指向任意 OpenAI 兼容端点,即使不存在于内置目录中,本地 OpenAI 兼容和内部提供者的 ID 同样有效。用户配置的价格在 Logs 的 `~$` 和 Usage 估算中优先于内置目录;历史条目也会按当前覆盖项重新计价,因此修改价格可能改变过去的总额(回退顺序:用户配置 → jawcode 目录 → expected-price 覆盖 → 模型级厂商价格);全零条目会回退到该顺序中的下一个来源。每个费率必须是大于等于 0 的有限数字,且不超过 1,000,000(每 100 万 token 的美元数);超出范围的条目会在管理边界被拒绝,并在加载时被丢弃。仅用于显示的估算:覆盖项不影响路由、账户选择、配额或计费。 | +| `modelCosts?` | `Record` | 按模型设置的显示价格(每 100 万 token 的美元数),以该提供者的精确上游模型 ID 为键(不是提供者标识符或路由后的 `provider/model` 标签),值为四个字段:`input`、`output`、`cacheRead`、`cacheWrite`(示例:`{ "deepseek-v4-flash": { "input": 0.14, "output": 0.28, "cacheRead": 0.0028, "cacheWrite": 0 } }`)。任何模型 ID 都是有效键——自定义提供者可以通过 `openai-chat` 适配器指向任意 OpenAI 兼容端点,即使不存在于内置目录中,本地 OpenAI 兼容和内部提供者的 ID 同样有效。用户配置的价格在 Logs 的 `~$` 和 Usage 估算中优先于内置目录;历史条目也会按当前覆盖项重新计价,因此修改价格可能改变过去的总额(回退顺序:用户配置 → jawcode 目录 → expected-price 覆盖 → 模型级厂商价格);用户明确将所有费率设为零时,会得到已知的零费用估算;删除该模型的覆盖项即可恢复自动定价。目录中的全零价格仍会回退到下一个来源。每个费率必须是大于等于 0 的有限数字,且不超过 1,000,000(每 100 万 token 的美元数);超出范围的条目会在管理边界被拒绝,并在加载时被丢弃。仅用于显示的估算:覆盖项不影响路由、账户选择、配额或计费。 | | `headers?` | `Record` | 额外的上游请求头。会拒绝 Authorization、cookie、API key 头、嵌入换行符以及无效名称。 | | `openRouterRouting?` | `OpenRouterProviderRouting` | 默认的 OpenRouter `order`、`only` 和 `allowFallbacks` 偏好;仅对使用 `openai-chat` 的规范 OpenRouter 有效。 | | `modelOpenRouterRouting?` | `Record` | 精确模型 id 级别的覆盖项,会替换提供者级 OpenRouter 偏好。 | diff --git a/gui/src/components/ModelPriceDialog.tsx b/gui/src/components/ModelPriceDialog.tsx new file mode 100644 index 0000000000..c4e08d98b6 --- /dev/null +++ b/gui/src/components/ModelPriceDialog.tsx @@ -0,0 +1,235 @@ +import { Fragment, useCallback, useEffect, useId, useRef, useState } from "react"; +import { createBoundedFetch, type BoundedFetch } from "../bounded-fetch"; +import { readJsonOrThrow } from "../fetch-json"; +import { useT, type TKey } from "../i18n/shared"; +import type { ModelRow } from "../pages/models-shared"; + +interface Cost4 { + input: number; + output: number; + cacheRead: number; + cacheWrite: number; +} + +const RATE_FIELDS = ["input", "output", "cacheRead", "cacheWrite"] as const; +const RATE_LABELS: Record = { + input: "pricing.override.input", + output: "pricing.override.output", + cacheRead: "pricing.override.cacheRead", + cacheWrite: "pricing.override.cacheWrite", +}; +const MAX_RATE = 1_000_000; +const REQUEST_TIMEOUT_MS = 60_000; +const EMPTY_DRAFT = { input: "", output: "", cacheRead: "", cacheWrite: "" }; +type Phase = "loading" | "loadFailed" | "ready" | "saving" | "unknown" | "refreshing" | "refreshFailed"; + +function isRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function isCost(value: unknown): value is Cost4 { + return isRecord(value) && RATE_FIELDS.every(field => ( + typeof value[field] === "number" && Number.isFinite(value[field]) + && value[field] >= 0 && value[field] <= MAX_RATE + )); +} + +interface ModelPriceDialogProps { + model: ModelRow; + apiBase: string; + onRefresh: (signal: AbortSignal) => Promise; + onClose: () => void; +} + +export default function ModelPriceDialog({ model, apiBase, onRefresh, onClose }: ModelPriceDialogProps) { + const t = useT(); + const id = useId(); + const dialogRef = useRef(null); + const inputRef = useRef(null); + const submitRef = useRef(null); + const requestRef = useRef(null); + const mutationPendingRef = useRef(false); + const [phase, setPhase] = useState("loading"); + const [draft, setDraft] = useState(EMPTY_DRAFT); + const [hasOverride, setHasOverride] = useState(false); + const [errorKey, setErrorKey] = useState(null); + const [recovered, setRecovered] = useState(false); + const endpoint = `${apiBase}/api/providers/${encodeURIComponent(model.provider)}/model-costs`; + const mutating = phase === "saving" || phase === "refreshing"; + const locked = phase !== "ready"; + + const readOverride = useCallback(async (recover = false) => { + if (requestRef.current) return; + const bounded = createBoundedFetch(REQUEST_TIMEOUT_MS); + requestRef.current = bounded; + setPhase("loading"); + setErrorKey(null); + try { + const response = await fetch(endpoint, { signal: bounded.signal, cache: "no-store" }); + const result = await readJsonOrThrow(response); + bounded.signal.throwIfAborted(); + if (!isRecord(result) || result.provider !== model.provider || !isRecord(result.modelCosts)) { + throw new Error("invalid model-costs response"); + } + const cost = Object.hasOwn(result.modelCosts, model.id) ? result.modelCosts[model.id] : undefined; + if (cost !== undefined && !isCost(cost)) throw new Error("invalid model cost"); + if (requestRef.current !== bounded) return; + setDraft(cost === undefined ? EMPTY_DRAFT : { + input: String(cost.input), output: String(cost.output), + cacheRead: String(cost.cacheRead), cacheWrite: String(cost.cacheWrite), + }); + setHasOverride(cost !== undefined); + // This read recovers an editable snapshot, not ordering against an earlier + // request still running on the server or writes from another client. + setRecovered(recover); + setPhase("ready"); + } catch { + if (requestRef.current !== bounded) return; + setPhase(recover ? "unknown" : "loadFailed"); + setErrorKey(recover ? "pricing.override.recoveryFailed" : "pricing.override.loadFailed"); + } finally { + bounded.clear(); + if (requestRef.current === bounded) requestRef.current = null; + } + }, [endpoint, model.id, model.provider]); + + useEffect(() => { + const dialog = dialogRef.current; + if (dialog && !dialog.open) dialog.showModal(); + void readOverride(); + return () => { + requestRef.current?.controller.abort(); + requestRef.current?.clear(); + requestRef.current = null; + if (dialog?.open) dialog.close(); + }; + }, [readOverride]); + + useEffect(() => { + if (phase === "ready") inputRef.current?.focus(); + else if (phase === "unknown" || phase === "loadFailed" || phase === "refreshFailed") submitRef.current?.focus(); + }, [phase]); + + // undefined retries only catalog refresh after a validated persistence receipt. + const save = async (cost: Cost4 | null | undefined) => { + if (requestRef.current || (cost === undefined ? phase !== "refreshFailed" : phase !== "ready")) return; + const bounded = createBoundedFetch(REQUEST_TIMEOUT_MS); + requestRef.current = bounded; + setPhase(cost === undefined ? "refreshing" : "saving"); + mutationPendingRef.current = true; + setErrorKey(null); + let confirmed = cost === undefined; + try { + if (cost !== undefined) { + const response = await fetch(endpoint, { + method: "PUT", headers: { "content-type": "application/json" }, + body: JSON.stringify({ modelId: model.id, cost }), signal: bounded.signal, + }); + const result = await readJsonOrThrow(response); + bounded.signal.throwIfAborted(); + const receiptCost = isRecord(result) ? result.cost : undefined; + if (!isRecord(result) || result.ok !== true || result.provider !== model.provider + || result.modelId !== model.id || (cost === null ? receiptCost !== null + : !isCost(receiptCost) || !RATE_FIELDS.every(field => receiptCost[field] === cost[field]))) { + throw new Error("invalid model-costs receipt"); + } + if (requestRef.current !== bounded) return; + confirmed = true; + setPhase("refreshing"); + } + if (!await onRefresh(bounded.signal)) throw new Error("catalog refresh failed"); + bounded.signal.throwIfAborted(); + if (requestRef.current === bounded) onClose(); + } catch { + if (requestRef.current !== bounded) return; + setPhase(confirmed ? "refreshFailed" : "unknown"); + setErrorKey(confirmed ? "pricing.override.refreshFailed" : "pricing.override.outcomeUnknown"); + } finally { + bounded.clear(); + if (requestRef.current === bounded) { + requestRef.current = null; + mutationPendingRef.current = false; + } + } + }; + + const requestClose = () => { + if (!mutationPendingRef.current) onClose(); + }; + + return ( + { event.preventDefault(); requestClose(); }}> + +
+
+ {t("pricing.override.modelId")} + {model.namespaced} +
+

{t("pricing.override.help")}

+ {phase === "loading" &&

{t("pricing.override.loading")}

} + {RATE_FIELDS.map(field => ( + + + { + if (locked || requestRef.current) return; + const value = event.target.value; + setDraft(current => ({ + ...current, + cacheRead: current.cacheRead || "0", cacheWrite: current.cacheWrite || "0", + [field]: value, + })); + setErrorKey(null); + }} /> + + ))} + {recovered &&

{t("pricing.override.recovered")}

} + {errorKey && } +
+ + + +
+ + + ); +} diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 4145cb8032..a361962237 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -2591,4 +2591,28 @@ export const de: Record = { "models.displayNameTooLong": "Der Anzeigename darf höchstens 128 Zeichen lang sein.", "models.displayNameNoSlash": "Der Anzeigename darf kein / enthalten.", "models.displayNameNoControl": "Der Anzeigename darf keine Steuerzeichen enthalten.", + "pricing.override.action": "Preis", + "pricing.override.actionLabel": "Preis für {model} bearbeiten", + "pricing.override.badge": "Manueller Preis", + "pricing.override.title": "Modellpreis", + "pricing.override.modelId": "Modell-ID", + "pricing.override.help": "USD pro 1 Mio. Token. Ein- und Ausgaberaten eingeben; leere Cache-Raten gelten als 0. Vier Raten von 0 bedeuten kostenlos.", + "pricing.override.input": "Eingabe", + "pricing.override.output": "Ausgabe", + "pricing.override.cacheRead": "Cache lesen", + "pricing.override.cacheWrite": "Cache schreiben", + "pricing.override.loading": "Gespeicherten Preis laden…", + "pricing.override.loadFailed": "Der gespeicherte Preis konnte nicht geladen werden. Erneut laden.", + "pricing.override.outcomeUnknown": "Das Ergebnis der Anfrage ist unklar. Der Preis könnte geändert worden sein. Vor weiteren Änderungen den gespeicherten Preis neu laden.", + "pricing.override.recoveryFailed": "Der gespeicherte Preis konnte nicht ermittelt werden. Die Bearbeitung bleibt gesperrt; erneut laden.", + "pricing.override.recovered": "Aktueller gespeicherter Preis geladen. Die frühere Anfrage oder ein anderer Client kann ihn noch ändern.", + "pricing.override.refreshFailed": "Der Preis wurde gespeichert, aber die Modellliste konnte nicht aktualisiert werden. Die Liste erneut aktualisieren.", + "pricing.override.invalid": "Ein- und Ausgaberaten eingeben. Jede Rate muss eine endliche Zahl zwischen 0 und 1.000.000 sein.", + "pricing.override.reset": "Automatischen Preis verwenden", + "pricing.override.save": "Speichern", + "pricing.override.saving": "Speichern…", + "pricing.override.reload": "Preis neu laden", + "pricing.override.refresh": "Liste aktualisieren", + "pricing.override.cancel": "Abbrechen", + "pricing.override.close": "Schließen", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 2a31ec7947..ff45937f47 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -2625,6 +2625,30 @@ export const en = { "models.displayNameTooLong": "Friendly name must be 128 characters or fewer.", "models.displayNameNoSlash": "Friendly name cannot contain /.", "models.displayNameNoControl": "Friendly name cannot contain control characters.", + "pricing.override.action": "Price", + "pricing.override.actionLabel": "Edit price for {model}", + "pricing.override.badge": "Manual price", + "pricing.override.title": "Model price", + "pricing.override.modelId": "Model ID", + "pricing.override.help": "USD per 1M tokens. Enter input and output rates; blank cache rates use 0. All four rates set to 0 mean free.", + "pricing.override.input": "Input", + "pricing.override.output": "Output", + "pricing.override.cacheRead": "Cache read", + "pricing.override.cacheWrite": "Cache write", + "pricing.override.loading": "Loading saved price…", + "pricing.override.loadFailed": "Could not load the saved price. Reload to try again.", + "pricing.override.outcomeUnknown": "The request did not finish reliably. The price may have changed. Reload the saved price before editing again.", + "pricing.override.recoveryFailed": "Could not recover the saved price. Editing stays locked; reload to try again.", + "pricing.override.recovered": "Latest saved price loaded. The earlier request or another client may still change it.", + "pricing.override.refreshFailed": "The price was saved, but the model list could not be refreshed. Retry the list refresh.", + "pricing.override.invalid": "Enter input and output rates. Every rate must be a finite number from 0 to 1,000,000.", + "pricing.override.reset": "Reset to automatic", + "pricing.override.save": "Save", + "pricing.override.saving": "Saving…", + "pricing.override.reload": "Reload price", + "pricing.override.refresh": "Refresh list", + "pricing.override.cancel": "Cancel", + "pricing.override.close": "Close", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 753982c1bf..eafe430758 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -2578,4 +2578,28 @@ export const fr: Record = { "models.displayNameTooLong": "Le nom d’affichage doit contenir au maximum 128 caractères.", "models.displayNameNoSlash": "Le nom d’affichage ne peut pas contenir /.", "models.displayNameNoControl": "Le nom d’affichage ne peut pas contenir de caractères de contrôle.", + "pricing.override.action": "Prix", + "pricing.override.actionLabel": "Modifier le prix de {model}", + "pricing.override.badge": "Prix manuel", + "pricing.override.title": "Prix du modèle", + "pricing.override.modelId": "ID du modèle", + "pricing.override.help": "USD par million de tokens. Saisissez les tarifs d’entrée et de sortie ; un tarif de cache vide vaut 0. Quatre tarifs à 0 signifient gratuit.", + "pricing.override.input": "Entrée", + "pricing.override.output": "Sortie", + "pricing.override.cacheRead": "Lecture du cache", + "pricing.override.cacheWrite": "Écriture du cache", + "pricing.override.loading": "Chargement du prix enregistré…", + "pricing.override.loadFailed": "Impossible de charger le prix enregistré. Rechargez pour réessayer.", + "pricing.override.outcomeUnknown": "Le résultat de la requête est incertain. Le prix a peut-être changé. Rechargez le prix enregistré avant toute autre modification.", + "pricing.override.recoveryFailed": "Impossible de récupérer le prix enregistré. La modification reste verrouillée ; rechargez pour réessayer.", + "pricing.override.recovered": "Le prix actuellement enregistré est chargé. La requête précédente ou un autre client peut encore le modifier.", + "pricing.override.refreshFailed": "Le prix est enregistré, mais la liste des modèles n’a pas pu être actualisée. Réessayez l’actualisation.", + "pricing.override.invalid": "Saisissez les tarifs d’entrée et de sortie. Chaque tarif doit être un nombre fini entre 0 et 1 000 000.", + "pricing.override.reset": "Revenir au prix automatique", + "pricing.override.save": "Enregistrer", + "pricing.override.saving": "Enregistrement…", + "pricing.override.reload": "Recharger le prix", + "pricing.override.refresh": "Actualiser la liste", + "pricing.override.cancel": "Annuler", + "pricing.override.close": "Fermer", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 300d1f8c51..6fe289e48c 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -2612,4 +2612,28 @@ export const ja: Record = { "models.displayNameTooLong": "表示名は 128 文字以内にしてください。", "models.displayNameNoSlash": "表示名に / は使用できません。", "models.displayNameNoControl": "表示名に制御文字は使用できません。", + "pricing.override.action": "価格", + "pricing.override.actionLabel": "{model} の価格を編集", + "pricing.override.badge": "手動価格", + "pricing.override.title": "モデル価格", + "pricing.override.modelId": "モデル ID", + "pricing.override.help": "100万トークンあたりの USD です。入力・出力単価を入力してください。空のキャッシュ単価は 0 とし、4項目すべてが 0 なら無料です。", + "pricing.override.input": "入力", + "pricing.override.output": "出力", + "pricing.override.cacheRead": "キャッシュ読み取り", + "pricing.override.cacheWrite": "キャッシュ書き込み", + "pricing.override.loading": "保存済み価格を読み込み中…", + "pricing.override.loadFailed": "保存済み価格を読み込めませんでした。再読み込みしてください。", + "pricing.override.outcomeUnknown": "リクエストの結果を確認できませんでした。価格が変更された可能性があります。編集する前に保存済み価格を再読み込みしてください。", + "pricing.override.recoveryFailed": "保存済み価格を確認できないため、編集はロックされています。再読み込みしてください。", + "pricing.override.recovered": "現在の保存済み価格を読み込みました。先ほどのリクエストや別のクライアントが後から変更する可能性があります。", + "pricing.override.refreshFailed": "価格は保存されましたが、モデル一覧を更新できませんでした。一覧の更新を再試行してください。", + "pricing.override.invalid": "入力・出力単価を入力してください。各単価は 0 以上 1,000,000 以下の有限の数値にしてください。", + "pricing.override.reset": "自動価格に戻す", + "pricing.override.save": "保存", + "pricing.override.saving": "保存中…", + "pricing.override.reload": "価格を再読み込み", + "pricing.override.refresh": "一覧を更新", + "pricing.override.cancel": "キャンセル", + "pricing.override.close": "閉じる", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 42c000c6bb..20160b7ffe 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -2613,4 +2613,28 @@ export const ko: Record = { "models.displayNameTooLong": "표시 이름은 128자 이하여야 합니다.", "models.displayNameNoSlash": "표시 이름에 /를 사용할 수 없습니다.", "models.displayNameNoControl": "표시 이름에 제어 문자를 사용할 수 없습니다.", + "pricing.override.action": "가격", + "pricing.override.actionLabel": "{model} 가격 편집", + "pricing.override.badge": "수동 가격", + "pricing.override.title": "모델 가격", + "pricing.override.modelId": "모델 ID", + "pricing.override.help": "토큰 100만 개당 USD입니다. 입력·출력 요율을 입력하세요. 빈 캐시 요율은 0으로 처리하며, 네 요율이 모두 0이면 무료입니다.", + "pricing.override.input": "입력", + "pricing.override.output": "출력", + "pricing.override.cacheRead": "캐시 읽기", + "pricing.override.cacheWrite": "캐시 쓰기", + "pricing.override.loading": "저장된 가격을 불러오는 중…", + "pricing.override.loadFailed": "저장된 가격을 불러오지 못했습니다. 다시 불러와 주세요.", + "pricing.override.outcomeUnknown": "요청 결과를 확인하지 못했습니다. 가격이 변경되었을 수 있으니 저장된 가격을 다시 불러온 뒤 편집하세요.", + "pricing.override.recoveryFailed": "저장된 가격을 확인하지 못해 편집이 잠겨 있습니다. 다시 불러와 주세요.", + "pricing.override.recovered": "현재 저장된 가격을 불러왔습니다. 이전 요청이나 다른 클라이언트가 이후에 가격을 변경할 수 있습니다.", + "pricing.override.refreshFailed": "가격은 저장했지만 모델 목록을 갱신하지 못했습니다. 목록 갱신을 다시 시도하세요.", + "pricing.override.invalid": "입력·출력 요율을 입력하세요. 모든 요율은 0 이상 1,000,000 이하의 유한한 숫자여야 합니다.", + "pricing.override.reset": "자동 가격으로 복원", + "pricing.override.save": "저장", + "pricing.override.saving": "저장 중…", + "pricing.override.reload": "가격 다시 불러오기", + "pricing.override.refresh": "목록 갱신", + "pricing.override.cancel": "취소", + "pricing.override.close": "닫기", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 51fcaef210..b433aa4381 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -2614,4 +2614,28 @@ export const ru: Record = { "models.displayNameTooLong": "Понятное имя должно содержать не более 128 символов.", "models.displayNameNoSlash": "Понятное имя не может содержать /.", "models.displayNameNoControl": "Понятное имя не может содержать управляющие символы.", + "pricing.override.action": "Цена", + "pricing.override.actionLabel": "Изменить цену для {model}", + "pricing.override.badge": "Своя цена", + "pricing.override.title": "Цена модели", + "pricing.override.modelId": "ID модели", + "pricing.override.help": "USD за 1 млн токенов. Укажите входной и выходной тарифы; пустые тарифы кеша равны 0. Четыре нулевых тарифа означают бесплатное использование.", + "pricing.override.input": "Вход", + "pricing.override.output": "Выход", + "pricing.override.cacheRead": "Чтение кеша", + "pricing.override.cacheWrite": "Запись кеша", + "pricing.override.loading": "Загрузка сохранённой цены…", + "pricing.override.loadFailed": "Не удалось загрузить сохранённую цену. Повторите загрузку.", + "pricing.override.outcomeUnknown": "Результат запроса неизвестен. Цена могла измениться. Загрузите сохранённую цену перед следующим изменением.", + "pricing.override.recoveryFailed": "Не удалось получить сохранённую цену. Редактирование заблокировано; повторите загрузку.", + "pricing.override.recovered": "Текущая сохранённая цена загружена. Предыдущий запрос или другой клиент ещё может изменить её.", + "pricing.override.refreshFailed": "Цена сохранена, но список моделей не обновлён. Повторите обновление списка.", + "pricing.override.invalid": "Укажите входной и выходной тарифы. Каждый тариф должен быть конечным числом от 0 до 1 000 000.", + "pricing.override.reset": "Вернуть автоматическую цену", + "pricing.override.save": "Сохранить", + "pricing.override.saving": "Сохранение…", + "pricing.override.reload": "Загрузить цену", + "pricing.override.refresh": "Обновить список", + "pricing.override.cancel": "Отмена", + "pricing.override.close": "Закрыть", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index c764bf11ca..b86b867b22 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -2614,4 +2614,28 @@ export const tr: Record = { "models.displayNameTooLong": "Görünen ad en fazla 128 karakter olabilir.", "models.displayNameNoSlash": "Görünen ad / içeremez.", "models.displayNameNoControl": "Görünen ad denetim karakterleri içeremez.", + "pricing.override.action": "Fiyat", + "pricing.override.actionLabel": "{model} fiyatını düzenle", + "pricing.override.badge": "Elle belirlenen fiyat", + "pricing.override.title": "Model fiyatı", + "pricing.override.modelId": "Model kimliği", + "pricing.override.help": "1 milyon token başına USD. Giriş ve çıkış ücretlerini girin; boş önbellek ücretleri 0 sayılır. Dört ücret de 0 ise ücretsizdir.", + "pricing.override.input": "Giriş", + "pricing.override.output": "Çıkış", + "pricing.override.cacheRead": "Önbellek okuma", + "pricing.override.cacheWrite": "Önbellek yazma", + "pricing.override.loading": "Kayıtlı fiyat yükleniyor…", + "pricing.override.loadFailed": "Kayıtlı fiyat yüklenemedi. Yeniden yükleyin.", + "pricing.override.outcomeUnknown": "İsteğin sonucu doğrulanamadı. Fiyat değişmiş olabilir. Yeniden düzenlemeden önce kayıtlı fiyatı yükleyin.", + "pricing.override.recoveryFailed": "Kayıtlı fiyat alınamadı. Düzenleme kilitli kalır; yeniden yükleyin.", + "pricing.override.recovered": "Güncel kayıtlı fiyat yüklendi. Önceki istek veya başka bir istemci fiyatı hâlâ değiştirebilir.", + "pricing.override.refreshFailed": "Fiyat kaydedildi ancak model listesi yenilenemedi. Listeyi yeniden yenileyin.", + "pricing.override.invalid": "Giriş ve çıkış ücretlerini girin. Her ücret 0 ile 1.000.000 arasında sonlu bir sayı olmalıdır.", + "pricing.override.reset": "Otomatik fiyata dön", + "pricing.override.save": "Kaydet", + "pricing.override.saving": "Kaydediliyor…", + "pricing.override.reload": "Fiyatı yeniden yükle", + "pricing.override.refresh": "Listeyi yenile", + "pricing.override.cancel": "İptal", + "pricing.override.close": "Kapat", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index ab6aedd67a..856c4c869c 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2576,4 +2576,28 @@ export const zhTW: Record = { "models.displayNameTooLong": "友善名稱不能超過 128 個字元。", "models.displayNameNoSlash": "友善名稱不能包含 /。", "models.displayNameNoControl": "友善名稱不能包含控制字元。", + "pricing.override.action": "價格", + "pricing.override.actionLabel": "編輯 {model} 的價格", + "pricing.override.badge": "手動價格", + "pricing.override.title": "模型價格", + "pricing.override.modelId": "模型 ID", + "pricing.override.help": "單位為每百萬 token 的美元價格。請輸入輸入與輸出費率;空白快取費率以 0 計算。四項皆為 0 表示免費。", + "pricing.override.input": "輸入", + "pricing.override.output": "輸出", + "pricing.override.cacheRead": "快取讀取", + "pricing.override.cacheWrite": "快取寫入", + "pricing.override.loading": "正在載入已儲存的價格…", + "pricing.override.loadFailed": "無法載入已儲存的價格,請重新載入。", + "pricing.override.outcomeUnknown": "無法確認請求結果,價格可能已變更。再次編輯前請重新載入已儲存的價格。", + "pricing.override.recoveryFailed": "無法取得已儲存的價格,編輯仍被鎖定。請重新載入。", + "pricing.override.recovered": "已載入目前儲存的價格。先前的請求或其他用戶端仍可能變更該價格。", + "pricing.override.refreshFailed": "價格已儲存,但無法重新整理模型清單。請重試重新整理清單。", + "pricing.override.invalid": "請輸入輸入與輸出費率。每項費率必須是 0 到 1,000,000 之間的有限數字。", + "pricing.override.reset": "恢復自動價格", + "pricing.override.save": "儲存", + "pricing.override.saving": "正在儲存…", + "pricing.override.reload": "重新載入價格", + "pricing.override.refresh": "重新整理清單", + "pricing.override.cancel": "取消", + "pricing.override.close": "關閉", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 052f449855..4e1fda0c2a 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -2612,4 +2612,28 @@ export const zh: Record = { "models.displayNameTooLong": "友好名称不能超过 128 个字符。", "models.displayNameNoSlash": "友好名称不能包含 /。", "models.displayNameNoControl": "友好名称不能包含控制字符。", + "pricing.override.action": "价格", + "pricing.override.actionLabel": "编辑 {model} 的价格", + "pricing.override.badge": "手动价格", + "pricing.override.title": "模型价格", + "pricing.override.modelId": "模型 ID", + "pricing.override.help": "单位为每百万 token 的美元价格。请输入输入和输出费率;空白缓存费率按 0 计算。四项均为 0 表示免费。", + "pricing.override.input": "输入", + "pricing.override.output": "输出", + "pricing.override.cacheRead": "缓存读取", + "pricing.override.cacheWrite": "缓存写入", + "pricing.override.loading": "正在加载已保存的价格…", + "pricing.override.loadFailed": "无法加载已保存的价格,请重新加载。", + "pricing.override.outcomeUnknown": "无法确认请求结果,价格可能已更改。再次编辑前请重新加载已保存的价格。", + "pricing.override.recoveryFailed": "无法获取已保存的价格,编辑仍被锁定。请重新加载。", + "pricing.override.recovered": "已加载当前保存的价格。之前的请求或其他客户端仍可能更改该价格。", + "pricing.override.refreshFailed": "价格已保存,但无法刷新模型列表。请重试刷新列表。", + "pricing.override.invalid": "请输入输入和输出费率。每项费率必须是 0 到 1,000,000 之间的有限数字。", + "pricing.override.reset": "恢复自动价格", + "pricing.override.save": "保存", + "pricing.override.saving": "正在保存…", + "pricing.override.reload": "重新加载价格", + "pricing.override.refresh": "刷新列表", + "pricing.override.cancel": "取消", + "pricing.override.close": "关闭", }; diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx index fc8db5626e..bc010c4abc 100644 --- a/gui/src/pages/Models.tsx +++ b/gui/src/pages/Models.tsx @@ -1,5 +1,6 @@ import { CodexStaleBanner } from "../components/codex-stale-banner"; import ModelDisplayNameDialog from "../components/ModelDisplayNameDialog"; +import ModelPriceDialog from "../components/ModelPriceDialog"; import { fetchCodexAppServerState } from "../codex-app-server-state"; import type { AppServerStateOutcome } from "../codex-app-server-state"; import { useCodexRestart } from "../use-codex-restart"; @@ -330,6 +331,8 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; const [v2HelpOpen, setV2HelpOpen] = useState(false); const [customModalOpen, setCustomModalOpen] = useState(false); const [displayNameModel, setDisplayNameModel] = useState(null); + const [priceModel, setPriceModel] = useState(null); + const priceTriggerRef = useRef(null); const [displayNameSaving, setDisplayNameSaving] = useState(false); const [displayNameRequestError, setDisplayNameRequestError] = useState(null); const [displayNameRecovery, setDisplayNameRecovery] = useState<{ @@ -1696,6 +1699,23 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; {t("models.customBadge")} )} + {!m.native && m.provider !== "combo" && ( + <> + {m.manualPricing === true && {t("pricing.override.badge")}} + + + )} {!m.custom && recentIds.has(m.id) && {t("models.newBadge")}} {m.contextCapped && {t("models.contextCappedValue", { value: fmtK(m.contextCap ?? contextCapValue) })}}
@@ -2651,6 +2671,21 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; onClose={closeDisplayNameEdit} /> )} + {priceModel && ( + load(true, signal)} + onClose={() => { + const trigger = priceTriggerRef.current; + setPriceModel(null); + window.setTimeout(() => { + if (trigger?.isConnected) trigger.focus(); + }, 0); + }} + /> + )} ); diff --git a/gui/src/pages/models-shared.ts b/gui/src/pages/models-shared.ts index 1f5ef7786b..19d9bb67f7 100644 --- a/gui/src/pages/models-shared.ts +++ b/gui/src/pages/models-shared.ts @@ -37,6 +37,7 @@ export interface ModelRow { displayName?: string; displayNameOverride?: string; displayNameSource?: "operator" | "provider" | "fallback"; + manualPricing?: boolean; inputModalities?: string[]; contextWindow?: number; contextCap?: number; diff --git a/gui/tests/models-price-editor.test.tsx b/gui/tests/models-price-editor.test.tsx new file mode 100644 index 0000000000..b759a8398e --- /dev/null +++ b/gui/tests/models-price-editor.test.tsx @@ -0,0 +1,427 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { clearClientResourceStoresForTests } from "../src/client-resource"; +import { LanguageProvider } from "../src/i18n/provider"; +import Models from "../src/pages/Models"; +import type { ModelRow } from "../src/pages/models-shared"; + +type Rates = { input: number; output: number; cacheRead: number; cacheWrite: number }; +type Mutation = { modelId: string; cost: Rates | null }; +const FREE = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }; +const SAVED = { input: 1.25, output: 9.5, cacheRead: 0.125, cacheWrite: 2.75 }; + +function deferred() { + let resolve!: () => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} + +describe("Models manual price editor", () => { + const globals = [ + "document", "window", "navigator", "localStorage", "sessionStorage", + "IS_REACT_ACT_ENVIRONMENT", "fetch", "setInterval", "clearInterval", + ] as const; + let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; + let testWindow: Window; + let container: HTMLElement; + let root: Root | null; + let rows: ModelRow[]; + let modelCosts: Record; + let mutations: Mutation[]; + let reads: Array<{ url: string; init?: RequestInit }>; + let catalogReads: number; + let getFailure: boolean; + let catalogFailure: boolean; + let getGate: ReturnType | null; + let putGate: ReturnType | null; + let catalogGate: ReturnType | null; + let getResponse: (() => Response) | null; + let putResponse: ((body: Mutation) => Response) | null; + + beforeEach(() => { + clearClientResourceStoresForTests(); + previousGlobals = Object.fromEntries(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])) as typeof previousGlobals; + testWindow = new Window({ url: "http://localhost/#models" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + sessionStorage: { configurable: true, value: testWindow.sessionStorage }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + setInterval: { configurable: true, value: () => 1 }, + clearInterval: { configurable: true, value: () => {} }, + }); + rows = [ + { provider: "xai-demo", id: "grok-4.6", namespaced: "xai-demo/grok-4.6", disabled: false, manualPricing: true }, + { provider: "xai-demo", id: "vendor/custom", namespaced: "xai-demo/vendor/custom", disabled: false, custom: true, customId: "custom-1" }, + { provider: "openai", id: "gpt-5.5", namespaced: "openai/gpt-5.5", disabled: false, native: true, manualPricing: true }, + { provider: "combo", id: "balanced", namespaced: "combo/balanced", disabled: false, manualPricing: true }, + ]; + const providers = [ + { name: "xai-demo", liveModels: false, models: ["grok-4.6", "vendor/custom"] }, + { name: "openai", liveModels: false, models: ["gpt-5.5"] }, + ]; + modelCosts = { "grok-4.6": { ...SAVED }, sibling: { ...FREE } }; + mutations = []; + reads = []; + catalogReads = 0; + getFailure = false; + catalogFailure = false; + getGate = null; + putGate = null; + catalogGate = null; + getResponse = null; + putResponse = null; + testWindow.localStorage.setItem("ocx-lang", "en"); + testWindow.localStorage.setItem("ocx-models-collapsed:v2", JSON.stringify([])); + testWindow.sessionStorage.setItem("ocx.models.catalog.v1:http://localhost", JSON.stringify({ + models: rows, providers, selectedModels: {}, disabled: [], contextCaps: {}, contextCapValue: 350_000, + })); + globalThis.fetch = (async (input, init) => { + const url = String(input); + if (url.endsWith("/api/providers/xai-demo/model-costs")) { + if (init?.method === "PUT") { + const body = JSON.parse(String(init.body)) as Mutation; + mutations.push(body); + if (putGate) await putGate.promise; + if (body.cost === null) delete modelCosts[body.modelId]; + else modelCosts[body.modelId] = body.cost; + rows = rows.map(row => row.provider === "xai-demo" && row.id === body.modelId + ? { ...row, manualPricing: body.cost !== null } : row); + return putResponse ? putResponse(body) : Response.json({ ok: true, provider: "xai-demo", ...body }); + } + reads.push({ url, init }); + if (getGate) await getGate.promise; + if (getFailure) return Response.json({ error: "unavailable" }, { status: 503 }); + return getResponse ? getResponse() : Response.json({ provider: "xai-demo", modelCosts }); + } + if (url.endsWith("/api/models")) { + catalogReads++; + if (catalogGate) await catalogGate.promise; + if (catalogFailure) return Response.json({ error: "unavailable" }, { status: 503 }); + return Response.json(rows); + } + if (url.endsWith("/api/providers")) return Response.json(providers); + if (url.endsWith("/api/selected-models")) return Response.json({ selected: {} }); + if (url.endsWith("/api/provider-context-caps")) return Response.json({ caps: {} }); + if (url.endsWith("/api/aliases")) return Response.json({ providers: {}, models: {}, defaults: { global: false, providers: {} } }); + if (url.endsWith("/api/combos")) return Response.json({ combos: [] }); + if (url.endsWith("/api/shadow-call-settings")) return Response.json({ enabled: false, model: "" }); + if (url.endsWith("/api/v2")) return Response.json({ enabled: false, agentsMaxThreadsConflict: false, multiAgentMode: "default" }); + return new Response(null, { status: 404 }); + }) as typeof fetch; + container = testWindow.document.createElement("div"); + testWindow.document.body.appendChild(container as never); + root = null; + }); + + afterEach(async () => { + clearClientResourceStoresForTests(); + if (root) await act(async () => root!.unmount()); + getGate?.resolve(); + putGate?.resolve(); + catalogGate?.resolve(); + testWindow.close(); + for (const key of globals) { + const descriptor = previousGlobals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }); + + async function flush() { + await act(async () => { await new Promise(resolve => testWindow.setTimeout(resolve, 0)); }); + } + + async function mount() { + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(container); + root.render(); + }); + await flush(); + } + + function trigger(model = "xai-demo/grok-4.6"): HTMLButtonElement { + return container.querySelector(`[aria-label="Edit price for ${model}"]`)!; + } + + function inputs(): HTMLInputElement[] { + return [...container.querySelectorAll("dialog input")]; + } + + function button(label: string): HTMLButtonElement { + return [...container.querySelectorAll("dialog button")].find(node => node.textContent === label)!; + } + + async function click(label: string) { + await act(async () => button(label).click()); + await flush(); + } + + async function open(model?: string) { + await act(async () => trigger(model).click()); + await flush(); + } + + async function fill(values: string[]) { + for (const [index, value] of values.entries()) { + await act(async () => { + const input = inputs()[index]!; + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!.call(input, value); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + }); + } + } + + test("real routed and custom rows expose Price; badges use manualPricing and exclude native/combo aliases", async () => { + await mount(); + expect(container.querySelectorAll('[aria-label^="Edit price for "]')).toHaveLength(2); + expect(trigger("openai/gpt-5.5")).toBeNull(); + expect(trigger("combo/balanced")).toBeNull(); + expect(trigger().closest(".models-model-row")!.textContent).toContain("Manual price"); + expect(trigger("xai-demo/vendor/custom").closest(".models-model-row")!.textContent).not.toContain("Manual price"); + expect(reads).toHaveLength(0); + }); + + test("opening loads exact fresh rates, focuses input, and closing aborts a pending read", async () => { + await mount(); + await open(); + expect(inputs().map(input => input.value)).toEqual(["1.25", "9.5", "0.125", "2.75"]); + expect(testWindow.document.activeElement).toBe(inputs()[0]); + expect(reads[0]!.init?.cache).toBe("no-store"); + await click("Cancel"); + expect(testWindow.document.activeElement).toBe(trigger()); + + modelCosts["grok-4.6"] = { input: 3, output: 7, cacheRead: 2, cacheWrite: 4 }; + await open(); + expect(inputs().map(input => input.value)).toEqual(["3", "7", "2", "4"]); + await click("Cancel"); + getGate = deferred(); + await open(); + expect(inputs().every(input => input.disabled)).toBe(true); + expect(button("Save").disabled).toBe(true); + const signal = reads.at(-1)!.init!.signal!; + await act(async () => container.querySelector("dialog")!.dispatchEvent(new testWindow.Event("cancel", { cancelable: true }))); + expect(signal.aborted).toBe(true); + expect(container.querySelector("dialog")).toBeNull(); + await act(async () => getGate!.resolve()); + expect(container.querySelector("dialog")).toBeNull(); + }); + + test("missing override starts empty; explicit free saves exact slash-containing ID, refreshes, then closes", async () => { + await mount(); + await open("xai-demo/vendor/custom"); + expect(inputs().map(input => input.value)).toEqual(["", "", "", ""]); + expect(button("Reset to automatic").disabled).toBe(true); + await click("Save"); + expect(mutations).toHaveLength(0); + expect(container.querySelector('[role="alert"]')!.textContent).toContain("Enter input and output rates"); + await fill(["0", "0"]); + expect(inputs().map(input => input.value)).toEqual(["0", "0", "0", "0"]); + const before = catalogReads; + catalogGate = deferred(); + await click("Save"); + expect(mutations).toEqual([{ modelId: "vendor/custom", cost: FREE }]); + expect(catalogReads).toBeGreaterThan(before); + expect(container.querySelector("dialog")).not.toBeNull(); + expect(button("Cancel").disabled).toBe(true); + await act(async () => catalogGate!.resolve()); + await flush(); + expect(container.querySelector("dialog")).toBeNull(); + expect(trigger("xai-demo/vendor/custom").closest(".models-model-row")!.textContent).toContain("Manual price"); + await open("xai-demo/vendor/custom"); + expect(inputs().map(input => input.value)).toEqual(["0", "0", "0", "0"]); + expect(button("Reset to automatic").disabled).toBe(false); + }); + + test("reset sends null and refresh removes the badge without changing sibling rates", async () => { + await mount(); + await open(); + await click("Reset to automatic"); + expect(mutations).toEqual([{ modelId: "grok-4.6", cost: null }]); + expect(modelCosts.sibling).toEqual(FREE); + expect(trigger().closest(".models-model-row")!.textContent).not.toContain("Manual price"); + await open(); + expect(inputs().map(input => input.value)).toEqual(["", "", "", ""]); + }); + + test("finite bounds are enforced and the maximum with fractional cache rates is accepted", async () => { + await mount(); + await open(); + for (const invalid of ["-1", "1000001", ""]) { + await fill([invalid]); + await click("Save"); + expect(mutations).toHaveLength(0); + expect(container.querySelector('[role="alert"]')!.textContent).toContain("finite number"); + } + await fill(["1000000", "0", "0.000001", "0.5"]); + await click("Save"); + expect(mutations).toEqual([{ modelId: "grok-4.6", cost: { input: 1000000, output: 0, cacheRead: 0.000001, cacheWrite: 0.5 } }]); + }); + + test("failed initial reads keep editing locked until a successful reload", async () => { + getFailure = true; + await mount(); + await open(); + expect(inputs().every(input => input.disabled)).toBe(true); + expect(container.querySelector('[role="alert"]')!.textContent).toContain("Could not load"); + expect(testWindow.document.activeElement).toBe(button("Reload price")); + await click("Reload price"); + expect(mutations).toHaveLength(0); + expect(inputs()[0]!.disabled).toBe(true); + getFailure = false; + await click("Reload price"); + expect(inputs()[0]!.value).toBe("1.25"); + expect(inputs()[0]!.disabled).toBe(false); + }); + + for (const failure of ["transport", "malformed", "wrong identity", "wrong cost", "http"] as const) { + test(`${failure} mutation outcome requires read recovery before new edits`, async () => { + await mount(); + await open(); + putResponse = body => { + if (failure === "transport") throw new TypeError("connection dropped"); + if (failure === "malformed") return new Response("{", { status: 200 }); + if (failure === "http") return Response.json({ error: "failed" }, { status: 503 }); + return Response.json({ ok: true, provider: "xai-demo", ...body, + ...(failure === "wrong identity" ? { modelId: "other" } : { cost: SAVED }), + }); + }; + await fill(["0", "0", "0", "0"]); + await click("Save"); + expect(mutations).toHaveLength(1); + expect(inputs().every(input => input.disabled)).toBe(true); + expect(button("Reset to automatic").disabled).toBe(true); + expect(container.querySelector('[role="alert"]')!.textContent).toContain("may have changed"); + await act(async () => button("Reset to automatic").dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true }))); + expect(mutations).toHaveLength(1); + getFailure = true; + await click("Reload price"); + expect(mutations).toHaveLength(1); + expect(inputs()[0]!.disabled).toBe(true); + expect(container.querySelector('[role="alert"]')!.textContent).toContain("Editing stays locked"); + getFailure = false; + await click("Reload price"); + expect(inputs().map(input => input.value)).toEqual(["0", "0", "0", "0"]); + expect(inputs()[0]!.disabled).toBe(false); + expect(container.textContent).toContain("may still change it"); + expect(mutations).toHaveLength(1); + putResponse = null; + await fill(["2", "3"]); + await click("Save"); + expect(mutations[1]).toEqual({ modelId: "grok-4.6", cost: { input: 2, output: 3, cacheRead: 0, cacheWrite: 0 } }); + expect(container.querySelector("dialog")).toBeNull(); + }); + } + + test("malformed GET cost or provider is never treated as an empty override", async () => { + await mount(); + for (const payload of [ + { provider: "other", modelCosts }, + { provider: "xai-demo", modelCosts: { "grok-4.6": { ...SAVED, input: -1 } } }, + { provider: "xai-demo", modelCosts: { "grok-4.6": { input: 1, output: 2 } } }, + { provider: "xai-demo", modelCosts: [] }, + ]) { + getResponse = () => Response.json(payload); + await open(); + expect(inputs().every(input => input.disabled)).toBe(true); + expect(button("Reset to automatic").disabled).toBe(true); + await click("Cancel"); + } + expect(mutations).toHaveLength(0); + }); + + test("a reset with a lost receipt recovers empty rates without replaying the reset", async () => { + await mount(); + await open(); + putResponse = () => { throw new TypeError("receipt lost"); }; + await click("Reset to automatic"); + expect(inputs()[0]!.disabled).toBe(true); + await click("Reload price"); + expect(inputs().map(input => input.value)).toEqual(["", "", "", ""]); + expect(inputs()[0]!.disabled).toBe(false); + expect(button("Reset to automatic").disabled).toBe(true); + expect(mutations).toEqual([{ modelId: "grok-4.6", cost: null }]); + }); + + test("the mutation deadline unlocks cancellation but requires a fresh read before editing", async () => { + await mount(); + await open(); + const descriptor = Object.getOwnPropertyDescriptor(AbortSignal, "timeout"); + const deadline = new AbortController(); + const timeoutBudgets: number[] = []; + const transport = globalThis.fetch; + let pendingSignal: AbortSignal | null | undefined; + try { + Object.defineProperty(AbortSignal, "timeout", { configurable: true, value: (ms: number) => { + timeoutBudgets.push(ms); + return deadline.signal; + } }); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (init?.method === "PUT" && String(input).endsWith("/model-costs")) { + pendingSignal = init.signal; + return new Promise((_resolve, reject) => { + init.signal!.addEventListener("abort", () => reject(new Error("request deadline")), { once: true }); + }); + } + return transport(input, init); + }) as typeof fetch; + await click("Save"); + expect(button("Cancel").disabled).toBe(true); + expect(timeoutBudgets).toEqual([60_000]); + await act(async () => deadline.abort()); + await flush(); + expect(pendingSignal?.aborted).toBe(true); + expect(button("Cancel").disabled).toBe(false); + expect(inputs().every(input => input.disabled)).toBe(true); + expect(button("Reload price").disabled).toBe(false); + } finally { + globalThis.fetch = transport; + if (descriptor) Object.defineProperty(AbortSignal, "timeout", descriptor); + else Reflect.deleteProperty(AbortSignal, "timeout"); + } + await click("Reload price"); + expect(inputs()[0]!.disabled).toBe(false); + expect(reads).toHaveLength(2); + }); + + test("confirmed receipt survives repeated failed catalog refreshes and retries never PUT again", async () => { + await mount(); + await open(); + catalogFailure = true; + await click("Reset to automatic"); + expect(mutations).toHaveLength(1); + expect(inputs().every(input => input.disabled)).toBe(true); + expect(container.querySelector('[role="alert"]')!.textContent).toContain("price was saved"); + await click("Refresh list"); + expect(mutations).toHaveLength(1); + expect(container.querySelector('[role="alert"]')!.textContent).toContain("price was saved"); + expect(reads).toHaveLength(1); + catalogFailure = false; + await click("Refresh list"); + expect(mutations).toEqual([{ modelId: "grok-4.6", cost: null }]); + expect(container.querySelector("dialog")).toBeNull(); + }); + + test("pending mutations reject duplicate submit and dismissal", async () => { + await mount(); + await open(); + putGate = deferred(); + await click("Save"); + await act(async () => { + container.querySelector("dialog form")!.dispatchEvent(new testWindow.Event("submit", { bubbles: true, cancelable: true })); + container.querySelector("dialog")!.dispatchEvent(new testWindow.Event("cancel", { cancelable: true })); + button("Cancel").dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true })); + }); + expect(mutations).toHaveLength(1); + expect(container.querySelector("dialog")).not.toBeNull(); + expect(inputs().every(input => input.disabled)).toBe(true); + await act(async () => putGate!.resolve()); + await flush(); + expect(container.querySelector("dialog")).toBeNull(); + }); +}); diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 60e0f22a0d..ffb001a82d 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1298,7 +1298,9 @@ "zhipu-bigmodel-provider.test.ts": "providers", "zz-ci-api-usage-isolation.test.ts": "ci-workflows", "zz-ci-storage-policy-isolation.test.ts": "ci-workflows", - "zz-pr-coderabbit-readiness-revalidation.test.ts": "ci-workflows" + "zz-pr-coderabbit-readiness-revalidation.test.ts": "ci-workflows", + "cli-models-price.test.ts": "cli", + "model-costs-management-api.test.ts": "server" }, "migrated": [ "adapters", diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 10b0cd9e89..485ed745ba 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -28,6 +28,22 @@ These answer in the CLI head and never reach the proxy, so they work with nothin Safe to run at any time; none of these change state. +### `ocx models price` + +Read the saved manual price for an exact provider/model selector. + +| Method | Route | +|---|---| +| GET | `/api/providers/{provider}/model-costs` | + +| Flag | Value | Meaning | +|---|---|---| +| `--json` | boolean | Emit provider, modelId, and cost (null for automatic pricing). | + +JSON mode: `envelope`. + +- The provider must be configured; everything after the first slash is the exact upstream model ID. + ### `ocx status` Proxy status, injection state, and version skew between this CLI and the running proxy. @@ -353,6 +369,27 @@ JSON mode: `payload`. Each of these writes. Check the flags column before running one unattended. +### `ocx models set-price` + +Save four manual USD-per-1M-token rates, or restore automatic pricing for one model. + +| Method | Route | +|---|---| +| PUT | `/api/providers/{provider}/model-costs` | + +| Flag | Value | Meaning | +|---|---|---| +| `--input` | number | Input rate; required unless --auto is used. | +| `--output` | number | Output rate; required unless --auto is used. | +| `--cache-read` | number | Cache read rate; defaults to 0. | +| `--cache-write` | number | Cache write rate; defaults to 0. | +| `--auto` | boolean | Remove this model's override; cannot be combined with rates. | +| `--json` | boolean | Emit the saved price or reset result as JSON. | + +JSON mode: `payload`. + +- Uses the exact upstream model ID after the first slash. Omitted cache rates default to zero; sibling model prices are preserved. + ### `ocx connect rotate` Rotate the connected client's data key against the hub, with commit and abort. @@ -648,6 +685,6 @@ JSON mode: `payload`. ## Counts -- declared capabilities: 35 -- of those, state-changing: 15 +- declared capabilities: 37 +- of those, state-changing: 16 - head-resolved invocations: 2 diff --git a/src/cli/capabilities.ts b/src/cli/capabilities.ts index ff1f5fb9a2..e34b8ec79b 100644 --- a/src/cli/capabilities.ts +++ b/src/cli/capabilities.ts @@ -95,6 +95,31 @@ export const HEAD_CAPABILITIES: readonly HeadCapability[] = [ * A capability must not name a route the command does not actually fetch. */ export const CAPABILITIES: readonly Capability[] = [ + { + command: ["models", "price"], + summary: "Read the saved manual price for an exact provider/model selector.", + routes: [{ method: "GET", path: "/api/providers/{provider}/model-costs" }], + flags: [{ name: "--json", value: "boolean", summary: "Emit provider, modelId, and cost (null for automatic pricing)." }], + mutates: false, + json: "envelope", + details: ["The provider must be configured; everything after the first slash is the exact upstream model ID."], + }, + { + command: ["models", "set-price"], + summary: "Save four manual USD-per-1M-token rates, or restore automatic pricing for one model.", + routes: [{ method: "PUT", path: "/api/providers/{provider}/model-costs" }], + flags: [ + { name: "--input", value: "number", summary: "Input rate; required unless --auto is used." }, + { name: "--output", value: "number", summary: "Output rate; required unless --auto is used." }, + { name: "--cache-read", value: "number", summary: "Cache read rate; defaults to 0." }, + { name: "--cache-write", value: "number", summary: "Cache write rate; defaults to 0." }, + { name: "--auto", value: "boolean", summary: "Remove this model's override; cannot be combined with rates." }, + { name: "--json", value: "boolean", summary: "Emit the saved price or reset result as JSON." }, + ], + mutates: true, + json: "payload", + details: ["Uses the exact upstream model ID after the first slash. Omitted cache rates default to zero; sibling model prices are preserved."], + }, { command: ["status"], summary: "Proxy status, injection state, and version skew between this CLI and the running proxy.", diff --git a/src/cli/models-runtime-subcommands.ts b/src/cli/models-runtime-subcommands.ts index a49828d203..4aa6d7b77a 100644 --- a/src/cli/models-runtime-subcommands.ts +++ b/src/cli/models-runtime-subcommands.ts @@ -15,6 +15,8 @@ */ export const MODELS_RUNTIME_SUBCOMMANDS = [ "live", + "price", + "set-price", "edit", "enable", "disable", diff --git a/src/cli/models-runtime.ts b/src/cli/models-runtime.ts index e21fa25d9e..d71ce84e47 100644 --- a/src/cli/models-runtime.ts +++ b/src/cli/models-runtime.ts @@ -13,9 +13,18 @@ import { type RuntimeApiDeps, } from "./runtime-api"; import { isModelsRuntimeSubcommand } from "./models-runtime-subcommands"; +import { isValidProviderName } from "../config/provider-name"; +import { isValidModelDiscoveryModelId } from "../providers/model-discovery-limits"; +import { redactSecretString } from "../lib/redact"; +import type { ProviderCostOverlay } from "../types"; +import { MAX_COST4_RATE } from "../usage/expected-prices"; +import { isValidCost4Rate } from "../usage/user-cost-overlays"; const USAGE = `Usage: ocx models live [--provider ] [--json] + ocx models price [--json] + ocx models set-price --input N --output N [--cache-read N] [--cache-write N] [--json] + ocx models set-price --auto [--json] ocx models edit [--model-id ] [--display-name ] [--context-window ] [--modalities ] [--reasoning-efforts ] @@ -28,7 +37,10 @@ const USAGE = `Usage: ocx models new-policy [on|off] [--provider ] [--json] ocx models new-arrivals [--json] ocx models context [--set-all]|provider on [--value ]|provider off|all > [--json] - ocx models shadow [model|-] [--enabled ] [--json]`; + ocx models shadow [model|-] [--enabled ] [--json] + +Prices are USD per 1M tokens. Omitted cache rates default to 0. +Price selectors use the exact upstream model ID after the first slash.`; type ModelRow = { provider?: string; @@ -55,6 +67,58 @@ async function live(argv: string[], deps: RuntimeApiDeps): Promise { })); } +async function price(write: boolean, argv: string[], deps: RuntimeApiDeps): Promise { + const args = [...argv]; + const selector = args.shift() ?? ""; + const slash = selector.indexOf("/"); + const provider = selector.slice(0, slash); + const modelId = selector.slice(slash + 1); + if (slash < 1 || !isValidProviderName(provider) || !isValidModelDiscoveryModelId(modelId)) { + throw new CliUsageError("model selector must be provider/model with an exact upstream model id", USAGE); + } + if (redactSecretString(modelId) !== modelId) { + throw new CliUsageError("modelId cannot be displayed safely", USAGE); + } + const wantsJson = takeFlag(args, "--json"); + const path = `/api/providers/${encodeURIComponent(provider)}/model-costs`; + if (!write) { + rejectArgs(args, USAGE); + const result = await runtimeRequest<{ provider: string; modelCosts: Record }>(path, {}, deps); + const cost = Object.hasOwn(result.modelCosts, modelId) ? result.modelCosts[modelId]! : null; + printData({ provider: result.provider, modelId, cost }, wantsJson, [ + cost === null ? `${selector}: automatic pricing` : `${selector}: ${JSON.stringify(cost)} USD per 1M tokens`, + ]); + return; + } + const auto = takeFlag(args, "--auto"); + const input = takeOption(args, "--input"); + const output = takeOption(args, "--output"); + const cacheRead = takeOption(args, "--cache-read"); + const cacheWrite = takeOption(args, "--cache-write"); + rejectArgs(args, USAGE); + if (auto && [input, output, cacheRead, cacheWrite].some(value => value !== undefined)) { + throw new CliUsageError("--auto cannot be combined with price rates", USAGE); + } + if (!auto && (input === undefined || output === undefined)) { + throw new CliUsageError("--input and --output are required unless --auto is used", USAGE); + } + const rate = (raw: string, flag: string): number => { + const value = Number(raw); + if (!raw.trim() || !isValidCost4Rate(value)) { + throw new CliUsageError(`${flag} must be a finite number between 0 and ${MAX_COST4_RATE}`, USAGE); + } + return value; + }; + const cost: ProviderCostOverlay | null = auto ? null : { + input: rate(input!, "--input"), + output: rate(output!, "--output"), + cacheRead: rate(cacheRead ?? "0", "--cache-read"), + cacheWrite: rate(cacheWrite ?? "0", "--cache-write"), + }; + const result = await runtimeRequest(path, { method: "PUT", body: JSON.stringify({ modelId, cost }) }, deps); + printData(result, wantsJson, [auto ? `${selector}: automatic pricing restored.` : `${selector}: manual pricing saved.`]); +} + async function edit(argv: string[], deps: RuntimeApiDeps): Promise { const args = [...argv]; const id = args.shift()?.trim(); @@ -328,6 +392,8 @@ export async function handleModelsRuntimeCommand(sub: string, argv: string[], de if (!isModelsRuntimeSubcommand(sub)) return null; let action: (() => Promise) | undefined; if (sub === "live") action = () => live(argv, deps); + else if (sub === "price") action = () => price(false, argv, deps); + else if (sub === "set-price") action = () => price(true, argv, deps); else if (sub === "edit") action = () => edit(argv, deps); else if (sub === "enable") action = () => visibility(true, argv, deps); else if (sub === "disable") action = () => visibility(false, argv, deps); diff --git a/src/server/management/model-routes.ts b/src/server/management/model-routes.ts index dd84d8af8c..cc7a732a88 100644 --- a/src/server/management/model-routes.ts +++ b/src/server/management/model-routes.ts @@ -85,6 +85,8 @@ import { multiAgentGuidanceEnabled, providerBaseUrlConfigError, providerHeadersConfigError, + providerModelCostsConfigError, + sanitizeModelCostsForDisplay, saveConfigPreservingClaudeCode, } from "../../config"; import { @@ -98,6 +100,7 @@ import { } from "../../oauth"; import { removeCredential } from "../../oauth/store"; import { providerDestinationResolvedError } from "../../lib/destination-policy"; +import { redactSecretString } from "../../lib/redact"; import { enrichProviderFromCatalog, listKeyLoginProviders } from "../../oauth/key-providers"; import { deriveProviderPresets } from "../../providers/derive"; import { providerCodexAccountMode } from "../../providers/registry"; @@ -128,7 +131,7 @@ import { setDebugSettings, type DebugFlag, } from "../../lib/debug-settings"; -import type { OcxClaudeCodeConfig, OcxConfig, OcxCustomModel, OcxProviderConfig } from "../../types"; +import type { OcxClaudeCodeConfig, OcxConfig, OcxCustomModel, OcxProviderConfig, ProviderCostOverlay } from "../../types"; import { drainAndShutdown } from "../lifecycle"; import { filterRequestLogs, getRequestLogEntries, type RequestLogEntry } from "../request-log"; import { estimateComboCost, estimateRequestCost, normalizeCostTokens, tokensPerSecond } from "../../usage/cost"; @@ -369,6 +372,60 @@ export async function handleModelRoutes(ctx: ManagementContext): Promise key !== "modelId" && key !== "cost")) { + return jsonResponse({ error: "only a valid modelId and cost object or null are allowed" }, 400, req, config); + } + const modelId = body.modelId; + if (redactSecretString(modelId) !== modelId) { + return jsonResponse({ error: "modelId cannot be displayed safely" }, 400, req, config); + } + const submitted = { [modelId]: body.cost }; + const validationError = body.cost === null ? null : providerModelCostsConfigError(submitted); + if (validationError) return jsonResponse({ error: validationError }, 400, req, config); + // Copy only validated rate fields; never echo a secret-shaped model key that the + // shared display boundary suppresses. Model IDs remain exact, including slashes. + const cost = body.cost === null ? null : sanitizeModelCostsForDisplay(submitted)?.[modelId]; + if (cost === undefined) return jsonResponse({ error: "modelId cannot be displayed safely" }, 400, req, config); + + const hadModelCosts = Object.hasOwn(provider, "modelCosts"); + const previousModelCosts = provider.modelCosts; + const nextModelCosts = Object.assign( + Object.create(null) as Record, + previousModelCosts ?? {}, + ); + if (cost === null) delete nextModelCosts[modelId]; + else nextModelCosts[modelId] = cost; + const mergedError = providerModelCostsConfigError(nextModelCosts); + if (mergedError) return jsonResponse({ error: mergedError }, 400, req, config); + if (Object.keys(nextModelCosts).length > 0) provider.modelCosts = nextModelCosts; + else delete provider.modelCosts; + try { + // The persistence owner refreshes usage overlays after its atomic write. + // Price-only edits do not change routing or require catalog convergence. + persistConfig(config); + } catch (error) { + if (hadModelCosts) provider.modelCosts = previousModelCosts; + else delete provider.modelCosts; + throw error; + } + return jsonResponse({ ok: true, provider: name, modelId, cost }, 200, req, config); + } + const displayNameMatch = url.pathname.match(/^\/api\/providers\/([^/]+)\/model-display-names$/); if (displayNameMatch && req.method === "PUT") { let name: string; diff --git a/src/server/management/model-rows.ts b/src/server/management/model-rows.ts index 6d9ec08853..07405c4362 100644 --- a/src/server/management/model-rows.ts +++ b/src/server/management/model-rows.ts @@ -46,6 +46,7 @@ export type ManagementModelRow = Partial & { native?: boolean; custom?: boolean; customId?: string; + manualPricing?: boolean; fastRowAvailable?: boolean; displayNameOverride?: string; displayNameSource?: "operator" | "provider" | "fallback"; @@ -181,8 +182,12 @@ export async function listManagementModelRows( for (const row of rows) knownIds.add(row.namespaced); return rows.map(row => { const pending = initialModelSelectionPending(config.providers[row.provider]); + const modelCosts = Object.hasOwn(config.providers, row.provider) + ? config.providers[row.provider]?.modelCosts : undefined; return { ...row, + ...(!row.native && modelCosts !== undefined && Object.hasOwn(modelCosts, row.id) + ? { manualPricing: true } : {}), ...(pending ? { disabled: true, initialSelectionPending: true } : {}), fastRowAvailable: !row.disabled && !pending && !knownIds.has(fastRowId(row.namespaced)) && catalogFastRowEligible(config, row), diff --git a/src/server/management/route-registry.ts b/src/server/management/route-registry.ts index 421ead31e0..6c7d57547b 100644 --- a/src/server/management/route-registry.ts +++ b/src/server/management/route-registry.ts @@ -334,6 +334,8 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [ { method: "GET", path: "/api/request-history/{id}/route-decision", module: "server/management/request-history-routes", mutates: false, mechanism: "ends-with" }, { method: "PUT", path: "/api/providers/{provider}/alias", module: "server/management/model-routes", mutates: true, mechanism: "regex" }, { method: "PUT", path: "/api/providers/{provider}/model-aliases", module: "server/management/model-routes", mutates: true, mechanism: "regex" }, + { method: "GET", path: "/api/providers/{provider}/model-costs", module: "server/management/model-routes", mutates: false, mechanism: "regex" }, + { method: "PUT", path: "/api/providers/{provider}/model-costs", module: "server/management/model-routes", mutates: true, mechanism: "regex" }, { method: "PUT", path: "/api/custom-models/{id}", module: "server/management/model-routes", mutates: true, mechanism: "regex" }, { method: "DELETE", path: "/api/custom-models/{id}", module: "server/management/model-routes", mutates: true, mechanism: "regex" }, { method: "GET", path: "/api/lab/subjects/{id}", module: "server/management/lab-routes", mutates: false, mechanism: "regex", exempt: { reason: "local-transport", why: "ocx lab reads the same rows from the local SQLite projection; src/cli/lab.ts imports ../lab/query directly and never fetches /api/lab." } }, diff --git a/src/usage/cost.ts b/src/usage/cost.ts index 2a3b2ae6d3..deb7f6f20b 100644 --- a/src/usage/cost.ts +++ b/src/usage/cost.ts @@ -177,8 +177,8 @@ export function calculateCost(tokens: CostTokens, cost4: Cost4): CostBreakdown { * bundle) nonzero -> overlay verified -> overlay verified-derived -> jawcode * model-level vendor price (cross-provider fallback: a model follows its official * vendor price — WP5 policy, e.g. kiro/claude-opus-4-6 uses the anthropic price) - * -> null. All-zero rows are overlay candidates (zero is "not billable here", - * not "free"). + * -> null. An explicit all-zero user override means free; all-zero catalog + * rows remain overlay candidates rather than evidence of free pricing. */ export function resolveMatchedPrice( provider: string, @@ -244,7 +244,7 @@ function resolveMatchedPriceInner( /** * Exact provider/model price lookup: user-configured `modelCosts` first, then * an exact official correction, the jawcode provider bundle, the expected-price overlay, then the - * model-level vendor fallback. All-zero rows fall through ("not billable"). + * model-level vendor fallback. All-zero catalog rows fall through; user zeros win. */ function resolveMatchedPriceExact( provider: string, @@ -302,14 +302,14 @@ function resolveMatchedPriceExact( }; } -/** User-configured overlay match (all-zero rows fall through like any other source). */ +/** User-configured overlay match; explicit zero rates are authoritative too. */ function userOverlayMatch( provider: string, modelId: string, userOverlays: readonly ExpectedPriceOverlay[], ): MatchedPrice | null { const overlay = findExpectedPriceOverlay(provider, modelId, userOverlays); - if (!overlay || !validCost4(overlay.cost4) || !hasNonZeroCost(overlay.cost4)) return null; + if (!overlay || !validCost4(overlay.cost4)) return null; return { provider, modelId, diff --git a/tests/cli/cli-models-price.test.ts b/tests/cli/cli-models-price.test.ts new file mode 100644 index 0000000000..c36b049ce5 --- /dev/null +++ b/tests/cli/cli-models-price.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, test } from "bun:test"; +import { handleModelsRuntimeCommand } from "../../src/cli/models-runtime"; +import { CAPABILITIES } from "../../src/cli/capabilities"; +import { MANAGEMENT_ROUTES } from "../../src/server/management/route-registry"; + +const COST = { input: 1.25, output: 5, cacheRead: 0.125, cacheWrite: 2 }; + +async function invoke(sub: string, args: string[], response: unknown = { ok: true }, status = 200) { + const calls: Array<{ path: string; method: string; body: unknown }> = []; + const stdout: string[] = []; + const stderr: string[] = []; + const log = console.log; + const error = console.error; + console.log = (...values: unknown[]) => { stdout.push(values.map(String).join(" ")); }; + console.error = (...values: unknown[]) => { stderr.push(values.map(String).join(" ")); }; + try { + const code = await handleModelsRuntimeCommand(sub, args, { + baseUrl: "http://127.0.0.1:1", + fetchImpl: async (url, init) => { + calls.push({ + path: new URL(String(url)).pathname, + method: init?.method ?? "GET", + body: init?.body ? JSON.parse(String(init.body)) : undefined, + }); + return Response.json(response, { status }); + }, + }); + return { code, calls, stdout: stdout.join("\n"), stderr: stderr.join("\n") }; + } finally { + console.log = log; + console.error = error; + } +} + +describe("models manual price commands", () => { + test("price reads the map and selects the exact ID after the first slash", async () => { + const result = await invoke("price", ["custom-price/org/model--fast", "--json"], { + provider: "custom-price", + modelCosts: { "org/model--fast": COST, "org--model--fast": { input: 9, output: 9, cacheRead: 9, cacheWrite: 9 } }, + }); + expect(result.code).toBe(0); + expect(result.calls).toEqual([{ path: "/api/providers/custom-price/model-costs", method: "GET", body: undefined }]); + expect(JSON.parse(result.stdout)).toEqual({ provider: "custom-price", modelId: "org/model--fast", cost: COST }); + }); + + test("missing own keys read as automatic, including prototype-shaped selectors", async () => { + for (const modelId of ["missing", "__proto__", "constructor", "toString"]) { + const result = await invoke("price", [`custom-price/${modelId}`, "--json"], { provider: "custom-price", modelCosts: {} }); + expect(result.code).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ provider: "custom-price", modelId, cost: null }); + } + const automatic = await invoke("price", ["custom-price/missing"], { provider: "custom-price", modelCosts: {} }); + expect(automatic.stdout).toContain("automatic pricing"); + }); + + test("set-price sends four numeric rates with omitted cache rates defaulted to zero", async () => { + const result = await invoke("set-price", ["custom-price/org/model", "--input", "1.25", "--output", "5", "--json"]); + expect(result.code).toBe(0); + expect(result.calls).toEqual([{ + path: "/api/providers/custom-price/model-costs", method: "PUT", + body: { modelId: "org/model", cost: { input: 1.25, output: 5, cacheRead: 0, cacheWrite: 0 } }, + }]); + }); + + test("explicit cache rates, all-zero pricing, and the maximum rate are transmitted unchanged", async () => { + const explicit = await invoke("set-price", ["custom-price/org/model", "--input", "1.25", "--output", "5", "--cache-read", "0.125", "--cache-write", "2"]); + expect(explicit.code).toBe(0); + expect(explicit.calls[0]!.body).toEqual({ modelId: "org/model", cost: COST }); + const zero = await invoke("set-price", ["custom-price/model", "--input", "0", "--output", "0"]); + expect(zero.code).toBe(0); + expect(zero.calls[0]!.body).toEqual({ modelId: "model", cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } }); + const max = await invoke("set-price", ["custom-price/model", "--input", "1000000", "--output", "1e6"]); + expect(max.code).toBe(0); + expect(max.calls[0]!.body).toEqual({ modelId: "model", cost: { input: 1_000_000, output: 1_000_000, cacheRead: 0, cacheWrite: 0 } }); + }); + + test("--auto sends null and preserves the exact upstream ID", async () => { + const payload = { ok: true, provider: "custom-price", modelId: "org/model", cost: null }; + const result = await invoke("set-price", ["custom-price/org/model", "--auto", "--json"], payload); + expect(result.code).toBe(0); + expect(result.calls).toEqual([{ + path: "/api/providers/custom-price/model-costs", method: "PUT", body: { modelId: "org/model", cost: null }, + }]); + expect(JSON.parse(result.stdout)).toEqual(payload); + }); + + test("invalid selectors and read options fail before any request", async () => { + for (const selector of ["", "native-model", "/model", "provider/", " provider/model", "provider/ model", "provider/model ", "provider/bad\nmodel", "provider/" + "x".repeat(1025), "__proto__/model"]) { + for (const sub of ["price", "set-price"]) { + const result = await invoke(sub, [selector, ...(sub === "set-price" ? ["--auto"] : [])]); + expect(result.code).toBe(2); + expect(result.calls).toHaveLength(0); + } + } + for (const args of [["--auto"], ["--input", "1"], ["extra"], ["--json", "--json"]]) { + const result = await invoke("price", ["custom-price/model", ...args]); + expect(result.code).toBe(2); + expect(result.calls).toHaveLength(0); + } + }); + + test("missing, conflicting, repeated, unknown and invalid rate arguments make no requests", async () => { + const cases = [ + [], ["--input", "1"], ["--output", "2"], ["--input"], ["--input", "--output", "2"], + ["--auto", "--input", "0"], ["--auto", "--cache-read", "0"], ["--auto", "--cache-write", "0"], + ["--auto", "--auto"], ["--auto", "--unknown"], ["--auto", "extra"], + ["--input", "1", "--input", "2", "--output", "3"], + ...["", " ", "NaN", "Infinity", "1e309", "-1", "1000001", "1x", "1,2"].map(rate => ["--input", rate, "--output", "1"]), + ...["--output", "--cache-read", "--cache-write"].map(flag => flag === "--output" + ? ["--input", "1", flag, "-1"] : ["--input", "1", "--output", "2", flag, "-1"]), + ]; + for (const args of cases) { + const result = await invoke("set-price", ["custom-price/model", ...args]); + expect(result.code).toBe(2); + expect(result.calls).toHaveLength(0); + expect(result.stderr.length).toBeGreaterThan(0); + } + }); + + test("API rejection is reported with a nonzero exit and no success message", async () => { + const result = await invoke("set-price", ["custom-price/model", "--auto"], { error: "provider not found" }, 404); + expect(result.code).toBe(1); + expect(result.stderr).toContain("provider not found"); + expect(result.stdout).toBe(""); + }); + + test("secret-shaped model selectors fail before request or output for read, set and reset", async () => { + const modelId = "sk-" + "a".repeat(40); + for (const [sub, flags] of [ + ["price", []], + ["set-price", ["--input", "1", "--output", "2"]], + ["set-price", ["--auto"]], + ] as const) { + const result = await invoke(sub, [`custom-price/${modelId}`, ...flags, "--json"]); + expect(result.code).toBe(2); + expect(result.calls).toHaveLength(0); + expect(result.stdout).toBe(""); + expect(result.stderr).not.toContain(modelId); + expect(result.stderr).toContain("modelId cannot be displayed safely"); + } + }); + + test("capabilities map both CLI verbs onto the registered route methods", () => { + for (const [sub, method, mutates] of [["price", "GET", false], ["set-price", "PUT", true]] as const) { + const capability = CAPABILITIES.find(entry => entry.command.join(" ") === `models ${sub}`); + expect(capability?.routes).toEqual([{ method, path: "/api/providers/{provider}/model-costs" }]); + expect(capability?.mutates).toBe(mutates); + expect(MANAGEMENT_ROUTES.find(route => route.method === method && route.path === "/api/providers/{provider}/model-costs")).toMatchObject({ + module: "server/management/model-routes", mutates, mechanism: "regex", + }); + } + }); +}); diff --git a/tests/cli/cli-models-runtime-dispatch.test.ts b/tests/cli/cli-models-runtime-dispatch.test.ts index 3608fe9457..8145ec701e 100644 --- a/tests/cli/cli-models-runtime-dispatch.test.ts +++ b/tests/cli/cli-models-runtime-dispatch.test.ts @@ -37,6 +37,22 @@ describe("models runtime subcommand dispatch (#3094)", () => { expect(isModelsRuntimeSubcommand("new-arrivals")).toBe(true); }); + test("price and set-price are routed through the runtime dispatcher", async () => { + expect(isModelsRuntimeSubcommand("price")).toBe(true); + expect(isModelsRuntimeSubcommand("set-price")).toBe(true); + const methods: string[] = []; + const deps = { + baseUrl: "http://127.0.0.1:1", + fetchImpl: async (_url: string | URL | Request, init?: RequestInit) => { + methods.push(init?.method ?? "GET"); + return Response.json({ provider: "dispatch-test", modelCosts: {}, ok: true }); + }, + }; + expect(await handleModelsRuntimeCommand("price", ["dispatch-test/model"], deps)).toBe(0); + expect(await handleModelsRuntimeCommand("set-price", ["dispatch-test/model", "--auto"], deps)).toBe(0); + expect(methods).toEqual(["GET", "PUT"]); + }); + test("handleModels routes exactly the shared set to the runtime module", () => { // Reading the source keeps this honest without booting the CLI: the dispatch must // consult the shared predicate rather than re-listing names inline. @@ -54,4 +70,3 @@ describe("models runtime subcommand dispatch (#3094)", () => { expect(new Set(MODELS_RUNTIME_SUBCOMMANDS).size).toBe(MODELS_RUNTIME_SUBCOMMANDS.length); }); }); - diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index fe613ac71f..496d51ea31 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1133,5 +1133,7 @@ "zhipu-bigmodel-provider.test.ts": "providers", "zz-ci-api-usage-isolation.test.ts": "ci-workflows", "zz-ci-storage-policy-isolation.test.ts": "ci-workflows", - "zz-pr-coderabbit-readiness-revalidation.test.ts": "ci-workflows" + "zz-pr-coderabbit-readiness-revalidation.test.ts": "ci-workflows", + "cli-models-price.test.ts": "cli", + "model-costs-management-api.test.ts": "server" } diff --git a/tests/server/model-costs-management-api.test.ts b/tests/server/model-costs-management-api.test.ts new file mode 100644 index 0000000000..856bf9ee79 --- /dev/null +++ b/tests/server/model-costs-management-api.test.ts @@ -0,0 +1,270 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { clearModelCache } from "../../src/codex/model-cache"; +import { resetCodexModelEntitlementCacheForTests } from "../../src/codex/model-entitlements"; +import { saveConfigPreservingClaudeCode } from "../../src/config"; +import { handleManagementAPI } from "../../src/server/management-api"; +import { handleModelRoutes } from "../../src/server/management/model-routes"; +import { listManagementModelRows } from "../../src/server/management/model-rows"; +import type { OcxConfig, ProviderCostOverlay } from "../../src/types"; +import { activeUserCostOverlays, refreshUserCostOverlays } from "../../src/usage/user-cost-overlays"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const PROVIDER = "manual-price-test"; +const COST: ProviderCostOverlay = { input: 1.25, output: 5, cacheRead: 0.125, cacheWrite: 2 }; +const SIBLING: ProviderCostOverlay = { input: 3, output: 7, cacheRead: 0.5, cacheWrite: 4 }; +const ZERO: ProviderCostOverlay = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }; +let home: string; +let previousHome: string | undefined; +let previousCodexHome: string | undefined; + +function fixture(costs?: Record): OcxConfig { + return { + port: 10100, + defaultProvider: PROVIDER, + modelCacheTtlMs: 60_000, + providers: { + [PROVIDER]: { + adapter: "openai-chat", + baseUrl: "https://price.example.invalid/v1", + alias: "price-alias", + liveModels: false, + models: ["org/model", "org/other", "sibling", "custom"], + ...(costs ? { modelCosts: costs } : {}), + }, + }, + }; +} + +beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + previousCodexHome = process.env.CODEX_HOME; + home = mkdtempSync(join(tmpdir(), "ocx-model-prices-")); + process.env.OPENCODEX_HOME = home; + process.env.CODEX_HOME = join(home, "codex"); +}); + +afterEach(() => { + clearModelCache(); + resetCodexModelEntitlementCacheForTests(); + refreshUserCostOverlays(fixture()); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + if (previousCodexHome === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = previousCodexHome; + removeTreeWithRetry(home); +}); + +function harness(config = fixture(), persist?: (saved: OcxConfig) => void) { + const persisted: OcxConfig[] = []; + let convergeCalls = 0; + async function call(method: "GET" | "PUT", body?: unknown, provider = PROVIDER, rawBody?: string, rawProvider?: string) { + const url = new URL(`http://127.0.0.1:10100/api/providers/${rawProvider ?? encodeURIComponent(provider)}/model-costs`); + const response = await handleModelRoutes({ + version: "test", + req: new Request(url, { + method, + headers: { "Content-Type": "application/json" }, + ...(method === "PUT" ? { body: rawBody ?? JSON.stringify(body) } : {}), + }), + url, + config, + deps: { + saveConfigPreservingClaudeCode: saved => { + persist?.(saved); + persisted.push(structuredClone(saved)); + }, + }, + convergeCodexCatalog: async () => { + convergeCalls += 1; + throw new Error("price writes must not converge catalogs"); + }, + syncClaudeAgentDefsBestEffort: async () => {}, + }); + if (!response) throw new Error("model-costs route was not dispatched"); + return response; + } + return { call, config, persisted, get convergeCalls() { return convergeCalls; } }; +} + +describe("provider model costs API", () => { + test("GET returns the exact configured provider's sanitized map or an empty map", async () => { + const h = harness(); + expect(await (await h.call("GET")).json()).toEqual({ provider: PROVIDER, modelCosts: {} }); + const costs = JSON.parse(JSON.stringify({ + "org/model": { ...COST, apiKey: "not-for-display" }, + bad: { ...COST, input: -1 }, + ["sk-" + "a".repeat(40)]: COST, + })); + h.config.providers[PROVIDER]!.modelCosts = costs; + expect(await (await h.call("GET")).json()).toEqual({ provider: PROVIDER, modelCosts: { "org/model": COST } }); + expect(h.persisted).toHaveLength(0); + }); + + test("set, replace with explicit zero, and reset persist only the exact model key", async () => { + const h = harness(fixture({ sibling: SIBLING, "org--model": SIBLING })); + for (const cost of [COST, ZERO, null]) { + const response = await h.call("PUT", { modelId: "org/model", cost }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ ok: true, provider: PROVIDER, modelId: "org/model", cost }); + const expected = { sibling: SIBLING, "org--model": SIBLING, ...(cost ? { "org/model": cost } : {}) }; + expect(h.config.providers[PROVIDER]!.modelCosts).toEqual(expected); + expect(h.persisted.at(-1)!.providers[PROVIDER]!.modelCosts).toEqual(expected); + } + expect(h.persisted).toHaveLength(3); + expect(h.convergeCalls).toBe(0); + }); + + test("reset of the last entry removes the map and repeated reset remains successful", async () => { + const h = harness(fixture({ "org/model": COST })); + for (let attempt = 0; attempt < 2; attempt++) { + expect((await h.call("PUT", { modelId: "org/model", cost: null })).status).toBe(200); + expect(Object.hasOwn(h.config.providers[PROVIDER]!, "modelCosts")).toBe(false); + expect(await (await h.call("GET")).json()).toEqual({ provider: PROVIDER, modelCosts: {} }); + } + }); + + test("the normal persistence owner writes disk and refreshes the overlay registry", async () => { + const config = fixture({ sibling: SIBLING }); + writeFileSync(join(home, "config.json"), JSON.stringify(config)); + const h = harness(config, saveConfigPreservingClaudeCode); + await h.call("PUT", { modelId: "org/model", cost: COST }); + const disk = JSON.parse(readFileSync(join(home, "config.json"), "utf8")) as OcxConfig; + expect(disk.providers[PROVIDER]!.modelCosts).toEqual({ sibling: SIBLING, "org/model": COST }); + expect(activeUserCostOverlays().find(row => row.provider === PROVIDER && row.modelId === "org/model")?.cost4).toEqual(COST); + expect(await (await harness(disk).call("GET")).json()).toEqual({ provider: PROVIDER, modelCosts: { sibling: SIBLING, "org/model": COST } }); + await h.call("PUT", { modelId: "org/model", cost: null }); + expect(JSON.parse(readFileSync(join(home, "config.json"), "utf8")).providers[PROVIDER].modelCosts).toEqual({ sibling: SIBLING }); + expect(activeUserCostOverlays().some(row => row.provider === PROVIDER && row.modelId === "org/model")).toBe(false); + }); + + test("persist failure restores map identity and own-property absence for set and reset", async () => { + for (const costs of [undefined, {}, { "org/model": COST, sibling: SIBLING }]) { + for (const cost of [SIBLING, null]) { + const config = fixture(costs); + const provider = config.providers[PROVIDER]!; + const previous = provider.modelCosts; + const snapshot = structuredClone(previous); + const hadMap = Object.hasOwn(provider, "modelCosts"); + const h = harness(config, () => { throw new Error("disk full"); }); + await expect(h.call("PUT", { modelId: "org/model", cost })).rejects.toThrow("disk full"); + expect(provider.modelCosts).toBe(previous); + expect(provider.modelCosts).toEqual(snapshot); + expect(Object.hasOwn(provider, "modelCosts")).toBe(hadMap); + expect(h.persisted).toHaveLength(0); + expect(h.convergeCalls).toBe(0); + } + } + }); + + test("missing, alias, case-folded and inherited provider names are not resolved", async () => { + const h = harness(); + for (const method of ["GET", "PUT"] as const) { + for (const provider of ["missing", "price-alias", PROVIDER.toUpperCase(), "__proto__", "constructor", "toString"]) { + expect((await h.call(method, { modelId: "org/model", cost: COST }, provider)).status).toBe(404); + } + expect((await h.call(method, { modelId: "org/model", cost: COST }, PROVIDER, undefined, "%E0%A4%A")).status).toBe(400); + } + expect(h.persisted).toHaveLength(0); + }); + + test("malformed bodies, model IDs, rates and extra fields fail before mutation", async () => { + const h = harness(fixture({ sibling: SIBLING })); + const original = h.config.providers[PROVIDER]!.modelCosts; + const invalid: unknown[] = [null, [], 4, {}, { modelId: "org/model" }, { cost: COST }, + ...["", " ", " model", "model ", "bad\nmodel", "x".repeat(1025), 42].map(modelId => ({ modelId, cost: null })), + ...[null, [], "1", true, -1, 1_000_001].map(input => ({ modelId: "org/model", cost: { ...COST, input } })), + ...[[], "auto", 0, { input: 1, output: 2 }, { ...COST, apiKey: "extra" }].map(cost => ({ modelId: "org/model", cost })), + { modelId: "org/model", cost: COST, extra: true }, + JSON.parse('{"modelId":"org/model","cost":null,"__proto__":{"polluted":true}}'), + JSON.parse('{"modelId":"org/model","cost":{"input":1,"output":2,"cacheRead":0,"cacheWrite":0,"constructor":{}}}'), + JSON.parse('{"modelId":"org/model","cost":{"input":1,"output":2,"cacheRead":0,"cacheWrite":0,"__proto__":{}}}'), + ]; + for (const body of invalid) expect((await h.call("PUT", body)).status).toBe(400); + for (const raw of ["{", "", '{"modelId":"org/model","cost":{"input":1e309,"output":1,"cacheRead":0,"cacheWrite":0}}']) { + expect((await h.call("PUT", undefined, PROVIDER, raw)).status).toBe(400); + } + expect(h.config.providers[PROVIDER]!.modelCosts).toBe(original); + expect(h.persisted).toHaveLength(0); + }); + + test("prototype-shaped model keys are stored and reset as own data without touching prototypes", async () => { + const h = harness(fixture({ sibling: SIBLING })); + for (const modelId of ["__proto__", "constructor", "toString"]) { + expect((await h.call("PUT", { modelId, cost: COST })).status).toBe(200); + const map = h.config.providers[PROVIDER]!.modelCosts!; + expect(Object.getPrototypeOf(map)).toBeNull(); + expect(Object.hasOwn(map, modelId)).toBe(true); + expect(map[modelId]).toEqual(COST); + const body = await (await h.call("GET")).json() as { modelCosts: Record }; + expect(Object.hasOwn(body.modelCosts, modelId)).toBe(true); + expect(body.modelCosts[modelId]).toEqual(COST); + await h.call("PUT", { modelId, cost: null }); + expect(Object.hasOwn(h.config.providers[PROVIDER]!.modelCosts!, modelId)).toBe(false); + } + expect(h.config.providers[PROVIDER]!.modelCosts).toEqual({ sibling: SIBLING }); + expect(Object.hasOwn(Object.prototype, "input")).toBe(false); + }); + + test("secret-shaped model IDs are rejected without echo on both set and reset", async () => { + const modelId = "sk-" + "a".repeat(40); + const h = harness(fixture({ [modelId]: COST, sibling: SIBLING })); + const original = h.config.providers[PROVIDER]!.modelCosts; + for (const cost of [COST, null]) { + const response = await h.call("PUT", { modelId, cost }); + expect(response.status).toBe(400); + expect(await response.text()).not.toContain(modelId); + } + expect(h.config.providers[PROVIDER]!.modelCosts).toBe(original); + expect(h.persisted).toHaveLength(0); + }); + + test("management dispatch reaches GET/PUT and still rejects cross-origin writes", async () => { + const config = fixture(); + const url = new URL(`http://127.0.0.1:10100/api/providers/${PROVIDER}/model-costs`); + let writes = 0; + for (const method of ["PUT", "GET"] as const) { + const response = await handleManagementAPI(new Request(url, { + method, headers: { Host: url.host, "Content-Type": "application/json" }, + ...(method === "PUT" ? { body: JSON.stringify({ modelId: "org/model", cost: COST }) } : {}), + }), url, config, { saveConfigPreservingClaudeCode: () => { writes++; } }); + expect(response?.status).toBe(200); + } + const blocked = await handleManagementAPI(new Request(url, { + method: "PUT", headers: { Host: url.host, Origin: "https://other.example.invalid" }, + body: JSON.stringify({ modelId: "org/model", cost: null }), + }), url, config, { saveConfigPreservingClaudeCode: () => { writes++; } }); + expect(blocked?.status).toBe(403); + expect(writes).toBe(1); + expect(config.providers[PROVIDER]!.modelCosts).toEqual({ "org/model": COST }); + }); + + test("set survives reload as manualPricing true and reset omits the badge field", async () => { + const config = fixture({ "org--other": SIBLING }); + config.customModels = [{ id: "custom-row", provider: PROVIDER, modelId: "custom" }]; + const h = harness(config); + expect((await h.call("PUT", { modelId: "org/model", cost: ZERO })).status).toBe(200); + expect((await h.call("PUT", { modelId: "custom", cost: COST })).status).toBe(200); + const reloaded = JSON.parse(JSON.stringify(config)) as OcxConfig; + const rows = await listManagementModelRows(reloaded, { entitlementWaitMs: 0 }); + expect(rows.find(row => row.provider === PROVIDER && row.id === "org/model")?.manualPricing).toBe(true); + for (const modelId of ["org/other", "sibling"]) { + const row = rows.find(row => row.provider === PROVIDER && row.id === modelId); + expect(row).toBeDefined(); + expect(Object.hasOwn(row!, "manualPricing")).toBe(false); + } + expect(rows.find(row => row.customId === "custom-row")?.manualPricing).toBe(true); + expect(rows.filter(row => row.native).every(row => !Object.hasOwn(row, "manualPricing"))).toBe(true); + for (const modelId of ["org/model", "custom"]) { + expect((await harness(reloaded).call("PUT", { modelId, cost: null })).status).toBe(200); + } + const resetRows = await listManagementModelRows(reloaded, { entitlementWaitMs: 0 }); + for (const modelId of ["org/model", "custom"]) { + const row = resetRows.find(row => row.provider === PROVIDER && row.id === modelId); + expect(row).toBeDefined(); + expect(Object.hasOwn(row!, "manualPricing")).toBe(false); + } + }); +}); diff --git a/tests/usage/usage-cost.test.ts b/tests/usage/usage-cost.test.ts index f234622e07..aa5711534e 100644 --- a/tests/usage/usage-cost.test.ts +++ b/tests/usage/usage-cost.test.ts @@ -1140,7 +1140,7 @@ describe("provider cost overlay (user-configured)", () => { }); }); - test("an all-zero overlay on a suffix-shaped configured provider falls through to compiled pricing, not the base provider's overlay", () => { + test("an explicit zero overlay on a suffix-shaped configured provider wins over every fallback", () => { refreshUserCostOverlays({ providers: { acme: { modelCosts: { "claude-opus-4-6": USER_PRICE } }, @@ -1150,16 +1150,12 @@ describe("provider cost overlay (user-configured)", () => { }, } as unknown as OcxConfig); const price = resolveMatchedPrice("acme-pabcdef", "claude-opus-4-6"); - // The all-zero row falls through to compiled/catalog pricing — the - // documented fallback order — and never to acme's user-configured price. + // Operator zero is an explicit free estimate, not missing catalog metadata. expect(price).not.toBeNull(); expect(price?.provider).toBe("acme-pabcdef"); - expect(price?.source).toBe("jawcode"); + expect(price?.source).toBe("user"); expect(price?.cost4).not.toEqual(USER_PRICE); - // A real positive catalog price, without pinning the vendor's current - // rate (the catalog lives outside this PR and may change independently). - expect(price?.cost4?.input).toBeGreaterThan(0); - expect(price?.cost4?.output).toBeGreaterThan(0); + expect(price?.cost4).toEqual({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }); }); test("a generated account label (not a configured provider) still collapses to the base provider's overlay", () => { @@ -1200,7 +1196,7 @@ describe("provider cost overlay (user-configured)", () => { expect(resolveMatchedPrice("acme-pabcdef", "acme-custom-model")).toBeNull(); }); - test("all-zero user overlay falls through to the expected overlay price", () => { + test("all-zero user overlay gives known-zero request and combo estimates until reset", () => { const zero: ExpectedPriceOverlay[] = [{ provider: "deepseek", modelId: "deepseek-chat", @@ -1210,10 +1206,13 @@ describe("provider cost overlay (user-configured)", () => { status: "verified", }]; const price = resolveMatchedPrice("deepseek", "deepseek-chat", undefined, zero); - expect(price?.source).toBe("expected"); - // A real positive expected-overlay price, without pinning the current - // rate (the overlay table may change independently of this feature). - expect(price?.cost4.input).toBeGreaterThan(0); + expect(price?.source).toBe("user"); + expect(price?.cost4).toEqual(zero[0]!.cost4); + const input = { provider: "deepseek", model: "deepseek-chat", usageStatus: "reported" as const, + usage: { inputTokens: 1_000_000, outputTokens: 100_000 } }; + expect(estimateRequestCost(input, undefined, zero)?.cost.total).toBe(0); + expect(estimateComboCost([{ ...input, ordinal: 1 }], undefined, undefined, zero)?.cost.total).toBe(0); + expect(resolveMatchedPrice("deepseek", "deepseek-chat", undefined, [])?.cost4.input).toBeGreaterThan(0); }); test("combo fails closed when a user-priced attempt shares a combo with an unpriced one", () => { From 062e9cbd39338945a3377f4ffbf2fa1dff41c65a Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:56:38 +0900 Subject: [PATCH 064/116] fix(models): validate price receipts and redact CLI failures [skip ci] Address independent review findings on the manual price CLI; preserve HTTP-specific exit codes and project only acknowledged fields. Co-authored-by: nordz0r <6949669+nordz0r@users.noreply.github.com> --- src/cli/models-runtime.ts | 49 ++++++++++++-- tests/cli/cli-models-price.test.ts | 67 +++++++++++++++++-- tests/cli/cli-models-runtime-dispatch.test.ts | 4 +- 3 files changed, 110 insertions(+), 10 deletions(-) diff --git a/src/cli/models-runtime.ts b/src/cli/models-runtime.ts index d71ce84e47..129f2fb53b 100644 --- a/src/cli/models-runtime.ts +++ b/src/cli/models-runtime.ts @@ -67,7 +67,31 @@ async function live(argv: string[], deps: RuntimeApiDeps): Promise { })); } +function priceRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +const PRICE_RATE_KEYS = ["input", "output", "cacheRead", "cacheWrite"] as const; + +function validPriceCost(value: unknown): value is ProviderCostOverlay { + return priceRecord(value) && Object.keys(value).length === PRICE_RATE_KEYS.length + && PRICE_RATE_KEYS.every(key => Object.hasOwn(value, key) && isValidCost4Rate(value[key])); +} + async function price(write: boolean, argv: string[], deps: RuntimeApiDeps): Promise { + try { + await priceRequest(write, argv, deps); + } catch (error) { + // Duplicated, inline and stray options also reach parser diagnostics. + // Keep HTTP-specific RuntimeApiError exits while masking usage errors. + if (error instanceof CliUsageError) { + throw new CliUsageError(redactSecretString(error.message), error.usage); + } + throw error; + } +} + +async function priceRequest(write: boolean, argv: string[], deps: RuntimeApiDeps): Promise { const args = [...argv]; const selector = args.shift() ?? ""; const slash = selector.indexOf("/"); @@ -83,9 +107,18 @@ async function price(write: boolean, argv: string[], deps: RuntimeApiDeps): Prom const path = `/api/providers/${encodeURIComponent(provider)}/model-costs`; if (!write) { rejectArgs(args, USAGE); - const result = await runtimeRequest<{ provider: string; modelCosts: Record }>(path, {}, deps); - const cost = Object.hasOwn(result.modelCosts, modelId) ? result.modelCosts[modelId]! : null; - printData({ provider: result.provider, modelId, cost }, wantsJson, [ + const result = await runtimeRequest(path, {}, deps); + if (!priceRecord(result) || result.provider !== provider || !priceRecord(result.modelCosts) + || !Object.values(result.modelCosts).every(validPriceCost)) { + throw new Error("Invalid model price response"); + } + let cost: ProviderCostOverlay | null = null; + if (Object.hasOwn(result.modelCosts, modelId)) { + const stored = result.modelCosts[modelId]; + if (!validPriceCost(stored)) throw new Error("Invalid model price response"); + cost = { ...stored }; + } + printData({ provider, modelId, cost }, wantsJson, [ cost === null ? `${selector}: automatic pricing` : `${selector}: ${JSON.stringify(cost)} USD per 1M tokens`, ]); return; @@ -116,7 +149,15 @@ async function price(write: boolean, argv: string[], deps: RuntimeApiDeps): Prom cacheWrite: rate(cacheWrite ?? "0", "--cache-write"), }; const result = await runtimeRequest(path, { method: "PUT", body: JSON.stringify({ modelId, cost }) }, deps); - printData(result, wantsJson, [auto ? `${selector}: automatic pricing restored.` : `${selector}: manual pricing saved.`]); + const receivedCost = priceRecord(result) ? result.cost : undefined; + if (!priceRecord(result) || result.ok !== true || result.provider !== provider || result.modelId !== modelId + || (cost === null ? receivedCost !== null : !validPriceCost(receivedCost) + || !PRICE_RATE_KEYS.every(key => receivedCost[key] === cost[key]))) { + throw new Error("Invalid model price persistence receipt"); + } + // Project the acknowledged fields only; unrelated response fields are not CLI output. + printData({ ok: true, provider, modelId, cost }, wantsJson, + [auto ? `${selector}: automatic pricing restored.` : `${selector}: manual pricing saved.`]); } async function edit(argv: string[], deps: RuntimeApiDeps): Promise { diff --git a/tests/cli/cli-models-price.test.ts b/tests/cli/cli-models-price.test.ts index c36b049ce5..9adda79977 100644 --- a/tests/cli/cli-models-price.test.ts +++ b/tests/cli/cli-models-price.test.ts @@ -5,7 +5,7 @@ import { MANAGEMENT_ROUTES } from "../../src/server/management/route-registry"; const COST = { input: 1.25, output: 5, cacheRead: 0.125, cacheWrite: 2 }; -async function invoke(sub: string, args: string[], response: unknown = { ok: true }, status = 200) { +async function invoke(sub: string, args: string[], response?: unknown, status = 200) { const calls: Array<{ path: string; method: string; body: unknown }> = []; const stdout: string[] = []; const stderr: string[] = []; @@ -17,12 +17,17 @@ async function invoke(sub: string, args: string[], response: unknown = { ok: tru const code = await handleModelsRuntimeCommand(sub, args, { baseUrl: "http://127.0.0.1:1", fetchImpl: async (url, init) => { + const path = new URL(String(url)).pathname; + const body = init?.body ? JSON.parse(String(init.body)) : undefined; calls.push({ - path: new URL(String(url)).pathname, + path, method: init?.method ?? "GET", - body: init?.body ? JSON.parse(String(init.body)) : undefined, + body, }); - return Response.json(response, { status }); + if (response instanceof Response) return response; + return Response.json(response === undefined + ? { ok: true, provider: path.split("/")[3], modelId: body?.modelId, cost: body?.cost } + : response, { status }); }, }); return { code, calls, stdout: stdout.join("\n"), stderr: stderr.join("\n") }; @@ -119,11 +124,63 @@ describe("models manual price commands", () => { test("API rejection is reported with a nonzero exit and no success message", async () => { const result = await invoke("set-price", ["custom-price/model", "--auto"], { error: "provider not found" }, 404); - expect(result.code).toBe(1); + expect(result.code).toBe(4); expect(result.stderr).toContain("provider not found"); expect(result.stdout).toBe(""); }); + test("duplicate, inline and stray price arguments never echo credential-shaped values", async () => { + const secret = "sk-" + "a".repeat(40); + for (const extra of [["--input", secret], [`--input=${secret}`], [secret]]) { + const result = await invoke("set-price", ["custom-price/model", "--input", "1", "--output", "2", ...extra]); + expect(result.code).toBe(2); + expect(result.calls).toHaveLength(0); + expect(result.stderr).not.toContain(secret); + expect(result.stderr).toContain("Unexpected argument(s)"); + expect(result.stdout).toBe(""); + } + }); + + test("malformed or mismatched success receipts fail without printing response contents", async () => { + const secret = "sk-" + "a".repeat(40); + const cost = { input: 1, output: 2, cacheRead: 0, cacheWrite: 0 }; + const receipt = { ok: true, provider: "custom-price", modelId: "model", cost }; + for (const response of [ + null, {}, "malformed", new Response("{"), new Response(null, { status: 204 }), + { ...receipt, ok: false }, { ...receipt, provider: "other" }, { ...receipt, modelId: "other" }, + { ...receipt, cost: null }, { ...receipt, cost: { input: 1, output: 2 } }, + { ...receipt, cost: { ...cost, output: 3 } }, { ...receipt, cost: { ...cost, apiKey: secret } }, + ]) { + const result = await invoke("set-price", ["custom-price/model", "--input", "1", "--output", "2"], response); + expect(result.code).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("Invalid model price persistence receipt"); + expect(result.stderr).not.toContain(secret); + } + const badReset = await invoke("set-price", ["custom-price/model", "--auto"], receipt); + expect(badReset.code).toBe(1); + expect(badReset.stdout).toBe(""); + const projected = await invoke("set-price", ["custom-price/model", "--input", "1", "--output", "2", "--json"], { ...receipt, apiKey: secret }); + expect(projected.code).toBe(0); + expect(JSON.parse(projected.stdout)).toEqual(receipt); + expect(projected.stdout).not.toContain(secret); + }); + + test("invalid GET maps fail rather than appearing automatic or leaking extra rate fields", async () => { + for (const response of [ + null, {}, new Response("{"), { provider: "other", modelCosts: {} }, + { provider: "custom-price", modelCosts: [] }, + { provider: "custom-price", modelCosts: { model: null } }, + { provider: "custom-price", modelCosts: { model: { ...COST, input: -1 } } }, + { provider: "custom-price", modelCosts: { model: { ...COST, extra: "unexpected" } } }, + ]) { + const result = await invoke("price", ["custom-price/model", "--json"], response); + expect(result.code).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("Invalid model price response"); + } + }); + test("secret-shaped model selectors fail before request or output for read, set and reset", async () => { const modelId = "sk-" + "a".repeat(40); for (const [sub, flags] of [ diff --git a/tests/cli/cli-models-runtime-dispatch.test.ts b/tests/cli/cli-models-runtime-dispatch.test.ts index 8145ec701e..06bc8f43b1 100644 --- a/tests/cli/cli-models-runtime-dispatch.test.ts +++ b/tests/cli/cli-models-runtime-dispatch.test.ts @@ -45,7 +45,9 @@ describe("models runtime subcommand dispatch (#3094)", () => { baseUrl: "http://127.0.0.1:1", fetchImpl: async (_url: string | URL | Request, init?: RequestInit) => { methods.push(init?.method ?? "GET"); - return Response.json({ provider: "dispatch-test", modelCosts: {}, ok: true }); + return Response.json(init?.method === "PUT" + ? { provider: "dispatch-test", modelId: "model", cost: null, ok: true } + : { provider: "dispatch-test", modelCosts: {} }); }, }; expect(await handleModelsRuntimeCommand("price", ["dispatch-test/model"], deps)).toBe(0); From a6e1227c8c6909eba8efc85d4a1ee3a992288bd7 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:14:02 +0900 Subject: [PATCH 065/116] fix(models): start price reload state from user actions [skip ci] Address exact-head GUI lint diagnosis without disabling the rule; initial loading uses initialized state and effects update only after the fetch. Co-authored-by: nordz0r <6949669+nordz0r@users.noreply.github.com> --- gui/src/components/ModelPriceDialog.tsx | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/gui/src/components/ModelPriceDialog.tsx b/gui/src/components/ModelPriceDialog.tsx index c4e08d98b6..f6e1a58200 100644 --- a/gui/src/components/ModelPriceDialog.tsx +++ b/gui/src/components/ModelPriceDialog.tsx @@ -62,8 +62,6 @@ export default function ModelPriceDialog({ model, apiBase, onRefresh, onClose }: if (requestRef.current) return; const bounded = createBoundedFetch(REQUEST_TIMEOUT_MS); requestRef.current = bounded; - setPhase("loading"); - setErrorKey(null); try { const response = await fetch(endpoint, { signal: bounded.signal, cache: "no-store" }); const result = await readJsonOrThrow(response); @@ -168,7 +166,12 @@ export default function ModelPriceDialog({ model, apiBase, onRefresh, onClose }: onSubmit={event => { event.preventDefault(); if (requestRef.current) return; - if (phase === "unknown" || phase === "loadFailed") { void readOverride(phase === "unknown"); return; } + if (phase === "unknown" || phase === "loadFailed") { + setPhase("loading"); + setErrorKey(null); + void readOverride(phase === "unknown"); + return; + } if (phase === "refreshFailed") { void save(undefined); return; } if (locked) return; const cost = { From 568a3e89cb4bc67987d86acbf5e9d63fb3015c9b Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:36:04 +0900 Subject: [PATCH 066/116] docs: record code-mode delivery and qualify Desktop model switching [skip ci] --- .../040_delivery_record.md | 100 ++++++++++++++++++ .../src/content/docs/guides/claude-code.md | 12 ++- 2 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 devlog/_plan/260907_code_mode_host_contract/040_delivery_record.md diff --git a/devlog/_plan/260907_code_mode_host_contract/040_delivery_record.md b/devlog/_plan/260907_code_mode_host_contract/040_delivery_record.md new file mode 100644 index 0000000000..3c2b28e23d --- /dev/null +++ b/devlog/_plan/260907_code_mode_host_contract/040_delivery_record.md @@ -0,0 +1,100 @@ +# 040 — Delivery record: code-mode host contract + +Recorded 2026-09-07 from GitHub PR and Actions API responses. This records the delivery requested +by [030_docs_and_delivery.md](030_docs_and_delivery.md#d-record). + +## Delivered revision and CI identity + +- [PR #3854](https://github.com/lidge-jun/opencodex/pull/3854) is merged into `dev`; + GitHub records `merged_at: 2026-09-07T06:41:03Z`. +- Final PR head: `6bdcba5bff4196debf3cd159c7af3d34e35a24e0`. +- Merge commit: `ece556a6ed32dc811bd660ddd8ef9e829512457a`. +- [Pre-merge CI run 34090946313](https://github.com/lidge-jun/opencodex/actions/runs/34090946313), + attempt 1: `event: pull_request`, `head_sha: 6bdcba5bff4196debf3cd159c7af3d34e35a24e0`, + `status: completed`, `conclusion: success`; updated `2026-09-07T06:39:04Z`. +- [Merge-head CI run 34091933836](https://github.com/lidge-jun/opencodex/actions/runs/34091933836), attempt 1: + `event: push`, `head_sha: ece556a6ed32dc811bd660ddd8ef9e829512457a`, + `status: completed`, `conclusion: success`; updated `2026-09-07T06:50:18Z`. + +The pre-merge run matches the final PR head; the later push run matches the merge commit. +These are distinct CI records. This API check does not attest that the separate local receipt +required by 030 was recorded. + +## Per-job results + +Each run has 21 completed jobs: 19 success, 2 skipped. Every job has the same conclusion in both +runs. Names below are the literal Actions job names; each evidence link identifies its own run. + +| Job | Conclusion in both runs | Pre-merge evidence | Merge-head evidence | +|---|---|---|---| +| `select windows runner` | success | [job 101644191502](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644191502) | [job 101647069433](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647069433) | +| `changes` | success | [job 101644191303](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644191303) | [job 101647069779](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647069779) | +| `windows ${{ matrix.shard }}/6` | skipped | [job 101644212182](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644212182) | [job 101647096144](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647096144) | +| `macos 1/2` | success | [job 101644233998](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644233998) | [job 101647111898](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111898) | +| `api usage` | success | [job 101644234038](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234038) | [job 101647111914](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111914) | +| `storage policy` | success | [job 101644234034](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234034) | [job 101647111922](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111922) | +| `docker smoke` | success | [job 101644234277](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234277) | [job 101647111928](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111928) | +| `keyring ubuntu` | success | [job 101644234063](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234063) | [job 101647111929](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111929) | +| `test 3/4` | success | [job 101644234103](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234103) | [job 101647111932](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111932) | +| `test 4/4` | success | [job 101644234047](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234047) | [job 101647111936](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111936) | +| `keyring macos` | success | [job 101644233982](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644233982) | [job 101647111942](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111942) | +| `test 1/4` | success | [job 101644234139](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234139) | [job 101647111951](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111951) | +| `gates` | success | [job 101644233985](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644233985) | [job 101647111970](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111970) | +| `keyring windows` | success | [job 101644234037](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234037) | [job 101647111972](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111972) | +| `macos 2/2` | success | [job 101644234066](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234066) | [job 101647111974](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111974) | +| `npm-global ubuntu-latest` | success | [job 101644234059](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234059) | [job 101647111980](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111980) | +| `npm-global windows-latest` | success | [job 101644234098](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234098) | [job 101647111990](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647111990) | +| `test 2/4` | success | [job 101644234167](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234167) | [job 101647112003](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647112003) | +| `npm-global macos-latest` | success | [job 101644234033](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644234033) | [job 101647112012](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647112012) | +| `macos control` | skipped | [job 101644235362](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101644235362) | [job 101647112696](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101647112696) | +| `ci` | success | [job 101646588871](https://github.com/lidge-jun/opencodex/actions/runs/34090946313/job/101646588871) | [job 101649082610](https://github.com/lidge-jun/opencodex/actions/runs/34091933836/job/101649082610) | + +The Windows full-suite matrix was **SKIPPED in both runs**. Windows keyring create/read/delete smoke and +npm-global packaging/install/help smoke passed; those focused passes do not establish Windows +full-suite coverage. The `ci` aggregate accepts successful or skipped prerequisites, so its green +result does not turn skipped jobs into passes. On the merge-head run, `gates` includes successful Typecheck, GUI tests, +Privacy scan, skill-surface check, release-helper syntax check, and CLI help smoke; its GUI lint, +GUI build, and dashboard-preview steps were skipped. + +Evidence retrieval (read-only): + +```sh +gh api repos/lidge-jun/opencodex/pulls/3854 +gh api repos/lidge-jun/opencodex/actions/runs/34090946313 +gh api 'repos/lidge-jun/opencodex/actions/runs/34090946313/jobs?per_page=100' +gh api repos/lidge-jun/opencodex/actions/runs/34091933836 +gh api 'repos/lidge-jun/opencodex/actions/runs/34091933836/jobs?per_page=100' +``` + +## Limits and residuals + +The delivered scope is the pre-call guidance and post-hoc recovery annotations described in +[030](030_docs_and_delivery.md). Guidance cannot force model compliance, repair the model's +JavaScript or patch payload, or replace the host's validation. The effect on the live Grok defect +rate remains **unmeasured** until a live re-probe; CI success is not a defect-rate measurement. + +Anthropic, Google, OpenAI-chat, and command-code tool-result paths still lack exec-result +annotation seams and do not annotate these host failures. Existing coverage is limited to native +routed Responses, Kiro, and Cursor. + +Two public review threads were **OPEN / UNRESOLVED in the recorded 2026-09-07 audit snapshot**: GitHub's review-thread API returned +`isResolved: false` for both on 2026-09-07. The merge and green CI do not resolve these findings. +Source inspected for that snapshot was read at worktree HEAD `0fd3408b99994f74bd509975df7ee89823ddfecd`: + +- [discussion_r3947178410](https://github.com/lidge-jun/opencodex/pull/3854#discussion_r3947178410): + `src/adapters/exec-tool-result-normalize.ts:196` searches arbitrary output for a marker substring. + Successful output from a command such as `rg` or `cat` can therefore receive a misleading + recovery hint when it quotes that phrase, even though the command did not fail. The requested + host-error status/envelope or exact diagnostic check remains unimplemented at this anchor. +- [discussion_r3947178418](https://github.com/lidge-jun/opencodex/pull/3854#discussion_r3947178418): + `src/adapters/cursor/tool-result-normalize.ts:114` gates annotation on tool name/namespace + without request-catalog or freeform provenance. A structured tool named `exec` can receive + unrelated host guidance. The requested code-mode provenance check remains unimplemented at + this anchor. + +These limitations were also recorded in [000](000_plan.md). Recording them here is not a fix, +review resolution, or claim that successful output is left byte-identical. + +Local runtime, tests, typecheck, build, and install: **NOT RUN** by instruction. No live model +re-probe was performed for this record. The remote results above belong to the recorded PR head +and merge commit and do not validate later candidate documentation or test patches. diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index 0b1c0e9db4..0c3cb32697 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -309,8 +309,16 @@ canonical ids. The synthetic 2026 date is an internal slot, not a release date. and `claude-ocx---` ids from older configs still resolve. If Claude Desktop's footer picker does not change the model for an already-running 3P -conversation, use `/model ` in that conversation. OpenCodex cannot observe picker state; it -routes the model id carried by each request. Confirm the result under **Logs → requestedModel**. +conversation, you can try `/model `, but this workaround may also fail on affected Desktop +builds. [Issue #3782](https://github.com/lidge-jun/opencodex/issues/3782) reports that on Windows +with Claude Desktop 1.46388.4, the conversation continues using its initial model after both +footer-picker and `/model` changes. The report does not establish which client or routing +component causes the behavior. + +You can also try selecting the intended default model in the OpenCodex Claude Desktop profile, +reapplying the profile, and starting a new conversation. This is a troubleshooting step, not a +guaranteed fix. OpenCodex cannot observe picker state; it routes the model id carried by each +request. Confirm what the client sends under **Logs → requestedModel**. Models with an authoritative 1M context window get an extra `…[1m]` picker row: selecting it makes Claude Code account a full 1M context for that model (auto-compaction stays on) — the proxy strips From e0a1a8836e447ece3010ba98813e6feb3161eefd Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:33:29 +0900 Subject: [PATCH 067/116] docs: complete Raycast status and model-name recovery guidance [skip ci] --- .../content/docs/fr/guides/integrations.md | 2 +- .../fr/reference/configuration/providers.md | 18 +++++++++ .../src/content/docs/guides/integrations.md | 24 ++++++++---- .../ja/reference/configuration/providers.md | 16 ++++++++ .../ko/reference/configuration/providers.md | 14 +++++++ .../ru/reference/configuration/providers.md | 18 +++++++++ .../tr/reference/configuration/providers.md | 17 ++++++++ .../reference/configuration/providers.md | 12 ++++++ .../reference/configuration/providers.md | 12 ++++++ src/cli/integrations.ts | 2 +- tests/cli/cli-headless-parity.test.ts | 39 +++++++++++++++++++ 11 files changed, 164 insertions(+), 10 deletions(-) diff --git a/docs-site/src/content/docs/fr/guides/integrations.md b/docs-site/src/content/docs/fr/guides/integrations.md index c718801ddc..97babedd18 100644 --- a/docs-site/src/content/docs/fr/guides/integrations.md +++ b/docs-site/src/content/docs/fr/guides/integrations.md @@ -128,7 +128,7 @@ niveaux. Dans ces cas, le commutateur est verrouillé afin que rien ne soit modi **OMP** n'est pas affecté non plus par les modifications voisines, mais pour une autre raison : son outil d'écriture ne modifie, octet par octet, que sa propre plage `providers.opencodex` ; le reste du fichier n'est jamais réécrit. Pour les autres formats susceptibles de contenir des commentaires (Hermes, OpenClaw, -Kimi Code, Gajae Code, MiniMax Code, ZCode, Prime Agent, Aside et Raycast — documents YAML, JSON5 et TOML réécrits en entier), ou lorsque les propres entrées +Kimi Code, Gajae Code, MiniMax Code et Raycast — documents YAML, JSON5 et TOML réécrits en entier), ou lorsque les propres entrées d'opencodex ont été modifiées, le commutateur se verrouille et la désactivation est refusée plutôt que de deviner quelles modifications vous appartiennent. diff --git a/docs-site/src/content/docs/fr/reference/configuration/providers.md b/docs-site/src/content/docs/fr/reference/configuration/providers.md index 96d00e5668..9686bb2470 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/fr/reference/configuration/providers.md @@ -473,6 +473,24 @@ avec un contexte de `922000` et une entrée maximale de `922000` ; OpenRouter i } ``` +## Éditeur de noms d'affichage des modèles + +Dans le tableau de bord, **Models** permet d'enregistrer durablement des noms lisibles pour les modèles découverts. Développez le fournisseur, +repérez un modèle découvert et choisissez **Name**. La boîte de dialogue garde le sélecteur exact +`provider/model` visible pendant que vous enregistrez un libellé lisible. Choisissez **Reset name** +pour revenir aux métadonnées du fournisseur ou au sélecteur utilisé par défaut. **Name** ne change +que l'affichage ; le crayon distinct consacré à l'alias modifie l'alias court de routage et n'est +pas un éditeur de nom d'affichage. Les lignes OpenAI natives et celles des modèles personnalisés +conservent leurs commandes existantes. + +Si la modification est enregistrée mais que l'actualisation échoue, la boîte de dialogue reflète +la valeur enregistrée et garde **Retry** disponible. Retry relance la convergence du catalogue +si le serveur a signalé son échec, ou recharge la liste si seule la requête de liste a échoué. +La reprise d'une réinitialisation conserve cette opération ; elle ne rétablit pas l'ancien nom. +Les requêtes ont un délai maximal de 60 secondes couvrant l'écriture et l'actualisation de la liste +qui suit. Un dépassement de délai n'annule pas une écriture : utilisez **Retry** pour vérifier +le nom actuel avant d'effectuer une autre modification. + ## Exemple complet ```json diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index ea3c93f2dd..b475b71e20 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -62,14 +62,22 @@ One caveat specific to Aside: the running app rewrites `models.json` itself, so fully quit and reopen Aside after applying, the same way Claude Desktop needs a restart. Aside's block is loopback-only and never carries a real credential. -Raycast has two prerequisites. Custom Providers is a **Raycast Pro** feature: on a -free plan the file is still written, but `ocx integration client status --client -raycast` and the Integrations page report a warning, because Raycast will not -read it. And Raycast only creates its `ai` folder when you open Raycast → -Settings → AI → **Reveal Providers Config** once; opencodex uses that folder as -the install signal and reports the client as not installed until then. Raycast -reads `~/.config/raycast/ai/providers.yaml` on macOS and Windows alike and does -not honor `XDG_CONFIG_HOME`, so that path is not relocatable. +The managed Raycast integration supports **macOS and Windows**. Custom Providers +is a **Raycast Pro** feature: on a free plan the file is still written, but +`ocx integration client status --client raycast` and the Integrations page report +a warning, because Raycast will not read it. On macOS or Windows, open Raycast → +Settings → AI → **Reveal Providers Config** once so the `ai` folder exists. +On these supported platforms, opencodex uses that folder as its install signal +and reports the client as not installed until it exists. Linux is unsupported, +even if the folder exists. + +The status field `aiDirPresent` reports only whether `~/.config/raycast/ai` exists, +independently of whether the Raycast app is installed or the platform is supported. +It does not prove that Raycast is installed or usable. The CLI prints `plan` on a +separate line and adds the macOS/Windows setup instruction when `aiDirPresent` is +false; `--json` preserves the raw status, including the nested `raycast` block. +Raycast reads `~/.config/raycast/ai/providers.yaml` on macOS and Windows alike and +does not honor `XDG_CONFIG_HOME`, so that path is not relocatable. The managed block is one element, `id: opencodex`, in the file's `providers` sequence: `name: OpenCodex`, `base_url: http://:/v1`, and every diff --git a/docs-site/src/content/docs/ja/reference/configuration/providers.md b/docs-site/src/content/docs/ja/reference/configuration/providers.md index 8938073e6c..dc7929d26e 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ja/reference/configuration/providers.md @@ -394,6 +394,22 @@ Vercel AI Gateway は、1 つのモデルを複数の基盤となる推論プロ } ``` +## モデルの表示名エディター + +ダッシュボードの **Models** では、検出されたモデルに読みやすい名前を付けて永続的に保存できます。プロバイダーを展開し、検出された +モデルを見つけて **Name** を選択します。読みやすい名前を保存する間も、ダイアログには正確な +`provider/model` セレクターが表示されます。**Reset name** を選ぶと、プロバイダーのメタデータ、 +または通常のセレクター表示に戻ります。**Name** が変更するのは表示だけです。別のエイリアス用 +鉛筆アイコンは短いルーティングエイリアスを変更するもので、表示名エディターではありません。 +ネイティブ OpenAI とカスタムモデルの行では、既存の操作方法が維持されます。 + +変更は保存されたものの更新に失敗した場合、ダイアログは保存済みの上書き設定を反映し、**Retry** を +引き続き利用できます。サーバーがカタログの収束処理の失敗を報告した場合、Retry はその処理を再実行し、 +一覧取得のリクエストだけが失敗した場合は一覧を再読み込みします。リセット後の復旧でもリセット操作を +維持し、以前の名前には戻しません。リクエストには、書き込みとその後の一覧更新を合わせて 60 秒の +期限があります。タイムアウトしても書き込みは取り消されません。次の変更を行う前に **Retry** で +現在の名前を確認してください。 + ## 完全な例 ```json diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md index 2dda27e7bf..75ae5055b6 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md @@ -401,6 +401,20 @@ Vercel AI Gateway는 하나의 모델을 여러 기반 추론 공급자에 걸 } ``` +## 모델 표시 이름 편집기 + +대시보드의 **Models**에서 발견된 모델의 읽기 쉬운 이름을 저장해 유지할 수 있습니다. 공급자를 펼치고 발견된 모델을 +찾아 **Name**을 선택하세요. 읽기 쉬운 이름을 저장하는 동안에도 대화 상자는 정확한 `provider/model` +선택자를 표시합니다. **Reset name**을 선택하면 공급자 메타데이터 또는 기본 선택자 표시로 돌아갑니다. +**Name**은 표시만 바꿉니다. 별도의 별칭 연필 아이콘은 짧은 라우팅 별칭을 바꾸며, 표시 이름 편집기가 +아닙니다. 네이티브 OpenAI와 사용자 지정 모델 행은 기존 조작 방식을 유지합니다. + +변경은 저장됐지만 새로고침에 실패하면 대화 상자는 저장된 재정의를 반영하고 **Retry**를 계속 제공합니다. +서버가 카탈로그 수렴 실패를 보고했다면 Retry는 수렴을 다시 실행하고, 목록 요청만 실패했다면 목록을 +다시 불러옵니다. 초기화 후 복구는 초기화 작업을 유지하며 이전 이름을 복원하지 않습니다. 요청에는 +쓰기와 후속 목록 새로고침을 모두 포함하는 60초 제한이 있습니다. 시간 초과가 쓰기를 취소하지는 않습니다. +다른 변경을 하기 전에 **Retry**로 현재 이름을 확인하세요. + ## 전체 예시 ```json diff --git a/docs-site/src/content/docs/ru/reference/configuration/providers.md b/docs-site/src/content/docs/ru/reference/configuration/providers.md index 14a8b0a3ce..3ddb29c806 100644 --- a/docs-site/src/content/docs/ru/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ru/reference/configuration/providers.md @@ -488,6 +488,24 @@ Pool/Direct рекламирует `922000`; синхронизированны } ``` +## Редактор отображаемых имён моделей + +На странице **Models** в дашборде можно задать понятные имена для обнаруженных моделей и сохранить их для дальнейшего использования. Разверните провайдера, +найдите обнаруженную модель и выберите **Name**. При сохранении понятной подписи диалог оставляет +видимым точный селектор `provider/model`. Выберите **Reset name**, чтобы вернуться к metadata +провайдера или обычному селектору, используемому по умолчанию. **Name** меняет только отображение; +отдельный значок карандаша для alias меняет короткий routing alias и не является редактором +отображаемого имени. Нативные строки OpenAI и строки пользовательских моделей сохраняют +существующие элементы управления. + +Если изменение сохранено, но обновление не удалось, диалог отражает сохранённое переопределение +и оставляет **Retry** доступным. Retry повторяет приведение каталога к согласованному состоянию, +если сервер сообщил о сбое этого процесса, или перезагружает список, если не удался только запрос +списка. Восстановление после сброса сохраняет операцию сброса и не возвращает старое имя. +Для запросов действует общий срок в 60 секунд, включающий запись и последующее обновление списка. +Тайм-аут не отменяет запись: используйте **Retry**, чтобы проверить текущее имя перед следующим +изменением. + ## Полный пример ```json diff --git a/docs-site/src/content/docs/tr/reference/configuration/providers.md b/docs-site/src/content/docs/tr/reference/configuration/providers.md index 3e01051010..daffcd2120 100644 --- a/docs-site/src/content/docs/tr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/tr/reference/configuration/providers.md @@ -518,6 +518,23 @@ bildirir; senkronize edilen katalog `xhigh`'ı ayrı tutarken `max` bildirir. } ``` +## Model görünen adı düzenleyicisi + +Kontrol panelindeki **Models**, keşfedilen modeller için okunabilir adları kalıcı olarak kaydetmenizi sağlar. Sağlayıcıyı genişletin, keşfedilen +bir modeli bulun ve **Name** seçeneğini seçin. Okunabilir bir etiket kaydederken iletişim kutusu +tam `provider/model` seçicisini görünür tutar. Sağlayıcı meta verilerine veya varsayılan seçici +gösterimine dönmek için **Reset name** seçeneğini seçin. **Name** yalnızca görünümü değiştirir; +ayrı takma ad kalemi kısa yönlendirme takma adını değiştirir ve bir görünen ad düzenleyicisi +değildir. Yerel OpenAI ve özel model satırları mevcut kontrollerini korur. + +Değişiklik kaydedildiği halde yenileme başarısız olursa iletişim kutusu kaydedilen geçersiz kılma +değerini yansıtır ve **Retry** kullanılabilir kalır. Sunucu katalog yakınsamasının başarısız +olduğunu bildirdiyse Retry bu işlemi tekrarlar; yalnızca liste isteği başarısız olduysa listeyi +yeniden yükler. Sıfırlama sonrası kurtarma, sıfırlama işlemini korur ve eski adı geri getirmez. +İsteklerin, yazma işlemini ve ardından gelen liste yenilemesini kapsayan 60 saniyelik bir süresi +vardır. Zaman aşımı yazma işlemini geri almaz: başka bir değişiklik yapmadan önce **Retry** ile +geçerli adı kontrol edin. + ## Tam örnek ```json diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md index 32f2b52a69..313663f346 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md @@ -395,6 +395,18 @@ Vercel AI Gateway 可以在多个底层推理提供者之间路由一个模型 } ``` +## 模型显示名称编辑器 + +仪表板的 **Models** 可让你为已发现的模型持久保存易读名称。展开提供者,找到一个已发现的模型,然后选择 **Name**。 +保存易读名称时,对话框会一直显示精确的 `provider/model` 选择器。选择 **Reset name** 可恢复为 +提供者元数据中的名称,或默认的选择器显示。**Name** 只改变显示;单独的别名铅笔图标用于修改 +短路由别名,并不是显示名称编辑器。原生 OpenAI 和自定义模型条目保留现有控件。 + +如果更改已保存但刷新失败,对话框会反映已保存的覆盖值,并继续提供 **Retry**。如果服务器报告 +目录收敛失败,Retry 会重新执行目录收敛;如果只是列表请求失败,则重新加载列表。重置后的恢复 +会保留重置操作,不会恢复旧名称。请求的总时限为 60 秒,涵盖写入及后续的列表刷新。超时不会撤销 +写入:进行其他更改前,请使用 **Retry** 检查当前名称。 + ## 完整示例 ```json diff --git a/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md b/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md index 2a53c4d33a..74ee860ff1 100644 --- a/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-tw/reference/configuration/providers.md @@ -352,6 +352,18 @@ Vercel AI Gateway 可在多個底層推論供應商之間路由一個模型。`v } ``` +## 模型顯示名稱編輯器 + +儀表板的 **Models** 可讓你為已探索到的模型持久儲存易讀名稱。展開供應商,找到已探索到的模型,然後選擇 **Name**。 +儲存易讀名稱時,對話方塊會持續顯示精確的 `provider/model` 選擇器。選擇 **Reset name** 可回到 +供應商中繼資料中的名稱,或預設的選擇器顯示。**Name** 只改變顯示;獨立的別名鉛筆圖示用來修改 +短路由別名,並不是顯示名稱編輯器。原生 OpenAI 與自訂模型列保留既有控制項。 + +若變更已儲存但重新整理失敗,對話方塊會反映已儲存的覆寫值,並繼續提供 **Retry**。若伺服器回報 +目錄收斂失敗,Retry 會重新執行目錄收斂;若只有清單請求失敗,則重新載入清單。重設後的復原 +會保留重設操作,不會還原舊名稱。請求的總期限為 60 秒,涵蓋寫入及後續的清單重新整理。逾時不會 +撤銷寫入:進行其他變更前,請使用 **Retry** 檢查目前名稱。 + ## 完整範例 ```json diff --git a/src/cli/integrations.ts b/src/cli/integrations.ts index 89ab3ee046..5b690a6c8b 100644 --- a/src/cli/integrations.ts +++ b/src/cli/integrations.ts @@ -189,7 +189,7 @@ function singleClientStatusLines(result: unknown): string[] { const rest = Object.fromEntries(Object.entries(result as Record).filter(([key]) => key !== "raycast")); const lines = [...summaryLines(rest), `plan: ${raycast.plan}`]; if (!raycast.aiDirPresent) { - lines.push('Open Raycast → Settings → AI → "Reveal Providers Config" once so the ai folder exists.'); + lines.push('On macOS or Windows, open Raycast → Settings → AI → "Reveal Providers Config" once so the ai folder exists.'); } return lines; } diff --git a/tests/cli/cli-headless-parity.test.ts b/tests/cli/cli-headless-parity.test.ts index dab85a132c..78f0cc04a1 100644 --- a/tests/cli/cli-headless-parity.test.ts +++ b/tests/cli/cli-headless-parity.test.ts @@ -609,6 +609,45 @@ describe("headless GUI parity CLI", () => { expect(runtime.requests[1]).toEqual({ path: "/api/grok/selection", method: "PUT", body: { excluded: ["b"] } }); }); + for (const plan of ["pro", "free", "unknown"] as const) { + for (const aiDirPresent of [true, false]) { + test(`Raycast status keeps plan ${plan} separate with aiDirPresent=${aiDirPresent}`, async () => { + const payload = { + clientId: "raycast", + installed: aiDirPresent, + raycast: { plan, aiDirPresent }, + }; + const runtime = fakeRuntime(() => payload); + const logSpy = spyOn(console, "log").mockImplementation(() => {}); + try { + expect(await handleClientIntegrationCommand(["status", "--client", "raycast"], runtime.deps)).toBe(0); + const out = logSpy.mock.calls.map(call => String(call[0])).join("\n"); + const lines = out.split("\n"); + expect(lines.filter(line => line.startsWith("plan:"))).toEqual([`plan: ${plan}`]); + expect(out).not.toContain("raycast."); + if (aiDirPresent) { + expect(out).not.toContain("Reveal Providers Config"); + } else { + expect(lines).toContain('On macOS or Windows, open Raycast → Settings → AI → "Reveal Providers Config" once so the ai folder exists.'); + } + + logSpy.mockClear(); + expect(await handleClientIntegrationCommand(["status", "--client", "raycast", "--json"], runtime.deps)).toBe(0); + expect(logSpy.mock.calls).toHaveLength(1); + const jsonOut = String(logSpy.mock.calls[0]![0]); + expect(JSON.parse(jsonOut)).toEqual(payload); + expect(jsonOut).not.toContain("Reveal Providers Config"); + expect(runtime.requests).toEqual([ + { path: "/api/client-integrations/raycast", method: "GET", body: null }, + { path: "/api/client-integrations/raycast", method: "GET", body: null }, + ]); + } finally { + logSpy.mockRestore(); + } + }); + } + } + test("client integration toggles hit the exact management routes", async () => { const runtime = fakeRuntime(); expect(await handleClientIntegrationCommand(["enable", "--client", "hermes", "--json"], runtime.deps)).toBe(0); From f8c8f6dd15b1518f25a3b1cd7b15c9b6c8b24f62 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 20:29:56 +0900 Subject: [PATCH 068/116] docs: qualify Desktop model switching in translated guides [skip ci] --- .../src/content/docs/fr/guides/claude-code.md | 12 ++++++++++-- .../src/content/docs/ja/guides/claude-code.md | 15 ++++++++++++--- .../src/content/docs/ko/guides/claude-code.md | 14 +++++++++++--- .../src/content/docs/ru/guides/claude-code.md | 12 ++++++++++-- .../src/content/docs/tr/guides/claude-code.md | 16 +++++++++++++--- .../src/content/docs/zh-cn/guides/claude-code.md | 12 +++++++++--- 6 files changed, 65 insertions(+), 16 deletions(-) diff --git a/docs-site/src/content/docs/fr/guides/claude-code.md b/docs-site/src/content/docs/fr/guides/claude-code.md index 2ae3940254..e11e6a06d8 100644 --- a/docs-site/src/content/docs/fr/guides/claude-code.md +++ b/docs-site/src/content/docs/fr/guides/claude-code.md @@ -290,8 +290,16 @@ anciens alias hachés et les identifiants `claude-ocx---` des c toujours résolus. Si le sélecteur situé au bas de Claude Desktop ne modifie pas le modèle d'une conversation 3P déjà en cours, -utilisez `/model ` dans cette conversation. OpenCodex ne peut pas observer l'état du sélecteur ; il -achemine l’identifiant du modèle porté par chaque requête. Confirmez le résultat sous **Journaux → requestModel**. +vous pouvez essayer `/model `, mais ce contournement peut également échouer sur les versions de Desktop +concernées. Le [ticket #3782](https://github.com/lidge-jun/opencodex/issues/3782) rapporte que sous Windows, +avec Claude Desktop 1.46388.4, la conversation continue d'utiliser son modèle initial après des changements +via le sélecteur du bas comme via `/model`. Ce signalement ne permet pas d'établir quel composant du client +ou du routage est à l'origine de ce comportement. + +Vous pouvez aussi essayer de sélectionner le modèle par défaut souhaité dans le profil Claude Desktop +d'OpenCodex, de réappliquer ce profil et de démarrer une nouvelle conversation. Il s'agit d'une étape de +dépannage, sans garantie de résolution. OpenCodex ne peut pas observer l'état du sélecteur ; il achemine +l'identifiant du modèle porté par chaque requête. Vérifiez ce que le client envoie sous **Logs → requestedModel**. Les modèles dont la fenêtre de contexte de référence atteint 1M obtiennent une ligne supplémentaire `…[1m]` dans le sélecteur. Sa sélection indique à Claude Code la fenêtre complète de 1M pour ce modèle, tout en maintenant le compactage automatique ; le proxy retire diff --git a/docs-site/src/content/docs/ja/guides/claude-code.md b/docs-site/src/content/docs/ja/guides/claude-code.md index 384c3f50df..adc8703340 100644 --- a/docs-site/src/content/docs/ja/guides/claude-code.md +++ b/docs-site/src/content/docs/ja/guides/claude-code.md @@ -163,9 +163,18 @@ Claude Code 2.1.129 以降は `GET /v1/models?limit=1000` でゲートウェイ 提供します。両系列は継続してデコードできるため、どちらの形式でも `settings.json` に保存したモデルは 引き続き動作します。 -Claude Desktop のフッターピッカーで実行中の 3P 会話のモデルが切り替わらない場合は、その会話で -`/model ` を使用してください。OpenCodex はピッカーの状態を直接参照できず、各リクエストに -含まれるモデル ID をルーティングします。結果は **Logs → requestedModel** で確認できます。 +Claude Desktop のフッターピッカーで実行中の 3P 会話のモデルが切り替わらない場合は、 +`/model ` を試せますが、影響を受ける Desktop ビルドではこの回避策も失敗することがあります。 +[Issue #3782](https://github.com/lidge-jun/opencodex/issues/3782) では、Windows 上の +Claude Desktop 1.46388.4 で、フッターピッカーと `/model` のどちらで変更しても、会話が最初の +モデルを使い続けると報告されています。この報告だけでは、クライアントやルーティングのどの +コンポーネントがこの動作の原因なのかは確定できません。 + +OpenCodex の Claude Desktop プロファイルで希望するデフォルトモデルを選択し、プロファイルを +再適用して、新しい会話を開始することも試せます。これはトラブルシューティングの手順であり、 +解決を保証するものではありません。OpenCodex はピッカーの状態を参照できず、各リクエストに +含まれるモデル ID をルーティングします。クライアントが何を送信しているかは +**Logs → requestedModel** で確認してください。 **エイリアス構文ルール:** provider には `/` や `--` を含められず `native` と同じでもいけません。 `/` も `~` も含まない plain な model ID は v1 接頭辞 `claude-ocx-…` のままです。`/` または `~` を含む diff --git a/docs-site/src/content/docs/ko/guides/claude-code.md b/docs-site/src/content/docs/ko/guides/claude-code.md index 676800d1e6..90857854f0 100644 --- a/docs-site/src/content/docs/ko/guides/claude-code.md +++ b/docs-site/src/content/docs/ko/guides/claude-code.md @@ -199,9 +199,17 @@ Claude Code 2.1.129 이상은 `GET /v1/models?limit=1000`에서 게이트웨이 제공해요. 두 계열은 계속 디코딩할 수 있으므로 어느 형식이든 `settings.json`에 저장한 모델이 계속 작동해요. -Claude Desktop의 하단 선택기로 이미 실행 중인 3P 대화의 모델이 바뀌지 않는다면, 그 대화에서 -`/model `를 사용하세요. OpenCodex는 선택기 상태를 따로 볼 수 없고 각 요청에 실린 모델 ID를 -라우팅해요. 적용 결과는 **Logs → requestedModel**에서 확인할 수 있어요. +Claude Desktop의 하단 선택기로 이미 실행 중인 3P 대화의 모델이 바뀌지 않는다면, +`/model `를 시도할 수 있지만, 문제가 있는 Desktop 빌드에서는 이 우회 방법도 실패할 수 있어요. +[이슈 #3782](https://github.com/lidge-jun/opencodex/issues/3782)에는 Windows의 +Claude Desktop 1.46388.4에서 하단 선택기와 `/model`로 각각 변경해도 대화가 처음 모델을 계속 +사용한다는 보고가 있어요. 이 보고만으로는 클라이언트나 라우팅의 어느 구성 요소가 이 동작을 +일으키는지 확정할 수 없어요. + +OpenCodex의 Claude Desktop 프로필에서 원하는 기본 모델을 선택하고, 프로필을 다시 적용한 뒤 +새 대화를 시작하는 방법도 시도할 수 있어요. 이는 문제 해결을 위한 시도이며 해결을 보장하지는 +않아요. OpenCodex는 선택기 상태를 볼 수 없고 각 요청에 실린 모델 ID를 라우팅해요. +클라이언트가 실제로 무엇을 보내는지는 **Logs → requestedModel**에서 확인하세요. **별칭 문법 규칙:** provider에는 `/`나 `--`를 넣을 수 없고 `native`와 같아도 안 돼요. `/`와 `~`가 없는 plain model ID는 v1 접두사 `claude-ocx-…`를 유지해요. `/` 또는 `~`가 있는 model ID는 v2 diff --git a/docs-site/src/content/docs/ru/guides/claude-code.md b/docs-site/src/content/docs/ru/guides/claude-code.md index 60464bfb90..f5504c9dc2 100644 --- a/docs-site/src/content/docs/ru/guides/claude-code.md +++ b/docs-site/src/content/docs/ru/guides/claude-code.md @@ -176,8 +176,16 @@ user-agent `claude-code/*` получает читаемую CLI-форму, а продолжает работать. Если нижний селектор Claude Desktop не переключает модель в уже запущенном 3P-диалоге, -используйте `/model ` внутри этого диалога. OpenCodex не видит состояние селектора и -маршрутизирует id модели из каждого запроса. Результат можно проверить в **Logs → requestedModel**. +можно попробовать `/model `, но в затронутых сборках Desktop этот обходной способ тоже может +не сработать. В [issue #3782](https://github.com/lidge-jun/opencodex/issues/3782) сообщается, что +в Windows с Claude Desktop 1.46388.4 диалог продолжает использовать исходную модель после изменений +как через нижний селектор, так и через `/model`. Это сообщение не устанавливает, какой компонент +клиента или маршрутизации вызывает такое поведение. + +Можно также попробовать выбрать нужную модель по умолчанию в профиле Claude Desktop в OpenCodex, +повторно применить профиль и начать новый диалог. Это шаг по устранению неполадки, а не гарантированное +решение. OpenCodex не видит состояние селектора; он маршрутизирует id модели, переданный в каждом +запросе. Проверьте, что отправляет клиент, в **Logs → requestedModel**. **Правила грамматики алиасов:** provider не может содержать `/` или `--` и не может быть равен `native`. Обычные id моделей (без `/` и `~`) остаются с префиксом v1 `claude-ocx-…`. Id с `/` diff --git a/docs-site/src/content/docs/tr/guides/claude-code.md b/docs-site/src/content/docs/tr/guides/claude-code.md index 4be81a4de8..497f5e635b 100644 --- a/docs-site/src/content/docs/tr/guides/claude-code.md +++ b/docs-site/src/content/docs/tr/guides/claude-code.md @@ -332,9 +332,19 @@ takma adlar ve eski yapılandırmalardan gelen `claude-ocx---` kimlikleri hala çözümlenir. Claude Desktop'ın altbilgi seçicisi zaten çalışan bir 3P görüşmesi için modeli -değiştirmezse, o görüşmede `/model ` komutunu kullanın. OpenCodex seçici -durumunu gözlemleyemez; her isteğin taşıdığı model kimliğini yönlendirir. Sonucu -**Logs → requestedModel** altında onaylayın. +değiştirmezse, `/model ` komutunu deneyebilirsiniz; ancak bu geçici çözüm de +etkilenen Desktop derlemelerinde başarısız olabilir. +[Sorun #3782](https://github.com/lidge-jun/opencodex/issues/3782), Windows üzerinde +Claude Desktop 1.46388.4 ile hem altbilgi seçicisi hem de `/model` üzerinden yapılan +değişikliklerden sonra görüşmenin ilk modelini kullanmaya devam ettiğini bildiriyor. +Bu bildirim, davranışa hangi istemci veya yönlendirme bileşeninin neden olduğunu +ortaya koymuyor. + +OpenCodex Claude Desktop profilinde istediğiniz varsayılan modeli seçmeyi, profili +yeniden uygulamayı ve yeni bir görüşme başlatmayı da deneyebilirsiniz. Bu bir sorun +giderme adımıdır; kesin çözüm değildir. OpenCodex seçici durumunu gözlemleyemez; +her isteğin taşıdığı model kimliğini yönlendirir. İstemcinin ne gönderdiğini +**Logs → requestedModel** altında kontrol edin. Yetkili 1M bağlam penceresine sahip modeller fazladan bir `…[1m]` seçici satırı alır: bunu seçmek Claude Code'un bu model için tam 1M bağlam hesabı yapmasını diff --git a/docs-site/src/content/docs/zh-cn/guides/claude-code.md b/docs-site/src/content/docs/zh-cn/guides/claude-code.md index dd8bc740b8..216766f70c 100644 --- a/docs-site/src/content/docs/zh-cn/guides/claude-code.md +++ b/docs-site/src/content/docs/zh-cn/guides/claude-code.md @@ -157,9 +157,15 @@ opencodex 会将已路由模型公开为稳定且可逆的别名: user-agent 会获得易读的 CLI 形式,其他客户端会获得 Desktop 哈希形式。两种别名族都会永久 保持可解码——以任一形式保存在 `settings.json` 中的模型都能继续工作。 -如果 Claude Desktop 底部的选择器没有切换已运行 3P 对话的模型,请在该对话中使用 -`/model `。OpenCodex 无法读取选择器状态,只会路由每个请求实际携带的模型 ID;可在 -**Logs → requestedModel** 中确认结果。 +如果 Claude Desktop 底部的选择器没有切换正在进行的 3P 对话的模型,可以尝试 +`/model `,但在受影响的 Desktop 版本中,这种变通方法也可能失败。 +[Issue #3782](https://github.com/lidge-jun/opencodex/issues/3782) 报告称,在 Windows 上使用 +Claude Desktop 1.46388.4 时,无论通过底部选择器还是 `/model` 更改模型,对话都会继续使用 +最初的模型。该报告并未确定是哪个客户端组件或路由组件导致了这一行为。 + +也可以尝试在 OpenCodex 的 Claude Desktop 配置档案中选择所需的默认模型,重新应用配置档案, +然后开始新对话。这是一项排查步骤,不保证能解决问题。OpenCodex 无法读取选择器状态, +而是根据每个请求携带的模型 ID 进行路由。请在 **Logs → requestedModel** 中确认客户端实际发送的内容。 **别名语法规则:**provider 不得包含 `/` 或 `--`,也不得等于 `native`。 不含 `/` 或 `~` 的普通 model ID 继续使用 v1 前缀 `claude-ocx-…`。包含 `/` 或 `~` 的 model ID From 209c88b16fb13d495029d005855006eceb3d20b7 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 21:10:26 +0900 Subject: [PATCH 069/116] fix(models): isolate async price-read state callbacks [skip ci] Exact CI gates diagnosis: keep effect request setup synchronous and update state only from registered fetch settlement callbacks; retain cancellation and identity guards. Co-authored-by: nordz0r <6949669+nordz0r@users.noreply.github.com> --- gui/src/components/ModelPriceDialog.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/gui/src/components/ModelPriceDialog.tsx b/gui/src/components/ModelPriceDialog.tsx index f6e1a58200..59f385a841 100644 --- a/gui/src/components/ModelPriceDialog.tsx +++ b/gui/src/components/ModelPriceDialog.tsx @@ -58,12 +58,11 @@ export default function ModelPriceDialog({ model, apiBase, onRefresh, onClose }: const mutating = phase === "saving" || phase === "refreshing"; const locked = phase !== "ready"; - const readOverride = useCallback(async (recover = false) => { + const readOverride = useCallback((recover = false) => { if (requestRef.current) return; const bounded = createBoundedFetch(REQUEST_TIMEOUT_MS); requestRef.current = bounded; - try { - const response = await fetch(endpoint, { signal: bounded.signal, cache: "no-store" }); + void fetch(endpoint, { signal: bounded.signal, cache: "no-store" }).then(async response => { const result = await readJsonOrThrow(response); bounded.signal.throwIfAborted(); if (!isRecord(result) || result.provider !== model.provider || !isRecord(result.modelCosts)) { @@ -81,14 +80,14 @@ export default function ModelPriceDialog({ model, apiBase, onRefresh, onClose }: // request still running on the server or writes from another client. setRecovered(recover); setPhase("ready"); - } catch { + }).catch(() => { if (requestRef.current !== bounded) return; setPhase(recover ? "unknown" : "loadFailed"); setErrorKey(recover ? "pricing.override.recoveryFailed" : "pricing.override.loadFailed"); - } finally { + }).finally(() => { bounded.clear(); if (requestRef.current === bounded) requestRef.current = null; - } + }); }, [endpoint, model.id, model.provider]); useEffect(() => { From c4924740bd21add8357747da7f7c7f91baa119e1 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:54:08 +0900 Subject: [PATCH 070/116] feat(usage): add inclusive custom time windows [skip ci] Reimplement the range slice of #2956 with exact ledger filtering, bounded cache identity and localized datetime controls. Keep #3379 open for its other dashboard controls and hourly reporting scope; offline reports are not included. Co-authored-by: Manson2438 <183030642+Manson2438@users.noreply.github.com> --- .../_plan/260907_lane_d/050_usage_ranges.md | 19 ++ .../src/content/docs/reference/cli/agents.md | 9 +- .../content/docs/reference/management-api.md | 19 +- gui/src/i18n/de.ts | 10 + gui/src/i18n/en.ts | 10 + gui/src/i18n/fr.ts | 10 + gui/src/i18n/ja.ts | 10 + gui/src/i18n/ko.ts | 10 + gui/src/i18n/ru.ts | 10 + gui/src/i18n/tr.ts | 10 + gui/src/i18n/zh-TW.ts | 10 + gui/src/i18n/zh.ts | 10 + gui/src/pages/Usage.tsx | 114 +++++-- gui/src/usage-time-range.ts | 31 ++ gui/tests/usage-custom-range.test.tsx | 279 ++++++++++++++++++ gui/tests/usage-time-range.test.ts | 34 +++ scripts/test-layout/layout.json | 3 +- .../ocx/references/01_management_surface.md | 2 + src/cli/capabilities.ts | 2 + src/cli/observe.ts | 15 +- src/cli/usage-report.ts | 7 +- src/server/management/logs-usage-routes.ts | 14 +- .../management/usage-aggregate-cache.ts | 21 +- src/usage/summary.ts | 53 +++- src/usage/time-range.ts | 48 +++ structure/05_gui-and-management-api.md | 8 + tests/cli/cli-usage-report.test.ts | 58 ++++ tests/fixtures/test-layout-expected.json | 3 +- tests/server/api-usage.test.ts | 105 +++++++ tests/usage/usage-aggregate-cache.test.ts | 49 +++ tests/usage/usage-summary.test.ts | 96 ++++++ tests/usage/usage-time-range.test.ts | 36 +++ 32 files changed, 1072 insertions(+), 43 deletions(-) create mode 100644 gui/src/usage-time-range.ts create mode 100644 gui/tests/usage-custom-range.test.tsx create mode 100644 gui/tests/usage-time-range.test.ts create mode 100644 src/usage/time-range.ts create mode 100644 tests/usage/usage-time-range.test.ts diff --git a/devlog/_plan/260907_lane_d/050_usage_ranges.md b/devlog/_plan/260907_lane_d/050_usage_ranges.md index 35b6758a76..e08d758e5b 100644 --- a/devlog/_plan/260907_lane_d/050_usage_ranges.md +++ b/devlog/_plan/260907_lane_d/050_usage_ranges.md @@ -28,3 +28,22 @@ integer epoch milliseconds or full ISO-8601 with timezone only; require both bou reject negative/unsafe/date-invalid/reversed, never normalize overflow dates. MODIFY src/cli/usage-report.ts heading prints since/until for customWindow responses. GUI datetime values become epoch ms locally; end selected minute includes 59.999s. + +P revalidation: custom windows always filter rows before aggregation. Introduce exported +UsageTimeWindow {since:number,until:number} and immutable optional accumulator window; +snapshot timestamps update first, clone retains the window, summary returns customWindow:true +and exact since/until while actual generatedAt stays now. Partition/day filtering must not +drop the partial first day. Grid uses local calendar day boundaries and caps at 366 days. +getFilteredUsageAggregate accepts window, keys both bounds, passes window to factory and +reuses existing revision/timezone/overlay guards. Only-window queries preserve account rows. +GUI skips held/session report caching for custom windows (arbitrary keys must not grow the +preset cache); useDataSurface key still includes bounds and unsubscribed stores already evict. +Workers split backend/API/CLI/tests and GUI/i18n/tests; main owns docs/manifests/generated map. + +Implementation checkpoint: shared strict ISO/epoch-ms parser, immutable per-entry window, +window-keyed filtered cache, API and CLI inclusive bounds, exact interval heading, and +localized Usage date/time controls are implemented. Custom GUI reports bypass held caches; +calendar grid stays within the server's bounded days. Tests cover partial/inclusive bounds, +filters/accounts, cache invalidation, clone/snapshot behavior, empty/error responses and UI +apply/clear/stale-response paths. New parser test registered in both manifests. ISO fractions +beyond millisecond precision reject instead of truncating. Product execution NOT RUN locally. diff --git a/docs-site/src/content/docs/reference/cli/agents.md b/docs-site/src/content/docs/reference/cli/agents.md index 300bb7d5e2..4b95d1bcd2 100644 --- a/docs-site/src/content/docs/reference/cli/agents.md +++ b/docs-site/src/content/docs/reference/cli/agents.md @@ -111,14 +111,21 @@ Inspect proxy requests, usage, storage, memory, and debug data. The direct alias | Alias | Equivalent resource | | --- | --- | | `ocx logs [filters] [--follow] [--json|--jsonl]` | `ocx observe logs` | -| `ocx usage [--range ] [--surface ] [--provider ] [--model ] [--json]` | `ocx observe usage` | +| `ocx usage [--range ] [--since --until ] [--surface ] [--provider ] [--model ] [--json]` | `ocx observe usage` | | `ocx storage [--json]` | `ocx observe storage` | | `ocx memory [--json]` | `ocx observe memory` | ```bash ocx observe usage --range 30d --json +ocx usage --since 2026-09-01T09:00:00Z --until 2026-09-01T10:59:59.999Z --json ``` +`--since` and `--until` must be supplied together. They accept integer epoch milliseconds or +full ISO datetimes with an explicit timezone, include both endpoints, and override `--range`. +Invalid or reversed bounds fail before the request. Human output prints the requested interval; +`--json` includes `customWindow`, `since`, and `until`. Existing surface/provider/model filters +still apply. These commands query the running proxy; they do not provide offline reports. + `--range today` (alias `1d`) reports the current local day. `--provider` and `--model` narrow the report to one upstream target — distinct from `--surface`, which selects the calling client (Codex, Claude Code, Grok) diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index 0b3598eac8..238d23b336 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -182,7 +182,7 @@ by the current window size. | `GET /api/debug/usage-logs` | Read bounded usage-debug entries | — | | `GET /api/debug/injection-logs` | Read bounded guidance-injection debug entries | — | | `GET /api/claude/inbound-debug` | Read Claude inbound debug state and entries | — | -| `GET /api/usage` | Stream the complete usage ledger into compact aggregates, then incrementally fold verified appends; summarize by range and client surface, with a Codex `accounts` breakdown keyed by stable non-PII log labels | Returns an `error: "read_failed"` summary if storage cannot be read | +| `GET /api/usage` | Stream the complete usage ledger into compact aggregates, then incrementally fold verified appends; summarize by preset or inclusive custom window and client surface, with a Codex `accounts` breakdown keyed by stable non-PII log labels | 400 invalid custom bounds; returns an `error: "read_failed"` summary if storage cannot be read | | `GET /api/storage` | Scan Codex storage usage by bucket | Returns an `error: "scan_failed"` payload on scan failure | | `POST /api/storage/cleanup/preview` | Preview archived-session cleanup and return a binding digest | 400 `invalid_json` or `invalid_percent` | | `POST /api/storage/cleanup` | Quarantine or permanently remove the previewed archived set | 400 invalid input; 409 stale/busy/referenced state; 500 filesystem/database failure | @@ -210,6 +210,23 @@ an earlier file prefix from 7-day, 30-day, or all-history totals. `managementUsa accepted for compatibility with bounded legacy readers, but changing it no longer expands or reduces the history summarized by this endpoint. +Pass both `since` and `until` to select an inclusive custom interval. Each accepts integer Unix +epoch **milliseconds**, or a full ISO datetime with an explicit timezone. Invalid dates, negative +or out-of-range values, reversed bounds, and a single bound are rejected. Custom bounds override +`range`; the response keeps the preset `range` field for compatibility and adds `customWindow: true`, +the exact `since`, and `until`. `generatedAt` remains the time the report was produced. + +Custom windows filter individual ledger entries before daily aggregation, including partial first +and last days. They preserve `surface`, `provider`, `model`, and `apiKeyId` filtering and never reuse +or overwrite unfiltered preset summaries. The daily chart remains capped at 366 local calendar days; +totals cover the full requested interval. Snapshot-window fields describe the scanned ledger before +the time filter, so they can extend beyond the requested bounds. + +The Usage page accepts local date/time inputs. Its selected ending minute includes the entire +minute through `:59.999`. Choosing a preset or clearing the custom window restores preset behavior. +This adds exact range selection and existing cost estimates; it does not add hourly chart buckets +or offline reporting. + The runtime ledger is append-only. Replacing or truncating it, or changing local pricing/time-zone inputs, triggers a complete rebuild. If you manually edit an older row in place while the proxy is running, restart the proxy (or replace the file) before relying on the new total; incremental refreshes diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index a361962237..79d1591728 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -2615,4 +2615,14 @@ export const de: Record = { "pricing.override.refresh": "Liste aktualisieren", "pricing.override.cancel": "Abbrechen", "pricing.override.close": "Schließen", + "usage.range.custom": "Eigener Zeitraum", + "usage.range.start": "Beginn (Ortszeit)", + "usage.range.end": "Ende (Ortszeit)", + "usage.range.apply": "Anwenden", + "usage.range.clear": "Zurücksetzen", + "usage.range.help": "Ortszeit. Die gesamte Endminute ist enthalten.", + "usage.range.required": "Geben Sie Datum und Uhrzeit für Beginn und Ende ein.", + "usage.range.invalid": "Geben Sie gültige lokale Daten und Uhrzeiten ab 1970-01-01 UTC ein.", + "usage.range.reversed": "Das Ende muss auf oder nach dem Beginn liegen.", + "usage.range.applied": "Ausgewählter Zeitraum: {start} – {end} (beide Grenzen eingeschlossen).", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index ff45937f47..cceef53d12 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -2649,6 +2649,16 @@ export const en = { "pricing.override.refresh": "Refresh list", "pricing.override.cancel": "Cancel", "pricing.override.close": "Close", + "usage.range.custom": "Custom date range", + "usage.range.start": "Start (local time)", + "usage.range.end": "End (local time)", + "usage.range.apply": "Apply", + "usage.range.clear": "Clear", + "usage.range.help": "Local time. Includes the entire end minute.", + "usage.range.required": "Enter both a start and an end date and time.", + "usage.range.invalid": "Enter valid local dates and times, on or after 1970-01-01 UTC.", + "usage.range.reversed": "The end must be at or after the start.", + "usage.range.applied": "Selected interval: {start} – {end} (both inclusive).", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index eafe430758..67b2586fe4 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -2602,4 +2602,14 @@ export const fr: Record = { "pricing.override.refresh": "Actualiser la liste", "pricing.override.cancel": "Annuler", "pricing.override.close": "Fermer", + "usage.range.custom": "Période personnalisée", + "usage.range.start": "Début (heure locale)", + "usage.range.end": "Fin (heure locale)", + "usage.range.apply": "Appliquer", + "usage.range.clear": "Effacer", + "usage.range.help": "Heure locale. La dernière minute est entièrement incluse.", + "usage.range.required": "Saisissez la date et l’heure de début et de fin.", + "usage.range.invalid": "Saisissez des dates et heures locales valides à partir du 1970-01-01 UTC.", + "usage.range.reversed": "La fin doit être égale ou postérieure au début.", + "usage.range.applied": "Période sélectionnée : {start} – {end} (bornes incluses).", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 6fe289e48c..92bb516827 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -2636,4 +2636,14 @@ export const ja: Record = { "pricing.override.refresh": "一覧を更新", "pricing.override.cancel": "キャンセル", "pricing.override.close": "閉じる", + "usage.range.custom": "期間を指定", + "usage.range.start": "開始(現地時間)", + "usage.range.end": "終了(現地時間)", + "usage.range.apply": "適用", + "usage.range.clear": "解除", + "usage.range.help": "現地時間です。終了時刻の分全体を含みます。", + "usage.range.required": "開始と終了の日時を両方入力してください。", + "usage.range.invalid": "1970-01-01 UTC以降の有効な現地日時を入力してください。", + "usage.range.reversed": "終了日時は開始日時と同じか、それ以降にしてください。", + "usage.range.applied": "選択した期間:{start} – {end}(両端を含む)。", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 20160b7ffe..7f02d3792f 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -2637,4 +2637,14 @@ export const ko: Record = { "pricing.override.refresh": "목록 갱신", "pricing.override.cancel": "취소", "pricing.override.close": "닫기", + "usage.range.custom": "기간 직접 지정", + "usage.range.start": "시작 (현지 시간)", + "usage.range.end": "종료 (현지 시간)", + "usage.range.apply": "적용", + "usage.range.clear": "해제", + "usage.range.help": "현지 시간 기준이며, 종료 시각의 마지막 분 전체를 포함합니다.", + "usage.range.required": "시작과 종료 날짜 및 시간을 모두 입력하세요.", + "usage.range.invalid": "1970-01-01 UTC 이후의 유효한 현지 날짜와 시간을 입력하세요.", + "usage.range.reversed": "종료 시각은 시작 시각과 같거나 이후여야 합니다.", + "usage.range.applied": "선택한 기간: {start} – {end} (양 끝 시각 포함).", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index b433aa4381..9548be7d64 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -2638,4 +2638,14 @@ export const ru: Record = { "pricing.override.refresh": "Обновить список", "pricing.override.cancel": "Отмена", "pricing.override.close": "Закрыть", + "usage.range.custom": "Произвольный период", + "usage.range.start": "Начало (местное время)", + "usage.range.end": "Конец (местное время)", + "usage.range.apply": "Применить", + "usage.range.clear": "Сбросить", + "usage.range.help": "Местное время. Последняя минута включена целиком.", + "usage.range.required": "Введите дату и время начала и конца.", + "usage.range.invalid": "Введите допустимые местные дату и время не ранее 1970-01-01 UTC.", + "usage.range.reversed": "Конец не может быть раньше начала.", + "usage.range.applied": "Выбранный период: {start} – {end} (обе границы включены).", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index b86b867b22..7b835eb03e 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -2638,4 +2638,14 @@ export const tr: Record = { "pricing.override.refresh": "Listeyi yenile", "pricing.override.cancel": "İptal", "pricing.override.close": "Kapat", + "usage.range.custom": "Özel tarih aralığı", + "usage.range.start": "Başlangıç (yerel saat)", + "usage.range.end": "Bitiş (yerel saat)", + "usage.range.apply": "Uygula", + "usage.range.clear": "Temizle", + "usage.range.help": "Yerel saat. Bitiş dakikasının tamamı dahildir.", + "usage.range.required": "Başlangıç ve bitiş için tarih ve saat girin.", + "usage.range.invalid": "1970-01-01 UTC veya sonrasına ait geçerli yerel tarih ve saat girin.", + "usage.range.reversed": "Bitiş, başlangıçla aynı veya daha sonra olmalıdır.", + "usage.range.applied": "Seçilen aralık: {start} – {end} (iki sınır da dahil).", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 856c4c869c..cd0b7e17d3 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2600,4 +2600,14 @@ export const zhTW: Record = { "pricing.override.refresh": "重新整理清單", "pricing.override.cancel": "取消", "pricing.override.close": "關閉", + "usage.range.custom": "自訂時間範圍", + "usage.range.start": "開始(本地時間)", + "usage.range.end": "結束(本地時間)", + "usage.range.apply": "套用", + "usage.range.clear": "清除", + "usage.range.help": "使用本地時間,包含結束時刻的整分鐘。", + "usage.range.required": "請輸入開始和結束的日期及時間。", + "usage.range.invalid": "請輸入不早於 1970-01-01 UTC 的有效本地日期和時間。", + "usage.range.reversed": "結束時間必須等於或晚於開始時間。", + "usage.range.applied": "所選範圍:{start} – {end}(包含兩端)。", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 4e1fda0c2a..d9f93f20c7 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -2636,4 +2636,14 @@ export const zh: Record = { "pricing.override.refresh": "刷新列表", "pricing.override.cancel": "取消", "pricing.override.close": "关闭", + "usage.range.custom": "自定义时间范围", + "usage.range.start": "开始(本地时间)", + "usage.range.end": "结束(本地时间)", + "usage.range.apply": "应用", + "usage.range.clear": "清除", + "usage.range.help": "使用本地时间,包含结束时刻的整分钟。", + "usage.range.required": "请输入开始和结束的日期及时间。", + "usage.range.invalid": "请输入不早于 1970-01-01 UTC 的有效本地日期和时间。", + "usage.range.reversed": "结束时间必须等于或晚于开始时间。", + "usage.range.applied": "所选范围:{start} – {end}(包含两端)。", }; diff --git a/gui/src/pages/Usage.tsx b/gui/src/pages/Usage.tsx index bd7537073b..44ecce0c98 100644 --- a/gui/src/pages/Usage.tsx +++ b/gui/src/pages/Usage.tsx @@ -10,6 +10,7 @@ import { useDataSurface } from "../data-surface"; import { DataSurfaceSkeleton } from "../components/data-surface"; import { SectionTabs } from "../components/section-tabs"; import { sectionAnchorId } from "../section-anchors"; +import { parseUsageTimeRange, type UsageRangeError, type UsageTimeWindow } from "../usage-time-range"; type Range = "all" | "30d" | "7d"; type UsageSurface = "all" | "codex" | "claude" | "grok"; @@ -79,6 +80,8 @@ interface UsageResponse { range: Range; surface: UsageSurface; since: number | null; + until?: number; + customWindow?: boolean; generatedAt: number; summary: UsageSummaryTotals; days: UsageDay[]; @@ -156,16 +159,18 @@ interface HeatmapCell { dayOfWeek: number; } -function buildHeatmap(days: UsageDay[]): { weeks: HeatmapCell[][]; months: { label: string; col: number }[]; buckets: number[] } { +function buildHeatmap(days: UsageDay[], customWindow = false): { weeks: HeatmapCell[][]; months: { label: string; col: number }[]; buckets: number[] } { const buckets = quantileBuckets(days.map(d => d.totalTokens)); + if (customWindow && days.length === 0) return { weeks: [], months: [], buckets }; const dayMap = new Map(days.map(d => [d.date, d])); - const today = new Date(); + const today = customWindow ? new Date(`${days[days.length - 1].date}T00:00:00`) : new Date(); today.setHours(0, 0, 0, 0); - const start = new Date(today); - start.setDate(start.getDate() - 364); - // Align to Sunday - start.setDate(start.getDate() - start.getDay()); + const start = customWindow ? new Date(`${days[0].date}T00:00:00`) : new Date(today); + if (!customWindow) { + start.setDate(start.getDate() - 364); + start.setDate(start.getDate() - start.getDay()); + } const weeks: HeatmapCell[][] = []; const months: { label: string; col: number }[] = []; @@ -173,6 +178,12 @@ function buildHeatmap(days: UsageDay[]): { weeks: HeatmapCell[][]; months: { lab let lastMonthCol = -4; let prevMonthIdx = -1; let week: HeatmapCell[] = []; + // Align a custom grid without inventing report dates outside the server's bounded days. + if (customWindow) { + while (week.length < start.getDay()) { + week.push({ date: "", requests: 0, totalTokens: 0, level: 0, dayOfWeek: week.length }); + } + } const cursor = new Date(start); while (cursor <= today) { @@ -214,7 +225,7 @@ function UsageFilters({ t, }: { surface: UsageSurface; - range: Range; + range: Range | null; onSurface: (surface: UsageSurface) => void; onRange: (range: Range) => void; t: TFn; @@ -378,7 +389,7 @@ function UsageHeatmapPanel({ locale, t, }: { - range: Range; + range: Range | null; heatmap: ReturnType; weekBars: UsageDay[]; locale: Locale; @@ -671,7 +682,7 @@ function UsageWorkspaceBody({ modelQuery: string; onModelQuery: (query: string) => void; sortedProviders: UsageProvider[]; - range: Range; + range: Range | null; locale: Locale; t: TFn; }) { @@ -762,31 +773,52 @@ export default function Usage({ apiBase, connected = false, apiKeyId }: { apiBas const [surface, setSurface] = useState("all"); const [scope, setScope] = useState("machine"); const [modelQuery, setModelQuery] = useState(""); + const [draftWindow, setDraftWindow] = useState({ since: "", until: "" }); + const [customWindow, setCustomWindow] = useState(null); + const [rangeError, setRangeError] = useState(null); + const since = customWindow?.since; + const until = customWindow?.until; + + const clearCustomWindow = () => { + setCustomWindow(null); + setDraftWindow({ since: "", until: "" }); + setRangeError(null); + }; + const selectRange = (next: Range) => { + setRange(next); + clearCustomWindow(); + }; const loadUsage = useCallback(async (signal: AbortSignal): Promise => { const query = new URLSearchParams({ range, surface }); if (connected && scope === "machine" && apiKeyId) query.set("apiKeyId", apiKeyId); + if (since !== undefined && until !== undefined) { + query.set("since", String(since)); + query.set("until", String(until)); + } const response = await fetch(`${apiBase}/api/usage?${query}`, { signal }); if (!response.ok) throw new Error(`${response.status} ${response.statusText}`.trim()); const next = await response.json() as UsageResponse; - writeHeldUsage(apiBase, range, surface, connected, scope, apiKeyId, next); + if (since === undefined) writeHeldUsage(apiBase, range, surface, connected, scope, apiKeyId, next); return next; - }, [apiBase, apiKeyId, connected, range, scope, surface]); + }, [apiBase, apiKeyId, connected, range, scope, surface, since, until]); - const resourceKey = usageCacheKey(apiBase, range, surface, connected, scope, apiKeyId); - const cached = readHeldUsage(apiBase, range, surface, connected, scope, apiKeyId); + const presetKey = usageCacheKey(apiBase, range, surface, connected, scope, apiKeyId); + const resourceKey = customWindow ? `${presetKey}:custom:${since}:${until}` : presetKey; + // Arbitrary custom windows belong only to the subscription-scoped resource store. + const cached = customWindow ? null : readHeldUsage(apiBase, range, surface, connected, scope, apiKeyId); // Range and surface identify different reports, so the key changes with both. That prevents // a force-loading dependency revalidation from ever showing a previous report as this one. const resource = useDataSurface( resourceKey, - [apiBase, apiKeyId, connected, range, scope, surface], + [apiBase, apiKeyId, connected, range, scope, surface, since, until], loadUsage, { isEmpty: () => false, initialData: cached ?? undefined }, ); const { state } = resource; const data = state.data ?? cached ?? null; - const heatmap = useMemo(() => buildHeatmap(data?.days ?? []), [data?.days]); + const heatmap = useMemo(() => buildHeatmap(data?.days ?? [], !!customWindow), [data?.days, customWindow]); const weekBars = useMemo(() => lastSevenDays(data?.days ?? []), [data?.days]); const activeDays = useMemo(() => (data?.days ?? []).filter(d => d.requests > 0).length, [data?.days]); const filteredModels = useMemo(() => { @@ -810,9 +842,57 @@ export default function Usage({ apiBase, connected = false, apiKeyId }: { apiBas <>

{t("usage.title")}

- +

{t("usage.subtitle")}

+
{ + event.preventDefault(); + const result = parseUsageTimeRange(draftWindow.since, draftWindow.until); + if (result.ok === false) { + setRangeError(result.error); + return; + } + setRangeError(null); + setCustomWindow(result.window); + }}> +
+ + + + +
+

{t("usage.range.help")}

+ {rangeError && } + {customWindow &&

{(() => { + const formatter = new Intl.DateTimeFormat(locale, { + year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", + second: "2-digit", fractionalSecondDigits: 3, timeZoneName: "short", + }); + return t("usage.range.applied", { start: formatter.format(customWindow.since), end: formatter.format(customWindow.until) }); + })()}

} +
{/* Only shown when connected. Naming the source is a two-plane concept: it answers "which store served these numbers", and that question only exists once there are @@ -869,7 +949,7 @@ export default function Usage({ apiBase, connected = false, apiKeyId }: { apiBas modelQuery={modelQuery} onModelQuery={setModelQuery} sortedProviders={sortedProviders} - range={range} + range={customWindow ? null : range} locale={locale} t={t} /> diff --git a/gui/src/usage-time-range.ts b/gui/src/usage-time-range.ts new file mode 100644 index 0000000000..eebc445ad2 --- /dev/null +++ b/gui/src/usage-time-range.ts @@ -0,0 +1,31 @@ +export interface UsageTimeWindow { + since: number; + until: number; +} + +export type UsageRangeError = "required" | "invalid" | "reversed"; + +function localMinute(value: string): number | null { + const parts = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value); + if (!parts) return null; + const [year, month, day, hour, minute] = parts.slice(1).map(Number); + const date = new Date(`${value}:00`); + const timestamp = date.getTime(); + // Reject calendar overflow and nonexistent local times (including DST gaps). + if (!Number.isSafeInteger(timestamp) || timestamp < 0 + || date.getFullYear() !== year || date.getMonth() !== month - 1 + || date.getDate() !== day || date.getHours() !== hour || date.getMinutes() !== minute) return null; + return timestamp; +} + +export function parseUsageTimeRange(start: string, end: string): + | { ok: true; window: UsageTimeWindow } + | { ok: false; error: UsageRangeError } { + if (!start || !end) return { ok: false, error: "required" }; + const since = localMinute(start); + const endMinute = localMinute(end); + if (since === null || endMinute === null) return { ok: false, error: "invalid" }; + if (since > endMinute) return { ok: false, error: "reversed" }; + // Both bounds are inclusive: the selected end minute includes its final millisecond. + return { ok: true, window: { since, until: endMinute + 59_999 } }; +} diff --git a/gui/tests/usage-custom-range.test.tsx b/gui/tests/usage-custom-range.test.tsx new file mode 100644 index 0000000000..c06b27eb33 --- /dev/null +++ b/gui/tests/usage-custom-range.test.tsx @@ -0,0 +1,279 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import { LanguageProvider } from "../src/i18n/provider"; +import { clearClientResourceStoresForTests } from "../src/client-resource"; +import Usage from "../src/pages/Usage"; + +const globals = ["document", "window", "navigator", "localStorage", "sessionStorage", "ResizeObserver", "IS_REACT_ACT_ENVIRONMENT"] as const; +const originalFetch = globalThis.fetch; +let previousGlobals: Record<(typeof globals)[number], unknown>; +let testWindow: Window; +let root: Root | undefined; +let container: HTMLElement; +let apiBase: string; +let sequence = 0; +type RequestGate = { url: string; resolve: (response: Response) => void }; +let requests: RequestGate[]; + +beforeEach(() => { + previousGlobals = Object.fromEntries(globals.map(key => [key, Reflect.get(globalThis, key)])) as typeof previousGlobals; + clearClientResourceStoresForTests(); + testWindow = new Window({ url: "http://localhost/" }); + testWindow.localStorage.setItem("ocx-lang", "en"); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + sessionStorage: { configurable: true, value: testWindow.sessionStorage }, + ResizeObserver: { configurable: true, value: testWindow.ResizeObserver }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + // The page also has a held memory cache: each test gets a distinct report identity. + apiBase = `http://usage-custom-${++sequence}`; + requests = []; + globalThis.fetch = ((input: RequestInfo | URL) => new Promise(resolve => { + requests.push({ url: String(input), resolve }); + })) as typeof fetch; +}); + +afterEach(async () => { + if (root) await act(async () => { root!.unmount(); }); + root = undefined; + globalThis.fetch = originalFetch; + clearClientResourceStoresForTests(); + testWindow.close(); + for (const key of globals) Object.defineProperty(globalThis, key, { configurable: true, value: previousGlobals[key] }); +}); + +async function mount(connected = false) { + const previousRequests = requests.length; + container = document.createElement("div"); + document.body.append(container); + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(container); + root.render(); + }); + expect(requests).toHaveLength(previousRequests + 1); +} + +function report(gate: RequestGate, marker: string, date = "2020-09-15") { + const query = new URL(gate.url).searchParams; + const custom = query.has("since"); + return { + range: query.get("range"), surface: query.get("surface"), + since: custom ? Number(query.get("since")) : null, + ...(custom ? { customWindow: true, until: Number(query.get("until")) } : {}), + generatedAt: Date.now(), + summary: { + requests: 1, measuredRequests: 1, reportedRequests: 1, unreportedRequests: 0, + unsupportedRequests: 0, estimatedRequests: 0, inputTokens: 10, outputTokens: 20, + cachedInputTokens: 0, reasoningOutputTokens: 0, totalTokens: 30, coverageRatio: 1, + }, + days: [{ date, requests: 1, measuredRequests: 1, reportedRequests: 1, totalTokens: 30, models: [] }], + models: [{ model: marker, provider: "openai", requests: 1, measuredRequests: 1, reportedRequests: 1, + estimatedRequests: 0, totalTokens: 30, inputTokens: 10, outputTokens: 20, shareRatio: 1 }], + providers: [], historyTruncated: false, truncatedPrefixBytes: 0, entriesTruncated: false, entriesDropped: 0, + }; +} + +async function respond(index: number, marker: string, date?: string) { + await act(async () => { requests[index].resolve(Response.json(report(requests[index], marker, date))); }); +} + +const form = () => container.querySelector('form[aria-label="Custom date range"]')!; +const startInput = () => form().querySelectorAll('input[type="datetime-local"]')[0]; +const endInput = () => form().querySelectorAll('input[type="datetime-local"]')[1]; +const interval = () => form().querySelector('[role="status"]')?.textContent; +const error = () => form().querySelector('[role="alert"]')?.textContent; +const preset = (name: string) => container.querySelector(`button.usage-segmented-btn[aria-label="${name}"]`)!; + +async function click(button: HTMLButtonElement) { + expect(button).toBeTruthy(); + await act(async () => { button.click(); }); +} + +async function enter(start: string, end: string) { + await act(async () => { + for (const [input, value] of [[startInput(), start], [endInput(), end]] as const) { + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")!.set!.call(input, value); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + input.dispatchEvent(new testWindow.Event("change", { bubbles: true })); + } + }); +} + +const apply = () => click(form().querySelector('button[type="submit"]')!); +const clear = () => click(form().querySelector('button[type="button"]')!); +const since = new Date(2020, 8, 15, 10, 20, 0, 0).getTime(); +const until = new Date(2020, 8, 15, 10, 21, 59, 999).getTime(); +const boundsQuery = `since=${since}&until=${until}`; + +function sessionEntries() { + return Array.from({ length: sessionStorage.length }, (_, index) => { + const key = sessionStorage.key(index)!; + return [key, sessionStorage.getItem(key)]; + }); +} + +test("Apply submits inclusive bounds once; Clear restores the held preset without custom cache entries", async () => { + await mount(); + expect(requests[0].url).toBe(`${apiBase}/api/usage?range=30d&surface=all`); + await respond(0, "preset-report-marker"); + const held = sessionEntries(); + expect(held).toHaveLength(1); + await enter("2020-09-15T10:20", "2020-09-15T10:21"); + expect(requests).toHaveLength(1); + expect(container.textContent).toContain("preset-report-marker"); + await apply(); + expect(requests).toHaveLength(2); + expect(requests[1].url).toBe(`${apiBase}/api/usage?range=30d&surface=all&${boundsQuery}`); + for (const name of ["Available history", "30d", "7d"]) expect(preset(name).getAttribute("aria-pressed")).toBe("false"); + expect(container.textContent).not.toContain("preset-report-marker"); + expect(container.textContent).toContain("Loading usage data"); + expect(interval()).toContain("both inclusive"); + expect(interval()).toContain(".999"); + const appliedInterval = interval(); + await respond(1, "custom-report-marker"); + expect(container.textContent).toContain("custom-report-marker"); + expect(sessionEntries()).toEqual(held); + // Resource eviction is scheduled on a zero-delay timer. Drain that turn before Clear + // so this explicitly covers restoring a held preset after its resource store was evicted. + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); + // A one-day historical window must not produce a year grid anchored to today's date. + expect(container.querySelectorAll(".heatmap-grid .heatmap-cell")).toHaveLength(7); + const activeCell = container.querySelector(".heatmap-grid .heatmap-cell-1")!; + await act(async () => { activeCell.dispatchEvent(new testWindow.MouseEvent("mouseover", { bubbles: true })); }); + expect(container.querySelector('[role="tooltip"]')?.textContent).toContain("2020-09-15"); + await enter("2020-09-16T10:20", "2020-09-16T10:21"); + expect(interval()).toBe(appliedInterval); + expect(requests).toHaveLength(2); + await clear(); + expect(startInput().value).toBe(""); + expect(endInput().value).toBe(""); + expect(interval()).toBeUndefined(); + expect(preset("30d").getAttribute("aria-pressed")).toBe("true"); + expect(container.textContent).toContain("preset-report-marker"); + expect(container.textContent).not.toContain("custom-report-marker"); + expect(requests.at(-1)!.url).toBe(`${apiBase}/api/usage?range=30d&surface=all`); + await act(async () => { root!.unmount(); }); + root = undefined; + container.remove(); + clearClientResourceStoresForTests(); + await mount(); + expect(container.textContent).toContain("preset-report-marker"); + await enter("2020-09-15T10:20", "2020-09-15T10:21"); + await apply(); + // Reopening that exact custom window must not resurrect a module/session-held report. + expect(container.textContent).not.toContain("custom-report-marker"); + expect(container.textContent).not.toContain("preset-report-marker"); + expect(container.textContent).toContain("Loading usage data"); + expect(requests.at(-1)!.url).toBe(`${apiBase}/api/usage?range=30d&surface=all&${boundsQuery}`); +}); + +test("missing, partial, invalid and reversed drafts make no request or applied-state change", async () => { + await mount(); + await respond(0, "held-valid-report"); + for (const [start, end, expected] of [ + ["", "", "Enter both"], + ["2020-09-15T10:20", "", "Enter both"], + ["", "2020-09-15T10:20", "Enter both"], + ["1969-01-01T12:00", "2020-09-15T10:20", "Enter valid"], + ["2020-09-16T10:20", "2020-09-15T10:20", "The end must"], + ]) { + await enter(start, end); + await apply(); + expect(error()).toContain(expected); + expect(startInput().getAttribute("aria-invalid")).toBe("true"); + expect(requests).toHaveLength(1); + expect(container.textContent).toContain("held-valid-report"); + expect(interval()).toBeUndefined(); + } + await enter("2020-09-15T10:20", "2020-09-15T10:21"); + await apply(); + await respond(1, "applied-valid-report"); + const previousInterval = interval(); + await enter("2020-09-16T10:20", "2020-09-15T10:20"); + await apply(); + expect(requests).toHaveLength(2); + expect(interval()).toBe(previousInterval); + expect(container.textContent).toContain("applied-valid-report"); + await clear(); + expect(error()).toBeUndefined(); +}); + +test("new bounds never show a held report or a superseded request that settles late", async () => { + await mount(); + await respond(0, "preset-stale-marker"); + await enter("2020-09-15T10:20", "2020-09-15T10:21"); + await apply(); + await respond(1, "first-custom-marker"); + // Change only until, then only since: each bound independently owns a new request. + await enter("2020-09-15T10:20", "2020-09-15T10:22"); + await apply(); + expect(requests[2].url).toBe(`${apiBase}/api/usage?range=30d&surface=all&since=${since}&until=${until + 60_000}`); + expect(container.textContent).not.toContain("first-custom-marker"); + await enter("2020-09-15T10:21", "2020-09-15T10:22"); + await apply(); + expect(requests[3].url).toBe(`${apiBase}/api/usage?range=30d&surface=all&since=${since + 60_000}&until=${until + 60_000}`); + await respond(2, "late-superseded-marker"); + expect(container.textContent).not.toContain("late-superseded-marker"); + expect(container.textContent).not.toContain("preset-stale-marker"); + expect(container.textContent).toContain("Loading usage data"); + await respond(3, "latest-custom-marker"); + expect(container.textContent).toContain("latest-custom-marker"); + expect(sessionEntries()).toHaveLength(1); +}); + +test("Apply preserves machine key, surface and hub scope; choosing a preset clears custom", async () => { + await mount(true); + await respond(0, "machine-report"); + await click(preset("Grok")); + await respond(1, "machine-grok-report"); + await enter("2020-09-15T10:20", "2020-09-15T10:21"); + await apply(); + expect(requests[2].url).toBe(`${apiBase}/api/usage?range=30d&surface=grok&apiKeyId=machine%2Fkey+%2B+one&${boundsQuery}`); + await respond(2, "machine-custom-report"); + const hub = [...container.querySelectorAll(".usage-scope-control button")].find(button => button.textContent === "Hub-wide")!; + await click(hub); + expect(requests[3].url).toBe(`${apiBase}/api/usage?range=30d&surface=grok&${boundsQuery}`); + await respond(3, "hub-custom-report"); + await enter("2020-09-15T10:20", "2020-09-15T10:22"); + await apply(); + expect(requests[4].url).toBe(`${apiBase}/api/usage?range=30d&surface=grok&since=${since}&until=${until + 60_000}`); + await respond(4, "hub-new-custom-report"); + await click(preset("7d")); + expect(requests.at(-1)!.url).toBe(`${apiBase}/api/usage?range=7d&surface=grok`); + expect(interval()).toBeUndefined(); + expect(startInput().value).toBe(""); + expect(endInput().value).toBe(""); + expect(preset("7d").getAttribute("aria-pressed")).toBe("true"); + expect(hub.getAttribute("aria-pressed")).toBe("true"); +}); + +test("each preset clears custom, including the retained preset; 7d never replaces custom days with this week", async () => { + await mount(); + await respond(0, "preset-marker"); + for (const [index, name] of ["30d", "Available history", "7d"].entries()) { + await enter("2020-09-15T10:20", `2020-09-15T10:${21 + index}`); + const previousRequests = requests.length; + await apply(); + expect(requests).toHaveLength(previousRequests + 1); + await respond(requests.length - 1, "custom-marker"); + await click(preset(name)); + expect(preset(name).getAttribute("aria-pressed")).toBe("true"); + expect(interval()).toBeUndefined(); + expect(startInput().value).toBe(""); + expect(endInput().value).toBe(""); + } + await enter("2020-09-15T10:20", "2020-09-15T10:21"); + await apply(); + expect(requests.at(-1)!.url).toBe(`${apiBase}/api/usage?range=7d&surface=all&${boundsQuery}`); + await respond(requests.length - 1, "custom-from-7d-marker"); + expect(container.querySelector(".daybars")).toBeNull(); + expect(container.querySelectorAll(".heatmap-grid .heatmap-cell")).toHaveLength(7); + expect(preset("7d").getAttribute("aria-pressed")).toBe("false"); +}); diff --git a/gui/tests/usage-time-range.test.ts b/gui/tests/usage-time-range.test.ts new file mode 100644 index 0000000000..8ef289ef31 --- /dev/null +++ b/gui/tests/usage-time-range.test.ts @@ -0,0 +1,34 @@ +import { expect, test } from "bun:test"; +import { parseUsageTimeRange } from "../src/usage-time-range"; + +test("local minutes become inclusive epoch-ms bounds, including a single minute", () => { + expect(parseUsageTimeRange("2024-02-29T12:34", "2024-02-29T12:34")).toEqual({ + ok: true, + window: { + since: new Date(2024, 1, 29, 12, 34, 0, 0).getTime(), + until: new Date(2024, 1, 29, 12, 34, 59, 999).getTime(), + }, + }); +}); + +test("both local datetime bounds are required", () => { + for (const [start, end] of [["", ""], ["2024-02-29T12:34", ""], ["", "2024-02-29T12:34"]]) { + expect(parseUsageTimeRange(start, end)).toEqual({ ok: false, error: "required" }); + } +}); + +test("malformed, overflowing and negative dates are rejected rather than normalized", () => { + for (const invalid of [ + "not-a-date", "2023-02-29T12:34", "2024-02-30T12:34", "2024-13-01T12:34", + "2024-02-29T24:00", "2024-02-29T12:60", "1969-01-01T12:00", + "2024-02-29", "2024-02-29T12:34Z", "2024-02-29T12:34:30", "2024-02-29T12:34+09:00", + ]) { + expect(parseUsageTimeRange(invalid, "2024-03-01T12:34")).toEqual({ ok: false, error: "invalid" }); + expect(parseUsageTimeRange("2024-02-01T12:34", invalid)).toEqual({ ok: false, error: "invalid" }); + } +}); + +test("reversed dates are rejected before extending the end minute", () => { + expect(parseUsageTimeRange("2024-03-01T12:35", "2024-03-01T12:34")) + .toEqual({ ok: false, error: "reversed" }); +}); diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index ffb001a82d..d46f547867 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1300,7 +1300,8 @@ "zz-ci-storage-policy-isolation.test.ts": "ci-workflows", "zz-pr-coderabbit-readiness-revalidation.test.ts": "ci-workflows", "cli-models-price.test.ts": "cli", - "model-costs-management-api.test.ts": "server" + "model-costs-management-api.test.ts": "server", + "usage-time-range.test.ts": "usage" }, "migrated": [ "adapters", diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 485ed745ba..512aa3a7e2 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -132,6 +132,8 @@ Token and estimated-cost report over a time range. | Flag | Value | Meaning | |---|---|---| | `--range` | string | today | 1d | 7d | 30d | all | +| `--since` | string | Inclusive start: epoch milliseconds or full ISO datetime with timezone; requires --until and overrides --range. | +| `--until` | string | Inclusive end: epoch milliseconds or full ISO datetime with timezone; requires --since. | | `--provider` | string | Restrict to one provider. | | `--model` | string | Restrict to one model id. | | `--json` | boolean | Emit the usage report as JSON. | diff --git a/src/cli/capabilities.ts b/src/cli/capabilities.ts index e34b8ec79b..86aa5438df 100644 --- a/src/cli/capabilities.ts +++ b/src/cli/capabilities.ts @@ -225,6 +225,8 @@ export const CAPABILITIES: readonly Capability[] = [ routes: [{ method: "GET", path: "/api/usage" }], flags: [ { name: "--range", value: "string", summary: "today | 1d | 7d | 30d | all" }, + { name: "--since", value: "string", summary: "Inclusive start: epoch milliseconds or full ISO datetime with timezone; requires --until and overrides --range." }, + { name: "--until", value: "string", summary: "Inclusive end: epoch milliseconds or full ISO datetime with timezone; requires --since." }, { name: "--provider", value: "string", summary: "Restrict to one provider." }, { name: "--model", value: "string", summary: "Restrict to one model id." }, { name: "--json", value: "boolean", summary: "Emit the usage report as JSON." }, diff --git a/src/cli/observe.ts b/src/cli/observe.ts index 46e264d2a8..10a77254d0 100644 --- a/src/cli/observe.ts +++ b/src/cli/observe.ts @@ -12,6 +12,8 @@ import { } from "./runtime-api"; import { formatUsageReport } from "./usage-report"; import { USAGE_RANGES, USAGE_SURFACES } from "../usage/summary"; +import { parseUsageTimeWindow, type UsageTimeWindow } from "../usage/time-range"; +import { redactSecretString } from "../lib/redact"; const USAGE = `Usage: ocx observe logs [--provider ] [--model ] [--status ] @@ -20,6 +22,7 @@ const USAGE = `Usage: ocx logs rebuild-index ocx logs index-status ocx observe usage [--range ] [--surface ] + [--since ] [--until ] [--provider ] [--model ] [--json] ocx observe storage [codex-logs [status|protect|unprotect|repair|compact] [--mode ]] [--json] ocx observe memory [--json] @@ -146,6 +149,14 @@ async function usage(argv: string[], deps: RuntimeApiDeps): Promise { const surface = takeOption(args, "--surface") ?? "all"; const provider = takeOption(args, "--provider"); const model = takeOption(args, "--model"); + const since = takeOption(args, "--since"); + const until = takeOption(args, "--until"); + let window: UsageTimeWindow | undefined; + try { + window = parseUsageTimeWindow(since, until); + } catch (error) { + throw new CliUsageError(error instanceof Error ? error.message : "invalid usage time window", USAGE); + } // `1d` is accepted here as well as server-side so the CLI does not reject an // alias the API would have understood. const ranges = [...USAGE_RANGES, "1d"]; @@ -153,8 +164,8 @@ async function usage(argv: string[], deps: RuntimeApiDeps): Promise { if (!USAGE_SURFACES.includes(surface as (typeof USAGE_SURFACES)[number])) { throw new CliUsageError(`--surface must be one of ${USAGE_SURFACES.join(", ")}`, USAGE); } - rejectArgs(args, USAGE); - const result = await runtimeRequest(`/api/usage${query({ range, surface, provider, model })}`, {}, deps); + rejectArgs(args.map(redactSecretString), USAGE); + const result = await runtimeRequest(`/api/usage${query({ range, surface, provider, model, since: window?.since, until: window?.until })}`, {}, deps); // Built only when it will be printed: JavaScript evaluates arguments before // the call, so passing formatUsageReport(...) inline would run the human // renderer during --json and let its assumptions affect a path that is meant diff --git a/src/cli/usage-report.ts b/src/cli/usage-report.ts index e9f92f442d..6b684277c0 100644 --- a/src/cli/usage-report.ts +++ b/src/cli/usage-report.ts @@ -24,6 +24,8 @@ interface UsageReportInput { range?: string; surface?: string; since?: number | null; + until?: number; + customWindow?: boolean; summary?: { requests?: number; totalTokens?: number; @@ -90,7 +92,10 @@ function table(header: string[], rows: string[][]): string[] { } function describeScope(data: UsageReportInput): string { - const parts = [`Usage — ${data.range ?? "?"}`]; + const interval = data.customWindow && typeof data.since === "number" && typeof data.until === "number" + ? `custom ${new Date(data.since).toISOString()} to ${new Date(data.until).toISOString()} (inclusive)` + : data.range ?? "?"; + const parts = [`Usage — ${interval}`]; if (data.surface && data.surface !== "all") parts.push(`surface=${data.surface}`); if (data.filter?.provider) parts.push(`provider=${data.filter.provider}`); if (data.filter?.model) parts.push(`model=${data.filter.model}`); diff --git a/src/server/management/logs-usage-routes.ts b/src/server/management/logs-usage-routes.ts index ecbd6f655d..0177e56776 100644 --- a/src/server/management/logs-usage-routes.ts +++ b/src/server/management/logs-usage-routes.ts @@ -51,6 +51,7 @@ import { usageLogRevisionKey, } from "../../usage/log"; import { getUsageDebugLogEntries } from "../../usage/debug"; +import { parseUsageTimeWindow, type UsageTimeWindow } from "../../usage/time-range"; import { USAGE_RANGES, USAGE_SURFACES, parseRange, parseUsageSurface, rangeWindow, type UsageRange, type UsageSummary, type UsageSurface } from "../../usage/summary"; import { stripCodexRuntimeProviderFields } from "../../codex/auth-context"; import { getProviderRegistryEntry } from "../../providers/registry"; @@ -177,6 +178,12 @@ export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise typeof value === "string" && value.trim() !== ""); const now = Date.now(); try { @@ -211,7 +218,7 @@ export async function handleLogsUsageRoutes(ctx: ManagementContext): Promise { +}, window?: UsageTimeWindow): Promise { + const fixedWindow = window ? Object.freeze({ ...window }) : undefined; const normalizedFilter = { provider: normalizeFilterValue(filter.provider), model: normalizeFilterValue(filter.model), @@ -273,11 +275,13 @@ export async function getFilteredUsageAggregate(filter: { normalizedFilter.provider, normalizedFilter.model, normalizedFilter.apiKeyId, + fixedWindow?.since ?? null, + fixedWindow?.until ?? null, ]); const existing = filteredFlights.get(key); if (existing) return existing; - const flight = refreshFilteredAggregate(key, normalizedFilter); + const flight = refreshFilteredAggregate(key, normalizedFilter, fixedWindow); filteredFlights.set(key, flight); try { return await flight; @@ -316,12 +320,13 @@ function publishFilteredAggregate( async function rebuildFilteredAggregate( key: string, filter: NormalizedUsageFilter, + window?: UsageTimeWindow, ): Promise { let lastError: unknown; for (let attempt = 0; attempt < MAX_REBUILD_ATTEMPTS; attempt += 1) { const overlayVersion = userCostOverlayVersion(); const timeZone = currentTimeZone(); - const accumulator = createUsageSummaryAccumulator({ filter, mode: "row-unique" }); + const accumulator = createUsageSummaryAccumulator({ filter, mode: "row-unique", window }); try { const scan = await scanUsageLedgerCooperatively({ onEntry: entry => accumulator.add(entry) }); if (scan.oversizedRows > 0) throw new Error("usage ledger contains an oversized row"); @@ -345,6 +350,7 @@ async function appendFilteredAggregate( key: string, state: RetainedUsageAggregate, filter: NormalizedUsageFilter, + window?: UsageTimeWindow, ): Promise { pinnedAggregates.add(state); let rebuildAfterUnpin = false; @@ -384,28 +390,29 @@ async function appendFilteredAggregate( pinnedAggregates.delete(state); trimRetainedFilteredAggregates(); } - if (rebuildAfterUnpin) return rebuildFilteredAggregate(key, filter); + if (rebuildAfterUnpin) return rebuildFilteredAggregate(key, filter, window); throw new Error("filtered usage append did not settle"); } async function refreshFilteredAggregate( key: string, filter: NormalizedUsageFilter, + window?: UsageTimeWindow, ): Promise { const state = retainedFilteredAggregates.get(key); - if (!state) return rebuildFilteredAggregate(key, filter); + if (!state) return rebuildFilteredAggregate(key, filter, window); const observed = currentUsageLogRevision(); const overlayVersion = userCostOverlayVersion(); const timeZone = currentTimeZone(); if (requiresRebuild(state, observed, overlayVersion, timeZone)) { retainedFilteredAggregates.delete(key); - return rebuildFilteredAggregate(key, filter); + return rebuildFilteredAggregate(key, filter, window); } if (state.revisionKey === usageLogRevisionKey(observed)) { state.retainedAt = Date.now(); return resultFrom(state, "unchanged"); } - return appendFilteredAggregate(key, state, filter); + return appendFilteredAggregate(key, state, filter, window); } export function usageAggregateRetainedStats(): UsageAggregateRetainedStats { diff --git a/src/usage/summary.ts b/src/usage/summary.ts index 6390db38c1..d7e678ab4f 100644 --- a/src/usage/summary.ts +++ b/src/usage/summary.ts @@ -1,6 +1,7 @@ import { baseProviderLabel } from "../providers/label"; import { canonicalAntigravityUsageModel } from "../providers/antigravity-models"; import { usageDisplayTotalTokens } from "./totals"; +import type { UsageTimeWindow } from "./time-range"; import { isUnresolvedRequestedModel, usageModelPriceOptions } from "./model-identity"; import { isCodexUsageAccountLogLabel, type PersistedUsageEntry, type UsageStatus } from "./log"; import { type AttemptCostEstimate, type CostEstimate, estimateAttemptCost, estimateRequestCost, serviceTierContext, type ServiceTierContext } from "./cost"; @@ -145,6 +146,8 @@ export interface UsageSummary { range: UsageRange; surface: UsageSurface; since: number | null; + customWindow?: true; + until?: number; generatedAt: number; summary: UsageSummaryTotals; days: UsageDay[]; @@ -297,6 +300,17 @@ function dayCountForAllRange(oldest: number | null, now: number): number { return Math.min(MAX_USAGE_DAY_BUCKETS, Math.max(1, days)); } +function customWindowDates(window: UsageTimeWindow): string[] { + const start = startOfLocalDay(window.since); + const date = new Date(startOfLocalDay(window.until)); + const dates: string[] = []; + while (date.getTime() >= start && dates.length < MAX_USAGE_DAY_BUCKETS) { + dates.push(localDateKey(date.getTime())); + date.setDate(date.getDate() - 1); + } + return dates.reverse(); +} + function blankTotals(): UsageSummaryTotals { return { requests: 0, @@ -1015,6 +1029,7 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { private readonly requestIds: Map | null; private readonly filter: NormalizedUsageFilter | null; private readonly mode: UsageAccumulatorMode; + private readonly window: UsageTimeWindow | undefined; private nextRequestId = 0; private nextOrdinal = 0; private snapshotStart: number | null = null; @@ -1025,6 +1040,7 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { constructor(options?: { filter?: { provider?: string | null; model?: string | null; apiKeyId?: string | null }; mode?: UsageAccumulatorMode; + window?: UsageTimeWindow; }) { const provider = normalizeFilterValue(options?.filter?.provider); const model = normalizeFilterValue(options?.filter?.model); @@ -1033,6 +1049,7 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { ? null : { provider, model, apiKeyId }; this.mode = options?.mode ?? "exact"; + this.window = options?.window ? Object.freeze({ ...options.window }) : undefined; this.requestIds = this.mode === "exact" ? new Map() : null; } @@ -1048,6 +1065,7 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { const cloned = new StreamingUsageSummaryAccumulator({ ...(this.filter ? { filter: this.filter } : {}), mode: this.mode, + window: this.window, }); cloned.nextRequestId = this.nextRequestId; cloned.nextOrdinal = this.nextOrdinal; @@ -1276,6 +1294,8 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { ? sourceEntry.timestamp : Math.max(this.snapshotEnd, sourceEntry.timestamp); } + if (this.window && (!Number.isFinite(sourceEntry.timestamp) + || sourceEntry.timestamp < this.window.since || sourceEntry.timestamp > this.window.until)) return; const projected = this.filter ? projectedEntryForFilter(sourceEntry, this.filter) : { entry: sourceEntry, comboOverlap: false }; if (!projected) return; this.comboOverlap ||= projected.comboOverlap; @@ -1340,7 +1360,9 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { now: number, surface: UsageSurface = "all", ): UsageSummary & { filter?: UsageFilterEcho } { - const { since, days: fixedDays } = rangeWindow(range, now); + const preset = rangeWindow(range, now); + const since = this.window?.since ?? preset.since; + const fixedDays = preset.days; const totals = blankTotals(); const models = new Map(); const providers = new Map(); @@ -1351,7 +1373,7 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { for (const partition of this.partitions.values()) { if (!usageSurfaceMatches(partition.surface, surface)) continue; - if (since !== null && partition.dayStart < since) continue; + if (!this.window && since !== null && partition.dayStart < since) continue; mergeTotals(totals, partition.totals); mergeModelMaps(models, partition.models); if (partition.providers) mergeModelMaps(providers, partition.providers); @@ -1377,27 +1399,34 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { } finalizeCoverage(totals); - const dayCount = range === "all" ? dayCountForAllRange(oldestTimestamp, now) : fixedDays; - const startOfToday = startOfLocalDay(now); + const customDates = this.window ? new Set(customWindowDates(this.window)) : null; + const dayCount = customDates?.size ?? (range === "all" ? dayCountForAllRange(oldestTimestamp, now) : fixedDays); + const startOfToday = startOfLocalDay(this.window?.until ?? now); const firstVisibleDay = new Date(startOfToday); firstVisibleDay.setDate(firstVisibleDay.getDate() - dayCount + 1); const firstVisibleDate = localDateKey(firstVisibleDay.getTime()); const lastVisibleDate = localDateKey(startOfToday); - for (let offset = dayCount - 1; offset >= 0; offset--) { + const visibleDates = customDates ?? new Set(); + for (let offset = dayCount - 1; !customDates && offset >= 0; offset--) { const date = new Date(startOfToday); date.setDate(date.getDate() - offset); - const key = localDateKey(date.getTime()); + visibleDates.add(localDateKey(date.getTime())); + } + for (const key of visibleDates) { if (!dayAccumulators.has(key)) { dayAccumulators.set(key, { totals: blankTotals(), models: new Map(), modelOverlaps: [] }); } } - const days = [...dayAccumulators] + const visibleDays = customDates + ? [...customDates].map(date => [date, dayAccumulators.get(date)!] as const) + : [...dayAccumulators] // All-history totals, models, providers, and accounts still cover every // retained row. Only the chart buckets are bounded so one malformed or // ancient timestamp cannot synthesize an enormous JSON response. .filter(([date]) => range !== "all" || (date >= firstVisibleDate && date <= lastVisibleDate)) - .sort(([a], [b]) => a.localeCompare(b)) + .sort(([a], [b]) => a.localeCompare(b)); + const days = visibleDays .map(([date, day]): UsageDay => ({ date, requests: day.totals.requests, @@ -1412,6 +1441,7 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { range, surface, since, + ...(this.window ? { customWindow: true as const, until: this.window.until } : {}), generatedAt: now, summary: totals, days, @@ -1449,6 +1479,7 @@ class StreamingUsageSummaryAccumulator implements UsageSummaryAccumulator { export function createUsageSummaryAccumulator(options?: { filter?: { provider?: string | null; model?: string | null; apiKeyId?: string | null }; mode?: UsageAccumulatorMode; + window?: UsageTimeWindow; }): UsageSummaryAccumulator { return new StreamingUsageSummaryAccumulator(options); } @@ -1501,7 +1532,11 @@ export function projectUsageSummary( const model = normalizeFilterValue(filter.model); const apiKeyId = normalizeExactFilterValue(filter.apiKeyId); if (provider === null && model === null && apiKeyId === null) return summary; - const accumulator = createUsageSummaryAccumulator({ filter: { provider, model, apiKeyId } }); + const accumulator = createUsageSummaryAccumulator({ + filter: { provider, model, apiKeyId }, + ...(summary.customWindow && summary.since !== null && summary.until !== undefined + ? { window: { since: summary.since, until: summary.until } } : {}), + }); for (const entry of entries ?? []) accumulator.add(entry); const projected = accumulator.summarize(summary.range, summary.generatedAt, summary.surface); return { diff --git a/src/usage/time-range.ts b/src/usage/time-range.ts new file mode 100644 index 0000000000..01b1beec83 --- /dev/null +++ b/src/usage/time-range.ts @@ -0,0 +1,48 @@ +/** Inclusive epoch-millisecond bounds, independent of the selected preset. */ +export interface UsageTimeWindow { + readonly since: number; + readonly until: number; +} + +const MAX_DATE_MS = 8_640_000_000_000_000; +const ISO_DATETIME = /^(\d{4}|\+\d{6})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,3})?(Z|([+-])(\d{2}):(\d{2}))$/; + +function parseTimestamp(input: string | number, name: "since" | "until"): number { + const invalid = (): never => { + throw new Error(`${name} must be nonnegative integer epoch milliseconds or a valid full ISO datetime with timezone`); + }; + let timestamp: number; + if (typeof input === "number") timestamp = input; + else if (/^\d+$/.test(input)) timestamp = Number(input); + else { + const parts = ISO_DATETIME.exec(input); + if (!parts) return invalid(); + const year = Number(parts[1]); + const month = Number(parts[2]); + const day = Number(parts[3]); + const leapYear = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + const monthDays = [31, leapYear ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + // Date.parse normalizes some impossible dates (e.g. February 30). + // Validate the written calendar fields before applying its timezone offset. + if (month < 1 || month > 12 || day < 1 || day > monthDays[month - 1]! + || Number(parts[4]) > 23 || Number(parts[5]) > 59 || Number(parts[6]) > 59 + || (parts[7] !== "Z" && (Number(parts[9]) > 23 || Number(parts[10]) > 59))) { + return invalid(); + } + timestamp = Date.parse(input); + } + if (!Number.isSafeInteger(timestamp) || timestamp < 0 || timestamp > MAX_DATE_MS) return invalid(); + return timestamp; +} + +/** No bounds selects the preset; supplying either bound requires both. */ +export function parseUsageTimeWindow( + since: string | number | null | undefined, + until: string | number | null | undefined, +): UsageTimeWindow | undefined { + if (since == null && until == null) return undefined; + if (since == null || until == null) throw new Error("since and until must be supplied together"); + const window = { since: parseTimestamp(since, "since"), until: parseTimestamp(until, "until") }; + if (window.since > window.until) throw new Error("since must be less than or equal to until"); + return Object.freeze(window); +} diff --git a/structure/05_gui-and-management-api.md b/structure/05_gui-and-management-api.md index a151a34d42..4a697671a4 100644 --- a/structure/05_gui-and-management-api.md +++ b/structure/05_gui-and-management-api.md @@ -357,6 +357,14 @@ keeps the saved state and renders fixed `ocx sync` guidance without server/accou ## Usage accounting +Custom usage windows are immutable bounds on the streaming accumulator, applied to each +ledger entry before attribution and daily aggregation. The filtered aggregate cache includes +both inclusive millisecond bounds in its identity and retains the existing ledger revision, +overlay-version and timezone checks. Preset warming never consumes custom summaries. +The response retains its preset range discriminator for compatibility and explicitly marks +`customWindow`, `since`, and `until`; the chart uses the window's local calendar days with +the existing 366-day cap. GUI custom reports bypass the held preset/session cache. + Account quota discovery is capability-based. Cheap OAuth and provider-key lists include `quotaMode` (`probe`, `passive`, or `unsupported`) without contacting upstream quota APIs. `GET /api/oauth/accounts?provider=..."a=1` and diff --git a/tests/cli/cli-usage-report.test.ts b/tests/cli/cli-usage-report.test.ts index b20112ee12..d1fdd7b4b5 100644 --- a/tests/cli/cli-usage-report.test.ts +++ b/tests/cli/cli-usage-report.test.ts @@ -136,6 +136,64 @@ describe("formatUsageReport", () => { }); describe("ocx usage command", () => { + test("duplicate, inline and stray custom-bound arguments do not echo credential-shaped values", async () => { + const secret = "sk-" + "a".repeat(40); + const errors: string[] = []; + const errorSpy = spyOn(console, "error").mockImplementation((...args: unknown[]) => { errors.push(args.map(String).join(" ")); }); + try { + for (const extra of [["--since", secret], [`--since=${secret}`], [secret]]) { + const result = await run(["usage", "--since", "0", "--until", "1", ...extra], payload()); + expect(result.code).toBe(2); + expect(result.urls).toEqual([]); + } + expect(errors.join("\n")).not.toContain(secret); + expect(errors.join("\n")).toContain("Unexpected argument(s)"); + } finally { errorSpy.mockRestore(); } + }); + + test("normalizes custom ISO bounds and preserves the selected preset and filters", async () => { + const body = payload({ customWindow: true, since: 1709164800123, until: 1709164800123 }); + const { code, urls, out } = await run([ + "usage", "--range", "7d", "--surface", "codex", "--provider", "openai", "--model", "gpt-5.5", + "--since", "2024-02-29T09:00:00.123+09:00", "--until", "1709164800123", + ], body); + expect(code).toBe(0); + expect(urls).toHaveLength(1); + const query = new URL(urls[0]!).searchParams; + expect(Object.fromEntries(query)).toEqual({ + range: "7d", surface: "codex", provider: "openai", model: "gpt-5.5", + since: "1709164800123", until: "1709164800123", + }); + expect(out.split("\n")[0]).toContain("custom 2024-02-29T00:00:00.123Z to 2024-02-29T00:00:00.123Z (inclusive)"); + expect((await run(["usage", "--since", "0", "--until", "0", "--json"], body)).out) + .toBe(JSON.stringify(body, null, 2)); + }); + + test("rejects malformed or unpaired windows as usage errors without an API request", async () => { + const errors: string[] = []; + const errorSpy = spyOn(console, "error").mockImplementation((...args: unknown[]) => { + errors.push(args.map(String).join(" ")); + }); + try { + for (const args of [ + ["--since", "0"], ["--until", "0"], ["--since", "2", "--until", "1"], + ["--since", "-1", "--until", "0"], ["--since", "1.5", "--until", "2"], + ["--since", "0", "--until", "8640000000000001"], + ["--since", "0", "--until", "2026-02-30T00:00:00Z"], + ["--since", "0", "--until", "2026-09-01T00:00:00"], + ["--since", "0", "--until", "2026-09-01T00:00:00.0001Z"], + ]) { + const result = await run(["usage", ...args], payload()); + expect(result.code).toBe(2); + expect(result.urls).toEqual([]); + } + expect(errors.join("\n")).toContain("since and until must be supplied together"); + expect(errors.join("\n")).toContain("timezone"); + } finally { + errorSpy.mockRestore(); + } + }); + test("forwards range and provider to the API", async () => { const { code, urls } = await run(["usage", "--range", "today", "--provider", "xai"], payload()); expect(code).toBe(0); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 496d51ea31..05ce7e87ff 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1135,5 +1135,6 @@ "zz-ci-storage-policy-isolation.test.ts": "ci-workflows", "zz-pr-coderabbit-readiness-revalidation.test.ts": "ci-workflows", "cli-models-price.test.ts": "cli", - "model-costs-management-api.test.ts": "server" + "model-costs-management-api.test.ts": "server", + "usage-time-range.test.ts": "usage" } diff --git a/tests/server/api-usage.test.ts b/tests/server/api-usage.test.ts index a86836a0de..fa5c0ee2e2 100644 --- a/tests/server/api-usage.test.ts +++ b/tests/server/api-usage.test.ts @@ -109,6 +109,111 @@ afterEach(() => { }); describe("GET /api/usage", () => { + test("custom bounds override presets while preserving surface, filters and accounts", async () => { + const since = new Date(2026, 1, 10, 12).getTime(); + const until = since + 3_600_000; + const rows = [ + { timestamp: since - 1, apiKeyId: "Key-A" }, + { timestamp: since, apiKeyId: "Key-A" }, + { timestamp: until, apiKeyId: "key-a" }, + { timestamp: since + 1, apiKeyId: "Key-A", surface: "claude" }, + { timestamp: until + 1, apiKeyId: "Key-A" }, + ].map((row, index) => ({ + requestId: `custom-${index}`, provider: "openai", model: "gpt-5.5", accountLogLabel: "main", + status: 200, durationMs: 1, usageStatus: "reported", usage: { inputTokens: 10, outputTokens: 5 }, + totalTokens: 15, ...row, + })); + writeFileSync(join(testDir, "usage.jsonl"), rows.map(row => JSON.stringify(row)).join("\n") + "\n"); + const server = startServer(0); + try { + const preset = await (await fetch(new URL("/api/usage?range=all", server.url))).json(); + const params = new URLSearchParams({ range: "today", since: new Date(since).toISOString(), until: String(until), surface: "codex" }); + const before = Date.now(); + const response = await fetch(new URL(`/api/usage?${params}`, server.url)); + expect(response.status).toBe(200); + const custom = await response.json(); + expect(custom).toMatchObject({ range: "today", surface: "codex", customWindow: true, since, until }); + expect(custom.generatedAt).toBeGreaterThanOrEqual(before); + expect(custom.generatedAt).toBeLessThanOrEqual(Date.now()); + expect(custom.summary.requests).toBe(2); + expect(custom.days).toHaveLength(1); + expect(custom.days[0].requests).toBe(2); + expect(custom.accounts[0]).toMatchObject({ accountLogLabel: "main", requests: 2 }); + expect(custom.filter).toBeUndefined(); + expect(custom.snapshotWindowStart).toBe(since - 1); + expect(custom.snapshotWindowEnd).toBe(until + 1); + params.set("apiKeyId", "Key-A"); + const byKey = await (await fetch(new URL(`/api/usage?${params}`, server.url))).json(); + expect(byKey.summary.requests).toBe(1); + expect(byKey.accounts[0].requests).toBe(1); + expect(byKey.filter).toMatchObject({ apiKeyId: "Key-A", matched: true }); + params.set("provider", "OpenAI"); + params.set("model", "GPT-5.5"); + const combined = await (await fetch(new URL(`/api/usage?${params}`, server.url))).json(); + expect(combined.filter).toMatchObject({ provider: "openai", model: "gpt-5.5", apiKeyId: "Key-A", matched: true }); + expect(combined.summary.requests).toBe(1); + expect(combined.accounts).toEqual([]); + params.set("since", String(until)); + const noMatch = await (await fetch(new URL(`/api/usage?${params}`, server.url))).json(); + expect(noMatch.summary.requests).toBe(0); + expect(noMatch.filter.matched).toBe(false); + const after = await (await fetch(new URL("/api/usage?range=all", server.url))).json(); + expect(after.summary).toEqual(preset.summary); + expect(after.summary.requests).toBe(5); + expect(after.customWindow).toBeUndefined(); + expect(after.until).toBeUndefined(); + } finally { + await server.stop(true); + } + }); + + test("rejects invalid custom bounds with 400 before scanning", async () => { + const scanSpy = spyOn(usageLedgerScannerModule, "scanUsageLedgerCooperatively"); + const server = startServer(0); + try { + for (const query of [ + "since=0", "until=0", "since=&until=1", "since=2&until=1", "since=-1&until=1", + "since=0&until=8640000000000001", "since=0&until=9007199254740992", + "since=0&until=2026-02-30T12:00:00Z", "since=0&until=2026-09-01T12:00:00", + "since=0&until=2026-09-01T12:00:00.0001Z", + ]) { + const response = await fetch(new URL(`/api/usage?${query}`, server.url)); + expect(response.status).toBe(400); + expect((await response.json()).error).toBeTruthy(); + } + expect(scanSpy).not.toHaveBeenCalled(); + } finally { + scanSpy.mockRestore(); + await server.stop(true); + } + }); + + test("empty custom history and read failures retain the requested interval", async () => { + const server = startServer(0); + const url = new URL("/api/usage?range=today&since=0&until=0", server.url); + try { + const empty = await (await fetch(url)).json(); + expect(empty).toMatchObject({ customWindow: true, since: 0, until: 0, summary: { requests: 0 } }); + expect(empty.days).toHaveLength(1); + expect(empty.error).toBeUndefined(); + const scanSpy = spyOn(usageLedgerScannerModule, "scanUsageLedgerCooperatively") + .mockRejectedValue(new Error("fixture scan failure")); + try { + // A distinct key forces a fresh custom scan. + url.searchParams.set("until", "1"); + const response = await fetch(url); + expect(response.status).toBe(200); // existing Usage UI reads the error field + expect(await response.json()).toMatchObject({ + range: "today", customWindow: true, since: 0, until: 1, error: "read_failed", + }); + } finally { + scanSpy.mockRestore(); + } + } finally { + await server.stop(true); + } + }); + test("concurrent cold requests share one base-ledger scan", async () => { writeFixture(Date.now()); const originalScan = usageLedgerScannerModule.scanUsageLedgerCooperatively; diff --git a/tests/usage/usage-aggregate-cache.test.ts b/tests/usage/usage-aggregate-cache.test.ts index c739d0546d..3efb5615e4 100644 --- a/tests/usage/usage-aggregate-cache.test.ts +++ b/tests/usage/usage-aggregate-cache.test.ts @@ -72,6 +72,55 @@ afterEach(() => { }); describe("retained usage aggregate cache", () => { + test("custom cache keys isolate both endpoints and never poison preset aggregates", async () => { + const path = join(testDir, "usage.jsonl"); + const rows = [NOW - 2_000, NOW - 1_000, NOW].map((timestamp, index) => ({ ...entry(String(index)), timestamp })); + writeFileSync(path, rows.map(row => JSON.stringify(row)).join("\n") + "\n"); + const base = await getUsageAggregate(); + const firstWindow = { since: NOW - 2_000, until: NOW - 1_000 }; + const first = await getFilteredUsageAggregate({}, firstWindow); + const same = await getFilteredUsageAggregate({}, { ...firstWindow }); + const differentStart = await getFilteredUsageAggregate({}, { since: NOW - 1_000, until: NOW - 1_000 }); + const differentEnd = await getFilteredUsageAggregate({}, { since: NOW - 2_000, until: NOW }); + expect(same.accumulator).toBe(first.accumulator); + expect(same.update).toBe("unchanged"); + expect(requests(first)).toBe(2); + expect(requests(differentStart)).toBe(1); + expect(requests(differentEnd)).toBe(3); + expect((await getUsageAggregate()).accumulator).toBe(base.accumulator); + expect(requests(base)).toBe(3); + expect(base.accumulator.summarize("all", NOW).customWindow).toBeUndefined(); + for (let index = 1; index <= 7; index++) { + await getFilteredUsageAggregate({}, { since: NOW, until: NOW + index }); + } + expect(usageAggregateRetainedStats().count).toBe(5); // base plus four filtered windows + }); + + test("custom incremental clones filter appended rows and rebuild with changed prices", async () => { + const path = join(testDir, "usage.jsonl"); + const window = { since: NOW - 1_000, until: NOW }; + writeFileSync(path, line("one")); + const original = await getFilteredUsageAggregate({}, window); + appendFileSync(path, [ + { ...entry("inside"), timestamp: NOW }, + { ...entry("outside"), timestamp: NOW + 1 }, + ].map(row => JSON.stringify(row)).join("\n") + "\n"); + const appended = await getFilteredUsageAggregate({}, window); + expect(appended.update).toBe("append"); + expect(requests(original)).toBe(1); + expect(requests(appended)).toBe(2); + expect(appended.accumulator.snapshotWindow.end).toBe(NOW + 1); + refreshUserCostOverlays({ providers: { openai: { modelCosts: { + "gpt-5.5": { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 0.2 }, + } } } } as unknown as OcxConfig); + const rebuilt = await getFilteredUsageAggregate({}, window); + expect(rebuilt.update).toBe("rebuild"); + expect(rebuilt.accumulator.summarize("today", NOW)).toMatchObject({ + customWindow: true, ...window, summary: { requests: 2 }, + }); + expect(rebuilt.accumulator.summarize("all", NOW).summary.estimatedCostUsd).toBeCloseTo(0.000006, 10); + }); + test("append and rebuild preserve unresolved attribution and restricted pricing without ledger changes", async () => { const path = join(testDir, "usage.jsonl"); writeFileSync(path, line("ordinary")); diff --git a/tests/usage/usage-summary.test.ts b/tests/usage/usage-summary.test.ts index 6e26fb2e66..36d83c779f 100644 --- a/tests/usage/usage-summary.test.ts +++ b/tests/usage/usage-summary.test.ts @@ -16,6 +16,102 @@ import { isUnresolvedRequestedModel } from "../../src/usage/model-identity"; const FIXED_NOW = Date.UTC(2026, 5, 28, 12, 0, 0); +describe("custom usage windows", () => { + const since = new Date(2026, 1, 10, 12, 0, 0, 123).getTime(); + const until = since + 3_600_000; + + test("includes both intraday endpoints before attribution and retains whole-log snapshot", () => { + for (const mode of ["exact", "row-unique"] as const) { + const accumulator = createUsageSummaryAccumulator({ mode, window: { since, until } }); + for (const ts of [since - 1, since, until, until + 1]) { + accumulator.add(entry({ ts, usageStatus: "reported", usage: { inputTokens: 10, outputTokens: 5 }, accountLogLabel: "main" })); + } + const result = accumulator.summarize("today", FIXED_NOW, "codex"); + expect(result).toMatchObject({ range: "today", customWindow: true, since, until, generatedAt: FIXED_NOW }); + expect(result.summary).toMatchObject({ requests: 2, inputTokens: 20, outputTokens: 10 }); + expect(result.days).toHaveLength(1); + expect(result.days[0]).toMatchObject({ date: "2026-02-10", requests: 2 }); + expect(result.accounts[0]).toMatchObject({ accountLogLabel: "main", requests: 2 }); + expect(result.filter).toBeUndefined(); + expect(accumulator.snapshotWindow).toEqual({ start: since - 1, end: until + 1 }); + } + }); + + test("same-instant windows survive caller mutation and independent incremental clones", () => { + const window = { since, until: since }; + const accumulator = createUsageSummaryAccumulator({ window, mode: "row-unique" }); + window.since = 0; + window.until = FIXED_NOW; + accumulator.add(entry({ ts: since })); + const clone = accumulator.clone(); + clone.add(entry({ ts: since, requestId: "second" })); + clone.add(entry({ ts: since + 1 })); + expect(accumulator.summarize("all", FIXED_NOW).summary.requests).toBe(1); + expect(clone.summarize("7d", FIXED_NOW)).toMatchObject({ + customWindow: true, since, until: since, summary: { requests: 2 }, + }); + expect(accumulator.snapshotWindow.end).toBe(since); + expect(clone.snapshotWindow.end).toBe(since + 1); + }); + + test("empty grids use exact local calendar days across DST and include endpoint midnight", () => { + for (const [year, month, day, expected] of [ + [2026, 2, 7, ["2026-03-07", "2026-03-08", "2026-03-09"]], + [2026, 9, 31, ["2026-10-31", "2026-11-01", "2026-11-02"]], + ] as const) { + const window = { + since: new Date(year, month, day, 23, 59).getTime(), + until: new Date(year, month, day + 2, 0, 0).getTime(), + }; + const accumulator = createUsageSummaryAccumulator({ window }); + const result = accumulator.summarize("30d", FIXED_NOW); + expect(result.days.map(row => row.date)).toEqual([...expected]); + expect(result.days.every(row => row.requests === 0)).toBe(true); + expect(result.summary.requests).toBe(0); + expect(result.since).toBe(window.since); + expect(result.until).toBe(window.until); + expect(accumulator.snapshotWindow).toEqual({ start: null, end: null }); + } + }); + + test("caps only the chart at 366 calendar days ending at until", () => { + const window = { since: new Date(2020, 0, 1, 12).getTime(), until: new Date(2026, 0, 1, 12).getTime() }; + const accumulator = createUsageSummaryAccumulator({ window }); + accumulator.add(entry({ ts: window.since })); + accumulator.add(entry({ ts: window.until })); + const result = accumulator.summarize("today", FIXED_NOW); + expect(result.summary.requests).toBe(2); + expect(result.days).toHaveLength(366); + expect(result.days[0]?.date).toBe("2025-01-01"); + expect(result.days.at(-1)?.date).toBe("2026-01-01"); + expect(result.days.reduce((sum, row) => sum + row.requests, 0)).toBe(1); + }); + + test("custom calendar order remains chronological across expanded ISO years", () => { + const accumulator = createUsageSummaryAccumulator({ window: { + since: new Date(9999, 11, 31, 12).getTime(), until: new Date(10000, 0, 1, 12).getTime(), + } }); + expect(accumulator.summarize("all", FIXED_NOW).days.map(day => day.date)) + .toEqual(["9999-12-31", "10000-01-01"]); + }); + + test("window filtering preserves preset cost attribution for the same retained rows", () => { + const rows = [since - 1, since, until, until + 1].map(ts => entry({ + ts, provider: "anthropic", model: "claude-3-haiku-20240307", usageStatus: "reported", + usage: { inputTokens: 100, outputTokens: 50 }, + })); + const accumulator = createUsageSummaryAccumulator({ window: { since, until }, mode: "row-unique" }); + rows.forEach(row => accumulator.add(row)); + const result = accumulator.summarize("today", FIXED_NOW); + const baseline = summarizeUsage(rows.slice(1, 3), "all", until); + expect(result.summary.estimatedCostUsd).toBeGreaterThan(0); + expect(result.summary).toEqual(baseline.summary); + expect(result.models).toEqual(baseline.models); + expect(result.providers).toEqual(baseline.providers); + expect(result.days[0]?.estimatedCostUsd).toBeCloseTo(result.summary.estimatedCostUsd, 10); + }); +}); + function entry(overrides: Partial & { ts: number }): PersistedUsageEntry { const { ts, ...rest } = overrides; return { diff --git a/tests/usage/usage-time-range.test.ts b/tests/usage/usage-time-range.test.ts new file mode 100644 index 0000000000..3a36def2bc --- /dev/null +++ b/tests/usage/usage-time-range.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, test } from "bun:test"; +import { parseUsageTimeWindow } from "../../src/usage/time-range"; + +describe("usage time window parsing", () => { + test("accepts epoch milliseconds and normalizes explicit ISO offsets", () => { + expect(parseUsageTimeWindow(undefined, null)).toBeUndefined(); + expect(parseUsageTimeWindow("0", 0)).toEqual({ since: 0, until: 0 }); + expect(parseUsageTimeWindow("1970-01-01T00:00:00.1Z", "1970-01-01T00:00:00.12Z")) + .toEqual({ since: 100, until: 120 }); + expect(parseUsageTimeWindow("2024-02-29T09:00:00.123+09:00", "2024-02-28T19:00:00.123-05:00")) + .toEqual({ since: 1709164800123, until: 1709164800123 }); + expect(parseUsageTimeWindow("1970-01-01T00:00:00Z", "8640000000000000")) + .toEqual({ since: 0, until: 8_640_000_000_000_000 }); + expect(parseUsageTimeWindow("+275760-09-13T00:00:00Z", 8_640_000_000_000_000)?.since) + .toBe(8_640_000_000_000_000); + }); + + test("rejects absent peers, reversed bounds and non-integer or invalid dates", () => { + for (const [since, until] of [[0, undefined], [null, 0], [2, 1]] as const) { + expect(() => parseUsageTimeWindow(since, until)).toThrow(); + } + for (const value of [ + "", " ", " 0", "1.5", "1e3", "0x10", "-1", -1, 0.5, NaN, Infinity, + "9007199254740992", "8640000000000001", "2026-09-01", "2026-09-01T12:00:00", + "2026-09-01T12:00Z", "2026-02-29T00:00:00Z", "2024-02-30T00:00:00Z", + "2100-02-29T00:00:00Z", "2026-04-31T00:00:00+09:00", "2026-13-01T00:00:00Z", + "2026-01-00T00:00:00Z", "2026-01-01T24:00:00Z", "2026-01-01T00:60:00Z", + "2026-01-01T00:00:60Z", "2026-01-01T00:00:00+24:00", "2026-01-01T00:00:00+01:60", + "1970-01-01T00:00:00+00:01", "+275760-09-13T00:00:00.001Z", + "2026-09-01T00:00:00.0001Z", + ]) { + expect(() => parseUsageTimeWindow(value, 8_640_000_000_000_000)).toThrow(); + expect(() => parseUsageTimeWindow(0, value)).toThrow(); + } + }); +}); From 089320e88cd32056ab491706cb37faedb4cedd24 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 18:57:31 +0900 Subject: [PATCH 071/116] docs: define lane D verification and handoff [skip ci] --- devlog/_plan/260907_lane_d/060_delivery.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 devlog/_plan/260907_lane_d/060_delivery.md diff --git a/devlog/_plan/260907_lane_d/060_delivery.md b/devlog/_plan/260907_lane_d/060_delivery.md new file mode 100644 index 0000000000..2009ba9bb9 --- /dev/null +++ b/devlog/_plan/260907_lane_d/060_delivery.md @@ -0,0 +1,18 @@ +# 060 Remote verification and delivery + +Consume D5's implementation checkpoint. Resolve remaining independent review feedback on +its owning layer, cascade all dependent refs, and preserve contributor trailers. Detailed +unpublished security-review notes stay in scratch. Reconcile A's added reasoning-envelope +budget arguments with D1 ordering when A reaches dev; preserve both changes. + +Fetch fresh dev before final dispatch. Run only the top branch's ci.yml workflow with +lane=all; require successful actual platform jobs including Windows on the exact head. +Download its dashboard-preview artifact and verify build-commit/build-gui-tree markers. +Capture the changed dialogs and custom Usage range with synthetic data through the existing +browser capability; publish proof images separately so evidence does not change tested code. + +Create D2-D5 PRs with the required template, screenshot, manual chain table and native +stack:null proof. Attach independent implementation/security verdicts and top CI URL to +each PR. Leave all merges and original issue/PR closure actions to the main task. +Local product tests/typecheck/build/install remain NOT RUN. D closes only when exact-head +remote evidence and the requested handoff table are complete. From e346d7ae03433bf1d642e9ff0172dbd0edcffca0 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:01:33 +0900 Subject: [PATCH 072/116] fix(usage): preserve dates across timezone calendar gaps [skip ci] Use server civil dates for custom heatmaps and guarantee backward progress when a local day is skipped. Add Santiago and Apia timezone regressions. Co-authored-by: Manson2438 <183030642+Manson2438@users.noreply.github.com> --- devlog/_plan/260907_lane_d/060_delivery.md | 6 +++ gui/src/pages/Usage.tsx | 54 ++++++++++++++++------ gui/tests/usage-custom-range.test.tsx | 27 +++++++++++ src/usage/summary.ts | 8 ++++ tests/usage/usage-summary.test.ts | 20 ++++++++ 5 files changed, 101 insertions(+), 14 deletions(-) diff --git a/devlog/_plan/260907_lane_d/060_delivery.md b/devlog/_plan/260907_lane_d/060_delivery.md index 2009ba9bb9..38bcb1c80a 100644 --- a/devlog/_plan/260907_lane_d/060_delivery.md +++ b/devlog/_plan/260907_lane_d/060_delivery.md @@ -16,3 +16,9 @@ stack:null proof. Attach independent implementation/security verdicts and top CI each PR. Leave all merges and original issue/PR closure actions to the main task. Local product tests/typecheck/build/install remain NOT RUN. D closes only when exact-head remote evidence and the requested handoff table are complete. + +Calendar audit fold-back: custom heatmaps iterate the server's returned civil dates, +using UTC only for weekday/month layout; they do not step a local midnight cursor. +The server's backward calendar walk resets midnight after decrement and explicitly +advances to the prior existing local day if a whole-day timezone jump prevented progress. +Regressions pin America/Santiago (2026-09-05..07) and Pacific/Apia (2011-12-29..31). diff --git a/gui/src/pages/Usage.tsx b/gui/src/pages/Usage.tsx index 44ecce0c98..36b0d4ba82 100644 --- a/gui/src/pages/Usage.tsx +++ b/gui/src/pages/Usage.tsx @@ -161,29 +161,55 @@ interface HeatmapCell { function buildHeatmap(days: UsageDay[], customWindow = false): { weeks: HeatmapCell[][]; months: { label: string; col: number }[]; buckets: number[] } { const buckets = quantileBuckets(days.map(d => d.totalTokens)); - if (customWindow && days.length === 0) return { weeks: [], months: [], buckets }; + const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + if (customWindow) { + const weeks: HeatmapCell[][] = []; + const months: { label: string; col: number }[] = []; + let week: HeatmapCell[] = []; + let weekStart: number | undefined; + let previousMonth = -1; + let lastMonthCol = -4; + const pad = (length: number) => { + while (week.length < length) week.push({ date: "", requests: 0, totalTokens: 0, level: 0, dayOfWeek: week.length }); + }; + // The server already supplied the bounded civil dates. Local midnight stepping + // can retain a shifted hour across DST and omit the final day of the report. + for (const day of days) { + const [year, month, date] = day.date.split("-").map(Number); + const calendar = new Date(Date.UTC(year, month - 1, date)); + const weekday = calendar.getUTCDay(); + const nextWeekStart = calendar.getTime() - weekday * 86_400_000; + if (weekStart !== nextWeekStart) { + if (week.length > 0) { pad(7); weeks.push(week); } + week = []; + weekStart = nextWeekStart; + } + const monthIndex = calendar.getUTCMonth(); + if (monthIndex !== previousMonth && weeks.length - lastMonthCol >= 4) { + months.push({ label: monthNames[monthIndex], col: weeks.length }); + previousMonth = monthIndex; + lastMonthCol = weeks.length; + } + pad(weekday); + week.push({ date: day.date, requests: day.requests, totalTokens: day.totalTokens, + level: bucketLevel(day.totalTokens, buckets), dayOfWeek: weekday }); + } + if (week.length > 0) { pad(7); weeks.push(week); } + return { weeks, months, buckets }; + } const dayMap = new Map(days.map(d => [d.date, d])); - const today = customWindow ? new Date(`${days[days.length - 1].date}T00:00:00`) : new Date(); + const today = new Date(); today.setHours(0, 0, 0, 0); - const start = customWindow ? new Date(`${days[0].date}T00:00:00`) : new Date(today); - if (!customWindow) { - start.setDate(start.getDate() - 364); - start.setDate(start.getDate() - start.getDay()); - } + const start = new Date(today); + start.setDate(start.getDate() - 364); + start.setDate(start.getDate() - start.getDay()); const weeks: HeatmapCell[][] = []; const months: { label: string; col: number }[] = []; - const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; let lastMonthCol = -4; let prevMonthIdx = -1; let week: HeatmapCell[] = []; - // Align a custom grid without inventing report dates outside the server's bounded days. - if (customWindow) { - while (week.length < start.getDay()) { - week.push({ date: "", requests: 0, totalTokens: 0, level: 0, dayOfWeek: week.length }); - } - } const cursor = new Date(start); while (cursor <= today) { diff --git a/gui/tests/usage-custom-range.test.tsx b/gui/tests/usage-custom-range.test.tsx index c06b27eb33..db441dbb83 100644 --- a/gui/tests/usage-custom-range.test.tsx +++ b/gui/tests/usage-custom-range.test.tsx @@ -119,6 +119,33 @@ function sessionEntries() { }); } +test("America/Santiago midnight DST retains final-day activity and tooltip", async () => { + const previous = process.env.TZ; + process.env.TZ = "America/Santiago"; + try { + expect(new Date(2026, 8, 6, 0).getHours()).toBe(1); + await mount(); + await respond(0, "preset-marker"); + await enter("2026-09-05T00:00", "2026-09-07T23:59"); + await apply(); + const gate = requests.at(-1)!; + const data = report(gate, "santiago-marker", "2026-09-07"); + data.days = ["2026-09-05", "2026-09-06", "2026-09-07"].map(date => ({ + date, requests: date === "2026-09-07" ? 7 : 0, measuredRequests: 0, reportedRequests: 0, + totalTokens: date === "2026-09-07" ? 700 : 0, models: [], + })); + await act(async () => gate.resolve(Response.json(data))); + const active = container.querySelector('.heatmap-grid .heatmap-cell:not(.heatmap-cell-0)'); + expect(active).not.toBeNull(); + await act(async () => active!.dispatchEvent(new testWindow.MouseEvent("mouseover", { bubbles: true }))); + expect(container.querySelector(".heatmap-tip-date")?.textContent).toBe("2026-09-07"); + expect(container.querySelector(".heatmap-tip")?.textContent).toContain("700"); + } finally { + if (previous === undefined) delete process.env.TZ; + else process.env.TZ = previous; + } +}); + test("Apply submits inclusive bounds once; Clear restores the held preset without custom cache entries", async () => { await mount(); expect(requests[0].url).toBe(`${apiBase}/api/usage?range=30d&surface=all`); diff --git a/src/usage/summary.ts b/src/usage/summary.ts index d7e678ab4f..2e731a2900 100644 --- a/src/usage/summary.ts +++ b/src/usage/summary.ts @@ -306,7 +306,15 @@ function customWindowDates(window: UsageTimeWindow): string[] { const dates: string[] = []; while (date.getTime() >= start && dates.length < MAX_USAGE_DAY_BUCKETS) { dates.push(localDateKey(date.getTime())); + const previous = date.getTime(); date.setDate(date.getDate() - 1); + date.setHours(0, 0, 0, 0); + // A skipped civil day can normalize back to this same midnight (Apia, 2011). + // Move through the preceding instant to find the prior existing local day. + if (date.getTime() >= previous) { + date.setTime(previous - 1); + date.setHours(0, 0, 0, 0); + } } return dates.reverse(); } diff --git a/tests/usage/usage-summary.test.ts b/tests/usage/usage-summary.test.ts index 36d83c779f..094e9e5a44 100644 --- a/tests/usage/usage-summary.test.ts +++ b/tests/usage/usage-summary.test.ts @@ -17,6 +17,26 @@ import { isUnresolvedRequestedModel } from "../../src/usage/model-identity"; const FIXED_NOW = Date.UTC(2026, 5, 28, 12, 0, 0); describe("custom usage windows", () => { + test("Pacific/Apia skipped day still reaches the preceding existing calendar date", () => { + const previous = process.env.TZ; + process.env.TZ = "Pacific/Apia"; + try { + const start = new Date(2011, 11, 29, 12).getTime(); + const end = new Date(2011, 11, 31, 12).getTime(); + expect(new Date(2011, 11, 30, 0).getDate()).toBe(31); + const accumulator = createUsageSummaryAccumulator({ window: { since: start, until: end } }); + accumulator.add(entry({ ts: start, requestId: "before-skip" })); + accumulator.add(entry({ ts: end, requestId: "after-skip" })); + const summary = accumulator.summarize("all", end); + expect(summary.days.map(day => day.date)).toEqual(["2011-12-29", "2011-12-31"]); + expect(summary.days.map(day => day.requests)).toEqual([1, 1]); + expect(summary.summary.requests).toBe(2); + } finally { + if (previous === undefined) delete process.env.TZ; + else process.env.TZ = previous; + } + }); + const since = new Date(2026, 1, 10, 12, 0, 0, 123).getTime(); const until = since + 3_600_000; From 5669413794ca54388782f6758171a81a2d1b361e Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 21:13:57 +0900 Subject: [PATCH 073/116] test(models): scope price errors to their dialog [skip ci] Exact gates log showed the fixture read an unrelated picker alert behind the modal. Keep all expected error text and mutation assertions. Co-authored-by: nordz0r <6949669+nordz0r@users.noreply.github.com> --- gui/tests/models-price-editor.test.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/gui/tests/models-price-editor.test.tsx b/gui/tests/models-price-editor.test.tsx index b759a8398e..a80180b893 100644 --- a/gui/tests/models-price-editor.test.tsx +++ b/gui/tests/models-price-editor.test.tsx @@ -219,7 +219,7 @@ describe("Models manual price editor", () => { expect(button("Reset to automatic").disabled).toBe(true); await click("Save"); expect(mutations).toHaveLength(0); - expect(container.querySelector('[role="alert"]')!.textContent).toContain("Enter input and output rates"); + expect(container.querySelector('dialog [role="alert"]')!.textContent).toContain("Enter input and output rates"); await fill(["0", "0"]); expect(inputs().map(input => input.value)).toEqual(["0", "0", "0", "0"]); const before = catalogReads; @@ -256,7 +256,7 @@ describe("Models manual price editor", () => { await fill([invalid]); await click("Save"); expect(mutations).toHaveLength(0); - expect(container.querySelector('[role="alert"]')!.textContent).toContain("finite number"); + expect(container.querySelector('dialog [role="alert"]')!.textContent).toContain("finite number"); } await fill(["1000000", "0", "0.000001", "0.5"]); await click("Save"); @@ -268,7 +268,7 @@ describe("Models manual price editor", () => { await mount(); await open(); expect(inputs().every(input => input.disabled)).toBe(true); - expect(container.querySelector('[role="alert"]')!.textContent).toContain("Could not load"); + expect(container.querySelector('dialog [role="alert"]')!.textContent).toContain("Could not load"); expect(testWindow.document.activeElement).toBe(button("Reload price")); await click("Reload price"); expect(mutations).toHaveLength(0); @@ -296,14 +296,14 @@ describe("Models manual price editor", () => { expect(mutations).toHaveLength(1); expect(inputs().every(input => input.disabled)).toBe(true); expect(button("Reset to automatic").disabled).toBe(true); - expect(container.querySelector('[role="alert"]')!.textContent).toContain("may have changed"); + expect(container.querySelector('dialog [role="alert"]')!.textContent).toContain("may have changed"); await act(async () => button("Reset to automatic").dispatchEvent(new testWindow.MouseEvent("click", { bubbles: true }))); expect(mutations).toHaveLength(1); getFailure = true; await click("Reload price"); expect(mutations).toHaveLength(1); expect(inputs()[0]!.disabled).toBe(true); - expect(container.querySelector('[role="alert"]')!.textContent).toContain("Editing stays locked"); + expect(container.querySelector('dialog [role="alert"]')!.textContent).toContain("Editing stays locked"); getFailure = false; await click("Reload price"); expect(inputs().map(input => input.value)).toEqual(["0", "0", "0", "0"]); @@ -396,10 +396,10 @@ describe("Models manual price editor", () => { await click("Reset to automatic"); expect(mutations).toHaveLength(1); expect(inputs().every(input => input.disabled)).toBe(true); - expect(container.querySelector('[role="alert"]')!.textContent).toContain("price was saved"); + expect(container.querySelector('dialog [role="alert"]')!.textContent).toContain("price was saved"); await click("Refresh list"); expect(mutations).toHaveLength(1); - expect(container.querySelector('[role="alert"]')!.textContent).toContain("price was saved"); + expect(container.querySelector('dialog [role="alert"]')!.textContent).toContain("price was saved"); expect(reads).toHaveLength(1); catalogFailure = false; await click("Refresh list"); From fe9460372597061f572beee6c325009fef618c42 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:14:02 +0900 Subject: [PATCH 074/116] fix(usage): encode custom report identity as a tuple [skip ci] Keep cache identity as technical data rather than a UI-string-shaped template. No locale or lint-rule changes. Co-authored-by: Manson2438 <183030642+Manson2438@users.noreply.github.com> --- gui/src/pages/Usage.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/pages/Usage.tsx b/gui/src/pages/Usage.tsx index 36b0d4ba82..7895ce9370 100644 --- a/gui/src/pages/Usage.tsx +++ b/gui/src/pages/Usage.tsx @@ -830,7 +830,7 @@ export default function Usage({ apiBase, connected = false, apiKeyId }: { apiBas }, [apiBase, apiKeyId, connected, range, scope, surface, since, until]); const presetKey = usageCacheKey(apiBase, range, surface, connected, scope, apiKeyId); - const resourceKey = customWindow ? `${presetKey}:custom:${since}:${until}` : presetKey; + const resourceKey = customWindow ? JSON.stringify([presetKey, since, until]) : presetKey; // Arbitrary custom windows belong only to the subscription-scoped resource store. const cached = customWindow ? null : readHeldUsage(apiBase, range, surface, connected, scope, apiKeyId); // Range and surface identify different reports, so the key changes with both. That prevents From 8ecf91fc88d8dc07f429f590b74880f25f9f4a3a Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 19:48:57 +0900 Subject: [PATCH 075/116] feat(gui): add guarded routed model picker drag ordering [skip ci] Add Custom routed ordering with fixed featured rows, keyboard controls, fresh settings snapshots and accepted-receipt recovery. Preserve native complete orders until an explicit preset/reset is accepted. Include source regressions and all nine locale strings; runtime checks await central CI. Implements the routed slice requested in #3774; native/featured full-picker placement remains open. Co-authored-by: leonclab <26379556+leonclab@users.noreply.github.com> --- .../src/content/docs/guides/model-ordering.md | 21 + gui/src/components/ModelPickerOrderEditor.tsx | 172 +++++++++ gui/src/i18n/de.ts | 15 + gui/src/i18n/en.ts | 15 + gui/src/i18n/fr.ts | 15 + gui/src/i18n/ja.ts | 15 + gui/src/i18n/ko.ts | 15 + gui/src/i18n/ru.ts | 15 + gui/src/i18n/tr.ts | 15 + gui/src/i18n/zh-TW.ts | 15 + gui/src/i18n/zh.ts | 15 + gui/src/model-picker-order.ts | 76 +++- gui/src/pages/Models.tsx | 61 ++- gui/src/styles-models-workspace.css | 7 + gui/tests/model-picker-order-editor.test.tsx | 358 ++++++++++++++++++ gui/tests/model-picker-order.test.ts | 109 +++++- 16 files changed, 917 insertions(+), 22 deletions(-) create mode 100644 gui/src/components/ModelPickerOrderEditor.tsx create mode 100644 gui/tests/model-picker-order-editor.test.tsx diff --git a/docs-site/src/content/docs/guides/model-ordering.md b/docs-site/src/content/docs/guides/model-ordering.md index 2d33b409d8..5333b839ce 100644 --- a/docs-site/src/content/docs/guides/model-ordering.md +++ b/docs-site/src/content/docs/guides/model-ordering.md @@ -178,3 +178,24 @@ On **Models**, choose **Default**, **A–Z by model**, **Group by provider**, or The controls use `GET/PUT /api/subagent-models`: `chosen` and `available` retain saved roster choices, including disabled or missing models; `pickerAvailable` contains only eligible routed catalog ids. The Models page sends `pickerOrder` and `pickerOrderMode`, never `models`. Roster-only saves preserve picker settings. Invalid combined updates and failed persistence leave the previous picker/roster state intact. Routed-only presets keep the existing featured/native priority bands. They affect the Codex catalog and Claude discovery's routed groups; Claude's native prefix and explicit Desktop profile/alias ownership remain unchanged. OpenCodex guidance ranks and configured fallback settings are preserved, but native Codex's advertised five and recommended default can change with display priority. Saving does not restart clients; a catalog refresh may remain pending, and clients holding an old catalog may need reopening. + + +### Custom routed order + +Choose **Custom order** on Models to load a fresh routed snapshot. Drag a movable row before +another row, or use its Up/Down buttons, then **Save draft**. Featured routed rows stay at the +front in their configured rank and cannot move. Native rows are not shown; this is not a preview +of the complete native picker. Surviving saved rows keep their relative order and new candidates +follow the current candidate list. Every save sends the complete routed list, without changing +the featured roster. + +An order containing bare native ids remains protected until you explicitly apply a routed preset +or Default. Selecting a different option alone does not replace it. Unknown featured state blocks +editing. Before saving, the editor checks a fresh snapshot; changes preserve your draft and block +saving until **Reload and discard draft** loads current settings. Request failures retain the +draft. Accepted saves can still have a pending catalog refresh; reload before editing again. + +The editor also requires an unambiguous model identity for every routed candidate. If the model +catalog is incomplete, refresh the Models page before editing; reloading picker settings alone +cannot restore missing catalog identities. Featured choices are matched exactly without trimming; +duplicate choices use their last configured position, and canonical ids take precedence over raw ids. diff --git a/gui/src/components/ModelPickerOrderEditor.tsx b/gui/src/components/ModelPickerOrderEditor.tsx new file mode 100644 index 0000000000..3c379f8cce --- /dev/null +++ b/gui/src/components/ModelPickerOrderEditor.tsx @@ -0,0 +1,172 @@ +import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react"; +import { createBoundedFetch, type BoundedFetch } from "../bounded-fetch"; +import { readJsonOrThrow } from "../fetch-json"; +import { IconArrowDown, IconArrowUp, IconGrip } from "../icons"; +import { useT, type TKey } from "../i18n/shared"; +import { + customPickerRows, isPickerOrderSaved, isPickerOrderSettings, movePickerBefore, + pickerSnapshotSignature, stepPickerOrder, type PickerModelIdentity, type PickerOrderSaved, +} from "../model-picker-order"; + +type Receipt = PickerOrderSaved & { catalogRefresh?: unknown }; +type Snapshot = { signature: string; identities: string; order: string[]; fixed: string[] }; +const DRAG_TYPE = "application/x-ocx-picker-order"; +let dragSequence = 0; +/** Local drag identity, not a security token. Like newClientId, supports LAN HTTP. */ +function newDragToken(): string { + const sequence = ++dragSequence; + if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") { + try { return `${sequence}:${crypto.randomUUID()}`; } + catch { /* Some browsers expose randomUUID but reject it outside secure contexts. */ } + } + return `picker-${Date.now().toString(36)}-${sequence}`; +} + +export default function ModelPickerOrderEditor({ apiBase, active, identities, onAccepted, onBusyChange }: { + apiBase: string; active: boolean; identities: readonly PickerModelIdentity[]; + onAccepted: (receipt: Receipt) => void; onBusyChange: (busy: boolean) => void; +}) { + const t = useT(); + const [snapshot, setSnapshot] = useState(null); + const [draft, setDraft] = useState([]); + const [busy, setBusy] = useState(false); + const [blocked, setBlocked] = useState(null); + const [error, setError] = useState(false); + const [announcement, setAnnouncement] = useState(""); + const [dragging, setDragging] = useState(null); + const [over, setOver] = useState(null); + const drag = useRef<{ id: string; token: string } | null>(null); + const generation = useRef(0); + const flight = useRef(null); + const identitySignature = JSON.stringify(identities.map(({ provider, id, namespaced }) => [provider, id, namespaced])); + const latestIdentitySignature = useRef(identitySignature); + useLayoutEffect(() => { latestIdentitySignature.current = identitySignature; }, [identitySignature]); + const identityChanged = snapshot !== null && snapshot.identities !== identitySignature; + const disabled = !active || busy || !snapshot || blocked !== null || identityChanged; + const dirty = snapshot !== null && JSON.stringify(draft) !== JSON.stringify(snapshot.order); + const clearDrag = useCallback(() => { drag.current = null; setDragging(null); setOver(null); }, []); + + // Layout cleanup fences even A → B → A and unmount before a pending promise resumes. + useLayoutEffect(() => { + generation.current++; + setSnapshot(null); setDraft([]); setBlocked(null); setError(false); + return () => { + generation.current++; + flight.current?.controller.abort(); flight.current?.clear(); flight.current = null; + drag.current = null; onBusyChange(false); + }; + }, [apiBase, active, onBusyChange]); + useEffect(() => { clearDrag(); }, [disabled, snapshot, identitySignature, clearDrag]); + + const run = async (save: boolean) => { + if (!active || flight.current || (save && (disabled || !dirty))) return; + const owner = generation.current, bounded = createBoundedFetch(15_000); + flight.current = bounded; setBusy(true); onBusyChange(true); setError(false); clearDrag(); + const owns = () => generation.current === owner && flight.current === bounded; + const current = () => owns() && !bounded.signal.aborted + && latestIdentitySignature.current === identitySignature; + try { + const response = await fetch(`${apiBase}/api/subagent-models`, { signal: bounded.signal }); + if (!current()) return; + const settings = await readJsonOrThrow(response); + if (!current()) return; + if (!isPickerOrderSettings(settings)) throw new Error("Invalid picker settings"); + const signature = pickerSnapshotSignature(apiBase, owner, settings); + if (save && (!snapshot || signature !== snapshot.signature || identitySignature !== snapshot.identities)) { + setBlocked("models.pickerOrder.changed"); return; + } + const rows = customPickerRows(settings, identities); + if (!rows) { + setBlocked(settings.pickerOrder.some(id => !id.includes("/")) + ? "models.pickerOrder.nativeLocked" : settings.chosen === undefined + ? "models.pickerOrder.unknownChosen" : "models.pickerOrder.catalogRequired"); + return; + } + if (!save) { + setSnapshot({ ...rows, signature, identities: identitySignature }); setDraft(rows.order); + setBlocked(null); setAnnouncement(""); return; + } + const result = await fetch(`${apiBase}/api/subagent-models`, { + method: "PUT", headers: { "Content-Type": "application/json" }, signal: bounded.signal, + body: JSON.stringify({ pickerOrder: draft, pickerOrderMode: null }), + }); + if (!current()) return; + const receipt = await readJsonOrThrow(result); + if (!current()) return; + if (!isPickerOrderSaved(receipt) || !("ok" in receipt) || receipt.ok !== true) throw new Error("Invalid picker receipt"); + setDraft(receipt.pickerOrder); setBlocked("models.pickerOrder.savedReload"); + onAccepted({ pickerOrder: receipt.pickerOrder, pickerOrderMode: receipt.pickerOrderMode, + catalogRefresh: "catalogRefresh" in receipt ? receipt.catalogRefresh : undefined }); + } catch { + if (owns() && latestIdentitySignature.current === identitySignature) setError(true); + // Current-identity timeouts surface an error; stale identities retain the draft silently. + } finally { + bounded.clear(); + if (owns()) { flight.current = null; setBusy(false); onBusyChange(false); } + } + }; + const enter = useEffectEvent(() => { void run(false); }); + useEffect(() => { if (active) enter(); }, [apiBase, active]); + + const move = (id: string, next: string[]) => { + if (disabled) return; + setDraft(next); + setAnnouncement(t("models.pickerOrder.position", { model: id, position: next.indexOf(id) + 1, total: next.length })); + clearDrag(); + }; + const movable = (id: string) => !disabled && draft.includes(id) && !snapshot?.fixed.includes(id); + return
+

{t("models.pickerOrder.editorHint")}

+ {(blocked || identityChanged) &&

{t(blocked ?? "models.pickerOrder.changed")}

} + {error &&

{t("models.pickerOrder.requestFailed")}

} + {snapshot && draft.length === 0 &&

{t("models.pickerOrder.empty")}

} +
    + {draft.map((id, index) => { + const fixed = snapshot?.fixed.includes(id) === true; + return
  1. { + if (!drag.current || drag.current.id === id || !movable(drag.current.id) || !movable(id) + || !event.dataTransfer.types.includes(DRAG_TYPE)) return; + event.preventDefault(); event.dataTransfer.dropEffect = "move"; setOver(id); + }} + onDragLeave={() => setOver(null)} + onDrop={event => { + const source = drag.current; + if (source && source.id !== id && source.token === event.dataTransfer.getData(DRAG_TYPE) && movable(source.id) && movable(id)) { + event.preventDefault(); move(source.id, movePickerBefore(draft, source.id, id, snapshot?.fixed ?? [])); + } + clearDrag(); + }} onDragEnd={clearDrag}> + + {id} + {fixed && {t("models.pickerOrder.featured")}} + + + + +
  2. ; + })} +
+

{announcement}

+
+ + +
+
; +} diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 79d1591728..d413e1277c 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -2625,4 +2625,19 @@ export const de: Record = { "usage.range.invalid": "Geben Sie gültige lokale Daten und Uhrzeiten ab 1970-01-01 UTC ein.", "usage.range.reversed": "Das Ende muss auf oder nach dem Beginn liegen.", "usage.range.applied": "Ausgewählter Zeitraum: {start} – {end} (beide Grenzen eingeschlossen).", + "models.pickerOrder.editorHint": "Routingsmodelle neu ordnen und den Entwurf speichern. Hervorgehobene Zeilen sind fest; native Modelle werden nicht angezeigt.", + "models.pickerOrder.nativeLocked": "Diese Reihenfolge enthält native Modelle. Vor der Bearbeitung eine Routing-Vorgabe oder Standard anwenden.", + "models.pickerOrder.unknownChosen": "Hervorgehobene Modelle sind unbekannt. Vor der Bearbeitung neu laden.", + "models.pickerOrder.changed": "Die Einstellungen haben sich geändert. Der Entwurf bleibt erhalten; erneutes Laden verwirft ihn und lädt die aktuellen Einstellungen.", + "models.pickerOrder.savedReload": "Reihenfolge gespeichert. Vor weiterer Bearbeitung aktuelle Einstellungen laden.", + "models.pickerOrder.requestFailed": "Anfrage fehlgeschlagen. Der Entwurf bleibt erhalten; erneut versuchen oder neu laden.", + "models.pickerOrder.empty": "Keine Routingmodelle verfügbar.", + "models.pickerOrder.dragModel": "{model} ziehen", + "models.pickerOrder.featured": "Hervorgehoben", + "models.pickerOrder.upModel": "{model} nach oben verschieben", + "models.pickerOrder.downModel": "{model} nach unten verschieben", + "models.pickerOrder.position": "{model}: Position {position} von {total}", + "models.pickerOrder.saveDraft": "Entwurf speichern", + "models.pickerOrder.reloadDraft": "Neu laden und Entwurf verwerfen", + "models.pickerOrder.catalogRequired": "Modellidentitäten fehlen oder sind mehrdeutig. Laden Sie die Modellseite neu, um den Katalog vor der Bearbeitung zu aktualisieren.", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index cceef53d12..b842f4618c 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -2659,6 +2659,21 @@ export const en = { "usage.range.invalid": "Enter valid local dates and times, on or after 1970-01-01 UTC.", "usage.range.reversed": "The end must be at or after the start.", "usage.range.applied": "Selected interval: {start} – {end} (both inclusive).", + "models.pickerOrder.editorHint": "Reorder routed models, then save your draft. Featured rows are fixed; native models are not shown.", + "models.pickerOrder.nativeLocked": "This saved order includes native models. Apply a routed preset or Default before editing Custom.", + "models.pickerOrder.unknownChosen": "Featured choices are unknown. Reload before editing.", + "models.pickerOrder.changed": "Picker settings changed. Your draft is kept; reload to discard it and use current settings.", + "models.pickerOrder.savedReload": "Order saved. Reload current settings before editing again.", + "models.pickerOrder.requestFailed": "Request failed. Your draft is kept; retry or reload.", + "models.pickerOrder.empty": "No routed models are available.", + "models.pickerOrder.dragModel": "Drag {model}", + "models.pickerOrder.featured": "Featured", + "models.pickerOrder.upModel": "Move {model} up", + "models.pickerOrder.downModel": "Move {model} down", + "models.pickerOrder.position": "{model}: position {position} of {total}", + "models.pickerOrder.saveDraft": "Save draft", + "models.pickerOrder.reloadDraft": "Reload and discard draft", + "models.pickerOrder.catalogRequired": "Model identities are missing or ambiguous. Reload the Models page to refresh its catalog before editing Custom.", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 67b2586fe4..d07b7f7a16 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -2612,4 +2612,19 @@ export const fr: Record = { "usage.range.invalid": "Saisissez des dates et heures locales valides à partir du 1970-01-01 UTC.", "usage.range.reversed": "La fin doit être égale ou postérieure au début.", "usage.range.applied": "Période sélectionnée : {start} – {end} (bornes incluses).", + "models.pickerOrder.editorHint": "Réordonnez les modèles routés, puis enregistrez le brouillon. Les lignes mises en avant sont fixes ; les modèles natifs ne sont pas affichés.", + "models.pickerOrder.nativeLocked": "Cet ordre contient des modèles natifs. Appliquez un préréglage de routage ou Par défaut avant de le personnaliser.", + "models.pickerOrder.unknownChosen": "Les modèles mis en avant sont inconnus. Rechargez avant de modifier.", + "models.pickerOrder.changed": "Les paramètres ont changé. Le brouillon est conservé ; rechargez pour le supprimer et utiliser les paramètres actuels.", + "models.pickerOrder.savedReload": "Ordre enregistré. Rechargez les paramètres actuels avant de modifier à nouveau.", + "models.pickerOrder.requestFailed": "Échec de la requête. Le brouillon est conservé ; réessayez ou rechargez.", + "models.pickerOrder.empty": "Aucun modèle routé disponible.", + "models.pickerOrder.dragModel": "Faire glisser {model}", + "models.pickerOrder.featured": "Mis en avant", + "models.pickerOrder.upModel": "Monter {model}", + "models.pickerOrder.downModel": "Descendre {model}", + "models.pickerOrder.position": "{model} : position {position} sur {total}", + "models.pickerOrder.saveDraft": "Enregistrer le brouillon", + "models.pickerOrder.reloadDraft": "Recharger et supprimer le brouillon", + "models.pickerOrder.catalogRequired": "Les identités des modèles sont manquantes ou ambiguës. Rechargez la page Modèles pour actualiser le catalogue avant de personnaliser l’ordre.", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 92bb516827..1db94902c5 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -2646,4 +2646,19 @@ export const ja: Record = { "usage.range.invalid": "1970-01-01 UTC以降の有効な現地日時を入力してください。", "usage.range.reversed": "終了日時は開始日時と同じか、それ以降にしてください。", "usage.range.applied": "選択した期間:{start} – {end}(両端を含む)。", + "models.pickerOrder.editorHint": "ルーティングモデルを並べ替えて下書きを保存します。おすすめ行は固定され、ネイティブモデルは表示されません。", + "models.pickerOrder.nativeLocked": "保存済みの順序にネイティブモデルが含まれています。ルーティングのプリセットかデフォルトを適用してからカスタム順序を編集してください。", + "models.pickerOrder.unknownChosen": "おすすめモデルが不明です。再読み込みしてから編集してください。", + "models.pickerOrder.changed": "設定が変更されました。下書きは保持されます。再読み込みすると下書きを破棄し、現在の設定を使用します。", + "models.pickerOrder.savedReload": "順序を保存しました。再編集する前に現在の設定を読み込んでください。", + "models.pickerOrder.requestFailed": "リクエストに失敗しました。下書きは保持されます。再試行するか再読み込みしてください。", + "models.pickerOrder.empty": "利用可能なルーティングモデルはありません。", + "models.pickerOrder.dragModel": "{model} をドラッグ", + "models.pickerOrder.featured": "おすすめ", + "models.pickerOrder.upModel": "{model} を上へ移動", + "models.pickerOrder.downModel": "{model} を下へ移動", + "models.pickerOrder.position": "{model}: {total} 件中 {position} 番目", + "models.pickerOrder.saveDraft": "下書きを保存", + "models.pickerOrder.reloadDraft": "下書きを破棄して再読み込み", + "models.pickerOrder.catalogRequired": "モデルの識別情報が不足しているか曖昧です。モデルページを再読み込みしてカタログを更新してからカスタム順序を編集してください。", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index 7f02d3792f..b31d6e4e1a 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -2647,4 +2647,19 @@ export const ko: Record = { "usage.range.invalid": "1970-01-01 UTC 이후의 유효한 현지 날짜와 시간을 입력하세요.", "usage.range.reversed": "종료 시각은 시작 시각과 같거나 이후여야 합니다.", "usage.range.applied": "선택한 기간: {start} – {end} (양 끝 시각 포함).", + "models.pickerOrder.editorHint": "라우팅 모델의 순서를 바꾼 뒤 초안을 저장하세요. 추천 모델은 고정되며 네이티브 모델은 표시하지 않습니다.", + "models.pickerOrder.nativeLocked": "저장된 순서에 네이티브 모델이 포함되어 있습니다. 라우팅 프리셋이나 기본값을 적용한 뒤 사용자 지정 순서를 편집하세요.", + "models.pickerOrder.unknownChosen": "추천 모델 정보를 확인할 수 없습니다. 다시 불러온 뒤 편집하세요.", + "models.pickerOrder.changed": "모델 선택 설정이 바뀌었습니다. 초안은 유지됩니다. 다시 불러오면 초안을 버리고 현재 설정을 사용합니다.", + "models.pickerOrder.savedReload": "순서가 저장되었습니다. 다시 편집하려면 현재 설정을 불러오세요.", + "models.pickerOrder.requestFailed": "요청에 실패했습니다. 초안은 유지됩니다. 재시도하거나 다시 불러오세요.", + "models.pickerOrder.empty": "사용 가능한 라우팅 모델이 없습니다.", + "models.pickerOrder.dragModel": "{model} 끌어서 이동", + "models.pickerOrder.featured": "추천 모델", + "models.pickerOrder.upModel": "{model} 위로 이동", + "models.pickerOrder.downModel": "{model} 아래로 이동", + "models.pickerOrder.position": "{model}: {total}개 중 {position}번째", + "models.pickerOrder.saveDraft": "초안 저장", + "models.pickerOrder.reloadDraft": "초안 버리고 다시 불러오기", + "models.pickerOrder.catalogRequired": "모델 식별 정보가 없거나 모호합니다. 모델 페이지를 새로고침해 목록을 갱신한 뒤 사용자 지정 순서를 편집하세요.", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 9548be7d64..a8370e7f5f 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -2648,4 +2648,19 @@ export const ru: Record = { "usage.range.invalid": "Введите допустимые местные дату и время не ранее 1970-01-01 UTC.", "usage.range.reversed": "Конец не может быть раньше начала.", "usage.range.applied": "Выбранный период: {start} – {end} (обе границы включены).", + "models.pickerOrder.editorHint": "Измените порядок маршрутизируемых моделей и сохраните черновик. Избранные строки закреплены; нативные модели не показаны.", + "models.pickerOrder.nativeLocked": "Сохранённый порядок содержит нативные модели. Перед редактированием примените пресет маршрутизации или порядок по умолчанию.", + "models.pickerOrder.unknownChosen": "Избранные модели неизвестны. Перезагрузите данные перед редактированием.", + "models.pickerOrder.changed": "Настройки изменились. Черновик сохранён; перезагрузка сбросит его и загрузит текущие настройки.", + "models.pickerOrder.savedReload": "Порядок сохранён. Перед следующим редактированием загрузите текущие настройки.", + "models.pickerOrder.requestFailed": "Ошибка запроса. Черновик сохранён; повторите запрос или перезагрузите данные.", + "models.pickerOrder.empty": "Нет доступных маршрутизируемых моделей.", + "models.pickerOrder.dragModel": "Перетащить {model}", + "models.pickerOrder.featured": "Избранная", + "models.pickerOrder.upModel": "Переместить {model} вверх", + "models.pickerOrder.downModel": "Переместить {model} вниз", + "models.pickerOrder.position": "{model}: позиция {position} из {total}", + "models.pickerOrder.saveDraft": "Сохранить черновик", + "models.pickerOrder.reloadDraft": "Перезагрузить и сбросить черновик", + "models.pickerOrder.catalogRequired": "Идентификаторы моделей отсутствуют или неоднозначны. Перезагрузите страницу моделей, чтобы обновить каталог перед редактированием порядка.", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 7b835eb03e..6a7c02c936 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -2648,4 +2648,19 @@ export const tr: Record = { "usage.range.invalid": "1970-01-01 UTC veya sonrasına ait geçerli yerel tarih ve saat girin.", "usage.range.reversed": "Bitiş, başlangıçla aynı veya daha sonra olmalıdır.", "usage.range.applied": "Seçilen aralık: {start} – {end} (iki sınır da dahil).", + "models.pickerOrder.editorHint": "Yönlendirilen modelleri sıralayıp taslağı kaydedin. Öne çıkan satırlar sabittir; yerel modeller gösterilmez.", + "models.pickerOrder.nativeLocked": "Kayıtlı sıra yerel modeller içeriyor. Özel sırayı düzenlemeden önce yönlendirme ön ayarını veya Varsayılan seçeneğini uygulayın.", + "models.pickerOrder.unknownChosen": "Öne çıkan modeller bilinmiyor. Düzenlemeden önce yeniden yükleyin.", + "models.pickerOrder.changed": "Seçici ayarları değişti. Taslağınız korunuyor; yeniden yüklemek taslağı siler ve güncel ayarları kullanır.", + "models.pickerOrder.savedReload": "Sıra kaydedildi. Yeniden düzenlemeden önce güncel ayarları yükleyin.", + "models.pickerOrder.requestFailed": "İstek başarısız. Taslağınız korunuyor; tekrar deneyin veya yeniden yükleyin.", + "models.pickerOrder.empty": "Kullanılabilir yönlendirilen model yok.", + "models.pickerOrder.dragModel": "{model} modelini sürükle", + "models.pickerOrder.featured": "Öne çıkan", + "models.pickerOrder.upModel": "{model} modelini yukarı taşı", + "models.pickerOrder.downModel": "{model} modelini aşağı taşı", + "models.pickerOrder.position": "{model}: {total} içinde {position}. sıra", + "models.pickerOrder.saveDraft": "Taslağı kaydet", + "models.pickerOrder.reloadDraft": "Yeniden yükle ve taslağı sil", + "models.pickerOrder.catalogRequired": "Model kimlikleri eksik veya belirsiz. Özel sırayı düzenlemeden önce kataloğu yenilemek için Modeller sayfasını yeniden yükleyin.", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index cd0b7e17d3..d59fa6d6bc 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2610,4 +2610,19 @@ export const zhTW: Record = { "usage.range.invalid": "請輸入不早於 1970-01-01 UTC 的有效本地日期和時間。", "usage.range.reversed": "結束時間必須等於或晚於開始時間。", "usage.range.applied": "所選範圍:{start} – {end}(包含兩端)。", + "models.pickerOrder.editorHint": "調整路由模型順序後儲存草稿。精選列固定,原生模型不在此顯示。", + "models.pickerOrder.nativeLocked": "已儲存的順序包含原生模型。請先套用路由預設或預設順序,再編輯自訂順序。", + "models.pickerOrder.unknownChosen": "精選模型資訊未知。請重新載入後再編輯。", + "models.pickerOrder.changed": "模型選擇設定已變更。草稿已保留;重新載入將捨棄草稿並使用目前設定。", + "models.pickerOrder.savedReload": "順序已儲存。再次編輯前請重新載入目前設定。", + "models.pickerOrder.requestFailed": "請求失敗。草稿已保留;請重試或重新載入。", + "models.pickerOrder.empty": "沒有可用的路由模型。", + "models.pickerOrder.dragModel": "拖曳 {model}", + "models.pickerOrder.featured": "精選", + "models.pickerOrder.upModel": "上移 {model}", + "models.pickerOrder.downModel": "下移 {model}", + "models.pickerOrder.position": "{model}:第 {position} 位,共 {total} 個", + "models.pickerOrder.saveDraft": "儲存草稿", + "models.pickerOrder.reloadDraft": "捨棄草稿並重新載入", + "models.pickerOrder.catalogRequired": "模型識別資訊缺失或不明確。請重新載入模型頁面以更新目錄,再編輯自訂順序。", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index d9f93f20c7..d20318ce42 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -2646,4 +2646,19 @@ export const zh: Record = { "usage.range.invalid": "请输入不早于 1970-01-01 UTC 的有效本地日期和时间。", "usage.range.reversed": "结束时间必须等于或晚于开始时间。", "usage.range.applied": "所选范围:{start} – {end}(包含两端)。", + "models.pickerOrder.editorHint": "调整路由模型顺序后保存草稿。精选行固定,原生模型不在此显示。", + "models.pickerOrder.nativeLocked": "已保存的顺序包含原生模型。请先应用路由预设或默认顺序,再编辑自定义顺序。", + "models.pickerOrder.unknownChosen": "精选模型信息未知。请重新加载后再编辑。", + "models.pickerOrder.changed": "模型选择设置已更改。草稿已保留;重新加载将丢弃草稿并使用当前设置。", + "models.pickerOrder.savedReload": "顺序已保存。再次编辑前请重新加载当前设置。", + "models.pickerOrder.requestFailed": "请求失败。草稿已保留;请重试或重新加载。", + "models.pickerOrder.empty": "没有可用的路由模型。", + "models.pickerOrder.dragModel": "拖动 {model}", + "models.pickerOrder.featured": "精选", + "models.pickerOrder.upModel": "上移 {model}", + "models.pickerOrder.downModel": "下移 {model}", + "models.pickerOrder.position": "{model}:第 {position} 位,共 {total} 个", + "models.pickerOrder.saveDraft": "保存草稿", + "models.pickerOrder.reloadDraft": "丢弃草稿并重新加载", + "models.pickerOrder.catalogRequired": "模型标识信息缺失或不明确。请重新加载模型页面以刷新目录,再编辑自定义顺序。", }; diff --git a/gui/src/model-picker-order.ts b/gui/src/model-picker-order.ts index dfa5073b08..0de6190f02 100644 --- a/gui/src/model-picker-order.ts +++ b/gui/src/model-picker-order.ts @@ -11,7 +11,7 @@ export interface PickerOrderSaved { pickerOrder: string[]; pickerOrderMode: SavedModelPickerOrderMode | null; } -export interface PickerOrderSettings extends PickerOrderSaved { pickerAvailable: string[] } +export interface PickerOrderSettings extends PickerOrderSaved { pickerAvailable: string[]; chosen?: string[] } function stringList(value: unknown): value is string[] { return Array.isArray(value) && value.every(id => typeof id === "string" && id.trim().length > 0); @@ -25,7 +25,11 @@ export function isPickerOrderSaved(value: unknown): value is PickerOrderSaved { return stringList(row.pickerOrder) && savedMode(row.pickerOrderMode); } export function isPickerOrderSettings(value: unknown): value is PickerOrderSettings { - return isPickerOrderSaved(value) && stringList((value as PickerOrderSettings).pickerAvailable); + if (!isPickerOrderSaved(value)) return false; + const row = value as PickerOrderSettings; + // Roster writes accept every string, including blanks; picker fields remain nonempty-string lists. + return stringList(row.pickerAvailable) && (!("chosen" in row) + || (Array.isArray(row.chosen) && row.chosen.every(id => typeof id === "string"))); } export function isModelPickerUsage(value: unknown): value is ModelPickerUsage[] { return Array.isArray(value) && value.every(row => row !== null && typeof row === "object" @@ -104,3 +108,71 @@ export function modelPickerOrderMode( } return "custom"; } + + +/** Resolve exact canonical ids before legacy provider/raw spellings; never guess a bare native id. */ +export function normalizePickerIds(ids: readonly string[], available: readonly string[], identities: readonly PickerModelIdentity[]): string[] { + const candidates = new Set(available.filter(id => id.includes("/"))); + const resolve = (id: string): string | undefined => { + if (candidates.has(id)) return id; + const matches = new Set(identities.filter(row => candidates.has(row.namespaced) + && id === `${row.provider}/${row.id}`).map(row => row.namespaced)); + return matches.size === 1 ? [...matches][0] : undefined; + }; + return [...new Set(ids.map(id => resolve(id.trim())).filter((id): id is string => id !== undefined))]; +} + +export function pickerSnapshotSignature(apiBase: string, generation: number, settings: PickerOrderSettings): string { + return JSON.stringify([apiBase, generation, settings.pickerAvailable, settings.chosen ?? null, + settings.pickerOrder, settings.pickerOrderMode]); +} + +/** Every candidate needs one observed provider/raw identity, with no encoded/raw collisions. */ +export function pickerIdentityCoverage(available: readonly string[], identities: readonly PickerModelIdentity[]): boolean { + const candidates = new Set(available.filter(id => id.includes("/"))); + const rawBySlug = new Map>(), slugsByRaw = new Map>(); + for (const row of identities) { + if (!candidates.has(row.namespaced)) continue; + const raw = `${row.provider}/${row.id}`; + const raws = rawBySlug.get(row.namespaced) ?? new Set(); + const slugs = slugsByRaw.get(raw) ?? new Set(); + raws.add(raw); slugs.add(row.namespaced); + rawBySlug.set(row.namespaced, raws); slugsByRaw.set(raw, slugs); + } + return [...candidates].every(slug => { + const raws = rawBySlug.get(slug); + return raws?.size === 1 && slugsByRaw.get([...raws][0]!)?.size === 1; + }); +} + +export function customPickerRows(settings: PickerOrderSettings, identities: readonly PickerModelIdentity[]): { order: string[]; fixed: string[] } | null { + // Unknown featured state and complete/native orders cannot safely become routed-only drafts. + if (settings.chosen === undefined || settings.pickerOrder.some(id => !id.includes("/"))) return null; + const available = [...new Set(settings.pickerAvailable.filter(id => id.includes("/")))]; + if (!pickerIdentityCoverage(available, identities)) return null; + // Roster strings stay verbatim. Map uses the LAST occurrence; each row prefers its exact canonical rank. + const chosenRank = new Map(settings.chosen.map((id, index) => [id, index])); + const rawBySlug = new Map(identities.map(row => [row.namespaced, `${row.provider}/${row.id}`])); + const rankOf = (slug: string) => chosenRank.get(slug) ?? chosenRank.get(rawBySlug.get(slug)!); + const fixed = available.filter(slug => rankOf(slug) !== undefined).sort((a, b) => rankOf(a)! - rankOf(b)!); + const saved = normalizePickerIds(settings.pickerOrder, available, identities); + return { fixed, order: [...new Set([...fixed, ...saved, ...available])] }; +} + +/** Drop semantics: remove first, re-find the target, then insert before it. */ +export function movePickerBefore(order: readonly string[], source: string, target: string, fixed: readonly string[]): string[] { + const next = [...order]; + if (source === target || fixed.includes(source) || fixed.includes(target) + || !next.includes(source) || !next.includes(target)) return next; + next.splice(next.indexOf(source), 1); + next.splice(next.indexOf(target), 0, source); + return next; +} + +/** Keyboard semantics deliberately differ from dropping before the next row. */ +export function stepPickerOrder(order: readonly string[], source: string, direction: -1 | 1, fixed: readonly string[]): string[] { + const next = [...order], index = next.indexOf(source), target = index + direction; + if (index < 0 || target < 0 || target >= next.length || fixed.includes(source) || fixed.includes(next[target]!)) return next; + [next[index], next[target]] = [next[target]!, next[index]!]; + return next; +} diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx index bc010c4abc..55d9c16106 100644 --- a/gui/src/pages/Models.tsx +++ b/gui/src/pages/Models.tsx @@ -1,10 +1,11 @@ import { CodexStaleBanner } from "../components/codex-stale-banner"; +import ModelPickerOrderEditor from "../components/ModelPickerOrderEditor"; import ModelDisplayNameDialog from "../components/ModelDisplayNameDialog"; import ModelPriceDialog from "../components/ModelPriceDialog"; import { fetchCodexAppServerState } from "../codex-app-server-state"; import type { AppServerStateOutcome } from "../codex-app-server-state"; import { useCodexRestart } from "../use-codex-restart"; -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { Switch, Notice, EmptyState, Select, Tooltip } from "../ui"; import { IconChevron, IconBoxes, IconInfo, IconCheck, IconAlert, IconRefresh, IconPencil } from "../icons"; import { useT } from "../i18n/shared"; @@ -18,7 +19,7 @@ import { setClientResourceData } from "../client-resource"; import { createBoundedFetch, type BoundedFetch } from "../bounded-fetch"; import { isModelPickerUsage, isPickerOrderSaved, isPickerOrderSettings, modelPickerOrder, modelPickerOrderMode, - type ModelPickerOrderMode, type PickerOrderSettings, type ModelPickerUsage, + type ModelPickerOrderMode, type PickerOrderSettings, type PickerOrderSaved, type ModelPickerUsage, } from "../model-picker-order"; import { startVisibilityPoll } from "../visibility-poll"; import { useDataSurface } from "../data-surface"; @@ -253,6 +254,7 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; const [pickerDraft, setPickerDraft] = useState(null); const [pickerBusy, setPickerBusy] = useState(false); const pickerFlight = useRef(null); + const pickerGeneration = useRef(0); const pickerResource = useDataSurface( pickerCacheKey, [apiBase], useCallback(async (signal: AbortSignal) => { @@ -269,16 +271,22 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; const pickerMode = pickerDraft ?? modelPickerOrderMode( pickerSettings?.pickerAvailable ?? [], pickerSettings?.pickerOrder ?? [], pickerSettings?.pickerOrderMode, ); - useEffect(() => { + useLayoutEffect(() => { + pickerGeneration.current++; setPickerDraft(null); setPickerBusy(false); return () => { + pickerGeneration.current++; pickerFlight.current?.controller.abort(); pickerFlight.current?.clear(); pickerFlight.current = null; cancelAppServerRead(); }; }, [apiBase, catalogActive, cancelAppServerRead]); + useLayoutEffect(() => { + // Pin inferred Custom before any late GET can switch mode and unmount its draft. + if (catalogActive && pickerDraft === null && pickerMode === "custom") setPickerDraft("custom"); + }, [catalogActive, pickerDraft, pickerMode]); const [customCap, setCustomCap] = useState(""); const [showCustom, setShowCustom] = useState(false); const [providerCapCustomOpen, setProviderCapCustomOpen] = useState>({}); @@ -1825,49 +1833,61 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; ? groups.filter(group => group.provider === selectedProvider) : groups; + const acceptPickerOrder = (data: PickerOrderSaved & { catalogRefresh?: unknown }, custom = false) => { + // A receipt proves only the saved fields. No old chosen/available snapshot is promoted. + const next: PickerOrderSettings = { pickerOrder: data.pickerOrder, pickerOrderMode: data.pickerOrderMode, pickerAvailable: [] }; + setClientResourceData(pickerCacheKey, next); + writeSessionListCache(pickerCacheKey, next); + if (custom) setPickerDraft("custom"); + pickerResource.refresh(); + const refresh = data.catalogRefresh; + const converged = refresh !== null && typeof refresh === "object" + && "status" in refresh && refresh.status === "committed" + && "degraded" in refresh && refresh.degraded === false; + publishFeedback(converged, t(converged ? "models.pickerOrder.saved" : "models.pickerOrder.pending")); + void reloadAppServerState(); + }; + const savePickerOrder = async () => { if (pickerFlight.current || !pickerSettings || pickerResource.state.showError || pickerMode === "custom") return; + const owner = pickerGeneration.current; const mode = pickerMode; const available = pickerSettings.pickerAvailable; const bounded = createBoundedFetch(15_000); pickerFlight.current = bounded; setPickerBusy(true); + const owns = () => pickerGeneration.current === owner && pickerFlight.current === bounded; + const current = () => owns() && !bounded.signal.aborted; try { let usage: ModelPickerUsage[] = []; if (mode === "most-used") { const response = await fetch(`${apiBase}/api/usage?range=all&surface=all`, { signal: bounded.signal }); + if (!current()) return; const payload = await readJsonOrThrow<{ models?: unknown }>(response, t("models.pickerOrder.usageFailed")); + if (!current()) return; if (!isModelPickerUsage(payload?.models)) throw new Error(t("models.pickerOrder.usageFailed")); usage = payload.models; } + if (!current()) return; const order = modelPickerOrder(mode, available, usage, models); const response = await fetch(`${apiBase}/api/subagent-models`, { method: "PUT", headers: { "Content-Type": "application/json" }, signal: bounded.signal, body: JSON.stringify({ pickerOrder: order, pickerOrderMode: mode === "default" ? null : mode }), }); + if (!current()) return; const data = await readJsonOrThrow(response, t("models.saveFailed")); if (!isPickerOrderSaved(data) || !("ok" in data) || data.ok !== true) throw new Error(t("models.saveFailed")); - if (bounded.signal.aborted || pickerFlight.current !== bounded) return; - const next = { ...pickerSettings, pickerOrder: data.pickerOrder, pickerOrderMode: data.pickerOrderMode }; - // This aborts an older GET and advances the shared resource generation. - setClientResourceData(pickerCacheKey, next); - writeSessionListCache(pickerCacheKey, next); + if (!current()) return; + acceptPickerOrder({ pickerOrder: data.pickerOrder, pickerOrderMode: data.pickerOrderMode, + catalogRefresh: "catalogRefresh" in data ? data.catalogRefresh : undefined }); setPickerDraft(null); - - const refresh = "catalogRefresh" in data ? data.catalogRefresh : undefined; - const converged = refresh !== null && typeof refresh === "object" - && "status" in refresh && refresh.status === "committed" - && "degraded" in refresh && refresh.degraded === false; - publishFeedback(converged, t(converged ? "models.pickerOrder.saved" : "models.pickerOrder.pending")); - // Durable save is already accepted. Observational failure must not undo it. - void reloadAppServerState(); } catch (error) { - if (pickerFlight.current === bounded) { + if (owns()) { publishFeedback(false, error instanceof Error ? error.message : t("models.networkError")); } } finally { bounded.clear(); - if (pickerFlight.current === bounded) { pickerFlight.current = null; setPickerBusy(false); } + if (owns()) { pickerFlight.current = null; setPickerBusy(false); } } }; @@ -2039,7 +2059,7 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; { value: "alphabetical", label: t("models.pickerOrder.alphabetical") }, { value: "provider", label: t("models.pickerOrder.provider") }, { value: "most-used", label: t("models.pickerOrder.mostUsed") }, - ...(pickerMode === "custom" ? [{ value: "custom", label: t("models.pickerOrder.custom") }] : []), + { value: "custom", label: t("models.pickerOrder.custom") }, ]} onChange={value => setPickerDraft(value as ModelPickerOrderMode)} disabled={pickerBusy || !pickerSettings || pickerResource.state.showError} @@ -2058,6 +2078,9 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; } {t("models.pickerOrder.hint")} + {pickerMode === "custom" && acceptPickerOrder(data, true)} />} + {(() => { const customCount = models.filter(m => m.custom).length; diff --git a/gui/src/styles-models-workspace.css b/gui/src/styles-models-workspace.css index 6195a7b24f..67872711e2 100644 --- a/gui/src/styles-models-workspace.css +++ b/gui/src/styles-models-workspace.css @@ -648,3 +648,10 @@ } } .models-integration-warning { overflow-wrap: anywhere; } + +.picker-order-editor { margin-block: 12px; } +.picker-order-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; } +.picker-order-row { display: flex; align-items: center; flex-wrap: wrap; gap: 8px; padding-block: 4px; } +.picker-order-name { flex: 1; min-width: 0; overflow-wrap: anywhere; } +.picker-order-actions { display: inline-flex; flex-shrink: 0; gap: 2px; } +.picker-order-row .cwi-target-grip:disabled { cursor: default; opacity: 0.5; } diff --git a/gui/tests/model-picker-order-editor.test.tsx b/gui/tests/model-picker-order-editor.test.tsx new file mode 100644 index 0000000000..7cfeb6b326 --- /dev/null +++ b/gui/tests/model-picker-order-editor.test.tsx @@ -0,0 +1,358 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import Models from "../src/pages/Models"; +import { clearClientResourceStoresForTests, setClientResourceData } from "../src/client-resource"; +import ModelPickerOrderEditor from "../src/components/ModelPickerOrderEditor"; +import { LanguageProvider } from "../src/i18n/provider"; +import type { PickerModelIdentity, PickerOrderSettings, PickerOrderSaved } from "../src/model-picker-order"; + +const globals = ["document", "window", "navigator", "localStorage", "sessionStorage", "fetch", "crypto", "IS_REACT_ACT_ENVIRONMENT"] as const; +const ids: PickerModelIdentity[] = ["f", "a", "b", "c"].map(id => ({ provider: "p", id, namespaced: `p/${id}` })); +const initial = (): PickerOrderSettings => ({ pickerAvailable: ["p/f", "p/a", "p/b", "p/c"], + chosen: ["native", "p/f"], pickerOrder: ["p/a", "p/b", "p/c", "p/f"], pickerOrderMode: null }); +const changedDraft = ["p/f", "p/b", "p/a", "p/c"]; +function deferred() { + let resolve!: (value: T) => void, reject!: (error: Error) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} +type Request = ReturnType> & { url: string; method: string; body: unknown; signal?: AbortSignal | null }; +let previous: Map; +let win: Window, host: HTMLElement, root: Root | null; +let requests: Request[], receipts: Array, busy: boolean[]; +const onAccepted = (value: PickerOrderSaved & { catalogRefresh?: unknown }) => { receipts.push(value); }; +const onBusyChange = (value: boolean) => { busy.push(value); }; + +beforeEach(() => { + clearClientResourceStoresForTests(); + previous = new Map(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])); + win = new Window({ url: "http://localhost/#models" }); + win.localStorage.setItem("ocx-lang", "en"); + const values = { document: win.document, window: win, navigator: win.navigator, + localStorage: win.localStorage, sessionStorage: win.sessionStorage, IS_REACT_ACT_ENVIRONMENT: true }; + for (const [key, value] of Object.entries(values)) Object.defineProperty(globalThis, key, { configurable: true, value }); + requests = []; receipts = []; busy = []; root = null; + Object.defineProperty(globalThis, "fetch", { configurable: true, value: (input: RequestInfo | URL, init?: RequestInit) => { + // Intentionally ignores abort: late network/body completion must be fenced by the component. + const request = { ...deferred(), url: String(input), method: init?.method ?? "GET", + body: init?.body ? JSON.parse(String(init.body)) : undefined, signal: init?.signal }; + requests.push(request); return request.promise; + } }); + host = document.createElement("div"); document.body.append(host); +}); +afterEach(async () => { + if (root) await act(async () => { root!.unmount(); }); + clearClientResourceStoresForTests(); + win.close(); + for (const key of globals) { + const descriptor = previous.get(key); + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } +}); +async function render(apiBase = "/a", identities = ids, active = true) { + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root ??= createRoot(host); + root.render(); + }); +} +async function reply(index: number, data: unknown, status = 200) { + await act(async () => { requests[index]!.resolve(Response.json(data, { status })); }); +} +const order = (within: ParentNode = host) => [...within.querySelectorAll(".picker-order-name")].map(row => row.textContent); +function button(name: string, within: ParentNode = host): HTMLButtonElement { + const found = [...within.querySelectorAll("button")] + .find(node => node.getAttribute("aria-label") === name || node.textContent === name); + if (!found) throw new Error(`Missing button: ${name}`); + return found; +} +async function click(name: string) { await act(async () => { button(name).click(); }); } +function row(id: string, within: ParentNode = host): HTMLElement { + const found = [...within.querySelectorAll("li")].find(node => node.querySelector("code")?.textContent === id); + if (!found) throw new Error(`Missing row: ${id}`); + return found; +} +function transfer() { + const data = new Map(); + return { effectAllowed: "uninitialized", dropEffect: "none", get types() { return [...data.keys()]; }, + setData: (type: string, value: string) => { data.set(type, value); }, getData: (type: string) => data.get(type) ?? "" }; +} +async function dragEvent(target: Element, type: string, dataTransfer: ReturnType) { + await act(async () => { + const event = new win.Event(type, { bubbles: true, cancelable: true }); + Object.defineProperty(event, "dataTransfer", { value: dataTransfer }); target.dispatchEvent(event); + }); +} +async function drop(source: string, target: string) { + const data = transfer(); + await dragEvent(button(`Drag ${source}`), "dragstart", data); + await dragEvent(row(target), "dragover", data); + await dragEvent(row(target), "drop", data); +} +async function edit() { await render(); await reply(0, initial()); await click("Move p/a down"); } + +// No sleeps, retries or real transport: each deferred settlement is explicitly released in act. +test("entering Custom reads a fresh GET each activation and only renders pickerAvailable", async () => { + await render("/a", ids, false); expect(requests).toHaveLength(0); + await render(); expect(requests.map(r => [r.url, r.method])).toEqual([["/a/api/subagent-models", "GET"]]); + expect(order()).toEqual([]); expect(busy.at(-1)).toBe(true); + await reply(0, { ...initial(), available: ["native", "other/roster-only"] }); + expect(order()).toEqual(["p/f", "p/a", "p/b", "p/c"]); expect(busy.at(-1)).toBe(false); + await render("/a", ids, false); await render(); expect(requests).toHaveLength(2); + await reply(1, { ...initial(), pickerOrder: ["p/c", "p/b", "p/a"] }); + expect(order()).toEqual(["p/f", "p/c", "p/b", "p/a"]); +}); + +for (const [name, override] of [ + ["missing", {}], ["null", { chosen: null }], ["non-array", { chosen: "p/f" }], ["invalid item", { chosen: [1] }], +] as const) test(`Custom cannot edit with ${name} chosen`, async () => { + await render(); + const { chosen: _chosen, ...settings } = initial(); + await reply(0, { ...settings, ...override }); + expect(order()).toEqual([]); expect(host.querySelector('[role="alert"]')).not.toBeNull(); + expect(button("Save draft").disabled).toBe(true); + await click("Save draft"); expect(requests).toHaveLength(1); +}); +test("saved bare native order remains locked without sending a replacement", async () => { + await render(); await reply(0, { ...initial(), pickerOrder: ["native", "p/a"] }); + expect(host.textContent).toContain("This saved order includes native models."); + expect(button("Save draft").disabled).toBe(true); expect(receipts).toEqual([]); + expect(requests.map(r => r.method)).toEqual(["GET"]); +}); + +test("forward/backward drop and Up/Down controls submit the complete routed list only", async () => { + await render(); await reply(0, initial()); + expect(button("Move p/f down").disabled).toBe(true); expect(button("Move p/a up").disabled).toBe(true); + await drop("p/a", "p/c"); expect(order()).toEqual(["p/f", "p/b", "p/a", "p/c"]); + await drop("p/c", "p/b"); expect(order()).toEqual(["p/f", "p/c", "p/b", "p/a"]); + button("Move p/c down").focus(); await click("Move p/c down"); + expect(order()).toEqual(["p/f", "p/b", "p/c", "p/a"]); + expect(document.activeElement).toBe(button("Move p/c down")); + await click("Move p/a up"); expect(order()).toEqual(changedDraft); + expect(host.querySelector('[role="status"]')?.textContent).toBe("p/a: position 3 of 4"); + await click("Save draft"); expect(requests.map(r => r.method)).toEqual(["GET", "GET"]); + await reply(1, initial()); + expect(requests[2]?.method).toBe("PUT"); + expect(requests[2]?.body).toEqual({ pickerOrder: changedDraft, pickerOrderMode: null }); +}); + +test("external, self, fixed and expired drag tokens cannot reorder", async () => { + await render(); await reply(0, initial()); + const original = ["p/f", "p/a", "p/b", "p/c"], external = transfer(); + external.setData("application/x-ocx-picker-order", "external"); + await dragEvent(row("p/b"), "drop", external); expect(order()).toEqual(original); + await drop("p/a", "p/a"); await drop("p/a", "p/f"); expect(order()).toEqual(original); + const local = transfer(); await dragEvent(button("Drag p/a"), "dragstart", local); + await dragEvent(row("p/b"), "drop", external); expect(order()).toEqual(original); + await dragEvent(row("p/b"), "drop", local); expect(order()).toEqual(original); + await dragEvent(button("Drag p/a"), "dragstart", local); + await dragEvent(row("p/a"), "dragend", local); + await dragEvent(row("p/c"), "drop", local); expect(order()).toEqual(original); +}); + +test("preflight roster drift blocks PUT, preserves draft, and requires explicit reload", async () => { + await edit(); await click("Save draft"); + const updated = { ...initial(), chosen: ["p/b"] }; + await reply(1, updated); + expect(order()).toEqual(changedDraft); expect(button("Save draft").disabled).toBe(true); + expect(host.textContent).toContain("Picker settings changed."); + await click("Save draft"); expect(requests.map(r => r.method)).toEqual(["GET", "GET"]); + await click("Reload and discard draft"); expect(order()).toEqual(changedDraft); + await reply(2, updated); expect(order()).toEqual(["p/b", "p/a", "p/c", "p/f"]); + expect(button("Move p/a down").disabled).toBe(false); expect(receipts).toEqual([]); +}); + +for (const failure of ["rejected", "malformed JSON", "malformed receipt", "network"] as const) + test(`failed PUT (${failure}) retains draft for a fresh preflight retry`, async () => { + await edit(); await click("Save draft"); await reply(1, initial()); + if (failure === "network") await act(async () => { requests[2]!.reject(new Error("offline")); }); + else if (failure === "malformed JSON") await act(async () => { requests[2]!.resolve(new Response("{")); }); + else await reply(2, failure === "rejected" ? { error: "refused" } : { ok: true, pickerOrder: [] }, failure === "rejected" ? 409 : 200); + expect(order()).toEqual(changedDraft); expect(receipts).toEqual([]); + expect(host.textContent).toContain("Request failed. Your draft is kept;"); + expect(button("Save draft").disabled).toBe(false); + await click("Save draft"); expect(requests[3]?.method).toBe("GET"); + await reply(3, initial()); expect(requests[4]?.body).toEqual({ pickerOrder: changedDraft, pickerOrderMode: null }); + }); + +test("pending accepted receipt publishes saved fields and requires reload before editing again", async () => { + await edit(); await click("Save draft"); await reply(1, initial()); + const accepted = { pickerOrder: changedDraft, pickerOrderMode: null, catalogRefresh: { status: "pending", degraded: true } }; + await reply(2, { ok: true, ...accepted, chosen: ["stale/receipt-choice"], pickerAvailable: ["stale/candidate"] }); + expect(receipts).toEqual([accepted]); expect(order()).toEqual(changedDraft); + expect(host.textContent).toContain("Order saved. Reload current settings before editing again."); + expect(button("Save draft").disabled).toBe(true); expect(button("Move p/a down").disabled).toBe(true); + expect(busy.at(-1)).toBe(false); expect(requests).toHaveLength(3); + await click("Reload and discard draft"); + await reply(3, { ...initial(), pickerOrder: changedDraft }); + expect(button("Move p/a down").disabled).toBe(false); +}); + +const stages = ["initial GET", "preflight GET", "preflight body", "PUT", "receipt body"] as const; +type Stage = typeof stages[number]; +async function pauseAt(stage: Stage): Promise<() => Promise> { + await render(); + if (stage === "initial GET") return () => reply(0, initial()); + await reply(0, initial()); await click("Move p/a down"); await click("Save draft"); + if (stage === "preflight GET") return () => reply(1, initial()); + if (stage !== "preflight body") await reply(1, initial()); + const accepted = { ok: true, pickerOrder: changedDraft, pickerOrderMode: null, catalogRefresh: { status: "pending" } }; + if (stage === "PUT") return () => reply(2, accepted); + const body = deferred(); let reads = 0; + const response = new Response(); + Object.defineProperty(response, "text", { value: () => { reads++; return body.promise; } }); + await act(async () => { requests[stage === "preflight body" ? 1 : 2]!.resolve(response); }); + expect(reads).toBe(1); // The deferred body is actually reached before changing owner/identity. + return async () => { await act(async () => { body.resolve(JSON.stringify(stage === "preflight body" ? initial() : accepted)); }); }; +} + +for (const stage of stages) { + test(`late ${stage} after unmount cannot write, publish a receipt or reset busy`, async () => { + const settle = await pauseAt(stage), count = requests.length; + await act(async () => { root!.unmount(); root = null; }); + const settledBusy = [...busy]; + expect(requests[count - 1]!.signal?.aborted).toBe(true); + await settle(); + expect(requests).toHaveLength(count); expect(receipts).toEqual([]); + expect(busy).toEqual(settledBusy); expect(host.textContent).toBe(""); + }); + test(`late ${stage} from API A→B→A cannot affect the new A flight`, async () => { + const settle = await pauseAt(stage); + await render("/b"); await render("/a"); + const count = requests.length, current = count - 1, settledBusy = [...busy]; + expect(requests[current]?.url).toBe("/a/api/subagent-models"); expect(busy.at(-1)).toBe(true); + expect(requests[current - 1]!.signal?.aborted).toBe(true); + await settle(); + expect(requests).toHaveLength(count); expect(receipts).toEqual([]); expect(order()).toEqual([]); + expect(busy).toEqual(settledBusy); // Old finally must not clear the successor's busy state. + await reply(current, { ...initial(), pickerOrder: ["p/c", "p/a", "p/b"] }); + expect(order()).toEqual(["p/f", "p/c", "p/a", "p/b"]); + }); + test(`identity drift during ${stage} suppresses stale snapshot, PUT and receipt publication`, async () => { + const settle = await pauseAt(stage), count = requests.length; + await render("/a", ids.map(row => row.id === "a" ? { ...row, id: "raw/a" } : row)); + await settle(); + expect(requests).toHaveLength(count); expect(receipts).toEqual([]); expect(busy.at(-1)).toBe(false); + expect(order()).toEqual(stage === "initial GET" ? [] : changedDraft); + expect(button("Save draft").disabled).toBe(true); + if (stage !== "initial GET") expect(host.textContent).toContain("Picker settings changed."); + // Reload, not the stale operation, is allowed to accept current identities. + await click("Reload and discard draft"); await reply(count, initial()); + expect(button("Move p/a down").disabled).toBe(false); + }); +} + + +for (const chosen of [[""], [" "]]) test(`blank chosen ${JSON.stringify(chosen)} keeps routed editing available`, async () => { + await render(); await reply(0, { ...initial(), chosen }); + expect(order()).toEqual(["p/a", "p/b", "p/c", "p/f"]); + expect(host.querySelector('[role="alert"]')).toBeNull(); + expect(button("Move p/f up").disabled).toBe(false); + await click("Move p/a down"); expect(button("Save draft").disabled).toBe(false); +}); + +for (const availability of ["absent", "throws"] as const) + test(`LAN drag with randomUUID ${availability}: same-editor works; cross-editor and stale tokens fail`, async () => { + Object.defineProperty(globalThis, "crypto", { configurable: true, value: availability === "absent" ? {} + : { randomUUID: () => { throw new Error("insecure context"); } } }); + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(host); + root.render({["left", "right"].map(name =>
+ +
)}
); + }); + await reply(requests.findIndex(r => r.url === "/left/api/subagent-models"), initial()); + await reply(requests.findIndex(r => r.url === "/right/api/subagent-models"), initial()); + const left = host.querySelector('[data-editor="left"]')!; + const right = host.querySelector('[data-editor="right"]')!; + const original = ["p/f", "p/a", "p/b", "p/c"], type = "application/x-ocx-picker-order"; + const leftDrag = transfer(), rightDrag = transfer(); + await dragEvent(button("Drag p/a", left), "dragstart", leftDrag); + await dragEvent(button("Drag p/a", right), "dragstart", rightDrag); + expect(leftDrag.getData(type)).not.toBe(""); + expect(leftDrag.getData(type)).not.toBe(rightDrag.getData(type)); + // Both editors have active local drags: rejection must compare identities, not just presence. + await dragEvent(row("p/c", right), "drop", leftDrag); expect(order(right)).toEqual(original); + await dragEvent(row("p/c", left), "drop", leftDrag); expect(order(left)).toEqual(changedDraft); + const fresh = transfer(); await dragEvent(button("Drag p/b", left), "dragstart", fresh); + expect(fresh.getData(type)).not.toBe(leftDrag.getData(type)); + await dragEvent(row("p/c", left), "drop", leftDrag); expect(order(left)).toEqual(changedDraft); + await dragEvent(row("p/c", left), "drop", fresh); expect(order(left)).toEqual(changedDraft); + const ended = transfer(); await dragEvent(button("Drag p/b", left), "dragstart", ended); + await dragEvent(row("p/b", left), "dragend", ended); + await dragEvent(row("p/c", left), "drop", ended); expect(order(left)).toEqual(changedDraft); + const retry = transfer(); await dragEvent(button("Drag p/a", right), "dragstart", retry); + await dragEvent(row("p/c", right), "drop", retry); expect(order(right)).toEqual(changedDraft); + expect(requests.map(r => r.method)).toEqual(["GET", "GET"]); expect(receipts).toEqual([]); + }); + + +test("fresh legacy featured settings cannot unlock a row missing from the model identity catalog", async () => { + const settings = { pickerAvailable: ["p/team-model", "p/a"], chosen: ["p/team/model"], pickerOrder: [], pickerOrderMode: null }; + const a = { provider: "p", id: "a", namespaced: "p/a" }; + await render("/a", [a]); await reply(0, settings); + expect(order()).toEqual([]); expect(button("Save draft").disabled).toBe(true); + expect(host.textContent).toContain("Reload the Models page to refresh its catalog"); + await click("Reload and discard draft"); await reply(1, settings); + expect(order()).toEqual([]); // Settings-only reload cannot repair a missing model catalog. + await render("/a", [a, { provider: "p", id: "team/model", namespaced: "p/team-model" }]); + await click("Reload and discard draft"); await reply(2, settings); + expect(order()).toEqual(["p/team-model", "p/a"]); + expect(button("Drag p/team-model").disabled).toBe(true); + expect(requests.map(r => r.method)).toEqual(["GET", "GET", "GET"]); +}); + +test("duplicate featured choices use last occurrence and padded roster strings do not lock rows", async () => { + await render(); await reply(0, { ...initial(), chosen: ["p/a", "p/b", "p/a", " p/c "] }); + expect(order()).toEqual(["p/b", "p/a", "p/c", "p/f"]); + expect(button("Drag p/b").disabled).toBe(true); expect(button("Drag p/a").disabled).toBe(true); + expect(button("Drag p/c").disabled).toBe(false); +}); + +test("Models pins cache-inferred Custom across late parent GET publication, then resets on API change", async () => { + const modelRows = ids.map(row => ({ ...row, disabled: false })); + const catalog = { models: modelRows, providers: [{ name: "p" }], selectedModels: {}, disabled: [], + contextCaps: {}, contextCapValue: 350_000 }; + const custom = { ...initial(), pickerOrder: ["p/c", "p/a", "p/f", "p/b"] }; + for (const base of ["/a", "/b"]) { + win.sessionStorage.setItem(`ocx.models.catalog.v1:${base}`, JSON.stringify(catalog)); + win.sessionStorage.setItem(`ocx.models.catalog.v1:${base}:picker-order`, JSON.stringify(base === "/a" ? custom + : { ...initial(), pickerOrder: [] })); + } + const deferredFetch = globalThis.fetch; + Object.defineProperty(globalThis, "fetch", { configurable: true, value: (input: RequestInfo | URL, init?: RequestInit) => { + const path = String(input); + if (path.endsWith("/api/subagent-models")) return deferredFetch(input, init); + const payload = path.endsWith("/api/models") ? modelRows + : path.endsWith("/api/providers") ? catalog.providers + : path.endsWith("/api/provider-context-caps") ? { caps: {} } + : path.endsWith("/api/selected-models") ? { selected: {} } + : path.endsWith("/api/aliases") ? { providers: {}, models: {}, defaults: { global: false, providers: {} } } + : undefined; + return Promise.resolve(payload === undefined ? new Response(null, { status: 404 }) : Response.json(payload)); + } }); + const { createRoot } = await import("react-dom/client"); + await act(async () => { root = createRoot(host); root.render(); }); + // Parent resource and editor have separate initial reads; resolve both without relying on effect order. + const initialReads = requests.map((request, index) => ({ request, index })); + expect(initialReads).toHaveLength(2); + for (const { index } of initialReads) await reply(index, custom); + expect(order()).toEqual(["p/f", "p/c", "p/a", "p/b"]); + await click("Move p/a down"); const editor = host.querySelector(".picker-order-editor"); + expect(order()).toEqual(["p/f", "p/c", "p/b", "p/a"]); expect(button("Save draft").disabled).toBe(false); + // Integration seam: publish the same parent resource state a late GET would install. + const late = deferred(); + const publication = late.promise.then(value => setClientResourceData("ocx.models.catalog.v1:/a:picker-order", value)); + await act(async () => { late.resolve({ ...initial(), pickerOrderMode: "provider" }); await publication; }); + expect(host.querySelector(".picker-order-editor")).toBe(editor); + expect(order()).toEqual(["p/f", "p/c", "p/b", "p/a"]); expect(button("Save draft").disabled).toBe(false); + expect(requests.every(r => r.method === "GET")).toBe(true); + await act(async () => { root!.render(); }); + expect(host.querySelector(".picker-order-editor")).toBeNull(); +}); diff --git a/gui/tests/model-picker-order.test.ts b/gui/tests/model-picker-order.test.ts index 29c72c0b16..50f79d0b15 100644 --- a/gui/tests/model-picker-order.test.ts +++ b/gui/tests/model-picker-order.test.ts @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; import { summarizeUsage } from "../../src/usage/summary"; import type { PersistedUsageEntry } from "../../src/usage/log"; -import { isModelPickerUsage, isPickerOrderSaved, isPickerOrderSettings, modelPickerOrder, modelPickerOrderMode } from "../src/model-picker-order"; +import { pickerIdentityCoverage, customPickerRows, normalizePickerIds, pickerSnapshotSignature, movePickerBefore, stepPickerOrder, isModelPickerUsage, isPickerOrderSaved, isPickerOrderSettings, modelPickerOrder, modelPickerOrderMode } from "../src/model-picker-order"; const models = ["zeta/beta", "alpha/zeta", "alpha/alpha"]; @@ -77,3 +77,110 @@ test("real mixed-resolved usage summary never credits an entire legacy bucket to expect(modelPickerOrder("most-used", ["p/c", "p/b", "p/a"], summary.models)) .toEqual(["p/a", "p/b", "p/c"]); }); + + +test("Custom normalizes exact canonical names before provider/raw aliases, without native guesses", () => { + const identities = [ + { provider: "p", id: "team/model", namespaced: "p/team-model" }, + { provider: "p", id: "collision", namespaced: "p/a" }, + { provider: "p", id: "collision", namespaced: "p/b" }, + ]; + expect(normalizePickerIds(["p/team/model", "p/collision", "native", "p/team-model"], + ["p/team-model", "p/a", "p/b"], identities)).toEqual(["p/team-model"]); + expect(normalizePickerIds(["p/team/model"], ["p/team/model", "p/team-model"], identities)).toEqual(["p/team/model"]); +}); + +test("featured rank wins, survivors retain saved order, newcomers follow GET candidate order", () => { + expect(customPickerRows({ pickerAvailable: ["p/new", "p/b", "p/a", "p/top", "p/b"], + chosen: ["native", "p/top", "p/a", "missing/model"], pickerOrder: ["gone/model", "p/b", "p/a"], pickerOrderMode: null, + }, ["new", "b", "a", "top"].map(id => ({ provider: "p", id, namespaced: `p/${id}` })))).toEqual({ fixed: ["p/top", "p/a"], order: ["p/top", "p/a", "p/b", "p/new"] }); + expect(customPickerRows({ pickerAvailable: [], chosen: [], pickerOrder: [], pickerOrderMode: null }, [])) + .toEqual({ fixed: [], order: [] }); +}); + +test("unknown chosen cannot edit; malformed supplied chosen rejects; native saved ids remain untouched", () => { + const settings = { pickerAvailable: ["p/a"], pickerOrder: ["native", "p/a"], pickerOrderMode: null }; + expect(isPickerOrderSettings(settings)).toBe(true); + expect(customPickerRows(settings, [])).toBeNull(); + expect(customPickerRows({ ...settings, chosen: [] }, [])).toBeNull(); + expect(settings.pickerOrder).toEqual(["native", "p/a"]); + expect(customPickerRows({ ...settings, pickerOrder: [] }, [])).toBeNull(); + for (const chosen of [null, undefined, "p/a", [2]]) expect(isPickerOrderSettings({ ...settings, chosen })).toBe(false); + expect(isPickerOrderSettings({ ...settings, chosen: [] })).toBe(true); +}); + +test("snapshot binds base, activation, candidate sequence, chosen, saved order and provenance", () => { + const settings = { pickerAvailable: ["p/b", "p/a"], chosen: [], pickerOrder: ["p/a"], pickerOrderMode: null }; + const expected = '["/a",7,["p/b","p/a"],[],["p/a"],null]'; + expect(pickerSnapshotSignature("/a", 7, settings)).toBe(expected); + expect(pickerSnapshotSignature("/b", 7, settings)).not.toBe(expected); + expect(pickerSnapshotSignature("/a", 9, settings)).not.toBe(expected); // A → B → A + for (const changed of [ + { ...settings, pickerAvailable: ["p/a", "p/b"] }, { ...settings, chosen: ["p/a"] }, + { ...settings, pickerOrder: [] }, { ...settings, pickerOrderMode: "provider" as const }, + { pickerAvailable: settings.pickerAvailable, pickerOrder: settings.pickerOrder, pickerOrderMode: null }, + ]) expect(pickerSnapshotSignature("/a", 7, changed)).not.toBe(expected); +}); + +test("drop-before re-finds target after removal, while keyboard Down swaps adjacent movable rows", () => { + const order = ["p/featured", "p/a", "p/b", "p/c"], fixed = ["p/featured"]; + expect(movePickerBefore(order, "p/a", "p/c", fixed)).toEqual(["p/featured", "p/b", "p/a", "p/c"]); + expect(movePickerBefore(order, "p/c", "p/a", fixed)).toEqual(["p/featured", "p/c", "p/a", "p/b"]); + expect(movePickerBefore(order, "p/a", "p/b", fixed)).toEqual(order); + expect(stepPickerOrder(order, "p/a", 1, fixed)).toEqual(["p/featured", "p/b", "p/a", "p/c"]); + expect(stepPickerOrder(order, "p/c", -1, fixed)).toEqual(["p/featured", "p/a", "p/c", "p/b"]); + for (const [source, target] of [["outside", "p/a"], ["p/a", "outside"], ["p/a", "p/a"], ["p/featured", "p/b"], ["p/b", "p/featured"]]) + expect(movePickerBefore(order, source!, target!, fixed)).toEqual(order); + expect(stepPickerOrder(order, "p/a", -1, fixed)).toEqual(order); + expect(stepPickerOrder(order, "p/c", 1, fixed)).toEqual(order); + expect(order).toEqual(["p/featured", "p/a", "p/b", "p/c"]); +}); + + +test("blank roster strings retain GET compatibility and preset provenance without becoming featured rows", () => { + for (const blank of ["", " "]) { + const settings = { pickerAvailable: models, chosen: [blank], pickerOrder: ["alpha/alpha", "alpha/zeta", "zeta/beta"], + pickerOrderMode: "provider" as const }; + expect(isPickerOrderSettings(settings)).toBe(true); + expect(normalizePickerIds(settings.chosen, models, [])).toEqual([]); + const identities = [{ provider: "alpha", id: "alpha", namespaced: "alpha/alpha" }, + { provider: "alpha", id: "zeta", namespaced: "alpha/zeta" }, { provider: "zeta", id: "beta", namespaced: "zeta/beta" }]; + expect(customPickerRows(settings, identities)).toEqual({ fixed: [], order: ["alpha/alpha", "alpha/zeta", "zeta/beta"] }); + expect(modelPickerOrderMode(models, settings.pickerOrder, settings.pickerOrderMode)).toBe("provider"); + expect(modelPickerOrder("alphabetical", settings.pickerAvailable)).toEqual(["alpha/alpha", "zeta/beta", "alpha/zeta"]); + expect(settings.chosen).toEqual([blank]); // Normalization must not rewrite the saved roster. + expect(isPickerOrderSettings({ ...settings, pickerOrder: [""] })).toBe(false); + expect(isPickerOrderSettings({ ...settings, pickerAvailable: [" "] })).toBe(false); + } + expect(normalizePickerIds(["", " ", "alpha/zeta"], models, [])).toEqual(["alpha/zeta"]); +}); + + +test("incomplete or ambiguous catalog identities block projection, even with canonical candidates", () => { + const settings = { pickerAvailable: ["p/team-model", "p/a"], chosen: ["p/team/model"], pickerOrder: [], pickerOrderMode: null }; + const team = { provider: "p", id: "team/model", namespaced: "p/team-model" }; + const a = { provider: "p", id: "a", namespaced: "p/a" }; + for (const identities of [[], [a], [team], [team, a, { ...team, namespaced: "p/a" }], + [team, a, { ...team, id: "team-model" }]]) { + expect(pickerIdentityCoverage(settings.pickerAvailable, identities)).toBe(false); + expect(customPickerRows(settings, identities)).toBeNull(); + } + expect(pickerIdentityCoverage(settings.pickerAvailable, [team, a, { ...team }])).toBe(true); + expect(customPickerRows(settings, [team, a])).toEqual({ fixed: ["p/team-model"], order: ["p/team-model", "p/a"] }); +}); + +test("featured ranks use last duplicate, exact canonical precedence, and untrimmed roster strings", () => { + const identities = [{ provider: "p", id: "team/model", namespaced: "p/team-model" }, + { provider: "p", id: "a", namespaced: "p/a" }, { provider: "p", id: "b", namespaced: "p/b" }]; + const settings = { pickerAvailable: ["p/team-model", "p/a", "p/b"], pickerOrder: [], pickerOrderMode: null }; + expect(customPickerRows({ ...settings, chosen: ["p/a", "p/b", "p/a"] }, identities)) + .toEqual({ fixed: ["p/b", "p/a"], order: ["p/b", "p/a", "p/team-model"] }); + expect(customPickerRows({ ...settings, chosen: ["p/team/model", "p/b", "p/team-model"] }, identities)) + .toEqual({ fixed: ["p/b", "p/team-model"], order: ["p/b", "p/team-model", "p/a"] }); + expect(customPickerRows({ ...settings, chosen: ["p/team-model", "p/b", "p/team/model"] }, identities)) + .toEqual({ fixed: ["p/team-model", "p/b"], order: ["p/team-model", "p/b", "p/a"] }); + const chosen = [" p/a ", "", " "]; + expect(customPickerRows({ ...settings, chosen, pickerOrder: [" p/a "] }, identities)) + .toEqual({ fixed: [], order: ["p/a", "p/team-model", "p/b"] }); + expect(chosen).toEqual([" p/a ", "", " "]); +}); From dd8fb50b5e15ace4204ec7aa4ffb0d02df293c94 Mon Sep 17 00:00:00 2001 From: t Date: Mon, 7 Sep 2026 21:46:20 +0900 Subject: [PATCH 076/116] fix(gui): reconcile picker lifecycle outside synchronous effects [skip ci] Keep cancellation and stale-response fencing while separating render state reconciliation from automatic transport startup. Preserve immediate user actions and cover unmount before automatic request issuance. Co-authored-by: leonclab <26379556+leonclab@users.noreply.github.com> --- gui/src/components/ModelPickerOrderEditor.tsx | 61 ++++++++++++------- gui/tests/model-picker-order-editor.test.tsx | 18 ++++++ 2 files changed, 58 insertions(+), 21 deletions(-) diff --git a/gui/src/components/ModelPickerOrderEditor.tsx b/gui/src/components/ModelPickerOrderEditor.tsx index 3c379f8cce..1ca60c96b1 100644 --- a/gui/src/components/ModelPickerOrderEditor.tsx +++ b/gui/src/components/ModelPickerOrderEditor.tsx @@ -35,34 +35,48 @@ export default function ModelPickerOrderEditor({ apiBase, active, identities, on const [announcement, setAnnouncement] = useState(""); const [dragging, setDragging] = useState(null); const [over, setOver] = useState(null); - const drag = useRef<{ id: string; token: string } | null>(null); - const generation = useRef(0); - const flight = useRef(null); + const lifetime = useRef({ + generation: 0, + flight: null as BoundedFetch | null, + drag: null as { id: string; token: string } | null, + }); + const [activation, setActivation] = useState({ apiBase, active, onBusyChange }); const identitySignature = JSON.stringify(identities.map(({ provider, id, namespaced }) => [provider, id, namespaced])); const latestIdentitySignature = useRef(identitySignature); useLayoutEffect(() => { latestIdentitySignature.current = identitySignature; }, [identitySignature]); const identityChanged = snapshot !== null && snapshot.identities !== identitySignature; const disabled = !active || busy || !snapshot || blocked !== null || identityChanged; const dirty = snapshot !== null && JSON.stringify(draft) !== JSON.stringify(snapshot.order); - const clearDrag = useCallback(() => { drag.current = null; setDragging(null); setOver(null); }, []); + const clearDrag = useCallback(() => { lifetime.current.drag = null; setDragging(null); setOver(null); }, []); - // Layout cleanup fences even A → B → A and unmount before a pending promise resumes. + // Reconcile before committing children, like the existing display-name dialog. + if (activation.apiBase !== apiBase || activation.active !== active || activation.onBusyChange !== onBusyChange) { + setActivation({ apiBase, active, onBusyChange }); + setSnapshot(null); setDraft([]); setBlocked(null); setError(false); setBusy(false); + } + const [dragContext, setDragContext] = useState({ disabled, snapshot, identitySignature }); + if (dragContext.disabled !== disabled || dragContext.snapshot !== snapshot || dragContext.identitySignature !== identitySignature) { + setDragContext({ disabled, snapshot, identitySignature }); + setDragging(null); setOver(null); + } + + // Capture the stable holder, but always abort its CURRENT flight during cleanup. useLayoutEffect(() => { - generation.current++; - setSnapshot(null); setDraft([]); setBlocked(null); setError(false); + const holder = lifetime.current; + holder.generation++; return () => { - generation.current++; - flight.current?.controller.abort(); flight.current?.clear(); flight.current = null; - drag.current = null; onBusyChange(false); + holder.generation++; + holder.flight?.controller.abort(); holder.flight?.clear(); holder.flight = null; + holder.drag = null; onBusyChange(false); }; }, [apiBase, active, onBusyChange]); - useEffect(() => { clearDrag(); }, [disabled, snapshot, identitySignature, clearDrag]); + useLayoutEffect(() => { lifetime.current.drag = null; }, [disabled, snapshot, identitySignature]); const run = async (save: boolean) => { - if (!active || flight.current || (save && (disabled || !dirty))) return; - const owner = generation.current, bounded = createBoundedFetch(15_000); - flight.current = bounded; setBusy(true); onBusyChange(true); setError(false); clearDrag(); - const owns = () => generation.current === owner && flight.current === bounded; + if (!active || lifetime.current.flight || (save && (disabled || !dirty))) return; + const owner = lifetime.current.generation, bounded = createBoundedFetch(15_000); + lifetime.current.flight = bounded; setBusy(true); onBusyChange(true); setError(false); clearDrag(); + const owns = () => lifetime.current.generation === owner && lifetime.current.flight === bounded; const current = () => owns() && !bounded.signal.aborted && latestIdentitySignature.current === identitySignature; try { @@ -102,11 +116,16 @@ export default function ModelPickerOrderEditor({ apiBase, active, identities, on // Current-identity timeouts surface an error; stale identities retain the draft silently. } finally { bounded.clear(); - if (owns()) { flight.current = null; setBusy(false); onBusyChange(false); } + if (owns()) { lifetime.current.flight = null; setBusy(false); onBusyChange(false); } } }; - const enter = useEffectEvent(() => { void run(false); }); - useEffect(() => { if (active) enter(); }, [apiBase, active]); + const enter = useEffectEvent(async () => { + const holder = lifetime.current, owner = holder.generation; + // Automatic startup is cancellable before issuing transport; event actions stay immediate. + await Promise.resolve(); + if (active && holder.generation === owner) void run(false); + }); + useEffect(() => { if (active) void enter(); }, [apiBase, active, onBusyChange]); const move = (id: string, next: string[]) => { if (disabled) return; @@ -125,13 +144,13 @@ export default function ModelPickerOrderEditor({ apiBase, active, identities, on const fixed = snapshot?.fixed.includes(id) === true; return
  • { - if (!drag.current || drag.current.id === id || !movable(drag.current.id) || !movable(id) + if (!lifetime.current.drag || lifetime.current.drag.id === id || !movable(lifetime.current.drag.id) || !movable(id) || !event.dataTransfer.types.includes(DRAG_TYPE)) return; event.preventDefault(); event.dataTransfer.dropEffect = "move"; setOver(id); }} onDragLeave={() => setOver(null)} onDrop={event => { - const source = drag.current; + const source = lifetime.current.drag; if (source && source.id !== id && source.token === event.dataTransfer.getData(DRAG_TYPE) && movable(source.id) && movable(id)) { event.preventDefault(); move(source.id, movePickerBefore(draft, source.id, id, snapshot?.fixed ?? [])); } @@ -141,7 +160,7 @@ export default function ModelPickerOrderEditor({ apiBase, active, identities, on aria-label={t("models.pickerOrder.dragModel", { model: id })} onDragStart={event => { if (!movable(id)) { event.preventDefault(); return; } - const token = newDragToken(); drag.current = { id, token }; setDragging(id); + const token = newDragToken(); lifetime.current.drag = { id, token }; setDragging(id); event.dataTransfer.effectAllowed = "move"; event.dataTransfer.setData(DRAG_TYPE, token); }}>