Skip to content

Commit e618338

Browse files
committed
fix(codex): hold selection ownership through dashboard feature toggles
1 parent 8e58c96 commit e618338

7 files changed

Lines changed: 103 additions & 23 deletions

File tree

‎docs-site/src/content/docs/fr/reference/configuration/agents.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ L’API de gestion expose `GET`/`PUT /api/v2`, `/api/injection-model`, `/api/eff
3434

3535
La page Codex Auth permet également de modifier l’indicateur natif `default_mode_request_user_input` de Codex (`GET`/`PUT /api/codex-auth/features/default-mode-request-user-input`). Son activation ajoute `[features] default_mode_request_user_input = true` au fichier `$CODEX_HOME/config.toml` de Codex au moyen de la commande officielle `codex features enable|disable`. Cette modification préserve le format du fichier et est retirée lorsque l’option est désactivée. Codex peut ainsi suspendre une session en mode Default et vous poser des questions avec l’outil `request_user_input`. Cet indicateur est encore en développement en amont et ne s’applique qu’aux nouvelles sessions ; l’activation échoue explicitement si la version installée de Codex ne le reconnaît pas encore.
3636

37+
Pendant qu’une mise à jour de Codex CLI détient l’installation, cette commande renvoie HTTP 503 avec `codex_cli_selection_busy` et `retryable: true` avant toute exécution. Réessayez après la mise à jour ; les erreurs d’écriture de la configuration restent des réponses 502.
38+
3739
## Liste des modèles et consignes
3840

3941
La liste v2 effective comprend, parmi les modèles configurés, les cinq premiers qui sont visibles dans le sélecteur, classés par priorité, compatibles avec v2 et présents dans le catalogue injecté. Un modèle est admissible en v2 si son choix imposé en amont vaut explicitement `"v2"`, vaut `null` ou est absent. Un véritable choix `"v1"` l’exclut. Les entrées exclues restent dans la configuration afin de pouvoir redevenir admissibles ultérieurement.

‎docs-site/src/content/docs/reference/configuration/agents.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,8 @@ Default-mode session and ask you questions with the `request_user_input` tool. T
115115
flag is under development upstream and only applies to new sessions; the toggle fails
116116
loudly when the installed Codex build does not know the flag yet.
117117

118+
While a Codex CLI update owns the installation, the toggle returns retryable HTTP 503 (`codex_cli_selection_busy`) before running the feature command. Retry after the update finishes; config-write failures still return 502.
119+
118120
## Roster and guidance
119121

120122
The effective v2 roster is the configured, picker-visible, priority-sorted first five models that

‎docs-site/src/content/docs/tr/reference/configuration/agents.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ kaldırılır), bu da Codex'in bir Varsayılan mod oturumunu duraklatmasına ve
6464
akışta geliştirilme aşamasındadır ve yalnızca yeni oturumlara uygulanır; yüklü
6565
Codex derlemesi bayrağı henüz tanımadığında anahtar yüksek sesle başarısız olur.
6666

67+
Codex CLI güncellemesi kurulumu kullanırken özellik komutu çalıştırılmadan önce `codex_cli_selection_busy` ve `retryable: true` ile HTTP 503 döner. Güncelleme bitince yeniden deneyin; yapılandırma yazma hataları 502 döndürmeye devam eder.
68+
6769
## Kadro ve rehberlik
6870

6971
Geçerli v2 kadrosu, yapılandırılmış, seçicide görünen, önceliğe göre sıralanmış,

‎src/server/management/agent-settings-routes.ts‎

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -562,35 +562,38 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
562562
const body = parsedBody as { enabled?: unknown };
563563
if (typeof body.enabled !== "boolean") return jsonResponse({ error: "body.enabled must be a boolean" }, 400);
564564
const { isDefaultModeRequestUserInputEnabled, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, activeCodexConfigPath } = await import("../../codex/features");
565-
const before = isDefaultModeRequestUserInputEnabled();
566-
let toggle = deps.toggleDefaultModeRequestUserInput;
567-
if (!toggle) {
568-
try {
569-
const { codexFeaturesInvocationAsync, runCodexFeaturesCommand } = await import("../../cli/v2");
570-
const action = body.enabled ? "enable" : "disable";
571-
const invocation = await codexFeaturesInvocationAsync(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, process.platform, { requireAvailable: true });
572-
toggle = (_enabled, env, validate) => runCodexFeaturesCommand(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, env, validate, invocation);
573-
} catch (error) {
574-
return jsonResponse({ error: `default_mode_request_user_input toggle failed: ${error instanceof Error ? error.message : String(error)}` }, 502);
565+
const selectionWrite = await beginCodexCliSelectionParentWriteAsync({ signal: req.signal });
566+
if (!selectionWrite.entered) return jsonResponse({ error: "codex_cli_selection_busy", retryable: true }, 503);
567+
try {
568+
const before = isDefaultModeRequestUserInputEnabled();
569+
let toggle = deps.toggleDefaultModeRequestUserInput;
570+
if (!toggle) {
571+
try {
572+
const { codexFeaturesInvocation, runCodexFeaturesCommand } = await import("../../cli/v2");
573+
const action = body.enabled ? "enable" : "disable";
574+
const invocation = selectionWrite.commit(() => codexFeaturesInvocation(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, process.platform, { requireAvailable: true }));
575+
toggle = (_enabled, env, validate) => runCodexFeaturesCommand(action, DEFAULT_MODE_REQUEST_USER_INPUT_FEATURE_KEY, env, validate, invocation);
576+
} catch (error) {
577+
if (error instanceof CodexCliSelectionMutationBusyError) throw error;
578+
return jsonResponse({ error: `default_mode_request_user_input toggle failed: ${error instanceof Error ? error.message : String(error)}` }, 502);
579+
}
575580
}
576-
}
577-
// The `codex features` subprocess rewrites config.toml itself — run it
578-
// under the shared write lock so it cannot interleave with an opencodex
579-
// scalar edit or injection mid-write on either side.
580-
const { acquireConfigWriteLock, releaseConfigWriteLock, configWriteLockFailureMessage, runConfigWriteChild, ConfigWriteDestinationChanged } = await import("../../codex/config-write-lock");
581-
const configPath = activeCodexConfigPath();
582-
// Preserve native home creation only after executable resolution succeeds.
583-
prepareCodexHome(dirname(configPath));
584-
{
581+
// Keep selection ownership across the config-lock await and the whole
582+
// synchronous child execution: an updater must not replace this command.
583+
const { acquireConfigWriteLock, releaseConfigWriteLock, configWriteLockFailureMessage, runConfigWriteChild, ConfigWriteDestinationChanged } = await import("../../codex/config-write-lock");
584+
const configPath = activeCodexConfigPath();
585+
// Preserve native home creation only after executable resolution succeeds.
586+
selectionWrite.commit(() => prepareCodexHome(dirname(configPath)));
585587
const configLock = await acquireConfigWriteLock(configPath);
586588
if (!configLock.ok) {
587589
return jsonResponse({ error: configWriteLockFailureMessage(configLock), retryable: configLock.error === "locked" }, 502);
588590
}
589591
let toggleError: string | null = null;
590592
let destinationChanged = false;
591593
try {
592-
runConfigWriteChild(configPath, configLock.handle, (env, validate) => toggle!(body.enabled as boolean, env, validate));
594+
selectionWrite.commit(() => runConfigWriteChild(configPath, configLock.handle, (env, validate) => toggle!(body.enabled as boolean, env, validate)));
593595
} catch (error) {
596+
if (error instanceof CodexCliSelectionMutationBusyError) throw error;
594597
destinationChanged = error instanceof ConfigWriteDestinationChanged;
595598
const err = error as { stderr?: unknown; message?: string };
596599
const raw = err.stderr;
@@ -613,7 +616,7 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise<Re
613616
warnings.push("Applies to new sessions; restart the Codex app or wait out its picker cache to see the change.");
614617
}
615618
return jsonResponse({ ok: true, enabled, changed: enabled !== before, warnings });
616-
}
619+
} finally { selectionWrite.exit(); }
617620
}
618621

619622
// Subagent prompt injection model: single native or routed model whose info is

‎structure/codex-cli-update.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ retain their synchronous leaf contracts; the nonblocking guarantee covers recove
413413
machine API, restart and Remote Workspace callers use the async
414414
entry points. Runtime publication rechecks selection inputs, cache epoch, cancellation and caller
415415
currentness after recovery. Codex feature-setting callers acquire admission before their synchronous
416-
transition; management keeps the lease across config-root hardening, then rechecks its mode plan and
416+
transition; management also holds it across single-feature command preparation, config-lock waits and child execution, and across config-root hardening, then rechecks its mode plan and
417417
commits in the existing no-await callback. Refusal precedes combined setting writes and returns a
418418
retryable `codex_cli_selection_busy` response. Diagnostics classify a held async parent by its exact
419419
buffer and owner, so it cannot appear as a retained Worker. Portable gate/caller regressions and

‎structure/gui-and-management-api.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ per-request first-party callback reads that live object; a failed write leaves i
271271

272272
| Endpoint area | Responsibility |
273273
| --- | --- |
274-
| Config/settings | Reasoning retention follows the [panel and settings contract](dashboard-and-usage.md). Read safe config/settings views; mutate supported settings only. Full `PUT /api/config` is disabled so masked secrets are not round-tripped. `PUT /api/settings` accepts `codexAutoStart`, `streamMode`, integer `appOwnedMemoryBudgetMb` (64..4096), strict boolean `codexAccountPickerEnabled`, strict boolean `fastRows`, and a validated per-account `codexQuotaAutoRefresh` toggle (each optional, at least one required). `fastRows` defaults on when absent: false is persisted, true deletes the key, and successful writes echo the effective boolean. An effective change converges the Codex catalog and refreshes enabled or already-owned client integrations after persistence. Picker enable initializes an empty UI-managed selector map, persists before one bounded catalog convergence, and reports only `catalogRefreshPending`; allocation/save failure restores every touched live field and skips convergence. Budget changes synchronously enforce the process-wide evictable retained-state cap; this is separate from RSS/native memory. `streamMode` persists the #314 stream-shape selection in config.json (Windows services need persisted input; macOS eager relay is explicit-only). |
274+
| Config/settings | Reasoning retention follows the [panel and settings contract](dashboard-and-usage.md). Read safe config/settings views; mutate supported settings only. Full `PUT /api/config` is disabled so masked secrets are not round-tripped. `PUT /api/settings` accepts `codexAutoStart`, `streamMode`, integer `appOwnedMemoryBudgetMb` (64..4096), strict boolean `codexAccountPickerEnabled`, strict boolean `fastRows`, and a validated per-account `codexQuotaAutoRefresh` toggle (each optional, at least one required). `fastRows` defaults on when absent: false is persisted, true deletes the key, and successful writes echo the effective boolean. An effective change converges the Codex catalog and refreshes enabled or already-owned client integrations after persistence. Picker enable initializes an empty UI-managed selector map, persists before one bounded catalog convergence, and reports only `catalogRefreshPending`; allocation/save failure restores every touched live field and skips convergence. Budget changes synchronously enforce the process-wide evictable retained-state cap; this is separate from RSS/native memory. `streamMode` persists the #314 stream-shape selection in config.json (Windows services need persisted input; macOS eager relay is explicit-only). Single native feature toggles retain Codex selection admission from command preparation through config-lock waiting and child completion; updater contention returns retryable 503 before the child runs. |
275275
| Startup safety | `GET /api/startup-health` reports whether injected Codex routing is restart-safe, with secret-free service/shim diagnostics. `POST /api/startup-action` provides allowlisted one-click installation for the background service or launcher shim. On Windows a healthy script shim is CLI-only; Codex Desktop requires the background service for full protection. Optional Codex compatibility uses the [confirmed local runtime](clients/codex-desktop.md#optional-compatibility-runtime), [machine-local dashboard consent](clients/codex-desktop.md#dashboard-controls), and [revision-bound next-start preference with shared awaited teardown](clients/codex-desktop.md#proxy-startup-preference); saving that preference performs no runtime action. |
276276
| Windows tray | `GET/POST /api/windows-tray` controls an owned, per-user HKCU login tray. The tray delegates fixed actions to the CLI and is never a proxy supervisor or restart-protection signal. |
277277
| Updates | `GET /api/update/check`, `POST /api/update/run`, and `GET /api/update/status` own dashboard self-update state. A launched worker PID is persisted in `update-job.json`; dead PIDs recover immediately when a new run starts, and `GET /api/update/status` already reports such a record as `failed` without writing it (`readUpdateJobForStatus`), while legacy active records without a PID recover only after ten minutes. Live PIDs remain exclusive regardless of record age. `GET /api/update/check` and `POST /api/update/run` await one per-channel asynchronous registry lookup and write successful results through to the package cache; run passes that result to the job starter. `GET /api/update/badge` only reads the cache and reports unknown after 40 hours, on missing cache, or on channel mismatch. The badge links to the update surface rather than gating other actions. `GET /api/update/badge?surface=desktop&session=<id>` projects only that process-local Tauri session; missing or expired state is unknown and never falls back to the package cache. `POST /api/update/desktop-snapshot` is a 1 KiB bounded display-state mutation with no install permission. It accepts the existing admin-token principal or a dedicated single-use, ten-second snapshot capability bound to nonce, method, path, PID, port and the SHA-256 digest of the exact body bytes; that capability cannot authorize another route. |

‎tests/codex-integration/codex-cli-update-parent-async.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ import { createCodexCliRecoveryTestHome } from "../helpers/codex-cli-recovery-ho
1313
import { trustWindowsTempFixtureAncestry } from "../helpers/windows-temp-ancestry";
1414
import { removeTreeWithRetry } from "../helpers/remove-tree";
1515
import { catalogConvergenceFactory } from "../helpers/catalog-convergence";
16+
import * as configWriteLock from "../../src/codex/config-write-lock";
17+
import { handleAgentSettingsRoutes } from "../../src/server/management/agent-settings-routes";
18+
import type { ManagementContext } from "../../src/server/management/context";
1619

1720
let home: string;
1821
let saved: Record<string, string | undefined>;
@@ -244,6 +247,74 @@ for (const outcome of ["allow", "deny", "plan-changed", "cancel"] as const) test
244247
} finally { proof.resolve(true); await pending; }
245248
});
246249

250+
function featureToggleFixture(signal?: AbortSignal) {
251+
process.env.CODEX_HOME = join(home, "codex");
252+
mkdirSync(process.env.CODEX_HOME);
253+
const path = join(process.env.CODEX_HOME, "config.toml");
254+
const original = "[features]\ndefault_mode_request_user_input = false\n";
255+
writeFileSync(path, original);
256+
const url = new URL("http://localhost/api/codex-auth/features/default-mode-request-user-input");
257+
const req = new Request(url, { method: "PUT", signal,
258+
headers: { "content-type": "application/json" }, body: JSON.stringify({ enabled: true }) });
259+
return { path, original, req, url };
260+
}
261+
function callFeatureToggle(f: ReturnType<typeof featureToggleFixture>, toggle: NonNullable<ManagementContext["deps"]["toggleDefaultModeRequestUserInput"]>) {
262+
return handleAgentSettingsRoutes({ req: f.req, url: f.url, config: { providers: [] } as unknown as OcxConfig,
263+
deps: { toggleDefaultModeRequestUserInput: toggle }, version: "test", trustedLoopbackIngress: true,
264+
guiSessionIssuance: null, convergeCodexCatalog: async () => { throw new Error("unexpected catalog convergence"); },
265+
syncClaudeAgentDefsBestEffort: async () => {} });
266+
}
267+
268+
test("single feature toggle refuses a held update gate before any child runs", async () => {
269+
const f = featureToggleFixture(); let children = 0;
270+
const worker = gate.createWorkerCommitWindow({ gate: gate.codexCliUpdateSelectionGate(), fence: gate.createCodexCliUpdateFence() });
271+
expect(worker.tryEnter()).toBe(true);
272+
try {
273+
const response = await callFeatureToggle(f, () => { children++; writeFileSync(f.path, f.original.replace("false", "true")); });
274+
expect(response?.status).toBe(503);
275+
expect(await response!.json()).toMatchObject({ error: "codex_cli_selection_busy", retryable: true });
276+
expect(children).toBe(0);
277+
expect(readFileSync(f.path, "utf8")).toBe(f.original);
278+
expect(gate.codexCliSelectionGateState()).toBe("worker_commit");
279+
} finally { worker.exit(); }
280+
});
281+
282+
for (const outcome of ["success", "child-failure", "cancel", "lock-failure"] as const) {
283+
test(`single feature toggle holds selection across config-lock wait and releases after ${outcome}`, async () => {
284+
const controller = new AbortController(); const f = featureToggleFixture(controller.signal);
285+
spies.push(spyOn(recovery, "codexCliUpdateRecoveryBlocksAdmissionAsync").mockResolvedValue(false));
286+
const reached = deferred<void>(), release = deferred<void>();
287+
const acquire = configWriteLock.acquireConfigWriteLock;
288+
spies.push(spyOn(configWriteLock, "acquireConfigWriteLock").mockImplementation(async (...args) => {
289+
reached.resolve(); await release.promise;
290+
return outcome === "lock-failure" ? { ok: false as const, error: "locked" as const } : acquire(...args);
291+
}));
292+
let children = 0, childGate = ""; let workerEntered = false;
293+
const worker = gate.createWorkerCommitWindow({ gate: gate.codexCliUpdateSelectionGate(), fence: gate.createCodexCliUpdateFence() });
294+
const pending = callFeatureToggle(f, () => {
295+
children++; childGate = gate.codexCliSelectionGateState();
296+
workerEntered = worker.tryEnter(); if (workerEntered) worker.exit();
297+
if (outcome === "child-failure") throw new Error("fixture child failure");
298+
writeFileSync(f.path, f.original.replace("false", "true"));
299+
});
300+
try {
301+
await reached.promise;
302+
expect(gate.codexCliSelectionGateState()).toBe("parent_write");
303+
const entered = worker.tryEnter(); if (entered) worker.exit();
304+
expect(entered).toBe(false);
305+
if (outcome === "cancel") controller.abort();
306+
release.resolve();
307+
const response = await pending;
308+
expect(response?.status).toBe(outcome === "success" ? 200 : outcome === "cancel" ? 503 : 502);
309+
expect(children).toBe(outcome === "cancel" || outcome === "lock-failure" ? 0 : 1);
310+
if (children) { expect(childGate).toBe("parent_write"); expect(workerEntered).toBe(false); }
311+
expect(readFileSync(f.path, "utf8")).toBe(outcome === "success" ? f.original.replace("false", "true") : f.original);
312+
expect(existsSync(f.path + ".ocx-write.lock")).toBe(false);
313+
expect(free()).toBe(true);
314+
} finally { release.resolve(); await pending; worker.exit(); }
315+
});
316+
}
317+
247318
const native = process.platform === "win32" && process.arch === "x64" ? test : test.skip;
248319
async function nativeTerminalStore() {
249320
await hardenSecretDirAsync(home, { required: true });

0 commit comments

Comments
 (0)