Files
magpie/internal/claudetui/transcript.go
T
yetone 43966a53fb claude: a subscription's run is Claude Code's interactive mode, -p only as the fallback
The owner (10-31): a Claude subscription ran `claude -p`, whose
requests Anthropic labels sdk-cli and counts at about twice the
interactive mode's cli (anthropics/claude-code#97074). Running the real
interactive Claude Code is what its terms describe and uses the plan as
a person does. Wanted inside magpie, on by default, with a way off.

`magpie claude-tui-helper <claude> <-p args>` (internal/claudetui)
stands where `claude -p` stood and speaks the same stream-json. It
turns the -p arguments into the interactive mode's (no -p, no
--dangerously-skip-permissions: --permission-mode default with only
mcp__magpie, and the WebSearch -p was given, allowed; --no-chrome;
--session-id or the --resume given), starts Claude Code in a
pseudo-terminal of its own (no tmux), pastes each message into its
prompt and presses Enter, and tells the session's transcript back as
-p's lines: whole assistant messages, an API error as the turn's error
result with its rate_limit_info, turn_duration as the result. Nothing
sets CLAUDE_CODE_ENTRYPOINT, and the user's ~/.claude and
~/.claude.json are never written. The folder-trust question is
answered only for magpie's own folder or a saved account's config
directory (MAGPIE_CLAUDE_TUI_TRUST).

A Claude Code that doesn't start or show its prompt in 45s becomes
`claude -p` on the same pid, its input still unread, so the turn is
answered all the same; that is remembered for 30 minutes
(<cache>/magpie/claude-tui-broken). An untrusted folder goes to -p
without the mark.

claudeTUI keeps -p for Windows and WSL, Settings › Models › Replies ›
Claude Code's interactive mode Off (claudePrintMode), safeguards,
client cache marks, a JSON schema, images and a first message over
400KB. A TUI run ends instead of taking an image turn, a rewind or an
effort change, and letGo doesn't take one back. The gateway's tests
run with claudeTUIRuns off: their binary has no claude-tui-helper.
docs/subsystems/claude-subscription-bridge.md has the section.

The core's scripts grow 725 bytes with the setting's row;
coreScriptBudget is raised to the exact size, 1,537,356, with no room
added.

Run (rebased on f2eb56c6b and its budget fix):
- mote: go vet of claudetui, gateway, cli, settings on darwin;
  GOOS=windows of claudetui, gateway, cli; GOOS=linux of claudetui,
  gateway; gofmt -l clean.
- mote: go test ./internal/claudetui: TestShimTurnsInteractive (a fake
  interactive Claude Code in the PTY: two turns, a /help pasted as
  words, the arguments it was given), TestShimFallsBackToPrint (failed
  start marks broken; untrusted folder doesn't), TestShimTrustsWhenTold,
  TestPasteable, TestTranslatorAPIError.
- mote: go test ./internal/gateway -run TestClaudeTUIChosen (plain,
  off, WSL, safeguards, cache marks, schema, image, long prompt),
  TestClaudeLean*, TestCleanClaudeEnv.
- mote: go test -timeout 45m ./internal/claudetui ./internal/cli
  ./internal/settings ./internal/gateway: all ok (gateway 524s).
  go test -run Budget ./internal/gui: ok after the raise below.
- Linux (magpie-desktop): go test ./internal/claudetui ok natively,
  the PTY's Linux ioctls among it. GOOS=linux go vet -tags nogui of
  cli, gateway, claudetui, settings ok.
- Linux box, Playwright 1.62, chromium and webkit: claude-tui-setting
  16/16, claude-lean-prompt-setting 16/16, i18n-keys 4/4, mobile-web
  30/30 against 74f1df869's tree. mote's WebKit didn't launch (other
  sessions' GUI suites, running 11-16h, held ~108 WebKit processes),
  so the GUI ran there instead.
- Real Claude Code 2.1.314 on a real Claude account's magpie config dir,
  haiku, through the built helper with the bridge's exact -p arguments
  (an MCP server named magpie with one tool, --tools "",
  --system-prompt-file, --thinking disabled, --effort low,
  --thinking-display): the tool was called without a permission prompt
  and its answer used; the system prompt's end token in every reply;
  a second turn on the same run; a later run with --resume remembered
  the first. All 18 transcript rows say "entrypoint":"cli". Startup to
  init 0.7–1.5s, a haiku turn 1.4–4s. Two messages sent at once are
  one turn, as Claude Code queues them.

Broken by hand:
- each claudeTUI condition taken out in turn (WSL, safeguards, cache
  marks, schema, images, the setting, the 400KB bound): its case red.
  The WSL case first passed with the check gone (its claudeCLI had no
  path); given one, it is red without it.
- the trust check taken out of ready(): TestShimTrustsWhenTold red
  (the run went to -p).

Not tried: a turn through a running gateway into the helper on a real
account (a sandbox HOME would copy the sign-in into a new keychain item
and refresh it apart from the live one); a ~400KB paste; Linux with a
real Claude Code; an API error from the real service (the translator
is tested on its rows). The full go test ./... did not run (mote was held by those suites);
the four packages this touches ran whole.
2026-10-31 03:20:45 +08:00

138 lines
3.9 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
}
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 {
Model string `json:"model"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
}
_ = json.Unmarshal(r.Message, &m)
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.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.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
}