diff --git a/docs/reference.md b/docs/reference.md index c9a1c1f23..997c4ca62 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -477,12 +477,16 @@ words (`stop`, `tool_calls`, `end_turn`, a Responses reply's page shows it as Upstream stop reason. **Output speed** (tok/s on the Usage and Routing pages, `magpie usage`) is -output tokens over the time after the first token, summed per request: the +all output tokens the vendor counted, reasoning and tool calls included, over +the time from the first output to the last, summed per request: the tokens of every timed request over the sum of their windows, so concurrent -subagents never add up. A reply that reasoned counts only its answer, from its -first text (`usage.DecodeOf`): hidden reasoning is written before the stream -shows anything, so counting it in a window that starts after it read -gpt-6.1-sol at hundreds of tok/s. A reply that reasoned and then wrote only +subagents never add up. The first output is the earlier of the first content +and the first sign the stream gave of reasoning (a reasoning item's or a +thinking block's start, or reasoning deltas over 100 ms or more; a summary is +no sign). A reply that reasoned with no sign of when counts only its answer, +from its first text (`usage.DecodeOf`): its reasoning was written before the +stream showed anything, so counting it in a window that starts after it read +gpt-6.1-sol at hundreds of tok/s. Such a reply that then wrote only tool calls, one not streamed, and a burst (under 100 ms, or over 10,000 tok/s) tell no speed. So does a reply its vendor held back and let go in a burst at its end, however long the burst took to come: one whose content came in under diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md index b84c056c4..0b1441070 100644 --- a/docs/subsystems/gui-shell.md +++ b/docs/subsystems/gui-shell.md @@ -119,20 +119,23 @@ Usage rows and aggregates use `Record.Decode` and `DecodeOf` in `decodeOf` in [`plugins/routing/client.js`](../../internal/gui/assets/plugins/routing/client.js); Usage rows use `ledDecode` in [`plugins/usage/page.js`](../../internal/gui/assets/plugins/usage/page.js). -When an answer follows reasoning, only answer tokens are timed from the -first answer text. Without answer text, all output tokens are timed only -when the gateway records paced visible reasoning and a usable content flow. -`firstToken.reasoningMs` in -[`ttft.go`](../../internal/gateway/ttft.go) requires reasoning at the first -content and subsequent reasoning deltas at least 100 ms later. It excludes -native Responses and Gemini, whose summaries do not measure their reported -reasoning tokens, and redacted thinking, including translated sealed blocks. -The upstream protocol is retained when the client receives a translation. +A reply's speed counts all its output tokens as the vendor's usage counts +them, reasoning and tool-call arguments included (Archivemylife on X), from +its first output of any kind to its end: the earlier of its first content +(`TTFT`) and its first sign of reasoning (`FirstReasoning`). That sign is +`firstToken.reasoningMs` in [`ttft.go`](../../internal/gateway/ttft.go), in +every protocol: a Responses reasoning item's start, an Anthropic thinking +or redacted-thinking block's start, sealed thinking, or reasoning deltas +spread over 100 ms or more (deltas that came at once are a buffered burst +and tell none). A summary is no sign (`summaryPart`: a Responses reasoning +summary's words, a Gemini thought, or one translated from another protocol, +`summarized`), as it is written after some of the reasoning it sums up +(#1463). A reply that reasoned with no sign of when counts only its answer, +its output less the reasoning, from its first text, and none with no text. +The burst and held-content checks judge the answer's part: from its first +text when it reasoned, else from its first token. These are receive-side timing checks, not access to the vendor's generation clock: a relay that releases a buffered reply evenly can still look paced. -Without an upstream guarantee, this is an observed output-rate estimate. -Summaries stay excluded rather than extending their visible portion's time -to an unobserved reasoning-token count. `Record.FirstReasoning` (`first_reasoning_ms`) and the corresponding `Call`, `Route` and `Try` field (`firstReasoning`) record this evidence with diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 5562c37a9..04347cdae 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1168,6 +1168,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st return max(ms-before, 1) } try.TTFT, try.FirstText = fromTry(ttft), fromTry(text) + try.FirstReasoning = fromTry(first.reasoningMs()) try.Net = nt.timing(try.Start, 0) t.ReasoningHidden = first.hidesReasoning(provider.Responses, uu.Reasoning) try.ReasoningHidden = t.ReasoningHidden @@ -1178,6 +1179,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st t.TitleLink = &link } t.Output, t.Reasoning, t.TTFT, t.FirstText = out, uu.Reasoning, ttft, text + t.FirstReasoning = first.reasoningMs() flow := first.flowFor(uu.Reasoning) t.Flow, try.Flow = flow, flow t.Usage = routeUsage("openai", model, uu) @@ -1634,6 +1636,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st call.Fallback = strings.TrimSuffix(call.Fallback, "; ") } call.TTFT, call.FirstText = first.ms() + call.FirstReasoning = first.reasoningMs() uu.add(sniff.usage()) call.ReasoningHidden = first.hidesReasoning(provider.Responses, uu.Reasoning) uu.Tier = servedTierAt(provider.HostOf(base), uu.Tier) @@ -1686,7 +1689,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st Input: uu.Input, Output: uu.Output, CacheRead: uu.CacheRead, CacheWrite: uu.CacheWrite, Reasoning: uu.Reasoning, Effort: effort, Millis: call.Millis, Masking: maskingMs(r.Context(), 0), // Codex's own sign-in: the request goes as Codex sent it - TierAsked: bodyTier(provider.Responses, body), TierSent: bodyTier(provider.Responses, body), TierServed: uu.Tier, TTFT: call.TTFT, FirstText: call.FirstText, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Status: call.Status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, + TierAsked: bodyTier(provider.Responses, body), TierSent: bodyTier(provider.Responses, body), TierServed: uu.Tier, TTFT: call.TTFT, FirstText: call.FirstText, FirstReasoning: call.FirstReasoning, ReasoningHidden: call.ReasoningHidden, Flow: call.Flow, Status: call.Status, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind, RequestID: requestID(res.Header), ResponseID: uu.ResponseID, Endpoint: r.URL.Path} failedWith(&rec, call.Status, call.Error, errType) if up := upBytesOf(r.Context()); up != nil { diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index a9d55e113..90f93a46e 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -518,6 +518,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov if h, ok := w.(*holdWriter); ok { h.mu.Lock() h.first.hidden = true + h.first.summarized = h.first.summarized || ev.Kind == KThink h.mu.Unlock() } case KError: diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 71a2eea06..a6a9a6136 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -499,7 +499,7 @@ type Call struct { // it was streamed (#196) TTFT int64 `json:"ttft,omitempty"` FirstText int64 `json:"firstText,omitempty"` - // FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning. + // FirstReasoning: ms to the reply's first sign of reasoning, streamed or sealed (a reasoning delta, a reasoning item's or thinking block's start); 0 for none. FirstReasoning int64 `json:"firstReasoning,omitempty"` ReasoningHidden bool `json:"reasoningHidden,omitempty"` // Flow: the ms its content took to come, from where its speed is @@ -4661,7 +4661,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro try.Entry, try.EntryWhy = entryOf() try.Swapped, try.Routed = swapped(asName, call.Usage.Served) && !usage.ListedAs(c.p.ID, c.model, call.Usage.Served), usage.GroupRouted(asName, call.Usage.Served) try.TTFT, try.FirstText = hw.first.ms() - try.FirstReasoning = hw.first.reasoningMs(call.To) + try.FirstReasoning = hw.first.reasoningMs() try.ReasoningHidden = hw.first.hidesReasoning(call.To, call.Usage.billed().Reasoning) call.ReasoningHidden = try.ReasoningHidden try.Flow = hw.first.flowFor(call.Usage.Reasoning) @@ -4671,7 +4671,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro call.TTFT, call.FirstText = sinceStart(began.Sub(start), hw.first.first), sinceStart(began.Sub(start), hw.first.text) call.FirstReasoning = 0 if try.FirstReasoning > 0 { - call.FirstReasoning = sinceStart(began.Sub(start), hw.first.reasoning) + call.FirstReasoning = sinceStart(began.Sub(start), hw.first.think) } // A try that fails from here and hands the request on, to another // account or member or the same one again, is in the ledger with diff --git a/internal/gateway/reasoning_speed_test.go b/internal/gateway/reasoning_speed_test.go index b1c32c3cf..61e94959a 100644 --- a/internal/gateway/reasoning_speed_test.go +++ b/internal/gateway/reasoning_speed_test.go @@ -13,37 +13,47 @@ import ( "github.com/yetone/magpie/internal/usage" ) +// A reply's first sign of reasoning is seen in every protocol, as the +// speed counts all its output from its first output of any kind +// (usage.DecodeOf, Archivemylife on X): reasoning deltas paced over 100 ms +// or more, a reasoning item's start, a thinking block's start, sealed +// thinking. Deltas that came at once, a buffered burst, tell none, nor does +// a summary (a Responses summary, a Gemini thought), written after some of +// the reasoning it sums up (#1463). func TestReasoningSpeedEvidence(t *testing.T) { thought := `data: {"choices":[{"delta":{"reasoning_content":"a thought"}}]}` + "\n\n" for _, c := range []struct { name string - proto provider.Protocol - event string - hidden bool + events []string + paced bool want bool }{ - {"chat", provider.Chat, thought, false, true}, - {"anthropic", provider.Anthropic, `data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"a thought"}}` + "\n\n", false, true}, - {"late Responses summary", provider.Responses, `data: {"type":"response.reasoning_summary_text.delta","delta":"a thought"}` + "\n\n", false, false}, - {"translated hidden Responses", provider.Responses, thought, false, false}, - {"translated redacted thinking", provider.Anthropic, thought, true, false}, - {"Gemini summary", provider.Gemini, thought, false, false}, + {"chat", []string{thought}, true, true}, + {"anthropic", []string{`data: {"type":"content_block_delta","delta":{"type":"thinking_delta","thinking":"a thought"}}` + "\n\n"}, true, true}, + {"Responses summary", []string{`data: {"type":"response.reasoning_summary_text.delta","delta":"a thought"}` + "\n\n"}, true, false}, + {"Gemini thought", []string{`data: {"candidates":[{"content":{"parts":[{"text":"a thought","thought":true}]}}]}` + "\n\n"}, true, false}, + {"Responses reasoning item", []string{`data: {"type":"response.output_item.added","item":{"type":"reasoning","summary":[]}}` + "\n\n"}, false, true}, + {"Anthropic thinking block", []string{`data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}` + "\n\n"}, false, true}, + {"Anthropic redacted block", []string{`data: {"type":"content_block_start","index":0,"content_block":{"type":"redacted_thinking","data":"sealed-test"}}` + "\n\n"}, false, true}, + {"chat burst", []string{thought + thought}, false, false}, + {"no reasoning", []string{`data: {"choices":[{"delta":{"content":"hi"}}]}` + "\n\n"}, true, false}, } { t.Run(c.name, func(t *testing.T) { - f := firstToken{start: time.Now().Add(-time.Second), hidden: c.hidden} - f.see([]byte(c.event)) - f.start = f.start.Add(-time.Second) - f.see([]byte(c.event)) - if got := f.reasoningMs(c.proto) > 0; got != c.want { + f := firstToken{start: time.Now().Add(-time.Second)} + for _, ev := range c.events { + f.see([]byte(ev)) + } + if c.paced { + f.start = f.start.Add(-time.Second) + for _, ev := range c.events { + f.see([]byte(ev)) + } + } + if got := f.reasoningMs() > 0; got != c.want { t.Fatalf("reasoning evidence=%v; want %v", got, c.want) } }) } - f := firstToken{start: time.Now().Add(-time.Second)} - f.see([]byte(thought + thought)) - if f.reasoningMs(provider.Chat) != 0 { - t.Fatal("a buffered burst acquired reasoning timing") - } } func TestReasoningSpeedThroughGateway(t *testing.T) { @@ -167,14 +177,19 @@ func TestHiddenReasoningThroughTranslation(t *testing.T) { u := lastUsage(t) r := lastRoute(s) n, w := u.Decode() + // a summary tells no start of the reasoning it sums up, and no + // text came to time the answer from if rec.Code != 200 || u.FirstReasoning != 0 || r.FirstReasoning != 0 || n != 0 || w != 0 || u.Reasoning != 1400 { - t.Fatalf("hidden reasoning acquired speed after translation: %d %+v %s", rec.Code, u, rec.Body) + t.Fatalf("hidden reasoning acquired speed from its summary: %d %d/%d %+v %s", rec.Code, n, w, u, rec.Body) } }) } } -// A visible portion never licenses timing a sealed portion of the same turn. +// A turn of streamed and sealed thinking and a tool call counts all of its +// output, the sealed thinking's too, from its first thinking block's start +// (Archivemylife on X): the vendor's count holds it all, and the stream +// showed when it began. func TestMixedRedactedReasoning(t *testing.T) { events := []string{ `data: {"type":"message_start","message":{"id":"m","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":5,"output_tokens":0}}}`, @@ -207,8 +222,8 @@ func TestMixedRedactedReasoning(t *testing.T) { s.Handler().ServeHTTP(w, httptest.NewRequest("POST", path, strings.NewReader(body))) row := lastUsage(t) n, ms := row.Decode() - if w.Code != 200 || row.FirstReasoning != 0 || !row.ReasoningHidden || n != 0 || ms != 0 { - t.Fatalf("mixed sealed reasoning timed: %d %+v", w.Code, row) + if w.Code != 200 || row.FirstReasoning <= 0 || !row.ReasoningHidden || n != 120 || ms < usage.MinDecodeMs { + t.Fatalf("mixed sealed reasoning: %d %d/%d %+v", w.Code, n, ms, row) } }) } @@ -229,7 +244,7 @@ func TestReasoningPacingEdges(t *testing.T) { f.see(thought) f.start = time.Now().Add(-f.reasoning - c.gap) f.see(thought) - if got := f.reasoningMs(provider.Chat) > 0; got != c.want { + if got := f.reasoningMs() > 0; got != c.want { t.Fatalf("paced=%v; want %v", got, c.want) } }) @@ -240,14 +255,15 @@ func TestReasoningPacingEdges(t *testing.T) { f.see(thought) f.start = f.start.Add(-time.Second) f.see(thought) - if f.reasoningMs(provider.Chat) != 0 { - t.Fatal("a tool-first turn acquired reasoning timing") + // reasoning after a tool call: the window still starts at the tool's + if got := f.reasoningMs(); got > 0 && got < f.first.Milliseconds() { + t.Fatalf("a tool-first turn's window starts at its later reasoning: %d < %d", got, f.first.Milliseconds()) } // Two writes after a long quiet start still form a burst below the decode minimum. f = firstToken{start: time.Now().Add(-14 * time.Second)} f.see(thought) f.see(thought) - if f.reasoningMs(provider.Chat) != 0 { + if f.reasoningMs() != 0 { t.Fatal("buffered reasoning acquired timing") } } @@ -262,7 +278,7 @@ func TestSlowReleasedReasoningIsUntimed(t *testing.T) { f.see(thought) } end := first.Milliseconds() + 10250 - n, w := usage.DecodeOf(500, 450, end, first.Milliseconds(), 0, f.flowFor(450), f.reasoningMs(provider.Chat)) + n, w := usage.DecodeOf(500, 450, end, first.Milliseconds(), 0, f.flowFor(450), f.reasoningMs()) if n != 0 || w != 0 { t.Fatalf("held reasoning inflated speed: %d/%d flow=%d", n, w, f.flowFor(450)) } @@ -279,7 +295,7 @@ func TestEncryptedReasoningWithoutTokenDetails(t *testing.T) { func TestGeminiSummaryWithoutThoughtCount(t *testing.T) { f := firstToken{start: time.Now().Add(-time.Second)} f.see([]byte(`data: {"candidates":[{"content":{"parts":[{"text":"visible summary","thought":true}]}}]}` + "\n\n")) - if !f.hidesReasoning(provider.Gemini, 0) || !f.hidesReasoning(provider.Gemini, 7) || f.reasoningMs(provider.Gemini) != 0 { + if !f.hidesReasoning(provider.Gemini, 0) || !f.hidesReasoning(provider.Gemini, 7) || f.reasoningMs() != 0 { t.Fatal("Gemini summary timed without its hidden thought count") } } @@ -297,10 +313,12 @@ func TestCodexBackendHiddenReasoningWithoutCount(t *testing.T) { if code, body := codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"hi"}`); code != 200 { t.Fatalf("%d %s", code, body) } + // its reasoning has no count of its own, but its output holds it, and + // the stream showed when it began: all 120 are timed from there r := lastUsage(t) n, ms := r.Decode() - if !r.ReasoningHidden || n != 0 || ms != 0 { - t.Fatalf("Codex hidden reasoning timed with no count: %+v", r) + if !r.ReasoningHidden || r.FirstReasoning <= 0 || n != 120 || ms < usage.MinDecodeMs { + t.Fatalf("Codex sealed reasoning with no count: %d/%d %+v", n, ms, r) } } @@ -340,8 +358,9 @@ func TestMultipleVisibleReasoningBlocks(t *testing.T) { f.start = time.Now().Add(-time.Second - time.Duration(i)*150*time.Millisecond) f.see([]byte(ev + "\n\n")) } - if first := f.reasoningMs(provider.Anthropic); first <= 0 || first != f.first.Milliseconds() { - t.Fatal("multiple visible blocks lost their first reasoning time") + // from the first block's start, when the model began to think + if first := f.reasoningMs(); first < 1000 || first >= 1150 || first > f.first.Milliseconds() { + t.Fatalf("multiple visible blocks lost their first reasoning time: %d (first content %d)", first, f.first.Milliseconds()) } } @@ -380,7 +399,7 @@ func TestLiveVisibleReasoningFixture(t *testing.T) { slack = time.Since(set).Milliseconds() + 1 } } - if got, at := f.reasoningMs(provider.Chat), sample.Events[0].At; got < at || got > at+slack { + if got, at := f.reasoningMs(), sample.Events[0].At; got < at || got > at+slack { t.Fatalf("live reasoning fixture lost its start: %d/%d (+%d ms passing)", got, at, slack) } // its 731 ms came after a 6.8 s wait, which tells no speed: under a @@ -399,10 +418,11 @@ func TestLiveVisibleReasoningFixture(t *testing.T) { } // A Codex turn that wrote a preamble, reasoned, then called a tool -// (Archivemylife on X, gpt-6.1-sol at service_tier priority): counted from -// the preamble, its window held the reasoning and its content read as one -// burst at the end, so it told no speed. Its answer is counted from what -// came after its last reasoning, the shell call's first bytes. +// (Archivemylife on X, gpt-6.1-sol at service_tier priority): its speed is +// all its output, the reasoning and the call's arguments too, over the time +// from its first output to its end, as the vendor's usage counts it. Counted +// as its answer alone after its last reasoning, it read 630 tokens in about +// 1.6 s, near 390 tok/s, though the turn wrote 1,239 tokens over 18 s. func TestCodexPreambleThenReasoningTellsSpeed(t *testing.T) { var sample struct { Record struct { @@ -423,10 +443,10 @@ func TestCodexPreambleThenReasoningTellsSpeed(t *testing.T) { t.Fatal(err) } f := firstToken{} - var called int64 // the shell call's start, as it came + var reasoned int64 // the reasoning item's start, as it came for _, e := range sample.Events { - if called == 0 && strings.Contains(string(e.Data), `"type":"function_call"`) { - called = e.At + if reasoned == 0 && strings.Contains(string(e.Data), `"type":"reasoning"`) { + reasoned = e.At } f.start = time.Now().Add(-time.Duration(e.At) * time.Millisecond) f.see([]byte("data: " + string(e.Data) + "\n\n")) @@ -436,16 +456,20 @@ func TestCodexPreambleThenReasoningTellsSpeed(t *testing.T) { if !f.hidesReasoning(provider.Responses, rec.Reasoning) { t.Fatal("the reasoning after the preamble was not seen") } - if text < called || text > called+50 { - t.Fatalf("answer counted from %d ms; want the shell call's start, %d", text, called) + think := f.reasoningMs() + if think < reasoned || think > reasoned+50 { + t.Fatalf("reasoning seen from %d ms; want the reasoning item's start, %d", think, reasoned) } - n, w := usage.DecodeOf(rec.Out, rec.Reasoning, rec.Ms, ttft, text, f.flowFor(rec.Reasoning)) - if n != rec.Out-rec.Reasoning || w <= 0 { - t.Fatalf("no speed: %d/%d (ttft %d, text %d, flow %d)", n, w, ttft, text, f.flowFor(rec.Reasoning)) + n, w := usage.DecodeOf(rec.Out, rec.Reasoning, rec.Ms, ttft, text, f.flowFor(rec.Reasoning), think) + if n != rec.Out || w < rec.Ms-ttft-50 || w > rec.Ms-ttft { + t.Fatalf("speed counted %d/%d; want all %d tokens from the first output, %d ms (ttft %d, text %d, flow %d)", n, w, rec.Out, rec.Ms-ttft, ttft, text, f.flowFor(rec.Reasoning)) } - // 630 tokens in about 1.6 s: priority's pace, not the 30 tok/s the - // whole turn after the preamble would read - if s := float64(n) / (float64(w) / 1000); s < 200 || s > 600 { + // 1,239 tokens over about 18.4 s + if s := float64(n) / (float64(w) / 1000); s < 55 || s > 80 { t.Fatalf("speed %.0f tok/s", s) } + row := usage.Record{Output: rec.Out, Reasoning: rec.Reasoning, Millis: rec.Ms, TTFT: ttft, FirstText: text, Flow: f.flowFor(rec.Reasoning), FirstReasoning: think, ReasoningHidden: true, Status: 200} + if rn, rw := row.Decode(); rn != n || rw != w { + t.Fatalf("the row counts %d/%d, the stream %d/%d", rn, rw, n, w) + } } diff --git a/internal/gateway/reasoning_uncounted_test.go b/internal/gateway/reasoning_uncounted_test.go index f407de7db..de81dfb8c 100644 --- a/internal/gateway/reasoning_uncounted_test.go +++ b/internal/gateway/reasoning_uncounted_test.go @@ -53,10 +53,11 @@ func TestStreamedReasoningWithoutCount(t *testing.T) { {"chat from anthropic", provider.Anthropic, real, "/v1/chat/completions", chatBody, 35, 0, true, true}, {"responses from anthropic", provider.Anthropic, real, "/v1/responses", `{"model":"fake/m1","stream":true,"input":"hi"}`, 35, 0, true, true}, // a Chat vendor's reasoning_content with no completion_tokens_details, - // a tool call its only answer: no text to time it from, and no count - // to take the reasoning out of its output, so no speed - {"chat tool, uncounted", provider.Chat, chatTool(""), "/v1/chat/completions", chatBody, 40, 0, true, false}, - {"anthropic from chat tool, uncounted", provider.Chat, chatTool(""), "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":400,"messages":[{"role":"user","content":"hi"}]}`, 40, 0, true, false}, + // a tool call its only answer: its output holds the reasoning, and + // the speed is all of it from the first reasoning (Archivemylife on + // X), so no count is needed to tell it + {"chat tool, uncounted", provider.Chat, chatTool(""), "/v1/chat/completions", chatBody, 40, 0, true, true}, + {"anthropic from chat tool, uncounted", provider.Chat, chatTool(""), "/v1/messages", `{"model":"fake/m1","stream":true,"max_tokens":400,"messages":[{"role":"user","content":"hi"}]}`, 40, 0, true, true}, // the same counted is known, and timed from its paced reasoning {"chat tool, counted", provider.Chat, chatTool(`,"completion_tokens_details":{"reasoning_tokens":30}`), "/v1/chat/completions", chatBody, 40, 30, false, true}, } { diff --git a/internal/gateway/speed.go b/internal/gateway/speed.go index c1f1b1fae..c03d0fd19 100644 --- a/internal/gateway/speed.go +++ b/internal/gateway/speed.go @@ -84,7 +84,7 @@ func noteSpeed(c candidate, ttft int64, tokens int, w int64, now time.Time) { // usage.DecodeOf counts it for the Requests and Usage pages. func noteTrySpeed(c candidate, t Try, out, reasoning int, now time.Time) { tokens, w := 0, int64(0) - if !t.ReasoningHidden || t.FirstText > 0 { + if !t.ReasoningHidden || t.FirstText > 0 || t.FirstReasoning > 0 { tokens, w = usage.DecodeOf(out, reasoning, t.Millis, t.TTFT, t.FirstText, t.Flow, t.FirstReasoning) } noteSpeed(c, t.TTFT, tokens, w, now) diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index d0d9a034d..90d02afef 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -147,7 +147,7 @@ type Route struct { // counts: streamed replies only (#196) TTFT int64 `json:"ttft,omitempty"` FirstText int64 `json:"firstText,omitempty"` - // FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning. + // FirstReasoning: ms to the reply's first sign of reasoning, streamed or sealed (a reasoning delta, a reasoning item's or thinking block's start); 0 for none. FirstReasoning int64 `json:"firstReasoning,omitempty"` ReasoningHidden bool `json:"reasoningHidden,omitempty"` // Flow: the ms its content took to come (Call.Flow) @@ -517,7 +517,7 @@ type Try struct { // (claude_entry.go). "" for a try that ran no Claude Code. Entry string `json:"entry,omitempty"` EntryWhy string `json:"entryWhy,omitempty"` - // FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning. + // FirstReasoning: ms to the reply's first sign of reasoning, streamed or sealed (a reasoning delta, a reasoning item's or thinking block's start); 0 for none. FirstReasoning int64 `json:"firstReasoning,omitempty"` ReasoningHidden bool `json:"reasoningHidden,omitempty"` // Flow: the ms its content took to come (Call.Flow) diff --git a/internal/gateway/ttft.go b/internal/gateway/ttft.go index 396eefec8..bc821a938 100644 --- a/internal/gateway/ttft.go +++ b/internal/gateway/ttft.go @@ -27,7 +27,28 @@ type firstToken struct { first time.Duration // to the first content; 0 until it comes text time.Duration // to the first text reasoning, lastReasoning time.Duration - hidden bool // redacted thinking cannot be timed by its visible portion + // think: the first sign of reasoning of any kind, seen or sealed — a + // reasoning delta, a Responses reasoning item's start, an Anthropic + // thinking block's start, a Gemini thought — before or after the first + // text. A reply's speed is all its output over the time from its first + // output of any kind, this or its first content, to its end + // (usage.DecodeOf, Archivemylife on X: reasoning and tool calls are + // tokens too); 0 when the reply showed no sign of when it reasoned + think time.Duration + // marked: think is a reasoning item's or thinking block's start, or + // sealed thinking, which come as the model begins to think; else it is + // a reasoning delta, which tells when only once the deltas span 100 ms + // (reasoningMs) + marked bool + // lastThink: the last sign of reasoning, which with think says whether + // the deltas were paced or one burst + lastThink time.Duration + hidden bool // redacted thinking cannot be timed by its visible portion + // summarized: the reasoning shown was a summary translated from another + // protocol (continuation's summaryUpstream), whose thinking block opens + // at the summary's first words, after the reasoning it sums up began, so + // it tells no start (#1463) + summarized bool // again: the reply reasoned again after its first text (a Codex // preamble, "I'll look at the tests", then its thinking, then a tool // call: Archivemylife on X), and nothing has come after that @@ -87,8 +108,11 @@ func (f *firstToken) see(b []byte) { if mayReason(ev) { _, _, reasoning, hidden := timingKind(ev) f.hidden = f.hidden || hidden - if reasoning || hidden || reasoningItem(ev) { + if reasoning || hidden || reasoningItem(ev) || thinkingBlock(ev) { f.again, f.lastReasoning = true, d + if !reasoning || hidden || !summaryPart(ev) { + f.thought(d, hidden || !reasoning) + } if flowContent(ev) { f.mark(d, len(ev)) } @@ -105,6 +129,11 @@ func (f *firstToken) see(b []byte) { } content, text, reasoning, hidden := timingKind(ev) f.hidden = f.hidden || hidden + if hidden || mayReason(ev) && (reasoningItem(ev) || thinkingBlock(ev)) { + f.thought(d, true) + } else if reasoning && !summaryPart(ev) { + f.thought(d, false) + } if reasoning { if f.reasoning == 0 { f.reasoning = d @@ -137,6 +166,14 @@ func mayReason(ev []byte) bool { return bodyHas(ev, "reasoning") || bodyHas(ev, "thinking") || bodyHas(ev, "encrypted_content") || bodyHas(ev, `"thought"`) } +// summaryPart: a Responses reasoning summary's words or a Gemini thought, +// a summary written after some of the reasoning it sums up, so its first +// words tell no start of it (hidesReasoning, #1463). A Responses reasoning +// item's start, before its summary, does. +func summaryPart(ev []byte) bool { + return bodyHas(ev, "reasoning_summary") || bodyHas(ev, `"candidates"`) && bodyHas(ev, `"thought"`) +} + // reasoningItem: a Responses reasoning item's start or end, which streams // nothing of the thinking it holds when its summary is off. func reasoningItem(ev []byte) bool { @@ -152,6 +189,30 @@ func reasoningItem(ev []byte) bool { return json.Unmarshal(data, &v) == nil && v.Item != nil && v.Item.Type == "reasoning" } +// thinkingBlock: an Anthropic thinking block's start, which comes as the +// model begins to think, whether its thinking then streams or is omitted. +func thinkingBlock(ev []byte) bool { + if !bodyHas(ev, "content_block_start") { + return false + } + _, data := eventParts(ev) + var v struct { + ContentBlock *struct { + Type string `json:"type"` + } `json:"content_block"` + } + return json.Unmarshal(data, &v) == nil && v.ContentBlock != nil && (v.ContentBlock.Type == "thinking" || v.ContentBlock.Type == "redacted_thinking") +} + +// thought notes a sign of reasoning at d, the first one kept; marked +// says it is a start or sealed thinking rather than a delta. +func (f *firstToken) thought(d time.Duration, marked bool) { + if f.think == 0 { + f.think, f.marked = d, marked + } + f.lastThink = d +} + // flowMost is the most marks kept: a reply that took longer than this many // distinct milliseconds to come has its flow untold (flowMs). const flowMost = 1 << 16 @@ -380,12 +441,14 @@ func (f *firstToken) hidesReasoning(proto provider.Protocol, counted int) bool { return f.hidden || f.reasoning > 0 && (counted <= 0 || proto == provider.Responses || proto == provider.Gemini || proto == provider.CodeAssist) } -// reasoningMs requires a paced visible channel. Responses and Gemini summaries -// do not measure their full reasoning count; translation keeps that restriction. -func (f *firstToken) reasoningMs(proto provider.Protocol) int64 { - if proto != provider.Chat && proto != provider.Anthropic || f.hidden || f.off || - f.reasoning == 0 || f.reasoning != f.first || f.lastReasoning-f.reasoning < 100*time.Millisecond { +// reasoningMs is when the reply first showed it was reasoning, as ms from +// start (think), in any protocol: 0 when it showed no sign of it, or its +// only signs were reasoning deltas that came at once, a buffered burst +// whose writing the stream didn't show, or a summary (summaryPart, or one +// translated from another protocol: summarized). +func (f *firstToken) reasoningMs() int64 { + if f.think == 0 || f.summarized || !f.marked && f.lastThink-f.think < 100*time.Millisecond { return 0 } - return f.reasoning.Milliseconds() + return f.think.Milliseconds() } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5193974b1..8d0648080 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4713,8 +4713,9 @@ const I18N = { "No streamed replies timed in this period": "这段时间没有可计时的流式回复", "No traffic counted in this period": "这段时间没有计入流量", "Traffic": "流量", - "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回复只算正文部分,从首个正文起计:推理在流里出现前就已写完", - "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "没有正文时,仅在可见推理持续流式输出时将其计入速度;隐藏推理不显示速度", + "All output tokens the vendor counted, reasoning and tool calls included, a second from the first output to the end, over the streamed replies": "流式回复中厂商计数的全部输出 token(含推理和工具调用),从首个输出到结束每秒的数量", + "A reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "有推理但流里看不出推理何时开始的回复,只算正文部分,从首个正文起计", + "Reasoning and tool calls count too, from the first output; a reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "推理和工具调用也计入,从首个输出起算;流里看不出推理何时开始的回复只算正文部分,从首个正文起计", "Cache": "缓存", "first token in {ms}": "{ms} 后出首字", "{n} tok/s": "{n} token/秒", @@ -10169,8 +10170,9 @@ const I18N = { "No streamed replies timed in this period": "這段時間沒有可計時的流式回覆", "No traffic counted in this period": "這段時間沒有計入流量", "Traffic": "流量", - "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "有推理的回覆只算正文部分,從首個正文起計:推理在流裡出現前就已寫完", - "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "沒有正文時,僅在可見推理持續串流輸出時將其計入速度;隱藏推理不顯示速度", + "All output tokens the vendor counted, reasoning and tool calls included, a second from the first output to the end, over the streamed replies": "串流回覆中廠商計數的全部輸出 token(含推理和工具呼叫),從首個輸出到結束每秒的數量", + "A reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "有推理但串流裡看不出推理何時開始的回覆,只算正文部分,從首個正文起計", + "Reasoning and tool calls count too, from the first output; a reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "推理和工具呼叫也計入,從首個輸出起算;串流裡看不出推理何時開始的回覆只算正文部分,從首個正文起計", "Cache": "快取", "first token in {ms}": "{ms} 後出首字", "{n} tok/s": "{n} token/秒", @@ -15637,8 +15639,9 @@ const I18N = { "No streamed replies timed in this period": "この期間に計測できたストリーミング応答はありません", "No traffic counted in this period": "この期間に数えた通信量はありません", "Traffic": "通信量", - "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "推論した応答は、最初の本文からの回答部分のみ数えます。推論はストリームに出る前に書き終わっています", - "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "本文がない場合、継続的にストリームされた可視の推論のみ速度に含めます。非表示の推論には速度を表示しません", + "All output tokens the vendor counted, reasoning and tool calls included, a second from the first output to the end, over the streamed replies": "ストリーミング応答で、ベンダーが数えた全出力トークン(推論とツール呼び出しを含む)を、最初の出力から終わりまでの毎秒で", + "A reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "推論したがストリームにその開始が見えない応答は、最初の本文からの回答部分のみ数えます", + "Reasoning and tool calls count too, from the first output; a reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "推論とツール呼び出しも最初の出力から数えます。ストリームに推論の開始が見えない応答は、最初の本文からの回答部分のみ数えます", "Cache": "キャッシュ", "first token in {ms}": "最初のトークンまで {ms}", "{n} tok/s": "{n} トークン/秒", @@ -21130,8 +21133,9 @@ const I18N = { "No streamed replies timed in this period": "In diesem Zeitraum wurde keine gestreamte Antwort gemessen", "No traffic counted in this period": "In diesem Zeitraum wurde kein Datenverkehr gezählt", "Traffic": "Datenverkehr", - "A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it": "Eine Antwort mit Reasoning zählt nur ihre Antwort ab dem ersten Text: Das Reasoning entstand, bevor der Stream es zeigte", - "No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed": "Ohne Antworttext zählt Reasoning nur bei sichtbar gestreamter Ausgabe; verborgenes Reasoning hat kein Tempo", + "All output tokens the vendor counted, reasoning and tool calls included, a second from the first output to the end, over the streamed replies": "Alle vom Anbieter gezählten Ausgabe-Token, Reasoning und Tool-Aufrufe eingeschlossen, pro Sekunde von der ersten Ausgabe bis zum Ende, über die gestreamten Antworten", + "A reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "Eine Antwort mit Reasoning, deren Stream nicht zeigt, wann es begann, zählt nur ihre Antwort ab dem ersten Text", + "Reasoning and tool calls count too, from the first output; a reply that reasoned with no sign in its stream of when counts only its answer, from its first text": "Reasoning und Tool-Aufrufe zählen mit, ab der ersten Ausgabe; eine Antwort mit Reasoning, deren Stream nicht zeigt, wann es begann, zählt nur ihre Antwort ab dem ersten Text", "Cache": "Cache", "first token in {ms}": "erstes Token nach {ms}", "{n} tok/s": "{n} Token/s", diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 9047e4767..f342bf3d5 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -601,27 +601,36 @@ function routingPage(part) { // 100 ms or would have it write over 10,000 tok/s, as it came in one // burst at its end (usage.DecodeWindow, #731: a whole Gemini tool call, // 8264 tokens 1 ms before the end, read 8,264,000 tok/s) - // A reply that reasoned counts its answer, its output less the - // reasoning, from its first text (usage.DecodeOf, tony on Discord): - // the reasoning was written before the stream showed any, OpenAI's - // encrypted and its summary sent when done, and counting it read - // gpt-6.1-sol at 163 tok/s. The reply's reasoning is its served try's. + // A reply counts all its output, reasoning and tool calls included, + // from its first output of any kind, its first content or its first + // sign of reasoning (usage.DecodeOf, Archivemylife on X: reasoning and + // tools are tokens too). One that reasoned with no sign of when in its + // stream counts its answer, its output less the reasoning, from its + // first text (tony on Discord), and none with no text. The reply's + // reasoning is its served try's. // A reply held back and let go in a burst at its end tells no speed // (usage.DecodeOf, John on Discord: Kimi Code at 2,237 tok/s): its - // content came in under a quarter of its window (flow), or its answer - // at over 20 times the pace its reasoning came before its first text, or - // it came in under a second after a wait four times longer + // answer's content came in under a quarter of its tail (flow), or its + // answer at over 20 times the pace its reasoning came before its first + // text, or it came in under a second after a wait four times longer // (pluviophile714 on Discord: gpt-6.1-sol, 392 tokens 0.25 s after an // 8.2 s first token, read 1,539 tok/s; usage.HeldWindowMs). function decodeOf(r, ms, ttft, firstText, flow = r.flow, firstReasoning = r.firstReasoning, reasoningHidden = r.reasoningHidden) { - if (reasoningHidden && !(firstText > 0)) return null; - const think = reasoningOf(r), visible = think > 0 && !(firstText > 0) && firstReasoning >= ttft && flow > 0 && think <= r.out; - const n = think > 0 && !visible ? r.out - think : r.out, from = visible ? firstReasoning : think > 0 ? firstText : ttft; - const w = ms - from; - if (!(n > 0 && ttft > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null; - if (flow > 0 && flow * 4 < w) return null; - if (w < 1000 && from > 4 * w) return null; - if (think > 0 && firstText > 0 && n * (firstText - ttft) > 20 * think * w) return null; + if (reasoningHidden && !(firstText > 0) && !(firstReasoning > 0)) return null; + if (!(ttft > 0)) return null; + const think = reasoningOf(r) > 0 ? reasoningOf(r) : 0, fr = firstReasoning > 0 ? firstReasoning : 0, ft = firstText > 0 ? firstText : 0; + const from = think && ft ? ft : ttft, tail = ms - from; + let n = r.out, start = ttft; + if (think && !fr) { + if (!ft) return null; + n = r.out - think, start = ft; + } else if (think > r.out) return null; + else if (fr && fr < ttft) start = fr; + const w = ms - start; + if (!(n > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null; + if (flow > 0 && flow * 4 < tail) return null; + if (w < 1000 && start > 4 * w) return null; + if (think && ft && (r.out - think) * (ft - ttft) > 20 * think * tail) return null; return { n, w }; } const reasoningOf = (r) => r.reasoning ?? (r.usage?.length ? r.usage[r.usage.length - 1].reasoning || 0 : 0); @@ -704,7 +713,7 @@ function routingPage(part) { cache: ["cache-hit", "Cache", prompt ? hitPct(read / prompt) : "—", tipLines(hitTip(read, prompt), t("Cache hit rate") + ": " + t("The share of the prompt read from the cache"))], speed: ["speed", "Speed", speed ? speed.text : "—", speed?.title || - t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed")], + t("All output tokens the vendor counted, reasoning and tool calls included, a second from the first output to the end, over the streamed replies") + ". " + t("A reply that reasoned with no sign in its stream of when counts only its answer, from its first text")], cost: ["cost", "Cost", routeCost(r), [r.priced ? costNote() : routeCredits([r]) ? "" : t("No known price or token counts for this request"), routeCredits([r]) ? creditsNote() : ""].filter(Boolean).join("\n")], }; return visibleMetrics.map((key) => values[key]).filter((metric) => metric[2] !== "—"); @@ -4463,7 +4472,7 @@ function routingPage(part) { if (g.key && visibleMetrics.includes("cache") && total.prompt) meta.push(metricElement(["cache-hit", "Avg. cache", hitPct(total.read / total.prompt), tipLines(hitTip(total.read, total.prompt), t("Total cache reads divided by total prompt tokens; larger prompts carry more weight"), coverage(total.cached))])); if (g.key && visibleMetrics.includes("speed") && total.decodeMs) meta.push(metricElement(["speed", "Avg. speed", t("{n} tok/s", { n: Math.round(total.decodeOut * 1000 / total.decodeMs) }), - tipLines(t("Total output tokens divided by the time from each reply's first token to its end; the wait for the first token, and replies without usable timing, are left out") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed"), + tipLines(t("Total output tokens divided by the time from each reply's first token to its end; the wait for the first token, and replies without usable timing, are left out") + ". " + t("Reasoning and tool calls count too, from the first output; a reply that reasoned with no sign in its stream of when counts only its answer, from its first text"), total.wholeMs ? t("Over each request's whole time, the wait for the first token and the reasoning counted: {n} tok/s", { n: Math.round(total.wholeOut * 1000 / total.wholeMs) }) : "", coverage(total.timed))])); const metaSig = JSON.stringify([bits, tokenHelp, meta.map((e) => [e.textContent, e.title])]); if (x.meta.dataset.sig !== metaSig) { x.meta.replaceChildren(...meta); x.meta.dataset.sig = metaSig; } diff --git a/internal/gui/assets/plugins/usage/page.js b/internal/gui/assets/plugins/usage/page.js index 45f0ccedc..b8b832728 100644 --- a/internal/gui/assets/plugins/usage/page.js +++ b/internal/gui/assets/plugins/usage/page.js @@ -2809,7 +2809,7 @@ function renderLedgerDash(l) { const gs = ledGroupSpeed(l); const ttft = ledTTFT(l) ? t("first token in {ms} on average", { ms: ledTook(ledTTFT(l)) }) + " · " + t(l.timed === 1 ? "{k} timed reply" : "{k} timed replies", { k: ledNum(l.timed) }) : t("no streamed replies timed"); const speedCard = block("Output speed", gs ? gs.mainParts : "—", gs?.other ? line(gs.other) : null, - "", [gs?.title, t("Output tokens a second after the first, over the streamed replies") + ". " + t("A reply that reasoned counts only its answer, from its first text: the reasoning was written before the stream showed it") + ". " + t("No answer text: speed includes reasoning only when visible reasoning streamed; hidden reasoning has no speed")].filter(Boolean).join("\n")); + "", [gs?.title, t("All output tokens the vendor counted, reasoning and tool calls included, a second from the first output to the end, over the streamed replies") + ". " + t("A reply that reasoned with no sign in its stream of when counts only its answer, from its first text")].filter(Boolean).join("\n")); speedCard.append(Object.assign(line(ttft), { className: "sub ttft" })); drawLedTrend(); } @@ -3399,25 +3399,36 @@ const LED_COLS = [ // seen (pluviophile714 on Discord: gpt-6.1-sol, 392 tokens 0.25 s after an // 8.2 s first token, read 1,539 tok/s; usage.HeldWindowMs) const ledHeldShort_ = (w, from) => w < 1000 && from > 4 * w; -// the tokens a reply was seen to write and the ms it took, as -// usage.DecodeOf and routing/client.js's decodeOf tell them: one that reasoned -// counts its answer from its first text, its reasoning written before -// the stream showed any (tony on Discord); null when it tells no speed. +// what a reply's speed counts, as usage.DecodeOf and routing/client.js's +// decodeOf count it: all its output tokens, reasoning and tool calls +// included (Archivemylife on X), from its first output of any kind, its +// first content or its first sign of reasoning, to its end (start); one +// that reasoned with no sign of when counts its answer from its first text +// (answer, tony on Discord), and none with no text. from is where the +// answer the burst is judged on starts. null when it counts none. +const ledSpan_ = (r) => { + const think = r.reasoning > 0 ? r.reasoning : 0, fr = r.first_reasoning_ms > 0 ? r.first_reasoning_ms : 0, ft = r.first_text_ms > 0 ? r.first_text_ms : 0; + const from = think && ft ? ft : r.ttft_ms; + if (think && !fr) return ft ? { n: r.out - think, start: ft, from, think, answer: true } : null; + if (think > r.out) return null; + return { n: r.out, start: fr && fr < r.ttft_ms ? fr : r.ttft_ms, from, think }; +}; // A reply held back and let go in a burst at its end tells none (John on -// Discord): its content came in under a quarter of its window (flow_ms), -// or its answer at over 20 times the pace its reasoning came before it, -// or it came in under a second after a wait four times longer (ledHeldShort_) +// Discord): its answer's content came in under a quarter of its window +// (flow_ms), or its answer at over 20 times the pace its reasoning came +// before it, or it came in under a second after a wait four times longer +// (ledHeldShort_) const ledDecode = (r) => { - if (ledFailed_(r) || r.canceled || r.reasoning_hidden && !(r.first_text_ms > 0) || !(r.ttft_ms > 0)) return null; - const think = r.reasoning > 0, visible = think && !(r.first_text_ms > 0) && r.first_reasoning_ms >= r.ttft_ms && r.flow_ms > 0 && r.reasoning <= r.out; - const n = think && !visible ? r.out - r.reasoning : r.out, from = visible ? r.first_reasoning_ms : think ? r.first_text_ms : r.ttft_ms; - const w = r.ms - from; - if (!(n > 0 && from > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null; - if (r.flow_ms > 0 && r.flow_ms * 4 < w) return null; - if (ledHeldShort_(w, from)) return null; - if (think && r.first_text_ms > 0 && n * (r.first_text_ms - r.ttft_ms) > 20 * r.reasoning * w) return null; + if (ledFailed_(r) || r.canceled || r.reasoning_hidden && !(r.first_text_ms > 0) && !(r.first_reasoning_ms > 0) || !(r.ttft_ms > 0)) return null; + const s = ledSpan_(r); + if (!s) return null; + const n = s.n, w = r.ms - s.start, tail = r.ms - s.from; + if (!(n > 0 && w >= 100 && n * 1000 <= 10000 * w)) return null; + if (r.flow_ms > 0 && r.flow_ms * 4 < tail) return null; + if (ledHeldShort_(w, s.start)) return null; + if (s.think && r.first_text_ms > 0 && (r.out - s.think) * (r.first_text_ms - r.ttft_ms) > 20 * s.think * tail) return null; if (ledCodexTurn(r) && (w < LED_CODEX_WINDOW_MS || n < LED_CODEX_BODY)) return null; - return { n, w }; + return { n, w, answer: !!s.answer }; }; // a Codex turn of one call read from its session file, its first token // known: its window after the first token can be one network push, not the @@ -3482,14 +3493,15 @@ const ledNoSpeed_ = (r) => { if (!(r.ms > 0)) return t("No duration was recorded to time a speed from"); if (!(r.out > 0)) return t("No output tokens to time a speed from"); if (!(r.ttft_ms > 0)) return r.source === "log" ? t("The session file has no first token to time a speed from") : t("Not streamed: no first token to time a speed from"); - const think = r.reasoning > 0, visible = think && !(r.first_text_ms > 0) && r.first_reasoning_ms >= r.ttft_ms && r.flow_ms > 0 && r.reasoning <= r.out; - const n = think && !visible ? r.out - r.reasoning : r.out; + // a reply that reasoned with no sign of when and no text counts none: + // why is said of its answer, all after its first token + const s = ledSpan_(r) || { n: r.out - (r.reasoning || 0), start: r.ttft_ms, from: r.ttft_ms, think: r.reasoning || 0 }, n = s.n; if (!(n > 0)) return t("All its output was reasoning: no answer after it to time a speed from"); - const from = visible ? r.first_reasoning_ms : think && r.first_text_ms > 0 ? r.first_text_ms : r.ttft_ms, w = r.ms - from; + const from = s.start, w = r.ms - from, tail = r.ms - s.from, burst = r.flow_ms > 0 && r.flow_ms * 4 < tail; const little = t("Too little came after the first token to time a speed by: {n} tokens in {ms}", { n: ledNum(n), ms: ledTook(Math.max(0, w)) }); if (w < 100) return little; - if (ledHeldShort_(w, from) && !(n * 1000 > 10000 * w || r.flow_ms > 0 && r.flow_ms * 4 < w)) return t("It came in under a second after a wait of {wait}: it may have been written during the wait and let go at once, so how fast it was written isn't seen", { wait: ledTook(from) }); - if (n * 1000 > 10000 * w || r.flow_ms > 0 && r.flow_ms * 4 < w || think && r.first_text_ms > 0 && n * (r.first_text_ms - r.ttft_ms) > 20 * r.reasoning * w) return t("It came in one burst at its end, not as it was written, so how fast it was written isn't seen"); + if (ledHeldShort_(w, from) && !(n * 1000 > 10000 * w || burst)) return t("It came in under a second after a wait of {wait}: it may have been written during the wait and let go at once, so how fast it was written isn't seen", { wait: ledTook(from) }); + if (n * 1000 > 10000 * w || burst || s.think && r.first_text_ms > 0 && (r.out - s.think) * (r.first_text_ms - r.ttft_ms) > 20 * s.think * tail) return t("It came in one burst at its end, not as it was written, so how fast it was written isn't seen"); return little; }; const ledFloorSpeed = (r) => { const f = ledFloor_(r); return f ? f.n / (f.w / 1000) : 0; }; @@ -3948,7 +3960,7 @@ function renderLedger() { const v = ledRowSpeed(r), floor = ledFloorSpeed(r), f = ledFloor_(r); const ttft = r.ttft_ms > 0 ? " · " + t("TTFT {ms}", { ms: ledTook(r.ttft_ms) }) : ""; td(v ? t("{n} tok/s", { n: ledNum(Math.round(v)) }) : floor ? "≥" + t("{n} tok/s", { n: ledNum(Math.round(floor)) }) : "—", "n speed" + (v || floor ? "" : " faint"), - v ? (r.reasoning > 0 && r.first_text_ms > 0 ? t("{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w), r: ledNum(r.reasoning) }) + v ? (ledDecode(r).answer ? t("{n} answer tokens in {ms} after the first text, the {r} reasoning tokens before it left out", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w), r: ledNum(r.reasoning) }) : t("{n} output tokens in {ms} after the first", { n: ledNum(ledDecode(r).n), ms: ledTook(ledDecode(r).w) })) + ttft : floor && f.gateway && f.answer ? t("At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too", { n: ledNum(f.n), ms: ledTook(f.w), r: ledNum(r.reasoning) }) + ttft : floor && f.gateway ? t("At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too", { n: ledNum(r.out), ms: ledTook(r.ms) }) + ". " + ledNoSpeed_(r) + ttft diff --git a/internal/gui/tests/reasoning-speed.test.cjs b/internal/gui/tests/reasoning-speed.test.cjs index a1c6451d6..34e4168d6 100644 --- a/internal/gui/tests/reasoning-speed.test.cjs +++ b/internal/gui/tests/reasoning-speed.test.cjs @@ -9,6 +9,11 @@ // tell the least its answer wrote at (zzzkl3994 on Discord); one that didn't reason is timed as before. The Routing page's rows, // a session's average and the Usage page's rows and their tooltip all say // it, in English, Chinese, Japanese and German; no backend, the API is faked. +// A reply whose stream showed when it began to reason counts all its output, +// reasoning and tool calls included, from its first output (Archivemylife on +// X): a Codex turn's preamble, reasoning and shell call, 1,239 tokens over +// the 18.4 s from its first token, is 67 tok/s, not its 630-token call in +// the 1.6 s after its last reasoning, 386. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); const path = require("node:path"); @@ -29,10 +34,12 @@ const timing = [ [1500, 1400, 0, 15000, 1000, 0], // paced visible reasoning: 107 tok/s [1500, 1400, 0, 9000, 8000, 0], // a late summary stays untimed, ≥100 on both pages [120, 0, 0, 9000, 1000, 0], // mixed redacted thinking without a reasoning count + [1239, 609, 0, 21114, 2720, 19484], // preamble, reasoning seen at 3.2 s, a shell call: 1239 in 18.4 s, 67 tok/s ]; const routes = timing.map(([out, reasoning, usageReasoning, ms, ttft, firstText], i) => ({ ...(i === 4 ? { firstReasoning: 1000, flow: 12000 } : {}), ...(i === 6 ? { reasoningHidden: true, flow: 7000 } : {}), + ...(i === 7 ? { firstReasoning: 3166, reasoningHidden: true } : {}), id: 100 - i, seq: 100 - i, time: at(i), agent: "codex", session: "think-chat", model: "codex/gpt-6.1-sol", provider: "codex", order: [seat], tries: [{ id: seat.id, model: seat.model, start: at(i), done: true, status: 200, ms, ttft, firstText }], done: true, status: 200, ms, ttft, firstText, tokens: out + 9000, out, ...(reasoning ? { reasoning } : {}), @@ -41,13 +48,15 @@ const routes = timing.map(([out, reasoning, usageReasoning, ms, ttft, firstText] const rows = timing.map(([out, reasoning, usageReasoning, ms, ttft, firstText], i) => ({ ...(i === 4 ? { first_reasoning_ms: 1000, flow_ms: 12000 } : {}), ...(i === 6 ? { reasoning_hidden: true, flow_ms: 7000 } : {}), + ...(i === 7 ? { first_reasoning_ms: 3166, reasoning_hidden: true } : {}), route_id: 100 - i, t: at(i), agent: "codex", agentName: "Codex", icon: "codex-color", provider: "codex", providerName: "Codex", host: "test@example.com", req: "codex/gpt-6.1-sol", model: "gpt-6.1-sol", served: "gpt-6.1-sol", in: 9000, out, ...(reasoning || usageReasoning ? { reasoning: reasoning || usageReasoning } : {}), ms, ttft_ms: ttft, ...(firstText ? { first_text_ms: firstText } : {}), status: 200, ep: "/backend-api/codex/responses", cost: 0.01, priced: true, })); -// what the server sums: 1000 answer tokens plus 1500 visible output tokens in 23.5 s -const M = { id: "gpt-6.1-sol", calls: 7, input: 63000, output: 8620, cache_read: 0, cache_write: 0, cost: 0.04, timed: 4, ttft_ms: 30000, decode_ms: 23500, decode_out: 2500 }; +// what the server sums: 1000 answer tokens plus 1500 visible output tokens in +// 23.5 s, and the Codex turn's 1239 in 18.394 s +const M = { id: "gpt-6.1-sol", calls: 8, input: 72000, output: 9859, cache_read: 0, cache_write: 0, cost: 0.05, timed: 5, ttft_ms: 32720, decode_ms: 41894, decode_out: 3739 }; function serve(lang) { const state = { agents: [{ id: "codex", name: "Codex", path: "/t/c.toml", icon: "codex-color", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; @@ -79,11 +88,11 @@ function serve(lang) { } const L = { - "zh-TW": { s: (n) => `${n} token/秒`, speed: "速度", note: /首個正文後/, rule: /有推理的回覆只算正文部分/ }, - en: { s: (n) => `${n} tok/s`, speed: "Speed", note: /200 answer tokens in 1\.5 s after the first text, the 2,000 reasoning tokens before it left out/, rule: /A reply that reasoned counts only its answer/ }, - zh: { s: (n) => `${n} token/秒`, speed: "速度", note: /首个正文后 1\.5 秒 输出 200 个正文 token,之前的 2,000 个推理 token 不计/, rule: /有推理的回复只算正文部分/ }, - ja: { s: (n) => `${n} トークン/秒`, speed: "速度", note: /回答 200 トークン(その前の推論 2,000 トークンは含めず)/, rule: /推論した応答は/ }, - de: { s: (n) => `${n} Token/s`, speed: "Tempo", note: /200 Antwort-Token in .* nach dem ersten Text, ohne die 2\.000 Reasoning-Token davor/, rule: /Eine Antwort mit Reasoning/ }, + "zh-TW": { s: (n) => `${n} token/秒`, speed: "速度", note: /首個正文後/, rule: /推理和工具呼叫/ }, + en: { s: (n) => `${n} tok/s`, speed: "Speed", note: /200 answer tokens in 1\.5 s after the first text, the 2,000 reasoning tokens before it left out/, rule: /[Rr]easoning and tool calls/ }, + zh: { s: (n) => `${n} token/秒`, speed: "速度", note: /首个正文后 1\.5 秒 输出 200 个正文 token,之前的 2,000 个推理 token 不计/, rule: /推理和工具调用/ }, + ja: { s: (n) => `${n} トークン/秒`, speed: "速度", note: /回答 200 トークン(その前の推論 2,000 トークンは含めず)/, rule: /推論とツール呼び出し/ }, + de: { s: (n) => `${n} Token/s`, speed: "Tempo", note: /200 Antwort-Token in .* nach dem ersten Text, ohne die 2\.000 Reasoning-Token davor/, rule: /Reasoning und Tool-Aufrufe/ }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -112,6 +121,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await speedOf(4), w.s(107), "visible reasoning timed from its first delta"); assert.equal(await speedOf(5), "≥" + w.s(100), "a late hidden summary tells the least, as the Usage row"); assert.equal(await speedOf(6), "", "redacted reasoning stays untimed without a count"); + assert.equal(await speedOf(7), w.s(67), "all the Codex turn's output from its first token, not its call's 386"); assert.match(await reqs.nth(0).locator(".speed").getAttribute("title"), w.rule); await reqs.nth(0).click(); await page.waitForTimeout(200); @@ -120,8 +130,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator(".rt-group-by button").nth(1).click(); const group = page.locator("button.rt-session").first(); await group.waitFor(); - // Hidden reasoning is excluded; visible reasoning adds its own decode window. - assert.equal((await group.locator(".speed .v").textContent()).trim(), w.s(106)); + // Hidden reasoning is excluded; visible reasoning adds its own decode window, + // and so does the Codex turn: 3739 tokens in 41.894 s + assert.equal((await group.locator(".speed .v").textContent()).trim(), w.s(89)); assert.match(await group.locator(".speed").getAttribute("title"), w.rule); // the Usage page's requests: each row, its tooltip, and the period's @@ -144,8 +155,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal((await cell(4).textContent()).trim(), w.s(107)); assert.equal((await cell(5).textContent()).trim(), "≥" + w.s(100)); assert.equal((await cell(6).textContent()).trim(), "—"); + assert.equal((await cell(7).textContent()).trim(), w.s(67)); const kpi = page.locator("#ledKpi .blk").nth(4); - assert.equal((await kpi.locator(".v").textContent()).trim(), w.s(106)); + assert.equal((await kpi.locator(".v").textContent()).trim(), w.s(89)); assert.match(await kpi.getAttribute("title") || await kpi.locator("[title]").first().getAttribute("title"), w.rule); assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, "no sideways scroll"); assert.deepEqual(errors, []); diff --git a/internal/usage/heat_disk.go b/internal/usage/heat_disk.go index ccb619c8e..f1355f579 100644 --- a/internal/usage/heat_disk.go +++ b/internal/usage/heat_disk.go @@ -34,7 +34,7 @@ import ( // history again on its first start, the cold start's peak (#2278). Raise // it with any change to what a row counts as; TestSettledCountedAsVersioned // fails until it is raised. -const settledCountVersion = "7" +const settledCountVersion = "8" func heatDiskPath() string { return filepath.Join(filepath.Dir(sessions.CachePath()), "heat-v1.json") diff --git a/internal/usage/reasoning_stream_speed_test.go b/internal/usage/reasoning_stream_speed_test.go index b029148a3..5825dc964 100644 --- a/internal/usage/reasoning_stream_speed_test.go +++ b/internal/usage/reasoning_stream_speed_test.go @@ -17,9 +17,14 @@ func TestVisibleReasoningSpeed(t *testing.T) { w int64 }{ {"visible tool turn", visible, 1500, 14000}, - {"answer remains separate", func() Record { r := visible; r.FirstText = 14000; r.Flow = 1000; return r }(), 100, 1000}, + // the answer after the reasoning: all of it counts, from the first + // reasoning (Archivemylife on X: reasoning is tokens too) + {"answer after reasoning", func() Record { r := visible; r.FirstText = 14000; r.Flow = 1000; return r }(), 1500, 14000}, + {"reasoning before the first token", func() Record { r := visible; r.TTFT, r.FirstText, r.Flow = 3000, 14000, 1000; return r }(), 1500, 14000}, {"hidden and old records", func() Record { r := visible; r.FirstReasoning = 0; return r }(), 0, 0}, - {"unknown flow", func() Record { r := visible; r.Flow = 0; return r }(), 0, 0}, + {"unknown flow", func() Record { r := visible; r.Flow = 0; return r }(), 1500, 14000}, + // sealed reasoning whose start the stream showed (a reasoning item's) + {"sealed reasoning, its start seen", func() Record { r := visible; r.ReasoningHidden = true; return r }(), 1500, 14000}, {"held reasoning at quarter boundary", func() Record { r := visible; r.Flow = 3500; return r }(), 1500, 14000}, {"held reasoning just below quarter", func() Record { r := visible; r.Flow = 3499; return r }(), 0, 0}, {"held reasoning", func() Record { r := visible; r.Flow = 1000; return r }(), 0, 0}, @@ -60,8 +65,8 @@ func TestVisibleReasoningSpeed(t *testing.T) { for _, c := range []*rowChunk{&hiddenChunk, hiddenChunk.pack().unpack()} { row := c.row(0) n, w := row.Decode() - if !row.ReasoningHidden || n != 0 || w != 0 { - t.Fatal("cache lost hidden reasoning flag") + if !row.ReasoningHidden || row.FirstReasoning != 1000 || n != 1500 || w != 14000 { + t.Fatalf("cache lost sealed reasoning: %+v, %d/%d", row, n, w) } } var sum Totals @@ -80,7 +85,7 @@ func TestVisibleReasoningSpeed(t *testing.T) { func TestPricedRowKeepsReasoningEvidence(t *testing.T) { visible := Record{Time: time.Now(), Provider: "deepseek", Model: "deepseek-chat", Output: 1500, Reasoning: 1400, Millis: 15000, TTFT: 1000, FirstReasoning: 1000, Flow: 12000, Status: 200} toolOnly := Record{Time: time.Now(), Provider: "deepseek", Model: "deepseek-chat", Output: 120, Millis: 9000, TTFT: 1000, Flow: 7000, Status: 200} - sealed := visible + sealed := toolOnly sealed.ReasoningHidden = true for _, c := range []struct { name string diff --git a/internal/usage/usage.go b/internal/usage/usage.go index 55d03f7a1..1235a66d1 100644 --- a/internal/usage/usage.go +++ b/internal/usage/usage.go @@ -113,7 +113,7 @@ type Record struct { // Compaction is Codex's explicit native marker. Nil means no matching // native Codex call established whether a gateway row compacted. Compaction *bool `json:"compaction,omitempty"` - // FirstReasoning is the start of paced visible reasoning, absent for hidden reasoning. + // FirstReasoning: ms to the reply's first sign of reasoning, streamed or sealed (a reasoning delta, a reasoning item's or thinking block's start); 0 for none. FirstReasoning int64 `json:"first_reasoning_ms,omitempty"` // ReasoningHidden: the reply reasoned and its stream doesn't tell how // much — sealed or summarised, or streamed with no reasoning count in @@ -726,75 +726,91 @@ func DecodeWindow(out int, ms, ttft int64) int64 { return w } -// DecodeOf is what a reply's speed is told by: the tokens it was seen to -// write and the ms it took (tony on Discord: gpt-6.1-sol read 163 tok/s, -// with a 14 s first token). A reply that reasoned counts only its answer — -// its output less the reasoning, from its first text — as most vendors -// keep the reasoning out of the stream (OpenAI's is encrypted, its summary -// sent when it's done; Claude's may come with no text): its tokens were -// written before the first content, over time the window from it doesn't -// hold, and counting them read a 2,000-token think and a 200-token answer -// in 1.5 s as 1,467 tok/s. Its time goes to the wait before the answer. -// With no answer text, paced visible reasoning can time all output from -// firstReasoning. Missing evidence (including older records), hidden reasoning -// and an unknown flow leave the speed untold. The -// window is DecodeWindow's: 0 for a reply that tells none. +// DecodeOf is what a reply's speed is told by: the tokens it wrote and the +// ms it took. Its speed is all its output tokens, as its vendor's usage +// counts them — reasoning and tool calls' arguments are tokens too — over +// the time from its first output of any kind to its end (Archivemylife on +// X): its first content (ttft) or, when it came first, its first sign of +// reasoning (firstReasoning), streamed or sealed — a reasoning delta, a +// Responses reasoning item's start, an Anthropic thinking block's start. +// The wait before either, the vendor reading the prompt, is TTFT's, not +// the speed's. Every protocol and vendor counts it so; only how its +// reasoning is seen differs: +// +// - a reply that reasoned and showed no sign of when (firstReasoning 0: +// a Chat vendor whose reasoning_tokens come with no reasoning delta, a +// Gemini thought not included, a record kept before the start was) had +// its reasoning written before its first content, over time its stream +// doesn't show, and counting it over the window from that content read +// a 2,000-token think and a 200-token answer in 1.5 s as 1,467 tok/s +// (tony on Discord). Such a reply counts its answer, its output less +// the reasoning, from its first text, and tells none with no text. +// +// The window is DecodeWindow's: 0 for a reply that tells none. // // A reply its vendor held back and let go in a burst at its end tells // none either (John on Discord: Kimi Code answering OpenCode read 1,367, -// then 2,237 and 2,012 tok/s). The burst is told two ways, as the reply's -// text came before it or with it: +// then 2,237 and 2,012 tok/s). The burst is judged on what came after the +// reasoning, its answer from its first text (or its first content, when it +// had none), as reasoning sealed in the stream comes in no bytes: // -// - flow, when known (Record.Flow), is how long its content took to come -// from where its window starts. A window HeldShare times longer had -// its content come in a small part of it: the rest was a wait while -// the vendor wrote and held it. The time it took to come is not the -// time it took to write (a burst let go over 236 ms read 528 tokens at -// 2,237 tok/s), and that time is not seen, so it tells no speed. A -// stream that came as it was written has a flow about its window. -// - a reply that reasoned is timed from its first text, its reasoning -// written before. When the answer would have been written over -// ThinkPace times faster than its reasoning came before it, from the -// first content to the first text, its first text came with the burst -// and the wait before it was the answer being written and held (22 -// reasoning tokens over 10.5 s, then 528 answer tokens in 236 ms). A -// reasoning hidden from the stream (OpenAI's, Claude's omitted) comes -// before the first content and leaves this time short; one that -// streams comes at the pace its answer does. +// - flow, when known (Record.Flow), is how long the answer's content took +// to come. An answer window HeldShare times longer had its content come +// in a small part of it: the rest was a wait while the vendor wrote and +// held it. The time it took to come is not the time it took to write +// (a burst let go over 236 ms read 528 tokens at 2,237 tok/s), and that +// time is not seen, so it tells no speed. A stream that came as it was +// written has a flow about its window. +// - when the answer would have been written over ThinkPace times faster +// than the reasoning came before it, from the first content to the +// first text, its first text came with the burst and the wait before it +// was the answer being written and held (22 reasoning tokens over +// 10.5 s, then 528 answer tokens in 236 ms). // - a window under HeldWindowMs after a wait HeldShare times longer: the // reply came whole in a moment after a long silence, and what it was // written over is not seen (pluviophile714 on Discord: gpt-6.1-sol, // 392 tokens 0.25 s after an 8.2 s first token, read 1,539 tok/s where // the vendor writes ~70). Its content can come spread over that moment -// (a relay replaying a held reply, OpenAI's answer let go after its -// hidden reasoning), so flow doesn't tell it. A stream as it is written -// takes a second or more to write a few hundred tokens; one that takes -// under a second is too short a sample to tell a speed by against such -// a wait, so a short answer after a long think tells none either. +// (a relay replaying a held reply), so flow doesn't tell it. A stream as +// it is written takes a second or more to write a few hundred tokens; +// one that takes under a second is too short a sample to tell a speed +// by against such a wait. func DecodeOf(out, reasoning int, ms, ttft, firstText, flow int64, firstReasoning ...int64) (tokens int, w int64) { - start := ttft - if reasoning > 0 { - if firstText > 0 { - out, start = out-reasoning, firstText - } else if len(firstReasoning) > 0 && firstReasoning[0] >= ttft && flow > 0 && reasoning <= out { - start = firstReasoning[0] - } else { - return 0, 0 - } - } if ttft <= 0 { return 0, 0 } + var think int64 + if len(firstReasoning) > 0 { + think = firstReasoning[0] + } + // from: where the answer the burst is judged on starts + start, from, answer := ttft, ttft, out-reasoning + if reasoning > 0 && firstText > 0 { + from = firstText + } + switch { + case reasoning > 0 && think <= 0: + // reasoned out of sight: the answer alone (above) + if firstText <= 0 { + return 0, 0 + } + out, start = answer, firstText + case reasoning > out: + return 0, 0 + case think > 0 && think < start: + start = think + } if w = DecodeWindow(out, ms, start); w == 0 { return 0, 0 } - if flow > 0 && flow*HeldShare < w { + tail := ms - from + if flow > 0 && flow*HeldShare < tail { return 0, 0 } if w < HeldWindowMs && start > HeldShare*w { return 0, 0 } - if reasoning > 0 && firstText > 0 && int64(out)*(firstText-ttft) > ThinkPace*int64(reasoning)*w { + if reasoning > 0 && firstText > 0 && int64(answer)*(firstText-ttft) > ThinkPace*int64(reasoning)*tail { return 0, 0 } return out, w @@ -813,7 +829,7 @@ const ( // Decode is the record's DecodeOf. func (r Record) Decode() (tokens int, w int64) { - if r.ReasoningHidden && r.FirstText <= 0 { + if r.ReasoningHidden && r.FirstText <= 0 && r.FirstReasoning <= 0 { return 0, 0 } return DecodeOf(r.Output, r.Reasoning, r.Millis, r.TTFT, r.FirstText, r.Flow, r.FirstReasoning)