Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-4921: fix(codex): report resumed usage as task delta (#5569)

Wangjue Yaoadc7636674a2
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index b9a43f2ee5..ca5e1ea1f3 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -1212,7 +1212,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
// there rather than in the shared ~/.codex/sessions (MUL-4424).
if u.InputTokens == 0 && u.OutputTokens == 0 {
taskCodexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])
- if scanned := scanCodexSessionUsage(startTime, taskCodexHome); scanned != nil {
+ if scanned := scanCodexSessionUsage(startTime, taskCodexHome, threadID, resumed); scanned != nil {
u = scanned.usage
if scanned.model != "" && opts.Model == "" {
opts.Model = scanned.model
@@ -2255,46 +2255,140 @@ type codexSessionUsage struct {
model string
}
-// scanCodexSessionUsage scans Codex session JSONL files written after startTime
-// to extract token usage. Codex writes token_count events to
-// $CODEX_HOME/sessions/YYYY/MM/DD/*.jsonl. codexHome is the backend's per-task
-// CODEX_HOME; sessions are isolated there rather than in the shared
-// ~/.codex/sessions (MUL-4424), so usage must be read from it.
-func scanCodexSessionUsage(startTime time.Time, codexHome string) *codexSessionUsage {
+// scanCodexSessionUsage extracts usage for threadID from its Codex rollout.
+// Codex 0.144.4 embeds the app-server thread ID in both the rollout filename and
+// the first session_meta item. Binding the scan to that ID prevents a
+// concurrently-created rollout (for example a Codex subagent) from being billed
+// to this task. A resumed rollout keeps its original date directory, so both flat
+// and YYYY/MM/DD layouts are searched.
+func scanCodexSessionUsage(startTime time.Time, codexHome, threadID string, resumed bool) *codexSessionUsage {
root := codexSessionRoot(codexHome)
- if root == "" {
+ if root == "" || strings.TrimSpace(threadID) == "" {
return nil
}
- // Look in today's session directory.
- dateDir := filepath.Join(root,
- fmt.Sprintf("%04d", startTime.Year()),
- fmt.Sprintf("%02d", int(startTime.Month())),
- fmt.Sprintf("%02d", startTime.Day()),
- )
+ type candidate struct {
+ path string
+ modTime time.Time
+ }
+ var files []candidate
+ for _, path := range findCodexSessionRollouts(root, threadID) {
+ info, err := os.Stat(path)
+ if err != nil || info.ModTime().Before(startTime) {
+ continue
+ }
+ files = append(files, candidate{path: path, modTime: info.ModTime()})
+ }
+ if len(files) == 0 {
+ return nil
+ }
+ sort.Slice(files, func(i, j int) bool {
+ if files[i].modTime.Equal(files[j].modTime) {
+ return files[i].path < files[j].path
+ }
+ return files[i].modTime.Before(files[j].modTime)
+ })
- files, err := filepath.Glob(filepath.Join(dateDir, "*.jsonl"))
- if err != nil || len(files) == 0 {
+ // Multiple paths for one thread can transiently exist during layout migration.
+ // They have the same owner, so prefer the latest deterministically without ever
+ // crossing into a different thread's rollout.
+ result := parseCodexSessionFileSince(files[len(files)-1].path, startTime, resumed)
+ if result == nil || (result.usage.InputTokens == 0 && result.usage.OutputTokens == 0 &&
+ result.usage.CacheReadTokens == 0 && result.usage.CacheWriteTokens == 0) {
return nil
}
+ return result
+}
- // Only scan files modified after startTime (this task's session).
- var result codexSessionUsage
- for _, f := range files {
- info, err := os.Stat(f)
- if err != nil || info.ModTime().Before(startTime) {
+// findCodexSessionRollouts returns uncompressed rollout files owned by threadID
+// in the two layouts supported by Codex 0.14x. filepath.Glob traverses a linked
+// sessions root, unlike WalkDir, which treats a symlink root as a single file and
+// never visits its children. The normal path uses Codex's filename contract and
+// validates session_meta.id when present. If a future Codex version changes the
+// filename, the metadata pass preserves exact ownership instead of silently
+// dropping usage. Filtering after globbing also keeps a provider-supplied thread
+// ID out of the glob expression.
+func findCodexSessionRollouts(root, threadID string) []string {
+ threadID = strings.TrimSpace(threadID)
+ if root == "" || threadID == "" {
+ return nil
+ }
+
+ patterns := []string{
+ filepath.Join(root, "rollout-*.jsonl"),
+ filepath.Join(root, "*", "*", "*", "rollout-*.jsonl"),
+ }
+ seen := make(map[string]bool)
+ var candidates []string
+ for _, pattern := range patterns {
+ paths, err := filepath.Glob(pattern)
+ if err != nil {
continue
}
- if u := parseCodexSessionFile(f); u != nil {
- // Take the last matching file's data (usually there's only one per task).
- result = *u
+ for _, path := range paths {
+ if seen[path] {
+ continue
+ }
+ seen[path] = true
+ candidates = append(candidates, path)
}
}
- if result.usage.InputTokens == 0 && result.usage.OutputTokens == 0 {
- return nil
+ // Fast path for the current Codex contract. Reject a filename match if its
+ // canonical session_meta explicitly names a different thread.
+ suffix := "-" + threadID + ".jsonl"
+ var matches []string
+ for _, path := range candidates {
+ if !strings.HasSuffix(filepath.Base(path), suffix) {
+ continue
+ }
+ if metadataID, ok := readCodexRolloutThreadID(path); ok && metadataID != threadID {
+ continue
+ }
+ matches = append(matches, path)
}
- return &result
+ if len(matches) > 0 {
+ return matches
+ }
+
+ // Compatibility path for a future filename format: the first session_meta
+ // remains the canonical owner of a rollout in Codex's own resume reader.
+ for _, path := range candidates {
+ if metadataID, ok := readCodexRolloutThreadID(path); ok && metadataID == threadID {
+ matches = append(matches, path)
+ }
+ }
+ return matches
+}
+
+// readCodexRolloutThreadID reads only the head of a rollout. Codex writes the
+// canonical session_meta first; the line cap prevents a malformed legacy file
+// without metadata from turning ownership checks into a full multi-GB scan.
+func readCodexRolloutThreadID(path string) (string, bool) {
+ f, err := os.Open(path)
+ if err != nil {
+ return "", false
+ }
+ defer f.Close()
+
+ var evt struct {
+ Type string `json:"type"`
+ Payload *struct {
+ ID string `json:"id"`
+ } `json:"payload"`
+ }
+ scanner := bufio.NewScanner(f)
+ scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
+ for lineCount := 0; lineCount < 64 && scanner.Scan(); lineCount++ {
+ line := scanner.Bytes()
+ if !bytesContainsStr(line, "session_meta") {
+ continue
+ }
+ if err := json.Unmarshal(line, &evt); err == nil && evt.Type == "session_meta" && evt.Payload != nil && evt.Payload.ID != "" {
+ return evt.Payload.ID, true
+ }
+ }
+ return "", false
}
// codexSessionRoot returns the Codex sessions directory. It prefers the
@@ -2324,27 +2418,24 @@ func codexSessionRoot(codexHome string) string {
return ""
}
+type codexRawTokenUsage struct {
+ InputTokens int64 `json:"input_tokens"`
+ OutputTokens int64 `json:"output_tokens"`
+ CachedInputTokens int64 `json:"cached_input_tokens"`
+ CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
+ ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
+}
+
// codexSessionTokenCount represents a token_count event in Codex JSONL.
type codexSessionTokenCount struct {
- Type string `json:"type"`
- Payload *struct {
+ Timestamp time.Time `json:"timestamp"`
+ Type string `json:"type"`
+ Payload *struct {
Type string `json:"type"`
Info *struct {
- TotalTokenUsage *struct {
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CachedInputTokens int64 `json:"cached_input_tokens"`
- CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
- ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
- } `json:"total_token_usage"`
- LastTokenUsage *struct {
- InputTokens int64 `json:"input_tokens"`
- OutputTokens int64 `json:"output_tokens"`
- CachedInputTokens int64 `json:"cached_input_tokens"`
- CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
- ReasoningOutputTokens int64 `json:"reasoning_output_tokens"`
- } `json:"last_token_usage"`
- Model string `json:"model"`
+ TotalTokenUsage *codexRawTokenUsage `json:"total_token_usage"`
+ LastTokenUsage *codexRawTokenUsage `json:"last_token_usage"`
+ Model string `json:"model"`
} `json:"info"`
Model string `json:"model"`
} `json:"payload"`
@@ -2352,6 +2443,16 @@ type codexSessionTokenCount struct {
// parseCodexSessionFile extracts the final token_count from a Codex session file.
func parseCodexSessionFile(path string) *codexSessionUsage {
+ return parseCodexSessionFileSince(path, time.Time{}, false)
+}
+
+// parseCodexSessionFileSince extracts usage accumulated after startTime. Codex
+// reports total_token_usage cumulatively for the whole resumed session, so the
+// last total before startTime is subtracted from the final total. Timestamp-less
+// events in a resumed rollout are baseline-only until an explicit post-start
+// timestamp establishes the boundary; fresh sessions retain the previous
+// whole-file behavior because every event belongs to the new task.
+func parseCodexSessionFileSince(path string, startTime time.Time, resumed bool) *codexSessionUsage {
f, err := os.Open(path)
if err != nil {
return nil
@@ -2359,7 +2460,10 @@ func parseCodexSessionFile(path string) *codexSessionUsage {
defer f.Close()
var result codexSessionUsage
- found := false
+ var previousTotal, accumulated, finalUsage codexRawTokenUsage
+ previousTotalFound := false
+ finalUsageFound := false
+ afterStartBoundary := false
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 256*1024), 1024*1024)
@@ -2376,6 +2480,10 @@ func parseCodexSessionFile(path string) *codexSessionUsage {
if err := json.Unmarshal(line, &evt); err != nil || evt.Payload == nil {
continue
}
+ timestampAfterStart := !startTime.IsZero() && !evt.Timestamp.IsZero() && evt.Timestamp.After(startTime)
+ if timestampAfterStart {
+ afterStartBoundary = true
+ }
// Track model from turn_context events.
if evt.Type == "turn_context" && evt.Payload.Model != "" {
@@ -2385,34 +2493,84 @@ func parseCodexSessionFile(path string) *codexSessionUsage {
// Extract token usage from token_count events.
if evt.Payload.Type == "token_count" && evt.Payload.Info != nil {
- usage := evt.Payload.Info.TotalTokenUsage
- if usage == nil {
- usage = evt.Payload.Info.LastTokenUsage
- }
- if usage != nil {
- cachedTokens := usage.CachedInputTokens
- if cachedTokens == 0 {
- cachedTokens = usage.CacheReadInputTokens
- }
- result.usage = TokenUsage{
- InputTokens: codexUncachedInputTokens(usage.InputTokens, cachedTokens),
- OutputTokens: usage.OutputTokens + usage.ReasoningOutputTokens,
- CacheReadTokens: cachedTokens,
- }
- if evt.Payload.Info.Model != "" {
- result.model = evt.Payload.Info.Model
+ afterStart := startTime.IsZero() || timestampAfterStart ||
+ (evt.Timestamp.IsZero() && (!resumed || afterStartBoundary))
+ if usage := evt.Payload.Info.TotalTokenUsage; usage != nil {
+ current := normalizeCodexRawTokenUsage(*usage)
+ if afterStart {
+ delta := current
+ if previousTotalFound {
+ delta = subtractCodexRawTokenUsage(current, previousTotal)
+ }
+ accumulated = addCodexRawTokenUsage(accumulated, delta)
+ finalUsage = accumulated
+ finalUsageFound = true
}
- found = true
+ previousTotal = current
+ previousTotalFound = true
+ } else if usage := evt.Payload.Info.LastTokenUsage; usage != nil && afterStart {
+ // Preserve event order: a later last_token_usage is the same
+ // fallback the old whole-file parser would have selected.
+ finalUsage = normalizeCodexRawTokenUsage(*usage)
+ finalUsageFound = true
+ }
+ if evt.Payload.Info.Model != "" {
+ result.model = evt.Payload.Info.Model
}
}
}
- if !found {
+ if !finalUsageFound {
return nil
}
+ cachedTokens := finalUsage.CachedInputTokens
+ result.usage = TokenUsage{
+ InputTokens: codexUncachedInputTokens(finalUsage.InputTokens, cachedTokens),
+ OutputTokens: finalUsage.OutputTokens + finalUsage.ReasoningOutputTokens,
+ CacheReadTokens: cachedTokens,
+ }
return &result
}
+func subtractCodexRawTokenUsage(total, baseline codexRawTokenUsage) codexRawTokenUsage {
+ total = normalizeCodexRawTokenUsage(total)
+ baseline = normalizeCodexRawTokenUsage(baseline)
+ // Guard each counter independently. Treating one field's reset as a reset of
+ // the entire snapshot would re-report still-monotonic fields and recreate the
+ // over-counting this fallback is meant to prevent.
+ return codexRawTokenUsage{
+ InputTokens: nonNegativeTokenDelta(total.InputTokens, baseline.InputTokens),
+ OutputTokens: nonNegativeTokenDelta(total.OutputTokens, baseline.OutputTokens),
+ CachedInputTokens: nonNegativeTokenDelta(total.CachedInputTokens, baseline.CachedInputTokens),
+ ReasoningOutputTokens: nonNegativeTokenDelta(total.ReasoningOutputTokens, baseline.ReasoningOutputTokens),
+ }
+}
+
+func normalizeCodexRawTokenUsage(usage codexRawTokenUsage) codexRawTokenUsage {
+ if usage.CachedInputTokens == 0 {
+ usage.CachedInputTokens = usage.CacheReadInputTokens
+ }
+ usage.CacheReadInputTokens = 0
+ return usage
+}
+
+func addCodexRawTokenUsage(a, b codexRawTokenUsage) codexRawTokenUsage {
+ return codexRawTokenUsage{
+ InputTokens: a.InputTokens + b.InputTokens,
+ OutputTokens: a.OutputTokens + b.OutputTokens,
+ CachedInputTokens: a.CachedInputTokens + b.CachedInputTokens,
+ ReasoningOutputTokens: a.ReasoningOutputTokens + b.ReasoningOutputTokens,
+ }
+}
+
+func nonNegativeTokenDelta(total, baseline int64) int64 {
+ if total < baseline {
+ // A counter reset means the final value already belongs to the new span.
+ return total
+ }
+ return total - baseline
+}
+
// bytesContainsStr checks if b contains the string s (without allocating).
func bytesContainsStr(b []byte, s string) bool {
return strings.Contains(string(b), s)
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index a3cdafed3e..637aaf631d 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -741,6 +741,7 @@ func TestCodexSessionRootPrefersExplicitTaskHome(t *testing.T) {
func TestScanCodexSessionUsageReadsPerTaskHome(t *testing.T) {
t.Parallel()
taskHome := t.TempDir()
+ threadID := "task-thread"
startTime := time.Now().Add(-time.Minute)
dateDir := filepath.Join(taskHome, "sessions",
fmt.Sprintf("%04d", startTime.Year()),
@@ -751,15 +752,15 @@ func TestScanCodexSessionUsageReadsPerTaskHome(t *testing.T) {
t.Fatalf("mkdir date dir: %v", err)
}
content := strings.Join([]string{
- `{"timestamp":"2026-07-13T00:00:00.000Z","type":"turn_context","payload":{"model":"gpt-5.6-sol"}}`,
- `{"timestamp":"2026-07-13T00:00:01.000Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":500,"output_tokens":20},"model":"gpt-5.6-sol"}}}`,
+ fmt.Sprintf(`{"timestamp":%q,"type":"turn_context","payload":{"model":"gpt-5.6-sol"}}`, startTime.Add(time.Second).UTC().Format(time.RFC3339Nano)),
+ fmt.Sprintf(`{"timestamp":%q,"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":500,"output_tokens":20},"model":"gpt-5.6-sol"}}}`, startTime.Add(2*time.Second).UTC().Format(time.RFC3339Nano)),
"",
}, "\n")
- if err := os.WriteFile(filepath.Join(dateDir, "rollout.jsonl"), []byte(content), 0o644); err != nil {
+ if err := os.WriteFile(filepath.Join(dateDir, "rollout-2026-07-13T00-00-00-"+threadID+".jsonl"), []byte(content), 0o644); err != nil {
t.Fatalf("write session file: %v", err)
}
- got := scanCodexSessionUsage(startTime, taskHome)
+ got := scanCodexSessionUsage(startTime, taskHome, threadID, false)
if got == nil {
t.Fatal("expected usage scanned from the per-task home")
}
@@ -771,6 +772,308 @@ func TestScanCodexSessionUsageReadsPerTaskHome(t *testing.T) {
}
}
+func TestScanCodexSessionUsageSubtractsResumeBaseline(t *testing.T) {
+ t.Parallel()
+ taskHome := t.TempDir()
+ threadID := "resumed-thread"
+ startTime := time.Date(2026, time.July, 13, 0, 0, 10, 0, time.UTC)
+ dateDir := filepath.Join(taskHome, "sessions", "2026", "07", "13")
+ if err := os.MkdirAll(dateDir, 0o755); err != nil {
+ t.Fatalf("mkdir date dir: %v", err)
+ }
+ content := strings.Join([]string{
+ `{"timestamp":"2026-07-13T00:00:00.000Z","type":"turn_context","payload":{"model":"gpt-5.6-sol"}}`,
+ `{"timestamp":"2026-07-13T00:00:05.000Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1000,"cached_input_tokens":700,"output_tokens":50,"reasoning_output_tokens":10},"model":"gpt-5.6-sol"}}}`,
+ `{"timestamp":"2026-07-13T00:00:11.000Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1300,"cached_input_tokens":900,"output_tokens":70,"reasoning_output_tokens":15},"model":"gpt-5.6-sol"}}}`,
+ `{"timestamp":"2026-07-13T00:00:12.000Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1800,"cached_input_tokens":1400,"output_tokens":100,"reasoning_output_tokens":25},"model":"gpt-5.6-sol"}}}`,
+ "",
+ }, "\n")
+ if err := os.WriteFile(filepath.Join(dateDir, "rollout-2026-07-13T00-00-00-"+threadID+".jsonl"), []byte(content), 0o644); err != nil {
+ t.Fatalf("write session file: %v", err)
+ }
+
+ got := scanCodexSessionUsage(startTime, taskHome, threadID, true)
+ if got == nil {
+ t.Fatal("expected usage")
+ }
+ // total_token_usage is cumulative for the resumed Codex session. This task
+ // should report only the delta after startTime, not the whole session total.
+ want := TokenUsage{InputTokens: 100, OutputTokens: 65, CacheReadTokens: 700}
+ if got.usage != want {
+ t.Fatalf("usage = %+v, want resumed-task delta %+v", got.usage, want)
+ }
+}
+
+func TestParseCodexSessionFileSinceResumeEdgeCases(t *testing.T) {
+ t.Parallel()
+ startTime := time.Date(2026, time.July, 13, 0, 0, 10, 0, time.UTC)
+ tests := []struct {
+ name string
+ lines []string
+ want TokenUsage
+ }{
+ {
+ name: "final last usage wins over earlier total",
+ lines: []string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":10}}}}`,
+ `{"timestamp":"2026-07-13T00:00:11Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":160,"output_tokens":20}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":7,"output_tokens":3}}}}`,
+ },
+ want: TokenUsage{InputTokens: 7, OutputTokens: 3},
+ },
+ {
+ name: "final total wins over earlier last usage",
+ lines: []string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":10}}}}`,
+ `{"timestamp":"2026-07-13T00:00:11Z","type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":7,"output_tokens":3}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":160,"output_tokens":20}}}}`,
+ },
+ want: TokenUsage{InputTokens: 60, OutputTokens: 10},
+ },
+ {
+ name: "cache alias changes from cache read to cached input",
+ lines: []string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1000,"cache_read_input_tokens":700}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1800,"cached_input_tokens":1400}}}}`,
+ },
+ want: TokenUsage{InputTokens: 100, CacheReadTokens: 700},
+ },
+ {
+ name: "cache alias changes from cached input to cache read",
+ lines: []string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1000,"cached_input_tokens":700}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":1800,"cache_read_input_tokens":1400}}}}`,
+ },
+ want: TokenUsage{InputTokens: 100, CacheReadTokens: 700},
+ },
+ {
+ name: "counter reset accumulates every segment",
+ lines: []string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":50}}}}`,
+ `{"timestamp":"2026-07-13T00:00:11Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":120,"output_tokens":60}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":10,"output_tokens":5}}}}`,
+ `{"timestamp":"2026-07-13T00:00:13Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":150,"output_tokens":70}}}}`,
+ },
+ want: TokenUsage{InputTokens: 170, OutputTokens: 80},
+ },
+ {
+ name: "one counter reset does not reset monotonic fields",
+ lines: []string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":50}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":120,"output_tokens":5}}}}`,
+ },
+ want: TokenUsage{InputTokens: 20, OutputTokens: 5},
+ },
+ {
+ name: "missing timestamp before boundary is baseline only",
+ lines: []string{
+ `{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":10}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":160,"output_tokens":25}}}}`,
+ },
+ want: TokenUsage{InputTokens: 60, OutputTokens: 15},
+ },
+ {
+ name: "missing timestamp after boundary remains in delta",
+ lines: []string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":10}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":160,"output_tokens":25}}}}`,
+ `{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":180,"output_tokens":30}}}}`,
+ },
+ want: TokenUsage{InputTokens: 80, OutputTokens: 20},
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "session.jsonl")
+ content := strings.Join(append(tc.lines, ""), "\n")
+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ got := parseCodexSessionFileSince(path, startTime, true)
+ if got == nil {
+ t.Fatal("expected usage")
+ }
+ if got.usage != tc.want {
+ t.Fatalf("usage = %+v, want %+v", got.usage, tc.want)
+ }
+ })
+ }
+}
+
+func TestParseCodexSessionFileSinceAllMissingTimestamps(t *testing.T) {
+ t.Parallel()
+ path := filepath.Join(t.TempDir(), "session.jsonl")
+ content := `{"type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":10}}}}` + "\n"
+ if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
+ t.Fatalf("write fixture: %v", err)
+ }
+ startTime := time.Date(2026, time.July, 13, 0, 0, 10, 0, time.UTC)
+
+ if got := parseCodexSessionFileSince(path, startTime, true); got != nil {
+ t.Fatalf("ambiguous resumed usage = %+v, want nil", got.usage)
+ }
+ got := parseCodexSessionFileSince(path, startTime, false)
+ if got == nil {
+ t.Fatal("fresh rollout should retain timestamp-less usage")
+ }
+ want := TokenUsage{InputTokens: 100, OutputTokens: 10}
+ if got.usage != want {
+ t.Fatalf("fresh usage = %+v, want %+v", got.usage, want)
+ }
+}
+
+func TestScanCodexSessionUsageFindsCrossDayResumeWithCacheOnlyDelta(t *testing.T) {
+ t.Parallel()
+ taskHome := t.TempDir()
+ threadID := "cross-day-thread"
+ startTime := time.Date(2026, time.July, 13, 0, 0, 10, 0, time.UTC)
+ previousDateDir := filepath.Join(taskHome, "sessions", "2026", "07", "12")
+ if err := os.MkdirAll(previousDateDir, 0o755); err != nil {
+ t.Fatalf("mkdir previous date dir: %v", err)
+ }
+ content := strings.Join([]string{
+ `{"timestamp":"2026-07-12T23:59:59Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"cached_input_tokens":100}}}}`,
+ `{"timestamp":"2026-07-13T00:00:11Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":150,"cached_input_tokens":150}}}}`,
+ "",
+ }, "\n")
+ path := filepath.Join(previousDateDir, "rollout-2026-07-12T23-59-59-"+threadID+".jsonl")
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatalf("write session file: %v", err)
+ }
+ if err := os.Chtimes(path, startTime.Add(time.Second), startTime.Add(time.Second)); err != nil {
+ t.Fatalf("set session mtime: %v", err)
+ }
+
+ got := scanCodexSessionUsage(startTime, taskHome, threadID, true)
+ if got == nil {
+ t.Fatal("expected cross-day cache-only usage")
+ }
+ want := TokenUsage{CacheReadTokens: 50}
+ if got.usage != want {
+ t.Fatalf("usage = %+v, want %+v", got.usage, want)
+ }
+}
+
+func TestScanCodexSessionUsageFollowsLinkedSessionsRoot(t *testing.T) {
+ t.Parallel()
+ if runtime.GOOS == "windows" {
+ t.Skip("directory symlink setup requires Windows developer mode")
+ }
+
+ root := t.TempDir()
+ taskHome := filepath.Join(root, "task-home")
+ store := filepath.Join(root, "session-store")
+ threadID := "linked-thread"
+ startTime := time.Date(2026, time.July, 13, 0, 0, 10, 0, time.UTC)
+ dateDir := filepath.Join(store, "2026", "07", "12")
+ if err := os.MkdirAll(dateDir, 0o755); err != nil {
+ t.Fatalf("mkdir store date dir: %v", err)
+ }
+ if err := os.MkdirAll(taskHome, 0o755); err != nil {
+ t.Fatalf("mkdir task home: %v", err)
+ }
+ if err := os.Symlink(store, filepath.Join(taskHome, "sessions")); err != nil {
+ t.Fatalf("link sessions root: %v", err)
+ }
+
+ content := strings.Join([]string{
+ `{"timestamp":"2026-07-13T00:00:05Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":100,"output_tokens":10}}}}`,
+ `{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":160,"output_tokens":25}}}}`,
+ "",
+ }, "\n")
+ path := filepath.Join(dateDir, "rollout-2026-07-12T23-59-59-"+threadID+".jsonl")
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatalf("write linked rollout: %v", err)
+ }
+ if err := os.Chtimes(path, startTime.Add(time.Second), startTime.Add(time.Second)); err != nil {
+ t.Fatalf("set rollout mtime: %v", err)
+ }
+
+ got := scanCodexSessionUsage(startTime, taskHome, threadID, true)
+ if got == nil {
+ t.Fatal("expected usage through linked sessions root")
+ }
+ want := TokenUsage{InputTokens: 60, OutputTokens: 15}
+ if got.usage != want {
+ t.Fatalf("usage = %+v, want %+v", got.usage, want)
+ }
+}
+
+func TestScanCodexSessionUsageSelectsCurrentThread(t *testing.T) {
+ t.Parallel()
+ taskHome := t.TempDir()
+ startTime := time.Date(2026, time.July, 13, 0, 0, 10, 0, time.UTC)
+ dateDir := filepath.Join(taskHome, "sessions", "2026", "07", "13")
+ if err := os.MkdirAll(dateDir, 0o755); err != nil {
+ t.Fatalf("mkdir date dir: %v", err)
+ }
+
+ writeRollout := func(threadID string, input int, modTime time.Time) {
+ t.Helper()
+ content := fmt.Sprintf(`{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":%d}}}}`+"\n", input)
+ path := filepath.Join(dateDir, "rollout-2026-07-13T00-00-00-"+threadID+".jsonl")
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatalf("write %s rollout: %v", threadID, err)
+ }
+ if err := os.Chtimes(path, modTime, modTime); err != nil {
+ t.Fatalf("set %s rollout mtime: %v", threadID, err)
+ }
+ }
+
+ writeRollout("current-thread", 60, startTime.Add(time.Second))
+ writeRollout("newer-subagent-thread", 900, startTime.Add(2*time.Second))
+
+ got := scanCodexSessionUsage(startTime, taskHome, "current-thread", false)
+ if got == nil {
+ t.Fatal("expected current thread usage")
+ }
+ want := TokenUsage{InputTokens: 60}
+ if got.usage != want {
+ t.Fatalf("usage = %+v, want current thread %+v", got.usage, want)
+ }
+}
+
+func TestScanCodexSessionUsageUsesSessionMetadataWhenFilenameDrifts(t *testing.T) {
+ t.Parallel()
+ taskHome := t.TempDir()
+ startTime := time.Date(2026, time.July, 13, 0, 0, 10, 0, time.UTC)
+ dateDir := filepath.Join(taskHome, "sessions", "2026", "07", "13")
+ if err := os.MkdirAll(dateDir, 0o755); err != nil {
+ t.Fatalf("mkdir date dir: %v", err)
+ }
+
+ writeRollout := func(filenameID, metadataID string, input int, modTime time.Time) {
+ t.Helper()
+ content := strings.Join([]string{
+ fmt.Sprintf(`{"timestamp":"2026-07-13T00:00:11Z","type":"session_meta","payload":{"id":%q}}`, metadataID),
+ fmt.Sprintf(`{"timestamp":"2026-07-13T00:00:12Z","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"input_tokens":%d}}}}`, input),
+ "",
+ }, "\n")
+ path := filepath.Join(dateDir, "rollout-2026-07-13T00-00-00-"+filenameID+".jsonl")
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatalf("write %s rollout: %v", filenameID, err)
+ }
+ if err := os.Chtimes(path, modTime, modTime); err != nil {
+ t.Fatalf("set %s rollout mtime: %v", filenameID, err)
+ }
+ }
+
+ // The apparent filename match belongs to another thread and must be rejected.
+ writeRollout("current-thread", "other-thread", 900, startTime.Add(2*time.Second))
+ // A future filename format can still be attributed by canonical session_meta.
+ writeRollout("future-filename", "current-thread", 60, startTime.Add(time.Second))
+
+ got := scanCodexSessionUsage(startTime, taskHome, "current-thread", false)
+ if got == nil {
+ t.Fatal("expected current thread usage from session metadata")
+ }
+ want := TokenUsage{InputTokens: 60}
+ if got.usage != want {
+ t.Fatalf("usage = %+v, want metadata-owned thread %+v", got.usage, want)
+ }
+}
+
func TestCodexRawItemCommandExecution(t *testing.T) {
t.Parallel()