Files
magpie/internal/claudetui/transcript.go
T
qiqllandggbdpq b7631300ec claudetui: a successful interactive turn tells its account's allowance
Since the interactive mode replaced -p for Claude subscription turns
(43966a53, e5f66f8a, 10-31), a turn that succeeded told no
rate_limit_event, so NoteClaudeLimits never ran and the Usage page's
5h/7d figures moved only on a manual refresh (/usage). Only a turn that
ended in a <synthetic> API error told one, from its transcript row.

What changed:
- tap.js, when a main-class reply opens, also copies its
  anthropic-ratelimit-unified-* response headers into the {s, open}
  line as "h". It only reads them; the request to Anthropic is sent as
  Claude Code made it.
- tap.go (rateLimitInfo) turns them into the rate_limit_info -p tells
  (Claude Code 2.1.291): status plus unifiedWindows five_hour, seven_day,
  seven_day_overage_included (5h, 7d, 7d_oi), each only when both its
  utilization and reset are numbers, the reset rounded to a second.
- A streamed reply tells it just before its message_start, as -p does,
  so the bridge keeps it before the reply begins. A reply whose message
  was told whole from the transcript, or that never began one, keeps it
  for the turn's end (tap.settle). Only the latest is told: a kept
  reading from an older reply is never told after a later reply's
  (toldOf), whether the older one ended before or after the later one
  began, since NoteClaudeLimits keeps the last it hears.
- transcript.go: a <synthetic> API error settles the tap first, then
  tells its own rate_limit_info, so the error's reading is the newest.
- docs/subsystems/claude-subscription-bridge.md says all of this.
  The gateway is unchanged: it already turns a rate_limit_event into
  NoteClaudeLimits and limitHeaders.

Run at this head (base origin/main 6c201095):
- gofmt -l on the changed Go files: nothing
- go vet ./internal/claudetui/, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: clean
- go test -count=1 ./internal/claudetui/: ok (62s)
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway/ -run
  'Claude|Tap|TUI': ok (60s)

Broken by hand:
- tap.go, tap.js and transcript.go at 6c201095 with the new tests: all of
  TestTapTellsReplyLimits, TestTapLimitsOfMessageToldWhole,
  TestTapErrorLimitsLast, TestShimTellsTapLimits and
  TestTapKeptLimitsNotAfterNewer (both subtests) red.
- keepLimits without `n > t.toldOf`: TestTapKeptLimitsNotAfterNewer/
  ended_after red (told 0.42 then 0.3). message_start without dropping an
  older kept reading: /ended_before red the same way.

Not tried: a turn on a real claude.ai account, so the headers were not
checked against a captured reply; Windows and WSL; the full go test
./... suite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Review: chosen over #5012, which reads the same headers but emits a
rate_limit_event the moment its line arrives. That event can land while an
unstreamed message is pending, and the bridge settles that message early.
This one tells the limits just before message_start, keeps them for a cut
stream's end, and never tells an older reply's limits after a newer one's.
ddnio's real setup-token run on #5012 shows Bun's response headers are
readable there, the same thing this reads.
Run at the pushed head on mote, go1.26.8: go test -tags nogui -count=1
./internal/claudetui/ ok (83s).
Broken by hand: with the limits before message_start turned off,
TestTapTellsReplyLimits, TestShimTellsTapLimits and
TestTapKeptLimitsNotAfterNewer are red.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 05:54:00 +08:00

157 lines
4.5 KiB
Go

