Commit Graph
35 Commits
Author SHA1 Message Date
yetone 8fa3c60f80 claude: an interactive run takes many images between words (#5654)
Chapin2018's message of nineteen images between words (the issue's
script, Claude Code 2.1.319, claude-fable-5-1) ended the interactive
helper "after 13s (exit status 1)" and the client got a 502, while -p
answered. The cause is how the helper saw a paste taken. It looked for
"[Image #N]" and "[Pasted text #N" only in what Claude Code drew after
the paste. Once the prompt runs past a row, Claude Code draws it again
only where it changed and moves the cursor past cells that are already
right. After the 33rd piece the drawing held "\r\x1b[16C\x1b[1B3": one
digit of "[Image #33]". The helper waited out pasteWait (10s) and ended.
Text marks came out in part too ("[Pasted t xt #16"), so several word
pieces each sat out their own 10s before that. There is no limit in
Claude Code's TUI: the same paste is on its screen whole, so no -p
fallback is needed.

Each check now also reads the prompt as the 200x50 screen grid shows
it: the rows between its last two rules, words one space apart (a mark
can wrap onto the next row). The mark that ends it counts (lastMark),
an image's [Image #N] or a whole [Pasted text #N +k lines], numbered
past the piece before, and so do words the prompt ends with. The
stream check stays first.

Run:
- Real, macOS arm64, this Mac, sandbox HOME and CLAUDE_CONFIG_DIR
  (token by env, nothing rotated, DISABLE_AUTOUPDATER=1), the issue's
  script unchanged, --images 19, Claude Code 2.1.319:
  - origin/main a46190e1f: exit 1 after ~32s, stderr as reported.
    2.1.316 failed the same way. -p: success, 5.8s.
  - This change: exit 0 in 5.3 to 12.1s on 5 runs, subtype success.
    The transcript's user row has all 19 image blocks and the words in
    order, and the model answered. The script's answer_ok stays false
    because the helper's result line has no "result" text (-p's does).
    The gateway reads the assistant events, not that field.
- TestShimSeesPastesOnAPromptDrawnInPart feeds the real run's bytes
  (testdata/paste-images-2.1.319.bin, folder name replaced at the same
  length). Each of the 33 pastes must be seen taken.
- Broken by hand: drop the prompt checks from imageTaken and textTaken
  and it goes red on text 12, text 22 and image 33, the pieces whose
  marks were drawn in part.
- WSL magpie-desktop (Ubuntu 24.04 amd64, go1.26.8), because mote is
  down:
  - gofmt -l . is clean.
  - go vet -tags nogui ./... and GOOS=windows go vet ./... pass. Plain
    vet there lacks gtk4 headers.
  - go test ./internal/claudetui/ is ok (120s).
  - The darwin build used for the real runs above.

