Commit Graph
4 Commits
Author SHA1 Message Date
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
yetone 8215164296 claude: a branch is a cut copy of its run's session, in its run's mode (bbfatx on X)
A sub-agent's first request that answers calls another request already
answered branches off the lead's run's session (branch). That branch was
`claude -p --resume S --fork-session --resume-session-at U`, and
claudePrint forced every branch to -p, because Claude Code's interactive
mode ignores --resume-session-at (Claude Code 2.1.316 on mote: it resumes
the whole session). Runs are the interactive mode by default now, so the
lead's cache has the interactive prompt, and a -p branch of it read only
tools and system from the cache and wrote the conversation again
(measured on mote, sandbox HOME, 30 MCP tools: an interactive fork of a
-p session read only tools and system; the other way round was not
measured). With "Interactive only" no branch was made at all,
and the fork was told the whole conversation.

Now the branch's run copies the session's lines up to U into a new
session file next to it, with sessionId set to the copy's id
(cutSession), and resumes it with --resume <copy> in the mode its source
run had (savedSession.tui). claudePrint keeps "branch" only for a branch
of a -p run. Under "Interactive only" a -p run's session isn't branched.
The run owns the copy, as it owns an unshelved session. The copy waits up
to 2s for U's line to be fully written; if it never is, the turn is told
whole, as before. claudetui's translator now passes each assistant row's
uuid through, as -p does, so an interactive run's lines can be cut.
Measured on mote with real Claude Code 2.1.316: a cut copy resumed
interactively read 7648 and wrote 14; with -p it read 24009 and wrote 13.

Run (mote-run, this tree):
- go test -tags nogui -count=1 -timeout 30m -run 'Claude|Bridge|ToolChoice|Subscription|Retire|Rewrit|Fork|Branch|Shelf|Shelve' ./internal/gateway: ok 63s
- go test -tags nogui -count=1 ./internal/claudetui: ok
- go vet -tags nogui ./internal/gateway ./internal/claudetui; gofmt -l: clean

Broken by hand (each red, then put back):
- old claude_subscription.go and transcript.go (cutSession stubbed):
  TestClaudeForkBranchesOffTheLeadsSession interactive (branch ran -p),
  interactive only (told it whole), print (old flags),
  TestClaudeCutSessionCopiesAsFarAsTheLine and
  TestTranslatorTellsTheRowsUUID red
- claudePrint's branch reason for every branch again: interactive and
  interactive only red
- the copy taking the whole file: all three subtests and the cut test red
- branch() refusing every run under Interactive only: interactive only red

Not tried: a real fork sub-agent through the gateway. The cache numbers
come from copying by hand with real Claude Code; the tests use a
stand-in. Windows and WSL keep no session on disk, so they never
branch, as before.

Not taken from the suggestion: the fork's own runtime and TypeScript
wrapper. The cut is done here at the one place a branch starts.
2026-11-01 16:33:07 +08:00
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
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