Files
magpie/internal/gui/usage_compaction_api_test.go
Hogee 3c4b4dc973 sessions, usage: a Codex subagent with no title takes its parent's spawn_agent task_name, its nickname shows apart, and Usage requests say which calls were compactions (#1591, Hogeexxl)
Hogeexxl's change (his fork branch codex/codex-session-details, f7c176c9),
cherry-picked with his authorship:

- A Codex child thread whose title is still empty after the existing
  precedence takes the task_name of the parent's spawn_agent call, linked by
  the call id and the SubAgentActivity "started" item that names the child's
  agent_thread_id. Conflicting links leave the title empty.
- session_meta.agent_nickname is exposed as `nickname` on the list, one,
  manage and overview responses, beside the title, not in place of it.
- GET /api/usage/requests and /v1/magpie/usage/requests carry `compaction`
  (true/false) for Codex calls with native evidence, and leave it out
  otherwise. A gateway row matched by a unique response_id takes the marker
  and keeps its own model, usage, cost and kind.
- Flags bits 1024 (rowCompactionKnown) and 2048 (rowCompaction) are new.
  TestRowFlagsApart covers them, and they don't overlap 1..512. The sessions
  cache goes to version 21 and the calls cache to calls-v15.

Review:
- Rollout format checked against Codex's source (openai/codex 669449b):
  - v2 spawn_agent args carry task_name.
  - A paginated rollout persists item_completed with a SubAgentActivity
    item: kind "started", id = the call id, agent_thread_id.
  - SessionMeta has a top-level agent_nickname, which Codex's own list.rs
    and metadata.rs read too.
  - compaction_response_id lives in token_usage_record.
  Gaps in legacy rollouts and in calls without a response_id are fixed in
  the next two commits.
- Privacy: only a title string the user's own Codex wrote and a boolean
  are added to local API responses. Nothing new goes to a vendor or to
  telemetry. The ingest POST parses fields one by one, so it is unchanged.
- No .github, dependency or network changes.

What was run:
- His tests pass: go test -tags nogui ./internal/sessions ./internal/usage,
  and the two new internal/gui API tests.
- Broken by hand, each caught by his tests:
  - the nickname read removed;
  - the conflict checks removed;
  - mergeCodexCompactions broken;
  - the gateway pair's setCodexCompaction removed;
  - the flag read forced to true.
- Not caught:
  - the parent check on the title link (covered by a test in the next
    commit);
  - `copy.codexCompactions = nil` in cloneCodexChunks removed. That line is
    defensive only: the shared chunks never hold the map.
- The gofmt, vet and full-suite record for the three commits is in the
  last one.
2026-10-15 04:21:31 +08:00

74 lines
2.8 KiB
Go

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)
}
}
}