magpie icon indicating copy to clipboard operation
magpie copied to clipboard

gateway, usage: Codex 自己登录打的回合没记在它自己的账号上,卡片「整窗」只统计到走 magpie 的那些——7 天窗实测 19.0M/$64.26 读成 2.3M/$0.31(关联 #1709)

Open Edward4226 opened this issue 1 month ago • 3 comments

结论:Codex 用自己 ChatGPT 登录打的那些回合,账本上记成 provider openai、不带账号(Host 是 chatgpt.com),而 Codex 卡的键是 codex\x00<账号邮箱>,windowHolds 永远匹配不上——卡片「整窗」于是只用「走 magpie 路由的那几次」外推。2026-10-15 实测这个账号的 7 天窗口:卡片 2.3M tokens / $0.31(官方已用 28%),它真正答过的调用是 19.0M / $64.26。

复现

检查版本:Magpie v0.1.1246(2026-10-15),upstream main b1d02fa,internal/gateway/codex_backend.go:975 仍是 Provider: call.Provider。

账号:这台机器上唯一的 codex 登录(邮箱从略),Plus。7 天窗口开始 2026-10-13 13:04:51 +08,读数 2026-10-15 11:08:17 +08,官方已用 28%,重置于 2026-10-20 13:04:51 +08(~/.config/magpie/quotas.json)。

拿 magpie 自己的定价(internal/usage/window_holds.go 的 apiPricer,模型价取 ~/.cache/magpie/models.json,就是卡片用的那一套)在这台机器的真实日志 ~/.config/magpie/usage.jsonl 上重算这个窗口:

口径 调用 tokens(in+out) Cost 换算整窗 tokens 换算整窗 Cost
卡片今天算的(只 codex + 账号的行) 42 636,289 $0.0877 2,272,460(2.3M) $0.31
加上被记成 openai / chatgpt.com 的行 496 5,323,179 $17.9937 19,011,353(19.0M) $64.26

第一行与卡片逐位吻合(卡片上写的是 整窗 ≈ 2.3M tokens · ≈ $0.313),说明重算口径就是卡片的口径;$ 差那一位是读数时间差了几分钟。

同一个窗口里按 provider 与 host 分组(同一份日志,先按 provider/host/endpoint 归拢,再各自看调用数与 tokens):

provider host 账号 endpoint 调用 tokens
codex chatgpt.com as <账号邮箱> <账号邮箱> /v1/... 126 636,289
openai chatgpt.com 空 /backend-api/codex/responses 563 4,686,890
commandcode api.commandcode.ai 空 /backend-api/codex/responses 602 7,701,819
opencode-go opencode.ai 空 /backend-api/codex/responses 1899 14,761,208

后两行是走 magpie 路由去别家供应商的,不是这个账号的额度,正常。第二行才是问题:provider 是 openai、账号空着、Host 是 chatgpt.com(provider.HostOf(provider.CodexBase) 的结果),Endpoint 是本机收到的 /backend-api/codex/...——即 Codex 用自己的登录打进来、magpie 原样转给 ChatGPT 的那些回合,共 563 次 / 4,686,890 tokens,一次都没记在这个账号头上。

(上表 126 与下面 42 的差是卡片自己的过滤:windowHolds 跳过 Input+Output == 0 的行;tokens 两边一致。)

tokens 差 8.4 倍,$ 差约 205 倍——被漏掉的那些大多是 gpt-6.1-sol(337 次)和 gpt-6-astra,而统计到的那 42 次里 40 次是便宜的 gpt-6-luna。所以模型越用重的,卡片越低。

根因

internal/gateway/codex_backend.go 的 codexUpstreamOn()「原样转发」路径写账本时硬编码了:

rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Provider: call.Provider, Host: provider.HostOf(base), Model: call.Model, ...}

call.Provider 在这条路上是 "openai"(Routing 视图的席位本来就是这么命名的),ProviderAccount 没写,于是 usage.Record.Account() 返回空。internal/usage/window_holds.go:194 的键是

acct := r.Provider + "\x00" + strings.ToLower(r.Account())

卡片那一侧是 codex\x00<账号邮箱>,两边永远对不上;卡片再按 scale = 100 / used% 把这点数放大,就成了上面那张表。

这份日志里这种行的形状其实早有人知道:internal/gateway/codex_backend.go:353 有一条 r.Provider == "openai" && strings.HasPrefix(r.Endpoint, CodexPath) 的排除,注释是「Codex's own sign-in … is no provider here」——只是没人管它在账本上的归属。

改动

