Files
magpie/internal/claudetui/transcript.go
T
yetone 8a410f35a2 claudetui: Claude Code's interactive mode streams its replies, through a preload that copies the main turn's stream
The owner: make a Claude subscription stream as it goes while Claude
Code runs in its interactive mode (TUI), on macOS, Windows and WSL.
Until now the helper read Claude Code's transcript, which has a message
only once it ends, so a reply came to the client whole.

Claude Code is a Bun program, and Bun loads a script named in
BUN_OPTIONS (--preload) before it. The helper writes tap.js to a folder
of its own and starts Claude Code with BUN_OPTIONS="--preload tap.js"
(after the user's own BUN_OPTIONS, but not a Windows one's for a Claude
Code in WSL, where both go through WSLENV). tap.js makes Bun.FetchSession
a subclass whose fetch is the real one's, so the request, its headers,
its connection and TLS are Claude Code's own. For a reply to a
request marked x-claude-code-request-class: main to /v1/messages that
is text/event-stream, it tees the body: Claude Code reads its copy as
before, and tap.js writes each event, as it comes, as a JSON line to
the file MAGPIE_CLAUDE_TAP names. It takes itself out of BUN_OPTIONS,
execArgv and the environment first, so nothing Claude Code runs
inherits it.

The helper reads that file and tells the events as -p's stream_event
lines, so the gateway reads them as it reads -p's. A transcript message
waits up to 1s for its stream to begin (then it's told whole, its late
stream left out); a turn's end waits for its streams to end; a stream
cut short ends with a message_stop and no message_delta, as -p ends
one. The bridge now keeps the streamed messages by id, since a whole
message can come during the next message's stream, and a client
tool_use shown from the stream isn't told again from the whole message.

On Windows, BUN_OPTIONS has no quoting, so a temp path with a space
takes its short name; one that still has whitespace gets no tap, and
replies come whole, as they do from a Claude Code that isn't Bun or
doesn't send through FetchSession (2.1.281 on Windows doesn't; 2.1.289
and 2.1.316 do).

Run:
- gofmt -l: clean. go vet on mote for darwin, GOOS=linux and
  GOOS=windows: 0.
- go test ./internal/claudetui ./internal/gateway on mote
  (-timeout 45m): ok, ok (gateway 654s).
- go test ./internal/claudetui with win-run (Windows 11) and wsl-run
  (magpie-desktop): ok, ok.
- macOS, real account (Claude Code 2.1.316, sandbox HOME, keychain
  token): a reply came as message_start, text deltas,
  content_block_stop, message_delta, message_stop, then the whole
  message, then the result; stderr clean, the tap's folder removed.
- Windows native, Claude Code 2.1.316 against a fake that sends an SSE
  event every 250ms (a user preload marking the request main, which
  also checks the user's BUN_OPTIONS is kept): the deltas came 250ms
  apart, before the whole message. The same with TEMP holding a space
  (short name).
- WSL magpie-desktop, Claude Code 2.1.289 run through wsl.exe from the
  Windows helper, the fake in WSL: the same.
- The scrub, on macOS and Windows: Claude Code's BUN_OPTIONS and
  execArgv have no tap, MAGPIE_CLAUDE_TAP is gone, --smol is kept.
- Rebased on origin/main 02ff0e908 (no file in common): on mote, vet
  for darwin, windows and linux nogui 0; go test ./internal/claudetui
  ok; -run 'CoreScriptBudget|I18n|Claude|Budget' ./internal/gui ok;
  -run Claude ./internal/gateway ok. In WSL claude-mode, account-weight,
  old-webkit and i18n-keys: 59 of 60, the one red i18n-keys' "Unmarked"
  (#4524).

Broken by hand: the told mark removed, TestClaudeTUIStreamedCallToldOnce
went red; streamed kept as the last id only, TestClaudeTUILateRowOfStreamed
went red; before() made a no-op, and settle's end loop removed, the tap
tests went red. Each was put back.

TestTapMessageWaitsForItsStream failed now and then on mote: the whole
message can be told once its stream has begun, before the rest of the
stream is read. It now checks what is promised: the stream begins
before the message, every event is told, and the result comes last
(-count=30 ok).

Not tried: a real account on Windows or in WSL (the keychain token
went missing mid-session; those runs used the fake, whose request
carries no x-claude-code-request-class since a custom base URL drops
it); a real turn of several messages with the client's tools; Claude
Code 2.1.281 on Windows, which doesn't stream and is told whole as
before.
2026-11-01 00:37:29 +08:00

149 lines
4.2 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"`
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}
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
}
}
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.failed = true
t.tap.settle()
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
}