Commit Graph
108 Commits
Author SHA1 Message Date
yetone bc8b01d603 claude: the short system prompt is set in the Claude Code editor, not Settings › Replies
The scattered settings audit after netube99 on X. Short Claude system
prompt and Claude Code's interactive mode changed only Claude
subscription runs, yet sat in Settings › Models › Replies, while the
Claude Code editor already had its own "Claude Code runs as" switch for
the second, whose card said "Switched here or in Settings › Models ›
Replies".

Both rows now go in a claudeRunList in the Claude editor (PROV_PREFS), so
Settings' search still finds them and Open goes to the editor. In the app
the editor's own "runs as" switch is the one shown, and the duplicate
interactive mode row is hidden by CSS; in magpie web as a gateway, where
that switch is disabled, the row shows (the list gets a gw class from
renderReplies: body.gateway-mode is set only on a change, not at boot).
provPrefsField lets Claude's run list through in gateway mode, without
the warm-ups, which are this computer's. The card and the "off" reason
no longer name Settings (zh, zh-TW, ja, de written with them), and the
bridge's subsystem page names the editor.

Run (mote, mote-run, origin/main ddd6c649b as BASE_REF):
- claude-lean-prompt-setting, claude-tui-setting, claude-mode,
  provider-prefs, settings-places, i18n-keys, bare-ids and mobile-web,
  both engines: 170 of 170.
- go test -run 'Budget|I18n|Strings' ./internal/gui: ok.

Broken by hand (chromium):
- both rows back in Replies: claude-lean-prompt-setting and
  provider-prefs 18 of 18 red;
- the editor's duplicate row not hidden: claude-tui-setting 8 of 8 red;
- no gw class in gateway mode: claude-tui-setting 8 of 8 red.

Not tried: the real app with a real Claude subscription.
2026-11-09 23:14:57 +08:00
yetone 5506c84437 gateway: a skill's body reaches the run with its Skill call's result
Claude Code answers a Skill call with "Launching skill: <name>" and sends
the skill's SKILL.md after the results, as a text block headed "Base
directory for this skill: …". Since d84f58fd2 (#5403) that text counts
as the agent's own (desktopNote), so it is no longer said to the run as
the user's, which was right, but nothing handed it to the run either:
on the Claude subscription route a model that launched a skill saw
"Launching skill: pdf" and never what the skill says. Every skill
launched through magpie's Claude subscription lost its body.

withSkillBodies appends each such body to its Skill call's result (two
skills at once each get their own), else to the result it follows, else
to the last; saidWithResults still leaves it out of the user's words.

Found with a real Claude Code 2.1.316 in a sandbox HOME against the live
gateway: a proxy between them showed the body in the request, and the
model answered as if it had none.

Run (mote, at this tree):
- go test -tags nogui ./internal/gateway -run
  'SkillBod|Desktop|TaskNotice|SaidWith|MidTurn|Notice' -count=1: ok.
- TestSkillBodyRealClaudeCode parses the request Claude Code sent
  (testdata/claude-code-skill-launch.json: its own bytes, trimmed to the
  launch turn, paths shortened) and checks what the run is handed.
- Broken by hand (withSkillBodies returning results as they came):
  TestSkillBodyReachesTheSkillResult and TestSkillBodiesTwoSkills red.
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok
  (1220.8s), at origin/main 6b0b7a96e. Rebased on 8f74442e4, whose
  gateway change is browser.go: -run
  'SkillBod|Browser|ClaudeSub|TaskNotice' ok.