internal/gateway/codex_backend.go

  • 新增 codexServed(base, h, on):这一次调用到底由谁提供——打到 OpenAI 自己的 API(base != provider.CodexBase,或带 sk- key)仍记 openai;否则记 codex 加登录账号的邮箱(有 compactOn 顶替时用它的账号)。
  • codexUpstreamOn() 的账本记录改用它,并写上 ProviderAccount。Routing 视图那几处 Provider: "openai" 一律不动。
  • loggedAnswers() 那条排除跟着认两种名字:openai(历史行)和 codex(修复后的行),行为一字不变。

internal/gateway/codex_backend_test.go

  • TestCodexOwnModelRecordedAsCodexAccount:CODEX_HOME/auth.json 是 auth_mode: chatgpt 时走一次 /backend-api/codex/responses,账本必须是 Provider == "codex"、ProviderAccount == "[email protected]"。
  • TestCodexOwnModelAnswersNoLead:codex 与 openai 两种名字都不算「答过这个 lead」,而路由到别家(sub2api)的照算——把上面那条排除的语义钉住。

补丁

没有 PR 权限,照旧走 fork 分支:

git fetch https://github.com/Edward4226/magpie.git fix/codex-account-attribution
git cherry-pick FETCH_HEAD
  • 分支:https://github.com/Edward4226/magpie/tree/fix/codex-account-attribution
  • 补丁:https://github.com/yetone/magpie/compare/main...Edward4226:magpie:fix/codex-account-attribution.patch
  • 对照:https://github.com/yetone/magpie/compare/main...Edward4226:magpie:fix/codex-account-attribution
  • 提交:cc506b1(b1d02fa 之上,2 files changed, 93 insertions(+), 3 deletions(-))

跑过的

反红:把 main 自己的 codex_backend.go 放回去、只留新增的两个测试, go test ./internal/gateway -count=1 -run 'TestCodexOwnModelRecordedAsCodexAccount|TestCodexOwnModelAnswersNoLead' -v:

--- FAIL: TestCodexOwnModelRecordedAsCodexAccount (0.56s)
    codex_backend_test.go:114: usage [{... Provider:openai Host:127.0.0.1:57928 ... ProviderAccount: ... Input:9 Output:2 ...}]
--- FAIL: TestCodexOwnModelAnswersNoLead (0.09s)
    codex_backend_test.go:133: codex/[email protected] answered a lead: [{provider:codex who:codex@[email protected] at:{...}}]
FAIL	github.com/yetone/magpie/internal/gateway	3.122s
检查 结果
gofmt -l 改过的两个文件 无输出
go build ./...(windows/amd64,go1.26.8) 通过
go vet ./internal/gateway ./internal/usage(windows,以及 GOOS=linux) 通过
go test ./internal/gateway -count=1 -run Codex ok,91.0s
go test ./internal/usage -count=1 -run 'Window|Holds|Quota|Ledger|Held' ok,5.2s
go test ./internal/provider -count=1 ok,240.6s
上面那张真实日志对照表 如上

边界

  • Routing 视图一行没动:Route.Provider、Weighed.Provider、codex_backend.go 里那几处 Provider: "openai" 仍是「OpenAI 自己的后端」,和账本归属是两件事。
  • 走 magpie 路由去别家供应商的调用、以及路由回 codex 账号自己的调用(窗口里那 126 次),记法完全不变,数字也不变。
  • 历史行不回填:已经写成 openai 的那些改不了,修复只对之后的调用生效。想立刻看到正确的数,得等一个窗口周期,或按上面那张表手算。
  • 估算本身仍是「已用 tokens ÷ 已用比例」外推,窗口内模型配比变了就会偏;卡片 tooltip 已有这句。
  • 修好之后 codex 会作为 provider 出现在用量页与账本里(Host 是 chatgpt.com as <账号邮箱>),和 internal/usage/window_holds_test.go 里那个 fixture 是同一个形状。
  • codexServed 在拿不到账号(没有登录、provider.Find("codex") 失败)时退回 openai,不会写出半个归属。

Not tried

  • 没在跑起来的 magpie 上验证修复后的卡片:本机没把改过的二进制接到真实账号上跑一轮,上面那张表是拿日志加 apiPricer 重算的。
  • 没跑完整 internal/gateway 套件:这台机器上整套会在某个用例上挂住(240s 超时)——main 上也一样(裸 main 挂在 TestGeminiNonStreamEndedShort,打了补丁挂在 TestGrokAccountDraws),这两个用例单独跑都过。所以只跑了 Codex 子集加 internal/usage 的额度子集。
  • internal/usage 整套有一条既有红:TestDesktopSessionAccountMetadata(Code tab account mapping),在裸 707fbb2 上同样红,与本补丁无关。
  • 没跑 GUI 测试,没碰 i18n。
  • GOOS=linux go build ./... 在这台机器上过不去(Wails 的 pkg/application/webview_window_linux.go 要 cgo),与本补丁无关;vet 两个平台都过。

