Files
magpie/internal/gateway/claude_runs.go
T
yetone 7f827b3b0b claude: magpie claude-code runs lists the Claude Code processes and says what they are
@Candydidi3 on X: with Opus in Claude Code, "magpie里拉起很多子进程". On a
Claude account each conversation is answered by a real Claude Code
(`claude -p`) with magpie's MCP helper (`magpie claude-mcp-helper`) as its
child. Claude Code's parallel subagents are conversations of their own,
so a session that starts N of them has N pairs running. idleMost (6)
pairs are kept for an hour so the next turn reads the prompt cache, and
runs waiting on tool calls stay up to 30 minutes. On macOS and Windows
nothing bounds the total unless the user sets `magpie claude-code runs N`.
A task manager names them "2.1.311" (Claude Code's binary is named by its
version) and "magpie", and nothing told the user what they were.

No leak was found. With the bridge's fakes, 12 concurrent conversations
left 6 runs when they ended their turns, 12 when they were parked on
tool calls and never answered (bounded by the 30-minute timer), and 0
right after they were cancelled. Real Claude Code 2.1.311, run with the
bridge's args, exits within 0.1s of stdin EOF and when its parent is
killed, and its helper exits with it.

So nothing about which processes run changes. They become visible
instead:
- GET /v1/magpie/claude-runs (claude_runs.go) lists each run with its pid,
  model, account, state (answering, idle for its next turn, or waiting on
  tools), since when, when magpie lets it go, and its RSS, plus
  claudeRoom's live count. It is loopback only, refused like the heap
  profile, and served no-store.
- `magpie claude-code runs` prints that list under the bound and says
  what the processes are and how long they are kept.
- runs record when they started, when the current turn began, and the
  timer's deadline (endIn wraps every timer.Reset). The literal 30-minute
  timeouts become runTimeout.

Tests:
- TestClaudeRunsNamesEachProcess: idle, tools and answering runs are
  listed with the pids that are alive, and dropped once they end; every
  caller profileCallersRefused lists is refused. It went red with the
  route taken out (404), and with the guard off 3 callers got the list.
- TestClaudeCodeRunsListsTheProcesses covers the CLI's lines and the case
  with no magpie running. The existing CLI test now stubs the gateway, so
  it never asks the live magpie on :3425.
- oneport_test knows ClaudeRunsPath.

Real run (10-27): a sandbox HOME with a made-up Claude sign-in in its own
CLAUDE_CONFIG_DIR (no keychain item was written for it), `magpie serve`
on 127.0.0.1:47820, and a `claude` wrapper that exec'd real Claude Code
2.1.311 against a mock Anthropic API. 8 concurrent subagent-like
requests left 6 Claude Code, each with its helper. `magpie claude-code
runs` listed the same 6 pids ps showed, idle, ends in 59m, about 160 MB
each. SIGTERM to the sandbox serve ended all 12 within a second.

Run (go1.26.8, -tags nogui, private GOCACHE):
- At 184b4b8ba (this change on origin/main 5a3292354): gofmt clean; vet
  for darwin, linux and windows; `go test -count=1 -timeout 45m` of
  internal/cli ok (88s) and internal/gateway FAIL (1079s). Of the 118
  tests that failed, 117 failed on "no space left on device" (other
  sessions filled the disk to 0 bytes free mid-run), and
  TestHistoryKeepsDaysAndDropsOld failed because its big writes were cut
  short. All 118 run again with -count=1: ok (153s). The history test
  -count=3: ok.
- At this commit, rebased on origin/main 56de2d192 (Kiro's and Qoder's
  mins, plugin options, Codex app-server restarts and Hermes, none of it in these
  files): gofmt clean; vet for darwin, linux and windows; `go build
  -tags nogui .`; TestClaudeRunsNamesEachProcess, TestClientPathCoversHandler
  and TestClaudeCodeRuns* ok. The GUI build and a full gateway run there
  didn't fit on the disk (about 500 MB free).
Not run: the full ./... suite, Windows or Linux, a real Anthropic account,
and the GUI suite (no GUI change).
2026-10-27 18:22:01 +08:00

124 lines
4.4 KiB
Go

