feat(codex): retain native session usage snapshots for chat

Verify typed ThreadTokenUsage/TokenUsageBreakdown/Thread/Turn against openai/codex@6fb1c3903d. Use native totalTokens and latest-call context tokens without re-adding cached/reasoning subsets. Replay bounded per-connection snapshots and clear on room/source release.

Cost stays unavailable: no subscription USD usage is reported by this notification. Throughput stays unavailable even with native Turn.durationMs because neither last-call nor cumulative-session output is a compatible turn-specific numerator. Thread readback exposes no token usage; no extra reads, resume, or live provider calls added.

Checks: go test -race ./internal/codex; go vet ./internal/codex; go test ./internal/server ./internal/protocol; git diff --check.
This commit is contained in:
2026-10-21 00:06:11 +01:00
parent 3e62ed7979
commit 83b60990d2
4 changed files with 315 additions and 0 deletions
+15
View File
@@ -65,6 +65,8 @@ type Chat struct {
connectionErr error
compactions map[string]protocol.ChatEventFrame
endedTurns map[string]string
usage map[string]usageSnapshot
usageOrder uint64
}
type pendingForm struct {
@@ -157,6 +159,7 @@ func (c *Chat) Close() {
return
}
c.closed = true
c.usage = nil
c.mu.Unlock()
c.cancel()
_ = c.conn.Close(websocket.StatusNormalClosure, "")
@@ -197,6 +200,7 @@ func (c *Chat) readLoop() {
func (c *Chat) failPending(err error) {
c.mu.Lock()
c.compactions = nil
c.usage = nil
c.connectionErr = err
c.approvals = nil
c.forms = map[string]pendingForm{}
@@ -274,6 +278,10 @@ func (c *Chat) respond(id json.RawMessage, result any) {
func (c *Chat) emit(frame protocol.ChatEventFrame) {
c.mu.Lock()
if frame.Kind == protocol.ChatEventUsage && !c.retainUsageLocked(frame) {
c.mu.Unlock()
return
}
if frame.Kind == protocol.ChatEventCompaction {
if frame.Compaction == nil {
c.mu.Unlock()
@@ -333,6 +341,9 @@ func (c *Chat) subscribe(id string) chan protocol.ChatEventFrame {
c.subs[id] = map[chan protocol.ChatEventFrame]struct{}{}
}
c.subs[id][ch] = struct{}{}
if snapshot, ok := c.usage[id]; ok {
ch <- snapshot.frame
}
if frame, ok := c.compactions[id]; ok {
ch <- frame
}
@@ -715,6 +726,10 @@ func (c *Chat) handleServerRequest(msg rpcMessage) {
}
func (c *Chat) handleNotification(msg rpcMessage) {
if msg.Method == "thread/tokenUsage/updated" {
c.receiveUsage(msg.Params)
return
}
if msg.Method == "serverRequest/resolved" {
var p struct {
ThreadID string `json:"threadId"`