codex: a setting for which client the requests to ChatGPT say they come from, CLI or Codex Desktop (ouhthuo on X)

ouhthuo wants the originator "Codex Desktop", with which, they say, a
high-effort gpt-6.1-sol request is routed to a newer model. magpie sent
codex_cli_rs on every request, and codexSign even overwrote a real Desktop's
own originator.

Settings > Codex > "Codex client" (CLI, the default, or Codex Desktop; the
settings key codexClient is "" or "desktop", POST /api/settings/codex-client,
no free text). codexClientHeaders is the one place that sets originator and
User-Agent, so the model requests, the /wham usage and reset calls, the token
refresh, the device and code sign-in exchanges and "test as" all follow it.
Desktop sends originator "Codex Desktop" and the UA shape codex-rs builds for
it: Codex Desktop/<codex version> (<os>; <arch>) unknown (Codex Desktop; <app
build>). Source: codex-rs login/src/auth/default_client.rs and a captured
Desktop UA. The default is unchanged; base_instructions and the identity
prompt are untouched. The OAuth authorize URL keeps codex_cli_rs.

The row sits in the Codex agent preferences, 5 languages. The two Codex menu
buttons share one helper (codexMenuPick) so app.js stays inside its budget
without raising it.

Run (mote): TestCodexClientSetting (red with codexClientHeaders ignoring the
setting), settings, settingsapi, gui and provider Codex tests ok; gofmt clean;
go vet darwin, windows and linux nogui clean; GUI codex-client,
codex-service-tier, codex-open-button, i18n-keys, i18n-en-no-cjk,
settings-general, click-scroll in chromium and webkit ok. Real Codex account
in a sandbox HOME: gpt-6.1-sol and gpt-6-sol at high effort answer under both
identities with identical usage; the reply's model field only echoes the
requested name, so whether the served model differs can't be told from here.
Red and not mine, already filed: settings-search (#6133, #5982) and
agent-prefs "Settings line" (#6139) fail on origin/main, TestMoveToPlugin
#5524.

Not tried: the real Desktop app (not installed here); the app build number
in the UA is the newest seen in local logs and can go stale.
This commit is contained in:
yetone
2026-11-13 01:17:30 +08:00
parent b4821050a8
commit 35aaaa4b94
14 changed files with 312 additions and 26 deletions
+1
View File
@@ -256,6 +256,7 @@ recorded as a prediction failure (`noPrediction`).
- An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`.
- A group's member may be Ultrafast as well as fast (`Group.Ultra`, a subset of `Fast`, `Group.SetMemberTier`; the member's button steps Standard speed, Fast, Ultrafast where `ultraOK`; `ultra=` in `magpie group`), and a model has its own speed (`settings.ModelTiers`, "<provider>/<model>" to `priority` or `ultrafast`, `provider.SetModelTier`, Model settings and `magpie model tier`; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (`provider.ModelTier`, the branch after `IsFastPick`), through the same `fastPick`, so an account without Ultrafast is sent `priority`. A group member goes as the group says. `TestModelTierSentToEveryAgent`, `TestGroupMemberUltrafast`, `model-speed.test.cjs`.
- Codex's service tier (`settings.CodexServiceTier`, a row in Codex's settings, JackyFill on X) sets the `service_tier` of every request of Codex's, whatever Codex's own `/fast` asked: empty is as Codex asks (the default, nothing changed), `default` sends none (standard), `priority` is Codex's Fast and `ultrafast` its Ultra Fast (the request values in Codex's `ServiceTier`; Flex is not offered, since the ChatGPT backend's requests drop it in `codex_request.go`). `codexTiered` ([`codex_tier.go`](../../internal/gateway/codex_tier.go)) rewrites the body as it comes in, on both of Codex's ways in: `codexBackend` (Codex signed in, `/backend-api/codex`) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (`tierMate`) or sent `priority`, and a provider that refuses a tier drops it. A model with no provider (`gpt-…`, Codex's own sign-in, whose plan magpie doesn't know) is sent `ultrafast` only where one of magpie's Codex accounts lists it on the model (`UltraModels`), else `priority`. Another agent's request is never touched, and fast picks still apply after. `TestCodexServiceTierSet`, `codex-service-tier.test.cjs`.
- The Codex client magpie presents to the ChatGPT backend (`settings.CodexClient`, a row in Codex's settings, ouhthuo on X) is Codex CLI by default (`originator: codex_cli_rs`, `User-Agent: codex_cli_rs/<ver> (<os>; <arch>) <terminal>`) or `desktop`: `originator: Codex Desktop` and `Codex Desktop/<ver> (<os>; <arch>) unknown (Codex Desktop; <app build>)`, as codex-rs `default_client.rs` builds it from the originator the app sets. Only these two values are accepted. `codexClientHeaders` in `internal/provider/codex_request.go` is the one place both headers are set, so a model request (`codexSign`), the account calls (`/wham`, resets, token refresh, device sign-in) and a test asked as Codex all follow it; the sign-in's authorize URL keeps `codex_cli_rs`. A real Codex client's own originator never reaches the backend on a signed-in account: `codexSign` replaces it, which this setting now chooses.
- A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`.
- What the vendor read from its cache reaches the agent in the names its SDK reads, not only the record. A relayed Chat reply whose usage tells the cache in another vendor's names (a relay's Anthropic `cache_read_input_tokens` and `cache_creation_input_tokens`, DeepSeek's `prompt_cache_hit_tokens` or Moonshot's top-level `cached_tokens` beside a 0 in `prompt_tokens_details`) is told in OpenAI's too, streamed (`chatTidy`) and whole (`chatWhole`), by `openAIUsage` in [`chattidy.go`](../../internal/gateway/chattidy.go): `prompt_tokens_details.cached_tokens` (and `cache_write_tokens`), with `prompt_tokens` and `total_tokens` made to hold the cached part where the vendor left it out. Every other field stays, and a usage already in OpenAI's names, or with no cache, goes byte for byte; one in OpenAI's names alone isn't even decoded (`mayMendUsage`). pi-ai, which DeepSeek Harness and Pi use, reads `prompt_tokens_details.cached_tokens` first, a 0 there too, and maps no Anthropic names at all, so such a relay showed DSH 缓存命中 0% while magpie had counted the hit (B3TT3R on Discord asked; DeepSeek's own API sends both names and was already read right). Relayed Responses and Messages replies, translated replies and a plugin's need nothing: their usage is written in the agent's own names. `TestAgentReadsCacheTokensOnEveryRoute`, `TestPluginAgentReadsCacheTokens`, `TestOpenAIUsageLeavesOpenAIsAlone`, `TestMayMendUsageOnlyOtherNames` in [`usage_cache_agent_test.go`](../../internal/gateway/usage_cache_agent_test.go).
- A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying "<provider> refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes.
+14
View File
@@ -2199,6 +2199,20 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, settingsState())
})
// the Codex client magpie presents to the ChatGPT backend: "" (Codex
// CLI) or "desktop" (ouhthuo on X)
mux.HandleFunc("POST /api/settings/codex-client", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ Client string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if err := provider.SetCodexClient(in.Client); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
// what the Open button of Codex's Agents row opens: "", "app" or
// "terminal" (Yink88564391 on X)
mux.HandleFunc("POST /api/settings/codex-open", func(rw http.ResponseWriter, r *http.Request) {
+18 -24
View File
@@ -21186,7 +21186,7 @@ function renderAlerts(s, keep) {
// AGENT_PREFS: an agent's own settings rows, by its id (openAgentPrefs)
const AGENT_PREFS = {
codex: ["codexAgentsV1Row", "codexOpenRow", "codexSubagentModelRow", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"],
codex: ["codexAgentsV1Row", "codexOpenRow", "codexSubagentModelRow", "codexServiceTierRow", "codexClientRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"],
claude: ["fullContextRow"],
grok: ["fullContextRow"],
};
@@ -21270,6 +21270,7 @@ function renderAgentPrefs() {
homeAgentPrefRows();
// what each row does, in its tooltip (#2120)
for (const [row, en] of [
["#codexClientRow", "Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app"],
["#codexServiceTierRow", "Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none"],
["#codexTitlesRow", "Names each thread in a hidden request of its own; same as the session, it goes on the session’s model, as Codex sends it when that is one of Codex’s own"],
["#codexDescriptionsRow", "Writes each thread’s short description in a hidden request of its own; same as the session, it goes on the session’s model, as Codex sends it when that is one of Codex’s own"],
@@ -21327,6 +21328,7 @@ function renderAgentPrefs() {
if (held.length) box.append(el("div", "hint codex-async-held", codexHeld(held)));
$("#codexAsyncSegs").replaceChildren(box);
renderCodexServiceTier(s);
renderCodexClient(s);
renderCodexOpen(s);
renderCodexTitles(s);
renderCodexDescriptions(s);
@@ -21413,39 +21415,31 @@ const CODEX_TIERS = [
{ v: "priority", name: "Fast", note: "priority" },
{ v: "ultrafast", name: "Ultrafast", note: "ultrafast" },
];
function renderCodexServiceTier(s) {
const v = s.codexServiceTier || "";
const cur = CODEX_TIERS.find((o) => o.v === v) || CODEX_TIERS[0];
const b = el("button", "rt-cond on");
function renderCodexServiceTier(s) { codexMenuPick(CODEX_TIERS, s.codexServiceTier, "Codex service tier", "codexServiceTier", "tier"); }
// a Codex row's button: the choice made, and the app's menu to change it,
// posted on its own to settings/<path> as {<field>: value}
function codexMenuPick(opts, v, label, key, field) {
const cur = opts.find((o) => o.v === (v || "")) || opts[0];
const b = el("button", "rt-cond on", t(cur.name));
b.type = "button";
b.setAttribute("aria-label", t("Codex service tier"));
b.setAttribute("aria-label", t(label));
b.setAttribute("aria-haspopup", "menu");
b.append(el("span", "", t(cur.name)));
b.onclick = (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
openProtoMenu(b, CODEX_TIERS, cur.v, (tier) => {
if (tier === cur.v) return;
prefWrite(api("settings/codex-service-tier", { tier }));
}, "Codex service tier", "sess-menu");
openProtoMenu(b, opts, cur.v, (x) => x !== cur.v && prefWrite(api("settings/" + key.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()), { [field]: x })), label, "sess-menu");
};
$("#codexServiceTierPick").replaceChildren(b);
$("#" + key + "Pick").replaceChildren(b);
}
// the Codex magpie presents to ChatGPT (ouhthuo on X)
const CODEX_CLIENTS = [{ v: "", name: "Codex CLI" }, { v: "desktop", name: "Codex Desktop" }];
function renderCodexClient(s) { codexMenuPick(CODEX_CLIENTS, s.codexClient, "Codex client", "codexClient", "client"); }
// what Codex's Open button opens (Yink88564391 on X)
const CODEX_OPENS = [{ v: "", name: "Automatic" }, { v: "app", name: "Codex app" }, { v: "terminal", name: "Terminal" }];
function renderCodexOpen(s) {
const cur = CODEX_OPENS.find((o) => o.v === (s.codexOpen || "")) || CODEX_OPENS[0];
const b = el("button", "rt-cond on", t(cur.name));
b.type = "button";
b.setAttribute("aria-label", t("Open Codex with"));
b.onclick = (e) => {
e.stopPropagation();
if (b.classList.contains("open")) return closeProtoMenu();
openProtoMenu(b, CODEX_OPENS, cur.v, (open) => open !== cur.v && prefWrite(api("settings/codex-open", { open })), "Open Codex with", "sess-menu");
};
$("#codexOpenPick").replaceChildren(b);
}
function renderCodexOpen(s) { codexMenuPick(CODEX_OPENS, s.codexOpen, "Open Codex with", "codexOpen", "open"); }
// Codex's descriptions: as sent, off, or a model
function renderCodexDescriptions(s) { codexSidePick(s, "codexDescriptions", "Codex thread descriptions", "no description, nothing sent", "codex-descriptions"); }
+16
View File
@@ -30,6 +30,10 @@ const I18N = {
"/fast in Codex": "Codex 里的 /fast",
"Standard": "标准",
"Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Codex 发出的每个请求都走这个层级,不管 Codex 里的 /fast 怎么设;套餐没有极速时按快速发",
"Codex client": "Codex 客户端",
"Codex CLI": "Codex 命令行",
"Codex Desktop": "Codex 桌面版",
"Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "发往 ChatGPT 账号的请求自称是哪个 Codex:命令行或桌面版应用",
"Check-in time": "签到时间",
"From {at} each day, for every vendor's check-in": "每天 {at} 起签到,所有服务商的签到都按这个时间",
"As soon as each vendor's day starts": "每个服务商的新一天一开始就签到",
@@ -5173,6 +5177,10 @@ const I18N = {
"/fast in Codex": "Codex 裡的 /fast",
"Standard": "標準",
"Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Codex 送出的每個請求都走這個層級,不論 Codex 裡的 /fast 怎麼設;方案沒有極速時按快速送出",
"Codex client": "Codex 用戶端",
"Codex CLI": "Codex 命令列",
"Codex Desktop": "Codex 桌面版",
"Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "送往 ChatGPT 帳號的請求自稱是哪個 Codex:命令列或桌面版應用程式",
"Check-in time": "簽到時間",
"From {at} each day, for every vendor's check-in": "每天 {at} 起簽到,所有服務商的簽到都按這個時間",
"As soon as each vendor's day starts": "每個服務商的新一天一開始就簽到",
@@ -10301,6 +10309,10 @@ const I18N = {
"/fast in Codex": "Codex の /fast",
"Standard": "標準",
"Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Codex が送るすべてのリクエストをこのティアで送ります。Codex の /fast の設定は問いません。プランに超高速がなければ高速で送ります",
"Codex client": "Codex クライアント",
"Codex CLI": "Codex CLI",
"Codex Desktop": "Codex Desktop",
"Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "ChatGPT アカウントへのリクエストが名乗る Codex:CLI またはデスクトップアプリ",
"Check-in time": "チェックインの時刻",
"From {at} each day, for every vendor's check-in": "毎日 {at} からチェックイン(すべてのサービスのチェックインに共通)",
"As soon as each vendor's day starts": "各サービスの日付が変わったらすぐにチェックイン",
@@ -15431,6 +15443,10 @@ const I18N = {
"/fast in Codex": "/fast in Codex",
"Standard": "Standard",
"Every request Codex sends goes at this tier, whatever /fast is set to in Codex; Ultrafast goes as Fast where the plan has none": "Jede Anfrage von Codex geht in dieser Stufe, egal wie /fast in Codex steht; Ultrafast geht als Schnell, wo der Tarif es nicht hat",
"Codex client": "Codex-Client",
"Codex CLI": "Codex CLI",
"Codex Desktop": "Codex Desktop",
"Which Codex requests to your ChatGPT accounts say they come from: the CLI or the desktop app": "Als welches Codex sich Anfragen an ChatGPT-Konten ausgeben: CLI oder Desktop-App",
"Check-in time": "Check-in-Zeit",
"From {at} each day, for every vendor's check-in": "Täglich ab {at}, für den Check-in jedes Anbieters",
"As soon as each vendor's day starts": "Sobald der Tag des jeweiligen Anbieters beginnt",
+4
View File
@@ -576,6 +576,10 @@
<div class="who"><div class="name" data-t>Codex service tier</div></div>
<div class="val" id="codexServiceTierPick"></div>
</div>
<div class="row pref" id="codexClientRow">
<div class="who"><div class="name" data-t>Codex client</div></div>
<div class="val" id="codexClientPick"></div>
</div>
<div class="row pref" id="codexTitlesRow">
<div class="who"><div class="name" data-t>Codex thread titles</div></div>
<div class="val" id="codexTitlesPick"></div>
+1
View File
@@ -176,6 +176,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
CodexAutoReview: "fake/m1",
CodexSubagentModel: "codex/gpt-6-astra",
CodexServiceTier: "priority",
CodexClient: "desktop",
CodexOpen: "terminal",
DesktopSubagentModel: "fake/m2",
DesktopGateway: "https://192.168.1.20:3425",
+1 -1
View File
@@ -20,7 +20,7 @@ const { chromium, webkit } = require("playwright");
const { watchSettingsReads, agentRow, openAgentSettings } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const CODEX = ["codexAgentsV1Row", "codexOpenRow", "codexServiceTierRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"];
const CODEX = ["codexAgentsV1Row", "codexOpenRow", "codexServiceTierRow", "codexClientRow", "fullContextRow", "codexAsyncRow", "codexTitlesRow", "codexDescriptionsRow", "codexPredictionsRow", "codexAutoReviewRow", "codexMemoriesRow"];
function settingsPayload(over) {
return {
+128
View File
@@ -0,0 +1,128 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Codex magpie presents to ChatGPT (ouhthuo on X): a row in Codex's
// settings on the Agents page. Its button says the choice, "Codex CLI" by
// default; the app's menu (no native select) offers Codex CLI and Codex
// Desktop, and a pick posts settings/codex-client on its own: "" or
// "desktop". Every language, Chromium and WebKit, a wide and a narrow
// window; no backend, the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const { watchSettingsReads, agentRow, openAgentSettings } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
function server(lang, posted) {
let cur = { theme: "light", lang, version: "0.1.400", titleModels: [], codexClient: "" };
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:false};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
// agents below Codex, so its opened row is not the list's end: a choice
// that rewraps its row at the very bottom must move the list
if (url.pathname === "/api/state") return json({ agents: [agentRow("codex", "Codex"), agentRow("claude", "Claude Code"), agentRow("pi", "Pi"), agentRow("opencode", "OpenCode"), agentRow("gemini", "Gemini CLI"), agentRow("kimi", "Kimi CLI"), agentRow("droid", "Droid"), agentRow("cline", "Cline"), agentRow("qwen", "Qwen Code"), agentRow("crush", "Crush")], profiles: [], settings: { lang, theme: "light" } });
if (url.pathname === "/api/settings/codex-client") {
const body = req.postDataJSON();
posted.push(["codex-client", body]);
cur = { ...cur, codexClient: body.client };
return json(cur);
}
if (url.pathname === "/api/settings") {
if (req.method() === "POST") posted.push(["settings", req.postDataJSON()]);
return json(cur);
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
try {
await route.fulfill({ body: await fs.readFile(file), contentType });
} catch {
await route.fulfill({ status: 404, body: "" });
}
};
}
// the words as i18n.js has them
const W = {
en: { name: "Codex client", cli: "Codex CLI", desktop: "Codex Desktop" },
zh: { name: "Codex 客户端", cli: "Codex 命令行", desktop: "Codex 桌面版" },
"zh-TW": { name: "Codex 用戶端", cli: "Codex 命令列", desktop: "Codex 桌面版" },
ja: { name: "Codex クライアント", cli: "Codex CLI", desktop: "Codex Desktop" },
de: { name: "Codex-Client", cli: "Codex CLI", desktop: "Codex Desktop" },
};
const engines = process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"];
const langs = process.env.LANGS ? process.env.LANGS.split(",") : Object.keys(W);
for (const engine of engines) {
for (const lang of langs) {
for (const width of [900, 400]) {
test(`${engine} ${lang} ${width}px: the Codex client is picked from the app menu in its settings`, async (t) => {
const w = W[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 720 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posted = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posted));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-codex-client.png`) });
}
await browser.close();
});
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=agents");
await openAgentSettings(page);
const row = page.locator('.row.agent[data-id="codex"] #codexClientRow');
const pick = page.locator("#codexClientPick button");
await pick.waitFor();
assert.equal((await row.locator(".name").textContent()).trim(), w.name);
assert.equal((await pick.textContent()).trim(), w.cli, "Codex CLI by default");
assert.equal(await page.locator("select").count(), 0, "a native select");
// only Codex's settings have it
await page.locator('.row.agent[data-id="claude"] .ag-link').click();
await page.locator('.row.agent[data-id="claude"] .ag-prefs').waitFor();
assert.equal(await page.locator('.row.agent[data-id="claude"] #codexClientRow').count(), 0, "the row in Claude Code's settings");
await openAgentSettings(page);
await pick.waitFor();
await pick.scrollIntoViewIfNeeded();
const box = await pick.boundingBox();
assert(box && box.x >= 0 && box.x + box.width <= width, `the button runs off the window: ${JSON.stringify(box)}`);
assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth), "the page scrolls sideways");
// where the button sits on screen: a pick that moved the page would
// move it. At a narrow width the row rewraps as the choice's words
// change (the button under the name or beside it), which moves the
// button with no scroll at all, so it is held to its place only
// while the row keeps its height.
const top = () => pick.evaluate((b) => Math.round(b.getBoundingClientRect().top));
const tall = () => row.evaluate((r) => Math.round(r.getBoundingClientRect().height));
for (const [label, client] of [[w.desktop, "desktop"], [w.cli, ""]]) {
const y = await top(), h = await tall();
await pick.click();
const menu = page.locator(".proto-menu");
await menu.waitFor();
const items = (await menu.locator(".pm-item .pm-name").allTextContents()).map((s) => s.trim());
assert.deepEqual(items, [w.cli, w.desktop]);
const mb = await menu.boundingBox();
assert(mb.x >= 0 && mb.x + mb.width <= width, `the menu runs off the window: ${JSON.stringify(mb)}`);
await menu.locator(".pm-item").filter({ has: page.locator(".pm-name", { hasText: new RegExp("^" + label + "$") }) }).click();
await page.locator("#codexClientPick button", { hasText: new RegExp("^\\s*" + label + "\\s*$") }).waitFor();
assert.deepEqual(posted.at(-1), ["codex-client", { client }]);
await page.waitForTimeout(200);
if (await tall() === h) assert(Math.abs((await top()) - y) <= 1, `picking ${label} moved the button from ${y} to ${await top()}`);
}
assert.equal(posted.length, 2, JSON.stringify(posted));
assert.deepEqual(errors, []);
});
}
}
}
+32
View File
@@ -60,11 +60,43 @@ func codexSign(token func(context.Context) (tok, accountID string, err error)) f
// sent with). The ChatGPT account's own calls that aren't a model's
// (/wham/usage, the reset credits, the token refresh) went with Go's
// User-Agent and no originator, unlike any request Codex makes.
//
// Which Codex that is is settings.CodexClient's: Codex CLI by default, the
// Codex app when the user chose it (ouhthuo on X: the backend routes some
// models by the client's originator).
func codexClientHeaders(h http.Header, ver string) {
if CodexClient() == "desktop" {
h.Set("originator", codexDesktopOriginator)
h.Set("User-Agent", codexDesktopUserAgent(ver))
return
}
h.Set("originator", "codex_cli_rs")
h.Set("User-Agent", codexUserAgent(ver))
}
// codexDesktopOriginator is the originator the Codex app gives
// (set_default_originator, which codex-rs login/src/auth/default_client.rs
// turns into the first word of the User-Agent as well); its threads record
// the same name.
const codexDesktopOriginator = "Codex Desktop"
// codexDesktopBuild is the app's own version, the last part of the
// User-Agent it sends, from the app's logs (26.1026.10807 is the newest
// build seen); its codex-rs version is ver.
const codexDesktopBuild = "26.1026.10807"
// codexDesktopUserAgent is the User-Agent the Codex app of codex-rs version
// v sends: "Codex Desktop/0.166.0 (Mac OS 26.6.0; arm64) unknown (Codex
// Desktop; 26.1026.10807)". The terminal is "unknown" on every system,
// since the app has none.
func codexDesktopUserAgent(v string) string {
ua := codexUserAgent(v)
if i := strings.Index(ua, ") "); i >= 0 {
ua = ua[:i+2]
}
return codexDesktopOriginator + strings.TrimPrefix(ua, "codex_cli_rs") + "unknown (" + codexDesktopOriginator + "; " + codexDesktopBuild + ")"
}
// codexAccountHeaders are the headers of a call Codex makes about the
// ChatGPT account (its /wham reads): the account it is about and
// codexClientHeaders. Codex sends no version header with them.
+55
View File
@@ -6,6 +6,7 @@ import (
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"testing"
@@ -408,3 +409,57 @@ func TestCodexInputDropsStatusWithID(t *testing.T) {
}
}
}
// The Codex client magpie presents is the user's choice (ouhthuo on X): Codex
// CLI unless "desktop" is set, and then the Codex app's originator and
// User-Agent on a model request and on the account calls alike (/wham, the
// token refresh), and as a test is asked as Codex asks. Anything else is
// refused, and read as Codex CLI from a file edited by hand.
func TestCodexClientSetting(t *testing.T) {
signIn(t)
p, _ := find(All(), "codex")
sign := func() http.Header {
t.Helper()
req, _ := http.NewRequest("POST", p.Responses+"/responses", nil)
if err := p.Sign(context.Background(), req, Responses, []byte(`{"prompt_cache_key":"thread-1"}`)); err != nil {
t.Fatal(err)
}
return req.Header
}
cli := func(h http.Header) bool {
return h.Get("originator") == "codex_cli_rs" && strings.HasPrefix(h.Get("User-Agent"), "codex_cli_rs/0.")
}
if h := sign(); !cli(h) {
t.Fatalf("by default: %v", h)
}
for _, bad := range []string{"Codex Desktop", "codex_cli_rs", "evil", "desktop2"} {
if err := SetCodexClient(bad); err == nil {
t.Errorf("%q was accepted", bad)
}
}
if err := SetCodexClient("desktop"); err != nil {
t.Fatal(err)
}
h := sign()
if h.Get("originator") != "Codex Desktop" || !regexp.MustCompile(`^Codex Desktop/0\.\d+[^ ]* \([^;]+; [^)]+\) unknown \(Codex Desktop; \d+\.\d+\.\d+\)$`).MatchString(h.Get("User-Agent")) {
t.Fatalf("as the Codex app: %v", h)
}
if h.Get("version") == "" || h.Get("session-id") != "thread-1" || h.Get("chatgpt-account-id") != "acct-1" {
t.Fatalf("the rest of the headers: %v", h)
}
acct := codexAccountHeaders("acct-1")
if acct["Originator"] != "Codex Desktop" || !strings.HasPrefix(acct["User-Agent"], "Codex Desktop/") {
t.Fatalf("an account call: %v", acct)
}
asked := http.Header{}
clientHeaders(ClientCodex, asked)
if asked.Get("originator") != "Codex Desktop" || !strings.HasPrefix(asked.Get("User-Agent"), "Codex Desktop/") {
t.Fatalf("a test asked as Codex: %v", asked)
}
if err := SetCodexClient(""); err != nil {
t.Fatal(err)
}
if h := sign(); !cli(h) {
t.Fatalf("back to the default: %v", h)
}
}
+26
View File
@@ -48,3 +48,29 @@ func SetCodexOpen(v string) error {
s.CodexOpen = v
return settings.Save(s)
}
// CodexClient is the Codex client magpie presents to the ChatGPT backend
// (settings.CodexClient): "" for Codex CLI, "desktop" for the Codex app. A
// value this magpie doesn't know (a newer one's, a file edited by hand) is
// read as "" and changes nothing.
func CodexClient() string {
v := strings.TrimSpace(heldSettings().CodexClient)
if !slices.Contains(settings.CodexClients, v) {
return ""
}
return v
}
// SetCodexClient sets settings.CodexClient.
func SetCodexClient(v string) error {
v = strings.TrimSpace(v)
if !slices.Contains(settings.CodexClients, v) {
return fmt.Errorf("the Codex client must be one of %q, not %q", settings.CodexClients[1:], v)
}
s := settings.Load()
if s.CodexClient == v {
return nil
}
s.CodexClient = v
return settings.Save(s)
}
+2 -1
View File
@@ -210,7 +210,8 @@ func clientHeaders(client string, h http.Header) {
shape := clientShape(client)
if shape == nil && client == ClientCodex {
v := codexVersion()
shape = http.Header{"User-Agent": {codexUserAgent(v)}, "Originator": {"codex_cli_rs"}, "Version": {v}}
shape = http.Header{"Version": {v}}
codexClientHeaders(shape, v)
}
for k, vs := range shape {
h[k] = vs
+13
View File
@@ -53,6 +53,10 @@ const CodexTierStandard = "default"
// CodexOpens are the values CodexOpen may take, "" for the default.
var CodexOpens = []string{"", "app", "terminal"}
// CodexClients are the values CodexClient may take, "" for Codex CLI, the
// default. Each is a client OpenAI makes, and only those.
var CodexClients = []string{"", "desktop"}
// CodexServiceTiers are the values CodexServiceTier may take, "" (as
// Codex asks) first.
var CodexServiceTiers = []string{"", CodexTierStandard, "priority", "ultrafast"}
@@ -849,6 +853,11 @@ type Settings struct {
// Ultra Fast). Codex's words, as codex-rs ServiceTier::request_value
// sends them; its Flex is not offered, the ChatGPT backend takes none.
CodexServiceTier string `json:"codexServiceTier,omitempty"`
// CodexClient is the Codex client magpie presents to the ChatGPT
// backend on a signed-in account's requests (ouhthuo on X): "" is Codex
// CLI (originator codex_cli_rs), "desktop" the Codex app (originator
// "Codex Desktop"), each with the User-Agent that client sends.
CodexClient string `json:"codexClient,omitempty"`
// CodexOpen is what the Open button of Codex's Agents row opens
// (Yink88564391 on X): "app" the Codex desktop app, "terminal" the CLI
// in a terminal. "" is the app where one is installed, else the
@@ -2579,6 +2588,10 @@ func saveOwn(s Settings, recording, reads bool) error {
if !slices.Contains(CodexServiceTiers, s.CodexServiceTier) {
return fmt.Errorf("Codex's service tier must be one of %q, not %q", CodexServiceTiers[1:], s.CodexServiceTier)
}
s.CodexClient = strings.TrimSpace(s.CodexClient)
if !slices.Contains(CodexClients, s.CodexClient) {
return fmt.Errorf("the Codex client must be one of %q, not %q", CodexClients[1:], s.CodexClient)
}
s.CodexOpen = strings.TrimSpace(s.CodexOpen)
if !slices.Contains(CodexOpens, s.CodexOpen) {
return fmt.Errorf("Codex's Open button must open one of %q, not %q", CodexOpens[1:], s.CodexOpen)
+1
View File
@@ -377,6 +377,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
in.DesktopSubagentModel = cur.DesktopSubagentModel
in.DesktopGateway = cur.DesktopGateway // Desktop's address, set in its row
in.CodexServiceTier = cur.CodexServiceTier // codex-service-tier
in.CodexClient = cur.CodexClient // codex-client
// and the model DeepSeek Harness compacts on, set in its row
in.DshCompactModel = cur.DshCompactModel
// and the model Codex compacts on, set in its row