gateway: a reply in flight shows on Routing how much has arrived and roughly its tokens (#4951, Canda15)
A long or reasoning reply looked stuck on the Routing page. A request still out now shows, on its row and beside the account answering it, the bytes the agent has had, "≈ n tokens" once a rate is learned, and how long ago content last came; after 15s with no content the account's dot stops pulsing. Nothing stays once the request is done. Ported from Canda15's 7f7bdb189 (github.com/Canda15/magpie), the idea and the per-protocol content extractors kept, the hot path and storage reworked: - every write to the agent passes captureResponseWriter.Write, which calls liveRow.observe; the row hangs on the request's inflight (an atomic pointer), not a context value made per request - rates are in memory only (256 pairs); the fork wrote a JSON file under the estimate lock on every finished request - a whole JSON reply is counted in bytes only: the fork held and decoded up to 8 MiB of it at the end; a stream is cut into lines in place, only a line cut by a write's end is copied, a line over 1 MiB passed over, and each event decoded once (the fork ran json.Valid then Unmarshal) - the reply's kind comes from its first byte, not a header read on every write; the keepalive check allocates nothing (the fork split each write) - everything a row counts is under its own lock, and inflight.tr is read under f.mu; the estimate is in float64 (the int64 product overflowed) - the route's Seq is bumped on every write and traceGather batches the wake-ups; the fork's global throttle could drop the last update before a pause - learned only from a streamed reply that did not fail and had the vendor's output tokens - left out: the finished row's "Received" metric and the ended caption (layout restraint; an ended row has its own metrics), a duplicate "Received" i18n key, the receive-monitor doc (the design is in gateway-routing.md now), the fork's xmod and Windows CI commits The Routing plugin and i18n.js are outside TestCoreScriptBudget. Run on mote at this head unless named: gofmt -l; go vet (darwin), GOOS=linux -tags nogui and GOOS=windows go vet ./...; go build ./...; go test -race on the live tests; go test ./internal/gateway ./internal/gui (gateway ok; gui red only on TestCoreScriptBudget, #5139, 1533907 > 1533802 before this change and untouched by it, and TestMainWindowCorners/macOS_26_SDK, #3949); routing-live-bytes.test.cjs and i18n-keys in Chromium and WebKit, en/zh/zh-TW/ja/de, 1100 and 420px (24/24); every routing-* and panel-routing* GUI file with i18n-keys in WSL Linux (Chromium all green; WebKit reds in 12 files, the same class at origin/main7dd2434d3run the same way: 25 there, 28 here, the sets differing by timing samples; routing-live-patch alone red 2 of 3 on main, 1 of 3 here; filed as #4121, #4520, #5156, #2174). Rebased onto38f4f74e6(gateway.go, trace.go and the Routing plugin moved): build, gateway vet, the live tests, routing-live-bytes and i18n-keys run again there, green (24/24). Broken by hand, each red, then put back: - no observe in capture.Write: TestLiveCountsARealStream - commentOnly never true: TestLiveHeartbeatIsBytesNotContent, TestCommentOnlyTellsHeartbeatsApart - learning from failed replies: TestRatesLearnFromRepliesTheVendorFinished - a whole reply read as a stream: TestContentCounterLeavesAWholeReply - no Seq bump in liveBytes: TestLiveWritesReachTheRoute - no quiet class, no per-second repaint: routing-live-bytes 0/20 Not tried: a real vendor's stream in the running app; the ChatGPT backend chain (codex_backend.go) writes past the capture writer and isn't counted; the full Go and GUI suites run after the tag. Co-authored-by: Canda15 <124772373+Canda15@users.noreply.github.com>
This commit is contained in:
@@ -1065,6 +1065,45 @@ had, was left out: the read-only key already reads more than this feed
|
||||
[`route_events_test.go`](../../internal/gateway/route_events_test.go), and
|
||||
`TestReadOnlyKeyEveryRoute`.
|
||||
|
||||
### A reply's progress while it is out
|
||||
|
||||
A long or reasoning reply otherwise looks stuck on the Routing page (#4951,
|
||||
Canda15). [`live.go`](../../internal/gateway/live.go) counts each request's
|
||||
reply as it reaches the agent: `serve` begins a `liveRow` on the request's
|
||||
`inflight` (`liveBegin`, none for the gateway's own requests), and
|
||||
`captureResponseWriter.Write`, which every byte to the agent passes, calls
|
||||
`observe`. The route (the full trace only, never `routeActivity`) gets
|
||||
`bytes` (every byte written, SSE framing and keepalives included),
|
||||
`contentAt` (epoch ms of the last write that was not only SSE comments, so
|
||||
a keepalive never moves it) and `estTok`. `trace.liveBytes` writes them
|
||||
under `trace.mu` and bumps the route's `Seq`, so a long poll gathers them
|
||||
like any change.
|
||||
|
||||
`estTok` is the content written so far (text, reasoning, tool names and
|
||||
arguments, per the agent's protocol,
|
||||
[`live_content.go`](../../internal/gateway/live_content.go)) at the rate
|
||||
learned for the provider and model that answer (`routed`, per try), from
|
||||
streamed replies that did not fail and whose vendor said its output
|
||||
tokens ([`live_rates.go`](../../internal/gateway/live_rates.go)). Under
|
||||
three such replies there is no estimate and the page shows none. Rates
|
||||
are in memory only (256 pairs), learned again after a restart; an
|
||||
estimate is never learned from.
|
||||
|
||||
Cost: `observe` takes the row's lock and the trace's, neither held while
|
||||
anything blocks. A whole JSON reply (its first byte `{` or `[`) is counted
|
||||
in bytes only, never copied or decoded; a stream is cut into lines in
|
||||
place, only a line cut by the end of a write is copied, and a line over
|
||||
1 MiB is passed over. The ChatGPT backend's chain (`codex_backend.go`)
|
||||
writes past the capture writer and is not counted.
|
||||
|
||||
The page ([`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js),
|
||||
`liveParts`, `paintLive`) shows the numbers on a request in flight's row
|
||||
and beside the account answering it, changed in place each second; after
|
||||
15 s with no content the account's dot stops pulsing. Nothing stays once
|
||||
the request is done. `TestLiveCountsARealStream` and the other tests in
|
||||
[`live_test.go`](../../internal/gateway/live_test.go), and
|
||||
`routing-live-bytes.test.cjs`.
|
||||
|
||||
## Turning provider search off
|
||||
|
||||
[Settings](../../internal/settings/settings.go)' `searcher: "off"` disables magpie's provider-assisted search,
|
||||
|
||||
@@ -50,6 +50,8 @@ type inflight struct {
|
||||
tr *trace
|
||||
// redaction: its maskings, their phase and time (redact_phase.go)
|
||||
redaction redaction
|
||||
// live: its reply counted as it reaches the agent (live.go)
|
||||
live atomic.Pointer[liveRow]
|
||||
}
|
||||
|
||||
type inflightKey struct{}
|
||||
|
||||
@@ -55,9 +55,13 @@ type captureResponseWriter struct {
|
||||
whole *spool
|
||||
// tools: whether the reply calls a tool, for a turn's end (turns)
|
||||
tools *toolScan
|
||||
// live: the reply counted for the Routing page while it is out
|
||||
// (live.go), nil when it isn't
|
||||
live *liveRow
|
||||
}
|
||||
|
||||
func (w *captureResponseWriter) Write(p []byte) (int, error) {
|
||||
w.live.observe(p)
|
||||
w.body.add(p)
|
||||
w.tools.add(p)
|
||||
if w.full != nil {
|
||||
|
||||
@@ -2187,6 +2187,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
var clientResponseID string // only a reply released to the client owns this ID
|
||||
call := Call{Time: start, From: from, Model: unprefixed(modelOf(body)), Agent: who.agent, Via: who.via, Kind: requestCallKind(r.Header, metadata),
|
||||
wire: archiving(r, capture, start, nil), headers: headerLogOf(r.Context())}
|
||||
// the reply counted as it reaches the agent, for the Routing page
|
||||
// while it is out (#4951); learned from once it ends
|
||||
capture.live = liveBegin(inflightOf(r.Context()), call.Model, from)
|
||||
defer func() { capture.live.finish(call.Status >= 400, call.Usage.Output) }()
|
||||
// the log has the body as it went: masked, or as written where it
|
||||
// went so
|
||||
logBody := func(b []byte) {
|
||||
@@ -4906,6 +4910,9 @@ func sinceStart(before, d time.Duration) int64 {
|
||||
// attempt sends a request to one provider. call.To stays empty when the
|
||||
// provider has no endpoint to send it to.
|
||||
func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, call *Call) (int, string) {
|
||||
// the try that answers is the one whose rate estimates the reply's
|
||||
// tokens (live.go), after a fallback another than the first
|
||||
liveOfInflight(inflightOf(r.Context())).routed(p.ID, unprefixed(model))
|
||||
// the tier the reply said, unknown where the vendor's word tells
|
||||
// nothing (servedTierAt)
|
||||
defer func() { call.Usage.Tier = servedTierAt(p.Host(), call.Usage.Tier) }()
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// liveRow counts a reply as the gateway writes it to the agent, for the
|
||||
// Routing page to show while it is out (#4951, Canda15): how many bytes
|
||||
// the agent has had, when the model last wrote content, and what that
|
||||
// content is worth in output tokens. A reply mid-reasoning or a long one
|
||||
// otherwise looks stuck. It counts and drops: no byte is kept or changed.
|
||||
//
|
||||
// captureResponseWriter.Write, which every byte to the agent passes,
|
||||
// calls observe; it may be called from a held stream's keepalive and the
|
||||
// try's goroutine in turn, so everything is under mu, which nothing that
|
||||
// blocks is called under.
|
||||
type liveRow struct {
|
||||
mu sync.Mutex
|
||||
// bytes is every byte written to the agent, SSE framing and the
|
||||
// gateway's own keepalive comments included
|
||||
bytes int64
|
||||
// contentAt is the epoch ms of the last write that was not only SSE
|
||||
// comments: a keepalive never moves it, so a stuck reply shows still
|
||||
contentAt int64
|
||||
// provider and model are the try's that answers (routed), whose
|
||||
// learned rate estimates the tokens
|
||||
provider, model string
|
||||
counter liveContentCounter
|
||||
ended bool
|
||||
f *inflight
|
||||
// tr: f's trace, nil when its routes are in none
|
||||
tr *trace
|
||||
}
|
||||
|
||||
// liveBegin starts counting f's reply, from is the agent's protocol, which
|
||||
// decides what its content is. A request not counted in flight (the
|
||||
// gateway's own) has no route to tell, and is not counted.
|
||||
func liveBegin(f *inflight, model string, from provider.Protocol) *liveRow {
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
f.mu.Lock()
|
||||
tr := f.tr
|
||||
f.mu.Unlock()
|
||||
l := &liveRow{f: f, tr: tr, model: model, counter: liveContentCounter{proto: from}}
|
||||
f.live.Store(l)
|
||||
return l
|
||||
}
|
||||
|
||||
// liveOfInflight is f's counter, nil when there is none.
|
||||
func liveOfInflight(f *inflight) *liveRow {
|
||||
if f == nil {
|
||||
return nil
|
||||
}
|
||||
return f.live.Load()
|
||||
}
|
||||
|
||||
// observe counts one write to the agent and tells its route.
|
||||
func (l *liveRow) observe(p []byte) {
|
||||
if l == nil || len(p) == 0 {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
l.bytes += int64(len(p))
|
||||
if !commentOnly(p) {
|
||||
l.contentAt = time.Now().UnixMilli()
|
||||
}
|
||||
l.counter.add(p)
|
||||
bytes, contentAt, content := l.bytes, l.contentAt, l.counter.total
|
||||
provider, model := l.provider, l.model
|
||||
l.mu.Unlock()
|
||||
l.tell(bytes, contentAt, provider, model, content)
|
||||
}
|
||||
|
||||
// tell writes the running totals on the request's route, the first one
|
||||
// begun for it (noteRoute); before it is begun a later write tells it,
|
||||
// the numbers being totals.
|
||||
func (l *liveRow) tell(bytes, contentAt int64, provider, model string, content int64) {
|
||||
if l.tr == nil {
|
||||
return
|
||||
}
|
||||
rt := l.f.route.Load()
|
||||
if rt == nil {
|
||||
return
|
||||
}
|
||||
l.tr.liveBytes(rt, bytes, contentAt, liveRates.estimate(provider, model, content))
|
||||
}
|
||||
|
||||
// commentOnly reports whether p holds SSE comment lines and blank lines
|
||||
// only, at least one comment: the gateway's keepalive. It allocates
|
||||
// nothing, as it runs on every write.
|
||||
func commentOnly(p []byte) bool {
|
||||
saw, start := false, true
|
||||
for _, c := range p {
|
||||
switch {
|
||||
case c == '\n':
|
||||
start = true
|
||||
case c == '\r' && start:
|
||||
case start:
|
||||
if c != ':' {
|
||||
return false
|
||||
}
|
||||
saw, start = true, false
|
||||
}
|
||||
}
|
||||
return saw
|
||||
}
|
||||
|
||||
// totals are the row's bytes, content bytes and last content time.
|
||||
func (l *liveRow) totals() (bytes, content, contentAt int64) {
|
||||
if l == nil {
|
||||
return 0, 0, 0
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.bytes, l.counter.total, l.contentAt
|
||||
}
|
||||
|
||||
// routed names the provider and model of the try about to answer: after a
|
||||
// fallback it is another than the first.
|
||||
func (l *liveRow) routed(provider, model string) {
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
l.provider = provider
|
||||
if model != "" {
|
||||
l.model = model
|
||||
}
|
||||
l.mu.Unlock()
|
||||
}
|
||||
|
||||
// finish ends the count once: the last event still in the buffer is
|
||||
// counted, and a streamed reply that did not fail and whose vendor said
|
||||
// its output tokens is learned from. An agent that went away after the
|
||||
// last content still makes a sample, the usage in hand saying the vendor
|
||||
// finished the reply.
|
||||
func (l *liveRow) finish(failed bool, output int) {
|
||||
if l == nil {
|
||||
return
|
||||
}
|
||||
l.mu.Lock()
|
||||
if l.ended {
|
||||
l.mu.Unlock()
|
||||
return
|
||||
}
|
||||
l.ended = true
|
||||
l.counter.flush()
|
||||
sse, content := l.counter.sse, l.counter.total
|
||||
bytes, contentAt, provider, model := l.bytes, l.contentAt, l.provider, l.model
|
||||
l.mu.Unlock()
|
||||
if sse && !failed && output > 0 {
|
||||
liveRates.learn(provider, model, content, output)
|
||||
}
|
||||
l.tell(bytes, contentAt, provider, model, content)
|
||||
}
|
||||
@@ -0,0 +1,288 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// The tokens of a reply in flight can only be estimated: the vendor's
|
||||
// usage comes with the last event. What is counted is its content, the
|
||||
// text, reasoning and tool names and arguments, not every byte written:
|
||||
// the framing grows with the number of events, and differs by protocol,
|
||||
// so it would read more events as more written. Content is counted in the
|
||||
// agent's protocol, translated replies too, as what the agent received.
|
||||
//
|
||||
// Only a stream is counted: a whole JSON reply arrives at once and has
|
||||
// nothing to show while it is out, and counting it would hold a copy of
|
||||
// it. An event is decoded and dropped; only its content's length stays.
|
||||
// What isn't known counts 0.
|
||||
|
||||
// liveLineMost is the longest SSE line kept across writes: one longer is
|
||||
// not counted rather than held.
|
||||
const liveLineMost = 1 << 20
|
||||
|
||||
// liveContentCounter counts a reply's content bytes, event by event.
|
||||
type liveContentCounter struct {
|
||||
proto provider.Protocol
|
||||
// known: the first write said whether this is a stream (sse)
|
||||
known, sse bool
|
||||
// part: a line cut by the end of a write, until its end comes
|
||||
part []byte
|
||||
// data: the data lines of the event being read
|
||||
data []byte
|
||||
// skip: the line being read is too long, and is passed over to its end
|
||||
skip bool
|
||||
total int64
|
||||
}
|
||||
|
||||
// add reads one write, line by line. A whole write's lines are read in
|
||||
// place; only a line a write cuts is copied, to be joined with the next.
|
||||
func (c *liveContentCounter) add(p []byte) {
|
||||
if !c.known {
|
||||
i := 0
|
||||
for i < len(p) && (p[i] == ' ' || p[i] == '\r' || p[i] == '\n' || p[i] == '\t') {
|
||||
i++
|
||||
}
|
||||
if i == len(p) {
|
||||
return
|
||||
}
|
||||
c.known = true
|
||||
c.sse = p[i] != '{' && p[i] != '['
|
||||
}
|
||||
if !c.sse {
|
||||
return
|
||||
}
|
||||
for len(p) > 0 {
|
||||
i := bytes.IndexByte(p, '\n')
|
||||
if i < 0 {
|
||||
if !c.skip && len(c.part)+len(p) <= liveLineMost {
|
||||
c.part = append(c.part, p...)
|
||||
} else {
|
||||
c.part, c.skip = c.part[:0], true
|
||||
}
|
||||
return
|
||||
}
|
||||
line := p[:i]
|
||||
p = p[i+1:]
|
||||
if c.skip {
|
||||
c.skip = false
|
||||
continue
|
||||
}
|
||||
if len(c.part) > 0 {
|
||||
if len(c.part)+len(line) > liveLineMost {
|
||||
c.part = c.part[:0]
|
||||
continue
|
||||
}
|
||||
c.part = append(c.part, line...)
|
||||
line = c.part
|
||||
}
|
||||
c.line(bytes.TrimSuffix(line, []byte{'\r'}))
|
||||
c.part = c.part[:0]
|
||||
}
|
||||
}
|
||||
|
||||
// line reads one SSE line: a blank one ends the event.
|
||||
func (c *liveContentCounter) line(line []byte) {
|
||||
if len(line) == 0 {
|
||||
c.event()
|
||||
return
|
||||
}
|
||||
rest, ok := bytes.CutPrefix(line, []byte("data:"))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
rest = bytes.TrimPrefix(rest, []byte{' '})
|
||||
if len(c.data)+len(rest)+1 > liveLineMost {
|
||||
c.data = c.data[:0]
|
||||
return
|
||||
}
|
||||
if len(c.data) > 0 {
|
||||
c.data = append(c.data, '\n')
|
||||
}
|
||||
c.data = append(c.data, rest...)
|
||||
}
|
||||
|
||||
// event counts the event read, and forgets it.
|
||||
func (c *liveContentCounter) event() {
|
||||
if len(c.data) > 0 {
|
||||
c.total += int64(liveContentOf(c.proto, bytes.TrimSpace(c.data)))
|
||||
c.data = c.data[:0]
|
||||
}
|
||||
}
|
||||
|
||||
// flush counts what the stream ended without a blank line after.
|
||||
func (c *liveContentCounter) flush() {
|
||||
if !c.sse {
|
||||
return
|
||||
}
|
||||
if len(c.part) > 0 && !c.skip {
|
||||
c.line(bytes.TrimSuffix(c.part, []byte{'\r'}))
|
||||
}
|
||||
c.part = nil
|
||||
c.event()
|
||||
c.data = nil
|
||||
}
|
||||
|
||||
// liveContentOf is the content bytes of one event, read by its protocol.
|
||||
func liveContentOf(proto provider.Protocol, b []byte) int {
|
||||
if len(b) == 0 || b[0] != '{' {
|
||||
return 0
|
||||
}
|
||||
switch proto {
|
||||
case provider.Chat:
|
||||
return liveChatContent(b)
|
||||
case provider.Responses:
|
||||
return liveResponsesContent(b)
|
||||
case provider.Gemini:
|
||||
return liveGeminiContent(b)
|
||||
default:
|
||||
return liveAnthropicContent(b)
|
||||
}
|
||||
}
|
||||
|
||||
// liveChatDelta is a Chat delta: its text, reasoning and tool calls.
|
||||
type liveChatDelta struct {
|
||||
Content json.RawMessage `json:"content"`
|
||||
ReasoningContent string `json:"reasoning_content"`
|
||||
Reasoning string `json:"reasoning"`
|
||||
ToolCalls []liveChatToolCall `json:"tool_calls"`
|
||||
}
|
||||
|
||||
type liveChatToolCall struct {
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"function"`
|
||||
}
|
||||
|
||||
func liveChatContent(b []byte) int {
|
||||
var v struct {
|
||||
Choices []struct {
|
||||
Delta liveChatDelta `json:"delta"`
|
||||
} `json:"choices"`
|
||||
}
|
||||
if json.Unmarshal(b, &v) != nil {
|
||||
return 0
|
||||
}
|
||||
n := 0
|
||||
for _, ch := range v.Choices {
|
||||
n += liveChatDeltaLen(ch.Delta)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func liveChatDeltaLen(d liveChatDelta) int {
|
||||
n := len(d.ReasoningContent) + len(d.Reasoning) + liveContentLen(d.Content)
|
||||
for _, tc := range d.ToolCalls {
|
||||
n += len(tc.Function.Name) + len(tc.Function.Arguments)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// liveContentLen is a content field's: a string, or text parts.
|
||||
func liveContentLen(raw json.RawMessage) int {
|
||||
if len(raw) == 0 {
|
||||
return 0
|
||||
}
|
||||
switch raw[0] {
|
||||
case '"':
|
||||
var s string
|
||||
if json.Unmarshal(raw, &s) == nil {
|
||||
return len(s)
|
||||
}
|
||||
case '[':
|
||||
var parts []struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if json.Unmarshal(raw, &parts) == nil {
|
||||
n := 0
|
||||
for _, p := range parts {
|
||||
n += len(p.Text)
|
||||
}
|
||||
return n
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// liveResponsesContent counts *.delta events only: *.done says the same
|
||||
// text again.
|
||||
func liveResponsesContent(b []byte) int {
|
||||
var v struct {
|
||||
Type string `json:"type"`
|
||||
Delta json.RawMessage `json:"delta"`
|
||||
Item struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
} `json:"item"`
|
||||
}
|
||||
if json.Unmarshal(b, &v) != nil {
|
||||
return 0
|
||||
}
|
||||
if strings.HasSuffix(v.Type, ".delta") {
|
||||
return liveContentLen(v.Delta)
|
||||
}
|
||||
// a function call starts with its name; its arguments come as deltas
|
||||
if v.Type == "response.output_item.added" && v.Item.Type == "function_call" {
|
||||
return len(v.Item.Name)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// liveAnthropicContent counts content_block_delta's text, thinking and
|
||||
// tool input, and a tool_use block's name.
|
||||
func liveAnthropicContent(b []byte) int {
|
||||
var v struct {
|
||||
Type string `json:"type"`
|
||||
Delta struct {
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
PartialJSON string `json:"partial_json"`
|
||||
} `json:"delta"`
|
||||
ContentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
} `json:"content_block"`
|
||||
}
|
||||
if json.Unmarshal(b, &v) != nil {
|
||||
return 0
|
||||
}
|
||||
n := len(v.Delta.Text) + len(v.Delta.Thinking) + len(v.Delta.PartialJSON)
|
||||
if v.ContentBlock.Type == "tool_use" {
|
||||
n += len(v.ContentBlock.Name)
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// liveGeminiContent counts a chunk's parts, each new.
|
||||
func liveGeminiContent(b []byte) int {
|
||||
var v struct {
|
||||
Candidates []struct {
|
||||
Content struct {
|
||||
Parts []struct {
|
||||
Text string `json:"text"`
|
||||
FunctionCall struct {
|
||||
Name string `json:"name"`
|
||||
Args json.RawMessage `json:"args"`
|
||||
} `json:"functionCall"`
|
||||
} `json:"parts"`
|
||||
} `json:"content"`
|
||||
} `json:"candidates"`
|
||||
}
|
||||
if json.Unmarshal(b, &v) != nil {
|
||||
return 0
|
||||
}
|
||||
n := 0
|
||||
for _, c := range v.Candidates {
|
||||
for _, p := range c.Content.Parts {
|
||||
n += len(p.Text)
|
||||
if p.FunctionCall.Name != "" || len(p.FunctionCall.Args) > 0 {
|
||||
n += len(p.FunctionCall.Name) + len(p.FunctionCall.Args)
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// routeMoment reads what a request's route says now: the bytes received
|
||||
// and when content last came, under the trace's lock the gateway writes
|
||||
// them under.
|
||||
func routeMoment(s *Server, model string) (bytes, contentAt int64, found bool) {
|
||||
s.trace.mu.Lock()
|
||||
defer s.trace.mu.Unlock()
|
||||
for _, rt := range s.trace.routes {
|
||||
if rt.Model == model {
|
||||
return rt.Bytes, rt.ContentAt, true
|
||||
}
|
||||
}
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
// A real request through the whole gateway, its vendor streaming slowly:
|
||||
// while it is out its route has the bytes the client has had, once it
|
||||
// ends exactly the bytes the client received, and the provider and model
|
||||
// that answered have learned from it.
|
||||
func TestLiveCountsARealStream(t *testing.T) {
|
||||
freshRates(t)
|
||||
chunks := []string{
|
||||
"data: {\"choices\":[{\"delta\":{\"content\":\"one\"}}]}\n\n",
|
||||
"data: {\"choices\":[{\"delta\":{\"content\":\"two\"}}]}\n\n",
|
||||
"data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":3,\"completion_tokens\":5,\"total_tokens\":8}}\n\n",
|
||||
"data: [DONE]\n\n",
|
||||
}
|
||||
// the vendor stops after the first event until the test has looked
|
||||
release := make(chan struct{})
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("content-type", "text/event-stream")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
for i, c := range chunks {
|
||||
if _, err := io.WriteString(w, c); err != nil {
|
||||
return
|
||||
}
|
||||
w.(http.Flusher).Flush()
|
||||
if i == 0 {
|
||||
<-release
|
||||
}
|
||||
}
|
||||
}))
|
||||
defer up.Close()
|
||||
defer func() {
|
||||
// let the vendor go on a failure half way, or httptest can't close
|
||||
select {
|
||||
case <-release:
|
||||
default:
|
||||
close(release)
|
||||
}
|
||||
}()
|
||||
|
||||
if err := provider.Save(provider.Provider{ID: "live", Name: "Live", Chat: up.URL + "/v1", Key: "k", Models: []string{"m"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := New()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"live/m","stream":true,"messages":[{"role":"user","content":"hi"}]}`))
|
||||
req.Header.Set("content-type", "application/json")
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
}()
|
||||
|
||||
// wait for the first bytes to reach the client's route
|
||||
var midBytes, midContentAt int64
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
if bytes, contentAt, ok := routeMoment(s, "live/m"); ok && bytes > 0 {
|
||||
midBytes, midContentAt = bytes, contentAt
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
close(release)
|
||||
_, _, found := routeMoment(s, "live/m")
|
||||
t.Fatalf("a request whose first bytes arrived has no progress on its route (found=%v)", found)
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
if midBytes != int64(len(chunks[0])) {
|
||||
t.Fatalf("mid-stream bytes are %d, the client got %d", midBytes, len(chunks[0]))
|
||||
}
|
||||
if midContentAt == 0 {
|
||||
t.Fatal("content arrived but the route has no content time")
|
||||
}
|
||||
|
||||
close(release)
|
||||
<-done
|
||||
|
||||
bytes, _, ok := routeMoment(s, "live/m")
|
||||
if !ok {
|
||||
t.Fatal("the route is gone")
|
||||
}
|
||||
if want := int64(rec.Body.Len()); bytes != want {
|
||||
t.Fatalf("counted %d bytes, the client received %d", bytes, want)
|
||||
}
|
||||
if want := int64(len(strings.Join(chunks, ""))); bytes != want {
|
||||
t.Fatalf("counted %d bytes, the upstream wrote %d", bytes, want)
|
||||
}
|
||||
|
||||
s.trace.mu.Lock()
|
||||
rt := s.trace.routes[len(s.trace.routes)-1]
|
||||
done2, output := rt.Done, rt.Output
|
||||
s.trace.mu.Unlock()
|
||||
if !done2 {
|
||||
t.Fatal("the route is still open after the reply ended")
|
||||
}
|
||||
// the vendor's 5, not an estimate
|
||||
if output != 5 {
|
||||
t.Fatalf("the route says %d output tokens, the vendor said 5", output)
|
||||
}
|
||||
|
||||
liveRates.mu.Lock()
|
||||
learned := liveRates.m["live/m"]
|
||||
liveRates.mu.Unlock()
|
||||
if learned.seen != 1 || learned.bytes != 6 || learned.output != 5 {
|
||||
t.Fatalf("learned %+v from the reply, want 6 content bytes for 5 tokens", learned)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// tokenRates learns how many output tokens a provider's model writes per
|
||||
// content byte, from streamed replies whose vendor said their output
|
||||
// tokens, to estimate a reply in flight before its usage comes (#4951).
|
||||
// An estimate is never learned from, and under liveRateMin replies there
|
||||
// is none: the page then shows no tokens rather than a guess.
|
||||
//
|
||||
// The rates are kept in memory only: a restart learns them again in
|
||||
// liveRateMin replies, and nothing is written per request.
|
||||
const (
|
||||
liveRateMin = 3 // replies learned before a pair estimates
|
||||
liveRateKeys = 256 // pairs kept, the least recently learned dropped
|
||||
)
|
||||
|
||||
// rateSample is a pair's sums: estimating a ratio needs no more.
|
||||
type rateSample struct {
|
||||
bytes, output int64
|
||||
seen int
|
||||
at int64
|
||||
}
|
||||
|
||||
type tokenRates struct {
|
||||
mu sync.Mutex
|
||||
m map[string]rateSample
|
||||
}
|
||||
|
||||
// liveRates is the gateway's one: estimate runs on every write of a
|
||||
// stream, a multiplication under a lock nothing blocks under.
|
||||
var liveRates = &tokenRates{m: map[string]rateSample{}}
|
||||
|
||||
func rateKey(provider, model string) string {
|
||||
if provider == "" || model == "" {
|
||||
return ""
|
||||
}
|
||||
return provider + "/" + model
|
||||
}
|
||||
|
||||
// estimate is content's output tokens at the pair's learned rate, rounded
|
||||
// down, or 0 when it has none yet.
|
||||
func (t *tokenRates) estimate(provider, model string, content int64) int {
|
||||
if content <= 0 || provider == "" || model == "" {
|
||||
return 0
|
||||
}
|
||||
t.mu.Lock()
|
||||
s, ok := t.m[rateKey(provider, model)]
|
||||
t.mu.Unlock()
|
||||
if !ok || s.seen < liveRateMin || s.bytes <= 0 || s.output <= 0 {
|
||||
return 0
|
||||
}
|
||||
// in floats: the sums grow with every reply, and their product with a
|
||||
// long reply's content would overflow
|
||||
return int(float64(content) * float64(s.output) / float64(s.bytes))
|
||||
}
|
||||
|
||||
// learn adds one finished reply: content bytes and the vendor's output.
|
||||
func (t *tokenRates) learn(provider, model string, content int64, output int) {
|
||||
key := rateKey(provider, model)
|
||||
if key == "" || content <= 0 || output <= 0 {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
s := t.m[key]
|
||||
s.bytes += content
|
||||
s.output += int64(output)
|
||||
s.seen++
|
||||
s.at = time.Now().UnixNano()
|
||||
t.m[key] = s
|
||||
if len(t.m) > liveRateKeys {
|
||||
oldest, at := "", int64(1<<62)
|
||||
for k, v := range t.m {
|
||||
if v.at < at {
|
||||
oldest, at = k, v.at
|
||||
}
|
||||
}
|
||||
delete(t.m, oldest)
|
||||
}
|
||||
}
|
||||
|
||||
// resetRates forgets every rate, for a test.
|
||||
func resetRates() {
|
||||
liveRates.mu.Lock()
|
||||
liveRates.m = map[string]rateSample{}
|
||||
liveRates.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// freshRates starts a test with no rate learned, and leaves none after.
|
||||
func freshRates(t *testing.T) {
|
||||
t.Helper()
|
||||
resetRates()
|
||||
t.Cleanup(resetRates)
|
||||
}
|
||||
|
||||
// liveFor is a counter for a request in flight whose route is rt.
|
||||
func liveFor(rt *Route, proto provider.Protocol) *liveRow {
|
||||
f := &inflight{tr: &trace{}}
|
||||
if rt != nil {
|
||||
f.route.Store(rt)
|
||||
}
|
||||
return liveBegin(f, "m", proto)
|
||||
}
|
||||
|
||||
func liveChatEvent(s string) []byte {
|
||||
return []byte(`data: {"choices":[{"delta":{"content":"` + s + `"}}]}` + "\n\n")
|
||||
}
|
||||
|
||||
// The bytes are every byte the agent got, the content only the words, and
|
||||
// a finish counted twice (an encoder's last write after serve) changes
|
||||
// nothing.
|
||||
func TestLiveCountsBytesAndContent(t *testing.T) {
|
||||
freshRates(t)
|
||||
live := liveFor(nil, provider.Chat)
|
||||
if b, c, at := live.totals(); b != 0 || c != 0 || at != 0 {
|
||||
t.Fatalf("a request with no byte yet: %d bytes, %d content, content at %d", b, c, at)
|
||||
}
|
||||
first := liveChatEvent("hello")
|
||||
live.observe(first)
|
||||
b, c, at := live.totals()
|
||||
if b != int64(len(first)) || c != 5 || at == 0 {
|
||||
t.Fatalf("after %q: %d bytes, %d content, content at %d", first, b, c, at)
|
||||
}
|
||||
live.finish(false, 42)
|
||||
live.finish(false, 42)
|
||||
if _, c, _ := live.totals(); c != 5 {
|
||||
t.Fatalf("content after it ended twice: %d, want 5", c)
|
||||
}
|
||||
}
|
||||
|
||||
// The gateway's keepalive adds bytes, but neither content nor a newer
|
||||
// content time: a stuck reply must look still.
|
||||
func TestLiveHeartbeatIsBytesNotContent(t *testing.T) {
|
||||
live := liveFor(nil, provider.Chat)
|
||||
live.observe(liveChatEvent("a"))
|
||||
b0, c0, at0 := live.totals()
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
beat := []byte(": keepalive\n")
|
||||
live.observe(beat)
|
||||
b, c, at := live.totals()
|
||||
if b != b0+int64(len(beat)) || c != c0 || at != at0 {
|
||||
t.Fatalf("a keepalive: bytes %d→%d, content %d→%d, content at %d→%d", b0, b, c0, c, at0, at)
|
||||
}
|
||||
live.observe(liveChatEvent("b"))
|
||||
if _, _, back := live.totals(); back <= at0 {
|
||||
t.Fatalf("content didn't move the time forward: %d then %d", at0, back)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommentOnlyTellsHeartbeatsApart(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
in string
|
||||
want bool
|
||||
}{
|
||||
{": keepalive\n", true},
|
||||
{": keepalive\n\n", true},
|
||||
{"\n: ping\r\n\n", true},
|
||||
{"", false},
|
||||
{"\n\n", false},
|
||||
{"data: {\"a\":1}\n\n", false},
|
||||
{": keepalive\ndata: {\"a\":1}\n\n", false},
|
||||
{"data: {\"a\":\":\"}\n", false},
|
||||
{`{"a":1}`, false},
|
||||
} {
|
||||
if got := commentOnly([]byte(c.in)); got != c.want {
|
||||
t.Errorf("commentOnly(%q) = %v, want %v", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What counts as content in each protocol, from events as the vendors
|
||||
// write them.
|
||||
func TestContentBytesPerProtocol(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
proto provider.Protocol
|
||||
body string
|
||||
want int
|
||||
}{
|
||||
{"chat text", provider.Chat, `{"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}]}`, 5},
|
||||
{"chat reasoning", provider.Chat, `{"choices":[{"delta":{"reasoning_content":"hm"}}]}`, 2},
|
||||
{"chat tool name", provider.Chat, `{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"read","arguments":""}}]}}]}`, 4},
|
||||
{"chat tool args", provider.Chat, `{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"a\":1}"}}]}}]}`, 7},
|
||||
{"chat usage", provider.Chat, `{"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":5}}`, 0},
|
||||
{"responses delta", provider.Responses, `{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"content_index":0,"delta":"abc"}`, 3},
|
||||
{"responses done", provider.Responses, `{"type":"response.output_text.done","text":"abc"}`, 0},
|
||||
{"responses call", provider.Responses, `{"type":"response.output_item.added","item":{"type":"function_call","name":"shell","arguments":""}}`, 5},
|
||||
{"anthropic text", provider.Anthropic, `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"abc"}}`, 3},
|
||||
{"anthropic thinking", provider.Anthropic, `{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"de"}}`, 2},
|
||||
{"anthropic tool", provider.Anthropic, `{"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_1","name":"grep","input":{}}}`, 4},
|
||||
{"anthropic input", provider.Anthropic, `{"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}`, 5},
|
||||
{"gemini text", provider.Gemini, `{"candidates":[{"content":{"parts":[{"text":"abc"}],"role":"model"}}]}`, 3},
|
||||
{"gemini call", provider.Gemini, `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"ls","args":{}}}]}}]}`, 4},
|
||||
{"done", provider.Chat, `[DONE]`, 0},
|
||||
{"empty", provider.Chat, `{}`, 0},
|
||||
} {
|
||||
if got := liveContentOf(c.proto, []byte(c.body)); got != c.want {
|
||||
t.Errorf("%s: %s gave %d, want %d", c.name, c.body, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A stream cut into writes of any size counts the same as written whole.
|
||||
func TestContentCounterSurvivesSplitWrites(t *testing.T) {
|
||||
stream := string(liveChatEvent("hello")) + ": keepalive\n" + string(liveChatEvent(" wörld")) + "data: [DONE]\n\n"
|
||||
for _, size := range []int{1, 2, 3, 7, 13, len(stream)} {
|
||||
c := &liveContentCounter{proto: provider.Chat}
|
||||
for i := 0; i < len(stream); i += size {
|
||||
c.add([]byte(stream[i:min(i+size, len(stream))]))
|
||||
}
|
||||
c.flush()
|
||||
if c.total != 12 {
|
||||
t.Errorf("written in %d-byte pieces: %d content bytes, want 12", size, c.total)
|
||||
}
|
||||
}
|
||||
// a stream ending without its blank line still counts its last event
|
||||
c := &liveContentCounter{proto: provider.Chat}
|
||||
c.add([]byte(strings.TrimSuffix(string(liveChatEvent("abc")), "\n\n")))
|
||||
c.flush()
|
||||
if c.total != 3 {
|
||||
t.Errorf("a last event without its blank line: %d, want 3", c.total)
|
||||
}
|
||||
}
|
||||
|
||||
// A whole JSON reply is not counted (nor copied): it arrives at once and
|
||||
// shows nothing while it is out, and it is not learned from.
|
||||
func TestContentCounterLeavesAWholeReply(t *testing.T) {
|
||||
freshRates(t)
|
||||
for i := 0; i < liveRateMin+1; i++ {
|
||||
live := liveFor(nil, provider.Chat)
|
||||
live.routed("vendor", "m")
|
||||
live.observe([]byte(`{"choices":[{"message":{"content":"pong"}}],"usage":{"completion_tokens":2}}`))
|
||||
if live.counter.sse || len(live.counter.part) != 0 || len(live.counter.data) != 0 {
|
||||
t.Fatalf("a whole reply was read as a stream or held: %+v", live.counter)
|
||||
}
|
||||
live.finish(false, 2)
|
||||
}
|
||||
if got := liveRates.estimate("vendor", "m", 100); got != 0 {
|
||||
t.Fatalf("whole replies were learned from: estimate %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// A line longer than liveLineMost is passed over, not held.
|
||||
func TestContentCounterDropsAnEndlessLine(t *testing.T) {
|
||||
c := &liveContentCounter{proto: provider.Chat}
|
||||
c.add([]byte("data: \""))
|
||||
chunk := []byte(strings.Repeat("x", 64<<10))
|
||||
for i := 0; i < 2*liveLineMost/len(chunk); i++ {
|
||||
c.add(chunk)
|
||||
}
|
||||
if len(c.part) > liveLineMost {
|
||||
t.Fatalf("held %d bytes of one line", len(c.part))
|
||||
}
|
||||
c.add([]byte("\"\n\n"))
|
||||
c.add(liveChatEvent("ok"))
|
||||
c.flush()
|
||||
if c.total != 2 {
|
||||
t.Fatalf("after an endless line: %d content bytes, want 2", c.total)
|
||||
}
|
||||
}
|
||||
|
||||
// Three replies learned before an estimate, at their summed ratio, per
|
||||
// provider and model, rounded down.
|
||||
func TestRatesLearnThenEstimate(t *testing.T) {
|
||||
freshRates(t)
|
||||
liveRates.learn("vendor", "m", 100, 10)
|
||||
if got := liveRates.estimate("vendor", "m", 500); got != 0 {
|
||||
t.Fatalf("one sample estimated %d", got)
|
||||
}
|
||||
liveRates.learn("vendor", "m", 100, 10)
|
||||
liveRates.learn("vendor", "m", 200, 20)
|
||||
if got := liveRates.estimate("vendor", "m", 959); got != 95 {
|
||||
t.Fatalf("959 content bytes at 10:1 is 95 tokens, got %d", got)
|
||||
}
|
||||
if got := liveRates.estimate("other", "m", 950); got != 0 {
|
||||
t.Fatalf("another provider was estimated from this one's samples: %d", got)
|
||||
}
|
||||
// sums past what an int64 product holds still estimate
|
||||
for i := 0; i < 3; i++ {
|
||||
liveRates.learn("big", "m", 1<<40, 1<<38)
|
||||
}
|
||||
if got := liveRates.estimate("big", "m", 1<<30); got != 1<<28 {
|
||||
t.Fatalf("large sums estimated %d, want %d", got, 1<<28)
|
||||
}
|
||||
}
|
||||
|
||||
// Only a streamed reply that didn't fail and whose vendor said its output
|
||||
// is learned from; an agent gone after the last content still is.
|
||||
func TestRatesLearnFromRepliesTheVendorFinished(t *testing.T) {
|
||||
freshRates(t)
|
||||
for _, c := range []struct {
|
||||
vendor string
|
||||
failed bool
|
||||
output int
|
||||
learn bool
|
||||
}{
|
||||
{"v-failed", true, 10, false},
|
||||
{"v-nousage", false, 0, false},
|
||||
{"v-ok", false, 10, true},
|
||||
} {
|
||||
live := liveFor(nil, provider.Chat)
|
||||
live.routed(c.vendor, "m")
|
||||
live.observe(liveChatEvent("hello"))
|
||||
live.finish(c.failed, c.output)
|
||||
liveRates.mu.Lock()
|
||||
got := liveRates.m[c.vendor+"/m"]
|
||||
liveRates.mu.Unlock()
|
||||
if c.learn != (got.seen == 1) || c.learn && (got.bytes != 5 || got.output != 10) {
|
||||
t.Errorf("%s: learned %+v, want learned=%v", c.vendor, got, c.learn)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The gateway's own requests are not counted, and every method is safe on
|
||||
// the nil they get.
|
||||
func TestLiveIsOptional(t *testing.T) {
|
||||
if l := liveBegin(nil, "m", provider.Chat); l != nil {
|
||||
t.Fatal("a request not in flight was counted")
|
||||
}
|
||||
var live *liveRow
|
||||
live.observe([]byte("x"))
|
||||
live.routed("p", "m")
|
||||
live.finish(true, 0)
|
||||
if liveOfInflight(nil) != nil || liveOfInflight(&inflight{}) != nil {
|
||||
t.Fatal("a request with no counter has one")
|
||||
}
|
||||
f := &inflight{}
|
||||
if l := liveBegin(f, "m", provider.Chat); liveOfInflight(f) != l {
|
||||
t.Fatal("the counter begun isn't the request's")
|
||||
}
|
||||
}
|
||||
|
||||
// Writes reach the request's route: a keepalive its bytes and not its
|
||||
// content time, and a route begun after the first write the running total.
|
||||
func TestLiveWritesReachTheRoute(t *testing.T) {
|
||||
freshRates(t)
|
||||
rt := &Route{Agent: "a", Model: "m", Time: time.Now()}
|
||||
live := liveFor(rt, provider.Chat)
|
||||
first := liveChatEvent("hello")
|
||||
live.observe(first)
|
||||
if rt.Bytes != int64(len(first)) || rt.ContentAt == 0 || rt.Seq == 0 {
|
||||
t.Fatalf("the route didn't hear the first bytes: %+v", rt)
|
||||
}
|
||||
at, seq := rt.ContentAt, rt.Seq
|
||||
beat := []byte(": keepalive\n")
|
||||
live.observe(beat)
|
||||
if rt.Bytes != int64(len(first)+len(beat)) || rt.ContentAt != at || rt.Seq <= seq {
|
||||
t.Fatalf("after a keepalive the route has %d bytes, content at %d (was %d), seq %d (was %d)", rt.Bytes, rt.ContentAt, at, rt.Seq, seq)
|
||||
}
|
||||
|
||||
f := &inflight{tr: &trace{}}
|
||||
late := liveBegin(f, "m", provider.Chat)
|
||||
late.observe(first)
|
||||
lateRoute := &Route{Agent: "a", Model: "m", Time: time.Now()}
|
||||
f.route.Store(lateRoute)
|
||||
late.observe(first)
|
||||
if want := int64(2 * len(first)); lateRoute.Bytes != want {
|
||||
t.Fatalf("a route begun late got %d bytes, want the running total %d", lateRoute.Bytes, want)
|
||||
}
|
||||
}
|
||||
|
||||
// The route gets an estimate once its provider and model learned a rate,
|
||||
// and none before.
|
||||
func TestRouteGetsTheEstimateOnlyOnceItIsCalibrated(t *testing.T) {
|
||||
freshRates(t)
|
||||
rt := &Route{Agent: "a", Model: "m", Time: time.Now()}
|
||||
live := liveFor(rt, provider.Chat)
|
||||
live.routed("vendor", "m")
|
||||
live.observe(liveChatEvent("hello"))
|
||||
if rt.EstTok != 0 {
|
||||
t.Fatalf("estimated %d tokens with no sample", rt.EstTok)
|
||||
}
|
||||
for i := 0; i < liveRateMin; i++ {
|
||||
done := liveFor(nil, provider.Chat)
|
||||
done.routed("vendor", "m")
|
||||
done.observe(liveChatEvent("hello"))
|
||||
done.finish(false, 2)
|
||||
}
|
||||
live.observe(liveChatEvent("hello"))
|
||||
// 10 content bytes at 15 bytes for 6 tokens
|
||||
if rt.EstTok != 4 {
|
||||
t.Fatalf("10 content bytes at 2.5 bytes a token is 4; got %d", rt.EstTok)
|
||||
}
|
||||
}
|
||||
@@ -151,6 +151,12 @@ type Route struct {
|
||||
// is unknown (maskingMs)
|
||||
Phase string `json:"phase,omitempty"`
|
||||
Masking int64 `json:"masking,omitempty"`
|
||||
// Bytes, ContentAt and EstTok: the reply as it reaches the agent
|
||||
// (live.go), the bytes it has had, the epoch ms content last came, and
|
||||
// the output tokens estimated from it, 0 while its pair has no rate
|
||||
Bytes int64 `json:"bytes,omitempty"`
|
||||
ContentAt int64 `json:"contentAt,omitempty"`
|
||||
EstTok int `json:"estTok,omitempty"`
|
||||
// Held: the file name, in HeldDir, of the report saved of a request
|
||||
// magpie held too long before routing it and stopped (giveUp)
|
||||
Held string `json:"held,omitempty"`
|
||||
@@ -861,6 +867,22 @@ func (t *trace) update(r *Route, f func(r *Route)) {
|
||||
}
|
||||
}
|
||||
|
||||
// liveBytes writes a reply's running totals on its route (live.go): the
|
||||
// bytes the agent has had, when content last came, and its estimated
|
||||
// output tokens. Each write wakes the pages waiting, which gather a
|
||||
// moment before they read (traceGather), so a stream's many writes reach
|
||||
// a page a few times a second, and the last before a pause is not lost.
|
||||
func (t *trace) liveBytes(rt *Route, bytes, contentAt int64, est int) {
|
||||
if rt == nil {
|
||||
return
|
||||
}
|
||||
t.mu.Lock()
|
||||
rt.Bytes, rt.ContentAt, rt.EstTok = bytes, contentAt, est
|
||||
t.changed()
|
||||
rt.Seq = t.seq
|
||||
t.mu.Unlock()
|
||||
}
|
||||
|
||||
// gatewayTrace tells this gateway's routing to another magpie on the same
|
||||
// computer, which does not serve the gateway and so has no trace of its own
|
||||
// (#2606, fatcutegg: the trace is the serving process's, and a second magpie
|
||||
|
||||
@@ -4570,6 +4570,12 @@ const I18N = {
|
||||
"Remove this window": "删除这个时段",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "时段倍率:每个时段是星期、一个如 09:00 的时间、另一个结束时间,以及一个 0 到 1000、至多三位小数的倍率",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "现在按 {rate} 计费:价格倍率乘以当前时段的倍率",
|
||||
// Insights › Routing (plugins/routing): the live progress a request still being answered shows
|
||||
"≈ {n} tokens": "≈ {n} token",
|
||||
"{d} ago": "{d}前",
|
||||
"How much of this reply has reached the client, framing included": "这条回复已经送到客户端的字节数,含流式封装",
|
||||
"What the words written so far are worth in output tokens, learned per provider and model": "已经写出的这些字值多少输出 tokens,按上游与模型学来的比例估算",
|
||||
"How long ago the model last wrote something. A quiet reply is not a failed one": "模型最近一次写出内容是多久以前。安静不代表失败",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "脱敏",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "每条被脱敏的请求、厂商看到的样子和遮法,都在 观测 › 脱敏",
|
||||
@@ -9140,6 +9146,12 @@ const I18N = {
|
||||
"Remove this window": "刪除這個時段",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "時段倍率:每個時段是星期、一個如 09:00 的時間、另一個結束時間,以及一個 0 到 1000、至多三位小數的倍率",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "現在以 {rate} 計費:價格倍率乘上目前時段的倍率",
|
||||
// Insights › Routing (plugins/routing): the live progress a request still being answered shows
|
||||
"≈ {n} tokens": "≈ {n} token",
|
||||
"{d} ago": "{d}前",
|
||||
"How much of this reply has reached the client, framing included": "這條回覆已經送到客戶端的位元組數,含串流封裝",
|
||||
"What the words written so far are worth in output tokens, learned per provider and model": "已經寫出的這些字值多少輸出 tokens,按上游與模型學來的比例估算",
|
||||
"How long ago the model last wrote something. A quiet reply is not a failed one": "模型最近一次寫出內容是多久以前。安靜不代表失敗",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "脫敏",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "每則被脫敏的請求、廠商看到的樣子和遮法,都在 觀測 › 脫敏",
|
||||
@@ -13712,6 +13724,12 @@ const I18N = {
|
||||
"Remove this window": "この時間帯を削除",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "時間帯倍率:各時間帯は曜日、09:00 のような時刻、終了する別の時刻、そして小数3位までの 0 から 1000 の倍率で指定します",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "現在は {rate} で計上:価格倍率×現在の時間帯の倍率",
|
||||
// Insights › Routing (plugins/routing): the live progress a request still being answered shows
|
||||
"≈ {n} tokens": "≈ {n} tokens",
|
||||
"{d} ago": "{d}前",
|
||||
"How much of this reply has reached the client, framing included": "この返信がクライアントに届いたバイト数(ストリームの枠を含む)",
|
||||
"What the words written so far are worth in output tokens, learned per provider and model": "ここまでに書かれた語が出力 tokens で何個ぶんか。上流とモデルごとに学んだ比率で推定",
|
||||
"How long ago the model last wrote something. A quiet reply is not a failed one": "モデルが最後に内容を書いたのはいつか。静かなのは失敗ではない",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "マスク",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "マスクしたリクエストごとに、ベンダーに届いた姿とマスクの仕方を 観測 › マスク で見られます",
|
||||
@@ -18284,6 +18302,12 @@ const I18N = {
|
||||
"Remove this window": "Dieses Zeitfenster entfernen",
|
||||
"Rate windows: every window is days, a time like 09:00, another time for it to end, and a rate from 0 to 1000 with at most three decimals": "Zeitfenster: jedes Zeitfenster besteht aus Wirktagen, einer Zeit wie 09:00, einer anderen Endzeit und einer Rate von 0 bis 1000 mit höchstens drei Dezimalstellen",
|
||||
"Bills at {rate} now: the price rate times this hour's window": "Rechnet gerade mit {rate} ab: der Preisfaktor mal das Zeitfenster dieser Stunde",
|
||||
// Insights › Routing (plugins/routing): the live progress a request still being answered shows
|
||||
"≈ {n} tokens": "≈ {n} tokens",
|
||||
"{d} ago": "vor {d}",
|
||||
"How much of this reply has reached the client, framing included": "Wie viele Bytes dieser Antwort schon beim Client angekommen sind, samt Stream-Rahmen",
|
||||
"What the words written so far are worth in output tokens, learned per provider and model": "Was die bisher geschriebenen Wörter in Ausgabe-tokens wert sind, geschätzt aus dem je Anbieter und Modell gelernten Verhältnis",
|
||||
"How long ago the model last wrote something. A quiet reply is not a failed one": "Wie lange es her ist, dass das Modell zuletzt etwas geschrieben hat. Still heißt nicht gescheitert",
|
||||
// Insights › Masking (plugins/redact), words said elsewhere too
|
||||
"Masking": "Maskierung",
|
||||
"Each request masking changed, what the vendor saw, and how, on Insights › Masking": "Jede maskierte Anfrage, was der Anbieter sah und wie, unter Einblick › Maskierung",
|
||||
|
||||
@@ -409,6 +409,17 @@ function routingPage(part) {
|
||||
return t("{n} d", { n: Math.round(m / 1440) });
|
||||
}
|
||||
const took = (ms = 0) => ms < 1000 ? t("{n} ms", { n: ms }) : t("{n} s", { n: (ms / 1000).toFixed(ms < 10e3 ? 1 : 0) });
|
||||
// A reply in flight (#4951): the bytes the agent has had, what the content
|
||||
// is worth in tokens, and how long ago content last came. For requests
|
||||
// still out only: an ended row has its own metrics, which say more.
|
||||
const liveSize = (n) => n >= 1048576 ? (n / 1048576).toFixed(1) + " MiB"
|
||||
: n >= 1024 ? (n / 1024).toFixed(1) + " KiB" : Math.round(n || 0) + " B";
|
||||
// an estimate always carries ≈, and with no rate learned yet there is none
|
||||
const liveTokens = (r) => r.estTok ? t("≈ {n} tokens", { n: tokens(r.estTok) }) : "";
|
||||
// quiet is not failed: the row says how long ago, and its dot stops
|
||||
// pulsing after liveQuietMs with no content
|
||||
const liveQuietMs = 15e3;
|
||||
const liveSince = (r, now = Date.now()) => r.contentAt ? t("{d} ago", { d: dur(Math.max(0, now - r.contentAt)) }) : "";
|
||||
// (the formats made once: made for each call, they were much of what the
|
||||
// accounts' countdowns cost), made again when the GUI's language changes
|
||||
let fmtLang = null, HM, WD;
|
||||
@@ -2732,7 +2743,17 @@ function routingPage(part) {
|
||||
else if (w.window) s = t("request longer than its {n} window · passed over", { n: ctxShort(w.window) });
|
||||
// a row another request weighed, answering that one: the header
|
||||
// tells of this request, so it says the answer is not this one's
|
||||
else if (trying.has(id)) { s = (r.id !== cur.id && agents.size <= 1 ? t("answering another request…") : t("answering…")) + (said && " · " + said); named = titleOf(trying.get(id)); }
|
||||
else if (trying.has(id)) {
|
||||
// this request's progress beside the account answering it; not
|
||||
// when the account answers another request, whose numbers they are
|
||||
const live = r.id === cur.id ? liveParts(r).map(([value]) => value).join(" · ") : "";
|
||||
// gone quiet, it says the numbers only: "answering…" would read as
|
||||
// the vendor still writing
|
||||
const hushed = live && r.contentAt && Date.now() - r.contentAt >= liveQuietMs;
|
||||
s = hushed ? live
|
||||
: (r.id !== cur.id && agents.size <= 1 ? t("answering another request…") : t("answering…")) + (said && " · " + said) + (live ? " · " + live : "");
|
||||
named = titleOf(trying.get(id));
|
||||
}
|
||||
else if (answered.has(id)) { s = (agents.size > 1 ? t("answered {agent}", { agent: agentName(r.agent) }) : t("answered this request")) + (said && " · " + said); named = titleOf(r); }
|
||||
else if (gave.has(id)) s = t("{status} · {fail} · passed to {agent}", { status: gave.get(id).status, fail: failWord(gave.get(id).fail), agent: agentName(r.agent) });
|
||||
else if (went.has(id)) s = t("{status} · {fail} · went on to the next", { status: went.get(id).status, fail: failWord(went.get(id).fail) });
|
||||
@@ -2794,6 +2815,10 @@ function routingPage(part) {
|
||||
const flying = !resting && (trying.has(id) || onWire.has(id));
|
||||
const on = flying || (!resting && answered.has(id));
|
||||
lightRow(row.li, row.wire, on, flying);
|
||||
// quiet: the reply is still out but no content came for liveQuietMs;
|
||||
// the dot stops pulsing, as it has not failed
|
||||
const quiet = flying && r.id === cur.id && !cur.done && cur.contentAt && Date.now() - cur.contentAt >= liveQuietMs;
|
||||
row.li.classList.toggle("quiet", !!quiet);
|
||||
row.li.classList.toggle("low", !!(tiered(w) && w.known && group(w) !== "fine"));
|
||||
row.li.classList.toggle("rest", !!resting || gave.has(id));
|
||||
row.li.classList.toggle("left", !!w.unlisted || !!w.window);
|
||||
@@ -3925,9 +3950,51 @@ function routingPage(part) {
|
||||
rowsMoved = true;
|
||||
}
|
||||
x.r = r;
|
||||
// a row is built again only when what it says changes (#3731); the live
|
||||
// numbers aren't in its sig, so they are changed in place
|
||||
paintLive(x.b, r);
|
||||
if (x.b.getAttribute("aria-pressed") !== sel) x.b.setAttribute("aria-pressed", sel);
|
||||
return x.b;
|
||||
}
|
||||
// liveParts: a request in flight's numbers, [value, help], for its row and
|
||||
// for the account answering it
|
||||
function liveParts(r, now = Date.now()) {
|
||||
if (r.done || !r.bytes) return [];
|
||||
const parts = [[liveSize(r.bytes), t("How much of this reply has reached the client, framing included")]];
|
||||
if (r.estTok) parts.push([liveTokens(r), t("What the words written so far are worth in output tokens, learned per provider and model")]);
|
||||
if (r.contentAt) parts.push([liveSince(r, now), t("How long ago the model last wrote something. A quiet reply is not a failed one")]);
|
||||
return parts;
|
||||
}
|
||||
// liveCells: those numbers as the row's cells, unlabelled (each value
|
||||
// carries its unit), found again by paintLive by their .recv class
|
||||
function liveCells(r, now = Date.now()) {
|
||||
return liveParts(r, now).map(([value, help]) => ["recv", "", value, help]);
|
||||
}
|
||||
// paintLive changes the cells in place, or adds or removes them all when
|
||||
// their count changed (a new number, or the request ended)
|
||||
function paintLive(button, r) {
|
||||
const meta = button.querySelector(".meta");
|
||||
if (!meta) return;
|
||||
const cells = liveCells(r);
|
||||
const had = [...meta.querySelectorAll(".rt-metric.recv")];
|
||||
if (had.length !== cells.length) {
|
||||
had.forEach((c) => c.remove());
|
||||
cells.forEach((c) => meta.append(metricElement(c, true)));
|
||||
meta.hidden = !meta.children.length;
|
||||
return;
|
||||
}
|
||||
cells.forEach(([cls, label, value, help], i) => {
|
||||
const cell = had[i];
|
||||
const v = cell.querySelector(".v");
|
||||
if (v && v.textContent !== value) v.textContent = value;
|
||||
if (cell.title !== help) cell.title = help;
|
||||
});
|
||||
}
|
||||
// with nothing written, no poll answers and "ago" would stand still: the
|
||||
// page's second paints the rows in flight again
|
||||
function livePaint() {
|
||||
for (const x of reqRows.values()) if (x.r && !x.r.done && x.r.bytes) paintLive(x.b, x.r);
|
||||
}
|
||||
// A day of history is up to 2,000 requests, and a row is ~20 elements:
|
||||
// all of them in the list, a day picked took the page 0.4–0.7s here and
|
||||
// seconds on Windows, and the old rows stayed in while the new ones went
|
||||
@@ -4195,7 +4262,10 @@ function routingPage(part) {
|
||||
const info = el("span", "meta");
|
||||
if (meta.length) info.append(el("span", "retry-count", meta.join(" · ")));
|
||||
info.append(...metrics.map((m) => metricElement(m, true)));
|
||||
info.hidden = !metrics.length && !meta.length;
|
||||
// a request in flight: its progress where an ended row's metrics go
|
||||
const live = liveCells(r);
|
||||
for (const cell of live) info.append(metricElement(cell, true));
|
||||
info.hidden = !metrics.length && !meta.length && !live.length;
|
||||
b.append(when, asked, to, info);
|
||||
|
||||
b.title = title;
|
||||
@@ -5084,7 +5154,7 @@ function routingPage(part) {
|
||||
let second = 0;
|
||||
function countdown() {
|
||||
if (!shown()) { clearInterval(second); second = 0; return; }
|
||||
second ||= setInterval(() => { if (!shown()) return countdown(); if (!pinned && loaded && cur) sync(); render(); renderActs(listed()); groupsReadAgain(); }, 1000);
|
||||
second ||= setInterval(() => { if (!shown()) return countdown(); if (!pinned && loaded && cur) sync(); render(); renderActs(listed()); groupsReadAgain(); livePaint(); }, 1000);
|
||||
}
|
||||
countdown();
|
||||
|
||||
|
||||
@@ -142,6 +142,8 @@
|
||||
@keyframes rtlive { 0% { box-shadow: 0 0 0 0 color-mix(in srgb, var(--fg) 40%, transparent); } 70%, 100% { box-shadow: 0 0 0 6px transparent; } }
|
||||
.rt-accts li.low em { color: var(--fg-2); }
|
||||
.rt-accts li.rest { border-style: dashed; }
|
||||
/* a reply still out with no content for 15s: the dot stops pulsing */
|
||||
.rt-accts li.quiet .dot { background: var(--amber); border-color: var(--amber); animation: none; }
|
||||
.rt-accts li.rest > :not(.tag) { opacity: .5; }
|
||||
.rt-accts li.rest em { color: var(--red); opacity: .85; }
|
||||
.rt-accts li.left { border-style: dotted; }
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A reply in flight shows, live, how much of it has arrived and roughly
|
||||
// its tokens (#4951, Canda15): the request's row has the bytes, "≈ n
|
||||
// tokens" once a rate is learned, and how long ago content last came,
|
||||
// changed in place as the trace says more (the row isn't built again), and
|
||||
// the account answering it says the same. Quiet for 15s, the account's dot
|
||||
// stops pulsing and "answering…" goes. Once the request is done none of it
|
||||
// stays. English, Chinese (simplified and traditional), Japanese and
|
||||
// German, at 1100px and 420px; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const M = "glm-5";
|
||||
const order = [{ id: "solo#s1", provider: "solo", name: "Solo", who: "solo-1", kind: "key", model: M }];
|
||||
const ago = (s) => new Date(Date.now() - s * 1e3).toISOString();
|
||||
// the request: in flight with the live numbers given, or done
|
||||
const route = (live, done = false) => ({
|
||||
id: 2, seq: 2, time: ago(30), agent: "zcode", model: M, provider: "solo", done, ...(done ? { status: 200, ms: 30000, out: 900 } : {}),
|
||||
order, tries: [{ id: "solo#s1", model: M, start: ago(30), done, ...(done ? { status: 200, ms: 30000 } : {}) }],
|
||||
...live,
|
||||
});
|
||||
|
||||
function serve(lang, live) {
|
||||
return async (request) => {
|
||||
const url = new URL(request.request().url());
|
||||
const json = (data) => request.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return request.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return request.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [{ id: "zcode", name: "ZCode", path: "/test/config.json", fields: [] }], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/gateway/trace") {
|
||||
if (url.searchParams.get("wait")) {
|
||||
if (live.queued.length) return json(live.queued.shift());
|
||||
live.pending.push(request);
|
||||
return;
|
||||
}
|
||||
return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 1, rerouted: 0, errors: 0 }, routes: [route({ bytes: 2048, contentAt: Date.now() - 1000 })] });
|
||||
}
|
||||
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], pools: [] });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await request.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const width of [1100, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: a reply in flight shows what has arrived, and nothing once it is done`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await browser.newPage({ viewport: { width, height: 900 } });
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (error) => errors.push(error.message));
|
||||
const live = { pending: [], queued: [], seq: 1 };
|
||||
await page.route("**/*", serve(lang, live));
|
||||
const send = (...routes) => {
|
||||
const d = { mine: true, now: new Date().toISOString(), seq: ++live.seq, totals: { requests: live.seq }, routes };
|
||||
const r = live.pending.shift();
|
||||
if (r) r.fulfill({ json: d }); else live.queued.push(d);
|
||||
};
|
||||
const say = (key, vars = {}) => page.evaluate(([lang, key, vars]) => {
|
||||
const s = (lang !== "en" && I18N[lang]?.[key]) || key;
|
||||
return s.replace(/\{(\w+)\}/g, (_, k) => vars[k] ?? `{${k}}`);
|
||||
}, [lang, key, vars]);
|
||||
const cells = () => page.evaluate(() => [...document.querySelectorAll(".rt-req .rt-metric.recv")].map((c) => c.textContent.trim()));
|
||||
const account = page.locator(".rt-accts li", { has: page.locator(".who", { hasText: /^solo-1$/ }) });
|
||||
|
||||
await page.goto("http://magpie.test/?view=routing");
|
||||
await page.locator(".rt-req .rt-metric.recv").first().waitFor();
|
||||
|
||||
// 2 KiB in, content a second ago, no rate learned: no tokens said
|
||||
let got = await cells();
|
||||
assert.equal(got.length, 2, JSON.stringify(got));
|
||||
assert.equal(got[0], "2.0 KiB");
|
||||
assert.ok(got[1].includes(await say("{n} s", { n: 1 })) || got[1].includes(await say("{n} s", { n: 2 })), got[1]);
|
||||
const answering = await say("answering…");
|
||||
await page.waitForFunction(() => /KiB/.test(document.querySelector(".rt-accts li.now em")?.textContent || ""));
|
||||
let em = (await account.locator("em").textContent()).trim();
|
||||
assert.ok(em.startsWith(answering) && em.includes("2.0 KiB"), em);
|
||||
|
||||
// more arrives, a rate is learned: the same cells change in place
|
||||
await page.evaluate(() => { window.firstCell = document.querySelector(".rt-req .rt-metric.recv"); window.firstRow = document.querySelector(".rt-req"); });
|
||||
send(route({ bytes: 3 * 1048576, estTok: 1234, contentAt: Date.now() }));
|
||||
await page.waitForFunction(() => document.querySelectorAll(".rt-req .rt-metric.recv").length === 3);
|
||||
got = await cells();
|
||||
assert.equal(got[0], "3.0 MiB");
|
||||
assert.equal(got[1], await say("≈ {n} tokens", { n: "1.2k" }));
|
||||
assert.ok(await page.evaluate(() => document.querySelector(".rt-req") === window.firstRow), "the row was built again");
|
||||
send(route({ bytes: 3 * 1048576 + 600000, estTok: 1500, contentAt: Date.now() }));
|
||||
await page.waitForFunction(() => document.querySelector(".rt-req .rt-metric.recv .v")?.textContent === "3.6 MiB");
|
||||
assert.ok(await page.evaluate(() => document.querySelector(".rt-req .rt-metric.recv") === window.firstCell || document.querySelector(".rt-req") === window.firstRow));
|
||||
// each cell says what it is when hovered
|
||||
assert.equal(await page.locator(".rt-req .rt-metric.recv").first().getAttribute("title"), await say("How much of this reply has reached the client, framing included"));
|
||||
// the page body never scrolls sideways
|
||||
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1));
|
||||
|
||||
// quiet for 20s: the dot stops, and the account says the numbers only
|
||||
send(route({ bytes: 3 * 1048576 + 600000, estTok: 1500, contentAt: Date.now() - 20000 }));
|
||||
await account.and(page.locator("li.quiet")).waitFor();
|
||||
assert.equal(await account.locator(".dot").evaluate((d) => getComputedStyle(d).animationName), "none");
|
||||
em = (await account.locator("em").textContent()).trim();
|
||||
assert.ok(!em.includes(answering) && em.includes("3.6 MiB"), em);
|
||||
assert.ok((await cells())[2].includes(await say("{n} s", { n: 20 })) || (await cells())[2].includes(await say("{n} s", { n: 21 })), (await cells())[2]);
|
||||
// the page's second moves "ago" on without a trace answer
|
||||
const before = (await cells())[2];
|
||||
await page.waitForFunction((b) => document.querySelectorAll(".rt-req .rt-metric.recv")[2]?.textContent.trim() !== b, before, { timeout: 4000 });
|
||||
|
||||
// done: no live cells, nothing quiet, the account answered it
|
||||
send(route({ bytes: 3 * 1048576 + 700000 }, true));
|
||||
await page.waitForFunction(() => !document.querySelector(".rt-metric.recv"));
|
||||
assert.equal(await page.locator(".rt-accts li.quiet").count(), 0);
|
||||
em = (await account.locator("em").textContent()).trim();
|
||||
assert.ok(!/MiB/.test(em), em);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user