Files
alan ce3482b057 Expose native OpenCode chat usage snapshots and replay session metrics
Read V2 session accounting, latest assistant prompt/cache components and native request-to-stream boundary. Resolve capacity by location/provider/catalog id with bounded metadata caching. Coalesce active/final readbacks; retain message-less session snapshots without changing admission or compaction state.

Provenance: https://opencode.ai/v2/openapi.json and anomalyco/opencode V2 4617210822bdbb31e5749751afbfb4584ccedac8: packages/schema/src/token-usage.ts, session-event.ts; packages/core/src/session/usage.ts, projector.ts, message-updater.ts, runner/step.ts. Native output is visible output, reasoning separate. Session totals include all five non-overlapping components. Generation rate uses created-to-streamed, not tool-inclusive completion.

Limitations: metrics remain unknown for missing components, absent timing/model metadata, reads beyond bounded latest-message/catalog budgets, or context preceding compaction. No local pricing, token estimation or default capacity. V1 gets no invented cumulative metrics; older V2 events remain available when readback is unavailable. No deployment or protocol/web/docs changes.

Checks: go test ./...; focused usage/stream race tests; go vet ./internal/opencode ./internal/server; go build ./...; git diff --check.
2026-10-21 00:13:51 +01:00

65 lines
2.5 KiB
Go

package server
import (
"context"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing.T) {
h := newChatHub()
room := newChatRoom(context.Background(), "ses_usage")
defer room.cancel()
room.running = true
room.nativeTurnID = "turn_keep"
room.turnDone = make(chan struct{})
h.rooms[room.sessionID] = room
sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})}
room.subs[sub.clientID] = sub
h.apply(protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running"}})
for _, n := range []int64{123, 123, 0, 5} {
total := n
u := &protocol.ChatUsage{Scope: "session", TotalTokens: &total}
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: u})
live := (<-sub.ch).ChatEvent
if live.MessageID != "" || *live.Usage.TotalTokens != n {
t.Fatalf("live=%+v", live)
}
total = 999 // producer-owned data must not mutate retained state
h.replayUsage(sub)
frame := (<-sub.ch).ChatEvent
if frame == nil || frame.Kind != protocol.ChatEventUsage || frame.MessageID != "" || frame.Usage.TotalTokens == nil || *frame.Usage.TotalTokens != n {
t.Fatalf("replay=%+v", frame)
}
*frame.Usage.TotalTokens = 888 // neither may a consumer
if !room.running || room.nativeTurnID != "turn_keep" || h.turns[room.sessionID].step != nil || h.turns[room.sessionID].compaction == nil {
t.Fatal("usage changed turn/admission/compaction")
}
select {
case <-room.turnDone:
t.Fatal("usage settled turn")
default:
}
}
if got := h.snapshot(room.sessionID); len(got) != 0 {
t.Fatalf("usage created transcript messages %+v", got)
}
// A full snapshot may legitimately reset every unknown field to nil.
h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Scope: "session"}})
<-sub.ch
h.replayUsage(sub)
if f := (<-sub.ch).ChatEvent; f.Usage.TotalTokens != nil {
t.Fatal("unknown snapshot accumulated old counter")
}
other := newChatRoom(context.Background(), "ses_other")
defer other.cancel()
h.rooms[other.sessionID] = other
otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})}
other.subs[otherSub.clientID] = otherSub
h.replayUsage(otherSub)
if len(otherSub.ch) != 0 {
t.Fatal("foreign usage replayed")
}
}