Not tried: Linux arm64 (the reporter's system) with a real account, the
gateway's /v1/messages path end to end with 19 images, and the full
suite (not run at push).

Refs #5654: kept open for the reporter to confirm.

Reported-by: Chapin2018
2026-11-08 18:24:16 +08:00
999ba6a00e claudetui: a replayed history keeps its words when one of its lines names an image file and an image follows (#5548)
#5548, Suge8 (magpie 0.1.3106, Claude Code 2.1.318, macOS, interactive
mode, Pi over OpenAI Chat): a compacted Pi conversation told whole to a
new Claude Code reached it as its four images and the closing notes
only; the history, which had `ls` output naming screenshots (a.jpg, …),
came into the next prompt, out of order.

Cause: send pasted a message's text piece and, without waiting for it
to show, the image after it; only the last text piece was waited for.
Claude Code 2.1.318 tries each pasted line ending in .png, .jpg, .jpeg,
.gif or .webp as an image file before it takes the words in (for a
relative name it asks the clipboard through osascript, about 0.45s),
and keeps one "pasting" mark for every paste. The image's read ended
first and cleared it, so the Enter after the closing notes sent the
prompt without the words.

Fix:
- send waits for every text piece to show before the next piece, not
  only the last one.
- shown counts a "[Pasted text #N" only with N past the paste before
  it, else the words' own last line: images and pasted text share
  Claude Code's numbering, so send keeps one number for both, and the
  prompt drawn again shows the earlier "[Pasted text #1". An inline
  paste (800 bytes and 2 line breaks at most) takes no number in
  2.1.318, so the number stays exact. A paste not shown within
  shownWait is still gone past, as before.
- Every paste goes through send, the WSL and queued (busy) messages
  too; a message of an image alone has no text to wait for, and one of
  text alone was already waited for.

Tests: the fake Claude Code now does what 2.1.318 does here: it draws a
long paste as "[Pasted text #N +B lines]" numbered with the images,
draws the prompt again as a paste starts, takes words naming an image
file in after 1s, and keeps one pasting mark (an Enter while it is set
is lost). TestShimWaitsForWordsNamingImages sends [words naming foo.png,
image, an ls naming bar.png and baz.png, image, closing notes], and the
same naming .txt files. TestShimPastesImages now expects its second
image as #3: the "and" between two images is 4 line breaks, pasted text
as 2.1.318 numbers it.

Run, at this tree on 9e6687e3, and again after a rebase on 30ae0e3f
(go vet and go test ./internal/claudetui/ ok, the new test red on its
old tui.go):
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- go test ./internal/claudetui/: ok (115s); with -race: ok (118s);
  the two image tests -race -count=10: ok.
- go test -tags nogui ./...: claudetui and the gateway's Claude tests
  ok. TestAlmaProvidersSeenDecodeOnce (agent), TestMarshalRawIsEncodingJSON,
  TestMarshalSizedIsJSONMarshal, FuzzMarshalRaw,
  TestServeWSLListensBesideLoopback (gateway) and TestPluginSOCKSProxy
  (plugin) fail on this machine (go1.27.3, HTTPS_PROXY set) at 9e6687e3
  without this change too; not looked into here.
- Real Claude Code 2.1.318 (claude-haiku-5-5) through a helper built
  from this tree, the issue's message driven straight into
  claude-tui-helper, in a sandbox CLAUDE_CONFIG_DIR: s-png (a line
  "foo.png") 3/3 and s-txt ("foo.txt") 2/2 recorded the whole prompt,
  807 chars, the words first and the image as [Image #2]. The old
  helper in the same setup, s-png 4/4: the words came after the image
  and the closing notes ("[Image #1] (The images…" first,
  imagePasteIds [1]); not lost this time, as the clipboard answered
  sooner than in the report.

Broken by hand:
- The old tui.go: TestShimWaitsForWordsNamingImages/.png fails, "Claude
  Code was sent "echo: [Image #1:red][Image #2:blue]\n\n(The images
  above are the tool's results.)\nReply with the codeword."", the
  words missing; /.txt passes.
- Each piece waited for, but shown taking any "[Pasted text #": both
  cases fail: the second image is missing, and with .png the ls too.

Taken from Suge8's own branch commit 15b05052 (byte-identical tui.go code
to the patch ggbdpq rebased on #5548; this one also carries the
subsystem doc and the fake's 2.1.318 numbering). The patch's
replay_image_test.go and its FAKE_SLOW_PASTE fake mode are left out:
they cover the same case as TestShimWaitsForWordsNamingImages with a
second fake.

Review run at this tree on origin/main 9700dd7cd (wsl-run,
magpie-desktop, Go 1.26.8):
- gofmt -l internal/claudetui, go vet ./internal/claudetui: clean
- go test -count=1 ./internal/claudetui/: ok (119s)
- -race -count=3 TestShimWaitsForWordsNamingImages|TestShimPastesImages: ok
Broken by hand: main's tui.go: TestShimWaitsForWordsNamingImages/.png
red, the words missing ("echo: [Image #1:red][Image #2:blue]...").
Known edge (Suge8's): the words' tail can match early when a piece's
last line equals an earlier piece's; it then goes on as before the fix.

Reported-by: Suge8
Co-authored-by: Suge8 <nnyless@foxmail.com>
Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-07 21:59:28 +08:00
yetone 325dc3ab32 claude-tui: a Claude Code that draws nothing is said with what it waits on, and its turn isn't waited out twice
sowhynot (v0.1.3222, macOS): every interactive run ended "Claude Code
showed no prompt in 45s: nothing on its screen (0 bytes read)", and the
bridge then started a new Claude Code told the whole conversation, which
waited out another 45s before the turn was answered 502.

Cause class: Claude Code blocks before its first draw on something it
waits for and writes nothing to the pty. Reproduced on mote with real
Claude Code 2.1.319 (npm latest) in a sandbox HOME: its read of the
"Claude Code" Keychain item is a synchronous `security
find-generic-password` with no time limit (its other Keychain reads have
2s/10s limits), so a Keychain waiting on an allow window or a locked
keychain gives exactly "0 bytes read" at 45s. Its network waits
(remote managed settings and policy limits, for a setup-token or team
account with --mcp-config) are bounded at ~30s and draw after, so they
don't give 0 bytes.

- claudetui: with 0 bytes read, the reason adds what Claude Code runs
  (its descendants from ps, longest first) and how much it holds; a
  Keychain read is named with its item and what to do. Other commands
  are named by program (and an interpreter's script) only, never their
  arguments. macOS and Linux; Windows says what it said before.
- gateway: a helper that ends saying why the interactive mode didn't
  come up is tuiNoStart, not tried again told the whole conversation,
  unless Claude Code ended itself before its prompt
  (claudetui.EndedEarly, the "No conversation found" case the retry is
  for).
- No early end on 0 bytes: a Keychain window may still be answered.
  No -p fallback: removed on purpose in e5f66f8a6, and -p waits on the
  same things.

Run (mote, at this tree on 05f6fd423; after the rebase onto 0978a6868, the new claudetui tests, TestShimNeverPrints, TestShimEndsAtItsCallersDeadline and -run TestClaudeTUI in gateway again: ok):
- go test -count=1 ./internal/claudetui/: ok
- go test -run 'TestClaudeTUI' ./internal/gateway/: ok
- go test -run 'TestClaude|TestSubscription' ./internal/gateway/: ok
- wsl-run (magpie-desktop): the new claudetui tests and
  TestShimEndsAtItsCallersDeadline: ok
- go vet darwin, GOOS=linux and GOOS=windows -tags nogui for
  claudetui and gateway: ok
- real Claude Code 2.1.319 under the rebuilt helper, sandbox HOME, a
  `security` on PATH that never answers: "...(0 bytes read); it waits on
  the macOS Keychain, whose `security find-generic-password` read of
  "Claude Code" hasn't answered in 33s: ..."

Broken by hand: with undrawn's result dropped,
TestShimSaysWhatAnUndrawnClaudeWaitsOn fails both cases; with the
gateway check off, TestClaudeTUINoPromptNotTriedAgain/no_prompt fails
"the helper started 2 times, want 1".

Not tried: a real Keychain allow window or a locked keychain, the
reporter's own machine (unconfirmed it is the Keychain; Gatekeeper or
endpoint software holding the exec fits the 51s too), a real Pro or
team account, Windows (no ps read there).

Reported-by: sowhynot
2026-11-07 15:17:47 +08:00
yetone 82403f9f6d claude: /usage is read through -p, never the interactive mode, which opened idle accounts' 5-hour window (#5582)
Since v0.1.2635 (ccd746e03), when the interactive mode is on (the
default), magpie read the plan's allowance by starting the interactive
Claude Code in its helper and typing /usage there (claudeUsageTUI). The
interactive Claude Code 2.1.316 sends a model request as it starts,
before anything is typed. That is probeQuotaStatus: haiku, max_tokens 1,
content "quota". It sends it unless CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC
is set, and that variable also keeps /usage from loading. The request
counts, so on an account with no 5-hour window it started one. The
reporter's reads came at magpie's start and when a window ended, and
each opened a window with warm-up off. Their counterexample (11-01,
v0.1.2433, before ccd746e03) read /usage through -p and opened nothing.

Recorded (sandbox HOME and CLAUDE_CONFIG_DIR, a fake sign-in, the real
Claude Code 2.1.316 behind a recording proxy that answers everything
itself, so no account was spent):
- magpie's interactive args and env, in a pty. At start, before /usage
  was typed:
  POST api.anthropic.com /v1/messages?beta=true
  {"model":"claude-haiku-4-5-20251001","max_tokens":1,
   "messages":[{"role":"user","content":"quota"}],...}
  then GET /api/oauth/usage once /usage was typed.
- The same with CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1: no POST, but
  no /api/oauth/usage either, and the panel says "Failed to load usage
  data". This can't be the fix.
- `claude -p /usage` with claudeUsageArgs and claudeUsageEnv: no
  /v1/messages at all, only GET /api/oauth/usage (plus profile and
  bootstrap GETs). It printed "You are currently using your subscription
  to power your Claude Code usage" / "Current session: 13% used · resets
  Nov 7 at 4pm (Asia/Shanghai)" / "Current week (all models): 4% used ·
  ...". ccd746e03 said -p's /usage tells only the session's cost. In
  2.1.316's source that is only for a sign-in without a subscription or
  the user:profile scope, such as a setup-token, which provider never
  reads (errClaudeSetupToken), or an API key.

Fix: claudeUsage always runs `claude -p /usage`, with the interactive
mode on or off. claudeUsageTUI and claudeTUIUsageArgs are gone. This is
the one choke point (provider.UsageClaudeVia -> runClaudeUsage) for
every magpie read of Claude usage: the signed-in account's card,
saved accounts (readSavedClaudeUsage), the 8-day keep-alive, the
used-up switch's spare reads and refreshes. The other interactive
starts are the bridge's turns, the warm-up and the model test. Each one
sends a model request the user asked for, and each runs with
cleanClaudeEnv's CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1, so the
startup probe isn't added there. Not changed: claudetui still takes a
typed /usage, and magpie no longer sends it.

Docs: docs/subsystems/claude-subscription-bridge.md says why and
removes the wrong -p claim. The comments in claude_warmup.go, tui.go
and claude_usage_cli.go are updated to match.

Tests: TestClaudeUsageStartsNoInteractiveRun replaces
TestClaudeUsageTUIOn, TestClaudeUsageTUIWorksInMagpiesFolder and
TestClaudeUsageTUISaysItsDeadline. With the interactive mode on, it
checks that a read of the signed-in account and of a saved one starts
no helper, runs -p /usage, and leaves the traffic variable off. The
"usage" rows of TestClaudeOneOffTrustsMagpiesFolder and
TestClaudeOneOffFailureLogged are removed, since a /usage read is no
longer an interactive one-off run. Their "test" rows stay.

Run (mote, at this tree on origin/main 665b9aff1; after the rebase on 9e6687e3a, vet and claudetui plus gateway's ClaudeUsage|OneOff|Trust|TUI tests again: ok):
- gofmt -l internal/gateway internal/provider internal/claudetui: clean.
- go vet for darwin, and for linux and windows with -tags nogui:
  ./internal/gateway ./internal/provider ./internal/claudetui ok.
- On mote: go test -count=1 -timeout 45m ./internal/provider ./internal/claudetui: ok (114s, 110s);
  go test -run 'Claude|Usage|Warm|Trust|OneOff|TUI|Shim|Guard|Loop|Budget' ./internal/gateway: ok (89s).

Broken by hand: with HEAD's claude_warmup.go (its claudeTUIOn branch
back) and the new test, TestClaudeUsageStartsNoInteractiveRun went red:
"a /usage read started the interactive Claude Code: claude-tui-helper
.../claude -p --output-format stream-json --input-format stream-json ...".

Not tried: a real account's -p /usage on this build. The windows output
above comes from the recorder's fake usage reply, and the reporter's
v0.1.2433 readings came from -p. Not tried: an Enterprise account whose
usage reply leaves the windows out. -p then prints only the
subscription line, which reads as "temporarily unavailable" and keeps
the last reading, where the interactive panel had said no window has
started. Not run on Windows or in WSL. The -p read there is the same code
(claudeUsage); the interactive read had run on Windows too.
Not run: the full ./... suite (mote's suite.lock had four full runs
queued).
2026-11-07 11:52:30 +08:00
yetone 9e6687e3a5 claudetui: the Claude in Chrome offer is declined once it has stayed drawn, and an error never ends on an empty screen
sowhynot (Discord, magpie 0.1.3216, Claude Code 2.1.319, macOS, Claude
Pro, interactive mode): every request and the endpoint test failed with
"claude-tui: Claude Code showed no prompt in the 21.9s its caller waits
for it:" and nothing after the colon; `claude -p` worked.

Cause: where the Claude in Chrome extension is installed and Claude
Code's tengu_chrome_auto_enable flag is on, 2.1.319 opens its
ChromeAutoEnableDialog as it starts (a claude.ai sign-in, no answer
recorded). The helper cleared its screen and sent Esc the moment it saw
"keep browser tools off". The dialog turns away a key that comes just
after it opens (refuseInput/refusedWithin) and draws nothing again for
it, so the screen the helper read stayed empty: nothing matched again,
the run waited out its caller, and lastScreen() had nothing to say. The
decline is never recorded, so every run met it again.

Fix:
- The offer is answered through onboard(): Esc once it has stayed drawn
  trustSettle, at most onboardTries times, then an error that says the
  offer takes no answer.
- seen(): with nothing drawn since the screen was cleared for
  redrawWait (1.5s), ready() reads the screen as it stands (the grid),
  so a key lost to a dialog that draws nothing again is sent again.
- What the run hadn't done is read from the screen as it stands too:
  "asked whether to use Claude in Chrome, not answered".
- lastScreen(): with nothing drawn since a clear it gives the grid's
  text, and with nothing on it, "nothing on its screen (N bytes read)".

There is no -p fallback for the one-off runs (the endpoint test, a
/usage read) by design: the shim never turns into -p (TestShimNeverPrints).

Run, on mote at this tree (base 665b9aff1):
- go test -count=1 ./internal/claudetui/: ok (118s).
- go vet ./internal/claudetui/ for darwin, linux and windows; go build
  ./... (darwin), GOOS=windows go build ./..., GOOS=linux go build
  -tags nogui ./...: ok. gofmt -l: clean.
- win-run (xiaomi-gpu): TestShimDeclinesChromeOffer,
  TestShimEndsAtItsCallersDeadline, TestShimNeverPrints,
  TestShimGoesThroughOnboarding: ok.
- Real Claude Code 2.1.319 (npm) through this helper in sandbox HOMEs on
  mote: onboarded, classic and CLAUDE_CODE_NO_FLICKER=1 renderers, init
  emitted; folder not trusted (MAGPIE_CLAUDE_TUI_TRUST=1), and
  onboarding not done (theme, notes) plus trust: gone through to the
  prompt, the message sent (401 on the fake API key, as expected).

Broken by hand:
- The old tui.go with the new tests: TestShimDeclinesChromeOffer waits
  30s with no answer; TestShimEndsAtItsCallersDeadline/chrome offer
  unanswered gives "showed no prompt in the 3s its caller waits for it: "
  with nothing after it, the reporter's line.
- seen() never reading the grid: TestShimDeclinesChromeOffer red (the
  fake turns keys away for 700ms, past the first Esc).

Not tried: the Chrome offer itself in a real 2.1.319. It needs a
claude.ai OAuth sign-in whose token /api/oauth/validate accepts, the
extension's folder in a Chrome profile and the GrowthBook flag on; no
sign-in is available on mote. The fake draws 2.1.319's dialog text and
its refusal is modelled on the dialog's source. Not run: the full
go test ./... before the push (it runs after, as the rules say).

Reported-by: sowhynot
2026-11-07 11:27:58 +08:00
yetone 77031d5817 claude usage: a /usage panel with no window is no window started, and a failure says why
koohoko5924 (Discord #help, v0.1.3057, macOS): a Claude Enterprise
account with a five-hour window only. A manual refresh took ~5s and
gave the card no window and the error "Claude Code's usage showed no
usage figures: ▐▛███▜▌ … magpie-claude-work…": Claude Code's banner,
not a reason.

Claude Code 2.1.316's Usage tab (gi) draws a window only once
Anthropic's answer has it non-null, and a window is null until the
request that starts it. An idle 5h-only account's panel loads with
the session's cost, maybe the plan's credit bar, and no window. The
helper told that panel's words, joined from the top of the screen, and
the card took them as a failure with the banner first.

- claudetui: a panel that loaded (tabs, Session/Total cost, nothing
  loading, refreshing, stale or failed, no gateway Spend limit) with no
  "Current session"/"Current week" is told as NoUsageWindow ("No usage
  window has started"). The provider reads that as no window started:
  no error, the unstarted 5h window as for any account.
- claudetui: the two rate-limit errors gi draws ("Claude is temporarily
  limiting requests to the usage page (not your usage limit)…",
  "Usage endpoint is rate limited until …") are failures to load, like
  "Failed to load usage data": retried once, then told as an error with
  the panel's own "Error: …" text, never the banner. A panel with no
  window and no error is told from its tabs on, the session's cost
  lines left out.
- provider: "(not your usage limit)" no longer reads as an account
  refused (claudeDenied, at every place claudeUsageDenied judged a
  reading: the CLI parse, codex_switch, quota_last, subscription_usage).
  Counts ("Last 7d · 403 requests …") are taken out wherever they sit in
  a line before that check, as the panel's words come on one line now.
  A no-figures error keeps every line (600 runes), not the first clipped
  at 120.

Tests are built from 2.1.316's own strings (ko/gi/hi in the bundled
cli.js), drawn on the helper's 200x50 grid row by row. Guessed: the
exact bytes of a real Enterprise panel (not captured; no such account
here) and the credit bar's layout.

Run (mote, at this tree): go test ./internal/claudetui ./internal/provider
-run 'Usage|Claude|Shim|Quota|Codex' ok; go vet for claudetui, provider,
gateway; GOOS=linux -tags nogui and GOOS=windows go vet; gofmt -l clean.

Broken by hand (each red, then restored):
- the NoUsageWindow case off: TestShimReadsUsageWithNoWindow red in all
  three panels (told the panel's words as success);
- the provider's claudeNoWindow branch off: TestClaudeUsageNoWindowStarted
  red ("showed no usage figures: No usage window has started");
- claudeDenied back to claudeUsageDenied: TestClaudeUsageWhyKept red
  ("read as an account refused");
- usageFailed back to "Failed to load usage data" and the whole screen as
  the reason: TestShimToldWhyUsageFailed red in all three (the banner as
  the reason; the rate-limit panels told as no window), TestUsageNoWindow
  red.

Not tried: a real Claude Enterprise account; a real rate-limited panel.
2026-11-06 06:30:23 +08:00
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
ggbdpq 6b4a6dcd41 claudetui: the Bypass Permissions disclaimer is answered as the trust question is (#5042, luzhuang)
A claude magpie spawns runs --dangerously-skip-permissions: the flag is
on the bridge's own arguments, a user's claude may be a wrapper that
adds it, and an account's default mode may be Bypass Permissions. Where
no settings source the run reads has skipDangerousModePermissionPrompt,
Claude Code 2.1.295 blocks on its disclaimer — "❯ No, exit / Yes, I
accept, Enter to confirm" — and no one was there to answer it: each run
sat on the dialog for 45s (ReadyWait), ended, and the next run asked
again, so interactive requests failed in a loop (502 or a hung restart)
until magpie fell back to claude -p.

- the helper tells the disclaimer yes where TrustEnv says so, with the
  same ↓-until-"Yes"-then-Enter the trust question gets (its "No, exit"
  pairs the same, and a key sent as it is first drawn is lost the same
  way); Claude Code records the acceptance itself, and the next run is
  shown none of it.
- where TrustEnv isn't set — the account Claude Code is signed in to, in
  a caller's folder — the disclaimer is the user's to answer: the run
  ends at once saying so, not after 45s.
- a disclaimer left unanswered at a run's deadline is named as such
  ("asked to accept running in Bypass Permissions mode, not answered"),
  never "showed no prompt".

Generated-by: GLM-5.3-Flash (ZCode)

Reviewed and ported, narrowed: as written, the shim accepted the
disclaimer wherever TrustEnv was set, and the bridge sets TrustEnv for
magpie's own folder in the account Claude Code is signed in to
(configDir ""), as do the warmup and /usage runs. Accepting there makes
Claude Code write skipDangerousModePermissionPrompt into the user's own
~/.claude/settings.json, a consent for every run after that is the
user's to give. Now a separate claudetui.BypassEnv says yes, set only by
claudeBypassEnv for a tui run in an account folder of magpie's
(configDir != ""), at the bridge and both warmup sites; TrustEnv alone
ends the run at once with the "asks to accept" message. The subject's
"as the trust question is" holds for the keys sent, not for where.

On mote, with tui.go at the parent: TestShimAcceptsBypassDisclaimer FAIL
("the shim wrote 0 lines of 3 in 30s"), TestShimNeverPrints' bypass
cases FAIL ("neither answered nor ended in 30s"),
TestShimEndsAtItsCallersDeadline/bypass_disclaimer_unanswered FAIL
("showed no prompt"); green with the patch. Broken by hand: the gate
back on TrustEnv turns TestShimNeverPrints/bypass_disclaimer_with_the_
folder_trusted red, and claudeBypassEnv ignoring configDir turns
TestClaudeBypassOnlyInMagpiesAccountFolder red ("user's own account: got
[MAGPIE_CLAUDE_TUI_BYPASS=1]"). go test -timeout 45m ./internal/gateway
and ./internal/claudetui ok; GOOS=linux/windows/darwin go vet ok. Not
tried: a real Claude Code 2.1.295 showing the disclaimer under a saved
account (needs a wrapper adding the flag).

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-05 18:31:17 +08:00
yetone fe6533ad8b claudetui: Claude Code's exit is recorded once its last words are read (#5283)
The shim closed `exited` as soon as cmd.Wait returned, which can be
before the PTY reader has read what Claude Code wrote just before it
ended. Every "Claude Code ended ..." error then carried an empty screen
in place of the reason it gave, which is what TestShimNeverPrints/
failed_start saw on a loaded ubuntu CI runner (run 41899504898):
"ended before it showed its prompt (exit status 3): " with no
"something went wrong". The shim's own stderr line is meant; the test
checks the reason is in it.

Now the exit goes through shim.ended: on Unix it waits for read to end
(the master reads EIO once the last slave writer is gone), on Windows,
whose pseudo console stays open, until reading has gone quiet for 250ms
after its first bytes; two seconds at most either way, for a terminal a
child of Claude Code keeps open.

Run:
- Red before: with a 200ms sleep injected at the top of read(), the old
  code failed failed_start 5 of 5 on Linux (wsl-run, magpie-desktop)
  with CI's exact message; with the fix and the same injection, 50 of 50
  green. Without injection the old code passed 300 of 300 there (an
  idle machine never loses the race).
- New TestShimEndedAfterLastWordsRead (a reader given the last words
  300ms late, terminal ending and staying open). Broken by hand (ended
  records at once): red on both subtests; restored: green 20 of 20 with
  TestShimNeverPrints on Linux.
- internal/claudetui: Linux (wsl-run) -count=3 ok; macOS (mote-run)
  -race -count=2 ok; Windows (win-run) -count=2: only
  TestShimFirstMessageWaitsForTools red, the same at origin/main
  49e382735 without this change (#4810, commented).
- go vet ./internal/claudetui with GOOS darwin, linux, windows (mote).
- gofmt -l clean.

Not tried: a real Claude Code ending before its prompt (only the fake);
the Windows quiet rule on a really slow ConPTY reader.
2026-11-05 04:54:38 +08:00
yetone dd61299231 claudetui: /usage's saved figures, drawn while Claude Code refreshes them, are not told as today's
jsc9495 (Discord #help, 0.1.2950+, Claude Max): on one account at one
moment magpie's card said 5h 92% / 7d 99% left, another app 53% / 94%.

Claude Code 2.1.316's /usage panel draws the figures it saved on its last
read (cachedUsageUtilization in .claude.json, used up to an hour old,
keyed by accountUuid) at once, with "Refreshing…" under them, while it
asks Anthropic for today's. When that fails it keeps them and says
"Showing last-known usage as of 20m ago (rate limited until …)" or
"… (could not refresh)". The helper took any figures that stood still
for a second as the answer, so with a refresh slower than 1s, or a
rate-limited or failed one, each read told the figures of the read
before it (up to an hour old) stamped with the time now.

Now "Refreshing…" is waited past (up to commandWait). A panel that is
still refreshing at that point, or that shows last-known usage, is told as
"/usage couldn't load the plan's usage: …". claudeUsageUnknown already
matches that, so the card keeps its own last reading and that reading's
time. Figures Claude Code seeds from this session's own reply headers
("Partial usage data", "Per-model breakdown unavailable", "Could not
refresh usage data") are current and are still reported.

Fixtures are real bytes. Claude Code 2.1.316 ran on mote in a sandbox
CLAUDE_CONFIG_DIR with a made-up sign-in and saved figures 20 minutes
old (8% / 1%), and /usage was typed through a pty. It drew "Refreshing…"
and then "Showing last-known usage as of 20m ago (rate limited until
12:11am)". No real account was used, and no Keychain or live config was
touched.

Run (mote-run, at this tree on f280b12e5):
- go test ./internal/claudetui/ -count=1: ok.
- go test ./internal/provider/ -run Claude: ok.
- go test ./internal/gateway/ -run 'ClaudeUsage|ClaudeTUI': ok.
- GOOS=linux and GOOS=windows go vet ./internal/claudetui/: ok.
- gofmt -l: clean.
- win-run on xiaomi-gpu, TestShimWaitsPastSavedUsage and
  TestShimWaitsForUsageFigures: ok.

Broken by hand: with HEAD's tui.go, TestShimWaitsPastSavedUsage is red in
both subtests. Each tells "Current session: 8% used", the saved figures,
as a success.

Not tried:
- A real account's refresh. The redraw after a successful refresh is the
  earlier usage-2.1.316.bin capture on a cleared screen, not a captured
  redraw.
- A panel still "Refreshing…" after 20s; it takes the same error path.
- Why the other app's 7d figure read lower on jsc9495's second account.
2026-11-04 23:19:21 +08:00
yetone 59c1306035 claude: an auto-mode client's tool loop keeps its interactive run (#4804)
Auto mode's safeguards change with every tool batch: prior_turn_context
grows by the turn before. An interactive Claude Code run read them once,
from CLAUDE_CODE_EXTRA_BODY in its environment as it started. So a tool
loop either started the run again (the whole conversation written to the
cache again), or kept it and sent the classifier the context it started
with, which is not what real Claude Code sends.

Each turn's safeguards now reach the running run:
- The bridge writes the extra body to <run tmp>/guard.json and hands its
  path to the helper as MAGPIE_CLAUDE_GUARD (mapped for WSL in newTap).
- tap.js, on each /v1/messages request whose string body has a
  safeguards key, reads the file and puts its safeguards in the body. It
  also sets CLAUDE_CODE_EXTRA_BODY to the file's text, so Claude Code's
  own later reads agree. The first time, it writes guard.json.live.
- setSafeguards rewrites the file (temp and rename, retried for Windows)
  instead of restarting, once .live exists. Without .live (a Claude Code
  that doesn't load the tap), it falls back to the old rule: keep the run
  when only the varying parts changed, otherwise restart. A beta change,
  or safeguards appearing or going, still restarts.
The tap changes only the safeguards value; any other byte of the body is
Claude Code's own. Bodies without safeguards, count_tokens and non-string
bodies are passed through untouched.

The tool-results path logged "process expired" alone while the run's end
read "magpie ended it". It now aborts the run with the reason and logs
"tool results process expired: <reason>". continueWith's "not waiting for
tool results" does the same.

Tests:
- TestClaudeTUIToolLoopCarriesEachBatchsSafeguards: three tool batches
  with growing prior_turn_context, then the answer. Checks one run and
  that each request carried its own batch's safeguards.
- TestClaudeTUIToolResultsLogWhyTheRunEnded: no tap and the rules change.
  Checks that the log has the reason.
- TestTapPutsTheGuardFilesSafeguards (bun and node): the rewrite, the
  bodies left alone, the env, and .live.
- TestTapEnv: MAGPIE_CLAUDE_GUARD is passed through, WSL-mapped.

Run (worktree at c360d9d30 + this change):
- mote: go test -run 'TestClaudeTUI|TestClaudeBridgeSafeguard|
  TestClaudeToolResults|TestClaudeNoRunSaysWhy' ./internal/gateway ok
  (73 PASS); go test -run TestTap ./internal/claudetui ok (bun and
  node); go vet ./internal/claudetui ./internal/gateway on darwin, linux
  and windows ok; gofmt -l internal clean.
- Full suite, go test -timeout 45m ./..., ran on the Linux box (wsl-run,
  magpie-desktop), not mote. mote had two other sessions' GUI suites
  sitting at 0% CPU for 3h42m at load 300, and one suite per machine.
  Result: 80 packages ok, internal/claudetui ok. Red:
  - TestGrokInstalled (#3548)
  - TestCodexBodyLimitFromMemory (#5118)
  - TestMoveCutShort (#5119)
  - TestCCListingKeepsItsNames (#4925)
  All four are red the same way run alone at origin/main d8b3749ef on
  that box. Root, internal/cli and internal/gui don't build there
  without GTK4 (#5120).
- Real use, macOS:
  - Sandbox HOME and CLAUDE_CONFIG_DIR, the owner's Max account copied
    to the sandbox dir's keychain item and deleted after. The refresh
    token didn't rotate.
  - A gateway on 127.0.0.1:3496; magpie built -tags dev at c360d9d30
    (before) and with this change (after).
  - Client: real interactive Claude Code 2.1.316 in tmux,
    --permission-mode auto, sonnet 5.5 through the gateway.
  - One turn, three sequential Bash calls (echo one, ls -la, echo three),
    four upstream requests.
  - Before: one run (pid 49488), cache_write 23005/86/162/86 (the first
    request cold). Its CLAUDE_CODE_EXTRA_BODY stayed the first request's
    safeguards, with no prior_turn_context, so requests 2 to 4 sent the
    classifier stale context.
  - After: one run (pid 64000), cache_read 23005/23091/23091/23253,
    cache_write 0/0/162/86. guard.json.live was written; the tap logged
    3 "guard":"set" (requests 2 to 4), and guard.json ended with 3
    prior_turn_context entries.

Broken by hand:
- The old claude_subscription.go makes both gateway tests red ("request
  0 carried ..."; the log said "tool results process expired" alone).
- tap.js without the rewrite makes TestTapPutsTheGuardFilesSafeguards
  red in bun and node.

Not tried:
- A tool loop whose rules change mid-loop with a real client (restart
  path; only the fake covers it).
- Linux or WSL with a real Claude Code (the TUI isn't used on Windows).
- Comparing the before/after upstream bodies byte for byte (the tap
  logs that it set the value, not the bodies).
- The gateway package as its own -timeout 45m run on macOS: only the
  targeted tests ran on mote, and the full package ran on Linux.
2026-11-04 06:38:56 +08:00
yetone 3d7b1233dd claudetui: /usage's screen is read at the terminal's own 200 by 50 on macOS and Linux (#4988, shinnqy on X)
shinnqy on X: in the latest magpie Claude Code's usage doesn't load.
#4988 (0.1.2776, macOS, Team plan): the card said 100% / unused, and
`magpie quota refresh claude` gave one window, "7 days · Fable" 0%, while
the account's 5 hours were 29% and 7 days 17% used.

Cause: 3a74cd92e reads /usage's panel off a terminal grid (screen.go) and
prefers that look of it over the stream. screenSize() made the grid 80 by
24 everywhere but Windows, saying "a pty here is given no size", but
child_unix.go makes the pseudo-terminal 200 by 50. Claude Code draws the
panel at the foot of its 50 rows; on the 80 by 24 grid every row under the
24th was clamped onto the 24th and drawn over it, so the kept look of the
panel held one window (the last drawn), or a figure redrawn in place was
lost to the stream's older one.

Fix: one screenCols/screenRows (200 by 50) for the Unix pseudo-terminal,
Windows' pseudo console and the grid. Windows is unchanged.

Test: TestShimReadsUsageBelowTheTwentyFourthRow, a 200 by 50 panel with
three windows drawn as 2.1.316 draws (ESC[H, CR + ESC[nB, ESC[55G), then a
frame that redraws only the session's figure (29% -> 30%). fakeFrames now
splits frames at a 50-row foot (ESC[50;1H) as well as ESC[24;1H.

Run at this head (mote): gofmt -l internal/claudetui clean; go vet
./internal/claudetui with GOOS darwin, linux, windows ok; go test
./internal/claudetui ok; go test -run 'Claude|Usage|TUI' ./internal/gateway
./internal/provider ok. xiaomi-gpu (win-run): -run
'TestShimReadsUsage|TestGrid|TestShimWaits' ./internal/claudetui ok.

Broken by hand: the new test on origin/main's tui.go (80 by 24 grid) is
red, telling "Current session: 29% used" for the redrawn 30%; green with
the fix.

Not tried: a real Claude Code panel with figures at 200 by 50 on macOS
(no real-account run in a sandbox; the fixture is synthetic, in 2.1.316's
encoding). The report's "messages can't be sent" half is not explained by
this: nothing here touches the request path, and no log came with it.
2026-11-03 12:51:31 +08:00
yetone 3a74cd92e8 claude: /usage waits for its figures, and a read without them is unknown
Seagull fries (haioushutiao, Discord #help; magpie 0.1.2704, Claude Code
2.1.316, Windows 11, Claude Pro): the Claude card said 暂时无法获取额度,
"Claude Code's /usage told no allowance: ❯ /usage ─── Settin s Status
Config Usage …". Reproduced with a real Claude Code 2.1.316 under
Windows' pseudo console in a sandbox: /usage's panel is drawn first with
"Loading usage data…" while Claude Code asks Anthropic for the figures
(5s timeout, retried only on a 401), and the helper took 3s of a still
screen as the panel drawn whole. On a slow answer it told the panel's
frame as the result, and parseClaudeUsage called any text with no window
"told no allowance". A failed load ("Error: Failed to load usage data",
"r to retry") went the same way.

claudetui:
- screen.go: a small terminal grid (CUP/CUU..CHA/VPA, EL, ED, ECH, CR/LF
  with scrolling, OSC/DCS skipped, an escape or UTF-8 character cut
  between reads kept), 200x50 on Windows as the pseudo console is made,
  80x24 elsewhere. The pseudo console sends only the cells that changed,
  skipping a cell that holds the same letter ("Settin\x1b[1Cs"), so the
  stream read split words and kept a redrawn digit beside the old one.
  While /usage is read, each look of the screen with a window is kept
  (panel), and usageText reads that before the stream.
- command(), built on b4073c06a's wait for the panel (ikunbots; its
  usageDrawn and "hadn't drawn" error kept, now also judged on the grid,
  since the pseudo console's split "Settin s" never matched its tabs):
  "Loading usage data" on screen is waited out (to
  commandWait, s.doing "was still loading /usage's figures" for the
  deadline message); "Failed to load usage data" gets one "r"; a panel
  still with no figure and loading or failed on screen is an
  error_during_execution result, "/usage couldn't load the plan's usage:
  <screen>".
- the fake draws the panel a frame at a time (fakeFrames), as Claude Code
  does: with one write, the pseudo console passed on only the last
  frame, which no longer shows the windows. TestShimReadsUsage now passes
  on Windows (#4820, the fake's side; a real panel with figures was not
  seen on Windows, see below).

provider:
- parseClaudeUsage: a panel with no figure is "Claude Code's /usage
  showed no usage figures: …", not "told no allowance" (kept for
  claudeUsageDenied's refusals).
- claudeUsageUnknown: Claude Code's "temporarily unavailable" and the
  helper's "couldn't load the plan's usage" keep the account's reported
  reading (quota_last), as the first did alone before. Other no-figure
  text is still shown as an error (TestClaudeHeaderSurvivesUnclassified-
  UsageFailure, TestClaudeUsageReadingAloneDoesNotHideUnclassifiedFailure
  hold that).

Fixtures are the reporter's case as the pseudo console passed it on for
the real 2.1.316 (a temporary dump of the helper's screen bytes, sandbox config,
proxy that never answers / refuses): testdata/usage-loading-win-2.1.316.bin
and usage-failed-win-2.1.316.bin.

Run at the pushed head:
- mote: go test ./internal/claudetui ./internal/provider ok; go test
  -run 'Claude|Usage|TUI' ./internal/gateway ok; GOOS=darwin/linux/
  windows go vet ./internal/claudetui ./internal/provider ok; gofmt -l
  clean.
- xiaomi-gpu (win-run): go test ./internal/claudetui: all pass except
  TestShimFirstMessageWaitsForTools, red on Windows at main (#4810).
- xiaomi-gpu, real Claude Code 2.1.316 (npm), sandbox CLAUDE_CONFIG_DIR
  with a fake token, magpie.exe built from this tree, helper run as the
  gateway runs it: a proxy that never answers gives is_error "/usage
  couldn't load the plan's usage: … Settings Status … Loading usage data…"
  after the 20s wait (was a success with the chrome); a refused proxy
  shows "Failed to load usage data", "r" is pressed, and the same error
  comes back in 6.6s. "Settings" is whole now.

Broken by hand (before the rebase onto b4073c06a; the merged loop is
re-checked below):
- old tui.go: TestShimWaitsForUsageFigures slow, retried and failed again
  all red, each telling the reporter's chrome as success.
- the "r" not written: TestShimWaitsForUsageFigures/retried red.
- old parse message: TestClaudeUsageWithoutFiguresIsUnknown red ("told
  no allowance"); old quota_last check: its couldn't-load cases red.
- after the rebase, on the merged loop: the "r" not written,
  TestShimWaitsForUsageFigures/retried red; the old "anything still 3s"
  in place of usageDrawn on the grid, TestShimWaitsPastTheBanner red.

Not tried: a real account (the box has none of the owner's), so a real
2.1.316 panel with figures was never seen through the pseudo console;
whether Claude Code's frames that show the windows reach the pseudo
console's output before it renders the next one is shown only by the
fake. Not taken: asking Anthropic's /api/oauth/usage, which the owner
ruled out (9bf6d4352).
2026-11-03 05:16:40 +08:00
yetone b4073c06a0 claude-tui: /usage waits for its panel, never takes Claude Code's banner as it (ikunbots on X)
ikunbots (v0.1.2738) showed a Claude card saying "Claude Code's /usage
told no allowance: ▘▘ ▝▝ /private/var/folders/…/magpie-claude-work-501
────". After /usage is typed, Claude Code draws itself again (banner,
folder, the prompt's rules) before the panel. A slow /usage leaves that
still, and the helper took any screen still for 3s as the panel, so the
banner was told as /usage's answer and parsed as an error.

Now a screen without "NN% used" counts as drawn only when the panel's
Settings tabs show and nothing says loading (usageDrawn). With no panel by
commandWait (or the caller's deadline), the result is an error naming what
was last drawn, never a success carrying the banner.

Run (on mote):
- go test ./internal/claudetui/: ok (new TestShimWaitsPastTheBanner: the
  fake draws the reporter's banner, then the 2.1.316 panel 4.5s later;
  TestUsageDrawn; a "banner, no /usage panel" case in
  TestShimEndsAtItsCallersDeadline).
- Broken by hand (old "anything still 3s" condition back):
  TestShimWaitsPastTheBanner red, told the banner as the result, as in the
  report.
- go test -run 'Usage|TUI' ./internal/gateway/ ./internal/provider/: ok.
- GOOS=darwin/linux/windows go vet ./internal/claudetui/ ./internal/gateway/: clean; gofmt clean.

Not tried: a real slow /usage on a real account; the "loading" word is
a guess at the panel's loading text, which only keeps waiting longer.
2026-11-03 02:41:17 +08:00
yetone e7185daebe claude: a failed interactive read says why in app.log, and names the trust question (#4830)
mydosu (#4830) found nothing in app.log to say why every /usage read and
test of a saved account failed, and the card's reason, "showed no
prompt", said nothing of the trust question Claude Code was waiting on.

- claudetui: when the helper's deadline comes while Claude Code shows
  "trust this folder", the reason is "Claude Code asked whether to trust
  <folder>, not answered in the 16.8s its caller waits for it: <screen>".
  Any other screen keeps "showed no prompt".
- gateway: askClaudeTUI and claudeUsageTUI log a failure to app.log
  (logOneOff): "claude: a /usage read of saved account <dir> failed: ...",
  with the helper's whole reason on one line, which the card clips to 300
  bytes. The home folder and any /Users/<name>, /home/<name> or
  C:\Users\<name> become ~, secrets go through redact.Scrub, and past
  800 bytes the line keeps the first 300 and the last 500, so the end of
  the last screen stays.
- docs/subsystems/claude-subscription-bridge.md says both.

Run at this head (mote, rebased on origin/main; the gateway set re-run
with Upstream|Unsent|Routing added after the rebase): gofmt -l clean; go vet for claudetui and
gateway, and GOOS=linux and GOOS=windows go vet for claudetui, gateway
and provider: ok. go test -count=1 -timeout 45m ./internal/claudetui
./internal/provider: ok. ./internal/gateway -run
'Claude|TUI|Usage|Warm|Ask|Trust|Subscription|Bridge|OneOff': ok.
Windows (win-run): ./internal/claudetui ran with the new trust_unanswered
case passing through ConPTY; TestShimFirstMessageWaitsForTools and
TestShimReadsUsage are red there, the same at origin/main f849ccced
(#4810, #4820). TestClaudeOneOffFailureLogged skips on Windows (a shell
script helper).

Broken by hand, each red: no logOneOff call (app.log says nothing); no
home and path masking (the line has the home folder and "mydosu"); no
redact.Scrub (the token's body is in the line); no head/tail cut (1530
bytes); no trust wording in ready() (trust_unanswered says "showed no
prompt").

Not tried: a real failing read on mydosu's Windows machine; the full
internal/gateway package (another session's full suite was queued on
mote). Not changed: oneOffErr's clip() can cut a rune in two for the
card's 300 bytes; logOneOff cuts on rune starts (#4878).
2026-11-02 15:06:47 +08:00
yetone d39358f1bb claude: /usage and "hi" reads run in magpie's work folder and say why they ended (#4830)
mydosu's Claude Code quota reads on Windows failed for both accounts
with "exit status 1" alone. Two things were behind it:

- Each one-off interactive run (claudeUsageTUI, askClaudeTUI) started in
  a new magpie-claude-<n> temp folder, which the helper trusted, so each
  read wrote one more trusted projects entry into the config's state file.
  The reporter had 67 in ~/.claude.json.
- The caller's budget (subscriptionTimeout, 20s) is shorter than the
  helper's own waits (45s for the prompt, 20s for a panel). The context's
  kill came first, and that is TerminateProcess on Windows, so Wait said
  "exit status 1" with an empty stderr. On Unix the same kill says
  "signal: killed".

What changed:

- One-off TUI runs work in claudeWorkDir (oneOffDir). That is the
  owner-checked folder the bridge's own runs already use, so each config
  directory holds one trusted entry instead of one per read. A temp
  folder is made only when that folder can't be.
- The run's session file there is removed by the session_id the helper's
  init line names (dropOneOff). It is not removed under WSL.
- The helper is told its caller's deadline (claudetui.DeadlineEnv, the
  context's deadline less min(3s, a quarter of what is left)). At that
  time it ends on its own, saying what Claude Code hadn't done and its
  last screen, e.g. "Claude Code hadn't drawn /usage's panel in the
  2.9s its caller waits for it: ...".
- A run that still says nothing reads "Claude Code's interactive mode
  said nothing before magpie stopped waiting for it (...)" (oneOffErr),
  not an exit code.
- quotaError says these reasons on the card as "Allowance unavailable:
  {why}" (an existing key in every language). The full text stays in
  the tooltip. Nearby comments were cut so the core script budget holds
  without a raise.
- No -p fallback was added. The -p asks keep their own temp folder,
  since -p asks nothing about trust.
- The entries older magpies left in ~/.claude.json are left alone:
  magpie never writes that file.

Run at this head (after the rebase on c875e66c2), on mote:

- go test -count=1 ./internal/claudetui: ok.
- go test -count=1 -run 'Claude|TUI|Usage|Warm|Ask' ./internal/gateway: ok.
- go test ./internal/gui -run 'Budget|I18n|Script': ok.
- node --test claude-quota-onboarding (chromium and webkit, en, zh,
  zh-TW, ja and de, 440px) and i18n-keys: 14 of 14.
- GOOS=linux and GOOS=windows go vet of claudetui and gateway: clean.
- gofmt -l: clean.

On xiaomi-gpu (Windows 11, win-run):

- TestShimEndsAtItsCallersDeadline passes through ConPTY.
- TestShimFirstMessageWaitsForTools and TestShimReadsUsage are red the
  same way on origin/main c875e66c2. They are filed as #4810 and #4820.
- The real Claude Code 2.1.316 ran under a sandbox HOME and
  CLAUDE_CONFIG_DIR, with fake credentials and a rebuilt magpie.exe.
  Before the change, each run left a new trusted temp entry. With
  MAGPIE_CLAUDE_TUI_BY 3s out, the helper now exits saying "Claude Code
  hadn't drawn /usage's panel in the 2.9s its caller waits for it: <its
  screen>". Untrusted, it says the trust reason.

Broken by hand (each went red):

- The helper ignores DeadlineEnv: claudetui's deadline test.
- oneOffDir never uses claudeWorkDir: two different pwds and sessions
  left.
- removeSession dropped: "session was left".
- oneOffErr's context branch removed: got "signal: killed".
- helperDeadline not passed: "helper was told by:" empty.
- quotaError's new lines removed: the onboarding GUI test shows
  "Allowance unavailable" alone.

Not tried:

- A real signed-in Claude account on Windows. So which step is slow on
  the reporter's machine (start-up, the prompt or the panel) is not
  known. The card now names it.
- Unrelated, seen while breaking it: with no deadline, a /usage whose
  panel is never drawn ends after 20s as a success with an empty result.

Reported by mydosu (myduso_27930 on Discord).
2026-11-02 10:14:49 +08:00
yetone af4ff747bc claudetui: Claude Code's first-run screens are gone through as a person would, not the run's end (#4817, steven_4422 on Discord)
With "runs as" Interactive, a Claude Code whose onboarding was never
finished (no hasCompletedOnboarding in the state file: steven_4422's
every request 502'd, uiuing's /usage read in #4817) stopped on the
"Security notes" screen, and 88a0262bf ended the run there. A person
presses Enter. The helper now does the same:

- "Choose the text style": Enter (as before, now after the settle);
- "Security notes: ... Press Enter to continue": Enter;
- "Use Claude Code's terminal setup? ... Esc to skip" (shown for
  TERM_PROGRAM Apple_Terminal or vscode): Esc, so no one's terminal
  settings are changed.

Each key waits until its screen has stayed drawn trustSettle (300ms),
as the trust dialog's does, and each screen gets onboardTries (3)
presses; one that is still shown after that ends the run with "stays on
its first-run screens, its onboarding not done; run Claude Code once in
a terminal and go through them", plus the screen. Claude Code then
records the onboarding done itself (hasCompletedOnboarding,
lastOnboardingVersion); magpie writes nothing in the user's
.claude.json. There is no -p fallback: with On nothing runs as -p (the
owner's 11-01 call, e5f66f8a6).

Run at the pushed head, on mote: go test ./internal/claudetui ok;
gofmt -l clean; go vet darwin, linux, windows ok. wsl-run claudetui ok
(at the pre-rebase base). win-run claudetui: TestShimGoesThroughOnboarding
and TestShimNeverPrints pass; TestShimFirstMessageWaitsForTools (#4810)
and TestShimReadsUsage (#4820, filed for this) fail the same at
origin/main eb3b9376e on Windows. go test -run "Claude|TUI" ./internal/gateway ok;
the full package ok but for #4807's TestCodexPoolSaysTheClientsVersion.

Real Claude Code 2.1.316 (npm darwin-arm64) on mote, through a built
magpie's claude-tui-helper, in fresh sandbox HOMEs with a fake
CLAUDE_CODE_OAUTH_TOKEN and ANTHROPIC_BASE_URL at a closed port, for
TERM_PROGRAM unset, Apple_Terminal and vscode: the first run got
through theme, notes (and terminal setup) and trust to init in 5-6s,
the second in 2s; .claude.json then had hasCompletedOnboarding true and
lastOnboardingVersion 2.1.316, settings.json theme dark.

Broken by hand: no Enter on the notes, both TestShimGoesThroughOnboarding
subtests red; Enter instead of Esc on terminal setup, "the user's
terminal was set up" red. Taking the settle out still passes (the fake
redraws and is answered again), so the settle is not guarded.

Not tried: a real signed-in account (no token was provided), so no
request past init; real Claude Code on Windows or WSL; iTerm or other
TERM_PROGRAMs whose onboarding may show other screens.
2026-11-02 04:19:23 +08:00
yetone ccd746e039 claude: /usage is read in the interactive mode, typed in it, not through -p
With the interactive mode on, the plan's allowance (the Claude account's
usage card) was still read by `claude -p /usage`, the one -p run left
beside a request. Claude Code 2.1.316's -p /usage also tells only the
session's cost, no window. Now claudeUsage, with claudeTUIOn, runs the
interactive mode's helper (claudeUsageTUI) and gives it a line
{"type":"command","command":"/usage"}. The helper types /usage, waits for
the panel to settle (a "N% used" and a second without change, or three
seconds of anything else, 20s at most), closes it with Esc, and tells
what was drawn as -p's lines say it (usageText: "Current session: 0% used
· resets 5am (Asia/Shanghai)"), so parseClaudeUsage reads it unchanged.
No model is asked. The helper types no other command. The machine
reasons a request is refused for (no shim, OS, missing, off) refuse the
read the same way. Turned off, -p runs it as before.

Run (mote, at this tree on origin/main a25d3d081):
- gofmt clean; go vet internal/gateway and internal/claudetui for darwin,
  windows, and linux with -tags nogui: ok.
- go test -run 'Usage|Claude|Command' ./internal/gateway
  ./internal/claudetui ./internal/provider: ok (59.9s, 4.1s, 25.2s).
- New tests: TestShimReadsUsage, which uses the bytes Claude Code 2.1.316
  drew for the panel (testdata/usage-2.1.316.bin), TestShimRunsNoOtherCommand,
  TestUsageText and TestClaudeUsageTUIOn.

Real run (this Mac, sandbox HOME, Claude Code 2.1.316, the test account):
the built helper with claudeTUIUsageArgs and the /usage line answered in
6.1s with local_command "usage" and "Current session: 0% used · resets
5am (Asia/Shanghai)" / "Current week (all models): 98% used · resets Nov
4 at 6am (Asia/Shanghai)". Exit 0.

Broken by hand: with claudeUsage's claudeTUIOn branch off,
TestClaudeUsageTUIOn read "Total cost: $0.0000" from -p and went red.
With usageText's reset dropped, TestShimReadsUsage and TestUsageText went
red.

Not tried: a plan with overages on, or a Team/Enterprise plan's panel;
both are read through the overages line and the "no window" fallback
only. Not run on Windows or in WSL. No GUI file changed. Not run: the
full gateway suite.
2026-11-02 00:39:54 +08:00
yetone 14e3513780 claude: Claude Code in WSL runs interactively when Windows can't read its transcripts
With the interactive mode on, Claude Code in WSL was refused with a 502
in two cases: the distro user's own folder unreadable from Windows
(\\wsl$ needs the 9P redirector, which a session over ssh hasn't;
"wslread") and a distro whose home the probe didn't find ("wsl-home").
Both now run interactively: the helper reads the transcript inside the
distro.

- claudetui/wslread.go: before Claude Code starts, a shell run through
  wsl.exe notes how much of $HOME/.claude/projects/*/<sid>.jsonl is
  there (a resumed session's earlier turns), says "ready", then tail -F's
  the rest; the helper copies it to a file of its own and tails that as
  any transcript. When Claude Code ends it waits for the copy to stop
  growing (settle), then closes the shell's stdin, which ends it.
- claudetui.WSL gets Distro (Projects omitempty); the gateway's tuiWSL
  sets it when Windows can't read the folder or the home is unknown.
- the wslread and wsl-home refusals are gone (claudeTUI, claudeWhy,
  claudeNotTUIWhy); the GUI's "wsl-home" reason and its 4 strings too.
- docs/subsystems/claude-subscription-bridge.md says how it is read.

Run, at origin/main ff65ebd14 plus this change (the reader through real
wsl.exe and the break-by-hand at 546cdbde6):
- WSL (magpie-desktop, go1.26.8): go vet -tags nogui, GOOS=windows vet,
  GOOS=darwin CGO_ENABLED=0 vet of claudetui ok; go test ./internal/claudetui
  ok; go test -run 'Claude|WSL' ./internal/gateway ok (51s);
  claude-mode.test.cjs chromium + webkit 44/44; i18n-keys 4/4.
- Windows 11 (xiaomi-gpu): go vet ok; go test ./internal/claudetui ok
  but TestShimFirstMessageWaitsForTools, red the same at main 2739626c3
  (bee3ea675's test, #4810);
  go test -run 'Claude|WSL' ./internal/gateway ok with
  TestClaudeAsRootEnv skipped: it is red the same at main 546cdbde6 on
  Windows (#2425, a root test where magpie is never root), at 546cdbde6.
- the reader through the real wsl.exe into magpie-desktop (a temporary
  test, not committed): ready in 93ms, the line already in the file left
  out, two lines written after copied, stopped in 9ms, no tail left in
  the distro.

Broken by hand: tuiWSL not setting Distro: TestClaudeTUIWSL red ("its
own folder, unread": Distro empty).

Not tried: a real Claude Code turn in WSL over ssh (real runs stay on
this Mac); mote (its disk is full); the full go test ./... .
2026-11-02 00:12:40 +08:00
yetone 59fdab0af7 gateway: a caller's folder the user hasn't trusted runs in magpie's, not a 502 (lwjef on X)
lwjef (X, 2116867007799030000): a cwd Claude Code hasn't trusted hangs
the interactive-mode bridge (paseo chat).

Cause: in the user's own account the helper leaves the trust question
to the user (no MAGPIE_CLAUDE_TUI_TRUST) and ends at once saying so. Up
to 11-01 that run became -p; since e5f66f8a6 nothing runs as -p, so the
turn got a 502 (endedBefore, "Claude Code asks whether to trust the
folder"). A Claude Code client such as paseo's asks again with backoff
on a 5xx, so the chat looked hung. The real Claude Code 2.1.309 in an
untrusted folder (sandbox HOME, copied account) ends the helper in 1.3s
with that line.

Fix: startTrusted runs startRun, and when the helper ended over the
trust question (its stderr read to the end, saidOnEnd) in the caller's
folder under the user's own account, remembers that folder for 10
minutes (passedOver) and starts the run once more in magpie's own folder,
told the caller's (envElsewhere), as a caller on another computer is.
Only one retry: a second refusal is returned as before. The saved-session
retry in start goes through startTrusted too.

Run (mote, at this tree):
- go test -run 'Claude|MCP|Bridge' ./internal/gateway: ok
- TestClaudeTUIUntrustedFolderAnswered: ok

Broken by hand: saidOnEnd returning false made the new test red (502
"exited before it answered magpie's initialize request ... trust the
folder"); passedOver turned off made it red with the same 502 after one
retry. An earlier draft that retried through start itself looped forever
with passedOver off; the retry is bounded to one since.

Not tried: a real gateway turn from paseo; the real helper and Claude
Code were run on each side of the retry (untrusted folder ends at once;
a trusted magpie folder answers), not through a live gateway. A user who
trusts the folder within 10 minutes still runs in magpie's folder until
then.

At the pushed head's tree, on origin/main 79f83798f (which has 2b52302dc,
crosscn's 400KB fix), on mote: gofmt -l is clean, and go vet
./internal/... is ok for darwin, windows and linux. go test -timeout 45m
./internal/claudetui ./internal/claudebridge is ok. ./internal/gateway is
ok except TestCodexPoolSaysTheClientsVersion, which fails the same way in
a gateway run at origin/main 79f83798f itself and passes alone at both
(#4807, filed here). The conflict with main's tuiRefusal and replay change
in start() was resolved by keeping main's req.told and calling
startTrusted. Before the rebase, the three packages were ok on
magpie-desktop (Linux) too.
2026-11-01 23:47:47 +08:00
yetone bee3ea6753 claudetui: the first message waits for Claude Code to list magpie's tools (MinhuWang on X)
MinhuWang (X, 2116836405548916907): in the interactive mode the first
message can go before MCP has loaded, and then has none of pi's tools.

Cause: the helper's ready() took the drawn "❯ " prompt as ready. Claude
Code connects its MCP servers beside the prompt, so a message pasted at
once was answered with no mcp__magpie__ tools. Reproduced with the real
Claude Code 2.1.309 (sandbox HOME, a copy of the owner's account): an MCP
server held 8s before answering initialize got "NOTOOL" for "what is the
secret word, use your tool".

Fix: startRun gives claude-mcp-helper a third argument, a `listed` file in
the run's temp folder, which RunMCP writes after it has answered
tools/list. The helper finds that path in the run's --mcp-config
(mcpListed) and ready() waits for it as well as the prompt, inside the
same ReadyWait (45s); past it the run ends saying the tools weren't
listed. Runs without that server (warm-up, model test) don't wait.

Run (mote, at this tree):
- go test ./internal/claudetui ./internal/claudebridge: ok
- go test -run 'Claude|MCP|Bridge' ./internal/gateway: ok
- real Claude Code 2.1.309 here, a sandbox HOME with a copy of the
  account's credentials, the new helper and the real claude-mcp-helper
  behind an 8s sleep: initialize answered at 12.7s, the first turn called
  mcp__magpie__pi_secret and answered "The secret word is PELICAN".
  Without the sleep: answered at 2.1s, same answer. 2.1.309 sends
  server/discover before initialize; the helper's method-not-found answer
  is taken and initialize follows.

Broken by hand: toolsListed returning true made
TestShimFirstMessageWaitsForTools red ("echo: hello (without magpie's
tools)"); RunMCP not writing the file made TestToolsListedFileWritten
red.

Not tried: Claude Code in WSL (the path is the gateway's Windows temp
path, handed to magpie.exe as the callback path is); a Claude Code that
lists tools only on its first request (2.1.309 lists them at start),
which would now wait 45s and fail saying so instead of answering
without tools; the full gateway suite (run after the next commits).
2026-11-01 23:26:57 +08:00
yetone 2b52302dcb claude: the interactive mode takes a first message of any length
@crosscn on X (11-01): after the upgrade made the interactive mode the
default, a week-old conversation (a DeepSeek harness on a Claude model)
got a 502, and worked again only with -p turned back on. A conversation
told whole to a new interactive Claude Code is its first message, and
words over 400KB were refused (claudePrint's "big", tuiPromptMost). The
bound was never tried: the commit that set it lists "a ~400KB paste"
under Not tried.

Tried on real Claude Code 2.1.316 in a sandbox HOME, haiku: a 3MB
bracketed paste showed "[Pasted text #1 +46154 lines]" after 35s; a
500KB one was sent, its transcript holds every line and the question,
and the model answered it (184,168 tokens written to the cache).

- tuiPromptMost and the "big" refusal are gone; claudeTUI, claudePrint,
  claudePrintWhy and claudeNotTUIWhy no longer take the prompt, which
  only that bound read.
- the helper waits for a paste to show a second per 64KB longer than
  pasteWait (shownWait): 10s alone would press Enter while a 3MB paste
  was still being taken in.
- the editor's tooltip says -p takes what the interactive mode can't
  "yet": a JSON schema (en, zh, zh-TW, ja, de).
- docs/subsystems/claude-subscription-bridge.md says so.

Tests: TestClaudeTUIBigFirstMessage (a ~1.1MB first message runs through
the helper, 200), TestShownWaitGrowsWithThePaste; TestClaudeTUIOnRefusesPrint
refuses a JSON schema now; TestClaudeTUIChosen's long-message row runs
interactively.

Run on mote (go1.26.8):
- full go test ./internal/gateway ./internal/claudetui (-timeout 45m) at
  15b035eef plus this change: claudetui ok, gateway red only on
  TestClaudeTUIOnRefusesPrint's -p half (the fake's "ok" fits no schema,
  502); that half now checks that -p ran it, not a 200. gofmt, vet
  (darwin, windows) ok; claude-mode and i18n-keys GUI files 44/44 and
  4/4 in chromium and webkit.
- rebased on origin/main ec104b862, at the pushed tree: gofmt, vet (darwin,
  windows, linux -tags nogui) ok; go test -run 'Claude|Budget'
  ./internal/gateway ./internal/gui ok; ./internal/claudetui ok;
  claude-mode 44/44, i18n-keys 4/4 in both engines.
- a real run through the helper (magpie built from this tree, real
  Claude Code 2.1.316, sandbox HOME, haiku): a 600KB first message as
  stream-json, answered "MANGO" in 12.5s, its transcript holding all of
  it.

Broken by hand: the 400KB refusal put back: TestClaudeTUIBigFirstMessage
red with the reporter's 502; shownWait returning pasteWait alone:
TestShownWaitGrowsWithThePaste red.

Not tried: the reporter's own conversation or a DeepSeek harness; a
first message past the model's context (Claude Code's own error then,
as with -p); a paste over 3MB; Windows or WSL with a large paste; the
whole go test ./... (the gateway and claudetui packages ran whole
before the rebase).
2026-11-01 21:30:04 +08:00
yetone e5f66f8a61 claude: with the interactive mode on, nothing ever runs as -p; the editor switches TUI and claude -p
The owner (11-01): the interactive mode falling back to -p is dangerous,
for the account (a -p request counts as another client's) and for the
cache (a -p run starts without the interactive mode's), so it goes
entirely. With Settings › Models › Replies' interactive mode on:

- a request it can't take (safeguards, client cache marks, a JSON
  schema, an image by URL, words over 400KB, a branch of a -p session,
  a WSL Claude Code whose home or transcripts magpie can't reach) is
  refused before any Claude Code starts, saying why and naming the
  setting (claudeTUIErr), never run as -p;
- a helper that can't start the interactive mode (sign-in asked,
  first-run notes, an untrusted folder, no prompt within ReadyWait)
  ends saying why (claudetui fail); printMode, OnlyEnv and the
  claude-tui-broken mark that sent every run to -p for a day are gone;
- a helper that never answers initialize fails the turn
  (tuiNoStart), and the next turn tries again.

Off still runs every request as -p. The "Interactive only" choice of
v0.1.2448 (claudeTUIOnly) is what On is now; the setting is no longer
read or sent.

The Claude Code provider editor's "Claude Code runs as" row is a
switch between Interactive mode (TUI) and claude -p (owner, 11-01),
saving claudePrintMode and reading /api/claude/mode again; disabled in
magpie web. It reads the settings first when the Settings page was
never opened (prefs null crashed the switch; found by the GUI test).
Chromium has no onfocusin property, so the card on keyboard focus
listens for focusin/focusout. Words in en, zh, zh-TW, ja and de.
Docs: claude-subscription-bridge.md describes refusal, not fallback.

Not covered yet, now refused under On rather than run as -p (follow-
ups, each to be done inside the interactive mode): an image by URL, a
JSON schema, safeguards, client cache marks, over 400KB, a -p
session's branch, WSL transcripts Windows can't read. /usage reads
the allowance with claude -p /usage (no model request) either way.

Run (worktree at df0320156 + this):
- mote: gofmt -l clean; go vet darwin/windows/linux of claudetui,
  gateway (gui for windows); go test claudetui, settings, settingsapi
  ok; gateway -run "TUI|Warm|Claude|AskClaude|Cache|Mode" ok (110s);
  gui -run "Budget|I18n|Settings|Claude" ok.
- mote GUI: claude-mode, claude-tui-setting, i18n-keys: 64/64 pass in
  Chromium and WebKit, 900 and 420 wide, en zh zh-TW ja de.
- wsl-run go vet -tags nogui ./internal/gui ./internal/claudetui ok;
  win-run go test ./internal/claudetui ok.
- Real Claude Code 2.1.316 on macOS through this build's
  claude-tui-helper, sandbox HOME, CLAUDE_CODE_OAUTH_TOKEN: trusted
  folder -> interactive run, streamed (message_start, 4 deltas,
  message_stop), result success in 5.2s; untrusted folder -> exit 1
  "Claude Code's interactive mode didn't run: Claude Code asks whether
  to trust the folder", no -p run; config without onboarding -> exit
  1 naming the first-run notes, no -p run.
Seen red: claude-mode's save test with prefs null before the fix, and
its focus test in Chromium before the listeners; TestClaudeModeLast
while it still read a helper's "this run is -p" line.
Not tried: a real gateway request refused in the GUI (covered by the
Go tests with the fake Claude Code); the new gateway tests run
against the old fallback code; Windows and WSL real runs of this
build; no full suite.
2026-11-01 17:43:17 +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 606743831e appdir: on Windows an agent's folder variable follows the registry, and a gone folder it names isn't made again (bm_rabbit on Discord)
bm_rabbit (0.1.2405, Windows x64, Pi 1.4.0) moved Pi's AgentDir from
F:\piData\.pi\agent to F:\HarnessData\Pi\.pi\agent, deleted the old one and
set the User variable PI_CODING_AGENT_DIR to the new path. Changing Pi's
model in magpie then made the deleted folder again with only models.json
and settings.json in it.

Cause: Windows gives a process its variables once, from the registry, and
never passes a changed User variable to one already running. magpie runs
for days in the tray, so appdir.Getenv("PI_CODING_AGENT_DIR") (piDir) kept
the old path, and edit's write did MkdirAll on it. Every agent folder
variable (CODEX_HOME, CLAUDE_CONFIG_DIR, ...) had the same problem.

Fix, where every agent folder is read (appdir.LookupEnv, follow.go): on
Windows a variable in agentenv.Vars that came from the registry (its value
in magpie's environment at start matched the registry's, unset in both
counts too) is read from HKCU\Environment, else HKLM's Session Manager
Environment, with %...% expanded, at most once a second, and set in
magpie's environment so the programs magpie starts get it too. A value
the launcher set itself, or one set inside magpie since (a test sandbox),
stands. The direct os.Getenv reads of agent variables go through appdir
now: claudetui's CLAUDE_CONFIG_DIR, sessions' CODEX_SQLITE_HOME and
PI_DESKTOP_DATA_DIR, cliupdate's GROK_HOME, omp's OMP_PROFILE/PI_PROFILE.

And edit's writeFile no longer makes a missing tree of folders that an
agent's variable names: when the folder the variable names is missing
and so is the folder above it (bm_rabbit's whole F:\piData was gone),
appdir.Gone returns a GoneError naming the variable and the folder. The
named folder itself is still made when its parent is there, as mkdir
would (a CODEX_HOME or ANTE_HOME set before the agent first ran; 12
internal/agent tests rely on it), and an agent's default folder is made
as before. TestAnteHome's ANTE_HOME was <tmp>/elsewhere/ante with
elsewhere missing; it now makes elsewhere first. Writes that call
os.MkdirAll themselves don't ask yet: #4634.

Pi's install-layout.json isn't Pi's: Pi 1.4.0's getAgentDir
(@earendil-works/pi-coding-agent dist/config.js) reads PI_CODING_AGENT_DIR,
else ~/.pi/agent, and no file in the package names install-layout.
magpie doesn't read it.

Tests: TestAgentVarFollowsTheRegistry, TestAgentVarAddedLaterFollows,
TestAgentVarSetByHandStands, TestRegistryReadAtMostEachFollowFor,
TestGoneNamedFolderIsNotMade (internal/appdir, a fake registry), and
TestWriteNeverMakesANamedFolderAgain (internal/edit).

Broken by hand: LookupEnv back on os.LookupEnv, TestAgentVarFollowsTheRegistry
and TestAgentVarAddedLaterFollows FAIL ("after the user moved it,
PI_CODING_AGENT_DIR = .../old, want .../new"); Gone's refusal turned off,
TestGoneNamedFolderIsNotMade and TestWriteNeverMakesANamedFolderAgain FAIL
("= <nil>, want a GoneError", "the folder was made again"); Gone refusing
whenever the named folder is missing, TestGoneNamedFolderIsNotMade FAILs
("a named folder whose parent exists: ..."). All put back, green.

Real Windows run on xiaomi-gpu, sandbox USERPROFILE/APPDATA/LOCALAPPDATA,
at this head: a probe built from this tree started with
PI_CODING_AGENT_DIR=<sb>\piData\.pi\agent in its environment and the User
registry; then the User variable was set to <sb>\HarnessData\Pi\.pi\agent
and <sb>\piData deleted, and agent.Find("pi").Apply("model", ...) ran in
the same process. Pi's dir and os.Getenv are the new folder,
settings.json written there, piData not made. With HarnessData deleted
too: "PI_CODING_AGENT_DIR names <sb>\HarnessData\Pi\.pi\agent, which
doesn't exist and neither does the folder above it: ...", not made. An
earlier run of the old code (LookupEnv on os.LookupEnv, no Gone) wrote
into the old folder and made it again: bm_rabbit's case. The User
variable was removed after; the box had none.

Full run at this change on d714c4216: on mote,
gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., and go test -tags nogui -timeout 45m ./...:
83 ok, 2 red, each open and not this change's: internal/gui
TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red alone on origin/main)
and TestColdTurnsTaken (#4510, warm-up ordering race, 0.00s), and
internal/cli TestLibraryMCPHub (#4140, TempDir cleanup; passes alone).
internal/appdir, internal/edit and internal/agent again alone: ok.
Rebased onto 76c130b29 (eight commits, edit's and appdir's among them;
file.go's imports merged by hand): gofmt -l (nothing), the three go vets,
and internal/appdir, internal/edit, internal/agent, internal/claudetui,
internal/sessions on mote: all ok. Not the whole suite again there.
Rebased again onto 88372a39d at push (six commits, none in appdir or
edit; dd7442f28 in internal/agent): go vet ./internal/..., internal/appdir
and internal/edit ok; internal/agent not run again at this head.
Windows (xiaomi-gpu, at d714c4216): internal/appdir, internal/edit, internal/claudetui
ok; internal/agent's 12 tests that make a named folder, TestGrok* and
TestPi* ok; internal/sessions red only in TestAgySessions and
TestAgyRowOnly, the same alone on origin/main (#4115).

Not tried: magpie's own GUI on Windows (the probe calls the same
agent.Apply the GUI's /api/set reaches); a REG_EXPAND_SZ value and a
Machine-only value on the real box (code path read, not run); bm_rabbit's
junction at C:\Users\Administrator\.pi.
2026-11-01 04:40:44 +08:00
yetone e6b595e1ab claude: Interactive only, a setting under which a model request never runs as claude -p (_yuchanns_ on X)
_yuchanns_ on X, on the interactive mode falling back to -p: for people
who stayed off magpie's Claude subscriptions because of -p, a fallback
is a time bomb. Settings › Models › Replies › Claude Code's interactive
mode now has three choices: Off (always -p), On (the default, falling
back to -p as before) and Interactive only.

With Interactive only (settings.ClaudeTUIOnly; ClaudePrintMode set too
wins):
- a run claudeTUI would make -p is not started; the request fails with
  the reason and the setting (claudeOnlyErr, claudeNotTUIWhy);
- the helper is handed MAGPIE_CLAUDE_TUI_ONLY=1 (claudetui.OnlyEnv,
  claudeCLI.tuiEnv). Where it would exec -p (no start, sign-in, first-run
  notes, untrusted folder, 45s timeout) it exits with the reason
  (fallBack in Run), and it ignores the broken mark;
- a helper that never answers initialize ends the turn with an error,
  not a -p retry, and `broken` isn't counted (claudeMachineWhy), so the
  next run tries the interactive mode again;
- the model test's and warm-up's "hi" (askClaude) runs through the
  helper (askClaudeTUI) in stream-json, its stdin closed at the first
  result. The helper command and env are built in one place now
  (tuiCommand, tuiEnv) for both.
Reading the plan's allowance (/usage) asks no model and stays -p; the
setting's text says so. Docs: claude-subscription-bridge.md.

Provider editor, on e8347401f's "Claude Code runs as" pill
(ClaudeMode.Only): with the interactive mode in use and no last
request, it says a request it can't take fails, and the card's foot says
nothing runs as -p. Where the interactive mode can't run, the pill names
Interactive only, never claude -p, the line says "Claude requests fail:
<why>", and Change in Settings goes to the row. A request refused this
way never ran, so it isn't noted as the last request (noteClaudeRun
comes after the refusal).

app.js: the Replies rows share one helper (segRow, which waitRow uses
too), so app.js is 530 bytes under main's with the third choice; no
budget raise.

Tests: TestClaudeTUIOnlyRefusesPrint, TestClaudeTUIOnlyHungHelperNoPrint,
TestClaudeTUIOnlyTellsHelper, TestAskClaudeTUIOnly (gateway);
TestShimOnlyNeverPrints (claudetui: fake fail/trust/login/notes each
exit with an error and no -p, a marked-broken run still interactive);
claude-tui-setting.test.cjs (three choices, Only saves claudeTUIOnly with
claudePrintMode false) and claude-mode.test.cjs (Only in use, and Only where it can't run).

Broken by hand, each red, then put back: the startRun gate off
(RefusesPrint 200); start()'s Only check off (HungHelper 502 without the
Only reason); tuiEnv's OnlyEnv off (TellsHelper); askClaude's branch off
(AskClaudeTUIOnly); the helper's fallBack ignoring only (4 subtests);
BrokenSince's `&& !only` gone ("marked broken"); the save without
claudeTUIOnly (16 of 16 setting tests) and claudemode.js's m.only
branches gone, rebuilt on e8347401f's file (10 of 10 Only tests,
Chromium).

Run on mote at e8347401f + this commit:
- at f1d6f4137 (main, after #4571's claude_cache.go) + this commit: go
  vet of gateway and gui ok, CoreScriptBudget|I18n ok, the gateway's
  TUI|Warm|Claude|AskClaude|Cache tests ok; the rest below at e8347401f
- gofmt -l clean; go vet and GOOS=windows go vet of claudetui, gateway,
  settings and gui ok; Linux vet (wsl-run, -tags nogui) ok
- go test ./internal/claudetui ./internal/settings ok; the gateway's
  TUI|Warm|Claude|AskClaude tests ok
- internal/gui CoreScriptBudget|I18n|Settings: ok but
  TestSettingsSaveKeepsWhatItDoesNotSend, SearchAll, red on main since
  b09349d17 (#4514)
- GUI (Chromium + WebKit, every language): claude-mode, claude-tui-setting
  and i18n-keys 94 of 94 at e8347401f; with the other Replies rows'
  files (claude-lean-prompt, member-model, loop-guard, refusal-retries,
  classify-timeout, image-timeout) 180 of 180 at 2e9df9b1b. Earlier
  segs-press-redraw's searchAllRow red is #4566, not this change.
Not tried: a real account under Interactive only (the fallback paths
are forced by the fake Claude Code); the full GUI suite (mote had
another session's full GUI suite and an agent+gateway suite going).
2026-11-01 02:53:08 +08:00
yetone 88a0262bf2 claudetui: Claude Code's first-run notes send the run to -p at once, not after 45s
A config folder whose onboarding isn't done (one only -p was run in,
given CLAUDE_CODE_OAUTH_TOKEN) has the interactive mode show "Security
notes: … Press Enter to continue". The helper knew the sign-in screen
but not this one, so it waited out ReadyWait (45s) before running -p.
Now firstRun is matched like signIn: the run is -p at once and the
start is marked broken. Agreeing to the notes is left to the user.

The match is on the screen's words with any space between them one
(strings.Fields): the real 2.1.316 screen didn't match a plain regexp,
since Claude Code draws some spaces by moving the cursor.

Run:
- mote: go test ./internal/claudetui -count=1 ok; go vet for darwin,
  windows, linux; gofmt clean.
- Broken by hand: with the case off, TestShimFallsBackToPrint/first-run
  notes goes red ("wrote 0 lines of 1 in 30s").
- Real, on xiaomi-gpu (Windows 11), Claude Code 2.1.316 (official dist,
  sha256 checked), a real subscription token, a fresh config folder:
  before, "showed no prompt in 45s" and -p at 48s; with the first regexp
  still 45s (the space case above); now "shows its first-run notes" and
  the -p answer at 7.9s and 16.9s (two runs), streamed.

Not tried: WSL with a fresh folder (same helper code path); macOS/Linux
native with a fresh folder.
2026-11-01 01:43:35 +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 a4151142a6 claudetui: the Unix pseudo-terminal child is made through proc.Command (#4491)
internal/claudetui/child_unix.go started Claude Code with exec.Command
directly, so TestNoCommandBypassesProc was red on main since the
interactive mode's Unix child landed (06c2c35d1, moved by c59c547c5).
It now uses proc.Command, as the Windows pseudo-console sibling
(child_windows.go) already does; the child keeps its *exec.Cmd and its
Setsid/Setctty attributes, set after the command is made.

The fix is yiqiui's, from #4491 (their branch
fix/claudetui-proc-command, ca129fa72); applied here by hand.

Run on mote (macOS) at this head: go test ./internal/proc
./internal/claudetui ok (the guard was red there before, in the full
run of 97c5ce8ef's tree: "internal/claudetui/child_unix.go:32 runs a
command with os/exec"); GOOS=linux go vet ./internal/claudetui clean;
in WSL (magpie-desktop) go test ./internal/claudetui ok.
Not tried: a real Claude Code TUI run after it; proc.Command adds
nothing on Unix (hide and batch are no-ops there).
2026-10-31 17:29:01 +08:00
yetone fb9c176756 claudetui: Claude Code in WSL runs in its interactive mode too
A Claude Code found in a WSL distro (Windows has none of its own) was
always claude -p, the entrypoint the plan counts at about twice the
interactive mode's. Many Windows users run it there.

The Windows helper now runs wsl.exe in its pseudo console. The gateway
hands it MAGPIE_CLAUDE_TUI_WSL (claudetui.WSL, claudeCLI.tuiWSL): the
wsl.exe arguments up to Claude Code's (wslrun.Tool.Args, with
MAGPIE_WSL_RUN), the distro's mount, and the projects folder as Windows
reads it. That is the account's config directory, handed in through
CLAUDE_CONFIG_DIR/p, or the distro user's own ~/.claude/projects
through \\wsl$\<distro> (wslrun.Tool.Home, a new line in the probe;
wslrun.Tool.Windows). TERM is added to WSLENV, and an image's path is
pasted as the distro reads it (/mnt/c/…). The helper is the Windows
magpie.exe, not the /mnt/c/… path the MCP helper starts at; the first
real run failed on exactly that (fork/exec /mnt/c/...magpie.exe). The
gate keeps -p for a WSL Claude Code whose home is unknown, and, in the
distro user's own folder, when Windows can't stat \\wsl$\<distro>\<home>
(tuiWSLUnread): over ssh it can't (no 9P redirector), and the helper
would wait for a transcript it can't see. Doc updated.

Run:
- go test ./internal/claudetui ./internal/wslrun on mote and on Windows
  11 (xiaomi-gpu): ok. New: TestShimInWSL (image path, WSLENV),
  TestClaudeTUIWSL (projects folder both ways, wsl args), the home in
  the probe and Windows() in wslrun, the gate's two WSL cases, TestClaudeTUIWSLUnread.
- go test -run 'Claude|Refusal|Thinking' ./internal/gateway on mote: ok.
- go vet of claudetui, gateway, wslrun for darwin, linux, windows
  (-tags nogui, and the main package for windows); gofmt -l clean.
- Real account on xiaomi-gpu: a sandbox HOME gateway (3462) with no
  Windows Claude Code reachable (PATH trimmed, MAGPIE_TEST_SANDBOX so
  the registry PATH isn't read), the Claude Max account, Claude Code
  2.1.289 in magpie-desktop, haiku-5-5. Tree: helper -> wsl.exe ->
  claude on a pts in the distro, TERM=xterm-256color,
  CLAUDE_CONFIG_DIR=/mnt/c/..., no CLAUDE_CODE_ENTRYPOINT. One tool
  call, two in one message, text then a call, and two image turns: all
  right. Every transcript row "entrypoint":"cli", no "-p" line in the
  log, images noted as /mnt/c/.../magpie-claude-images-*/image-N.png
  and no folder left. Killing the gateway ended its four claude
  processes in the distro within 3s. The token wasn't refreshed; the
  copied credentials were deleted.

Broken by hand: shim.path returning the Windows path unchanged,
TestShimInWSL red; tuiWSLUnread ignoring the stat error,
TestClaudeTUIWSLUnread red.

Not tried: a WSL Claude Code run from the distro user's own ~/.claude
for real (only the account config directory ran; over ssh
\\wsl$\magpie-desktop is unreadable, so that run would be -p, and a
desktop session's \\wsl$ wasn't tried), a distro whose default user is root, a distro not sharing
Windows' loopback (wslrun.Tool.Host set), WSL1.
2026-10-31 17:29:01 +08:00
yetone 06c2c35d13 claude: the interactive mode's start is waited for, and a hung one goes to -p (#4504)
derrors (Linux Docker, 2 vCPU, v0.1.2281): every new Claude Code run
failed "Claude Code has not answered magpie's initialize request in 10s"
and the turn was 502 after 6 tries, while -p runs on the same account
answered.

Cause: the claude-tui-helper answers the bridge's initialize only once
the interactive Claude Code shows its prompt (claudetui.ready, up to
45s), or as -p after it falls back. The bridge gave it the 10s of any
control request and then ended it, so a Claude Code slower than 10s to
start was killed before its own -p fallback could run, and nothing was
marked: each try started the interactive mode again.

Fix:
- startRun waits tuiInitWait (claudetui.ReadyWait + 2x controlWait, 65s)
  for a TUI run's initialize, and gives up on the request's context.
- a helper that still answers nothing is ended, the machine is marked
  (claudetui.MarkBroken), and start runs the turn again as -p.
- claudePrintWhy goes -p at once while the mark holds ("the interactive
  mode failed to start lately"), so no helper is started.
- the mark counts failed starts in a row: 30m after one, doubled to a
  day (brokenFor), so a machine where it never starts waits about once a
  day. A start that shows its prompt removes the mark.
- the helper falls back at once when Claude Code asks how to sign in
  (a container signed in for -p only, CLAUDE_CODE_OAUTH_TOKEN), which
  it otherwise took for the prompt or waited 45s on.
Every other control request keeps its 10s; initialize is the only one
a TUI run is sent (cliControl's one other caller is setSafeguards,
and a run with safeguards or cache marks is -p).

Run (mote, at this tree):
- go test ./internal/claudetui/ (whole package) ok
- go test ./internal/gateway/ -run Claude ok
- GOOS=linux and GOOS=windows go vet ./internal/claudetui/
  ./internal/gateway/ ok; gofmt -l clean
- wsl-run (magpie-desktop, Ubuntu 24.04): go test ./internal/claudetui/
  ./internal/gateway/ -run 'TestShim|TestBroken|TestClaudeTUI|
  TestClaudeEndedRunSaysWhy|TestClaudeUnloadable' ok

Broken by hand (each red, then restored):
- TUI initialize waits controlWait, no mark, no retry (the old code):
  TestClaudeTUISlowStartAnswered 502 "Claude Code has not answered
  magpie's initialize request in 10s", the reporter's message
- TUI initialize waits controlWait only: marked broken, red
- no MarkBroken in the bridge, or no retry in start:
  TestClaudeTUIHungHelperGoesPrint 502
- no sign-in check: TestShimFallsBackToPrint/asks_to_sign_in timed out
- no clearBroken: TestShimStartClearsBroken red
- brokenFor not doubling: TestBrokenGrows red

Not tried: a real Claude Code in a headless container, or any real
account. Why derrors' Claude Code was slow or stuck is not known: the
sign-in screen is a guess from -p working where the interactive mode
didn't; the helper's line now logs the screen it stopped on. No full
suite.
2026-10-31 08:13:47 +08:00
yetone c59c547c5b claudetui: Claude Code's interactive mode on Windows, in a pseudo console
A Claude run on Windows was always claude -p, the entrypoint the plan
counts at about twice the interactive mode's. The helper now starts
Claude Code in a ConPTY there (child_windows.go): CreatePseudoConsole on
two pipes, CreateProcess with the console attribute and
STARTF_USESTDHANDLES with no handles. Without that flag a child takes
the helper's own standard handles (the bridge's pipes) and draws into
them, not the console. A .cmd claude is quoted by proc.Command as the -p
run's. Ending closes the console, then kills after 3s; the -p fallback
runs Claude Code as a child, as Windows has no exec. The pty code moved
to child_unix.go unchanged, and tui.go has no build tag.

Windows ends a run by killing its job, which no handler hears, so a
turn's images folder is now removed once its message is sent, and a
helper starting removes magpie-claude-images-* folders over an hour old
(dropLeftImages). The gateway's gate lets Windows through (WSL stays
-p), and the setting's text no longer says Windows is always -p
(en, zh, zh-TW, ja, de). Doc updated.

Run:
- go test ./internal/claudetui on macOS (mote), Linux (magpie-desktop
  WSL2) and Windows 11 26200 (xiaomi-gpu): ok. The fake Claude Code on
  Windows is a claude.cmd, its console made raw with SetConsoleMode.
  New: TestDropLeftImages, and TestShimPastesImages checks the folder is
  gone after its message.
- go test -run Claude ./internal/gateway on mote, and the TUI tests on
  Windows: ok.
- i18n-keys and claude-tui-setting (chromium and webkit, en/zh/ja/de,
  1100 and 420): 20 of 20 on the Windows box. On mote chromium passed
  and every webkit case timed out in browserType.launch, beside other
  sessions' GUI suites running for up to 20 hours (load 22).
- go vet -tags nogui of claudetui, gateway and cli for darwin, linux and
  windows; gofmt -l clean.
- Real account on xiaomi-gpu: a sandbox HOME gateway (port 3462) with
  the Claude Max account, real claude.exe 2.1.281, haiku-5-5. One tool
  call, two in one message, text then a call, and two image turns
  (twice): all right answers. 81 transcript rows, every one
  "entrypoint":"cli", no "-p" line in the log. Images noted as
  C:\Users\...\magpie-claude-images-*\image-N.png and no folder left.
  Killing the gateway ended its four resident helpers and claude.exe.
  The token wasn't refreshed; the copied credentials were deleted.
  (This ran before the 1809 check in start was added; the claudetui
  tests on Windows and GOOS=windows vet ran again after it: ok.)

Broken by hand: STARTF_USESTDHANDLES removed, TestShimTurnsInteractive
on Windows red (3 lines of 5 in 30s: the fake's drawing reached the
shim's stdout).

Not tried: an npm claude.cmd install with the real account (only the
fake .cmd), Windows 10 before 1809 (no CreatePseudoConsole: the start
checks for it and falls back to -p), a run ended mid-turn by the client
on Windows.
A stray "The system cannot find the path specified." showed once in the
Windows test output; it wasn't on the shim's stderr, and three reruns
didn't show it.
2026-10-31 06:10:00 +08:00
yetone bca0d6d69a claudetui: a turn's images are pasted as files, not sent to claude -p
A request with images ran claude -p, and a turn with one ended the
interactive run. The helper now writes each base64 image to
image-N.<ext> (0600) in a magpie-claude-images-* temp folder and pastes
its path alone, which Claude Code 2.1.314 reads into the message as
[Image #N]; a path inside other words stays words. Claude Code reads the
file after the paste returns, so the helper waits for [Image #N] past the
last one before pasting the next piece. The folder is removed when the
helper ends. Only an image known by its URL still goes to -p
(urlImages), and tuiPromptMost counts words without images.

Run: go test ./internal/claudetui ./internal/cli on mote and in WSL
magpie-desktop, ok; go test -run 'TestClaudeTUI|TestSubscription|
TestClaudePrint' ./internal/gateway on mote, ok; go vet ./..., GOOS=linux
go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, gofmt -l,
ok. Real account (Claude Code 2.1.314, haiku, sandbox HOME) through the
sandbox gateway with tools: a red then a blue square in two turns, 3 of 3
answered red, blue; the transcript has image blocks in both user rows,
entrypoint cli, and the second turn went on in the same run.
Broken by hand: without the wait for [Image #N], TestShimPastesImages
loses the second image.
Not tried: an image over Claude Code's size limit; Linux with a real
account.
2026-10-31 05:00:39 +08:00
yetone faaba45236 claudetui: the folder-trust question is answered Yes only once Yes is drawn
The real-account end-to-end through a running gateway found every
interactive run going to -p. The gateway's working folder
(magpie-claude-work-<uid>) wasn't yet trusted under the account's config
dir, so Claude Code 2.1.314 asked whether to trust it, with "No, exit"
chosen. The helper pressed down and then, 300ms later, Enter without
looking. Its down was lost when sent as the question was first drawn
(the question is drawn again on No), Enter chose "No, exit", and Claude
Code ended with status 1 (screen: "B"). The start failure marked the
interactive mode broken for 30 minutes and every run went to -p, so
v0.1.2266's default did nothing on a fresh account.

ready() now reads the choice as the last of "❯ No, exit" / "❯ Yes, I
trust" drawn, presses down (at most once a second) while No is chosen,
and Enter only on a Yes that stayed drawn for 300ms (trustSettle). The
test's fake asks as the real one does: words placed by cursor moves, No
chosen first, keys in its first 150ms lost, and drawn again on No; Enter
on No exits 1.

Run:
- By hand: real Claude Code 2.1.314 in a PTY in the gateway's folder,
  sandbox HOME with a real account's config dir: the question opens on
  No; a down sent at once is undone by the redraw, one sent 0.3s or 1.5s
  in moves to Yes.
- mote: go test -count=3 -run TestShim ./internal/claudetui ok; go test
  ./internal/claudetui ok; go vet ./internal/claudetui on darwin, linux,
  windows; gofmt -l clean.
- Real account, sandbox HOME, a gateway running this build (and the next
  commit's), haiku: a tool call, two calls in one message, words then a
  call: all answered, every transcript row "entrypoint":"cli", no broken
  mark.

Broken by hand: the old ready() with the new fake:
TestShimTrustsWhenTold red, "Claude Code ended before it showed its
prompt (exit status 1)", the real failure.

Not tried: Linux with a real Claude Code; a Claude Code version whose
question words differ (it then waits out 45s and goes -p, marked).
2026-10-31 04:20:10 +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