package claudetui
import (
"encoding/json"
)
// emitter is where a translator's lines go.
type emitter interface {
emit(v any)
// a message the user sent reached the transcript, and a turn ended
sawRow()
turnOver()
}
// translator tells the bridge, as `claude -p`'s stream-json, what the
// session's transcript says. Claude Code writes a row a content block of an
// assistant message, under the message's id, as -p tells one not streamed:
// each goes on as it is. An API error is a <synthetic> message whose text
// is the error, and a turn's end a turn_duration row: they become the
// turn's result, as -p ends a turn.
type translator struct {
out emitter
// the turn failed: its <synthetic> row's result is told, and the
// turn_duration after it says nothing more
failed bool
// tap has the streams of the messages (tap.go): a message is told
// after its stream has begun, and a turn's end after its streams'
tap *tap
}
func newTranslator(out emitter) *translator { return &translator{out: out} }
// quiet and flush are for a translator that holds rows back; this one
// tells each as it comes.
func (t *translator) quiet() {}
func (t *translator) flush() {}
func (t *translator) row(b []byte) {
var r struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
UUID string `json:"uuid"`
IsSidechain bool `json:"isSidechain"`
IsMeta bool `json:"isMeta"`
RequestID string `json:"requestId"`
Error json.RawMessage `json:"error"`
IsAPIError bool `json:"isApiErrorMessage"`
APIStatus int `json:"apiErrorStatus"`
ToolUseResult json.RawMessage `json:"toolUseResult"`
Operation string `json:"operation"`
APIParams struct {
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
} `json:"apiErrorParams"`
Message json.RawMessage `json:"message"`
}
if json.Unmarshal(b, &r) != nil || r.IsSidechain {
return
}
switch r.Type {
case "queue-operation":
// a message sent mid-turn waits in Claude Code's queue
if r.Operation == "enqueue" {
t.out.sawRow()
}
case "user":
if !r.IsMeta && isPrompt(r.Message) {
t.failed = false
t.out.sawRow()
}
if len(r.ToolUseResult) > 0 && r.ToolUseResult[0] == '{' {
t.out.emit(map[string]any{"type": "user", "tool_use_result": r.ToolUseResult})
}
case "assistant":
var m struct {
ID string `json:"id"`
Model string `json:"model"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
}
_ = json.Unmarshal(r.Message, &m)
if m.Model != "<synthetic>" && m.ID != "" {
t.tap.before(m.ID)
}
line := map[string]any{"type": "assistant", "message": r.Message}
// the row's place in the session, as -p tells it: the bridge
// branches a conversation off there (cutSession)
if r.UUID != "" {
line["uuid"] = r.UUID
}
if r.RequestID != "" {
line["request_id"] = r.RequestID
}
if len(r.Error) > 0 {
line["error"] = r.Error
}
t.out.emit(line)
if m.Model != "<synthetic>" || !r.IsAPIError {
return
}
text := ""
for _, c := range m.Content {
if c.Type == "text" {
text += c.Text
}
}
t.failed = true
// the error's own allowance after any an earlier reply of the
// turn told (tap.settle), as it is the latest
t.tap.settle()
if len(r.APIParams.RateLimitInfo) > 0 && string(r.APIParams.RateLimitInfo) != "null" {
t.out.emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": r.APIParams.RateLimitInfo})
}
t.out.turnOver()
t.out.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true,
"result": text, "api_error_status": r.APIStatus})
case "system":
if r.Subtype == "turn_duration" {
t.tap.settle()
}
if r.Subtype == "turn_duration" && !t.failed {
t.out.emit(map[string]any{"type": "result", "subtype": "success", "is_error": false})
}
if r.Subtype == "turn_duration" {
t.failed = false
t.out.turnOver()
}
}
}
// isPrompt says whether a user row's message is one typed in: text, not a
// tool's result.
func isPrompt(raw json.RawMessage) bool {
var m struct {
Content json.RawMessage `json:"content"`
}
if json.Unmarshal(raw, &m) != nil || len(m.Content) == 0 {
return false
}
if m.Content[0] == '"' {
return true
}
var blocks []struct {
Type string `json:"type"`
}
if json.Unmarshal(m.Content, &blocks) != nil {
return false
}
for _, b := range blocks {
if b.Type == "tool_result" {
return false
}
}
return len(blocks) > 0
}