diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index c86d81040..a982e7816 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -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`, "/" 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/ (; ) `) or `desktop`: `originator: Codex Desktop` and `Codex Desktop/ (; ) unknown (Codex Desktop; )`, 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 " 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. diff --git a/internal/gui/api.go b/internal/gui/api.go index 123c0658d..bc5c24a05 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -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) { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index ff33bf363..b2d3cd2eb 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -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/ as {: 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"); } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index f57b3b10f..a7fa8a06a 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -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", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index c6164ec1c..5aefe4fcd 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -576,6 +576,10 @@
Codex service tier
+
+
Codex client
+
+
Codex thread titles
diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index 8e2eb9438..60a2c3346 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -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", diff --git a/internal/gui/tests/agent-prefs.test.cjs b/internal/gui/tests/agent-prefs.test.cjs index 3b667fdd3..fa56bd834 100644 --- a/internal/gui/tests/agent-prefs.test.cjs +++ b/internal/gui/tests/agent-prefs.test.cjs @@ -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 { diff --git a/internal/gui/tests/codex-client.test.cjs b/internal/gui/tests/codex-client.test.cjs new file mode 100644 index 000000000..89433befe --- /dev/null +++ b/internal/gui/tests/codex-client.test.cjs @@ -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, []); + }); + } + } +} diff --git a/internal/gui/traytip_words_test.go b/internal/gui/traytip_words_test.go index c6a92f0bd..fc1ff3016 100644 --- a/internal/gui/traytip_words_test.go +++ b/internal/gui/traytip_words_test.go @@ -65,7 +65,7 @@ func TestPluginWindowWordsSaidInEveryLanguage(t *testing.T) { } for _, lang := range []string{"zh", "zh-TW", "ja", "de"} { for _, w := range words { - if _, ok := pageWords()[lang][w]; !ok { + if _, ok := pageWords(lang)[w]; !ok { t.Errorf("i18n.js's %s doesn't say %q", lang, w) } } @@ -84,3 +84,16 @@ func TestParsePageWords(t *testing.T) { t.Errorf("parsed a comment or past the table: %v", got) } } + +// parsePageWordsIn reads only the language asked for: the tray holds one +// language's words, not the page's four. +func TestParsePageWordsInOneLanguage(t *testing.T) { + src := "const I18N = {\n zh: {\n \"Credits\": \"积分\",\n },\n \"zh-TW\": {\n \"Credits\": \"積分\",\n },\n};\n" + got := parsePageWordsIn(src, "zh-TW") + if len(got) != 1 || got["zh-TW"]["Credits"] != "積分" { + t.Errorf("parsed %v", got) + } + if pageWords("ja")["Credits"] == "" || pageWords("zh")["Credits"] == pageWords("ja")["Credits"] { + t.Errorf("ja then zh: %q %q", pageWords("ja")["Credits"], pageWords("zh")["Credits"]) + } +} diff --git a/internal/gui/traywords.go b/internal/gui/traywords.go index 6084e1c6c..3adf4e948 100644 --- a/internal/gui/traywords.go +++ b/internal/gui/traywords.go @@ -8,20 +8,37 @@ import ( "github.com/yetone/magpie/internal/lazyre" ) -// pageWords are the page's own translations (assets/i18n.js's I18N), by -// language, read once: the words a usage card's window is named and -// counted in ("Credits", "credits", "5 hours") come from the vendor or a -// plugin in English, and the Usage page says them with t(). The tray's -// tooltip says them with the same table (pageWord), so a window reads in -// the tray as on its card, in every language the page has (yi_time on -// Discord: "Credits 0 / 500 credits · 已用 0%"). -var pageWords = sync.OnceValue(func() map[string]map[string]string { +// pageWords are the page's own translations (assets/i18n.js's I18N) in +// one language, read when first asked for it: the words a usage card's +// window is named and counted in ("Credits", "credits", "5 hours") come +// from the vendor or a plugin in English, and the Usage page says them +// with t(). The tray's tooltip says them with the same table (pageWord), +// so a window reads in the tray as on its card, in every language the +// page has (yi_time on Discord: "Credits 0 / 500 credits · 已用 0%"). +// Only the language last asked for is kept: all four blocks held ~4.5 MB +// of an idle tray magpie's heap, for the few words one language needs. +func pageWords(lang string) map[string]string { + pageWordsMu.Lock() + defer pageWordsMu.Unlock() + if pageWordsLang == lang && pageWordsHeld != nil { + return pageWordsHeld + } b, err := assets.ReadFile("assets/i18n.js") if err != nil { return nil } - return parsePageWords(string(b)) -}) + pageWordsLang, pageWordsHeld = lang, parsePageWordsIn(string(b), lang)[lang] + if pageWordsHeld == nil { + pageWordsHeld = map[string]string{} + } + return pageWordsHeld +} + +var ( + pageWordsMu sync.Mutex + pageWordsLang string + pageWordsHeld map[string]string +) var ( pageLangHead = lazyre.New(`^ "?([\w-]+)"?: \{`) @@ -34,6 +51,12 @@ var ( // JSON can't read (a JS-only escape) is left out: that word reads in // English, as the page's own fallback does. func parsePageWords(src string) map[string]map[string]string { + return parsePageWordsIn(src, "") +} + +// parsePageWordsIn is parsePageWords with only lang's block read ("" for +// every block). +func parsePageWordsIn(src, lang string) map[string]map[string]string { if i := strings.Index(src, "\n};"); i >= 0 { src = src[:i] } @@ -41,8 +64,11 @@ func parsePageWords(src string) map[string]map[string]string { var cur map[string]string for _, line := range strings.Split(src, "\n") { if m := pageLangHead.FindStringSubmatch(line); m != nil { - cur = map[string]string{} - out[m[1]] = cur + cur = nil + if lang == "" || m[1] == lang { + cur = map[string]string{} + out[m[1]] = cur + } continue } if cur == nil || !strings.HasPrefix(line, " \"") { @@ -62,7 +88,7 @@ func parsePageWords(src string) map[string]map[string]string { // pageWord is s as the page says it in lang (its t()): s itself in // English, or where the page has no word for it. func pageWord(lang, s string) string { - if v, ok := pageWords()[lang][s]; ok && v != "" { + if v, ok := pageWords(lang)[s]; ok && v != "" { return v } return s diff --git a/internal/provider/codex_autoreset.go b/internal/provider/codex_autoreset.go index f59154bec..1b8b9ea3f 100644 --- a/internal/provider/codex_autoreset.go +++ b/internal/provider/codex_autoreset.go @@ -23,7 +23,6 @@ import ( "time" "github.com/yetone/magpie/internal/settings" - "github.com/yetone/magpie/internal/steady" ) // The two times an account the user lets spend its resets by itself @@ -342,7 +341,7 @@ func (a *autoResets) save() { } b, _ := json.MarshalIndent(a.spent, "", " ") _ = os.MkdirAll(settings.Dir(), 0o755) - if err := steady.WriteFile(a.path, append(b, '\n'), 0o644); err != nil { + if err := writeChanged(a.path, append(b, '\n'), 0o644); err != nil { log.Printf("writing what a week's auto-use spent to %s: %v", a.path, err) } } diff --git a/internal/provider/codex_request.go b/internal/provider/codex_request.go index 567e5d8b2..41a291c44 100644 --- a/internal/provider/codex_request.go +++ b/internal/provider/codex_request.go @@ -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. diff --git a/internal/provider/codex_request_test.go b/internal/provider/codex_request_test.go index 0e758f3a5..fd9fdc4ac 100644 --- a/internal/provider/codex_request_test.go +++ b/internal/provider/codex_request_test.go @@ -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) + } +} diff --git a/internal/provider/codex_resets_used.go b/internal/provider/codex_resets_used.go index a41e78691..e81a0bdd9 100644 --- a/internal/provider/codex_resets_used.go +++ b/internal/provider/codex_resets_used.go @@ -22,7 +22,6 @@ import ( "github.com/yetone/magpie/internal/filelock" "github.com/yetone/magpie/internal/settings" - "github.com/yetone/magpie/internal/steady" ) // Why a reset was used: by itself as the account's week was used up and no @@ -105,7 +104,7 @@ func noteResetUsed(user, why string, out ResetOutcome) error { if err := os.MkdirAll(settings.Dir(), 0o755); err != nil { return fmt.Errorf("keeping that a reset was used to %s: %w", resetsUsedPath(), err) } - if err := steady.WriteFile(resetsUsedPath(), append(b, '\n'), 0o600); err != nil { + if err := writeChanged(resetsUsedPath(), append(b, '\n'), 0o600); err != nil { return fmt.Errorf("keeping that a reset was used to %s: %w", resetsUsedPath(), err) } return nil diff --git a/internal/provider/codex_tier.go b/internal/provider/codex_tier.go index 0b3b47610..8024adcfd 100644 --- a/internal/provider/codex_tier.go +++ b/internal/provider/codex_tier.go @@ -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) +} diff --git a/internal/provider/kiro.go b/internal/provider/kiro.go index 38b53424a..5823ac87b 100644 --- a/internal/provider/kiro.go +++ b/internal/provider/kiro.go @@ -42,7 +42,6 @@ import ( "github.com/yetone/magpie/internal/edit" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/settings" - "github.com/yetone/magpie/internal/steady" ) // KiroExecutable finds kiro-cli, which refreshes its own sign-in; a var so @@ -466,7 +465,7 @@ func writeFileAtomic(path string, b []byte) error { if err != nil { return err } - return steady.WriteFile(path, b, 0o600) // on the disk before it is renamed in (#1505) + return writeChanged(path, b, 0o600) // on the disk before it is renamed in (#1505) } // kiroPost posts to a sign-in endpoint. diff --git a/internal/provider/logins.go b/internal/provider/logins.go index ae6e891e0..1fd95d1e0 100644 --- a/internal/provider/logins.go +++ b/internal/provider/logins.go @@ -19,6 +19,7 @@ import ( "log" "os" "path/filepath" + "runtime" "slices" "sort" "strings" @@ -319,6 +320,15 @@ func writeLoginsTold(ls []savedLogin, tell bool) error { defer Changed() // an account added, switched or gone: All builds anew } beforeLoginsWrite() + b = append(b, '\n') + if fileHolds(loginsPath(), b, 0o600) { + // the bytes are on the disk already (#6289): no new generation, no + // new mtime, and what filememo parsed stays + lastLoginsMu.Lock() + lastLogins, loginsKnown = slices.Clone(ls), true + lastLoginsMu.Unlock() + return nil + } // the file there now is kept first: as its last good generation, or // copied aside when it doesn't read, never written over unkept if err := lastgood.Keep(loginsPath(), validLogins, 0o600); err != nil { @@ -328,7 +338,7 @@ func writeLoginsTold(ls []savedLogin, tell bool) error { if !tell { write = writePrivateQuiet } - if err := write(loginsPath(), append(b, '\n')); err != nil { + if err := write(loginsPath(), b); err != nil { return err } lastLoginsMu.Lock() @@ -365,6 +375,9 @@ func sortLogins(ls []savedLogin) { // an agent reading it at that moment sees either version, never half; the // new one is on the disk before it is renamed over the old (#1505). func writePrivate(path string, b []byte) error { + if fileHolds(path, b, 0o600) { // the file has these bytes (#6289): nothing moves + return nil + } defer filememo.Forget() // read again, where a request holds it return writePrivateQuiet(path, b) } @@ -372,6 +385,9 @@ func writePrivate(path string, b []byte) error { // writePrivateQuiet is writePrivate with nothing read forgotten: a // request holding the file reads the old bytes for up to a second. func writePrivateQuiet(path string, b []byte) error { + if fileHolds(path, b, 0o600) { + return nil + } path, err := edit.Target(path) // a symlink stays, its target written if err != nil { return err @@ -382,6 +398,33 @@ func writePrivateQuiet(path string, b []byte) error { return steady.WriteFile(path, b, 0o600) } +// fileHolds reports whether path is a file of exactly b, with the mode +// the write would give it. A read that fails is "no": it is written. +// writeChanged is steady.WriteFile for a file that is left alone, mtime +// and all, when it already holds b (#6289). +func writeChanged(path string, b []byte, perm os.FileMode) error { + if fileHolds(path, b, perm) { + return nil + } + return steady.WriteFile(path, b, perm) +} + +func fileHolds(path string, b []byte, perm os.FileMode) bool { + path, err := edit.Target(path) + if err != nil { + return false + } + fi, err := os.Stat(path) + if err != nil || !fi.Mode().IsRegular() || fi.Size() != int64(len(b)) { + return false + } + if runtime.GOOS != "windows" && fi.Mode().Perm() != perm { + return false + } + old, err := os.ReadFile(path) + return err == nil && bytes.Equal(old, b) +} + func upsertLogin(ls []savedLogin, l savedLogin) []savedLogin { l.User = codexName(ls, l) if claudeSignInOfAnother(ls, l) { diff --git a/internal/provider/logins_unchanged_test.go b/internal/provider/logins_unchanged_test.go new file mode 100644 index 000000000..d4746bed7 --- /dev/null +++ b/internal/provider/logins_unchanged_test.go @@ -0,0 +1,76 @@ +package provider + +import ( + "os" + "testing" + "time" + + "github.com/yetone/magpie/internal/filememo" +) + +// An unchanged save leaves logins.json alone (#6289): its mtime stays and +// what filememo parsed of it is not parsed again. +func TestUnchangedLoginsSaveKeepsFileAndParse(t *testing.T) { + signIn(t) + if err := writeLogins([]savedLogin{{Agent: "codex", User: "me@example.com", Plan: "pro"}}); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-time.Hour).Truncate(time.Second) + if err := os.Chtimes(loginsPath(), old, old); err != nil { + t.Fatal(err) + } + if _, err := filememo.ReadNow("logins", loginsPath(), parseLogins); err != nil { + t.Fatal(err) + } + if err := writeLogins(readLogins()); err != nil { + t.Fatal(err) + } + fi, err := os.Stat(loginsPath()) + if err != nil { + t.Fatal(err) + } + if !fi.ModTime().Equal(old) { + t.Fatalf("an unchanged save moved logins.json's time to %v", fi.ModTime()) + } + parses := 0 + if _, err := filememo.ReadNow("logins", loginsPath(), func(b []byte) ([]savedLogin, error) { + parses++ + return parseLogins(b) + }); err != nil { + t.Fatal(err) + } + if parses != 0 { + t.Fatalf("an unchanged save made logins.json parse again: %d parses", parses) + } + // a real change is still written + ls := readLogins() + ls[0].Order = 7 + if err := writeLogins(ls); err != nil { + t.Fatal(err) + } + if fi, _ := os.Stat(loginsPath()); fi.ModTime().Equal(old) { + t.Fatal("a changed account was not written") + } +} + +// The siblings written through writePrivate hold still too. +func TestWritePrivateSameBytesLeavesFile(t *testing.T) { + p := t.TempDir() + "/x.json" + if err := writePrivate(p, []byte("{}\n")); err != nil { + t.Fatal(err) + } + old := time.Now().Add(-time.Hour).Truncate(time.Second) + os.Chtimes(p, old, old) + if err := writePrivate(p, []byte("{}\n")); err != nil { + t.Fatal(err) + } + if fi, _ := os.Stat(p); !fi.ModTime().Equal(old) { + t.Fatal("the same bytes moved the file's time") + } + if err := writePrivate(p, []byte("{\"a\":1}\n")); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(p); string(b) != "{\"a\":1}\n" { + t.Fatalf("changed bytes not written: %q", b) + } +} diff --git a/internal/provider/test_as.go b/internal/provider/test_as.go index 2a17d253e..bfa3cff30 100644 --- a/internal/provider/test_as.go +++ b/internal/provider/test_as.go @@ -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 diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 114c3123b..9abf1624a 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -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) diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index c64eb0889..34166ca70 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -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