Preserve native Codex thread IDs and explicit parent chains. Associate gateway calls with their actual thread by unique response ID before legacy matching; fold identical native history copies and keep ambiguous actors unknown. Existing Sessions APIs expose optional Codex roles, parent/root relationships and per-thread model/effort consumption. The overview uses its existing calendar range. Usage request APIs expose query-time actor classification and reuse session/subagent/parent_agent for Codex. Other agents, pricing, gateway routing, UI assets, raw Usage logs and model-only aggregation retain their semantics. Verified after rebasing onto main331c27703a, at commit 50baace0a52953263dddc49f4dc55f97a8457dd1, code tree 78743e334f8c841e2a188aafe26996c016a8fa4b. Only this message is amended afterward. Go 1.26.8 darwin/arm64; tests used temporary HOME and pinned Go caches. Passed (each exit 0): - git diff --name-only origin/main...HEAD -- '*.go' | xargs gofmt -l (no output) - go vet ./... - GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go vet -tags nogui ./... - GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go vet ./... - go build -o /tmp/magpie-codex-session-identity-p4-darwin - GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -tags nogui -o /tmp/magpie-codex-session-identity-p4-linux - GOOS=windows GOARCH=amd64 CGO_ENABLED=0 go build -o /tmp/magpie-codex-session-identity-p4-windows.exe - go test -tags nogui ./... - go test -race -tags nogui ./internal/sessions ./internal/usage ./internal/gui -run '^(TestCodexIdentityParentChainsAndSummaryCache|TestCodexIdentityParentMergeAcrossRolloutFiles|TestCodexCallThreadIDPriorityAndCache|TestCodexCompactionPromotesThreadID|TestCodexSourceNativeVariants|TestCodexIdentityFieldsOmitOtherAgents|TestCodexIdentityInvalidatesOldSummaryCache|TestCodexLedgerResponseIdentityAndOwnConsumption|TestCodexRequestPageFoldsCopiesBeforeResponseMatching|TestCodexExactResponsePairPreemptsLegacyMatchInLedgerAndDirect|TestCodexQueryPageExactResponsePairPreemptsLegacyMatch|TestCodexRejectedGatewayDoesNotPairWithNativeCall|TestCodexKnownSubagentWithUnknownRootKeepsOwnConsumption|TestCodexQueryPageRefreshesIdentityAndSharesJSONFields|TestCodexActorSurvivesPackedRequestChunk|TestPackedRequestPageCallerAndRouteIdentity|TestPackedGatewayRetainsOversizedSnapshot|TestCodexSessionAPIAddsOwnModelEffort)$' -count=1 - git diff --check Behavior-break proof: removing identity/thread-ID promotion fails native identity, upgrade/conflict and compaction assertions. Disabling exact-pair preemption loses a neighboring main call. Removing API enrichment yields missing consumption; using All for a 7-day overview yields 740/74 instead of 40/4. Restored code passed its targeted tests and the final checks above. Native checks had Clang enum/linker deployment-target warnings. Linux/Windows runtime, real accounts/vendors and manual UI were not exercised. No frontend suite was run because the change does not touch GUI assets. Refs #1591 (Codex portion only). Reviewed and applied by yetone (cherry-picked from Hogeexxl's fork, bf8c8c9e). The one conflict was call_cache.go's version: main had taken calls-v13 for compaction times (e1dcd1e1d), so this is calls-v14. Run with the follow-up commit on top, at tree 122b933ba4c474e443f2b29c6d0a4163ae364f78 on origin/maine5cd125f0(Go 1.26.8 darwin/arm64, sandbox HOME, private GOCACHE): - gofmt -l on the changed files: none - go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./... - the darwin, linux (nogui) and windows builds - go test -tags nogui -timeout 40m ./...: all ok - go test -race -tags nogui -run 'Codex|Packed|QueryPage|RequestPage' ./internal/sessions ./internal/usage ./internal/gui: ok Broken by hand, each red: codexIdentityRow not setting Subagent (8 usage tests), setting it for a main thread too (2), Session kept raw instead of the root (7), thread_spawn's parent_thread_id not read (3 sessions tests), response pairs not reserved before the old matching (6). Not tried: a real Codex subagent rollout (none on this machine; every recent rollout is a vscode main thread whose session_id equals its id), and the GUI by hand. Claude Code's fields are unchanged.
291 lines
12 KiB
Go
291 lines
12 KiB
Go
package sessions
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func codexIdentityRollout(t *testing.T, codex, filenameID string, lines ...string) string {
|
|
t.Helper()
|
|
path := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T10-00-00-"+filenameID+".jsonl")
|
|
writeLines(t, path, lines...)
|
|
return path
|
|
}
|
|
|
|
func codexIdentityMeta(t *testing.T, id, session, source, parent, fork string) string {
|
|
t.Helper()
|
|
payload := map[string]any{"id": id, "session_id": session}
|
|
if source != "" {
|
|
payload["source"] = json.RawMessage(source)
|
|
}
|
|
if parent != "" {
|
|
payload["parent_thread_id"] = parent
|
|
}
|
|
if fork != "" {
|
|
payload["forked_from_id"] = fork
|
|
}
|
|
line, err := json.Marshal(map[string]any{"timestamp": stamp(0), "type": "session_meta", "payload": payload})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return string(line)
|
|
}
|
|
|
|
func codexIdentityUsage(at int, responseID, session, thread string) string {
|
|
return fmt.Sprintf(`{"timestamp":%q,"type":"token_usage_record","payload":{"response_id":%q,"session_id":%q,"thread_id":%q,"turn_id":"turn","usage":%s}}`,
|
|
stamp(at), responseID, session, thread, cxUse(100, 20, 0, 10, 3))
|
|
}
|
|
|
|
func TestCodexIdentityParentChainsAndSummaryCache(t *testing.T) {
|
|
d := setupCalls(t)
|
|
spawn := func(parent string) string {
|
|
return fmt.Sprintf(`{"subagent":{"thread_spawn":{"parent_thread_id":%q,"depth":2}}}`, parent)
|
|
}
|
|
rows := []struct {
|
|
fileID, id, session, source, parent, fork string
|
|
}{
|
|
{"main-a", "main-a", "shared-a", `"vscode"`, "", ""},
|
|
{"child-b", "child-b", "shared-a", spawn("main-a"), "", ""},
|
|
{"nested-c", "nested-c", "shared-a", spawn("child-b"), "", ""},
|
|
{"child-d", "child-d", "shared-a", spawn("main-a"), "", ""},
|
|
{"fork-f", "fork-f", "fork-f", `"vscode"`, "", "main-a"},
|
|
{"missing-parent", "missing-parent", "shared-a", spawn("absent-parent"), "", ""},
|
|
{"missing-source-parent", "missing-source-parent", "shared-a", spawn(""), "", ""},
|
|
{"top-parent", "top-parent", "shared-a", `{"subagent":"review"}`, "main-a", ""},
|
|
{"conflicting-parent", "conflicting-parent", "shared-a", spawn("main-a"), "other-parent", ""},
|
|
{"cycle-x", "cycle-x", "shared-a", spawn("cycle-y"), "", ""},
|
|
{"cycle-y", "cycle-y", "shared-a", spawn("cycle-x"), "", ""},
|
|
{"unknown-source", "unknown-source", "shared-a", `"other"`, "", ""},
|
|
}
|
|
for i, row := range rows {
|
|
meta := codexIdentityMeta(t, row.id, row.session, row.source, row.parent, row.fork)
|
|
codexIdentityRollout(t, d.codex, row.fileID, meta, codexIdentityUsage(i+1, "response-"+row.id, row.session, ""))
|
|
}
|
|
codexIdentityRollout(t, d.codex, "missing-meta", codexIdentityUsage(20, "response-missing-meta", "shared-a", ""))
|
|
|
|
identities := CodexIdentities()
|
|
wants := map[string]CodexIdentity{
|
|
"main-a": {ID: "main-a", Role: codexRoleMain, RootSession: "main-a"},
|
|
"child-b": {ID: "child-b", Role: codexRoleSubagent, ParentSession: "main-a", RootSession: "main-a"},
|
|
"nested-c": {ID: "nested-c", Role: codexRoleSubagent, ParentSession: "child-b", RootSession: "main-a"},
|
|
"child-d": {ID: "child-d", Role: codexRoleSubagent, ParentSession: "main-a", RootSession: "main-a"},
|
|
"fork-f": {ID: "fork-f", Role: codexRoleMain, RootSession: "fork-f"},
|
|
"missing-parent": {ID: "missing-parent", Role: codexRoleSubagent, ParentSession: "absent-parent"},
|
|
"missing-source-parent": {ID: "missing-source-parent", Role: codexRoleSubagent},
|
|
"top-parent": {ID: "top-parent", Role: codexRoleSubagent, ParentSession: "main-a", RootSession: "main-a"},
|
|
"conflicting-parent": {ID: "conflicting-parent", Role: codexRoleUnknown},
|
|
"cycle-x": {ID: "cycle-x", Role: codexRoleSubagent, ParentSession: "cycle-y"},
|
|
"cycle-y": {ID: "cycle-y", Role: codexRoleSubagent, ParentSession: "cycle-x"},
|
|
"missing-meta": {ID: "missing-meta", Role: codexRoleUnknown},
|
|
"unknown-source": {ID: "unknown-source", Role: codexRoleUnknown},
|
|
}
|
|
for id, want := range wants {
|
|
if got := identities[id]; got != want {
|
|
t.Errorf("identity %s = %+v, want %+v", id, got, want)
|
|
}
|
|
}
|
|
delete(identities, "main-a")
|
|
if got := CodexIdentities()["main-a"]; got.Role != codexRoleMain || got.RootSession != "main-a" {
|
|
t.Fatalf("identity snapshot shares its map: %+v", got)
|
|
}
|
|
|
|
listed := map[string]Session{}
|
|
for _, s := range List(All) {
|
|
if s.Agent == "codex" {
|
|
listed[s.ID] = s
|
|
}
|
|
}
|
|
if got := listed["nested-c"]; got.ID != "nested-c" || got.Role != codexRoleSubagent || got.ParentSession != "child-b" || got.RootSession != "main-a" {
|
|
t.Fatalf("listed nested thread: %+v", got)
|
|
}
|
|
if got := listed["fork-f"]; got.Role != codexRoleMain || got.RootSession != "fork-f" {
|
|
t.Fatalf("fork was bound to its source: %+v", got)
|
|
}
|
|
if got, ok := Get("codex:nested-c"); !ok || got.Role != codexRoleSubagent || got.ParentSession != "child-b" || got.RootSession != "main-a" {
|
|
t.Fatalf("Get nested thread: %+v, %t", got, ok)
|
|
}
|
|
managed := map[string]Managed{}
|
|
for _, s := range ListAgent("codex") {
|
|
managed[s.ID] = s
|
|
}
|
|
if got := managed["nested-c"]; got.Role != codexRoleSubagent || got.ParentSession != "child-b" || got.RootSession != "main-a" {
|
|
t.Fatalf("managed nested thread: %+v", got)
|
|
}
|
|
|
|
stats := StatsAt(0, callT0.Add(24*time.Hour))
|
|
for _, s := range stats.Sessions {
|
|
if s.Agent == "codex" && s.ID == "nested-c" {
|
|
if s.Role != codexRoleSubagent || s.ParentSession != "child-b" || s.RootSession != "main-a" {
|
|
t.Fatalf("stats summary identity: %+v", s)
|
|
}
|
|
goto cache
|
|
}
|
|
}
|
|
t.Fatal("nested Codex thread missing from stats summaries")
|
|
|
|
cache:
|
|
before := CodexIdentities()
|
|
Saved()
|
|
Reset()
|
|
if after := CodexIdentities(); !reflect.DeepEqual(before, after) {
|
|
t.Fatalf("summary cache reload changed identities\n got: %+v\nwant: %+v", after, before)
|
|
}
|
|
}
|
|
|
|
func TestCodexCallThreadIDPriorityAndCache(t *testing.T) {
|
|
d := setupCalls(t)
|
|
path := codexIdentityRollout(t, d.codex, "file-thread",
|
|
codexIdentityMeta(t, "own-thread", "shared-session", `"vscode"`, "", ""),
|
|
`{"timestamp":"`+stamp(1)+`","type":"turn_context","payload":{"turn_id":"turn","model":"gpt-6-astra","effort":"high"}}`,
|
|
codexIdentityUsage(2, "response-explicit", "shared-session", "payload-thread"),
|
|
codexIdentityUsage(3, "response-file", "shared-session", ""),
|
|
codexIdentityUsage(4, "response-upgrade", "shared-session", ""),
|
|
codexIdentityUsage(4, "response-upgrade", "shared-session", "payload-upgraded"),
|
|
codexIdentityUsage(6, "response-conflict", "shared-session", "payload-first"),
|
|
codexIdentityUsage(7, "response-conflict", "shared-session", "payload-conflict"),
|
|
)
|
|
want := map[string]string{
|
|
"response-explicit": "payload-thread",
|
|
"response-file": "own-thread",
|
|
"response-upgrade": "payload-upgraded",
|
|
"response-conflict": "",
|
|
}
|
|
check := func() {
|
|
t.Helper()
|
|
got := map[string]Call{}
|
|
for _, c := range Calls(time.Time{}) {
|
|
got[c.ResponseID] = c
|
|
}
|
|
if len(got) != len(want) {
|
|
t.Fatalf("calls: %+v", got)
|
|
}
|
|
for response, thread := range want {
|
|
c := got[response]
|
|
if c.ThreadID != thread || c.Session != "shared-session" || c.Effort != "high" {
|
|
t.Errorf("%s identity = %+v; want thread %s with shared session and effort", response, c, thread)
|
|
}
|
|
}
|
|
}
|
|
check()
|
|
Reset()
|
|
disk := loadCalls(file{path: path, agent: "codex"})
|
|
if disk == nil || len(disk.Calls) != len(want) {
|
|
t.Fatalf("call cache did not reload from disk: %+v", disk)
|
|
}
|
|
for _, c := range disk.Calls {
|
|
if c.ThreadID != want[c.ResponseID] {
|
|
t.Errorf("disk cached %s thread id %q, want %q", c.ResponseID, c.ThreadID, want[c.ResponseID])
|
|
}
|
|
}
|
|
check()
|
|
if _, err := os.Stat(path); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func TestCodexIdentityParentMergeAcrossRolloutFiles(t *testing.T) {
|
|
d := setupCalls(t)
|
|
spawn := func(parent string) string {
|
|
return fmt.Sprintf(`{"subagent":{"thread_spawn":{"parent_thread_id":%q}}}`, parent)
|
|
}
|
|
codexIdentityRollout(t, d.codex, "upgrade-first", codexIdentityMeta(t, "child-upgrade", "shared-child", `{"subagent":{"other":"review"}}`, "", ""))
|
|
codexIdentityRollout(t, d.codex, "upgrade-later", codexIdentityMeta(t, "child-upgrade", "shared-child", spawn("main-root"), "", ""))
|
|
codexIdentityRollout(t, d.codex, "main-root", codexIdentityMeta(t, "main-root", "shared-root", `"cli"`, "", ""))
|
|
codexIdentityRollout(t, d.codex, "conflict-first", codexIdentityMeta(t, "child-conflict", "shared-conflict", spawn("main-root"), "", ""))
|
|
codexIdentityRollout(t, d.codex, "conflict-later", codexIdentityMeta(t, "child-conflict", "shared-conflict", spawn("main-other"), "", ""))
|
|
codexIdentityRollout(t, d.codex, "main-other", codexIdentityMeta(t, "main-other", "shared-other", `"exec"`, "", ""))
|
|
|
|
identities := CodexIdentities()
|
|
if got := identities["child-upgrade"]; got.Role != codexRoleSubagent || got.ParentSession != "main-root" || got.RootSession != "main-root" {
|
|
t.Errorf("later parent did not upgrade the missing parent: %+v", got)
|
|
}
|
|
if got := identities["child-conflict"]; got.Role != codexRoleUnknown || got.ParentSession != "" || got.RootSession != "" {
|
|
t.Errorf("conflicting parents across rollout files were guessed: %+v", got)
|
|
}
|
|
}
|
|
|
|
func TestCodexIdentityFieldsOmitOtherAgents(t *testing.T) {
|
|
cl := Session{Agent: "claude", ID: "claude-session"}
|
|
encoded, err := json.Marshal(cl)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, key := range []string{`"role"`, `"parent_session"`, `"root_session"`, `"model_effort"`} {
|
|
if strings.Contains(string(encoded), key) {
|
|
t.Fatalf("non-Codex session has %s: %s", key, encoded)
|
|
}
|
|
}
|
|
summary, err := json.Marshal(Summary{Agent: "claude", ID: "claude-session"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, key := range []string{`"role"`, `"parent_session"`, `"root_session"`, `"model_effort"`} {
|
|
if strings.Contains(string(summary), key) {
|
|
t.Fatalf("non-Codex summary has %s: %s", key, summary)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCodexCompactionPromotesThreadID(t *testing.T) {
|
|
usage := cxUsage{Input: 100, Output: 10, Cached: 20, Reasoning: 3, Known: 31}
|
|
state := &codexUsageState{}
|
|
if change := state.record(codexContribution{ResponseID: "response", Session: "shared", Model: "gpt-6-astra", At: callT0, Usage: usage}); change == nil {
|
|
t.Fatal("initial response was not recorded")
|
|
}
|
|
change := state.compacted(callT0, "gpt-6-astra", cxCompaction{
|
|
ResponseID: "response",
|
|
Record: &cxRecordedUsage{ThreadID: "payload-thread", SessionID: "shared", ResponseID: "response", Usage: &usage},
|
|
})
|
|
if change == nil || change.Value.ThreadID != "payload-thread" || len(state.Entries) != 1 || state.Entries[0].Usage != usage {
|
|
t.Fatalf("compaction did not promote thread identity without duplicating usage: change=%+v entries=%+v", change, state.Entries)
|
|
}
|
|
}
|
|
|
|
func TestCodexSourceNativeVariants(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
source string
|
|
role string
|
|
parent string
|
|
}{
|
|
{`"cli"`, codexRoleMain, ""},
|
|
{`"vscode"`, codexRoleMain, ""},
|
|
{`"exec"`, codexRoleMain, ""},
|
|
{`"mcp"`, codexRoleMain, ""},
|
|
{`{"custom":"codex"}`, codexRoleMain, ""},
|
|
{`{"subagent":{"thread_spawn":{"parent_thread_id":"parent"}}}`, codexRoleSubagent, "parent"},
|
|
{`{"subagent":{"other":"review"}}`, codexRoleSubagent, ""},
|
|
{`"other"`, codexRoleUnknown, ""},
|
|
} {
|
|
role, parent := codexSource(json.RawMessage(tc.source))
|
|
if role != tc.role || parent != tc.parent {
|
|
t.Errorf("codexSource(%s) = %s/%s, want %s/%s", tc.source, role, parent, tc.role, tc.parent)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCodexIdentityInvalidatesOldSummaryCache(t *testing.T) {
|
|
d := setupCalls(t)
|
|
path := codexIdentityRollout(t, d.codex, "old-cache-thread",
|
|
codexIdentityMeta(t, "old-cache-thread", "shared-session", `"exec"`, "", ""),
|
|
)
|
|
writeCache(&save{cacheFile: cacheFile{
|
|
Version: cacheVersion - 1,
|
|
Zone: zone(),
|
|
Files: map[string]*state{path: {
|
|
ID: "old-cache-thread",
|
|
Size: 1,
|
|
Mod: 1,
|
|
}},
|
|
}, path: CachePath()})
|
|
Reset()
|
|
if got := CodexIdentities()["old-cache-thread"]; got.Role != codexRoleMain || got.RootSession != "old-cache-thread" {
|
|
t.Fatalf("old summary cache hid current identity: %+v", got)
|
|
}
|
|
}
|