Skip to content
Merged
Prev Previous commit
Next Next commit
fix(codex): write top-level keys before tables so model_provider is read
config.toml was assembled by appending model/model_provider at the END
of the file — after the user's existing [windows]/[marketplaces] tables.
In TOML a bare key after a [table] header belongs to that table, so
model_provider got silently nested under the last table and Codex never
saw it, falling back to provider "openai" (hence the login prompt).

Rewrite the assembler to split existing content into top-level keys vs.
table blocks and emit ALL top-level keys first, then tables, then our
provider table. Also de-dupe managed keys a previous buggy write left in
the table region. Verified live: Codex now shows provider:
copilot-reverse and connects to the local worker.

Co-Authored-By: Claude <noreply@anthropic.com>
  • Loading branch information
wangcansunking and claude committed Jun 26, 2026
commit c60d487354d0e4d0124e4d49907ab2be6ae77e85
47 changes: 33 additions & 14 deletions src/tui/setup/codex-toml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,26 +22,39 @@ export function applyCodexToml(opts: CodexTomlOpts): { path: string; changed: st
const path = codexTomlPath(opts.home);
if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true });

// Read existing top-level lines, dropping our managed keys and any prior managed provider table,
// but keeping everything else (approval_policy, other providers, etc.) verbatim.
// Parse existing content into top-level (pre-table) bare keys vs. table blocks, dropping our
// managed keys and any prior managed provider table. We MUST keep top-level keys and tables
// separate: in TOML a bare `key = value` after a `[table]` header belongs to that table, so
// appending our `model_provider` at the end (after the user's [windows]/[marketplaces] tables)
// silently nested it under the last table — Codex then couldn't see it and fell back to "openai".
const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
const kept: string[] = [];
let inOurTable = false;
const keptTopKeys: string[] = []; // bare key=value lines before any table
const keptTables: string[] = []; // everything from the first [table] onward (preserved verbatim)
let inTable = false; // have we passed the first table header?
let inOurTable = false; // are we inside our own [model_providers.copilot-reverse] block?
for (const line of existing.split(/\r?\n/)) {
const tableMatch = /^\s*\[/.test(line);
if (tableMatch) inOurTable = line.trim() === `[model_providers.${PROVIDER_ID}]`;
if (inOurTable) continue; // skip our previously-written provider table
if (/^\s*\[/.test(line)) {
inTable = true;
inOurTable = line.trim() === `[model_providers.${PROVIDER_ID}]`;
}
if (inOurTable) continue; // skip our previously-written provider table entirely
const keyMatch = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
if (keyMatch && MANAGED_TOP_KEYS.includes(keyMatch[1])) continue; // skip our managed top keys
kept.push(line);
// Drop our managed top keys wherever they appear. They belong at the top level, but a previous
// buggy version wrote them AFTER tables (where TOML nests them) — so filter them in the table
// region too, otherwise the rewrite would duplicate them.
if (keyMatch && MANAGED_TOP_KEYS.includes(keyMatch[1])) continue;
(inTable ? keptTables : keptTopKeys).push(line);
}

const head = kept.join("\n").replace(/\n{3,}/g, "\n\n").trim();
const managed = [
// Reassemble in valid TOML order: ALL top-level keys (ours + the user's) first, then all table
// blocks (the user's preserved tables, then our managed provider table last).
const topKeys = [
`model = "${opts.model}"`,
`model_provider = "${PROVIDER_ID}"`,
...(opts.contextWindow ? [`model_context_window = ${opts.contextWindow}`] : []),
"",
...keptTopKeys.filter((l) => l.trim()), // the user's other top-level keys (approval_policy, etc.)
];
const ourTable = [
`[model_providers.${PROVIDER_ID}]`,
`name = "copilot-reverse"`,
`base_url = "${opts.baseUrl}"`,
Expand All @@ -51,9 +64,15 @@ export function applyCodexToml(opts: CodexTomlOpts): { path: string; changed: st
// .env), so we embed the placeholder directly — the worker ignores the key value anyway.
`requires_openai_auth = false`,
`experimental_bearer_token = "${opts.apiKey ?? "copilot-reverse-local"}"`,
].join("\n");
];
const userTables = keptTables.join("\n").replace(/\n{3,}/g, "\n\n").trim();
const managed = [
topKeys.join("\n"),
...(userTables ? [userTables] : []),
ourTable.join("\n"),
].join("\n\n");

const body = (head ? `${head}\n\n` : "") + managed + "\n";
const body = managed + "\n";
writeFileSync(path, body);
return { path, changed: MANAGED_TOP_KEYS };
}
31 changes: 31 additions & 0 deletions tests/tui/codex-toml.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,37 @@ describe("applyCodexToml", () => {
expect(toml).toContain('experimental_bearer_token = "copilot-reverse-local"');
});

it("places top-level keys BEFORE any table (TOML: a bare key after [table] belongs to that table)", () => {
const home = tmp();
mkdirSync(join(home, ".codex"), { recursive: true });
// Pre-existing config that has tables (like a real ~/.codex/config.toml with [marketplaces] etc).
writeFileSync(codexTomlPath(home), '[windows]\nsandbox = "unelevated"\n\n[tui.x]\na = 1\n');
applyCodexToml({ home, baseUrl: "http://127.0.0.1:7891/openai", model: "gpt-5.5", contextWindow: 1_050_000 });
const toml = readFileSync(codexTomlPath(home), "utf8");
const lines = toml.split("\n");
const providerLine = lines.findIndex((l) => /^model_provider\s*=/.test(l));
const firstTable = lines.findIndex((l) => /^\s*\[/.test(l));
// model_provider must be a TRUE top-level key — appear before the first [table], else Codex
// parses it into that table and falls back to provider "openai".
expect(providerLine).toBeGreaterThanOrEqual(0);
expect(firstTable).toBeGreaterThanOrEqual(0);
expect(providerLine).toBeLessThan(firstTable);
// pre-existing table content is still preserved
expect(toml).toContain('sandbox = "unelevated"');
});

it("de-duplicates managed keys left in the table region by a previous buggy write", () => {
const home = tmp();
mkdirSync(join(home, ".codex"), { recursive: true });
// Simulate the old broken output: managed keys sitting AFTER a table (TOML-nested).
writeFileSync(codexTomlPath(home), '[windows]\nsandbox = "x"\n\nmodel = "old"\nmodel_provider = "old-prov"\n');
applyCodexToml({ home, baseUrl: "http://x/openai", model: "gpt-5.5" });
const toml = readFileSync(codexTomlPath(home), "utf8");
expect(toml.match(/^model_provider = /gm)?.length).toBe(1); // exactly one, at the top
expect(toml.match(/^model = /gm)?.length).toBe(1);
expect(toml).not.toContain('"old-prov"'); // stale value gone
});

it("preserves unrelated existing keys and is idempotent", () => {
const home = tmp();
mkdirSync(join(home, ".codex"), { recursive: true });
Expand Down
Loading