Not tried: a real run through a gateway built from this tree (the
Claude subscription's sign-in would be refreshed by a sandbox copy).

docs/subsystems/claude-subscription-bridge.md says what withSkillBodies
does, beside withTaskNotices.
2026-11-09 08:38:02 +08:00
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
yetone 0f8c3d8672 claude: a deferred built-in the bridge's model calls reaches the client as WebFetch, not mcp__magpie__WebFetch
Claude Code with tool search on leaves WebFetch, WebSearch, CronCreate and
the other deferred built-ins out of tools until a ToolSearch loads them.
The run's model, offered the client's tools as mcp__magpie__<name>, called
mcp__magpie__WebFetch, and toolStart handed that over whole: the 11-02
fix for an unloaded magpie MCP tool (packinggoods) kept the full name for
every cut name the client hadn't declared. The client answered "No such
tool available: mcp__magpie__WebFetch", the model retried, and
status lines such as claude-hud showed a "magpie" MCP failure.

toolStart now keeps the prefix only when the cut name has the router's
form, <server>__<tool> (magpieServerTool): the client names magpie's MCP
tools mcp__magpie__<server>__<tool>, and its built-ins (WebFetch,
WebSearch, CronCreate, CronDelete, CronList, NotebookEdit, Monitor,
TaskStop, SendMessage, EnterWorktree, ExitWorktree: the deferred list of
a real Claude Code session) have no __ and no prefix. A sibling the same
line got wrong: another MCP server's deferred tool, called as
mcp__magpie__mcp__linear__get_issue, is handed over as
mcp__linear__get_issue, the client's name (it was handed over whole too).
toolStart is the one place a called name is mapped back for the client:
streamed and whole messages and the interactive mode's early call
(r.onCall) all go through it; mcpCall's declaredName serves offered
tools only, and the history's names (bridgeName) are unchanged.

Run (on mote, at this tree):
- go test ./internal/gateway -count=1 -timeout 45m: ok
- gofmt -l: nothing; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok; go build: ok
Broken by hand: magpieServerTool returning true (the old behaviour)
turns TestClaudeBridgeHandsOverAnUnloadedMagpieTool red on the new
WebFetch and mcp__linear__ cases ("handed a call of
mcp__magpie__WebFetch, want WebFetch").
Not tried: a real Claude Code client with tool search on (the reporter's
Windows setup); a deferred tool the run's model calls by the bare client
name (WebFetch) is still the run's Claude Code's to answer and isn't
handed over. A client MCP server of its own named "magpie" with a tool
lacking __ would now be cut; magpie's router names every tool
<server>__<tool>.
Rebased on eadc6cdb9 (GUI routing files only); at the pushed head
go test ./internal/gateway -run 'TestClaudeBridge|TestClaudeToolChoice|
BridgeToolName': ok.
Full suite: not run at push.

Reported-by: steven_4422 (Discord)
2026-11-08 16:05:42 +08:00
yetone 9a92fd099b claude: a long auto mode classifier keeps its cache marks as claude -p (#5585, #5655)
With Claude Code's interactive mode on, the classifier was pasted into a
new run each call with none of its marks: Claude Code marks only the last
block of what it is pasted, and the classifier's tail changes every call,
so each call read only Claude Code's own prompt and wrote the whole
transcript again (126K and 132K a call at 1h's 2x in iamnil's rows).
Desktop's header-less classifier lost its marks at parse time
(e5f66f8a6); an opted-in one lost them when pasted.

There is no honest way to make the interactive Claude Code put a mark
mid-message: rewriting its body in tap.js would make the request unlike
Claude Code's and can pass the four-mark limit. So a classifier whose
marks keep 64KB or more of history (marksPrintAt, keptByPrint) runs as
claude -p, which keeps the marks (DISABLE_PROMPT_CACHING, the client's
marks in the first message, the tail through CLAUDE_CODE_EXTRA_BODY).
-p counts about 2x a token; with S Claude Code's prompt, M the marked
transcript and D the new part, interactive ~ 0.1S + 2M a call and -p ~
2(0.1(S+M) + 2D), which meet at M ~ 15-20K tokens. A shorter classifier
and every other request stay interactive; claudePrint names it
"cache-marks". No entrypoint, system prompt or identity text changes.

Run:
- TestClaudeTUIClassifierKeepsLongMarksAsPrint (with and without the
  header; a short classifier as control) is red with keptByPrint forced
  false (the old routing) and green with the fix.
- On mote at 70c10074c: go test -tags nogui -run
  'Claude|Classifier|AutoMode|Cache' ./internal/gateway ok; go vet
  ./internal/gateway for darwin, linux and windows ok; gofmt clean.
- Real account (one Max account, sandbox HOME, its keychain item copied
  to the sandbox's service name and deleted after; port 3481; Claude
  Code 2.1.316; claude-haiku-4-5), two classifier-shaped calls sharing a
  ~244KB prefix, interactive mode on:
    before (4ab1191bc): call 1 read 0 wrote 49,838; call 2 read 0 wrote 49,865
    after:              call 1 read 0 wrote 49,763; call 2 read 49,748 wrote 42
  The gateway logged both after-runs as claude -p with the reason.

Not tried: Claude Desktop's real classifier (the body was built to its
shape), Sonnet, Windows/WSL. Full suite not run at push; queued on mote
under the suite lock.

Reported-by: jerrychoi
Reported-by: iamnil (Discord)
2026-11-08 11:39:44 +08:00
yetone a7113d5c92 gateway: a Mac's Claude Code cache pick reaches the remote magpie's relay (linkaww)
linkaww's chain: Claude Code on a Mac (API-key mode) -> the Mac's
magpie -> a Docker magpie whose Claude provider is the relay. Two rules
asked for: a 5m pick on the Mac never writes an hour's cache; with
nothing picked, the relay keeps Claude Code's subscription default, an
hour.

Claude Code 2.1.316 marks five minutes with no ttl, whether its user
picked them or it is its default off a subscription (the marker names a
ttl only for 1h). So since v0.1.3256 the relay, which followed the marks,
wrote 5m with nothing picked, and an unmarked side call (Haiku's title,
the classifier) fell to the Docker computer's own pick, an hour, under a
5m pick.

Now the Mac's magpie names the pick: X-Magpie-Claude-Cache-TTL
(ClaudeCacheTTLHeader), "5m", "1h" or "default", set by passOnCaller
for a request from Claude Code on this computer (its token or its
claude-cli/ User-Agent from loopback, never Claude Desktop's) and passed
on as it came through further magpies. It is read as claudeRunTTL reads
the pick (claudePickedTTL); a settings.json that can't be read or parsed
names none (claudeSettingsKnown), and the marks decide as before. The
far magpie takes it from a magpie/ request alone (callerFrom) and takes
it off what comes in (withCaller), so no vendor sees it; native
passthrough already drops X-Magpie-*. runTTLFor: forced 5m; marks that
name an hour; else the pick (Request.pickedTTL), "default" giving
claudeRunTTL (that computer's pick or an hour); else the marks; else
claudeRunTTL. Claude Code on the relay's own computer gets the same
rule from its local pick. A Claude Code that goes straight to a remote
magpie sends no header and keeps today's marks-first behaviour. Nothing
sent to Anthropic changes beyond the run's CLAUDE_CODE_PROMPT_CACHE_TTL.

Known limits, in the bridge doc: a pick made only in Claude Code's shell
env or a project's .claude/settings.json isn't seen by magpie, so it
goes as "default" (an hour unless the marks name one);
subagentPromptCacheTtl is not told apart.

Tests: TestClaudeRunKeepsTheUsersCacheTTL gains 11 cases (the Mac's
5m/1h/default, marked and unmarked, against this computer's settings,
forced, marks naming 1h, Claude Code here, unreadable settings);
TestClaudeCacheTTLFromAMagpieOnly; TestClaudeCacheTTLOf;
TestClaudeCacheTTLReachesTheRemoteMagpie (two real handlers: 5m,
default, unreadable -> none, another agent -> none, vendor sees no
X-Magpie-* header).

Run (on mote, at this tree rebased on 3b541a7f3 = origin/main just fetched;
the targeted tests and vet again there):
- go test -count=1 -run 'TestClaudeCacheTTL|TestClaudeRunKeepsTheUsersCacheTTL|TestRemoteMagpieAgent|TestAskedCacheTTL|TestClaudeInstructionsCachedApart' ./internal/gateway: ok
- go vet ./internal/gateway, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: ok; gofmt -l internal/: nothing
- full go test -count=1 -timeout 45m ./... through suite.lock: still
  running at push (started at base bb33142ea) (owner's rule: no verified commit waits on it); any
  red it shows gets its own issue.

Broken by hand: runTTLFor ignoring pickedTTL -> 5 table cases red
(unmarked 5m, marked 1h, default, Claude Code here); the header taken
from a non-magpie -> FromAMagpieOnly red; passOnCaller not setting it ->
ReachesTheRemoteMagpie red ("told \"\""); claudeSettingsKnown always
true -> TestClaudeCacheTTLOf "here, unreadable" and the table's
unreadable case red.

Not tried: a real Claude subscription, a real Docker magpie, or
linkaww's own Mac; cache writes were checked by the run's environment,
not by Anthropic's usage numbers.

Reported-by: linkaww on Discord
2026-11-08 02:10:17 +08:00
yetone bb33142eae gateway: a relayed Claude run cut from a busy, forked or side-questioned session keeps its 5m cache (linkaww)
The relay's runs keep the cache lifetime of the session they go on from
(savedSession.cachePrefix). Three of the four places that make a
savedSession left it out: branch (a fork's turn), retryBranch (a turn
sent again while its run is busy) and branchAt (the turn after the
interactive mode's side question). cachePrefix.runTTL() reads an empty
ttl as an hour, so each such run was started with
CLAUDE_CODE_PROMPT_CACHE_TTL=1h under a 5m pick, and wrote 1h cache
entries. Each now carries its run's cachePrefix, as shelve did.

Tests: the fork, busy-retry and side question harnesses log each run's
CLAUDE_CODE_PROMPT_CACHE_TTL; with promptCacheTtl 5m picked
(pickFiveMinutes), everyRunKept5m requires every resumed run to have 5m.

Run (on mote, at this commit, base 2dac9b84e = origin/main just fetched):
- go test -count=1 -run of the side question, busy retry, fork and
  TestClaudeRunKeepsTheUsersCacheTTL tests ./internal/gateway: ok
- go test -count=1 -timeout 45m ./... through suite.lock: every package
  ok (88), exit 0
- gofmt -l internal/: nothing
- go vet ./internal/gateway, GOOS=linux go vet -tags nogui, GOOS=windows
  go vet: ok

Broken by hand: the three cachePrefix carries taken out, the busy-retry
test (print and interactive), the fork test (print and interactive) and
the side question test each fail "a branch's run, want a 5m cache as its
parent's".

Not tried: a real Claude subscription, and linkaww's Mac -> Docker
magpie chain. The second half of the report (a 5m pick and an unmarked
side call, and no pick at all) is the next commit.

Reported-by: linkaww on Discord
2026-11-08 02:03:17 +08:00
yetone dca338f3a3 gateway: a relayed Claude run keeps its cache as long as the request's own marks ask (Linka)
v0.1.3247 (dbc74414b) gave a bridge run the prompt-cache TTL of the
user's pick, but read it only on the machine the relay runs on: its env,
settings.json's env, then promptCacheTtl. A Docker magpie has none of
them, so it fell back to 1h while the Mac it serves was set to 5m. The
Mac's pick reaches the remote only as the cache marks its Claude Code
puts on the request.

A new run's TTL is now picked by runTTLFor:
1. FORCE_PROMPT_CACHING_5M on this computer: 5m, as Claude Code does.
2. The request's own marks: the longest TTL on its tools, system,
   messages or the request itself (askedCacheTTL, Request.askedTTL).
3. claudeRunTTL: this computer's CLAUDE_CODE_PROMPT_CACHE_TTL or
   promptCacheTtl.
4. 1h, only for a request with no marks (Chat, Responses clients).

The run started from a saved transcript (replaySession) follows it too.
Warmup and usage runs have no request and keep claudeRunTTL
(cleanClaudeEnv). Linka's FORCE_PROMPT_CACHING_5M=1 workaround keeps
working. Docs: claude-subscription-bridge.md.

Tests: four new cases in TestClaudeRunKeepsTheUsersCacheTTL (the child's
env and the first message's marks): client 5m with nothing set here;
client 5m over this computer's 1h; client 1h over its 5m; forced 5m over
client 1h. New TestAskedCacheTTL with bodies shaped like Claude Code's
(billing line, marked system blocks, the last message marked).

Run on mote: go vet ./internal/gateway for darwin, linux and windows;
gofmt clean; go test -count=1 -timeout 45m ./internal/gateway: ok (958.9s), at base 578053d6a.
Broken by hand: startRun back on claudeRunTTL(os.Environ()), three of
the four new cases red (client 5m, 5m over 1h, 1h over 5m); the forced
case passes on the old code too, as it should.

Not tried: a real request through a real Docker magpie. Linka's other
ask, a settings UI for the remote's built-in Claude Code and the Agents
page not detecting it, is not addressed here.

Reported-by: Linka
2026-11-07 23:25:10 +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 dbc74414bb claude: a relayed run keeps its prompt cache as long as the user picked, not always an hour
linkaww (Discord #feedback, server v0.1.3237 in Docker, Claude Code
2.1.319) set the Agents page's prompt cache for the main conversation and
subagents to 5 minutes, and settings.json had "5m", but 237 of 241
relayed requests since 11-01 wrote an hour's cache. cleanClaudeEnv took
CLAUDE_CODE_PROMPT_CACHE_TTL out of the run's environment and put back
"1h" every time (17363b7e3, #626), for every run, warm-up and model test
the bridge starts, -p and the interactive helper alike. Claude Code reads
the variable before the setting, and a saved account's Claude Code reads
its own folder's settings.json anyway, so the pick never reached it.

The hour was pinned because magpie marks the caller's instructions (or
the history's last whole chunk) in the run's first message, and
Anthropic refuses a 1h mark after a 5m one. That reasoning stays: the
run's lifetime and magpie's mark are now one value.

- claudeRunTTL resolves the user's pick as Claude Code 2.1.316 does:
  FORCE_PROMPT_CACHING_5M, then CLAUDE_CODE_PROMPT_CACHE_TTL (in magpie's
  environment or settings.json's env), then settings.json's
  promptCacheTtl. Nothing set (or a value Claude Code doesn't take) is
  an hour, as before.
- cleanClaudeEnvTTL gives the run that value; FORCE_PROMPT_CACHING_5M
  is now blocked too, since it is folded into the value (before, a user
  with it set got a 5m Claude Code under magpie's 1h mark).
- Request.cacheTTL / runMark: magpie's mark in the first message has
  the same lifetime.
- cachePrefix.ttl: a run going on from a saved session keeps the
  lifetime it started with, so an old 1h mark never sits under a newer
  5m pick (an older session with none is an hour's). A replayed session
  has no marks and takes the pick.
- The incoming request's ttl is not followed for ordinary requests:
  Claude Code 2.1.316 sends ttl "5m" explicitly as its default for a
  non-subscription endpoint (MTe: {ttl:"5m",reason:"default"}), so a
  5m mark can't tell a pick from the default, and following it would
  turn the hour off for everyone. Opted-in client marks
  (X-Magpie-Cache-Marks) already run with Claude Code's caching off and
  are unchanged.

Run (mote, at this tree on origin/main 9ed0f1fa4):
- go test ./internal/gateway/ (-count=1, 45m): ok, 980s.
- go vet ./internal/gateway/ on darwin, GOOS=linux, GOOS=windows: ok.
- gofmt -l internal/: clean.
- TestClaudeRunKeepsTheUsersCacheTTL: six cases (nothing picked, Agents
  page 5m and 1h, settings.json env, magpie's env, forced 5m) through the
  bridge with a scripted Claude Code that logs its environment and the
  first message it is told.

Broken by hand:
- "CLAUDE_CODE_PROMPT_CACHE_TTL=1h" put back in cleanClaudeEnvTTL: four
  of the six cases red (each 5m pick).
- runMark always 1h: the same four red on the first message's mark.

Not tried: a real Claude subscription request with 5m picked (no real
run, so the cache_creation split was not read from Anthropic); Docker
web mode; Windows and Linux runs of the test (it uses a shell script and
skips on Windows). The full go test ./... runs under the suite lock on
mote after the push. Idle runs are still kept an hour (idleLongest); with
5m picked that only holds the process longer. Branch sessions (cut
copies) carry no lifetime and take the hour, which is always a valid
order.

Reported-by: linkaww
2026-11-07 20:44:51 +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 665b9aff12 gateway: a reply of several requests tells the last one's prompt, bills them all
Claude Code reads a reply's input, cache_creation and cache_read as how
full its conversation is. A reply more than one upstream request made
summed all three across them. In the bridge: Claude Code's own
ToolSearch/WebSearch going on into the answering message, a TUI message
written after its call was told (lateUsage), a cut stream's retry
(b42ff722). Each later request re-sends what the earlier one had, so the
reporter's TaskStop reply after a ToolSearch said cache_read 1,154,857
(577,009 + 577,848) and cache_creation 829 (253 + 576) for a ~577k
conversation, and Claude Code compacted early. 12 of their 30 replies
after ToolSearch were about 2x.

The translated route summed the same way across its tries (#5115): the
empty reply asked again (#667), a loop's re-ask (#1359), a cut reply's
continuation (#853), and search.go's web search rounds. The Anthropic
passthrough has no in-reply fold; each try is its own call.

Usage.after (claude_subscription.go) replaces plus at these joins: the
client is told the last request's input, cache writes and cache reads,
and every request's output and reasoning (all of it was streamed). The
earlier requests' prompts go in Deferred, which the ledger bills
(billed()) and no encoder tells. Usage.restart makes a later request's
prompt counts replace the earlier's, a zero too, so a later request that
reads nothing from the cache isn't told, or billed again, the earlier's
reads. Cache writes are last-only for the client as well: the later
request reads what the earlier wrote, so summed they count it twice.
ggbdpq's #5115 analysis named the translated route's case; no code of
theirs was used.

Tests (usage_last_prompt_test.go), on the reporter's numbers:
- TestClaudeOwnCallReplyTellsLastPrompt: bridge, told 6/576/577848,
  billed 8/829/1154857; and a second request that missed the cache.
- TestClaudeTUILateMessagePromptNotTold: interactive mode's late message.
- TestRetriedReplyTellsLastPrompt: Gemini three reasoning-only replies
  then an answer, Chat and Anthropic clients; ledger has all four.
- TestLaterTryZeroCacheReadNotTold: a continuation and a search round
  whose later request reads 0 from the cache.
Tests that pinned the summed client numbers now pin the last request's
and check the billed sum (CachePartialUpdateMatrix, Probe1717 zero split,
cut stream retry, own WebSearch, search rounds, StreamCutUsage renamed
TestStreamCutUsageTellsLastTry).

Run (mote, Go 1.26.8, -tags nogui):
- The new tests on origin/main ca77a9ea8: red, the client told
  8/829/1154857 (the report's numbers), prompt_tokens 2,000,000 for
  four 500k tries.
- Broken by hand: restart dropped -> TestClaudeCutStreamGoesOnInRetry
  and the cache-missed case red (reads billed twice); after() put back
  to plus -> 12 tests red; restart on the translated tries dropped ->
  TestLaterTryZeroCacheReadNotTold red (cache reads 200 billed, 111
  told). The last one was green before that test was added.
- go test ./internal/gateway/ whole: ok except
  TestClaudeInternalMessagesKeepCacheWrites, which pinned the sum and
  was updated after; that test with the usage, cache, search,
  continuation and TUI tests then ok (61.8s).
- go vet ./internal/gateway for darwin, linux and windows; gofmt clean.
- The full suite runs after the push (mote's suite lock held 3h+ by
  another session).

Not tried: a real Claude Code account or the real TUI, the reporter's
session, a real Gemini/translated provider, Windows or Linux runs of
the package.

Reported-by: sleepy_shibe (Discord)
2026-11-07 10:03:52 +08:00
yetoneandggbdpq 766d2a9f54 gateway: a Claude turn sent again while its run is busy with it goes on from a copy of its session (#5405)
A client's connection dropped mid-reply and its request was retried,
with no cancel reaching magpie (#5405, margbug01: a gateway between
the client and the server magpie retried after "unexpected EOF"). The
run the first attempt resumed was still busy with the very turn, so
resume and unshelve found nothing, and the retry started a new Claude
Code told the whole conversation in one message: only Claude Code's
own system prompt and tools read from the cache, the rest (92K to 142K
tokens in the report) written again on every retry.

retryBranch, tried in start between unshelve and retire, finds a busy
run of the account whose last heard request is this one, message for
message, and starts the retry's run from a copy of that run's session
cut before the turn (cutReply at backLine/backMsg), told only the
turn, as a branch off a side question already is. The busy run is left
alone; when both park at the same key, keepIdle lets the older go.
nil, and the conversation told whole as before, when no run matches,
the client places its own cache marks, the run was or is being taken
back, it was started for this turn (nothing before the turn to cut
at), or the session can't be cut (logged).

Changed from ggbdpq's patch: it matched with follows, which also takes
a request that goes on past the busy run's turn; the retry is matched
by the heard request's key alone. A copy cut for an older run is
discarded when a newer one is taken, a failed cut is logged as the
patch's notes say, and a run with a reply id but no line yet is cut
by the reply, as branchAt does. The test waits for the busy run to
have heard the turn instead of sleeping 200ms, and stops the held
first attempt in t.Cleanup, so a failing assert doesn't leave it
running. The doc's "goes on to step 3" now says step 4.

Run (mote, -tags nogui):
- TestClaudeTurnSentAgainWhileItsRunIsBusyBranchesOffItsSession
  (print, interactive) -count=3: ok.
- Broken by hand: claude_subscription.go back to origin/main, test
  kept: FAIL in both modes, "0 runs branched, 2 started anew, want one
  of each". Restored: ok.
- TestClaudeTurnPastABusyRunsTurnIsNotBranchedOffIt (print,
  interactive): a turn sent past the busy run's own, with a reply the
  client has, is told whole (one message, or the interactive mode's
  transcript), not branched off the busy run. -count=3 with the other
  test: ok; -race -count=5 of both: ok.
- Broken by hand: the match back to follows: FAIL in both modes, "the
  turn past the busy run's was branched off it" (nextTurn gives its run only
  "now commit it", the turn and reply before it lost). Restored: ok.
- -run TestClaude ./internal/gateway/: ok 139s.
- -race -count=5 -run of the busy-retry, fork, side-question,
  given-up, rewind, unshelve and branch tests: ok 52s.
- go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of
  internal/gateway: clean.
- gofmt -l on both Go files: empty.

Not tried: a real Claude subscription with a real dropped
connection. The full suite runs after the push.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
2026-11-06 10:04:01 +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
yetone 60fe6645a9 claude: a caller's folder Claude Code would ask about is known before the run, and the session kept (sleepy_shibe)
sleepy_shibe on Discord (magpie 0.1.2996, Claude Code 2.1.318, own
account, interactive mode): message counts 36, 65, 85, 108, 128 for one
conversation. Confirmed at origin/main 74d1cda42: a caller's folder Claude
Code asked about was passed over for untrustedFor (10 min) only. Past
that, the next run went in the caller's folder again, claudeSessions
pointed at another project folder than the conversation's session in
magpie's folder, so `from` went nil and the run was told the whole
conversation; Claude Code asked about trust, startTrusted dropped
req.branch and started from nil in magpie's folder (the deferred
from.discard() had already removed the session), told it all again.

Now, for the own account in the interactive mode, each run first decides
as Claude Code does (untrustedHere -> claudeTrusts), from
hasTrustDialogAccepted in claudeProfilePath()'s .claude.json
(provider.ClaudeTrustedProjects; a missing file is nothing trusted, an
unreadable one unknown, which goes on as before). The rules are Claude
Code 2.1.316's, read from its bundled JS (UI/zh/jh/Y0/lr): the key of the
repository's main checkout (a worktree's is the checkout it was added
from), or any folder from the run's up to the git root and never past it
(a nested repository isn't trusted by its parent), every folder above
outside a repository; NFC keys, forward slashes on Windows
(claudeTrustKey, shared with claudeTrustKeys). An untrusted folder stays
in magpie's folder with its session; a folder trusted since is run in on
the next run. When Claude Code asks all the same, startRun keeps `from`
and startTrusted goes on from it in magpie's folder with the branch.

Run (mote, at this tree on 74d1cda42):
- go test ./internal/gateway -run TestClaude: ok (118s);
  go test ./internal/provider -run Claude: ok
- GOOS=windows and GOOS=linux go vet ./internal/gateway ./internal/provider: ok
- win-run go test ./internal/gateway -run TestClaudeTrust: ok
- real Claude Code 2.1.316 in a sandbox HOME + CLAUDE_CONFIG_DIR (dummy
  key, no account), tmux, 10 cases: repo/subfolder/parent-in-repo/
  worktree-of-trusted/worktree-itself trusted -> no question; worktree
  under a trusted parent, nested repo in a trusted repo, repo under a
  trusted parent, unrelated folder -> asked; outside a repo a trusted
  parent -> no question. All ten match claudeTrustedBy.
Broken by hand:
- untrustedHere returning passedOver only (the old choice):
  TestClaudeTUIUntrustedFolderKeepsItsSession/untrusted red (helper
  started twice) and TestClaudeTUIFolderTrustedLaterRunInAtOnce red (ran
  in magpie's folder).
- startTrusted dropping req.branch and starting from nil (the old
  fallback): .../unknown red (resumed a new transcript, not the
  conversation's session).
Not tried: the owner's real account or a real turn through the gateway
(no sign-in in the sandbox); Claude Code 2.1.318 itself (2.1.316 is
installed here); a Windows or Linux real Claude Code; the full suite
before the push (it runs after, through the suite lock).
2026-11-06 04:35:12 +08:00
yetone 498b6419ff claude: a turn Anthropic refuses in the interactive mode as a third-party app's is asked again as claude -p, and the agent's prompt is remembered
Raven (Discord #general): Cindy with Pi as its engine, routed through
group/auto to a Claude subscription, failed every turn with "Anthropic
refused an interactive-mode turn on claude-opus-5-5 as a third-party
app's", and the message told them to turn the interactive mode off in
Settings, which makes every request of every agent run as -p (about twice
the plan count).

Now, with the interactive mode on:
- a refusal carrying "Third-party apps now draw from your extra usage",
  met before a byte of the reply reached the client (stream head, or a
  whole reply with no parts), is asked again once as claude -p
  (redoAsPrint); the client sees only the -p answer;
- the agent's system prompt (sha256 of its first 2KB, billing header
  dropped, so Pi's trailing <cwd> doesn't change it) is remembered for
  12h, and its next turns go straight to -p (wantTUI, req.tuiRefused,
  clientCache.print) while every other agent stays interactive;
- a refusal after the reply had begun (keepalive sent, or text said) is
  not redone, so nothing is spent twice; the prompt is still remembered
  and the message now says magpie runs its next turns as -p: ask again;
- a -p run that is refused too fails as before ("run as claude -p"),
  once, no loop;
- the setting is untouched; with it off (claudePrintMode) everything is
  -p as before. The run is the real claude binary, nothing else changed
  in what is sent.

This reverses the #4503 call (fbbdf6e05, v0.1.2754: no automatic -p redo)
and the 10-31/11-01 "nothing ever runs as -p with the interactive mode
on", for this refusal only. The switch's foot, the Settings text (en, zh,
zh-TW, ja, de) and docs/subsystems/claude-subscription-bridge.md say so.

Run (mote, at this head rebased on 1100ed649):
- go test -run 'ThirdParty|TUIRefusal|ClaudeTUI|ClaudeSubscription|ClaudePrint'
  ./internal/gateway/ ok; Budget/i18n tests in ./internal/gui ok
- gofmt -l clean; go vet ./internal/gateway (darwin, GOOS=linux,
  GOOS=windows) ok; GOOS=windows go vet ./internal/gui ok. GOOS=linux go
  vet ./internal/gui fails in wails' cgo-only linux files on mote, the same
  on main, untouched here.
- GUI, chromium and webkit: claude-mode, claude-tui-setting,
  claude-quota-onboarding, mobile-web, i18n-keys, gui-zh-tw, gui-ja,
  gui-de: 57 pass, 6 fail in each engine; the fails are i18n-keys "a
  plugin's words are its own" (#5327, #5332) and mobile-web (#3952,
  #5013), the same 6 at origin/main 1100ed649 alone.
- Red on the old code: the new tests run against 1d704f819 all fail (400,
  the old "turn the interactive mode off" message).

Broken by hand: dropping len(col.res.Parts)==0 from the whole-reply redo
turns TestClaudeTUIThirdPartyRefusalAfterWordsNotRedone/whole red;
dropping the refusedTUI call turns ...PromptRemembered, ...AfterStart and
...AfterWords/stream red.

Tests use the real Pi 1.1.0 system prompt (testdata/workdir/pi-1.1.0.json)
with its cwd changed per conversation.

Not tried: a real Claude account (no refused turn reproduced against
Anthropic; the refusal text is the one the reporter's log and #4503
carry). A -p run continuing with tool results under a remembered prompt
(the wantTUI resume path) has no test of its own.
2026-11-06 01:20:14 +08:00
yetone 2947685999 claude: an interactive run's calls keep the conversation they answered when their line comes late
kay20475 on X (magpie 0.1.3005, local magpie -> shared server magpie ->
Claude subscription, interactive bridge): a Claude Code sub-agent's
requests on one account read 99%, 6%, 6%, 99% from the cache; the two 6%
requests were 169.1k each, 35s apart, about 3s long with a short reply.
That is the shape of Claude Code's AgentSummary: every ~30s it sends the
sub-agent's conversation with its last results and "Describe your most
recent action in 3-5 words", while the sub-agent's own run has already
taken those results.

Cause. Such a request finds no run waiting on its calls and should go on
in a branch of the sub-agent's run's session (branch). branch takes it
only when the conversation stored on the call's line (callLine.told)
matches the one before the reply. park stored that only on lines it
already had. The interactive mode streams a reply first and reads its
session lines from the file afterwards (118-162ms after the call). So the
run parked before noteLines had the call's line, and the line came in
with no conversation. The next park then gave it the next request's
conversation. branch returned nil, and every AgentSummary (and every
fork directive) was told the whole conversation in a new Claude Code,
pasted as one text block. A single block can't match the cache beyond
the tools and system prompt, so 6%, and the next summary missed the same
way because its tail differs.

Fix. park also keeps the conversation for each call the client was shown
(r.shown), as a line with no uuid yet. noteLines keeps it when the line
comes, and branch skips lines with no uuid.

Test: TestClaudeForkBranchesOffTheLeadsSession/interactive now has the
fake write the call's session line after the reply's stream, once the
result is handed over, so after the park, which is the real order.
Broken by hand: with this test and the old claude_subscription.go on
mote, it fails ("told it whole", want "branched at line-...").

Run on mote at this tree (base 4cb7159f1): gofmt -l clean; go vet
./internal/gateway on darwin, GOOS=linux and GOOS=windows ok; go test
-timeout 45m ./internal/gateway (679s) ./internal/claudetui
./internal/claudebridge all ok. The fork/side-question/cut tests
-count=3 ok. The full ./... suite and the GUI suite were not run (no
GUI or other-package change).
Rebased on 351844594 (GUI only since 4cb7159f1): go test -count=1 -run
'Claude|Fork|Branch|Subscription' ./internal/gateway ok (77s) on mote.

Not tried: a real Claude Code AgentSummary against a real account. The
reporter's requests are matched by shape only (size, timing, short
reply). Ruled out: the remote-magpie hop. The bridge doesn't key runs on
headers (only anthropic-beta for safeguards), so losing
x-claude-code-session-id can't move a turn off its run. Not fixed here: a
sub-agent loop with no plain reply, told anew in the interactive mode, is
still pasted as one text, so a new run for it reads only tools+system.
2026-11-05 14:05:54 +08:00
yetone 49e382735f claude: a side question after a run's first reply of words branches by the reply's id
sleepy_shibe (Discord #feedback, magpie 0.1.2948, Claude Code 2.1.318,
claude-opus-5-5, macOS, interactive mode): when the last turn's reply
was words only, the turn after a prompt suggestion found no run
("claude: no run waits for this turn: its run ended 0s ago: the
interactive Claude Code can't go on with this turn") and a new Claude
Code was told the whole conversation as a transcript. With a tool call
in the turn it branched. 3 sessions, 7 times.

Cause (the reporter's reading, checked in a test): the interactive mode
streams a reply and the bridge hears its session line only later, from
the file. resume saves run.lastLine as the turn's backLine. A run's
first reply of words has no line heard yet, so backLine, behindLine and
the shelf's behindLine were empty while behindMsg (from message_start)
held the reply's id. branchAt returned nil at `at == ""` with no log,
and the run was let go. With a tool call, the run waited on the call and
heard the call's line first, so there was a line to cut at (8ac5f98e).
A run after a branch is a new run, so every first reply of words after
one hit it.

Fix, every path that cuts behind a side question:
- branchAt cuts with the reply's id alone when no line was heard.
- cutReply takes an empty uuid with a msg and cuts after the reply's
  last main-thread line; cutSessionAt's empty-uuid check moves to its
  uuid callers (cutSessionWhere does the polling).
- unshelve's search for a session behind a side question accepts a
  behindMsg alone, and cutBehind cuts by cutReply when either is set.
- cutReply waits for the reply's lines up to cutWait before falling
  back to the uuid's line. Before, a run that had heard an earlier
  turn's line cut after it at once when the new reply's lines weren't
  written yet, dropping the last turn.

Tests:
- TestClaudeInteractiveSideQuestionAfterAFirstReplyOfWordsKeepsTheReply:
  the fake writes the reply's line late; first turn words only, the
  suggestion, then "now commit it". The next turn must resume a copy of
  the run's own session (U1 and A1), told only the new turn. On
  origin/main ed7aeb052 it is red and logs the reporter's exact line.
- TestClaudeShelvedSideQuestionAfterAFirstReplyOfWordsKeepsTheReply:
  the same run let go past idleMost; the shelved session (behindLine
  empty, behindMsg set) is found and cut.
- TestClaudeCutReplyWaitsForTheReplysLines, and two id-only cases plus
  two error cases in TestClaudeCutReplyKeepsTheWholeReply.

Broken by hand, each red then restored: branchAt's old guard (the
interactive test), unshelve's old condition and cutBehind's old route
(the shelved test each), cutReply falling back to the uuid without
waiting (the wait test).

Run (mote, at this tree on origin/main ed7aeb052):
- go test -tags nogui -count=3 -run 'TestClaudeCutReply|TestClaudeShelved...|
  TestClaudeInteractiveSideQuestion|TestClaudeCutSession' ./internal/gateway/: ok
- go test -tags nogui -count=1 -timeout 45m ./...: ok, 87 packages, no
  FAIL (gateway 770s, claudetui 75s); log kept whole.
- go vet -tags nogui ./internal/gateway/, GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./..., go build ./..., GOOS=linux go build
  -tags nogui ./..., GOOS=windows go build ./...: ok
- gofmt -l: clean

Not tried: a real interactive Claude Code 2.1.318 with a real account;
the fake reproduces the timing (the reply's row heard after the stream
ended), not the real TUI. A reply split into several rows whose later
rows are not yet written when the cut runs would still be cut short
(as before this change); not seen.
2026-11-05 04:23:56 +08:00
yetone d892dd6a22 gateway: a Claude conversation keeps the folder it named first when its caller moves
EricWvi on X (Claude Code -> local magpie -> a magpie on a server -> a
Claude subscription): the cache read flipped between under 10% and over
90%, each drop on a turn whose folder had changed (.../frontend, then
.../frontend/src). Claude Code 2.1.316 says a cd as a later
"# Environment update" message, "Primary working directory: /y (was /x)".

clientNamedWorkPlace took the last folder named, so a run started again
for the conversation (saved session resumed, branch, replay) got a
different prefix than its first run:
- a caller elsewhere: envTurnsNote names the folder, so append.md changed;
- a caller on this computer: the run worked in the new folder, whose
  session project doesn't hold the saved session, so --resume was lost
  and the whole conversation was told again.
Either way the whole conversation was written to the cache again.

Now the first text that names a folder decides it (within that text, its
last line, so "said twice" in one system prompt keeps its meaning). The
move still reaches the model in the conversation as the caller said it.
No text is added to the prompt; the note's wording is unchanged.

The reporter's per-turn flips on a v0.1.2879 server are the earlier
safeguards restart (git_state.cwd in safeguardsKept), fixed by 59c130603
in v0.1.2882 while the tap is live.

Run (mote, via mote-run, at this tree):
- go test -tags nogui ./internal/gateway -run 'TestClaude|TestWorkDir'
  -count=1: ok (114.9s)
- go test -tags nogui ./internal/gateway -count=1 -timeout 45m: ok (778.6s, mote at load ~45)
- go vet -tags nogui ./... ; GOOS=linux and GOOS=windows go vet
  ./internal/gateway: ok (cgo deprecation warnings only)
- gofmt -l internal/gateway: clean
Broken by hand: without the `if dir != ""` guard,
TestClaudeTUIConversationKeepsItsFolderWhenTheCallerMoves is red in both
subtests (caller elsewhere: append.md names .../frontend/src; caller on
this computer: --resume of another session, not s<pid>).
Not tried: a real Claude Code cd against a real remote magpie and
subscription; whether a model told the first folder in envTurnsNote after
a move misreads the environment update (not measured).
2026-11-05 01:37:56 +08:00
yetone d3c544ddf4 claude: a replayed transcript marks no earlier turn as the one to answer
The interactive mode gives a conversation no run has to a new Claude
Code as its own transcript (replaySession): a user line with the
messages before the last reply, the reply as the assistant line, and
the turn after it typed. The user line was rendered with
renderClaudePrompt, which ran historyEnd again on the cut messages, so
for U0 A0 U1 A1 U2 it was history(U0, A0) + <current_turn>U1, "the turn
to answer now", followed by A1, then U2 typed. U1 was answered already;
the reporter saw the model answer an old question again, and say
earlier tool calls had no results (愛睏柴犬阿茶 on Discord #feedback,
with the analysis and the fix suggested).

renderClaudePrompt is now renderClaudePromptAt(req, historyEnd(...));
replaySession calls it with the split at the end, which tells every
message before the reply inside <conversation_history> and closes it
there, with no <current_turn>. Every other render is unchanged.

Siblings: historyEnd has two callers, replaySession (whose own split,
on the whole request, is right: the reply and the turn typed after it)
and renderClaudePrompt. replaySession is the only place that renders a
cut slice of the messages (grep 'Messages = .*Messages\[:').
renderClaudeTurn (the typed turn) has no history marks.

Run (on mote, mote-run):
- go test ./internal/gateway -run TestClaudeTUIReplayMarksNoEarlierTurnCurrent:
  red on the old code (all 5 subtests: two turns, three turns, tool
  results in both turns, tool results only before the reply, the
  client's calls after the reply), green with the fix.
- Broken by hand: put renderClaudePrompt(&before) back in replaySession,
  the new test went red; restored.
- go vet ./internal/gateway, GOOS=linux and GOOS=windows go vet: ok.
- go test ./internal/gateway -run 'Claude|Replay|Prompt|Turn': ok 124.6s.
- go test ./internal/gateway -run 'Loop|Guard|Doc': ok.
- gofmt -l internal/: clean.

Not tried: a real Claude Code resumed on such a transcript with a real
account (the change to what the model sees was checked in the
transcript file only); the full suite runs after the tag.
2026-11-04 14:26:27 +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 8468afecb3 claude: a turn's images say they are attached, so the file notes after them are not taken for the images
Claude Code notes each image it is given ([Image: source: .../images/N.jpg])
in a note after the message, with a path in the gateway's temp folder. With
no history before the turn, nothing said what they are: the model took the
paths for the images, said it could not see them and quoted the paths as on
another computer (sinsoul1647 on Discord, v0.1.2862, 7 tool-result photos).
The prompt (renderClaudePrompt) and a saved session's turn (renderClaudeTurn)
now say the images, tool results' too, are in the message.

Tried: real claude 2.1.316 on mote against a fake Anthropic server, with
-p user images, MCP tool-result images, a url source, the TUI paste and a
resumed transcript: every one reached the API as image blocks, so the loss
is the model's reading of the notes, not a dropped image.
Not tried: the reporter's client; whether the model stops quoting paths.
Broken by hand: with the note left out, TestClaudePromptSaysToolResultImagesAreAttached is red.

Run at the pushed head (rebased on 8e27369bd): gofmt -l clean; go vet gateway linux and windows ok; go test ./internal/gateway -run Claude|Subscription|Prompt|Image ok (not the full gateway suite: another full suite was on mote).
2026-11-04 00:14:37 +08:00
yetone 40a287b217 gateway: a quiet Claude Code run begins the reply and pings its client (#5043)
A streamed Claude subscription turn whose run says nothing for minutes
(the interactive mode tells a message only once it is whole; a long
conversation replayed to a new Claude Code is prefilled uncached first)
gave its client the held stream's 200 and comments, and those stop at
keepaliveLongest (5 min). Claude Code 2.1.316's byte watchdog then ended
the request 300s later, at 599s: the reporter's 599.29s and 599.33s.
Each cancel aborts the TUI run (letGo), so the retry is a new Claude Code
that replays the history and writes it to the cache again (#3808).

keepBridgeHeard wraps the run's events for a stream: after
bridgeHeardAfter (1 min) of a quiet run it sends an empty KStart, which
makes relay begin the reply (message_start), and a KAlive every
keepaliveEvery while it stays quiet, up to translatedQuietLongest, so the
client gets its protocol's pings (#2316's pattern). The hold still holds
the frames to holdLead and passes an error over. The run's own start
later adds its usage (collector), and a failure in the first minute is
still a status.

The gain is bounded. Claude Code 2.1.316 turns every 10s with bytes into
a ping of its own (RSr, __n=1e4) and counts 30 pings in a row (vSr=30),
so a stream of pings and comments alone ends 600s after its last other
event. The run now has until about 14 minutes (message_start at ~4 min
plus 600s), where it had 599s. The reporter's retries answered first at
385s and 527s.

Run:
- Real claude.exe 2.1.316 (-p, sandbox HOME, env -i) against a fake
  Anthropic server:
  - headers at 3s, comments to 300s: ended at 598.38s ("[byte-watchdog]
    ... no bytes for 300000ms"; "Stream idle timeout before first event").
  - comments forever: ended at ~600s from headers ("no chunks received
    for 300s").
  - no headers: "Request timed out" at 360s.
  - this fix's shape (message_start + ping at 300s, a ping every 60s):
    lasted to 904s, then "no chunks received for 300s" and fell back to
    non-streaming. That is the 600s bound above.
- mote-run: go test -tags nogui -count=1 -timeout 45m ./internal/gateway
  ok (675.8s), at this change before its comment-only edits.
- mote-run: go test -tags nogui -count=1 -timeout 45m ./internal/gateway
  ok (680.2s) again at this tree, rebased on origin/main 5ee5274bd.
- mote-run: TestClaudeBridgeQuietRunKeepsClientAlive -count=3 ok, and
  gofmt -l internal/gateway clean, at the committed tree.
- mote-run: GOOS=linux and GOOS=windows go vet -tags nogui
  ./internal/gateway ok.

Broken by hand:
- Without the keepBridgeHeard call, the new test fails: no
  message_start or ping before the reply.
- Without the synthetic KStart (KAlive alone), it fails with "0 pings
  while the run was quiet": the client gets comments only.

Not tried:
- A real Claude account, the interactive (TUI) mode, a real replay.
  The test uses a -p fake Claude Code. The wrapper doesn't depend on
  the mode.
- Chat and Responses clients through the bridge. Their encoders take an
  empty KStart, but no test covers it here.
- A run quiet for longer than ~14 min still ends. Only a real event of
  the reply would keep it alive (#5060).
- magpie's pingEvery comment in gateway.go describes 2.1.311's count
  without the synthetic pings. Not changed here.
2026-11-03 17:36:51 +08:00
yetone 3088872e63 claude: an interactive run goes on when only Claude Code's varying safety context changed (xybio)
xybio on Discord (Claude Pro, Claude Code through magpie, likely in auto
mode) saw it twice: right after the 5-hour window reset, one message took
the window from 100% to 0%. Their Usage page for the day (claude-opus-5-5):
- 62 requests and 17M tokens, almost all of it cache (input 102,
  output 31.3K);
- a 29.4% cache hit rate, so about 12M tokens were written to the cache,
  around 290K for each of the 41 that succeeded.
That is the whole conversation written again on almost every request.

The cause is in the bridge. With server review on, which it is for a Claude
account (AutoModeReviewed), every request carries Claude Code's
`safeguards`. The interactive mode's Claude Code reads
CLAUDE_CODE_EXTRA_BODY only as it starts, so setSafeguards restarted the run
whenever the field differed in any byte. A new run is told the whole
conversation, and that writes it all to the cache again.

The field's classifier_context differs on nearly every request. That is in
Claude Code's own code (2.1.316, Jmr):
- prior_turn_context grows with each tool round's tool_use_ids;
- git_state.status follows every edit;
- system_reminders, artifacts, text_provenance and the shed list vary too.
So every tool round and every turn of one message started a fresh run
(4 turns gave 4 runs in the new test on the old code), each paying a full
cache write of the history.

Change: in an interactive run, setSafeguards compares safeguardsKept forms.
That form leaves out the parts Claude Code itself names as variable and
sheds over its 256KB budget:
- prior_turn_context, system_reminders, artifacts, text_provenance, shed;
- Chrome's tabs;
- git_state except cwd, root, branch and default_branch.
When only those changed, the run goes on with the context it started with.
A change to the rules, permission or auto mode, folders, or the
repository and branch still restarts it. A field that isn't the expected
JSON is compared whole. The -p path is unchanged: it takes every change in
place through apply_flag_settings. The cost is that the server classifier
sees those varying parts as they were when the run started. This is noted
in docs/subsystems/claude-subscription-bridge.md.

Run at the pushed head (52d69934f, on origin/main 9335e23d3), on mote:
- go test -tags nogui -run 'TestClaudeTUI|TestClaudeBridgeSafeguard|
  TestClaude.*Safeguard|AutoMode' ./internal/gateway: ok.
- gofmt -l internal/gateway: clean.

Run at 4ff686b49, the same tree before the rebase (the rebase brought in
only 9335e23d3, outside these files):
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway: ok.
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway: one red,
  TestClosedBeforeSentEveryTimeSaysWhy (a bare EOF on the Codex
  closed-before-sent path, which this change doesn't touch). It passed
  30 of 30 alone. Filed as #5031.

Broken by hand:
- The comparison off (always restart):
  TestClaudeTUISafeguardsVaryingPartsKeepTheRun is red, "4 turns ...
  started 4 runs, want 1".
- The comparison always passing: the same test is red, "a changed rule
  went on in 1 runs", and so is TestClaudeTUISafeguardsInEnv.

Not tried:
- A real Claude account in auto mode through the interactive bridge, and
  the real 5h meter before and after.
- Whether xybio's windows also fell in the earlier cache regressions
  (v0.1.2677 to v0.1.2799). The local-classifier path, where each check is
  a one-off run that re-writes its transcript, is not changed here.
2026-11-03 14:58:57 +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 17d2ef10fa claude: a conversation's instructions stay after Claude Code's prompt in every interactive run
m4rs0n on Discord: since #2432 (eb8b840dd) a Claude subscription
conversation in the interactive mode broke the prompt cache as it grew.
The same body sent again read 100% from the cache, but the same body plus
an assistant "ok" and a new user turn read only 1,273 of 8,565 tokens and
wrote 7,290. A tool loop read a constant 1,273 every call (opus 1,273,
sonnet 1,197, haiku 2,000: Claude Code's own system prompt).

Cause: eb8b840dd gave a one-off ask (no tools, no reply) its caller's
instructions with --append-system-prompt-file, after Claude Code's own
prompt, and lets that run go after its reply. Every other run (with tools,
with a reply, a resumed or replayed session) kept them in the first pasted
message. So the conversation's next request started a run whose system
block ended at Claude Code's prompt and whose first message held the
instructions. The cached prefix broke right after Claude Code's prompt,
and the rest was written again. A tool loop's runs did the same: a pasted
first message loses magpie's mark (the paste is one text). The bisect
v0.1.2676..v0.1.2677 has only 541102eba (the onboarding mark), which
doesn't touch the request. Before it, those runs were -p, which keeps the
marks.

Change:
- appendsPrompt no longer requires no tools and no reply. Every
  interactive run that isn't lean and has no client cache marks appends
  the instructions. -p keeps them in the first message, where its mark
  holds.
- A run that resumes a session (shelved, branched, branchAt, or a
  replaySession transcript) is given the file again when the session's run
  had it (savedSession.appended). Sessions keep no system prompt, and every
  run key holds the system prompt, so the file is the one the session's
  run had. Appended runs can now be shelved and branched, which they
  couldn't before.
- replaySession leaves the instructions out of the transcript's user line
  when they are appended.
- docs/subsystems/claude-subscription-bridge.md says so.

Tests:
- TestClaudeTUIConversationKeepsItsInstructionsWhereTheFirstAskHadThem is
  the reporter's sequence: A, then A + "ok" + "Now say two words." Both
  runs are given the same append file, which starts with the rules. No
  run is typed them, and no session file holds them.
- TestClaudeTUIResumedSessionIsGivenItsInstructions: a shelved session is
  resumed with its append file.
- TestClaudeAppendInTheInteractiveMode replaces
  TestClaudeAppendOnlyForInteractiveOneOffs. Tools and reply append in
  the interactive mode; client marks and -p don't.
- TestClaudeTUIReplayGoesInATranscript now expects the rules out of the
  transcript's user line and the append flag on the run.

Run at the pushed head, on mote:
- go test ./internal/gateway -run 'Claude|TUI|Subscription|Replay|Branch|Lean|Append|Shelve|Resume': ok.
- GOOS=linux and GOOS=windows go vet ./internal/gateway: ok.
- gofmt -l: clean.
- The full internal/gateway package was red once, before the replay test
  was updated, with the failing test cut off by a tail. A rerun with the
  whole log is under way. Its result goes in the report and, if red, in an
  issue.

Broken by hand: the new tests on origin/main's code fail.
- TestClaudeAppendInTheInteractiveMode/tools and /reply fail.
- The conversation test fails ("given ... and <none> after Claude Code's
  system prompt, want the same instructions").
- The resumed test fails.
- With only the savedSession.appended carry removed, the resumed test
  fails ("<none> ... want A's instructions").

Not tried:
- A real Claude account. The sandbox recipe needs a live login's OAuth
  token copied out, and rotated tokens written back, which this session's
  rules forbid. The prefix claim rests on Claude Code 2.1.316 marking the
  end of its system block itself (recorded 2026-11-03 for #2432), not on a
  new real request.
- Windows and WSL runs of the interactive mode.

Sibling paths:
- Streaming and non-streaming both start runs through startRun.
- count_tokens doesn't write the cache.
- An API-key Claude request is passed through with the client's own
  marks, outside this bridge.
2026-11-03 12:40:21 +08:00
ggbdpq 0561d53521 gateway: spawned Claude Code registers no claude-cli:// URL handler (#4928)
--setting-sources "" keeps the user's own disableDeepLinkRegistration
from loading, so every spawned claude registered the claude-cli:// OS
URL handler again and "Claude Code URL Handler.app" came back after the
user had deleted it. A headless run has no use for an OS URL handler:
the setting is now passed as flag settings (--settings is not one of
the sources --setting-sources controls) on the bridge run and the
warm-up and usage runs beside it, whatever the user's settings read.

Review: applied as ggbdpq posted it (patch sha256 checked against the
issue's). Checked in the Claude Code binary that flag settings read
disableDeepLinkRegistration === "disable" and that --setting-sources
"" doesn't filter --settings. `claude auth login` and `auth status`
take no --setting-sources, so the user's own settings already apply
there; they are not changed.

Broken by hand at the reviewed head: claude_warmup.go and
claude_subscription.go reverted to their parent,
TestClaudeSubscriptionPromptKeepsForeignHarnessOutOfSystem,
TestWarmClaudeAsksClaudeCodeOnce, TestClaudeUsageRunsClaudeCode,
TestAskClaudeTUIOn and TestClaudeUsageTUIOn red. Restored, green.

Run at the pushed tree (this stack of nine on origin/main 3c2dceb34),
on mote (macOS arm64, Go 1.26.8):
- go test -count=1 -timeout 45m ./internal/catalog/...
  ./internal/plugin/... ./internal/davsync/... ./internal/gateway/...:
  catalog, plugin and davsync ok; gateway red on one test only,
  TestCodexPoolSaysTheClientsVersion, the open #4807 (another test's
  Codex identity reaches it in a full package run). It passes run
  alone at this tree, 3 of 3.
- go vet ./... (darwin); GOOS=linux and GOOS=windows go vet -tags
  nogui ./...: ok. gofmt -l on every tracked .go file: clean.
- The hand breaks above ran on this stack before its rebase onto
  3c2dceb34. That commit changed member.go only, nothing these tests
  reach.
Not tried: the GUI suite, since no GUI file changed. Windows and Linux
test runs (the Claude bridge tests use a shell fake and skip on
Windows). No real vendor, Claude Code or network was used; every
case runs against fakes.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-03 07:43:18 +08:00
ggbdpq a8d36b0faa fix(claude): a run let go after answering a prompt suggestion leaves its session for the conversation's next turn (#4914)
Claude Code asks its prompt suggestion after each turn as the
conversation and one message more, and its run goes on with it (#1638):
the run waits on from the suggestion's exchange, under a key the
conversation's own next turn never comes by, since the client leaves the
exchange out of its messages. While the run is kept, that turn finds it
by where it stood before and takes it back to there (resume). But a run
let go past idleMost was lost to its conversation: shelve kept its
session where the suggestion's exchange had left it, or, when the
conversation's own turn had already taken the run back from a suggestion
(-p), not at all — its session was marked taken back, which the file may
not say, and no session was kept. The next turn found no run and no
saved session, and a new Claude Code was told the whole conversation in
one message, a prefix the cache had never seen, written to the cache
again (a 50k conversation: 19k read and 29k written where 49k read and
50 written; the log said no run here had had a conversation one had).

The shelf now keeps a session where the conversation's next turn comes
by, too (savedSession.behind, run.behindKey), and unshelve takes it from
there when no session waits at the turn's own key. A session taken back
is kept once the run has answered a whole turn since (run.replied, set
as a turn ends, cleared at each take-back): the file's lines since are
that turn and what came after, and Claude Code's resume goes on from
them. And a run's end is kept under the boundary before its own
(run.convPrev), so the log of a turn that finds it gone says what became
of it when its last exchange was a side question.

Run: TestClaudeLetGoConversationAfterSuggestionResumesItsSession fails
on the parent a3768cdd1 with the product file alone reverted to it,
tests kept (the ablation: the shelf keeps no session for the
conversation's next turn), and passes on the fixed tree with
TestClaudeLetGoConversationResumesItsSession, whose fake now answers a
rewind; go test -tags nogui -count=1 ./internal/gateway/ (559s, only
the known TestCodexPoolSaysTheClientsVersion flake red); gofmt -l
clean on both files; go vet -tags nogui on internal/gateway for
darwin, linux and windows; go build -tags nogui ./... on all three.

Review, changed from ggbdpq's patch: the session kept under the
conversation's next key is cut before the side question when it is
resumed. ggbdpq's patch resumed the shelved session whole, so the
suggestion's question and answer stayed in the history the model
reads on the conversation's next turn. A shelved session found by
behindKey is now copied up to the line before the side question
(cutBehind: cutSessionBefore at behindTurn for a -p run, cutSession
at behindLine for a TUI run, the branch point both already use), the
copy is resumed and the shelved file removed. If the cut fails, the
session is dropped and a new Claude Code is told the conversation, as
before the patch.

The test now checks the resumed session id is a new copy, that the
copy ends at a2 then a3 with one SUGGESTION left (the first one,
already taken back above a2), and that the resumed run is told a3
alone. Its fake Claude writes stdin lines with printf: sh's echo
turned the JSON's \n escapes into newlines, which split every line
and hid its uuid.

Broken by hand at the reviewed head: claude_subscription.go reverted
to its parent, the test red (no session kept); ggbdpq's own
claude_subscription.go put back, red at the cut check (the shelved
session resumed whole). Restored, green.

Run at the pushed tree (this stack of nine on origin/main 3c2dceb34),
on mote (macOS arm64, Go 1.26.8):
- go test -count=1 -timeout 45m ./internal/catalog/...
  ./internal/plugin/... ./internal/davsync/... ./internal/gateway/...:
  catalog, plugin and davsync ok; gateway red on one test only,
  TestCodexPoolSaysTheClientsVersion, the open #4807 (another test's
  Codex identity reaches it in a full package run). It passes run
  alone at this tree, 3 of 3.
- go vet ./... (darwin); GOOS=linux and GOOS=windows go vet -tags
  nogui ./...: ok. gofmt -l on every tracked .go file: clean.
- The hand breaks above ran on this stack before its rebase onto
  3c2dceb34. That commit changed member.go only, nothing these tests
  reach.
Not tried: the GUI suite, since no GUI file changed. Windows and Linux
test runs (the Claude bridge tests use a shell fake and skip on
Windows). No real vendor, Claude Code or network was used; every
case runs against fakes.

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-03 07:43:18 +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 1490045f59 claude bridge: an unloaded deferred magpie MCP tool is handed over by its full name
packinggoods (#feedback, 11-02): every first MCP call in Claude Code
failed with "Error: No such tool available: magpie-web-search__web_search"
and the retry worked.

Claude Code with tool search on names a deferred MCP tool in a reminder
and leaves it out of tools until ToolSearch loads it. Through the Claude
subscription bridge the run's model reads that name and calls it,
mcp__magpie__magpie-web-search__web_search; toolStart cut mcp__magpie__
and, the tool not being one the client sent, handed the client the bare
magpie-web-search__web_search, which it has no tool of. After a
ToolSearch the tool is in tools, the cut name maps back, and the call
works: the retry. a3768cdd1 (the router sending a name it no longer
lists to its server) doesn't reach this; nothing gets to the router.

toolStart now hands such a call over under the name the model called,
the client's own, when the cut name maps to nothing and isn't among the
run's tools. A declared tool maps as before; with the run's tools not
yet set the old behaviour stays.

Reproduced in a sandbox HOME with Claude Code 2.1.316 against a fake
Anthropic API and a stdio MCP server: a call of the bare name gives
the reporter's exact error, and a call of the full name of an unloaded
deferred tool runs.

Run at this head (mote): go test -tags nogui ./internal/gateway -run
'TestClaudeBridgeHandsOverAnUnloadedMagpieTool|TestClaudeBridgeKeepsMagpieMCPNames|TestClaudeRunEndsAfterStructuredOutput|ToolChoice|ToolName'
ok; then rebased on fb872a68e (a2837c1f5 and 2ff93ffd6 on top change
only two provider movers' mins): gofmt -l internal/gateway clean,
GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway ok,
go test -tags nogui ./internal/gateway -run 'Claude|MCP|Hub|ToolName|ToolChoice'
ok (88s).
Broken by hand: with the name = called line out,
TestClaudeBridgeHandsOverAnUnloadedMagpieTool is red: handed
"magpie-web-search__web_search", want
"mcp__magpie__magpie-web-search__web_search".
Not tried: a real bridge run on a real Claude account, and the
reporter's own setup (agent, account) is inferred from the screenshot.
Not changed: a deferred tool of another client MCP server
(mcp__linear__…) is still answered by the run (#4956, related #4854).
2026-11-03 02:36:06 +08:00
yetone eb8b840dd4 claude: a one-off ask's instructions go after Claude Code's system prompt in the interactive mode (#2432)
The interactive mode's helper pastes a run's first message as one text,
without the cache marks renderClaudePrompt puts on it. A one-off ask's
caller instructions were in that message, so Claude Code's auto mode
classifier wrote them to the cache on every check of one conversation:
laozhang713's six checks on one account, no 429, read 1,197 and wrote
83-85k each (#2432; j1374615791-lab saw the same at 125k).

A new interactive run for a one-off ask (no tools, no reply before it,
not lean, no client marks: appendsPrompt) now gets the instructions by
--append-system-prompt-file (append.md, the leanSystem text, the
environment note worded as a lean run's), and its first message holds
the ask alone. Such a run is let go after its reply (ended); it is never
shelved or branched (run.appended), since a session resumed without the
file would have no instructions. Every other run is unchanged.

Run:
- TestClaudeTUIOneOffAskAppendsInstructions and
  TestClaudeAppendOnlyForInteractiveOneOffs (tools, reply, -p) on mote.
  Broken by hand (appendsPrompt returning false): the first goes red.
- mote: gofmt; go vet ./internal/gateway for darwin, linux and windows;
  go test ./internal/gateway -run 'Claude|Lean|TUI|Subscription|Replay|Branch'
  ok (65s), at base a3768cdd1.
- Real Claude Code 2.1.316, interactive, in a sandbox HOME against a
  recording server, two runs with the same appended rules and different
  asks: the two marked system blocks are byte for byte the same, the
  rules at the end of the 110k one; only the unmarked billing line differs.

Not tried: a real account's cache_read on the second classifier ask;
the full internal/gateway package and the full suite (running after the
push); Windows/WSL runs of the bridge.
2026-11-03 02:08:41 +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 aab48dea94 claude: a saved account's .claude.json says magpie's work folder is trusted (#4830)
mydosu (#4830, Windows, v0.1.2679, Claude Code 2.1.316): since
d39358f1b the /usage reads and the "hi" test of a saved account run in
<tmp>/magpie-claude-work, and the account's config directory never got
a trusted entry for it. Every read waited out its 16.8s on the trust
question.

magpie now writes the entry itself, before each run there, into a saved
account's .claude.json (provider.ClaudeTrustFolder, gateway trustWork).
This covers every place Claude Code runs in that folder with a
non-default config dir: askClaudeTUI, claudeUsageTUI, and the bridge's
startRun when the caller's folder isn't used. The key is the one Claude
Code 2.1.316 looks a folder up by (its trust check, read from the
binary): the path in NFC, with forward slashes on Windows
("C:/Users/<me>/AppData/Local/Temp/magpie-claude-work"), and also with
its links resolved (/private/var/... on a Mac). For a Claude Code in WSL
it is the mount path. Only a direct child of claude-accounts is written,
never ~/.claude.json or the account Claude Code is signed in to. Other
keys and the project's own fields are kept, numbers go back as written
(UseNumber), a file that can't be parsed is left alone, and nothing is
written once the entry is there. A run's own fallback temp folder isn't
recorded. The helper's yes answer stays as it was.

I could not reproduce the missing entry itself. On xiaomi-gpu, Claude
Code 2.1.316 with a fake sign-in and the helper's yes recorded the key.
This fix does not depend on why it wasn't recorded on mydosu's machine.

Run at this head:
- mote: gofmt -l internal (empty); GOOS=linux and GOOS=windows go vet
  ./internal/gateway ./internal/provider; go test ./internal/provider
  ./internal/claudetui ok; go test -run
  'Claude|TUI|Usage|Warm|Ask|Trust|Subscription|Bridge'
  ./internal/gateway ok. The full gateway package was not run: two
  other sessions' full gateway suites were running on mote.
- xiaomi-gpu (win-run): go test -run
  'TestClaudeTrust|TestClaudeOneOffTrusts|TestClaudeBridgeTrusts'
  ./internal/provider ./internal/gateway ok (the shell-script ones
  skip there).
- xiaomi-gpu, real Claude Code 2.1.316 in a sandbox HOME/TEMP, helper
  told not to answer the question (MAGPIE_CLAUDE_TUI_TRUST=0). A saved
  account dir under a sandbox claude-accounts, with the entry written by
  trustWork (key "C:/Users/yeton/trust4830-sb/tmp/magpie-claude-work"):
  /usage drew its panel in 5.6s, exit 0. The same dir without the entry:
  "Claude Code asks whether to trust the folder" in 0.9s.

Broken by hand, each red:
- trustWork returning at once: TestClaudeOneOffTrustsMagpiesFolder,
  TestClaudeTrustWorkOnlyMagpiesFolderInSavedAccounts,
  TestClaudeBridgeTrustsMagpiesFolderForSavedAccount.
- the bridge's call dropped: TestClaudeBridgeTrustsMagpiesFolderForSavedAccount.
- no "/" for "\" on Windows: TestClaudeTrustKeysAsClaudeCodeKeys on
  mote, plus TestClaudeTrustWorkOnlyMagpiesFolderInSavedAccounts on
  Windows.
- no claude-accounts guard: TestClaudeTrustFolderOnlyMagpiesAccounts.

Not tried: a real signed-in saved account (the reporter's), and Claude
Code in WSL (the key is the mount path, by unit test only).
2026-11-02 14:51:16 +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 a8e98e1abb gateway: a Claude Code run that exits mid-reply is a failure, not a 200 (#4822)
A Claude subscription run whose Claude Code exited after its reply began,
with no message_stop nor a result (only the message_start, or part of the
text), closed its segment as if the reply had ended. The client was
answered 200 with nothing or the words so far, and the agent took it as a
finished turn.

- readOutput: at the end of Claude Code's output, a reply begun on the
  open segment (KStart, tracked in emit as unended until a KStop or
  KError) ends with a KError, 502, "Claude Code exited before it ended
  its reply" and the end of its stderr. -p and the interactive mode share
  this path.
- relay, not streamed: any error is a status, words said before it too
  (was: a 200 with the partial reply), as a translated reply cut short is
  (errEndedShort). The try's usage is kept as before (d2a83de61).
- Streamed with nothing sent yet: the head's KError is a status, as
  before, so the spare answers by the existing failover rules, and the
  cut try keeps its handed_on usage row. Streamed after text: the
  protocol's error event (Anthropic `error`, chat's error chunk with no
  [DONE], Responses' response.failed), no end event, no other run.
- A reply that ended with message_stop, or whose stop was told, is
  unchanged.
- The tests' fake Claude Code (claudeSubscriptionFirstSays) answers
  control requests, so it runs in the interactive mode too.

TestClaudeSubscriptionRunExitedMidReplyFails: message_start then exit and
text then exit, on /v1/messages, /v1/chat/completions and /v1/responses,
streamed and not, -p and interactive (24 cases): the spare's answer and
the cut try's handed_on row (900 cache write) where nothing was sent, the
error event and no end where text was streamed.

Run, at this tree on origin/main 89ffc58f5:
- mote: go test -run TestClaudeSubscriptionRunExitedMidReplyFails
  ./internal/gateway ok (24/24); go vet -tags nogui ./internal/gateway
  for darwin, linux and windows ok; gofmt -l clean.
- mote: go test -tags nogui -timeout 45m ./internal/gateway
  ./internal/claudetui: claudetui ok; gateway red on
  TestCodexPoolSaysTheClientsVersion alone (#4807, another test's Codex
  identity, open and passes alone; this change doesn't touch Codex).
- Full suite (go test -tags nogui -timeout 45m ./..., Linux, wsl-run)
  was still running at push time; internal/agent's install-detection
  reds there are #4033. Its result goes on #4822.
Broken by hand: with claude_subscription.go at origin/main, all 24 cases
red (200, runs "own", partial or empty reply). With the relay change
alone reverted, the 6 text/not-streamed cases red (200 partial).
Not tried: a real Claude Code whose upstream cuts the stream and exits
mid-reply. A non-streamed reply cut after text now goes on to the spare
account, which is billed for the conversation again (the client gets a
whole answer instead of a cut one, as for translated providers).
2026-11-02 04:38:57 +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 a25d3d0815 claude: a JSON schema is answered in the interactive mode, through an answer tool
With the interactive mode on, a request with a JSON schema was refused
with a 400 since v0.1.2592: interactive Claude Code takes --json-schema and does nothing
with it, its StructuredOutput tool being -p's alone. It now runs in the
interactive mode like any other request.

- serveClaudeSubscription compiles the schema (santhosh-tekuri/jsonschema
  v6.0.3, draft-07 unless it says otherwise, as -p reads one; a $ref
  outside the schema is refused, never fetched) and adds an answer tool,
  StructuredOutput or a numbered name apart from the client's tools, with
  the schema as its input schema, through the bridge's MCP server. A
  schema that can't be compiled is a 400 before any run.
- mcpCall checks each call against the schema: one that doesn't fit is
  told why (isError) to be made again, as -p's is; one that fits is kept.
- At the turn's result the kept input is the reply's structured output.
  A turn that ended with no call is told once to call the tool, and
  fails "no answer fitting the schema" if it still doesn't. Neither the
  call nor the words around it reach the client.
- claudePrint no longer lists the schema. The two refusal tests
  (TestClaudeTUIOnRefusesPrint, TestClaudeTUIRefusalIsNoAccountsFault)
  now use the case that is still refused before any run: an image by
  its URL that can't be downloaded (127.0.0.1, which magpie never
  fetches).
- The provider editor's card no longer says -p takes "a JSON schema"
  the interactive mode can't (en, zh-CN, zh-TW, ja, de).
- docs/subsystems/claude-subscription-bridge.md: the refusal list, and
  how a schema is answered.

Run:
- A real run, haiku, the test account in a sandbox HOME, real Claude
  Code 2.1.316 through the helper with --json-schema and a stdio MCP
  server named magpie serving the answer tool and its description: the
  result's structured_output was null (the premise), and the model
  called mcp__magpie__StructuredOutput at once with
  {"color":"Sky blue","hex":"#87CEEB"}, which fits the schema's
  pattern. 7.2s, one turn. Not run: the whole gateway path with a real
  account (the unit tests drive it with Claude Code's real transcript
  rows).
- mote, at this tree (base 14e351378, origin/main just fetched): gofmt,
  go vet (darwin, windows, linux -tags nogui), go mod verify ok;
  go test ./internal/gateway ./internal/claudetui: claudetui ok, gateway
  red in TestCodexPoolSaysTheClientsVersion only, which is #4807 (red in
  a full package run on mote, another test's Codex identity reaches it);
  alone at this tree -count=3 ok. claude-mode 44/44 and i18n-keys 4/4 in
  chromium and webkit.
- Broken by hand: answer() taking every call without checking it made
  TestClaudeTUISchemaAnswer red ("a call that doesn't fit was told
  Answer received.").
2026-11-02 00:35:21 +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 37d7913c20 claude: the interactive mode is given an earlier conversation as a transcript
A conversation no run has (a run lost to an update, a client's own
history) was told to a new Claude Code in its interactive mode as one
first message, pasted. #4778's 229 messages and 3 images that way were
refused; #4780's 56 messages and 25 images were pasted one by one until
the paste timed out, and the request got a 502 or an empty reply.

Now, when the conversation has a reply that calls no tool,
replaySession writes it as Claude Code's own transcript: a session file
in the project folder Claude Code reads, a user line holding the
conversation before that reply (as renderClaudePrompt tells it, images
as image blocks, client cache marks out) and an assistant line holding
the reply's words. The run starts with --resume on it, as a saved
session's run does, and is typed only the turns after the reply. If
Claude Code can't go on from it, start tries once more told whole
(req.told). -p (interactive mode off), WSL (no session folder) and a
conversation with no such reply are told whole as before. The file goes
in the folder of the work path with its links followed: the first try
wrote it beside the unresolved /var/folders path on a Mac, and the
replay test was red on mote for it.

Real run (this Mac, sandbox HOME and CLAUDE_CONFIG_DIR, one of the
owner's real Claude accounts by CLAUDE_CODE_OAUTH_TOKEN, real Claude Code
2.1.316 through magpie claude-tui-helper, -p stream-json in, the
interactive mode under it, --model haiku): the transcript was made by
replaySession itself (a throwaway test on mote, not committed) from 6
earlier messages with 3 images (red, blue, green 64x64 PNGs) and a
455KB file whose line 004321 names a fruit, 464,798 bytes; the work
folder was reached through a symlink. Typed only "Name the colours of
images A, B and C, and the secret fruit named in line 004321 of the
file. One line." Answer in 8.4s: "A: red, B: blue, C: green; secret
fruit in line 004321: PAPAYA." Claude Code appended to the same session
file (504,788 bytes after).

Run (mote, at this tree, rebased on 85e37162e): go vet ./internal/gateway, GOOS=windows and
GOOS=linux -tags nogui go vet; go test -run
"TUI|Claude|Resume|Interactive|Refusal|Replay|Fallback|Branch"
./internal/gateway ok. gofmt -l clean.

Broken by hand: with replaySession returning nil,
TestClaudeTUIReplayGoesInATranscript is red ("the run wasn't given a
transcript to go on from"). TestClaudeTUISafeguardsInEnv now expects the
new run of changed safeguards to be given the whole conversation
through the transcript, not typed it, and
TestClaudeTUIBranchOfPrintRunIsToldWhole (049848c5e) accepts a branch of
a -p run's session given the whole conversation as a transcript of its
own, never the -p session (it was red at the rebased head before).

Not tried: the full gateway path (a real magpie serve with the
subscription) end to end; the request was driven at the helper with the
transcript replaySession wrote. Not changed: #4780's ask that an empty
200 not count as an answer and that the specific reason reach the
client; WSL still tells the conversation whole. Part of #4778 and #4780.
2026-11-01 22:43:52 +08:00
yetone 949000a36a claude: a request the interactive mode refuses is a 400 no account rests for
A request Claude Code's interactive mode can't take (a JSON schema, a
branch of a -p run's session, WSL Claude Code whose home wasn't found)
was refused with a 502. The fallback asked every account of the
subscription in turn and rested some for it: #4778 saw 15 tries across 3
accounts. The refusal is the same on every account, so it is now a 400
(tuiRefusal), which the fallback neither retries nor rests an account
for.

The message is reworded so that "Models" no longer stands just before
the error's "invalid_request_error": "Settings › Models › Replies
runs every request as -p\",\"type\":\"invalid_request_error" matched
provider.ModelUnserved, which made the 400 retryable again.

Run (mote, at this tree): go vet ./internal/gateway, GOOS=windows and
GOOS=linux -tags nogui go vet; go test -run
"TUI|Claude|Resume|Interactive|Refusal|Fallback" ./internal/gateway ok.
gofmt -l clean.

Broken by hand: with the 400 mapping taken out,
TestClaudeTUIRefusalIsNoAccountsFault is red (502); with the old wording
it was red on WSL (retryable true through ModelUnserved).

Not tried: a refusal against real accounts. Not changed: a run that
starts and fails (tuiNoStart) is still a 502, retried on the next
account. Part of #4778.
2026-11-01 22:43:52 +08:00
yetone 049848c5ed claude: a branch of a -p run's session goes to the interactive mode, told whole
With the interactive mode on, tool results another request answered
first for a run made as claude -p (before the mode was turned on) were
refused with a 502 (claudePrint's "branch"): the branch would have gone
on as -p. It now starts a new interactive Claude Code told the whole
conversation (startRun): -p's prompt isn't the interactive mode's, so
the cache has nothing of the -p session to read either way, and nothing
runs as -p while the mode is on. This is the second refusal behind
@crosscn's 502 on an old conversation (X, 11-01); the first, words over
400KB, went in v0.1.2614.

- startRun drops such a branch (from and req.branch nil) and logs it;
- the "branch" entry in claudePrint is gone;
- docs/subsystems/claude-subscription-bridge.md says so.

Test: TestClaudeTUIBranchOfPrintRunIsToldWhole (a -p run's saved
session given as the branch: the run is interactive, has no --resume,
and is told the first words too; req.branch is cleared).

Run on mote (go1.26.8), at origin/main da275848b plus this change:
gofmt, vet (darwin, windows, linux -tags nogui) ./internal/gateway ok;
go test -run Claude ./internal/gateway ok (61s); the fork, branch and
cut tests (-run 'Fork|Branch|Cut') ok before the rebase.

Broken by hand: the new block turned off: the test red, the run resumed
the -p session with -p's arguments.

Not tried: a real -p branch with real Claude Code (it needs a -p run's
lead parked on calls when the mode is switched); whether @crosscn's
conversation reached this path rather than the 400KB one; the full go
test ./... (the gateway's Claude tests ran).
2026-11-01 21:36:20 +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 15b035eef0 claude: the interactive mode takes an image known by its URL
The interactive mode is pasted files, so an image a client names by its
URL alone made the run fall to the refusal list ("image"), which with
the TUI on means a 502. Now serveSubscription downloads each such image
first (fetchURLImages): from public addresses only (publicClient, the
same fetch the other providers use), checked to be an image by its
bytes, and kept by URL (32 of them) so a conversation that hands the
same URLs over each turn downloads each once. One that can't be had
fails the request with a 400 naming the URL and why; nothing of a
non-image's content is echoed. claudePrint's "image" entry stays as a
backstop, unreachable with the mode on.

The provider editor's tooltip for claude -p no longer lists the image
among what the interactive mode can't take (en, zh, zh-TW, ja, de), and
the bridge's subsystem page says how the image is fetched.

Run (mote, at this tree on 9f17ad4c1): gofmt -l clean; go vet
./internal/gateway, also GOOS=windows; go test -count=1 -timeout 45m
./internal/gateway: ok (760s), with ./internal/claudetui ok; GUI claude-mode, claude-tui-setting and
i18n-keys in chromium and webkit: 44, 16 and 4 pass in each engine, 0 fail.

Rebased on 9d08993c8 (main touched claude_subscription.go's tool names), then
at the pushed tree: go vet ./internal/gateway; go test -run Claude
./internal/gateway ok (68s); i18n-keys and claude-mode 48 pass, 0 fail
in each engine.

Broken by hand: with the fetchURLImages call taken out,
TestClaudeTUIImageByURL is red (502 "an image known by its URL"); green
with it back.

Not tried: a real image by URL through a real interactive Claude Code
(the plan's quota is kept for the long-conversation runs that come
next); the download itself is
FetchImage's, which the other providers' image paths already use.
2026-11-01 20:54:37 +08:00
yetone 7d1f2ecba3 claudecode: magpie keeps the Claude Code it downloaded at the newest release
alextjy on Discord runs magpie in Docker with Claude Code from
`magpie claude-code install`, and asked whether a magpie update touches
it and how it updates. The download lives in <cache>/claude-code
(/config/cache, on the volume), so a new image keeps it. But nothing
ever updated it: every run magpie starts sets DISABLE_AUTOUPDATER, so it
stayed at the version first installed until the user ran install again.

claudecode.KeepCurrent now runs while magpie serves (a WhileServing
loop): a minute after start and every six hours it asks
downloads.claude.ai for the latest release and downloads a newer one,
checked against the manifest's SHA-256 and size as install does. The
version it replaced is removed on the next look rather than at once,
since a run being started may hold its path (Install, the CLI's, still
removes it at once; a folder with a .part download in it is left
alone). It does nothing when magpie downloaded none, when the machine
has its own `claude` (that one is run and updates itself), or when
DISABLE_AUTOUPDATER is set for magpie, Claude Code's own way to hold a
version. A failed look keeps the download and is logged. It never
downgrades.

The status line of `magpie claude-code`, the Docker docs (en, zh, ja)
and the bridge's subsystem page say so.

Run:
- wsl-run (Ubuntu 24.04, Go 1.26.8): go vet, then go test -race -v
  ./internal/claudecode/ -run 'Keep|Install|Find': all pass.
- Broken by hand on WSL, each red: no newer() check
  (UpdatesMagpiesDownload, LeavesWhatIsntMagpiesToUpdate), no own()
  check (the_machine's_own), pruning at install (UpdatesMagpiesDownload),
  no prune on the next look (UpdatesMagpiesDownload).
- Real use on WSL, sandbox HOME and XDG_CACHE_HOME: a throwaway program
  with a fake 2.1.1 download ran KeepCurrent against the real
  downloads.claude.ai. After 1m34s it logged "updated from 2.1.1 to
  2.1.316", the kept binary's --version said "2.1.316 (Claude Code)",
  2.1.1 was still there for the next look, and the loop ended with its
  context.
- mote, at this tree: GOOS=windows and GOOS=linux go vet -tags nogui of
  both packages, go vet ./internal/claudecode/, go build ., then
  go test -tags nogui ./internal/claudecode/ ./internal/cli/ -timeout 45m:
  VET-OK; claudecode ok 0.680s, cli ok 56.673s.
- gofmt -l clean.

Not tried: the Docker image itself (no docker on the test boxes), and a
Windows run whose replaced binary is still in use (prune leaves what it
can't remove for the next look). Full suite not run: the change is the
claudecode package, one WhileServing line and one CLI status line. A
WSL run of ./internal/cli/ at the default 10m timeout timed out while
the box ran other sessions' full suites; the 45m run above replaces it.
2026-11-01 19:00:51 +08:00