package gateway
// GET /v1/magpie/claude-runs: the Claude Code processes the Claude
// subscription's bridge has running, for `magpie claude-code runs`.
//
// Each conversation on a Claude account is answered by a real Claude Code
// (`claude -p`), with magpie's MCP helper (`magpie claude-mcp-helper`)
// beside it for the client's tools, and a run is kept for the
// conversation's next turn (idleMost, idleLongest) or while it waits on
// the client's tool results (parkLongest, its 30-minute timer). Claude
// Code's parallel subagents are conversations of their own, so a session
// that starts many has many pairs running. In Activity Monitor or Task
// Manager they show as Claude Code's version ("2.1.311": its binary is
// named so) and "magpie", with nothing to say they are magpie's or why
// they stay (@Candydidi3 on X: "magpie里拉起很多子进程"). This lists each
// with its pid, model, account, what it waits for and since when.
import (
"net/http"
"slices"
"time"
)
// ClaudeRunsPath is where the gateway lists its Claude Code runs.
const ClaudeRunsPath = "/v1/magpie/claude-runs"
// ClaudeRun is one Claude Code process a conversation runs on.
type ClaudeRun struct {
PID int `json:"pid"`
Model string `json:"model"`
Account string `json:"account,omitempty"`
// State is "answering" (a turn is under way), "idle" (kept for the
// conversation's next turn) or "tools" (its reply called the client's
// tools, whose results it waits for); Since is when it began to.
State string `json:"state"`
Since time.Time `json:"since"`
Started time.Time `json:"started"`
// Ends is when magpie lets it go if nothing comes for it (its timer).
Ends time.Time `json:"ends,omitzero"`
// RSS is Claude Code's resident memory in bytes, 0 when not read.
RSS int64 `json:"rss,omitempty"`
}
// ClaudeRuns is what ClaudeRunsPath answers.
type ClaudeRuns struct {
Object string `json:"object"` // "claude-runs"
Runs []ClaudeRun `json:"runs"`
// Live is every Claude Code magpie has running, the runs and its
// one-off asks (a test, a warm-up, a /usage read) together.
Live int `json:"live"`
// Most is how many may run at once (0: no bound), MostWhy what says so.
Most int `json:"most"`
MostWhy string `json:"mostWhy,omitempty"`
// IdleMost runs are kept for a next turn, IdleFor each at most.
IdleMost int `json:"idleMost"`
IdleFor time.Duration `json:"idleFor"`
}
// runTimeout is how long a run is kept with nothing coming for it while
// a turn is under way or its client's tools run: its timer (endIn).
const runTimeout = 30 * time.Minute
// claudeRunList is the bridge's runs, oldest first, and claudeRoom's count.
func (b *subscriptionBridge) claudeRunList() ClaudeRuns {
type seen struct {
run *subscriptionRun
idle time.Time
}
var all []seen
b.mu.Lock()
for _, r := range b.runs {
s := seen{run: r}
if r.idleKey != "" && b.idle[r.idleKey] == r {
s.idle = r.idleAt
}
all = append(all, s)
}
b.mu.Unlock()
out := ClaudeRuns{Object: "claude-runs", Runs: []ClaudeRun{}, IdleMost: idleMost, IdleFor: idleLongest}
for _, s := range all {
r := s.run
r.mu.Lock()
closed, parked, tree, active, ends := r.closed, r.parkedAt, r.tree, r.active, r.ends
r.mu.Unlock()
if closed {
continue
}
user, _ := ownerAccount(r.owned())
c := ClaudeRun{PID: r.pid(), Model: r.model, Account: user, Started: r.started, State: "answering", Since: active, Ends: ends}
switch {
case !s.idle.IsZero():
c.State, c.Since = "idle", s.idle
case !parked.IsZero():
c.State, c.Since = "tools", parked
}
if c.Since.IsZero() {
c.Since = r.started
}
if tree != nil {
if rss, ok := claudeRunRSS(tree); ok {
c.RSS = rss
}
}
out.Runs = append(out.Runs, c)
}
slices.SortFunc(out.Runs, func(a, b ClaudeRun) int { return a.Started.Compare(b.Started) })
claudeRoom.mu.Lock()
out.Live = claudeRoom.live
claudeRoom.mu.Unlock()
out.Most, out.MostWhy = claudeRunsMost()
return out
}
// claudeRuns answers ClaudeRunsPath, to a program on this computer only:
// it names the accounts and models in use.
func (s *Server) claudeRuns(w http.ResponseWriter, r *http.Request) {
if why := profileRefused(r, "list of Claude Code processes", "magpie claude-code runs"); why != "" {
writeJSON(w, http.StatusForbidden, map[string]any{"error": map[string]any{"message": why}})
return
}
w.Header().Set("Cache-Control", "no-store")
writeJSON(w, http.StatusOK, s.subscription.claudeRunList())
}