动作

#1709 要的就是把这个「API 等价美元额度」放到卡片上——这个值在归属修好之前会一直偏低(今天这个 7 天窗是 2.3M/$0.31 对 19.0M/$64.26)。这与 #2010(credits 混入,已在 e10b7f92a 修)、#2045(把估算显示出来)、#1423(每周等价美元)不是同一个因,按仓库习惯单独开一条。

要压成一个 commit、把 loggedAnswers 那半句拆出去单独提、或者反过来想让 ChatGPT 登录的回合也算一笔「已答记录」(那样 lead 会钉在同一个 codex 账号上),说一声我改。

Edward4226 avatar Oct 15 '26 03:10 Edward4226

现象

Codex 用自己的 ChatGPT 登录、原样中继的回合,用量账本写成 provider openai、不带账号。卡片「整窗」用 codex 加登录邮箱对账(internal/usage/window_holds.go:配额键 q.Provider + "\x00" + 邮箱,日志键 r.Provider + "\x00" + r.Account())。Account() 只认 ProviderAccount,或 Host 里的 as。这条中继两边都没有,所以整窗只算上走 magpie 路由、Host 写成 host as email 的那些。

最小复现

基线是当前 main 01c41e8b。主线程新沙盒只把 internal/gateway/codex_backend.go 换回该提交,测试留在 1d61458b。HOME 在 E:\magpie-sandboxes\hunt23-d-review-fc0e558e-814c-4889-8be3-a7b00b78da3b\home(该目录及 E:\、E:\magpie-sandboxes 没有 Git 祖先)。GOPATH、GOMODCACHE、GOCACHE 固定在替换 HOME 之前的缓存。GOTOOLCHAIN=auto。

--- FAIL: TestCodexOwnModelRecordedAsCodexAccount (0.38s)
    codex_backend_test.go:145: usage [{... Provider:openai Host:127.0.0.1:60842 ... ProviderAccount: ... Model:gpt-5.5 Input:9 Output:2 ... Endpoint:/backend-api/codex/responses ...}]
--- FAIL: TestCodexOwnRelayAnswersNoLead (0.03s)
    codex_backend_test.go:207: own sign-in answered a lead: [{provider:codex who:codex@[email protected] ...}]

第一条的 Host 是测试里的假上游,不是生产上的 chatgpt.com。失败点是归属:provider 仍是 openai,账号为空。第二条是合成账本行,断言失败,不是编译错误。同一次里 TestCodexAPIKeyRecordedAsOpenAI、TestCodexOwnModelPassesThrough、TestCodexOwnModelTraced 没有失败。

根因

codexUpstreamOn 把这次调用的 Call.Provider 写成 "openai",用量行又抄了它,Host 只用 provider.HostOf(base),没有邮箱。整窗因此对不上 Codex 卡片。1 小时缓存那条线、插件中间件那次改动都没有动这一行;01c41e8b 上仍是 Provider: call.Provider。

修法

codexServed:ChatGPT 登录的中继记成 provider codex 和该登录邮箱。compactOn 换成另一个账号时,记那个账号。用 API key 打到 OpenAI、以及没有可命名的登录,仍是 openai、空账号。Routing 视图的 OpenAI 席位不动(Call 和 trace 仍写 openai)。已经写过的行不改写。

