Commit Graph
19 Commits
Author SHA1 Message Date
yetoneanddeephbz fe08c8ddb5 gateway: a Claude run started for a tool loop with no history chunks its messages too, so AgentSummary reads the last one's cache (#1716)
#1716 chunked only the history: the messages before historyEnd's split.
A conversation with no reply that calls no tool, as a sub-agent's loop of
tool calls that Claude Code's AgentSummary asks a summary of with its last
results (JinJieBeWater on #1716), has split 0, so it was told in one block
and its one mark stayed on the instructions: every such request wrote the
whole loop again. Such a conversation now has its every message but the
last chunked. A later request with a history is told it wrapped from its
first message, so it never matched past the instructions before either.

What was run:
- TestClaudeToolLoopCachedAcrossNewRuns (new), TestClaudeHistoryCachedAcrossNewRuns,
  ClaudePrompt*, ClaudeInstructions*: pass.
- Broken by hand, each seen red: no split-0 chunking; the last message
  chunked when it ends a chunk (a 32-message loop); boundaries counted
  from the end; the mark left on the instructions too; no chunk mark.
- Real Max account, claude-haiku-5-5, Claude Code 2.1.296 through a
  recording proxy, each run started anew with magpie's rendered prompt,
  a loop of 20 then 24 tool rounds (42 then 50 messages):
    origin/main:     second run read 3,790, wrote 70,764
    #1716 alone:     second run read 3,791, wrote 70,813
    with this:       second run read 48,661, wrote 25,993
  Grown history (21 then 41 messages) and same history with a new ask
  are unchanged from #1716 alone (22,348/28,178 and 40,848/9,678).
  Every request kept to four marks, all 1h.
- Not tried: a long turn to answer after a history is still one block,
  and images count toward Anthropic's 20-block lookback.

Co-authored-by: deephbz <13776377+deephbz@users.noreply.github.com>
2026-10-13 08:59:40 +08:00
deephbz 96eb536f85 gateway: a Claude Code run started anew marks its history's last whole chunk of messages, not only the instructions, so a later run for the same conversation reads the history from the cache instead of writing it all again 2026-10-13 08:59:39 +08:00
yetone 5b14ebf49a gateway: a Claude subscription run is told the user's words after a tool result as theirs, not the tool's (#1878)
JinJieBeWater found that Claude Code's AgentSummary label request ("Describe
your most recent action in 3-5 words. Do not use tools.", sent as a text
block after the sub-agent's last tool_result) reached the inner Claude as
tool output, so it went on with the task instead of answering the label.

Two paths had it:

- renderParts (a run started anew, or a resumed turn) wrote the text right
  after the tool's last line. A text or file part after a tool result in the
  same message now closes it with "[end of tool result id=…]" and is marked
  "[user message]". A result followed by nothing or by another result is
  told as before, so existing prompts and their cache prefix don't change.
- match folded the text into the last result, and continueWith handed it to
  Claude Code as the MCP result. It no longer folds; saidWithResults takes
  the words, and continueWith writes them to Claude Code's stdin as a user
  message before handing the results over, waiting for Claude Code's
  command_lifecycle "queued" for that uuid (2s at most). Claude Code then
  tells its model the message with the result as one the user sent while it
  worked, in the same turn.

Going on in the run, rather than starting a new one for such requests, keeps
the cache prefix (#1716/#1717) and #872's mid-turn messages, which use the
same shape. #872's text is now queued as the user's instead of appended to
the result. Words in a message that holds images (pi-ai's "Attached
image(s) from tool result:" captions) still fold into the result, decided by
the message's parts, not its text. A tool whose output says "Do not use
tools." keeps it inside its result. The fork test's fake Claude now models
mid-turn absorption the way Claude Code does.

Run: gofmt -l; go vet on darwin, linux (-tags nogui), windows for
./internal/gateway; go test -tags nogui ./internal/gateway/ -count=1 green;
-race -count=3 on the new tests. Broken by hand, each red: no end marker;
an end marker after every result; the words not passed to continueWith; the
old fold into the result; the words queued after the result is handed over.
Real Claude Code 2.1.296 driven through the gateway in a sandbox HOME
against a local mock of Anthropic: on continuation the next request's
tool_result holds "SOURCE_LAST_LINE" then the "user sent a new message
while you were working" reminder with the label request; on a new run the
prompt holds the closed result and "[user message]".

Not run: the owner's real Claude subscription (its credentials are in the
Keychain, off-limits here), so the real model's answer to the label isn't
seen; Windows tests; the full ./... suite.
2026-10-13 07:44:34 +08:00
yetone aafddbe589 gateway: a Claude Code turn after its prompt suggestion goes on in its run, taken back from the suggestion; a turn that finds no run says why (#1638, chicring)
Cause (case 2: 41 messages told to a new Claude Code at 02:40:00, minutes
after the last reply at 02:37:13, no stop log). Claude Code 2.1.290 asks
its prompt suggestion after each turn: the conversation so far, with the
turn's system prompt, tools and thinking, and one more user message,
"[SUGGESTION MODE: ...", with no system message after it. That request
goes on from the turn's reply, so resume handed it the conversation's
run, and ended kept the run waiting at the suggestion's reply. The user's
real next turn didn't follow the suggestion, found no run under its key,
and was told the whole conversation in a new run (88k tokens written to
the cache again). Nothing was logged because nothing ended.

Fix. ended keeps, beside the run's new key, the key it went on from
(behindKey) and the turn's uuid (behindTurn). resume, finding no run
under a turn's key, takes one whose behindKey is that key, rewinds it to
behindTurn (rewind_conversation, as letGo does), marks it rewound so it
isn't shelved, and tells it only the turn's messages. A run that can't be
rewound is let go and the turn told whole to a new run, as before.

Logging. A turn after a reply that starts a new run logs "claude: no run
waits for this turn: <why>" (whyNoRun): it went on with a turn this one
doesn't follow, waits under another key (model, settings, system prompt
or tools differ), waits at an earlier turn, is busy, ended (how long ago
and why: abortFor's reason, or how Claude Code exited), or no run here
had the conversation. "tool results no run waiting" now adds "the run
that made the calls ended Xs ago: <why>" (whyCallsLost).

Case 1 (499 mid-reply, then "tool results no run waiting" and 17 messages
told) is not fixed. The run that answered had been started anew for that
turn, so letGo has no earlier user message to rewind to, and its results
were already handed to it over MCP. Keeping its cache would mean rewinding
to Claude Code's own tool_result message and telling the results again as
text, or interrupting instead of ending the run; neither can be checked
without the reporter's request shapes, and a fork that took the lead's
calls (claimResume) looks the same from here. The new log line says which
run ended and why, so the next report can tell.

Tests (claude_side_question_test.go), with 2.1.290's request shapes
(billing line with changing cch, 1h cache_control, adaptive thinking,
output_config effort, context_management, system messages, signed
thinking sent back):
- TestClaudeSideQuestionKeepsTheConversationsRun: turn, turn, suggestion,
  real turn go to one Claude Code (turn 4), rewound to the suggestion's
  uuid, told only the new message; twice. Red with the take-back disabled
  ("went to another Claude Code: pid ... turn 1").
- TestClaudeSideQuestionNotRewound: a run refusing the rewind is let go,
  the turn goes to a new run, 1 run left. Red with the fix disabled (2 runs).
- TestClaudeNoRunSaysWhy (gone / another key) and
  TestClaudeToolResultsNoRunSaysWhy: red with the log line, or the
  lostCalls record, removed by hand.

Run:
- the new tests -race -count=5: ok
- real e2e: the real 2.1.290 client in -p --prompt-suggestions against
  the bridge, whose Claude Code was the real 2.1.290 too, both against a
  local mock of Anthropic: one bridge run for the whole session, "taken
  back from the side question" logged after each suggestion, 0 runs told
  the whole conversation; the real turn's request to the mock went on
  from the reply before the suggestion, without it.
- gofmt -l .: clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok
- set -o pipefail; go test -tags nogui ./... at load average ~45-53:
  every package ok but agent, gateway, library, plugin and provider, which
  hit go test's 10m default. Rerun with -timeout 40m -p 2: agent, library,
  plugin ok; gateway red only in TestOTelWaterfallIncludesUnbilledFallback
  and TestOTelWaterfallFailureAndCancellation (#1794, already filed: they
  read only the first OTel export; -count=10 alone passes); provider red
  only in TestCopilotSecretToolUsername (#1627, already filed; red 1 of 5
  alone under load, then 5 of 5 green). Neither touches this change.
- the new tests with the bridge's neighbours (LetGo, TurnGivenUpOn,
  ToolResultsGivenUpOn, Idle, EndedRunSaysWhy, ForksAnswering) -race
  -count=5: ok

Not tried: the real Claude subscription upstream, the interactive TUI
(the -p flag turns on the same suggestion), other side requests
(extract_memories, away_summary, /btw), case 1's actual requests.
2026-10-12 19:59:58 +08:00
yetone c9fb7c9a1f gateway: a Claude run its timer ended mid-reply is no longer kept idle, holding one of 6 places (#1667)
A resumed turn's 30-minute timer calls abort. Fired during a reply,
finish closed the run and removeRun took it out of b.idle, where it
wasn't yet. The reply's last event, already in the segment, still
reached the client whole, so ended was told ok and kept the closed run
with keepIdle, then re-armed its timer. That timer found it closed and
never took it out, so it held one of idleMost places until pushed out,
and the push-out shelved a session removeRun may already have deleted.
letGo's keepIdle had the same window.

keepIdle now reads r.closed under b.mu and refuses an ended run,
returning false; ended and letGo then return without re-arming the
timer or rewinding. finish sets closed before removeRun takes b.mu, so a
run is either refused here or kept and then taken out by removeRun.

Tests: TestClaudeRunEndedMidReplyIsNotKeptIdle fires the run's timer
(abort through removeRun) and then calls ended with a whole reply. On
the old code it fails: "a run its timer ended mid-reply is kept idle (1
runs), holding a slot of 6"; it passes with the fix. TestClaudeIdle*
kept closed runs only so abort did nothing; they now keep live runs, and
TestClaudeIdleReplacementKeepsItsKey sets the other run at old's key
directly, since keeping it there through keepIdle would end old.

Run: go test -race -run 'Claude|Subscription|Idle|LetGo|Rewind'
./internal/gateway (ok); the full suite is in the next commit's body.
Not tried with a real Claude Code: the window needs a 30-minute reply.
2026-10-12 03:28:16 +08:00
yetone 1d67f79ca3 gateway: a Claude subscription's next turn goes on in the Claude Code that had the conversation, whatever the client's billing line says (#1638, chicring)
The bridge finds the run a conversation went on in by turnKey, and a
rewritten turn's by newLooseTurn. Both hashed the request's system prompt
raw, with the client Claude Code's x-anthropic-billing-header line in it.
renderClaudePrompt already leaves that line out of what a run is told,
but its fields change from turn to turn on the clients that send them:
cch (#1600, 2.1.114), and cc_prev_req, cc_prompt_id, cc_prompt_index and
cc_turn_index (2.1.296's binary, when it counts itself first party). So
no next user turn found its idle run or its shelved session. Each turn
started a new Claude Code that was told the whole conversation in one
message, which wrote it to the prompt cache again: the reporter's
cache_read stayed fixed (~18k, system + tools) while cache_write grew
with the conversation (~368k). Tool rounds inside one turn still went on
(follows doesn't look at the system), which is why it showed only when a
turn ended.

Both keys now hash withoutBillingHeader(req.System). The rest of the
system prompt stays in, so a real change to it still starts a new run.

Run:
- TestClaudeBillingLineKeepsTheRun: two turns whose billing lines differ
  only in cch, cc_prev_req and cc_prompt_id go on in one run, and the run
  is told "b2" alone, never the billing line. Red on the old turnKey
  (2 runs; the second told the whole conversation).
- TestClaudeRunKeysLeaveOutTheBillingLine: both keys ignore the line and
  still change with the rest of the system. Red with only newLooseTurn
  reverted.
- go test ./internal/gateway (434s), gofmt, linux and windows vet.
- Real Claude Code 2.1.296 under a fake upstream: --resume sent bytes
  identical to an in-process run, with and without an MCP tool round, so
  the resume itself doesn't move the prefix.

Not tried: the reporter's own client version and setup. A 2.1.296 client
pointed at a plain base URL sent a constant billing line, so I couldn't
see the per-turn fields from the client side here. If a miss remains, it
is logged as "a new Claude Code is told the whole conversation".
2026-10-12 00:37:27 +08:00
yetone e9f6e48d6a gateway, docs: keepIdle's record no longer says a reply ending after letGo kept a run twice, which serveSubscription rules out (#1596)
d1f0576a7's comment, test comment and subsystem doc named the cause of
a run under two keys as letGo keeping it at backKey and the same
request's ended then keeping it at the turn after. That order can't
happen: serveSubscription's ended callback starts with `if !gone()
{ return }`, and gone is the stop of the context.AfterFunc that calls
letGo, so for one request exactly one of the two runs. The reporter's
own overlap test drove ended by hand while letGo ran, an order the
gateway doesn't produce.

Which callers kept one run twice in the reporter's gateway is not known;
keepIdle, the only writer of b.idle, now holds the rule whichever it
was. The comments and doc say that instead. No code change.

Run: gofmt -l, GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway, -run TestClaudeIdle ./internal/gateway.
2026-10-11 20:53:02 +08:00
yetone dbe81adae6 gateway tests: TestClaudeIdleEvictionEnds fails on what keepIdle's old loop allocates, not on a 5s deadline (#1596)
d1f0576a7's child process failed the old loop by -test.timeout=5s under
GOMEMLIMIT=64MiB, with 30s for the parent. On a busy machine (load ~130
here) starting the gateway test binary and its TestMain can take a good
part of that, so the passing case had little room. Now the child runs
the keeps in a goroutine and watches TotalAlloc: past 256 MiB without
ending, it exits 2 with what it allocated. The ending loop is done in
microseconds, so its child has 4m and the parent 5m.

The rekey scenario set idleAt before keepIdle stamped it with
time.Now(); it is now set after, so on a coarse clock (Windows) the
stale run is still the oldest and the scenario still reaches the loop.

Run: on origin/main 5c9221899, -run TestClaudeIdle ./internal/gateway
green (each child ~20ms); with internal/gateway/claude_subscription.go
from 76db4c6c2 (before the fix), rekey and stale both red in ~0.5s,
"keepIdle allocated 258 MiB without ending". gofmt -l clean, GOOS=linux
and GOOS=windows go vet -tags nogui ./internal/gateway clean;
go test -tags nogui ./internal/gateway and the full suite before push.
2026-10-11 20:53:02 +08:00
yetoneandSma1lboy d1f0576a78 gateway: a Claude run kept again leaves its old key, so letting go past idleMost ends instead of spinning with the bridge locked (X, Sma1lboy)
Sma1lboy found magpie at 158 GB after two days with many omp agents on a
Claude subscription, and traced it to keepIdle.

Cause: letGo keeps a run at backKey when the client goes away mid-reply,
and the reply's ended can then keep the same run at the turn after. The
run sat in b.idle under both keys. Past idleMost, the eviction loop picked
that run as oldest on every pass but deleted only run.idleKey (the newer
key, then ""), so len(b.idle) never fell: the loop never ended, held b.mu
(stopping every Claude subscription request) and appended to drop
without bound.

Fix: keeping a run again removes its earlier entry when that entry is
still its own (not a run that replaced it), and the eviction loop deletes
the map key it found as oldest, aborting each run once.

Run: go test -tags nogui ./internal/gateway/ (ok, 396s); gofmt -l clean;
GOOS=linux and GOOS=windows go vet ./internal/gateway clean. The new
TestClaudeIdleRunMoves and TestClaudeIdleEvictionEnds (rekey and stale,
in a child process) fail on the old keepIdle: the child times out in the
loop. Not reproduced with a real two-day omp workload.

Co-authored-by: Sma1lboy <541898146chen@gmail.com>
2026-10-11 19:10:43 +08:00
yetone cb25d3861b gateway: a Claude subscription's tool calls reach their run on a MAGPIE_ADDR that isn't loopback (#1546, jiayeZhu)
With MAGPIE_ADDR pinned to a concrete address outside 127/8 and gateway
keys on, the Claude subscription bridge's MCP helper posted its tool
calls to http://<that address>/_magpie/claude-mcp/<token> with no key.
lanGuard answered 401, the call never reached the run, and every turn
of tool results found "no run waiting" and started a new Claude Code
told the whole conversation; the reporter's cache hits fell from ~95%
to ~30%.

- lanGuard lets that callback in by its run's own token: a POST to
  /_magpie/claude-mcp/<token> whose token (24 random bytes) is one a
  live run registered (addCallback in startRun, dropCallback in
  removeRun), compared in constant time. No path is exempt on its own:
  an unknown, ended, truncated, extended, percent-encoded or GET form
  is still asked for a key, and so is every other route.
- The helper is handed the callback URL in a 0600 file in the run's
  own temp dir rather than as an argument; RunMCP reads a path as that
  file. The test fakes read it from there.
- docs: claude-subscription-bridge, gateway-routing's HTTP surface and
  reference.md's network section say how the callback is let in.

Run:
- TestClaudeToolCallbackOnANonLoopbackAddress (new): a gateway behind
  lanGuard on this machine's own non-loopback IP, MAGPIE_ADDR set to
  it, fake Claude Code making a real helper call; red on the old guard
  with the reporter's "refused POST /_magpie/claude-mcp/... no API key
  was sent" line, green now.
- TestOnlyALiveRunsCallbackSkipsTheKey (new) and
  TestNetworkGatewayGuardsEveryRoute (now also tried with a live run's
  token as a Bearer key): red with a blanket path exemption put in by
  hand, green now.
- Real use: sandbox HOME, magpie serve on MAGPIE_ADDR=10.0.0.111:3561
  with a gateway key, a fake claude driving the real claude-mcp-helper.
  origin/main: callback refused, "tool results no run waiting", a new
  Claude Code told the whole conversation. This build: the result
  reached the same process (pid unchanged), nothing refused, a made-up
  token still 401.
- go test -tags nogui ./... (full suite), gofmt -l, GOOS=linux and
  GOOS=windows go vet -tags nogui on internal/gateway and
  internal/claudebridge.
2026-10-11 05:50:04 +08:00
yetone c112d2a448 gateway: the Claude subscription answers when magpie runs as root (FrierenF)
Run as root (a server, a Docker container), every Claude subscription
request failed with "Claude Code: exited before it answered magpie's
initialize request (exit status 1): --dangerously-skip-permissions cannot
be used with root/sudo privileges for security reasons".

Claude Code 2.1.296's setup refuses bypassPermissions/
--dangerously-skip-permissions when process.getuid() === 0, IS_SANDBOX is
not "1" and CLAUDE_CODE_BUBBLEWRAP is unset (read from the installed
binary; --permission-mode bypassPermissions is refused the same way). The
bridge's run has no tool of Claude Code's own that touches the machine,
only magpie's MCP tools, answered by the client, and Anthropic's web
search, so the bridge run as root is now given IS_SANDBOX=1
(claudeCLI.asRoot). Its args are unchanged, and a run as anyone else has
its env exactly as before. A WSL distro whose default user is root is the
same case: the WSL probe now prints `id -u` (wslrun.Tool.Root), and
IS_SANDBOX goes into the distro (WSLENV) only then. The warm-up and /usage
runs don't pass the flag and are untouched.

Run:
- Docker node:22-bookworm-slim as root, @anthropic-ai/claude-code@2.1.296,
  fake API: the bridge's exact argv refuses with the message above without
  IS_SANDBOX, and with IS_SANDBOX=1 answers from the fake API
  (permissionMode bypassPermissions).
- The gateway's serveClaudeSubscription as root in that container (linux
  test binary, real claude, no credentials): before, 502 "Claude Code
  ended without an answer"; after, it gets past the check to Claude
  Code's own "Not logged in".
- TestClaudeRunsAsRoot (a fake that refuses as root does) goes red with
  asRoot removed from the launch; TestClaudeAsRootEnv; TestParseProbe.
- go test -tags nogui ./internal/gateway ./internal/wslrun ./internal/agent,
  gofmt -l, go vet (darwin, GOOS=linux, GOOS=windows). WSL root path is
  unit-tested only, not tried on the Windows box.
2026-10-10 19:39:19 +08:00
yetone 3ee97def30 claude: a server or container without Claude Code can have magpie download Anthropic's own build, asked first and checked against its manifest (Jorben)
A Claude subscription signs in and answers through the local `claude`, so
on a server or in the Docker image, which has none, it couldn't be used
(Jorben on Discord: could it be downloaded on first use, as Bun is).

- internal/claudecode: Anthropic's native build, as claude.ai/install.sh
  takes it: downloads.claude.ai/claude-code-releases/latest names the
  version, its manifest.json the platform's SHA-256 and size (linux
  glibc/musl, darwin, win32). A build that doesn't match both is not kept.
  It goes to <cache>/claude-code/<version>/claude, one version kept. Find
  takes the machine's own claude first, then the download.
- magpie claude-code [install [--yes]|remove]: says the version, platform,
  size, the URL it comes from, where it goes, that its checksum is checked
  and that it is Anthropic's software under Anthropic's terms, then asks
  [y/N]. magpie accounts add claude offers it when there is no Claude Code
  (not on Windows, where one in WSL may be the one).
- the gateway's claudeBinary and the sign-in's claudeExecutable take
  claudecode.Find; their "not installed" errors name the command.
- Docker docs (en, zh, ja): Claude sign-in needs `docker exec -it magpie
  magpie claude-code install` first; kept in /config/cache.
  The Dockerfile is unchanged: distroless cc-debian12 has glibc.

Run:
- go test -tags nogui ./... under a temp HOME with pinned caches: all ok
- gofmt -l: none; go vet (darwin), GOOS=linux and GOOS=windows go vet
  -tags nogui ./...: clean; darwin, linux, windows builds
- TestClaudeSubscriptionRunsTheDownloadedClaudeCode fails on the old
  proc.FindTool lookup ("Claude Code is not installed"); taking the
  checksum compare out fails TestInstallRefusesABuildTheManifestDoesntName
- real: magpie claude-code install --yes downloaded Claude Code 2.1.296
  darwin-arm64 (230 MB) into a sandbox HOME, checked; it ran --version
- real, in gcr.io/distroless/cc-debian12:nonroot with the image's /config
  layout: install downloaded 2.1.296 linux-arm64 (245 MB) to
  /config/cache/magpie/claude-code, it ran `2.1.296 (Claude Code)` there,
  and magpie accounts add claude went on to print the claude.ai sign-in
  link and ask for the pasted address
- the claudecode tests built for linux/arm64 pass in debian:12-slim
2026-10-10 14:44:57 +08:00
yetone ab3fe0fe41 gateway: a Claude subscription turn whose saved session Claude Code can't load goes on in a new Claude Code instead of 502 "Claude Code ended", and a Claude Code that ends early says why (FrierenF on Discord)
What: a conversation let go past idleMost is resumed from its saved
session (unshelve, `claude --resume <sid>`). Claude Code 2.1.295 that
can't load the session prints "No conversation found with session ID"
and exits 1 before it reads anything, without answering a control
request (tried with the real binary in a scratch CLAUDE_CONFIG_DIR: a
missing and an empty session file both do this; a loadable one answers
initialize). With the safety context set (Claude Code's auto mode),
start's initialize got its reply channel closed and the turn was
answered 502 "Claude Code: Claude Code ended", with no reason; without
it, the turn got an empty 200.

Now:
- start sends initialize to a run resumed from a saved session too, as
  the probe that Claude Code loaded it; when that run fails, the session
  is let go and a new Claude Code is told the whole conversation in the
  same request (start / startRun).
- cliControl reports a run that ended before answering with its exit
  status and stderr tail (endedBefore, shared with whyEnded), and its
  timeout no longer says "safety context" for every request.
- The other paths that can meet an ended run already start a new one:
  resume (setSafeguards / tell failing -> abort, fall through) and the
  tool-results path (claimResume / continueWith -> runExpired).
- The resume harness's fake Claude Code now acknowledges control
  requests as Claude Code does.

Not known: why FrierenF's saved session couldn't be loaded, or whether
their run ended for another reason; their next failure will now name it.

Run:
- TestClaudeUnloadableSessionStartsAnew (both with and without
  safeguards) and TestClaudeEndedRunSaysWhy fail on origin/main:
  "502 Claude Code ended"; no run started anew (empty 200);
  "Claude Code: Claude Code ended" lacks exit status 3 and stderr.
  They pass with the change, -race -count=10.
- go test -tags nogui ./internal/gateway/ under a temp HOME, pinned
  caches: ok (174s).
- gofmt -l clean; go vet (darwin), GOOS=linux go vet -tags nogui,
  GOOS=windows go vet (with and without nogui) for internal/gateway;
  go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok.
- Not run: a real signed-in Claude account (no credentials copied), the
  Windows box, the rest of the repo's packages.
2026-10-09 22:29:41 +08:00
yetone 71ee5e3519 gateway: a Claude subscription conversation whose client took its images out goes on in its run (#1382, Songxiaor)
Hana's pre-step hook replaces each image before the last assistant message
with "[图片已省略:历史图片保留为文件引用,避免重复发送原始 base64]" in the
tool result or user message that held it. Over pi-ai's openai-completions
the user message of the results' images ("Attached image(s) from tool
result:" and the images) is gone and each result's text has the line added
to its end. The step after one that read an image missed its run both
ways: tool results failed follows() (the hash of what the run heard), and a
new turn failed turnKey and looseTurn.rewrote (message count changed). A
new claude -p was told the whole conversation: 10 of 67 requests, 79% of
the session's cache writes.

lostMedia (claude_lost_media.go) tells this rewrite by its shape, not by
Hana's string: comparing the conversation a run had (each part kept as the
hash and length of its words, heardRuns) with the request's, a role's run
of messages at a time, it holds when at least one image or file was taken
out and nothing else changed: each image/file is still there, gone, or has
text in its place; a tool result may have text added to its end only when
it carried images or the images after the results went; the caption
before those images goes with them only when a result before it grew.
follows() checks it when the hash misses (toldRuns), and looseTurn.rewrote
when the #912 cut rule doesn't match; the looseTurn key drops the message
count, which the per-turn comparison covers. messageWords is now built from
messageParts, the same words, so the hash and the comparison can't drift.
The shape over the string: any client that strips media the same way is
covered, and a compaction or edit (#459) changes words lostMedia never
accepts. Not covered: a tool result of an image alone, whose pi-ai text
"(see attached image)" is replaced rather than added to.

claude_lost_media_test.go builds its fixtures from pi-ai's literal Chat
Completions bodies (read from the installed HanaAgent server seed, 1.0.0-beta: pi-ai
openai-completions.js and Hana's media-strip hook): a table of 18 shapes
for lostMedia, an end-to-end new turn through serveClaudeSubscription with
the script Claude Code (a tool's image, a user's image), and tool results
after the image step through serveSubscription (goes on; a changed user
message or a changed result still starts anew). The two end-to-end tests
fail with lostMedia unhooked from follows/rewrote; each guard in
lostFromRun was broken by hand and turned a table case red.
docs/subsystems/claude-subscription-bridge.md has the rule.

Run: gofmt -l; go vet -tags nogui ./internal/gateway/ (darwin, GOOS=linux,
GOOS=windows); go test -tags nogui ./internal/gateway/ -count=1 under a
temp HOME (ok); -race -count=5 on the lost-media, rewritten, #459, letGo,
given-up and fork tests (ok). Not tried against a real Hana or a sandbox
magpie with a real claude: the harness's script stands in for Claude Code.
2026-10-09 13:45:42 +08:00
yetone 16dc154589 claude: a new Claude Code told a whole conversation is told which turns were answered already and which turn to answer, and the gateway logs that it happened (#1365)
What changed: renderClaudePrompt told a run started anew the conversation
as one stretch of Human:/Assistant: text, every image of every turn in it,
and the model in #1365 took the earlier images for new ones. When the
conversation has a reply that calls no tool, the turns up to it now go in
<conversation_history>, with a note that the images and files in them were
sent with those earlier messages and need no answer again, and the rest
(from the user message after that reply, as nextTurn splits it,
historyEnd) in <current_turn>. Images stay in place inside their section;
none is dropped. A first turn, a conversation with no reply in it (one-off
asks, the auto mode classifier's transcript), or messages ending in a
reply are told as before. start logs "a new Claude Code is told the whole
conversation" with the message and image counts, after the "tool results
<why>" line that says why no run took it.

Why: a rebuild can't always be avoided (a run past its idle time with no
saved session, a run started anew for the turn and given up on, a
conversation the client changed). Its replay should not read as the user
sending everything again. Only the text of the one message a new run is
told changes, no header or other request field.

What was run:
- New TestClaudePromptMarksEarlierTurns: the earlier turn and its image are
  inside <conversation_history>, the current turn's text, tool round and
  two images inside <current_turn>, and a first turn or reply-less
  conversation has no markers. With historyEnd's split turned off it fails.
- go test -tags nogui ./internal/gateway/ (full package) under a temp HOME,
  including the existing renderClaudePrompt tests (prompt cache, foreign
  calls, images); -race -count=20 on the new tests; gofmt -l; go vet for
  darwin, linux and windows (-tags nogui); GOOS=linux/windows go build.
Not tried against a real Claude model: whether it now leaves earlier
images alone is untested.
2026-10-09 11:05:33 +08:00
yetone 7ea1cb6743 claude: a client that goes away while the run answers its tool results takes the turn back, not the whole conversation to a new Claude Code (#1365)
What changed: ended() kept a turn's id (turnUUID, backKey) only until the
reply that called a tool. From then on, a client that went away while the
run answered the turn's tool results (a cut connection, or the user
interrupting to send a message queued during the tool call) could not be
rewound: letGo ended the run. The client's next request, its results sent
again or the next turn, logged "tool results no run waiting", and a new
Claude Code was told the whole conversation in one message, with every
image in it, which the model in #1365 took for new. Now the turn's id lasts
across its tool rounds, until a reply ends without calling a tool. letGo
rewinds the run to the turn's user message, its tool rounds with it, and
the run waits at the conversation before the turn. The next request is
resumed there (nextTurn's key is backKey) and told the turn since its user
message. resume logs "a turn taken back goes on in its run" after the
"no run waiting" line. A run started anew for the turn, or one with a call
still in the client's hands, is ended as before. Nothing else sent to
Anthropic changes.

Why: the issue's log showed "no run waiting" four times, then a whole-
conversation replay. On current main a queued message with an image is
sent beside the tool_result (checked with Claude Code 2.1.295 against a
local mock) and match keeps it with the result, so it does not break
matching by itself. The MCP call reaches magpie ~3ms after the tool
reply's message_stop, well inside match's 500ms grace. What drops the run
is a client going away during a tool-result continuation. The exact client
trigger in the report is not confirmed.

What was run:
- New TestClaudeToolResultsGivenUpOnAreTakenBack (fake Claude Code that
  makes its call through magpie's MCP callback and answers
  rewind_conversation): the turn's results are given up on mid-reply, the
  run is rewound to the turn's message, and the resend goes on in the same
  process, told the turn and not turn 1's words. With ended() clearing the
  id as before, it fails: no rewind is asked.
- Real Claude Code 2.1.295 against a local mock of Anthropic:
  rewind_conversation to a user message, sent while the reply to that
  turn's tool result is streaming, answers rewound:true, and the next
  request's messages drop the turn and its tool round.
- go test -tags nogui ./internal/gateway/ (full package) under a temp HOME;
  -race -count=20 on the new test and the TestClaudeTurnGivenUpOn* /
  TestClaudeFirstTurnGivenUpOnEnds tests; gofmt -l; go vet for darwin,
  linux and windows (-tags nogui); GOOS=linux/windows go build.
Not tried with a real Claude account or Claude Desktop.
2026-10-09 11:05:33 +08:00
yetone 2b5f19fc73 gateway: a request whose tool results another request already answered (Claude Code's fork sub-agents and their lead, a turn sent again) gets a Claude Code run of its own instead of a 409 "the agent's turn is already being resumed" (ylorn on Discord)
A Claude Code fork sub-agent's first request is its lead's conversation
with a result for each of the lead's in-flight calls ("Fork started —
processing in background") and its directive after. The lead's own resume
and every fork it started therefore match the same run at once; the first
to claim it won and the rest got a terminal 409 that Claude Code does not
retry, so the forks died. The 409 dates from e8cd4bac (#794); nothing
between v0.1.1108 and main changed it. A request that loses the claim now
gets a run of its own, told the conversation whole.

Verified: TestClaudeForksAnsweringTheLeadsCallsEachGetAnAnswer drives the
real server stack (httptest Handler, fake claude whose MCP calls go back
through /_magpie/claude-mcp) with a lead and 8 forks resuming at once.
Before the change it failed 7/20 plain and 5/10 under -race (409 for forks
and the lead); after, -count=30, -race -count=20 (macOS) and -race
-count=10 (Linux Docker) pass. TestClaudeBridgeSafeguardConcurrentHandoff
now expects the second caller to get its own run. go test -race
./internal/gateway is green on macOS and in Linux Docker; go vet for
darwin/linux/windows and gofmt clean. Not tried with a real Claude
subscription.
2026-10-08 23:59:50 +08:00
yetone 01e66e0f4a gateway: a reply a Claude subscription account answered carries its anthropic-ratelimit-unified-5h/7d headers, so a Claude Code signed in to claude.ai shows the 5-hour and weekly limits in its status line (claude-hud, #1257)
Claude Code tells the allowance in its rate_limit_event, not as headers, so
magpie says what it keeps of the account again as Anthropic does: a share
0-1 and a Unix-seconds reset per window, set as the request comes in and
again as the reply begins, after the turn's own event.

Claude Code 2.1.293 reads them only when it is signed in to claude.ai (the
sign-in field's claudeai); with magpie's key it ignores them.

Run: go test -tags nogui ./... (temp HOME); the two new tests fail without
limitHeaders; GOOS=linux/windows go vet of gateway and provider; real
Claude Code 2.1.293 in a sandbox HOME against a fake server sending these
headers: its statusline stdin had rate_limits.five_hour/seven_day with
used_percentage 42/17 when OAuth-signed in, none with ANTHROPIC_AUTH_TOKEN.
Not run: a real Claude account through a running magpie.
2026-10-08 15:28:52 +08:00
yetone 055f17883f gateway: a Claude subscription conversation the client sends back rewritten goes on in the run that had its last turn, and Claude Code's temp images go with their session (#912, margbug01) — Alma takes the [Context: …] block out of its last user message once the turn is over, the <alma_notification> block out of the end of the reply, and picks the tools for each turn, so turnKey, which hashes all of it, never matched and every turn started a new claude -p told the whole conversation, written to the prompt cache again with its images. ended keeps a looseTurn beside the key: the settings without the tools, the conversation before the last turn hashed, and the last turn's messages one by one. When the exact key misses, rewritten takes the one idle run or saved session whose looseTurn has the same owner, settings and earlier turns, the same roles, tool calls and results in the last turn, where a user message only had one part taken out (cutFrom) and the reply is a non-empty start of what the run said. Two that could be it start a new run, as does an idle run not told a tool offered now (offers) or a saved session one of whose tools is gone (toolsCover). Claude Code's <CLAUDE_CODE_TMPDIR or /tmp>/claude-<uid>/<work project>/<session> folder, where it keeps the images it was given, is removed with the session (removeSession), and the sweep removes those a stopped gateway left once their session file is gone and nothing in them changed for a day; CLAUDE_CODE_TMPDIR joins agentenv.Vars. Old images are still sent to a new run: replacing them would change what the model sees. docs/subsystems/claude-subscription-bridge.md is new. claude_rewritten_test.go has a case for each relaxation (failing before the change) and one for each rule that keeps another conversation out (each failing with that rule taken out). Tested for real with the owner's Claude Max account in a sandbox HOME: turn one asked with a [Context] block and two tools, turn two sent it back with the block taken out, the reply cut short and one tool, and went on in the same claude process ("goes on in its run", cache_read 1932). go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. 2026-10-05 22:56:30 +08:00