diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index 464eb6b1a..3c0feb5f1 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -380,6 +380,16 @@ metadata, gateway-only entries and conflicting identities set `role` to `unknown` and do not acquire a guessed parent or root. These fields are omitted for other agents. This is Codex-specific (#1591). +Codex keeps the existing session-title precedence. Only when that leaves the +title empty may a child thread use its parent's `spawn_agent` `task_name`, +matched by the same `call_id` and an `item_completed` event whose item has type +`SubAgentActivity`, kind `started`, the same `id`, and the child's +`agent_thread_id`. +The native top-level `session_meta.agent_nickname` is exposed separately as +`nickname` on list, one, manage and overview responses; it does not replace the +title. The parsed-session cache is versioned for nickname and task-title +metadata, and the Codex-call cache for compaction, so older parses are rebuilt. + `GET /api/sessions`, `/api/sessions/one` and `/api/sessions/manage` also return `model_effort` for each Codex thread, grouped by the canonical Usage ledger's `model` and effective reasoning effort. It carries that thread's input, output, @@ -405,3 +415,12 @@ parent thread ID. `native_session` stays the recorded native header. The new `session_role` is omitted for other agents, whose existing field semantics stay unchanged. Ambiguous or unpaired calls do not inherit a relationship from shared session metadata. + +`GET /api/usage/requests` and `GET /v1/magpie/usage/requests` expose Codex +`compaction` as `true` or `false` when a native Codex call establishes the +marker state, and omit it when there is no matching native evidence. A unique +`response_id` match adds this metadata to the gateway row while preserving that +row's model, usage, cost and kind. +Compaction is already included in Codex's total consumption, so this marker +does not add tokens or cost. This is Codex-only; Claude behavior and the POST +`/v1/magpie/usage/requests` ingest allowlist are unchanged. diff --git a/internal/gui/sessions_codex_details_test.go b/internal/gui/sessions_codex_details_test.go new file mode 100644 index 000000000..a32b59227 --- /dev/null +++ b/internal/gui/sessions_codex_details_test.go @@ -0,0 +1,153 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/sessions" +) + +func codexDetailsAPILine(t *testing.T, at time.Time, typ string, payload any) string { + t.Helper() + b, err := json.Marshal(struct { + Timestamp string `json:"timestamp"` + Type string `json:"type"` + Payload any `json:"payload"` + }{at.Format(time.RFC3339Nano), typ, payload}) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func writeCodexDetailsAPIRollout(t *testing.T, codex, id string, at time.Time, lines ...string) { + t.Helper() + path := filepath.Join(codex, "sessions", at.Format("2006/01/02"), "rollout-"+at.Format("2006-01-02T15-04-05")+"-"+id+".jsonl") + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } +} + +func TestCodexSubagentDetailsReachSessionAPIs(t *testing.T) { + home := sandboxHome(t) + codex := filepath.Join(home, ".codex") + t.Setenv("CODEX_HOME", codex) + now := holdUsageClock(t, time.Date(2026, 10, 15, 12, 0, 0, 0, time.Local)) + catalog.Reset() + t.Cleanup(catalog.Reset) + sessions.Reset() + forgetStats() + t.Cleanup(func() { sessions.Reset(); forgetStats() }) + + mainMeta := codexDetailsAPILine(t, now.Add(-time.Minute), "session_meta", map[string]any{ + "id": "main-a", "session_id": "shared", "source": "cli", + }) + spawn := codexDetailsAPILine(t, now, "response_item", struct { + Type string `json:"type"` + Name string `json:"name"` + CallID string `json:"call_id"` + Arguments string `json:"arguments"` + }{"function_call", "spawn_agent", "call-child", `{"task_name":"Inspect the fixture"}`}) + activity := codexDetailsAPILine(t, now, "event_msg", struct { + Type string `json:"type"` + Item struct { + Type string `json:"type"` + Kind string `json:"kind"` + ID string `json:"id"` + AgentThreadID string `json:"agent_thread_id"` + } `json:"item"` + }{Type: "item_completed", Item: struct { + Type string `json:"type"` + Kind string `json:"kind"` + ID string `json:"id"` + AgentThreadID string `json:"agent_thread_id"` + }{Type: "SubAgentActivity", Kind: "started", ID: "call-child", AgentThreadID: "child-a"}}) + writeCodexDetailsAPIRollout(t, codex, "main-a", now, mainMeta, spawn, activity) + childMeta := codexDetailsAPILine(t, now.Add(-time.Minute), "session_meta", map[string]any{ + "id": "child-a", "session_id": "shared", "source": map[string]any{"subagent": map[string]any{"thread_spawn": map[string]any{"parent_thread_id": "main-a"}}}, + "agent_nickname": "Scout", + }) + turn := codexDetailsAPILine(t, now.Add(-time.Second), "turn_context", map[string]any{"turn_id": "turn-child", "model": "fixture-model"}) + usage := codexDetailsAPILine(t, now, "token_usage_record", map[string]any{ + "response_id": "child-response", "session_id": "shared", "thread_id": "child-a", "turn_id": "turn-child", + "usage": map[string]int{"input_tokens": 12, "output_tokens": 3, "total_tokens": 15}, + }) + writeCodexDetailsAPIRollout(t, codex, "child-a", now, childMeta, turn, usage) + + mux := http.NewServeMux() + sessionRoutes(mux, folderOnly{}) + sessionManageRoutes(mux, folderOnly{}) + request := func(path string) *httptest.ResponseRecorder { + t.Helper() + w := httptest.NewRecorder() + mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) + if w.Code != http.StatusOK { + t.Fatalf("%s: %d %s", path, w.Code, w.Body) + } + return w + } + + var listed struct { + Sessions []sessions.Session `json:"sessions"` + } + if err := json.Unmarshal(request("/api/sessions").Body.Bytes(), &listed); err != nil { + t.Fatal(err) + } + assertDetails := func(s sessions.Session, where string) { + t.Helper() + if s.Title != "Inspect the fixture" || s.Nickname != "Scout" { + t.Errorf("%s: title/nickname = %q/%q", where, s.Title, s.Nickname) + } + } + var child sessions.Session + for _, s := range listed.Sessions { + if s.Agent == "codex" && s.ID == "child-a" { + child = s + break + } + } + assertDetails(child, "list") + + var one sessions.Session + if err := json.Unmarshal(request("/api/sessions/one?key=codex:child-a").Body.Bytes(), &one); err != nil { + t.Fatal(err) + } + assertDetails(one, "one") + + var managed struct { + Sessions []sessions.Managed `json:"sessions"` + } + if err := json.Unmarshal(request("/api/sessions/manage?agent=codex").Body.Bytes(), &managed); err != nil { + t.Fatal(err) + } + for _, row := range managed.Sessions { + if row.Agent == "codex" && row.ID == "child-a" { + assertDetails(row.Session, "manage") + child = row.Session + } + } + + var overview sessions.Overview + if err := json.Unmarshal(request("/api/sessions/overview?days=7&agent=codex").Body.Bytes(), &overview); err != nil { + t.Fatal(err) + } + for _, summary := range overview.Top["tokens"] { + if summary.Agent == "codex" && summary.ID == "child-a" { + if summary.Title != "Inspect the fixture" || summary.Nickname != "Scout" { + t.Errorf("overview title/nickname = %q/%q", summary.Title, summary.Nickname) + } + return + } + } + t.Fatal("overview token top omitted the active Codex child") +} diff --git a/internal/gui/usage_compaction_api_test.go b/internal/gui/usage_compaction_api_test.go new file mode 100644 index 000000000..cadd96c6b --- /dev/null +++ b/internal/gui/usage_compaction_api_test.go @@ -0,0 +1,73 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/sessions" + "github.com/yetone/magpie/internal/usage" +) + +func TestUsageRequestAPIsReturnCodexCompactionStates(t *testing.T) { + sandboxHome(t) + now := holdUsageClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)) + at := now.Add(-time.Hour) + for _, row := range []struct { + id string + at time.Time + }{ + {"resp-api-true", at}, + {"resp-api-false", at.Add(time.Second)}, + {"resp-api-orphan", at.Add(2 * time.Second)}, + } { + usage.Append(usage.Record{Time: row.at, Agent: "codex", Provider: "openai", Model: "api-model", Effort: "gateway-effort", Kind: "chat", + Input: 8, Output: 2, Status: 200, ResponseID: row.id}) + } + calls := []sessions.Call{ + {Time: at, Agent: "codex", ThreadID: "fixture-thread", Session: "fixture-session", ResponseID: "resp-api-true", Model: "native-model", Compaction: true}, + {Time: at.Add(time.Second), Agent: "codex", ThreadID: "fixture-thread", Session: "fixture-session", ResponseID: "resp-api-false", Model: "native-model"}, + } + old := usage.LogCalls + usage.LogCalls = func(time.Time) []sessions.Call { return calls } + t.Cleanup(func() { usage.LogCalls = old }) + + guiMux := http.NewServeMux() + usageRoutes(guiMux, folderOnly{}) + responses := map[string]*httptest.ResponseRecorder{ + "GUI": httptest.NewRecorder(), + "gateway": httptest.NewRecorder(), + } + guiMux.ServeHTTP(responses["GUI"], httptest.NewRequest("GET", "/api/usage/requests?period=all", nil)) + gatewayRequest := httptest.NewRequest("GET", "/v1/magpie/usage/requests?period=all", nil) + gatewayRequest.RemoteAddr = "127.0.0.1:5000" + gateway.New().Handler().ServeHTTP(responses["gateway"], gatewayRequest) + for name, response := range responses { + if response.Code != http.StatusOK { + t.Fatalf("%s request API: %d %s", name, response.Code, response.Body) + } + var page ledgerJSON + if err := json.Unmarshal(response.Body.Bytes(), &page); err != nil { + t.Fatalf("%s request API JSON: %v: %s", name, err, response.Body) + } + rows := map[string]ledgerRow{} + for _, row := range page.Rows { + rows[row.ResponseID] = row + } + for id, want := range map[string]bool{"resp-api-true": true, "resp-api-false": false} { + row, ok := rows[id] + if !ok || row.Compaction == nil || *row.Compaction != want { + t.Errorf("%s %s compaction = %+v (found=%v), want known %v", name, id, row.Compaction, ok, want) + } + if ok && (row.Model != "api-model" || row.Effort != "gateway-effort" || row.Kind != "chat" || row.Input != 8 || row.Output != 2) { + t.Errorf("%s %s lost gateway details: %+v", name, id, row) + } + } + if row, ok := rows["resp-api-orphan"]; !ok || row.Compaction != nil { + t.Errorf("%s unmatched gateway row claims native evidence: %+v, found=%v", name, row.Compaction, ok) + } + } +} diff --git a/internal/sessions/call_cache.go b/internal/sessions/call_cache.go index 41126cd55..5f79a8b9c 100644 --- a/internal/sessions/call_cache.go +++ b/internal/sessions/call_cache.go @@ -37,10 +37,11 @@ import ( // (Compact): Claude Code's compact_boundary durationMs, Codex's compaction // call's own time. // v14: Codex calls keep the thread that made the request. +// v15: Codex calls keep the compaction marker independently of its duration. // What each version names is what a cache of the one before it cannot serve: // the version is part of the directory's name, so a cache written by an older // one is never read (pruneCalls). -const callCacheVersion = "calls-v14" +const callCacheVersion = "calls-v15" const maxKeptCalls = 131072 const maxKeptFiles = 64 diff --git a/internal/sessions/calls.go b/internal/sessions/calls.go index a1343f186..0a435c44a 100644 --- a/internal/sessions/calls.go +++ b/internal/sessions/calls.go @@ -42,6 +42,8 @@ type Call struct { ErrorText string `json:"error_text,omitempty"` // its message, the first 400 characters // Codex: the turn's own figures, set only when the turn made just this call TTFT int64 `json:"ttft_ms,omitempty"` + // Compaction is Codex's explicit marker that this response compacted the context. + Compaction bool `json:"compaction,omitempty"` // Millis: how long the call took. Codex's, of a turn that made this call alone, is what // it says; the rest are told from the file's times, the call's last line less the line // that asked for it (a prompt, a tool's result), and so a little more or less than it was @@ -844,7 +846,7 @@ func (st *callFile) codexChanged(change *codexChange) { threadID = r.ThreadID } c := Call{Time: v.At, Agent: "codex", Session: r.Session, ThreadID: threadID, Model: v.Model, Tokens: spent(v.Usage.raw()), ResponseID: v.ResponseID, - Upstream: context.Upstream, AccountID: r.AccountID, UserID: r.UserID, Reasoning: v.Usage.Reasoning, Effort: context.Effort, Cwd: context.Cwd, File: st.Path, From: r.LastEnd, To: st.End} + Upstream: context.Upstream, AccountID: r.AccountID, UserID: r.UserID, Reasoning: v.Usage.Reasoning, Effort: context.Effort, Compaction: v.Compaction, Cwd: context.Cwd, File: st.Path, From: r.LastEnd, To: st.End} if c.Session == "" { c.Session = r.Session } diff --git a/internal/sessions/calls_test.go b/internal/sessions/calls_test.go index 9470048da..14ee5e16f 100644 --- a/internal/sessions/calls_test.go +++ b/internal/sessions/calls_test.go @@ -660,6 +660,66 @@ func TestCallsCodexCompactTook(t *testing.T) { check() } +func TestCallsCodexLateCompactionMarkerPatchesZeroDuration(t *testing.T) { + u := cxUse(100, 40, 0, 10, 2) + lines := append(cxTurnLines(0, "t1", "gpt-6-astra", "high"), cxRecordLine(0, "resp-zero", u, u)) + path := codexUsageLog(t, lines) + find := func(want bool) Call { + t.Helper() + for _, call := range Calls(time.Time{}) { + if call.ResponseID == "resp-zero" { + if call.Compaction != want { + t.Fatalf("compaction marker %v; want %v: %+v", call.Compaction, want, call) + } + return call + } + } + t.Fatalf("compaction response missing: %+v", Calls(time.Time{})) + return Call{} + } + if call := find(false); call.Compact != 0 || call.Millis != 0 { + t.Fatalf("initial call has unexpected timing: %+v", call) + } + appendText(t, path, cxCompactionLine(0, "resp-zero", u, u)+"\n") + if call := find(true); call.Compact != 0 || call.Millis != 0 { + t.Fatalf("late marker changed zero duration: %+v", call) + } + Reset() + if call := find(true); call.Compact != 0 || call.Millis != 0 { + t.Fatalf("cached marker lost zero duration: %+v", call) + } +} + +func TestCallsCodexOldCacheWithoutCompactionMarkerIsIgnored(t *testing.T) { + u := cxUse(100, 40, 0, 10, 2) + lines := append(cxTurnLines(0, "t1", "gpt-6-astra", "high"), cxRecordLine(0, "resp-old-cache", u, u), cxCompactionLine(0, "resp-old-cache", u, u)) + path := codexUsageLog(t, lines) + if calls := Calls(time.Time{}); len(calls) != 1 || !calls[0].Compaction { + t.Fatalf("native compaction: %+v", calls) + } + st := loadCalls(file{path: path, agent: "codex"}) + if st == nil || len(st.Calls) != 1 { + t.Fatal("could not load the cached call") + } + st.Calls[0].Compaction = false // an older cache has no marker field + writeCalls(st, 0, false) + old := filepath.Join(filepath.Dir(CachePath()), "calls-v14", hashHead(path)+".gob") + if err := os.MkdirAll(filepath.Dir(old), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Rename(callCachePath(path), old); err != nil { + t.Fatal(err) + } + Reset() + calls := Calls(time.Time{}) + if len(calls) != 1 || !calls[0].Compaction { + t.Fatalf("old cache hid the native compaction marker: %+v", calls) + } + if _, err := os.Stat(old); !os.IsNotExist(err) { + t.Fatalf("old call cache still exists: %v", err) + } +} + // bare is a call without where it is in its file, which a test of what the // calls are has no want of. func bare(c Call) Call { diff --git a/internal/sessions/codex.go b/internal/sessions/codex.go index 05a59ae0d..d5331c5e9 100644 --- a/internal/sessions/codex.go +++ b/internal/sessions/codex.go @@ -36,7 +36,17 @@ type cxLine struct { ModelProvider string `json:"model_provider"` Role string `json:"role"` Message string `json:"message"` - Content []struct { + AgentNickname string `json:"agent_nickname"` + CallID string `json:"call_id"` + Name string `json:"name"` + Arguments string `json:"arguments"` + Item struct { + ID string `json:"id"` + Type string `json:"type"` + Kind string `json:"kind"` + AgentThreadID string `json:"agent_thread_id"` + } `json:"item"` + Content []struct { Type string `json:"type"` Text string `json:"text"` } `json:"content"` @@ -78,18 +88,21 @@ func spent(t Tokens) Tokens { } var ( - cxMeta = []byte(`"type":"session_meta"`) - cxTurn = []byte(`"type":"turn_context"`) - cxRecord = []byte(`"type":"token_usage_record"`) - cxCompacted = []byte(`"type":"compacted"`) - cxCount = []byte(`"type":"token_count"`) - cxSettings = []byte(`"type":"thread_settings_applied"`) - cxUserMsg = []byte(`"type":"user_message"`) - cxUserRole = []byte(`"role":"user"`) - cxRole = []byte(`"role":"`) - cxType = []byte(`"type":"`) - cxPayload = []byte(`"payload":{"type":"`) - cxText = []byte(`,"text":"`) + cxMeta = []byte(`"type":"session_meta"`) + cxTurn = []byte(`"type":"turn_context"`) + cxRecord = []byte(`"type":"token_usage_record"`) + cxCompacted = []byte(`"type":"compacted"`) + cxCount = []byte(`"type":"token_count"`) + cxSettings = []byte(`"type":"thread_settings_applied"`) + cxUserMsg = []byte(`"type":"user_message"`) + cxUserRole = []byte(`"role":"user"`) + cxRole = []byte(`"role":"`) + cxType = []byte(`"type":"`) + cxPayload = []byte(`"payload":{"type":"`) + cxText = []byte(`,"text":"`) + cxSpawnAgent = []byte(`"name":"spawn_agent"`) + cxSubAgentActivity = []byte(`"type":"SubAgentActivity"`) + cxStartedKind = []byte(`"kind":"started"`) ) func codexLine(s *state, b []byte, main bool) { @@ -135,7 +148,8 @@ func codexHead(s *state, b []byte, main bool) bool { case payload == "": return true case top == "event_msg": - return payload == "token_count" || payload == "task_started" || payload == "thread_settings_applied" || payload == "user_message" && s.Title == "" + return payload == "token_count" || payload == "task_started" || payload == "thread_settings_applied" || payload == "user_message" && s.Title == "" || + bytes.Contains(h, cxSubAgentActivity) && bytes.Contains(h, cxStartedKind) case cxCalls[payload]: // a tool call, named in its head name := typeAfter(h, cxName) @@ -143,7 +157,7 @@ func codexHead(s *state, b []byte, main bool) bool { name = payload } s.tool(at, name, "") - return false + return top == "response_item" && payload == "function_call" && name == "spawn_agent" case payload == "message" && typeAfter(h, cxRole) == "assistant": if main { s.day(dateOf(at)).Replies++ @@ -278,6 +292,99 @@ func setSessionCodexIdentity(s *Session, identities map[string]CodexIdentity) { } } +type codexTaskTitle struct { + parent string + title string +} + +func codexSubagentTaskTitles(files []file) map[string]codexTaskTitle { + type parentCalls struct { + names map[string]string + children map[string]string + badNames map[string]bool + badChildren map[string]bool + } + parents := map[string]*parentCalls{} + for _, f := range files { + if f.agent != "codex" || cache[f.path] == nil { + continue + } + calls := parents[f.key] + if calls == nil { + calls = &parentCalls{names: map[string]string{}, children: map[string]string{}, badNames: map[string]bool{}, badChildren: map[string]bool{}} + parents[f.key] = calls + } + st := cache[f.path] + for id := range st.CodexSpawnConflicts { + calls.badNames[id] = true + } + for id := range st.CodexAgentConflicts { + calls.badChildren[id] = true + } + for id, name := range st.CodexSpawnNames { + if old := calls.names[id]; old != "" && old != name { + calls.badNames[id] = true + } + calls.names[id] = name + } + for id, child := range st.CodexAgentIDs { + if old := calls.children[id]; old != "" && old != child { + calls.badChildren[id] = true + } + calls.children[id] = child + } + } + out, conflicts := map[string]codexTaskTitle{}, map[string]bool{} + for parentKey, calls := range parents { + parent := strings.TrimPrefix(parentKey, "codex:") + for id, name := range calls.names { + child := calls.children[id] + if calls.badNames[id] || calls.badChildren[id] || name == "" || child == "" { + continue + } + task := codexTaskTitle{parent: parent, title: name} + if old, ok := out[child]; ok && old != task { + conflicts[child] = true + } else { + out[child] = task + } + } + } + for child := range conflicts { + delete(out, child) + } + return out +} + +func codexTaskParentFiles(children, all []file) []file { + parents := map[string]bool{} + for _, f := range children { + if f.agent != "codex" { + continue + } + st := cache[f.path] + if st != nil && !st.CodexIdentityConflict && st.CodexIdentity != nil && st.CodexIdentity.Role == codexRoleSubagent && st.CodexIdentity.ParentSession != "" { + parents[st.CodexIdentity.ParentSession] = true + } + } + var out []file + for _, f := range all { + if f.agent == "codex" && parents[strings.TrimPrefix(f.key, "codex:")] { + out = append(out, f) + } + } + return out +} + +func setSessionCodexTaskTitle(s *Session, titles map[string]codexTaskTitle) { + if s.Agent != "codex" || s.Title != "" || s.Role != codexRoleSubagent || s.ParentSession == "" { + return + } + if task, ok := titles[s.ID]; ok && task.parent == s.ParentSession { + s.Title = task.title + } +} + func codexIdentitySnapshot(files []file) map[string]CodexIdentity { identities := map[string]CodexIdentity{} conflicts := map[string]bool{} @@ -400,7 +507,8 @@ func codexBody(s *state, b []byte, main bool) { } want := s.ID == "" && bytes.Contains(b, cxMeta) || bytes.Contains(b, cxTurn) || bytes.Contains(b, cxCount) || bytes.Contains(b, cxRecord) || bytes.Contains(b, cxCompacted) || bytes.Contains(b, cxStarted) || bytes.Contains(b, cxSettings) || - s.Title == "" && bytes.Contains(b, cxUserMsg) || (main || s.Title == "") && bytes.Contains(b, cxUserRole) + s.Title == "" && bytes.Contains(b, cxUserMsg) || (main || s.Title == "") && bytes.Contains(b, cxUserRole) || + bytes.Contains(b, cxSpawnAgent) || bytes.Contains(b, cxSubAgentActivity) && bytes.Contains(b, cxStartedKind) if !want { return } @@ -436,6 +544,39 @@ func codexBody(s *state, b []byte, main bool) { if s.Cwd == "" { s.Cwd = p.Cwd } + if p.AgentNickname != "" { + s.CodexNickname = p.AgentNickname + } + case l.Type == "response_item" && p.Type == "function_call" && p.Name == "spawn_agent": + if p.CallID != "" { + if name := title(gjson.Get(p.Arguments, "task_name").String()); name != "" { + if s.CodexSpawnNames == nil { + s.CodexSpawnNames = map[string]string{} + } + if old, ok := s.CodexSpawnNames[p.CallID]; ok && old != name { + if s.CodexSpawnConflicts == nil { + s.CodexSpawnConflicts = map[string]bool{} + } + s.CodexSpawnConflicts[p.CallID] = true + } else { + s.CodexSpawnNames[p.CallID] = name + } + } + } + case l.Type == "event_msg" && p.Type == "item_completed" && p.Item.Type == "SubAgentActivity" && p.Item.Kind == "started": + if p.Item.ID != "" && p.Item.AgentThreadID != "" { + if s.CodexAgentIDs == nil { + s.CodexAgentIDs = map[string]string{} + } + if old, ok := s.CodexAgentIDs[p.Item.ID]; ok && old != p.Item.AgentThreadID { + if s.CodexAgentConflicts == nil { + s.CodexAgentConflicts = map[string]bool{} + } + s.CodexAgentConflicts[p.Item.ID] = true + } else { + s.CodexAgentIDs[p.Item.ID] = p.Item.AgentThreadID + } + } case l.Type == "turn_context": codexState(s).context("", p.TurnID, p.Model) if p.Model != "" { diff --git a/internal/sessions/codex_subagent_details_test.go b/internal/sessions/codex_subagent_details_test.go new file mode 100644 index 000000000..efb0d07a7 --- /dev/null +++ b/internal/sessions/codex_subagent_details_test.go @@ -0,0 +1,237 @@ +package sessions + +import ( + "encoding/json" + "path/filepath" + "testing" + "time" +) + +func codexDetailsLine(t *testing.T, typ string, payload any) string { + t.Helper() + b, err := json.Marshal(struct { + Timestamp string `json:"timestamp"` + Type string `json:"type"` + Payload any `json:"payload"` + }{callT0.Format(time.RFC3339Nano), typ, payload}) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func codexDetailsRollout(t *testing.T, codex, id string, lines ...string) string { + t.Helper() + path := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T10-00-00-"+id+".jsonl") + writeLines(t, path, lines...) + return path +} + +func codexDetailsMeta(t *testing.T, id, session, parent, nickname string) string { + t.Helper() + payload := map[string]any{"id": id, "session_id": session, "source": "cli"} + if parent != "" { + payload["source"] = map[string]any{"subagent": map[string]any{"thread_spawn": map[string]string{"parent_thread_id": parent}}} + } + if nickname != "" { + payload["agent_nickname"] = nickname + } + return codexDetailsLine(t, "session_meta", payload) +} + +func codexDetailsSpawn(t *testing.T, callID, taskName string) string { + t.Helper() + args, err := json.Marshal(map[string]string{"task_name": taskName, "message": "anonymous fixture task body"}) + if err != nil { + t.Fatal(err) + } + payload := struct { + Type string `json:"type"` + Name string `json:"name"` + CallID string `json:"call_id"` + Arguments string `json:"arguments"` + }{"function_call", "spawn_agent", callID, string(args)} + return codexDetailsLine(t, "response_item", payload) +} + +func codexDetailsSubagentEvent(t *testing.T, callID, childID string) string { + return codexDetailsSubagentActivity(t, callID, childID, "started") +} + +func codexDetailsSubagentActivity(t *testing.T, callID, childID, kind string) string { + t.Helper() + payload := struct { + Type string `json:"type"` + Item struct { + Type string `json:"type"` + Kind string `json:"kind"` + ID string `json:"id"` + AgentThreadID string `json:"agent_thread_id"` + } `json:"item"` + }{Type: "item_completed"} + payload.Item.Type, payload.Item.Kind = "SubAgentActivity", kind + payload.Item.ID, payload.Item.AgentThreadID = callID, childID + return codexDetailsLine(t, "event_msg", payload) +} + +func TestCodexSubagentTaskTitleIgnoresOtherActivityKinds(t *testing.T) { + d := setupCalls(t) + codexDetailsRollout(t, d.codex, "main", + codexDetailsMeta(t, "main", "shared-session", "", ""), + codexDetailsSpawn(t, "call-interacted", "Task name from an interacted event"), + codexDetailsSubagentActivity(t, "call-interacted", "child-interacted", "interacted"), + codexDetailsSpawn(t, "call-completed", "Task name from a completed event"), + codexDetailsSubagentActivity(t, "call-completed", "child-completed", "completed"), + codexDetailsSpawn(t, "call-interrupted", "Task name from an interrupted event"), + codexDetailsSubagentActivity(t, "call-interrupted", "child-interrupted", "interrupted"), + ) + for i, id := range []string{"child-interacted", "child-completed", "child-interrupted"} { + codexDetailsRollout(t, d.codex, id, + codexDetailsMeta(t, id, "shared-session", "main", "Child"), + codexDetailsUsage(t, id, i+1), + ) + if got := Titles([]string{"codex:" + id})["codex:"+id]; got != "" { + t.Fatalf("non-start activity named a child: %q", got) + } + } +} + +func codexDetailsUsage(t *testing.T, id string, at int) string { + t.Helper() + payload := map[string]any{ + "response_id": "response-" + id, + "session_id": "shared-session", + "thread_id": id, + "turn_id": "turn-" + id, + "usage": map[string]int{"input_tokens": 12, "cached_input_tokens": 0, "cache_write_input_tokens": 0, "output_tokens": 3, "reasoning_output_tokens": 1, "total_tokens": 15}, + } + b, err := json.Marshal(map[string]any{"timestamp": callT0.Add(time.Duration(at) * time.Second).Format(time.RFC3339Nano), "type": "token_usage_record", "payload": payload}) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +func codexDetailsSession(t *testing.T, id string) Session { + t.Helper() + for _, got := range List(All) { + if got.Agent == "codex" && got.ID == id { + return got + } + } + t.Fatalf("Codex session %q is missing", id) + return Session{} +} + +func TestCodexSubagentTaskTitleAndNickname(t *testing.T) { + d := setupCalls(t) + codexDetailsRollout(t, d.codex, "main-a", + codexDetailsMeta(t, "main-a", "shared-session", "", ""), + codexDetailsSpawn(t, "call-child-b", "Use the explicit task name"), + codexDetailsSubagentEvent(t, "call-child-b", "child-b"), + codexDetailsSpawn(t, "call-child-c", "A task name must not replace a title"), + codexDetailsSubagentEvent(t, "call-child-c", "child-c"), + codexDetailsSpawn(t, "call-unmatched", "This task name has no exact child link"), + codexDetailsSubagentEvent(t, "different-call-id", "child-d"), + ) + codexDetailsRollout(t, d.codex, "child-b", + codexDetailsMeta(t, "child-b", "shared-session", "main-a", "Scout"), + codexDetailsUsage(t, "child-b", 1), + ) + codexDetailsRollout(t, d.codex, "child-c", + codexDetailsMeta(t, "child-c", "shared-session", "main-a", "Reviewer"), + codexDetailsLine(t, "response_item", map[string]any{"type": "message", "role": "user", "content": []map[string]string{{"type": "input_text", "text": "Existing user title"}}}), + codexDetailsUsage(t, "child-c", 2), + ) + codexDetailsRollout(t, d.codex, "child-d", + codexDetailsMeta(t, "child-d", "shared-session", "main-a", "Helper"), + codexDetailsUsage(t, "child-d", 3), + ) + + // A child-only title lookup must refresh its confirmed parent as well. + if got := Titles([]string{"codex:child-b"})["codex:child-b"]; got != "Use the explicit task name" { + t.Fatalf("Titles did not resolve the linked parent task name: %q", got) + } + if got := codexDetailsSession(t, "child-b"); got.Title != "Use the explicit task name" || got.Nickname != "Scout" { + t.Fatalf("linked task title and native nickname = %q / %q", got.Title, got.Nickname) + } + if got := codexDetailsSession(t, "child-c"); got.Title != "Existing user title" || got.Nickname != "Reviewer" { + t.Fatalf("task name replaced an existing title or nickname was lost: %q / %q", got.Title, got.Nickname) + } + if got := codexDetailsSession(t, "child-d"); got.Title != "" || got.Nickname != "Helper" { + t.Fatalf("unmatched task name was guessed or native nickname was lost: %q / %q", got.Title, got.Nickname) + } + + stats := StatsAt(7, callT0.Add(24*time.Hour)) + for _, summary := range stats.Sessions { + if summary.Agent != "codex" { + continue + } + switch summary.ID { + case "child-b": + if summary.Title != "Use the explicit task name" || summary.Nickname != "Scout" { + t.Errorf("summary lost child task details: %q / %q", summary.Title, summary.Nickname) + } + case "child-c": + if summary.Title != "Existing user title" || summary.Nickname != "Reviewer" { + t.Errorf("summary changed existing title or lost nickname: %q / %q", summary.Title, summary.Nickname) + } + } + } +} + +func TestCodexSubagentTaskTitleRefreshesWhenParentGrows(t *testing.T) { + d := setupCalls(t) + parent := codexDetailsRollout(t, d.codex, "main-a", + codexDetailsMeta(t, "main-a", "shared-session", "", ""), + codexDetailsSpawn(t, "call-child", "Incremental task name"), + ) + codexDetailsRollout(t, d.codex, "child", + codexDetailsMeta(t, "child", "shared-session", "main-a", "Child"), + codexDetailsUsage(t, "child", 1), + ) + if got := Titles([]string{"codex:child"})["codex:child"]; got != "" { + t.Fatalf("unmatched spawn call named the child: %q", got) + } + appendText(t, parent, codexDetailsSubagentEvent(t, "call-child", "child")+"\n") + if got := Titles([]string{"codex:child"})["codex:child"]; got != "Incremental task name" { + t.Fatalf("parent append did not refresh the child title: %q", got) + } +} + +func TestCodexSubagentConflictingSpawnLinksDoNotNameChildren(t *testing.T) { + d := setupCalls(t) + codexDetailsRollout(t, d.codex, "main-a", + codexDetailsMeta(t, "main-a", "shared-session", "", ""), + codexDetailsSpawn(t, "call-name", "First task name"), + codexDetailsSpawn(t, "call-name", "Conflicting task name"), + codexDetailsSubagentEvent(t, "call-name", "child-name"), + codexDetailsSpawn(t, "call-child", "Ambiguous child link"), + codexDetailsSubagentEvent(t, "call-child", "child-one"), + codexDetailsSubagentEvent(t, "call-child", "child-two"), + ) + for _, id := range []string{"child-name", "child-one", "child-two"} { + codexDetailsRollout(t, d.codex, id, + codexDetailsMeta(t, id, "shared-session", "main-a", ""), + codexDetailsUsage(t, id, 1), + ) + if got := Titles([]string{"codex:" + id})["codex:"+id]; got != "" { + t.Errorf("conflicting spawn metadata named %s: %q", id, got) + } + } +} + +func TestCodexSubagentNicknameInvalidatesOldParseCache(t *testing.T) { + d := setupCalls(t) + path := codexDetailsRollout(t, d.codex, "child", + codexDetailsMeta(t, "child", "shared-session", "main-a", "Fresh nickname"), + codexDetailsUsage(t, "child", 1), + ) + writeCache(&save{cacheFile: cacheFile{Version: cacheVersion - 1, Zone: zone(), Files: map[string]*state{path: { + ID: "child", CodexNickname: "stale nickname", Size: 1, Mod: 1, + }}}, path: CachePath()}) + Reset() + if got := codexDetailsSession(t, "child"); got.Nickname != "Fresh nickname" { + t.Fatalf("older parse cache hid the native nickname: %q", got.Nickname) + } +} diff --git a/internal/sessions/manage.go b/internal/sessions/manage.go index a03d2f51a..dd80b5f04 100644 --- a/internal/sessions/manage.go +++ b/internal/sessions/manage.go @@ -118,14 +118,17 @@ func ListAgent(agent string) []Managed { } refresh(mine, all) identities := map[string]CodexIdentity(nil) + taskTitles := map[string]codexTaskTitle(nil) if agent == "codex" { identities = codexIdentitySnapshot(mine) + taskTitles = codexSubagentTaskTitles(mine) } price := pricer() out := []Managed{} for _, fs := range groups { s, _ := assemble(fs, price) setSessionCodexIdentity(&s, identities) + setSessionCodexTaskTitle(&s, taskTitles) if s.Resume == "" && !s.ReadOnly { s.Resume = resumeCommand(s.WSL, s.Agent, s.ID, s.Cwd, s.Path) } diff --git a/internal/sessions/sessions.go b/internal/sessions/sessions.go index e0991132f..e6b8fbd7c 100644 --- a/internal/sessions/sessions.go +++ b/internal/sessions/sessions.go @@ -121,6 +121,7 @@ type Session struct { ID string `json:"id"` Cwd string `json:"cwd"` Title string `json:"title"` // the name it was given, else the agent's own title, else the first prompt + Nickname string `json:"nickname,omitempty"` Start time.Time `json:"start"` Last time.Time `json:"last"` Role string `json:"role,omitempty"` @@ -175,6 +176,11 @@ type state struct { ID string `json:"id,omitempty"` CodexIdentity *CodexIdentity `json:"codex_identity,omitempty"` CodexIdentityConflict bool `json:"codex_identity_conflict,omitempty"` + CodexNickname string `json:"codex_nickname,omitempty"` + CodexSpawnNames map[string]string `json:"codex_spawn_names,omitempty"` + CodexSpawnConflicts map[string]bool `json:"codex_spawn_conflicts,omitempty"` + CodexAgentIDs map[string]string `json:"codex_agent_ids,omitempty"` + CodexAgentConflicts map[string]bool `json:"codex_agent_conflicts,omitempty"` Cwd string `json:"cwd,omitempty"` Title string `json:"title,omitempty"` Named string `json:"named,omitempty"` // the agent's own title for it @@ -337,6 +343,10 @@ func (s *state) clone() *state { t := *s.Total c.Total = &t } + c.CodexSpawnNames = maps.Clone(s.CodexSpawnNames) + c.CodexSpawnConflicts = maps.Clone(s.CodexSpawnConflicts) + c.CodexAgentIDs = maps.Clone(s.CodexAgentIDs) + c.CodexAgentConflicts = maps.Clone(s.CodexAgentConflicts) c.Days = make(map[string]*day, len(s.Days)) for k, v := range s.Days { d := &day{Active: v.Active, Models: make(map[string]Tokens, len(v.Models)), Prompts: v.Prompts, Replies: v.Replies} @@ -608,7 +618,8 @@ func CachePath() string { return filepath.Join(filepath.Dir(catalog.CachePath()) // 18: Claude Code's 1-hour cache writes apart from its 5-minute ones. // 19: the names the user gave Claude Code's and WorkBuddy's (custom-title). // 20: Codex's source and direct parent thread identity. -const cacheVersion = 20 +// 21: Codex subagent nicknames and parent spawn task names. +const cacheVersion = 21 type cacheFile struct { Version int `json:"version"` @@ -1004,12 +1015,14 @@ func List(limit int) []Session { // after it has nothing left to do refresh(files, files) identities := codexIdentitySnapshot(files) + taskTitles := codexSubagentTaskTitles(files) price := pricer() out := []Session{} for _, k := range keys { if s, ok := assemble(groups[k], price); ok { setSessionCodexIdentity(&s, identities) + setSessionCodexTaskTitle(&s, taskTitles) out = append(out, s) if len(out) == limit { break @@ -1061,6 +1074,9 @@ func assemble(fs []file, price func(string) *catalog.Price) (Session, bool) { s.ID = st.ID } } + if s.Agent == "codex" && st.CodexNickname != "" { + s.Nickname = st.CodexNickname + } if !st.Start.IsZero() && (s.Start.IsZero() || st.Start.Before(s.Start)) { s.Start = st.Start } @@ -1548,9 +1564,21 @@ func Titles(keys []string) map[string]string { return out } refresh(fs, files) + parents := codexTaskParentFiles(fs, files) + if len(parents) > 0 { + refresh(parents, files) + } + titleFiles := append(append([]file(nil), fs...), parents...) + taskTitles := codexSubagentTaskTitles(titleFiles) + identities := codexIdentitySnapshot(fs) price := pricer() for k, g := range groups { - if s, ok := assemble(g, price); ok && s.Title != "" { + if s, ok := assemble(g, price); ok { + setSessionCodexIdentity(&s, identities) + setSessionCodexTaskTitle(&s, taskTitles) + if s.Title == "" { + continue + } out[k] = s.Title } } @@ -1575,6 +1603,7 @@ func Get(key string) (Session, bool) { return Session{}, false } var identities map[string]CodexIdentity + var taskTitles map[string]codexTaskTitle if strings.HasPrefix(key, "codex:") { var codexFiles []file for _, f := range files { @@ -1584,10 +1613,12 @@ func Get(key string) (Session, bool) { } refresh(codexFiles, files) identities = codexIdentitySnapshot(codexFiles) + taskTitles = codexSubagentTaskTitles(codexFiles) } else { refresh(fs, files) } s, ok := assemble(fs, pricer()) setSessionCodexIdentity(&s, identities) + setSessionCodexTaskTitle(&s, taskTitles) return s, ok } diff --git a/internal/sessions/stats.go b/internal/sessions/stats.go index 411715b31..e37406dce 100644 --- a/internal/sessions/stats.go +++ b/internal/sessions/stats.go @@ -34,6 +34,7 @@ type Summary struct { ID string `json:"id"` Cwd string `json:"cwd"` Title string `json:"title"` + Nickname string `json:"nickname,omitempty"` Last time.Time `json:"last"` Role string `json:"role,omitempty"` ParentSession string `json:"parent_session,omitempty"` @@ -124,6 +125,7 @@ func statsAt(days int, now time.Time) Stats { // finds them read rather than starting another run refresh(files, files) identities := codexIdentitySnapshot(files) + taskTitles := codexSubagentTaskTitles(files) var want []file for _, f := range files { if !f.mod.Before(since) { @@ -309,8 +311,10 @@ func statsAt(days int, now time.Time) Stats { continue } setSessionCodexIdentity(&s, identities) + setSessionCodexTaskTitle(&s, taskTitles) sum := Summary{Key: key, Agent: s.Agent, ID: s.ID, Cwd: cmp.Or(folder[key], s.Cwd), Title: clip(s.Title, 160), - Last: s.Last, Role: s.Role, ParentSession: s.ParentSession, RootSession: s.RootSession, Priced: true, Active: sh.active / 1000, Models: []string{}, Days: []int{}, + Nickname: s.Nickname, + Last: s.Last, Role: s.Role, ParentSession: s.ParentSession, RootSession: s.RootSession, Priced: true, Active: sh.active / 1000, Models: []string{}, Days: []int{}, Prompts: sh.prompts, Replies: sh.replies, tools: sh.tools, skills: sh.skills, skillLast: sh.skillLast, perDay: map[int]*summaryDay{}} for _, n := range sh.tools { diff --git a/internal/usage/codex_compaction_test.go b/internal/usage/codex_compaction_test.go new file mode 100644 index 000000000..47f4a94ee --- /dev/null +++ b/internal/usage/codex_compaction_test.go @@ -0,0 +1,305 @@ +package usage + +import ( + "encoding/json" + "math" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/sessions" +) + +func codexCompactionCall(at time.Time, responseID string, input, output int, compacted bool) sessions.Call { + return sessions.Call{Time: at, Agent: "codex", Session: "fixture-session", ThreadID: "fixture-thread", ResponseID: responseID, + Model: "native-model", Effort: "native-effort", Tokens: sessions.Tokens{Input: input, Output: output}, Millis: 1000, Compaction: compacted} +} + +func compactionValue(row Row) (bool, bool) { + if row.Compaction == nil { + return false, false + } + return *row.Compaction, true +} + +func TestCodexCompactionLedgerCorrelationAndDuplicateMerge(t *testing.T) { + for _, reverse := range []bool{false, true} { + t.Run(map[bool]string{false: "late marker last", true: "late marker first"}[reverse], func(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)) + at := now.Add(-time.Hour) + for i, row := range []struct { + id string + input int + output int + kind string + effort string + }{ + {"resp-true", 11, 1, "chat", "gw-high"}, + {"resp-duplicate", 13, 2, "tool", "gw-low"}, + {"resp-false", 17, 3, "analysis", "gw-medium"}, + {"resp-unpaired", 19, 4, "chat", "gw-high"}, + } { + Append(Record{Time: at.Add(time.Duration(i) * time.Second), Agent: "codex", Provider: "openai", Model: "m", Served: "m", + Effort: row.effort, Kind: row.kind, Input: row.input, Output: row.output, Status: 200, ResponseID: row.id}) + } + duplicateFalse := codexCompactionCall(at.Add(time.Second), "resp-duplicate", 900, 90, false) + duplicateTrue := duplicateFalse + duplicateTrue.Compaction = true + duplicateTrue.Compact = 25 // internal call timing stays out of the HTTP usage row + duplicates := []sessions.Call{duplicateFalse, duplicateTrue} + if reverse { + duplicates[0], duplicates[1] = duplicates[1], duplicates[0] + } + native := []sessions.Call{ + codexCompactionCall(at, "resp-true", 800, 80, true), + duplicates[0], duplicates[1], + codexCompactionCall(at.Add(2*time.Second), "resp-false", 700, 70, false), + codexCompactionCall(at.Add(4*time.Second), "resp-direct-true", 23, 4, true), + codexCompactionCall(at.Add(5*time.Second), "resp-direct-false", 29, 5, false), + } + old := LogCalls + LogCalls = func(time.Time) []sessions.Call { return native } + defer func() { LogCalls = old }() + + ledger := LedgerOf(All, Filter{}) + if ledger.Sum.Calls != 6 || len(ledger.Rows) != 6 || ledger.Sum.Input != 112 || ledger.Sum.Output != 19 { + t.Fatalf("matched native calls were counted or billed again: totals=%+v rows=%+v", ledger.Sum, ledger.Rows) + } + if math.Abs(ledger.Sum.Cost-0.0002) > 1e-12 { + t.Fatalf("gateway price changed or native call was billed twice: %v", ledger.Sum.Cost) + } + for id, want := range map[string]bool{"resp-true": true, "resp-duplicate": true, "resp-false": false} { + row, ok := findRowByResponse(ledger.Rows, id) + got, known := compactionValue(row) + if !ok || !known || got != want { + t.Errorf("%s compaction = %v, known=%v, found=%v; want %v", id, got, known, ok, want) + } + } + row, ok := findRowByResponse(ledger.Rows, "resp-true") + if !ok || row.Model != "m" || row.Effort != "gw-high" || row.Kind != "chat" || row.Input != 11 || row.Output != 1 || !row.Priced { + t.Fatalf("native metadata replaced gateway request details: %+v", row) + } + if _, known := compactionValue(mustResponseRow(t, ledger.Rows, "resp-unpaired")); known { + t.Fatal("an unpaired gateway row claimed native compaction evidence") + } + if compacted, known := compactionValue(mustResponseRow(t, ledger.Rows, "resp-direct-true")); !known || !compacted { + t.Fatal("native-only compacted call lost its marker") + } + if compacted, known := compactionValue(mustResponseRow(t, ledger.Rows, "resp-direct-false")); !known || compacted { + t.Fatal("native-only non-compacted call lost its false marker") + } + trueJSON, _ := json.Marshal(mustResponseRow(t, ledger.Rows, "resp-direct-true")) + falseJSON, _ := json.Marshal(mustResponseRow(t, ledger.Rows, "resp-false")) + orphanJSON, _ := json.Marshal(mustResponseRow(t, ledger.Rows, "resp-unpaired")) + if string(trueJSON) == "" || !strings.Contains(string(trueJSON), `"compaction":true`) || strings.Contains(string(trueJSON), `"compact_ms"`) { + t.Fatalf("Codex usage JSON marker: %s", trueJSON) + } + if !strings.Contains(string(falseJSON), `"compaction":false`) || strings.Contains(string(orphanJSON), `"compaction"`) { + t.Fatalf("Codex three-state usage JSON: false=%s orphan=%s", falseJSON, orphanJSON) + } + }) + } +} + +func mustResponseRow(t *testing.T, rows []Row, responseID string) Row { + t.Helper() + row, ok := findRowByResponse(rows, responseID) + if !ok { + t.Fatalf("response %s missing from %+v", responseID, rows) + } + return row +} + +func TestCodexRequestPageDoesNotMutateSharedCompactionChunks(t *testing.T) { + pageHome(t) + now := time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC) + yes, no := true, false + makeChunks := func(responseID string, compacted ...bool) (*rowChunk, *rowChunk) { + gateway, native := &rowChunk{}, &rowChunk{} + gateway.add(Row{Record: Record{Time: now.Add(-time.Minute), Agent: "codex", Provider: "openai", Model: "gateway-model", + Input: 12, Output: 2, Status: 200, ResponseID: responseID}}, "", 1, false) + for i, marker := range compacted { + marker := marker + native.add(Row{Record: Record{Time: now.Add(-time.Hour), Agent: "codex", Model: "native-model", ResponseID: responseID, + Compaction: &marker}, Source: "log"}, "", int64(i), false) + } + return gateway, native + } + build := func(gateway, native *rowChunk) RequestPage { + var natives []*rowChunk + if native != nil { + natives = []*rowChunk{native} + } + return buildRequestBlocksWithCodex(All, Filter{}, 0, 100, now, []*rowChunk{gateway}, natives, nil, nil, nil) + } + assertMarker := func(t *testing.T, page RequestPage, want bool) { + t.Helper() + if len(page.Rows) != 1 { + t.Fatalf("page rows = %d, want one gateway row: %+v", len(page.Rows), page.Rows) + } + got, known := compactionValue(page.Rows[0]) + if !known || got != want { + t.Fatalf("page compaction = %v, known=%v; want %v", got, known, want) + } + } + assertNoMarker := func(t *testing.T, page RequestPage) { + t.Helper() + if len(page.Rows) != 1 { + t.Fatalf("page rows = %d, want one gateway row: %+v", len(page.Rows), page.Rows) + } + if _, known := compactionValue(page.Rows[0]); known { + t.Fatalf("unpaired page has compaction evidence: %+v", page.Rows[0]) + } + } + + t.Run("removing unique match clears evidence", func(t *testing.T) { + gateway, native := makeChunks("resp-unique", yes) + assertMarker(t, build(gateway, native), true) + if gateway.Rows[0].Flags&(rowCompactionKnown|rowCompaction) != 0 { + t.Fatal("request build wrote the native compaction marker into the cached gateway chunk") + } + assertNoMarker(t, build(gateway, nil)) + if gateway.Rows[0].Flags&(rowCompactionKnown|rowCompaction) != 0 { + t.Fatal("unpaired request retained compaction evidence from an earlier page build") + } + }) + + t.Run("changed duplicate copies recompute marker", func(t *testing.T) { + gateway, native := makeChunks("resp-duplicate", no, yes) + assertMarker(t, build(gateway, native), true) + if native.Rows[0].Flags&(rowCompactionKnown|rowCompaction) != rowCompactionKnown { + t.Fatal("duplicate folding wrote the merged marker into the cached native chunk") + } + if native.Rows[1].Flags&(rowCompactionKnown|rowCompaction) != rowCompactionKnown|rowCompaction { + t.Fatal("request build changed the second cached native copy") + } + _, changedNative := makeChunks("resp-duplicate", no, no) + assertMarker(t, build(gateway, changedNative), false) + }) + + t.Run("concurrent page builds share immutable chunks", func(t *testing.T) { + gateway, native := makeChunks("resp-concurrent", no, yes) + var wg sync.WaitGroup + errs := make(chan string, 8) + for i := 0; i < cap(errs); i++ { + wg.Add(1) + go func() { + defer wg.Done() + page := build(gateway, native) + if len(page.Rows) != 1 { + errs <- "page did not contain exactly one gateway row" + return + } + got, known := compactionValue(page.Rows[0]) + if !known || !got { + errs <- "page lost duplicate-merged compaction marker" + } + }() + } + wg.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + if gateway.Rows[0].Flags&(rowCompactionKnown|rowCompaction) != 0 || native.Rows[0].Flags&(rowCompactionKnown|rowCompaction) != rowCompactionKnown { + t.Fatal("concurrent page builds mutated shared source rows") + } + }) +} + +func TestCodexLateCompactionMarkerInvalidatesRequestAndEffortCaches(t *testing.T) { + pageHome(t) + now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC)) + at := now.Add(-time.Hour) + root := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30") + pairedPath := filepath.Join(root, "rollout-2026-09-30T10-00-00-fixture-thread-paired.jsonl") + directPath := filepath.Join(root, "rollout-2026-09-30T10-00-00-fixture-thread-direct.jsonl") + writeCodexCall(t, pairedPath, "fixture-thread", "fixture-session", `"vscode"`, "resp-paired", "native-model", "native-low", at, 100, 10) + writeCodexCall(t, directPath, "fixture-thread", "fixture-session", `"vscode"`, "resp-direct", "native-model", "native-low", at.Add(time.Minute), 30, 3) + Append(Record{Time: at, Agent: "codex", Provider: "openai", Model: "m", Served: "m", Effort: "gateway-high", Kind: "chat", + Input: 60, Output: 6, Status: 200, ResponseID: "resp-paired"}) + pageBuilds, effortBuilds := 0, 0 + building = func() { pageBuilds++ } + effortBuilt = func() { effortBuilds++ } + t.Cleanup(func() { building, effortBuilt = nil, nil }) + + first := QueryPage(All, Filter{}, 0, 100) + if first.Total != 2 || first.Sum.Input != 90 || first.Sum.Output != 9 || first.Through.Calls != 1 || first.Direct.Calls != 1 || pageBuilds != 1 { + t.Fatalf("initial page totals/builds: %+v, builds=%d", first, pageBuilds) + } + paired, _ := findRowByResponse(first.Rows, "resp-paired") + if compacted, known := compactionValue(paired); !known || compacted { + t.Fatalf("initial paired row compaction = %v, known=%v", compacted, known) + } + if _, known := compactionValue(mustResponseRow(t, first.Rows, "resp-direct")); !known { + t.Fatal("direct native row omitted its non-compaction marker") + } + initialEffort := CodexModelEffort(All) + if effortBuilds != 1 || !hasEffortInput(initialEffort["fixture-thread"], "m", "gateway-high", 60) { + t.Fatalf("initial model-effort cache: builds=%d values=%+v", effortBuilds, initialEffort) + } + CodexModelEffort(All) + if effortBuilds != 1 { + t.Fatalf("unchanged model-effort read rebuilt %d times", effortBuilds) + } + + appendCompactionLine(t, pairedPath, "resp-paired", "fixture-thread", "fixture-session", "turn-resp-paired", at.Add(time.Second), 100, 10) + changedAt := now.Add(5 * time.Minute) + if err := os.Chtimes(pairedPath, changedAt, changedAt); err != nil { + t.Fatal(err) + } + second := QueryPage(All, Filter{}, 0, 100) + paired, _ = findRowByResponse(second.Rows, "resp-paired") + if second.Total != 2 || second.Sum.Input != 90 || second.Sum.Output != 9 || second.Through.Calls != 1 || second.Direct.Calls != 1 || pageBuilds != 2 { + t.Fatalf("late marker duplicated usage or skipped request-page rebuild: %+v builds=%d", second, pageBuilds) + } + if compacted, known := compactionValue(paired); !known || !compacted { + t.Fatalf("late native marker did not reach the cached gateway row: %v, known=%v", compacted, known) + } + packedPage := QueryPage(All, Filter{}, 1, 100) + if pageBuilds != 3 { + t.Fatalf("a second page did not reuse the packed native chunk: builds=%d", pageBuilds) + } + packedPair := mustResponseRow(t, packedPage.Rows, "resp-paired") + if compacted, known := compactionValue(packedPair); !known || !compacted { + t.Fatalf("packed chunk lost the late marker: %v, known=%v", compacted, known) + } + updatedEffort := CodexModelEffort(All) + if effortBuilds != 2 || !hasEffortInput(updatedEffort["fixture-thread"], "m", "gateway-high", 60) { + t.Fatalf("late marker did not invalidate model-effort cache: builds=%d values=%+v", effortBuilds, updatedEffort) + } + if math.Abs(second.Sum.Cost-0.000168) > 1e-12 { + t.Fatalf("late marker changed gateway cost: %v", second.Sum.Cost) + } +} + +func hasEffortInput(rows []sessions.ModelEffort, model, effort string, input int) bool { + row, ok := findModelEffort(rows, model, effort) + return ok && row.Input == input +} + +func appendCompactionLine(t *testing.T, path, responseID, threadID, sessionID, turnID string, at time.Time, input, output int) { + t.Helper() + usage := map[string]int{"input_tokens": input, "cached_input_tokens": 0, "cache_write_input_tokens": 0, + "output_tokens": output, "reasoning_output_tokens": 0, "total_tokens": input + output} + line, err := json.Marshal(map[string]any{"timestamp": at.Format(time.RFC3339Nano), "type": "compacted", "payload": map[string]any{ + "compaction_response_id": responseID, + "latest_token_usage_record": map[string]any{"response_id": responseID, "session_id": sessionID, "thread_id": threadID, "turn_id": turnID, + "usage": usage, "thread_token_usage": usage}, + }}) + if err != nil { + t.Fatal(err) + } + f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if _, err := f.Write(append(line, '\n')); err != nil { + t.Fatal(err) + } +} diff --git a/internal/usage/codex_identity.go b/internal/usage/codex_identity.go index a398b6231..744335aea 100644 --- a/internal/usage/codex_identity.go +++ b/internal/usage/codex_identity.go @@ -73,6 +73,34 @@ func sameCodexCall(a, b Row) bool { a.Error == b.Error && a.ErrType == b.ErrType && a.RequestID == b.RequestID } +func codexCompactionOf(call sessions.Call) *bool { + if call.Agent != "codex" { + return nil + } + compacted := call.Compaction + return &compacted +} + +func mergeCodexCompactions(values []*bool) *bool { + allKnown, confirmed := len(values) > 0, false + for _, value := range values { + if value == nil { + allKnown = false + continue + } + confirmed = confirmed || *value + } + if confirmed { + yes := true + return &yes + } + if allKnown { + no := false + return &no + } + return nil +} + func isCodexRow(row Row) bool { if row.Client != "" { return row.Client == "codex" @@ -80,14 +108,19 @@ func isCodexRow(row Row) bool { return row.Agent == "codex" } -func duplicateCodexCalls(calls []sessions.Call) (map[int]bool, map[int]string) { +func duplicateCodexCalls(calls []sessions.Call) (map[int]bool, map[int]string, map[int]*bool) { local := map[string][]int{} for i, call := range calls { if call.Agent == "codex" && call.ResponseID != "" { local[call.ResponseID] = append(local[call.ResponseID], i) } } - skip, actors := map[int]bool{}, map[int]string{} + skip, actors, compactions := map[int]bool{}, map[int]string{}, map[int]*bool{} + for index, call := range calls { + if call.Agent == "codex" { + compactions[index] = codexCompactionOf(call) + } + } for _, indexes := range local { if len(indexes) < 2 { continue @@ -114,13 +147,18 @@ func duplicateCodexCalls(calls []sessions.Call) (map[int]bool, map[int]string) { for _, index := range indexes[1:] { skip[index] = true } + merged := make([]*bool, len(indexes)) + for i, index := range indexes { + merged[i] = codexCompactionOf(calls[index]) + } + compactions[indexes[0]] = mergeCodexCompactions(merged) if actorConflict { actors[indexes[0]] = "" } else { actors[indexes[0]] = actor } } - return skip, actors + return skip, actors, compactions } func cloneCodexChunks(chunks []*rowChunk) []*rowChunk { @@ -128,6 +166,7 @@ func cloneCodexChunks(chunks []*rowChunk) []*rowChunk { for i, chunk := range chunks { copy := *chunk copy.codexActors = slices.Clone(chunk.codexActors) + copy.codexCompactions = nil copy.codexIdentities = nil out[i] = © } @@ -220,6 +259,11 @@ func foldCodexRows(locals []*rowChunk) map[rowRef]bool { for _, ref := range refs[1:] { skip[ref] = true } + compactions := make([]*bool, len(refs)) + for i := range refs { + compactions[i] = rows[i].Compaction + } + refs[0].Chunk.setCodexCompaction(refs[0].Index, mergeCodexCompactions(compactions)) } return skip } diff --git a/internal/usage/direct.go b/internal/usage/direct.go index ded82b58e..4bc4a3275 100644 --- a/internal/usage/direct.go +++ b/internal/usage/direct.go @@ -46,6 +46,7 @@ func directRows(p Period, now time.Time) []Row { logs, others := reader(since), sharedRecords(since) matched := map[int]bool{} actors := map[int]string{} + _, _, compactions := duplicateCodexCalls(logs) if len(logs) > 0 { local := &rowChunk{} for i, c := range logs { @@ -76,7 +77,7 @@ func directRows(p Period, now time.Time) []Row { } } } - rows, _, _, _ := ledgerMatched(since, until, Filter{}, nil, logs, others, matched, nil, actors) + rows, _, _, _ := ledgerMatched(since, until, Filter{}, nil, logs, others, matched, nil, actors, compactions) return rows } diff --git a/internal/usage/ledger.go b/internal/usage/ledger.go index a523e94e1..d16089e1a 100644 --- a/internal/usage/ledger.go +++ b/internal/usage/ledger.go @@ -344,6 +344,8 @@ func logRecord(c sessions.Call) Record { Millis: c.Millis, TTFT: c.TTFT, Session: c.Session, RequestID: c.RequestID, Error: c.ErrorText, ErrType: c.Error, Subagent: sessions.SubagentOf(c.File), ParentAgent: sessions.SubagentParent(c.File)} if c.Agent == "codex" { r.ResponseID = c.ResponseID + compacted := c.Compaction + r.Compaction = &compacted } if c.Agent == "codex" || c.Agent == "opencode" { r.Requested, r.Served = c.Model, "" @@ -359,11 +361,11 @@ func logRecord(c sessions.Call) Record { // and an end within 2s. Fallback matches must be unique in both logs: an // ambiguous direct call stays visible. One gateway entry consumes one file call. func gatewayMatches(recs []Record, logs []sessions.Call) map[int]bool { - matched, _, _ := gatewayMatchesDetails(recs, logs) + matched, _, _, _ := gatewayMatchesDetails(recs, logs) return matched } -func gatewayMatchesDetails(recs []Record, logs []sessions.Call) (map[int]bool, map[int]int, map[int]string) { +func gatewayMatchesDetails(recs []Record, logs []sessions.Call) (map[int]bool, map[int]int, map[int]string, map[int]*bool) { gateway, local := &rowChunk{}, &rowChunk{} for i, r := range recs { r.Agent = ReportedAs(r.Agent) @@ -374,7 +376,7 @@ func gatewayMatchesDetails(recs []Record, logs []sessions.Call) (map[int]bool, m r.Agent = c.Agent // the native log already names its agent local.add(Row{Record: r, codexActor: codexActor(c)}, c.Msg, int64(i), c.Error != "") } - duplicates, actors := duplicateCodexCalls(logs) + duplicates, actors, compactions := duplicateCodexCalls(logs) pairs := codexResponseMatches(recs, logs, duplicates) deduplicate := map[rowRef]bool{} for index := range duplicates { @@ -391,7 +393,7 @@ func gatewayMatchesDetails(recs []Record, logs []sessions.Call) (map[int]bool, m for index := range duplicates { matched[index] = true } - return matched, pairs, actors + return matched, pairs, actors, compactions } func ledgerWith(since time.Time, f Filter, recs []Record, logs []sessions.Call) (rows []Row, sum Totals, agents, providers []string) { @@ -402,13 +404,13 @@ func ledgerWith(since time.Time, f Filter, recs []Record, logs []sessions.Call) // priced and judged here as this computer's are, and none from until on (a // picked range's end, #1492; zero for none). func ledgerWithShared(since, until time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall) (rows []Row, sum Totals, agents, providers []string) { - matched, pairs, actors := gatewayMatchesDetails(recs, logs) - return ledgerMatched(since, until, f, recs, logs, others, matched, pairs, actors) + matched, pairs, actors, compactions := gatewayMatchesDetails(recs, logs) + return ledgerMatched(since, until, f, recs, logs, others, matched, pairs, actors, compactions) } // ledgerMatched is ledgerWithShared with the session files' calls the // gateway saw already told (matched, by their index in logs). -func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall, matched map[int]bool, pairs map[int]int, actors map[int]string) (rows []Row, sum Totals, agents, providers []string) { +func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessions.Call, others []SharedCall, matched map[int]bool, pairs map[int]int, actors map[int]string, compactions map[int]*bool) (rows []Row, sum Totals, agents, providers []string) { renamed := provider.Renamed() // the upstream names in force now, read once for the lot: a row is // judged by the names standing today, which is what Ledger says, and @@ -457,6 +459,7 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi if override, ok := actors[call]; ok { actor = override } + r.Compaction = compactions[call] } add(r, priceOf(r), r.Source, actor) } @@ -467,6 +470,9 @@ func ledgerMatched(since, until time.Time, f Filter, recs []Record, logs []sessi // Session identity does not establish a billing provider; price the // record through the same lookup without inferring one from the account. r := logRecord(c) + if metadata, ok := compactions[i]; ok { + r.Compaction = metadata + } actor := codexActor(c) if override, ok := actors[i]; ok { actor = override diff --git a/internal/usage/reasoning_stream_speed_test.go b/internal/usage/reasoning_stream_speed_test.go index b74a6479f..5d1483426 100644 --- a/internal/usage/reasoning_stream_speed_test.go +++ b/internal/usage/reasoning_stream_speed_test.go @@ -149,7 +149,7 @@ func TestRowFlagsApart(t *testing.T) { } }) } - bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost} + bits := []uint16{1, 2, 4, 8, 16, 32, swapKnown, rowHandedOn, rowReasoningHidden, rowOwnCost, rowCompactionKnown, rowCompaction} var all uint16 for _, b := range bits { if all&b != 0 { diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 5a2b00411..e07ea5713 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -79,6 +79,8 @@ type packedRow struct { const ( rowHandedOn = 128 rowReasoningHidden = 512 + rowCompactionKnown = 1024 + rowCompaction = 2048 ) // rowOwnCost marks a reported call that said what it cost (#1874): Cost is @@ -87,18 +89,19 @@ const ( const rowOwnCost = 256 type rowChunk struct { - Archive []byte - Locations []*time.Location - Rows []packedRow - Strings []string - codexActors []string - codexIdentities map[string]sessions.CodexIdentity - dict map[string]uint32 - Source sessions.CallSource - Bytes int64 - Used uint64 - Count int - Latest time.Time + Archive []byte + Locations []*time.Location + Rows []packedRow + Strings []string + codexActors []string + codexCompactions map[int]*bool + codexIdentities map[string]sessions.CodexIdentity + dict map[string]uint32 + Source sessions.CallSource + Bytes int64 + Used uint64 + Count int + Latest time.Time // Computer is the other computer whose day this is (#542), by id Computer string } @@ -168,6 +171,12 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) { p.Flags |= rowOwnCost p.Cost = *r.OwnCost } + if r.Compaction != nil { + p.Flags |= rowCompactionKnown + if *r.Compaction { + p.Flags |= rowCompaction + } + } c.Rows = append(c.Rows, p) if c.codexActors != nil || r.codexActor != "" { if c.codexActors == nil { @@ -188,6 +197,18 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) { func (c *rowChunk) row(i int) Row { p := &c.Rows[i] r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time, Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: p.Millis, TTFT: p.TTFT, FirstText: p.FirstText, FirstReasoning: p.FirstReasoning, ReasoningHidden: p.Flags&rowReasoningHidden != 0, Sent: p.Sent, Flow: p.Flow, Own: p.Own, Retried: p.Retried, Queued: p.Queued, Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0} + if p.Flags&rowCompactionKnown != 0 { + compacted := p.Flags&rowCompaction != 0 + r.Compaction = &compacted + } + if compacted, ok := c.codexCompactions[i]; ok { + if compacted == nil { + r.Compaction = nil + } else { + value := *compacted + r.Compaction = &value + } + } for i, s := range rowText(&r) { *s = c.Strings[p.Text[i]] } @@ -212,6 +233,18 @@ func (c *rowChunk) row(i int) Row { return r } +func (c *rowChunk) setCodexCompaction(index int, compacted *bool) { + if c.codexCompactions == nil { + c.codexCompactions = make(map[int]*bool) + } + if compacted == nil { + c.codexCompactions[index] = nil + return + } + value := *compacted + c.codexCompactions[index] = &value +} + type rowRef struct { Chunk *rowChunk Index int @@ -877,6 +910,7 @@ func buildRequestBlocksWithCodex(p Period, f Filter, offset, limit int, now time actor = local.Chunk.codexActors[local.Index] } setCodexActor(gateway.Chunk, gateway.Index, actor) + gateway.Chunk.setCodexCompaction(gateway.Index, local.row().Compaction) } all := append(append(slices.Clone(gateways), chunks...), others...) visit := func(fn func(rowRef, Row)) { diff --git a/internal/usage/usage.go b/internal/usage/usage.go index ddf25a844..840d07e86 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -95,6 +95,9 @@ type Record struct { // none for a reply that wasn't streamed (#196) TTFT int64 `json:"ttft_ms,omitempty"` FirstText int64 `json:"first_text_ms,omitempty"` + // Compaction is Codex's explicit native marker. Nil means no matching + // native Codex call established whether a gateway row compacted. + Compaction *bool `json:"compaction,omitempty"` // FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning. FirstReasoning int64 `json:"first_reasoning_ms,omitempty"` ReasoningHidden bool `json:"reasoning_hidden,omitempty"`