loggedAnswers(#1367)仍把中继排除在 lead 的回答者之外:provider 是 openai,或 provider 是 codex 且 Host 里没有 as。Host 为 host as email 的账号行照旧算。排除靠的是 provider.Where() 的 Host 形状,不是单独字段。

没有做 #1709 的剩余美元估算,也没有改价格或整窗公式。

已经记成 openai、Host 只有 chatgpt.com、没有邮箱的旧行,这张补丁不会补进卡片。报告里那个 7 天窗的历史中继不会因此改数。合入之后只有新回合会记到账号上。

验证

检查 结果
上游 01c41e8b 的 codex_backend.go + 本分支测试 FAIL。TestCodexOwnModelRecordedAsCodexAccount 为 Provider:openai、账号空;TestCodexOwnRelayAnswersNoLead 把 codex 中继行当成 lead 的回答者(主线程新沙盒)
恢复 1d61458b 后再跑上述五条 PASS,2.759s
gofmt -l 两个 Go 文件 无输出
-race -count=5;Windows / Linux / Darwin 的 vet 与 build 提交者在 rebase 前的 922bd471 上跑过。主线程没有在 1d61458b 上重跑
go test -tags nogui -count=1 -timeout 25m ./internal/gateway 提交者:1497s、exit 1。看到的失败只有 TestClaudeAsRootEnv(Windows 上 root() 不为真)和 TestSweepBridgeProjectsTakesOnlyTheBridgesFolders(符号链接权限)。主线程没有重跑整包

没跑什么

全量 go test ./... 没跑。没有起 magpie,没有读真实 usage.jsonl,所以没有复核报告里的 19.0M / $64.26。compactOn 换账号只在 codexServed 里接上,没有 HTTP 用例。gateway 整包不是全绿。

补丁与分支

https://github.com/ggbdpq/magpie/tree/hunt23-d-codex-window @ 1d61458bef19731bf66d6d9575aa51e53e425d54(修复提交 38d25fe3a614aca901963da41b6b9d044e59393f,基于 01c41e8ba2aad586ec885c92bc4b959a49005eda)

两个提交都要。第二个只删掉直接调用 codexServed 的测试,避免撤掉产品文件时变成编译错误。它的说明里还写着 rebase 前的 922bd471,以邮件头里的 SHA 为准。

git format-patch
From 38d25fe3a614aca901963da41b6b9d044e59393f Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Thu, 15 Oct 2026 13:49:50 +0800
Subject: [PATCH 1/2] gateway: a turn on Codex's own ChatGPT sign-in is counted
 on that account (#2297)

What changed
Codex's own-model relay wrote the ledger as provider openai with no account, so the Codex card's window (codex and the sign-in email) never saw those calls. The relay now records provider codex and that email. An API-key call, a relay with no sign-in to name, and the Routing view's OpenAI seat stay as they were. Rows already written are left as they are. The relay is still not a lead's answerer (#1367); a row whose host names an account ("host as email") still is.

Run
Red, before the product change: TestCodexOwnModelRecordedAsCodexAccount failed with Provider openai and an empty account; TestCodexOwnRelayAnswersNoLead failed because a codex relay row counted as a lead's answerer.
Green after: those two, TestCodexAPIKeyRecordedAsOpenAI, TestCodexServedNamesTheAccountThatSigned, TestCodexOwnModelPassesThrough and TestSealedTaskFromChatGPTLeadStillRefused, go test -tags nogui -count=1.
New tests go test -tags nogui -race -count=5 passed (1m08s) with gcc from D:\DevTools\Env\mingw64\bin, process-local CC.
gofmt -l on the two Go files printed nothing.
go vet -tags nogui and go build -tags nogui of ./internal/gateway passed for GOOS=windows, linux and darwin (CGO_ENABLED=0).
go test -tags nogui -count=1 -timeout 25m ./internal/gateway did not finish: exit 1 at 1497s. Failures seen: TestClaudeAsRootEnv (root() is false on Windows) and TestSweepBridgeProjectsTakesOnlyTheBridgesFolders (symlink privilege). Not this change. Full ./..., GUI and a real account were not run.

Generated-by: Grok 4.7 (Cursor)
---
 docs/subsystems/gateway-routing.md     |   2 +-
 internal/gateway/codex_backend.go      |  36 +++++-
 internal/gateway/codex_backend_test.go | 159 +++++++++++++++++++++++++
 3 files changed, 193 insertions(+), 4 deletions(-)

diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index ad2bc2c9..db43f3df 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -98,7 +98,7 @@ recorded as a prediction failure (`noPrediction`).
 ## Constraints and failure behavior
 
 - A fallback happens only while none of the reply has been sent. An agent never gets half a reply from one upstream and the rest from another.
-- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try.
+- A request is one usage record, counted once by how it ended (小一 on Discord: Codex on credits showed "5,482 · 1,094 failed" while rows said "2 tries/3 tries" and had been answered). The final record carries `tries` when the route took more than one (`rec.Tries`, from the trace's `Tries`). A try a vendor refused or turned away (`hw.refused`, `hw.turnedAway`) still writes its own record, for what it billed and why it failed, marked `handed_on`; `usage.Totals.count` skips such a record for calls and failures. A request failed only when the agent got an error (`LostRequest`); one answered after a failed try is counted beside it as answered on a retry (`Totals.Retried`, `RetriedRequest`, the `retried` filter). Logs written before `handed_on` are read the same way: the log index marks a failed, non-rejected record followed by another of the same route id as handed on (`routeRows` in [`log_index.go`](../../internal/usage/log_index.go)). Counts by account or route (`vias`, window holds) still count every try. A turn relayed on Codex's own ChatGPT sign-in is recorded as that codex account (`codexServed` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)), so the account card's window counts it; the Routing view still names the seat OpenAI, an API-key call stays `openai` with no account, and a row already written without an account is left as it is. Those relay rows are still not a lead's answerer (`loggedAnswers`, #1367); a row an account answered, its host `host as email`, still is.
 - Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing. The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go).
 - 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`.
 - 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.
diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go
index 9d0ece5f..b031d111 100644
--- a/internal/gateway/codex_backend.go
+++ b/internal/gateway/codex_backend.go
@@ -339,7 +339,11 @@ type loggedAnswer struct {
 // remembered (#1367). A call refused or failed answered nothing, a title
 // isn't the conversation's own turn, and Codex's own sign-in (the ChatGPT
 // backend, relayed as it came) is no provider here: a lead it answered is
-// told of as one sealed by the ChatGPT backend.
+// told of as one sealed by the ChatGPT backend. That relay is a row whose
+// provider is openai (one written before it named the account, or a call
+// sent with an API key) or codex with the API host alone. A row an account
+// answered names that account in Host ("host as email", provider.Where)
+// and still counts.
 func loggedAnswers(convs ...string) []loggedAnswer {
 	convs = slices.DeleteFunc(slices.Clone(convs), func(c string) bool { return strings.TrimSpace(c) == "" })
 	if len(convs) == 0 {
@@ -350,7 +354,10 @@ func loggedAnswers(convs ...string) []loggedAnswer {
 		if r.Provider == "" || r.Provider == "magpie" || r.IsRejected() || r.IsReported() || r.Status <= 0 || r.Status >= 400 || r.Computer != "" || isTitleKind(r.Kind) {
 			return
 		}
-		if r.Provider == "openai" && strings.HasPrefix(r.Endpoint, CodexPath) {
+		// ponytail: host " as " is provider.Where. A relay that starts
+		// writing Host that way would be counted as a lead's answerer.
+		ownRelay := r.Provider == "openai" || (r.Provider == "codex" && !strings.Contains(r.Host, " as "))
+		if ownRelay && strings.HasPrefix(r.Endpoint, CodexPath) {
 			return // Codex's own sign-in
 		}
 		if !slices.Contains(convs, r.NativeSession) && !slices.Contains(convs, r.Session) {
@@ -977,7 +984,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
 	}
 	end(call.Status, call.Error, uu.Input+uu.Output+uu.CacheRead+uu.CacheWrite, uu.Output)
 	s.record(call)
-	rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent, Provider: call.Provider, Host: provider.HostOf(base), Model: call.Model,
+	servedProvider, servedAccount := codexServed(base, r.Header, on)
+	rec := usage.Record{RouteID: tr.ID, Time: start, Agent: call.Agent,
+		Provider: servedProvider, Host: provider.HostOf(base), ProviderAccount: servedAccount, Model: call.Model,
 		Requested: call.Model, Served: served,
 		Input: uu.Input, Output: uu.Output, CacheRead: uu.CacheRead, CacheWrite: uu.CacheWrite,
 		Reasoning: uu.Reasoning, Effort: effort, Millis: call.Millis,
@@ -988,6 +997,27 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
 	appendUsage(r, rec)
 }
 
+// codexServed is who a relay through codexUpstreamOn is recorded as.
+// Codex's own ChatGPT sign-in is the codex account, and a compaction
+// signed by another of its accounts (compactOn) is that account, so the
+// account card's window counts the call. A call sent to OpenAI's API
+// with Codex's key stays openai with no account. With no sign-in to
+// name, it stays openai too, rather than a codex row that names nobody.
+// Rows already written are not rewritten.
+func codexServed(base string, h http.Header, on *provider.Provider) (id, account string) {
+	if base != provider.CodexBase || apiKey(h) {
+		return "openai", ""
+	}
+	if on != nil && on.Account != nil && on.Account.User != "" {
+		return on.ID, on.Account.User
+	}
+	p, err := provider.Find("codex")
+	if err != nil || p.Account == nil || p.Account.User == "" {
+		return "openai", ""
+	}
+	return p.ID, p.Account.User
+}
+
 // unreadableItem is the item OpenAI's refusal names: sealed content it
 // can't verify, or an id it doesn't have ("Item with id 'rs_…' not found").
 var unreadableItem = regexp.MustCompile(`(?i)(?:encrypted content for item|item with id) '?([A-Za-z]+_[A-Za-z0-9_-]+)'?`)
diff --git a/internal/gateway/codex_backend_test.go b/internal/gateway/codex_backend_test.go
index 0daee5c5..789628f7 100644
--- a/internal/gateway/codex_backend_test.go
+++ b/internal/gateway/codex_backend_test.go
@@ -9,6 +9,7 @@ import (
 	"net/http/httptest"
 	"os"
 	"path/filepath"
+	"strconv"
 	"strings"
 	"testing"
 	"time"
@@ -80,6 +81,164 @@ func TestCodexOwnModelPassesThrough(t *testing.T) {
 	}
 }
 
+// codexChatGPTAuth signs this test's Codex in to a synthetic ChatGPT
+// account. CODEX_HOME is the only auth.json it reads.
+func codexChatGPTAuth(t *testing.T, email string) {
+	t.Helper()
+	dir := filepath.Join(t.TempDir(), "codex-home")
+	if err := os.MkdirAll(dir, 0o700); err != nil {
+		t.Fatal(err)
+	}
+	t.Setenv("CODEX_HOME", dir)
+	claims, err := json.Marshal(map[string]any{"email": email})
+	if err != nil {
+		t.Fatal(err)
+	}
+	exp, err := json.Marshal(map[string]any{"exp": time.Now().Add(time.Hour).Unix()})
+	if err != nil {
+		t.Fatal(err)
+	}
+	token := func(payload []byte) string {
+		return "h." + base64.RawURLEncoding.EncodeToString(payload) + ".s"
+	}
+	auth, err := json.Marshal(map[string]any{
+		"auth_mode": "chatgpt",
+		"tokens": map[string]string{
+			"id_token":      token(claims),
+			"access_token":  token(exp),
+			"refresh_token": "rt-synthetic",
+			"account_id":    "acct-synthetic",
+		},
+	})
+	if err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(filepath.Join(dir, "auth.json"), auth, 0o600); err != nil {
+		t.Fatal(err)
+	}
+	provider.ForgetAccounts()
+	t.Cleanup(provider.ForgetAccounts)
+}
+
+// A turn relayed on Codex's own ChatGPT sign-in is that codex account's
+// in the ledger. Recorded as openai with no account, the card's window
+// (keyed codex + the email) never sees it. The Routing view still calls
+// the seat openai, and the row is still not a lead's answerer (#1367).
+func TestCodexOwnModelRecordedAsCodexAccount(t *testing.T) {
+	setup(t, provider.Chat, &fake{t: t})
+	chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "text/event-stream")
+		io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":9,"output_tokens":2}}}`))
+	})
+	codexChatGPTAuth(t, "[email protected]")
+	s := New()
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`))
+	req.Header.Set("Authorization", "Bearer chatgpt-token")
+	req.Header.Set("session_id", "lead-own")
+	s.Handler().ServeHTTP(rec, req)
+	if rec.Code != 200 {
+		t.Fatalf("%d %s", rec.Code, rec.Body.String())
+	}
+	u := usage.Load(time.Time{})
+	if len(u) != 1 || u[0].Provider != "codex" || u[0].ProviderAccount != "[email protected]" || u[0].Input != 9 || u[0].Output != 2 {
+		t.Fatalf("usage %+v", u)
+	}
+	if strings.Contains(u[0].Host, " as ") {
+		t.Fatalf("relay host names an account, so it would count as a routed answer: %q", u[0].Host)
+	}
+	if a := loggedAnswers("lead-own"); len(a) != 0 {
+		t.Fatalf("own sign-in answered a lead: %+v", a)
+	}
+	st := s.Trace(t.Context(), 0, 0)
+	if len(st.Routes) != 1 || len(st.Routes[0].Usage) != 1 || st.Routes[0].Usage[0].Provider != "openai" {
+		t.Fatalf("routing view %+v", st.Routes)
+	}
+}
+
+// An API-key call stays openai with no account, even while a ChatGPT
+// sign-in is on disk: that spend is not the subscription card's.
+func TestCodexAPIKeyRecordedAsOpenAI(t *testing.T) {
+	setup(t, provider.Chat, &fake{t: t})
+	up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+		w.Header().Set("Content-Type", "text/event-stream")
+		io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":4,"output_tokens":1}}}`))
+	}))
+	t.Cleanup(up.Close)
+	was := codexAPIBase
+	codexAPIBase = up.URL + "/v1"
+	t.Cleanup(func() { codexAPIBase = was })
+	codexChatGPTAuth(t, "[email protected]")
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"hi"}`))
+	req.Header.Set("Authorization", "Bearer sk-synthetic")
+	New().Handler().ServeHTTP(rec, req)
+	if rec.Code != 200 {
+		t.Fatalf("%d %s", rec.Code, rec.Body.String())
+	}
+	u := usage.Load(time.Time{})
+	if len(u) != 1 || u[0].Provider != "openai" || u[0].ProviderAccount != "" || u[0].Input != 4 {
+		t.Fatalf("usage %+v", u)
+	}
+}
+
+// A compaction signed by another account is that account's, not the
+// sign-in the request would have relayed on. No sign-in to name stays
+// openai, so the row is not half a codex account.
+func TestCodexServedNamesTheAccountThatSigned(t *testing.T) {
+	on := &provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "[email protected]"}}
+	id, acct := codexServed(provider.CodexBase, http.Header{}, on)
+	if id != "codex" || acct != "[email protected]" {
+		t.Fatalf("stand-in: %s %s", id, acct)
+	}
+	setHome(t, t.TempDir())
+	t.Setenv("CODEX_HOME", t.TempDir())
+	provider.ForgetAccounts()
+	t.Cleanup(provider.ForgetAccounts)
+	id, acct = codexServed(provider.CodexBase, http.Header{}, nil)
+	if id != "openai" || acct != "" {
+		t.Fatalf("no sign-in: %s %s", id, acct)
+	}
+}
+
+// Codex's own sign-in relay is not a lead's answerer, under the name it
+// was logged by before (openai) or the codex account it is logged by now.
+// A row an account answered — host "as email", or another provider, or
+// /v1 — still is. One codex row is not counted twice.
+func TestCodexOwnRelayAnswersNoLead(t *testing.T) {
+	setHome(t, t.TempDir())
+	// usage.Path follows the first home a process reads; -count keeps
+	// writing there, so each run's sessions are its own.
+	stamp := strconv.FormatInt(time.Now().UnixNano(), 10)
+	now := time.Now()
+	row := func(name, prov, account, host, endpoint string) string {
+		t.Helper()
+		session := name + "-" + stamp
+		usage.Append(usage.Record{
+			Time: now, Agent: "codex", Provider: prov, Host: host, ProviderAccount: account,
+			Model: "gpt-5.5", Input: 9, Output: 2, Status: 200, Endpoint: endpoint, Session: session,
+		})
+		return session
+	}
+	relay := row("lead-relay", "openai", "", provider.HostOf(provider.CodexBase), CodexPath+"/responses")
+	row("lead-relay", "codex", "[email protected]", provider.HostOf(provider.CodexBase), CodexPath+"/responses")
+	if a := loggedAnswers(relay); len(a) != 0 {
+		t.Fatalf("own sign-in answered a lead: %+v", a)
+	}
+	routed := row("lead-routed", "codex", "[email protected]", "chatgpt.com as [email protected]", CodexPath+"/responses")
+	if a := loggedAnswers(routed); len(a) != 1 || a[0].provider != "codex" || a[0].who != "codex@[email protected]" {
+		t.Fatalf("routed account: %+v", a)
+	}
+	v1 := row("lead-v1", "codex", "[email protected]", "chatgpt.com as [email protected]", "/v1/responses")
+	if a := loggedAnswers(v1); len(a) != 1 || a[0].who != "codex@[email protected]" {
+		t.Fatalf("/v1 account: %+v", a)
+	}
+	other := row("lead-other", "sub2api", "", "relay.example.com", CodexPath+"/responses")
+	if a := loggedAnswers(other); len(a) != 1 || a[0].provider != "sub2api" {
+		t.Fatalf("relay: %+v", a)
+	}
+}
+
 // A turn on one of Codex's own models shows in the Routing view's live
 // trace, as those on magpie's do.
 func TestCodexOwnModelTraced(t *testing.T) {
-- 
2.55.0.windows.4

From 1d61458bef19731bf66d6d9575aa51e53e425d54 Mon Sep 17 00:00:00 2001
From: ggbdpq <[email protected]>
Date: Thu, 15 Oct 2026 13:52:54 +0800
Subject: [PATCH 2/2] gateway: drop the helper call so the new ledger tests
 still compile without the fix

What changed
TestCodexServedNamesTheAccountThatSigned called codexServed, so putting the old product file back was a compile error rather than a failing assertion. The HTTP and ledger-row tests do not need that helper.

Run
Not a behavior change. The race and package runs above still describe 922bd471.

Generated-by: Grok 4.7 (Cursor)
---
 internal/gateway/codex_backend_test.go | 19 -------------------
 1 file changed, 19 deletions(-)

diff --git a/internal/gateway/codex_backend_test.go b/internal/gateway/codex_backend_test.go
index 789628f7..6659ebda 100644
--- a/internal/gateway/codex_backend_test.go
+++ b/internal/gateway/codex_backend_test.go
@@ -182,25 +182,6 @@ func TestCodexAPIKeyRecordedAsOpenAI(t *testing.T) {
 	}
 }
 
-// A compaction signed by another account is that account's, not the
-// sign-in the request would have relayed on. No sign-in to name stays
-// openai, so the row is not half a codex account.
-func TestCodexServedNamesTheAccountThatSigned(t *testing.T) {
-	on := &provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "[email protected]"}}
-	id, acct := codexServed(provider.CodexBase, http.Header{}, on)
-	if id != "codex" || acct != "[email protected]" {
-		t.Fatalf("stand-in: %s %s", id, acct)
-	}
-	setHome(t, t.TempDir())
-	t.Setenv("CODEX_HOME", t.TempDir())
-	provider.ForgetAccounts()
-	t.Cleanup(provider.ForgetAccounts)
-	id, acct = codexServed(provider.CodexBase, http.Header{}, nil)
-	if id != "openai" || acct != "" {
-		t.Fatalf("no sign-in: %s %s", id, acct)
-	}
-}
-
 // Codex's own sign-in relay is not a lead's answerer, under the name it
 // was logged by before (openai) or the codex account it is logged by now.
 // A row an account answered — host "as email", or another provider, or
-- 
2.55.0.windows.4

合入时请保留原作者(git am / cherry-pick 两个提交),或在合入提交加 Co-authored-by: ggbdpq <[email protected]>。

Generated-by: Grok 4.7 (Cursor)

ggbdpq avatar Oct 15 '26 06:10 ggbdpq

感谢 @Edward4226 的复现和 @ggbdpq 的补丁,原因确认。

internal/gateway/codex_backend.go:980(codexUpstreamOn)里,Codex 用自己的 ChatGPT 登录、原样转发的那些回合,写账本时用的是 Provider: call.Provider,也就是 openai,而且不带账号。卡片的「整窗」按 codex 加登录邮箱来对账(internal/usage/window_holds.go:171 和 :194),这些行永远对不上,所以整窗只算到了走 magpie 路由的那几次。

修复会用 ggbdpq 的补丁(保留作者署名),我在上面再加一条检查:请求的 chatgpt-account-id 要和这台机器上 Codex auth.json 登录的是同一个账号,才把它记到这个账号上。WSL 里的 Codex 或者用了别的 CODEX_HOME 的 Codex,用的是它自己的登录,这种情况仍然记成 openai,不会记到别的账号头上。用 API key 的调用也仍然是 openai。

要说明的是,已经写进账本的旧行不会改写,所以这次 7 天窗口里过去的那些回合不会补回卡片,修复合入后的新回合才会算进去。合入后我会在这里回复,issue 先保持打开。

yetone avatar Oct 15 '26 07:10 yetone

Confirming this can close: 540454ac lands our patch — thanks for the co-author credit and for adding the chatgpt-account-id check exactly as you described when taking the issue (a Codex in WSL or another CODEX_HOME now stays openai instead of being put on this machine's account, with TestCodexServedNamesTheAccountThatSigned covering it). I rebased our old branch (hunt23-d-codex-window, base 01c41e8b) onto current main to see what was left of ours: it resolves to zero diff — both commits became empty, so I left the branch untouched as a record. Nothing pending from our side.

Semantics check on c551a229, item by item:

  • codexServed's inputs are unchanged (base, the request header, on), and the ledger write still sets Provider/ProviderAccount from it. Your account-id check is an earlier return we did not have: under our original wording, a WSL Codex would have been recorded on this machine's account; now it stays openai. That narrowing is the right call and supersedes ours.
  • 5f73537f (one-account overload) restructured codexUpstreamOn and the ledger write moved into the extracted per-try function, with call.Route/call.Masked added alongside; our line survives as-is and the Routing view still names the seat OpenAI.
  • bf2e067e (credits at the allowance's edge) adds the 429 ask-again (relayOnCredits, creditsAsked) earlier in the same try loop; it does not touch who the row names, and our tests pass alongside it.
  • 3b8bcc36 (#2973, SignInExpired) is provider-side token refresh; it changes which token goes out, not how the row is named. de281760 (tool-loop detection) sits before the relay and is unrelated to the ledger row.
  • loggedAnswers still carries our ownRelay logic and comment verbatim; the relay stays out of a lead's answerers as openai or as codex without a "host as email".
  • The gateway-routing.md sentence survives with your account-id clause appended.

Re-verified on the rebased tree (go1.26.8 darwin/arm64, -tags nogui -count=1): TestCodexOwnModelRecordedAsCodexAccount, TestCodexAPIKeyRecordedAsOpenAI, TestCodexServedNamesTheAccountThatSigned, TestCodexOwnRelayAnswersNoLead, TestSealedTaskFromChatGPTLeadStillRefused, TestCodexOwnModelPassesThrough — ok; the credits/overload families (TestCodexCredits*, TestCodexOneAccount*) — ok; the four ledger tests -race -count=3 — ok. Broken by hand, each red, then put back: codexServed forced to "openai" plus ownRelay reverted to openai only → TestCodexOwnModelRecordedAsCodexAccount, TestCodexServedNamesTheAccountThatSigned, TestCodexOwnRelayAnswersNoLead red, TestCodexAPIKeyRecordedAsOpenAI correctly still green. gofmt -l clean; go vet and go build (CGO_ENABLED=0) for darwin, linux and windows pass on ./internal/gateway and ./internal/provider. Not run: the full suite, the GUI, a real Codex sign-in.

Refreshed with AI assistance (GLM-5.3-Flash via ZCode).

The issue can close whenever you like.

ggbdpq avatar Oct 23 '26 15:10 ggbdpq