Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
claude: magpie claude-code runs lists the Claude Code processes and says what they are
yetone7f827b3b0b46
diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.mdindex 42733de66..014d96f6c 100644--- a/docs/subsystems/claude-subscription-bridge.md+++ b/docs/subsystems/claude-subscription-bridge.md@@ -494,6 +494,30 @@ for the same room), and the request isn't tried again after a moment. Amember of the group at another provider answers it. Alone, the client getsthe 503.+### Which ones run (`ClaudeRunsPath`)++Each run is two processes: Claude Code, and the MCP helper it starts for+the caller's tools (`magpie claude-mcp-helper`, `internal/claudebridge`).+Claude Code's parallel subagents are conversations of their own, so a+session that starts eight has eight pairs running while they work and+`idleMost` (6) pairs kept for an hour after. Those still waiting on tool+calls stay for `runTimeout` (30 minutes) once their caller stops. A task+manager names Claude Code by its version (its binary is+`versions/2.1.311`), so on macOS Activity Monitor shows these as "2.1.311" and+"magpie", with nothing to say what they are (@Candydidi3 on X).++`GET /v1/magpie/claude-runs` (`claude_runs.go`, loopback only, as the+heap profile) lists each run with its pid, model, account, `state`+(`answering`, `idle` for its next turn, `tools` waiting on the caller's+tools) and `since`. It also gives `ends`, when its timer lets it go+(`endIn` records it at each reset), and Claude Code's RSS. `live` is+`claudeRoom`'s count, one-off asks included. `magpie claude-code runs`+prints the list under the bound and says what the processes are.+On 10-27, a sandbox `magpie serve` with a made-up Claude sign-in and real+Claude Code 2.1.311 against a mock API got 8 concurrent subagent-like+requests. It kept 6 Claude Code and 6 helpers, and the list named the same+6 pids that `ps` showed. Quitting magpie ended all 12 within a second.+## How large one Claude Code process may grow (`claudeRunBudget`, #3256)`claudeRoom` bounds how many Claude Code processes run, not how large each@@ -755,7 +779,8 @@ go test -tags nogui ./internal/provider/ -run '^TestClaudeSignInBridgesASOCKSProgo test -tags nogui ./internal/netproxy/ -run '^TestEnvForBunWith' -count=1go test -tags nogui ./internal/gateway/ -run '^TestClaudeToolNamesComeBackAsDeclared$' -count=1go test -tags nogui ./internal/gateway/ -run 'TestClaudeRunsHeldToTheRoom|TestClaudeRoom|TestClaudeOneOffsTakeRoom|TestClaudeMemRuns|TestClaudeRunsMost|TestClaudeNoRoom' -count=1-go test -tags nogui ./internal/cli/ -run '^TestClaudeCodeRunsSetsTheUsersOwn$' -count=1+go test -tags nogui ./internal/cli/ -run '^TestClaudeCodeRuns' -count=1+go test -tags nogui ./internal/gateway/ -run '^TestClaudeRunsNamesEachProcess$' -count=1go test -tags nogui ./internal/settings/ -run '^TestClaudeRunsMostIsMachineLocal$' -count=1go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn|ClaudeTextToolCalls|ClaudeTextCallsHoldsOnlyTheLine|ClaudePromptSaysPastCallsAreARecord' -count=1go test -tags nogui ./internal/gateway/ -run 'TestClaudeTaskNotification|TestWithTaskNotices|TestClaudeTurnToldTheTaskNotification' -count=1diff --git a/internal/cli/claude_code_cli.go b/internal/cli/claude_code_cli.goindex 32b2da651..a79d5c7a6 100644--- a/internal/cli/claude_code_cli.go+++ b/internal/cli/claude_code_cli.go@@ -2,7 +2,10 @@ package cliimport ("context"+ "encoding/json""fmt"+ "io"+ "net/http""os""strconv""strings"@@ -17,7 +20,7 @@ import (const claudeCodeUsage = "usage: magpie claude-code which Claude Code the Claude subscription runs\n" +" magpie claude-code install [--yes] download Anthropic's own build of Claude Code for magpie (a server or container without one)\n" +" magpie claude-code remove delete the Claude Code magpie downloaded\n" +- " magpie claude-code runs [N|auto] how many Claude Code processes may run at once (auto: what this machine's memory holds)"+ " magpie claude-code runs [N|auto] the Claude Code processes running for Claude subscriptions, and how many may run at once (auto: what this machine's memory holds)"// claudeCodeCmd: magpie claude-code [install [--yes]|remove]. A Claude// subscription is answered by Claude Code, and signed in to through it; a@@ -91,31 +94,131 @@ func claudeCodeRuns(args []string) error {if auto > 0 {autoSaid = why}- if s.ClaudeRunsMost > 0 {+ switch {+ case s.ClaudeRunsMost > 0:fmt.Println(green.Render("●"), s.ClaudeRunsMost, "Claude Code processes may run at once", muted.Render("· your setting"))fmt.Println(muted.Render(" auto would be " + autoSaid + " · magpie claude-code runs auto"))- return nil- }- if auto > 0 {+ case auto > 0:fmt.Println(green.Render("●"), auto, "Claude Code processes may run at once", muted.Render("· "+why))- } else {+ fmt.Println(muted.Render(" magpie claude-code runs N sets how many"))+ default:fmt.Println(green.Render("●"), "any number of Claude Code processes may run", muted.Render("· "+autoSaid))+ fmt.Println(muted.Render(" magpie claude-code runs N sets how many"))}- fmt.Println(muted.Render(" magpie claude-code runs N sets how many"))+ printClaudeRuns()return nil}+// printClaudeRuns lists the Claude Code processes the running magpie has+// for Claude subscriptions (gateway.ClaudeRunsPath), and what they are:+// each conversation on a Claude account, a subagent's too, is answered by+// a real Claude Code with magpie's MCP helper beside it, kept for its next+// turn. A task manager shows them as Claude Code's version and "magpie"+// (@Candydidi3 on X asked why magpie started so many).+func printClaudeRuns() {+ base := claudeCode.gateway()+ runs, err := fetchClaudeRuns(base)+ fmt.Println()+ if err != nil {+ fmt.Println(muted.Render(" " + err.Error()))+ return+ }+ n := len(runs.Runs)+ others := max(runs.Live-n, 0)+ head := fmt.Sprintf("%d Claude Code running for Claude subscription conversations", n)+ if n == 0 {+ head = "no Claude Code running for Claude subscription conversations"+ }+ if others > 0 {+ head += fmt.Sprintf(", %d more for a test, warm-up or usage read", others)+ }+ fmt.Println(head)+ now := time.Now()+ for _, r := range runs.Runs {+ state := map[string]string{"answering": "answering", "idle": "kept for its next turn", "tools": "waiting on your agent's tools"}[r.State]+ if state == "" {+ state = r.State+ }+ line := fmt.Sprintf(" pid %-7d %-22s %s %s", r.PID, r.Model, state, runSpan(now.Sub(r.Since)))+ var tail []string+ if r.State != "answering" && !r.Ends.IsZero() && r.Ends.After(now) {+ tail = append(tail, "ends in "+runSpan(r.Ends.Sub(now)))+ }+ if r.RSS > 0 {+ tail = append(tail, bytesSize(uint64(r.RSS)))+ }+ if r.Account != "" {+ tail = append(tail, r.Account)+ }+ if len(tail) > 0 {+ line += muted.Render(" · " + strings.Join(tail, " · "))+ }+ fmt.Println(line)+ }+ for _, l := range []string{+ "Each conversation on a Claude account (each subagent too) is answered by Claude Code, which a task",+ "manager names by its version (2.1.x), with a \"magpie claude-mcp-helper\" beside it for your agent's tools.",+ fmt.Sprintf("One whose turn is over is kept up to %s for its next (%d at most), so that turn reads the prompt", runSpan(runs.IdleFor), runs.IdleMost),+ "cache instead of writing it again. magpie ends each by itself; quitting magpie ends them all.",+ } {+ fmt.Println(muted.Render(" " + l))+ }+}++// runSpan says a duration the way the run list does: 45s, 12m, 1h5m.+func runSpan(d time.Duration) string {+ switch {+ case d < time.Minute:+ return fmt.Sprintf("%ds", max(int(d/time.Second), 0))+ case d < time.Hour:+ return fmt.Sprintf("%dm", int(d/time.Minute))+ }+ h, m := int(d/time.Hour), int(d%time.Hour/time.Minute)+ if m == 0 {+ return fmt.Sprintf("%dh", h)+ }+ return fmt.Sprintf("%dh%dm", h, m)+}++// fetchClaudeRuns asks the gateway at base for its Claude Code runs. The+// error says why there is no list: nothing answers (no magpie running, so+// no Claude Code of magpie's either), or a magpie too old to tell.+func fetchClaudeRuns(base string) (gateway.ClaudeRuns, error) {+ var out gateway.ClaudeRuns+ c := &http.Client{Timeout: 10 * time.Second}+ res, err := c.Get(base + gateway.ClaudeRunsPath)+ if err != nil {+ return out, fmt.Errorf("no magpie answers at %s, so none of its Claude Code is running", base)+ }+ defer res.Body.Close()+ body, err := io.ReadAll(io.LimitReader(res.Body, 4<<20))+ switch {+ case err != nil:+ return out, fmt.Errorf("the list of Claude Code processes from %s was cut off: %v", base, err)+ case res.StatusCode == http.StatusNotFound:+ return out, fmt.Errorf("the magpie at %s is older than this one and doesn't list its Claude Code processes: update it", base)+ case res.StatusCode != http.StatusOK:+ return out, fmt.Errorf("the magpie at %s answered %s: %s", base, res.Status, strings.TrimSpace(string(body)))+ }+ if json.Unmarshal(body, &out) != nil || out.Object != "claude-runs" {+ return out, fmt.Errorf("what %s answered is not a list of Claude Code processes: is it magpie?", base)+ }+ return out, nil+}+// claudeCode is what the command reads of the machine; tests stand in for it.var claudeCode = struct {own func() stringdownloaded func() (string, string)latest func(context.Context) (claudecode.Release, error)install func(context.Context, claudecode.Release, func(int64)) (string, error)+ gateway func() string // the running magpie's gateway, asked for its runs}{own: func() string { return proc.FindTool("claude") },downloaded: claudecode.Downloaded,latest: claudecode.Latest,install: claudecode.Install,+ gateway: gateway.URL,}func claudeCodeStatus() error {diff --git a/internal/cli/claude_code_cli_test.go b/internal/cli/claude_code_cli_test.goindex 017ba6d8c..b21de4cad 100644--- a/internal/cli/claude_code_cli_test.go+++ b/internal/cli/claude_code_cli_test.go@@ -3,6 +3,7 @@ package cliimport ("crypto/sha256""encoding/hex"+ "encoding/json""fmt""io""net/http"@@ -11,8 +12,10 @@ import ("runtime""strings""testing"+ "time""github.com/yetone/magpie/internal/claudecode"+ "github.com/yetone/magpie/internal/gateway""github.com/yetone/magpie/internal/libc""github.com/yetone/magpie/internal/settings")@@ -111,6 +114,7 @@ func TestClaudeCodeRunsSetsTheUsersOwn(t *testing.T) {t.Setenv("HOME", t.TempDir())t.Setenv("USERPROFILE", os.Getenv("HOME"))t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ noGateway(t)out, err := claudeCodeOut(t, "runs", "3")if err != nil {t.Fatal(err)@@ -146,3 +150,62 @@ func TestClaudeCodeRunsSetsTheUsersOwn(t *testing.T) {t.Fatalf("runs after auto said (%v):\n%s", err, out)}}++// noGateway has `magpie claude-code runs` find no magpie running, never+// the one on this computer.+func noGateway(t *testing.T) {+ t.Helper()+ srv := httptest.NewServer(http.NotFoundHandler())+ base := srv.URL+ srv.Close()+ old := claudeCode.gateway+ claudeCode.gateway = func() string { return base }+ t.Cleanup(func() { claudeCode.gateway = old })+}++// `magpie claude-code runs` lists the Claude Code processes the running+// magpie has for Claude subscriptions, each with its pid, model, what it+// waits for, until when and its account, and says what they are: a task+// manager names them by Claude Code's version and "magpie", with nothing+// to tell why so many run (@Candydidi3 on X). With no magpie answering,+// it says none of its Claude Code runs.+func TestClaudeCodeRunsListsTheProcesses(t *testing.T) {+ t.Setenv("HOME", t.TempDir())+ t.Setenv("USERPROFILE", os.Getenv("HOME"))+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ now := time.Now()+ runs := gateway.ClaudeRuns{Object: "claude-runs", Live: 3, IdleMost: 6, IdleFor: time.Hour, Runs: []gateway.ClaudeRun{+ {PID: 4512, Model: "claude-opus-4-7", Account: "[email protected]", State: "answering", Since: now.Add(-12 * time.Second), Started: now.Add(-time.Minute)},+ {PID: 4520, Model: "claude-opus-4-7", Account: "[email protected]", State: "idle", Since: now.Add(-4 * time.Minute), Ends: now.Add(56*time.Minute + 30*time.Second), RSS: 180 << 20},+ }}+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != gateway.ClaudeRunsPath {+ http.NotFound(w, r)+ return+ }+ json.NewEncoder(w).Encode(runs)+ }))+ defer srv.Close()+ old := claudeCode.gateway+ claudeCode.gateway = func() string { return srv.URL }+ t.Cleanup(func() { claudeCode.gateway = old })+ out, err := claudeCodeOut(t, "runs")+ if err != nil {+ t.Fatal(err)+ }+ for _, want := range []string{+ "2 Claude Code running for Claude subscription conversations, 1 more for a test, warm-up or usage read",+ "pid 4512", "answering 12s",+ "pid 4520", "kept for its next turn 4m", "ends in 56m", "180.0 MB", "[email protected]",+ "claude-mcp-helper", "by its version",+ } {+ if !strings.Contains(out, want) {+ t.Errorf("runs says no %q:\n%s", want, out)+ }+ }+ noGateway(t)+ out, err = claudeCodeOut(t, "runs")+ if err != nil || !strings.Contains(out, "none of its Claude Code is running") {+ t.Fatalf("with no magpie running, runs said (%v):\n%s", err, out)+ }+}diff --git a/internal/gateway/claude_runs.go b/internal/gateway/claude_runs.gonew file mode 100644index 000000000..b791e36bb--- /dev/null+++ b/internal/gateway/claude_runs.go@@ -0,0 +1,123 @@+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())+}diff --git a/internal/gateway/claude_runs_test.go b/internal/gateway/claude_runs_test.gonew file mode 100644index 000000000..2e4d72be1--- /dev/null+++ b/internal/gateway/claude_runs_test.go@@ -0,0 +1,159 @@+package gateway++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "regexp"+ "strconv"+ "strings"+ "testing"+ "time"++ "github.com/yetone/magpie/internal/provider"+)++// listClaudeRuns asks srv for its Claude Code runs as `magpie claude-code+// runs` does, over loopback.+func listClaudeRuns(t *testing.T, srv *Server) ClaudeRuns {+ t.Helper()+ r := httptest.NewRequest("GET", ClaudeRunsPath, nil)+ r.RemoteAddr, r.Host = "127.0.0.1:50123", "127.0.0.1:3425"+ r.Header.Set("User-Agent", "Go-http-client/1.1")+ w := httptest.NewRecorder()+ lanGuard(srv.Handler()).ServeHTTP(w, r)+ if w.Code != http.StatusOK {+ t.Fatalf("%s: %d %s", ClaudeRunsPath, w.Code, w.Body.String())+ }+ var out ClaudeRuns+ if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || out.Object != "claude-runs" {+ t.Fatalf("%s answered %s (%v)", ClaudeRunsPath, w.Body.String(), err)+ }+ return out+}++// runsUntil asks for the runs until ok holds of them, 10s at most.+func runsUntil(t *testing.T, srv *Server, what string, ok func(ClaudeRuns) bool) ClaudeRuns {+ t.Helper()+ deadline := time.Now().Add(10 * time.Second)+ for {+ l := listClaudeRuns(t, srv)+ if ok(l) {+ return l+ }+ if time.Now().After(deadline) {+ t.Fatalf("never %s: %+v", what, l)+ }+ time.Sleep(20 * time.Millisecond)+ }+}++// A Claude account's conversations, a subagent's each, run on Claude Code+// processes of their own that magpie keeps for the next turn or while the+// client's tools run, and a task manager shows them as Claude Code's+// version and "magpie" (@Candydidi3 on X: "magpie里拉起很多子进程").+// ClaudeRunsPath names each: its pid, model and account, whether it+// answers, waits for its next turn or on tools, since when and until+// when magpie keeps it, and drops it once it ends.+func TestClaudeRunsNamesEachProcess(t *testing.T) {+ fresh(t)+ t.Setenv("MAGPIE_ADDR", "")+ t.Setenv("MAGPIE_PUBLIC_URL", "")++ t.Run("kept for its next turn", func(t *testing.T) {+ fakeClaude(t)+ s := New()+ t.Cleanup(s.subscription.abortAll)+ p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "[email protected]"}}+ body := `{"model":"claude-opus-4-1","max_tokens":100,"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"a subagent's task"}]}`+ rec := httptest.NewRecorder()+ var u Usage+ before := time.Now()+ req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body))+ if code, msg := s.serveClaudeSubscription(rec, req, provider.Anthropic, p, "claude-opus-4-1", []byte(body), &u); code != 200 {+ t.Fatalf("%d %s", code, msg)+ }+ m := regexp.MustCompile(`pid (\d+) turn 1`).FindStringSubmatch(rec.Body.String())+ if m == nil {+ t.Fatalf("the reply names no pid: %s", rec.Body.String())+ }+ pid, _ := strconv.Atoi(m[1])+ l := runsUntil(t, s, "idle", func(l ClaudeRuns) bool { return len(l.Runs) == 1 && l.Runs[0].State == "idle" })+ r := l.Runs[0]+ if r.PID != pid || !alive(pid) || r.Model != "claude-opus-4-1" || r.Account != "[email protected]" {+ t.Errorf("the run is listed as %+v; Claude Code is pid %d", r, pid)+ }+ if r.Started.Before(before) || r.Since.Before(r.Started) || time.Since(r.Since) > time.Minute {+ t.Errorf("started %v, idle since %v (asked at %v)", r.Started, r.Since, before)+ }+ if left := time.Until(r.Ends); left < idleLongest-time.Minute || left > idleLongest {+ t.Errorf("it ends in %s, not the %s an idle run is kept", left, idleLongest)+ }+ if l.Live < 1 || l.IdleMost != idleMost || l.IdleFor != idleLongest {+ t.Errorf("live %d, idleMost %d, idleFor %s", l.Live, l.IdleMost, l.IdleFor)+ }+ s.subscription.abortAll()+ runsUntil(t, s, "dropped once it ended", func(l ClaudeRuns) bool { return len(l.Runs) == 0 })+ })++ t.Run("waiting on tools, and answering", func(t *testing.T) {+ dir := fakeClaudeCalling(t)+ s := New()+ t.Cleanup(s.subscription.abortAll)+ pid := askForCall(t, s, context.Background(), "subagent: read the file")+ if pid == 0 {+ t.Fatal("no tool call")+ }+ ctx, cancel := context.WithCancel(context.Background())+ done := make(chan struct{})+ go func() {+ defer close(done)+ p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}+ body := `{"model":"claude-sonnet-5","max_tokens":100,"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hang on"}]}`+ var u Usage+ req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)).WithContext(ctx)+ s.serveClaudeSubscription(httptest.NewRecorder(), req, provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u)+ }()+ t.Cleanup(func() { cancel(); <-done })+ var hung int+ l := runsUntil(t, s, "two runs, one answering", func(l ClaudeRuns) bool {+ b, err := os.ReadFile(filepath.Join(dir, "hang.pid"))+ hung, _ = strconv.Atoi(strings.TrimSpace(string(b)))+ return err == nil && hung > 0 && len(l.Runs) == 2+ })+ by := map[int]ClaudeRun{}+ for _, r := range l.Runs {+ by[r.PID] = r+ }+ if r := by[pid]; r.State != "tools" || r.Model != "claude-sonnet-5" || r.Account != "u" || !r.Ends.After(time.Now()) || time.Until(r.Ends) > runTimeout {+ t.Errorf("the run waiting on tools, pid %d, is listed as %+v", pid, r)+ }+ if r := by[hung]; r.State != "answering" || r.Since.IsZero() {+ t.Errorf("the run answering, pid %d, is listed as %+v", hung, r)+ }+ cancel()+ <-done+ runsUntil(t, s, "the given-up turn's run dropped", func(l ClaudeRuns) bool {+ return len(l.Runs) == 1 && l.Runs[0].PID == pid+ })+ })++ t.Run("to this computer's programs only", func(t *testing.T) {+ srv := New()+ for _, c := range profileCallersRefused("magpie-no-such-key") {+ r := httptest.NewRequest("GET", ClaudeRunsPath, nil)+ r.RemoteAddr, r.Host = c.remote, c.host+ for i := 0; i+1 < len(c.hdr); i += 2 {+ r.Header.Set(c.hdr[i], c.hdr[i+1])+ }+ w := httptest.NewRecorder()+ lanGuard(srv.Handler()).ServeHTTP(w, r)+ if w.Code != http.StatusForbidden && w.Code != http.StatusUnauthorized {+ t.Errorf("%s: %d %s", c.name, w.Code, w.Body.String())+ }+ }+ })+}diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.goindex 8304cf700..a323f63a5 100644--- a/internal/gateway/claude_subscription.go+++ b/internal/gateway/claude_subscription.go@@ -278,6 +278,13 @@ type subscriptionRun struct {asked []stringparkedAt time.Time+ // started is when it was started, and active when its turn under way+ // began (r.mu), for `magpie claude-code runs` (claudeRunList)+ started time.Time+ active time.Time+ // ends is when its timer lets it go (endIn), under r.mu+ ends time.Time+// shown is the client's tool calls its last reply made, in the order// the client was told them: a client that names them by ids of its own// (AmpCode) has its results paired with them by position (remap)@@ -824,7 +831,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,}cmd.Stdout, cmd.Stderr = stdoutW, stderrW- run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, schema: len(req.Format.schema()) > 0, pending: map[string]chan mcpToolResult{}, stdin: stdin, effort: req.Effort, sessions: sessions}+ run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, schema: len(req.Format.schema()) > 0, pending: map[string]chan mcpToolResult{}, stdin: stdin, effort: req.Effort, sessions: sessions, started: time.Now()}run.owner.Store(&owner)run.names = bridgeNames(req.Tools)run.safeguardBeta = req.SafeguardBeta@@ -836,7 +843,8 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,}// A caller may abandon a turn after receiving tool_use. Do not leave the// parked Claude process and MCP request alive forever.- run.timer = time.AfterFunc(30*time.Minute, func() { run.abortFor("it waited as long as it may") })+ run.timer = time.AfterFunc(runTimeout, func() { run.abortFor("it waited as long as it may") })+ run.ends = time.Now().Add(runTimeout)segment := run.attach()b.mu.Lock()b.runs[token] = run@@ -1077,9 +1085,10 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu}ch := make(chan Event, 64)run.segment = ch+ run.active = time.Now()run.turnUUID, run.backKey = turn, keyrun.mu.Unlock()- run.timer.Reset(30 * time.Minute)+ run.endIn(runTimeout)// a turn the router picked another effort for (#502) goes on in the// same Claude Code, told the level first: it asks the next turn at it// in output_config alone, the conversation it wrote to the cache@@ -1404,7 +1413,7 @@ func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) {if !r.bridge.keepIdle(r, key, conv) {return // it ended during its reply (#1667)}- r.timer.Reset(idleLongest)+ r.endIn(idleLongest)}// keepIdle leaves run waiting for the turn after the conversation key@@ -1781,7 +1790,7 @@ func (r *subscriptionRun) letGo() {r.asked, r.shown, r.parkedAt = nil, nil, time.Time{}clear(r.early)r.mu.Unlock()- r.timer.Reset(idleLongest)+ r.endIn(idleLongest)log.Printf("claude: the turn the client gave up on was taken back; its run waits for the conversation's next turn")}@@ -1860,10 +1869,10 @@ func (r *subscriptionRun) park() {case r.timer == nil:returncase final:- r.timer.Reset(finalGrace)+ r.endIn(finalGrace)returncase r.stdin == nil:- r.timer.Reset(parkLongest)+ r.endIn(parkLongest)return}if why, over := r.oversized(3); over {@@ -2098,11 +2107,20 @@ func (w *lockedWriter) Write(p []byte) (int, error) {return len(p), nil}+// endIn has the run let go in d unless something comes for it first.+func (r *subscriptionRun) endIn(d time.Duration) {+ r.mu.Lock()+ r.ends = time.Now().Add(d)+ r.mu.Unlock()+ r.timer.Reset(d)+}+func (r *subscriptionRun) attach() chan Event {r.mu.Lock()defer r.mu.Unlock()ch := make(chan Event, 64)r.segment = ch+ r.active = time.Now()return ch}@@ -3565,7 +3583,7 @@ var queuedWait = 2 * time.Second// doing what they asked (#1878).func (r *subscriptionRun) continueWith(results []Part, said string, tools []bridgeTool) (<-chan Event, error) {if r.timer != nil {- r.timer.Reset(30 * time.Minute)+ r.endIn(runTimeout)}if said != "" {if err := r.queue(said); err != nil {diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.goindex 7b67245cf..674e418f9 100644--- a/internal/gateway/gateway.go+++ b/internal/gateway/gateway.go@@ -742,6 +742,9 @@ func (s *Server) Handler() http.Handler {mux.HandleFunc("GET /v1/magpie/trace", s.gatewayTrace)mux.HandleFunc("GET /v1/magpie/concurrency", s.concurrency)mux.HandleFunc("GET /v1/magpie/limit", s.keyLimit)+ // the Claude Code processes the Claude subscription runs, for magpie+ // claude-code runs (loopback only)+ mux.HandleFunc("GET "+ClaudeRunsPath, s.claudeRuns)// a heap profile of this process, for magpie heap (loopback only)mux.HandleFunc("GET "+HeapPath, s.heapProfile)// a CPU profile of this process over some seconds, for magpie cpudiff --git a/internal/gateway/oneport_test.go b/internal/gateway/oneport_test.goindex dd49dc6e5..82fbd0540 100644--- a/internal/gateway/oneport_test.go+++ b/internal/gateway/oneport_test.go@@ -29,7 +29,7 @@ func TestClientPathCoversHandler(t *testing.T) {consts := map[string]string{"claudeMCPPath": claudeMCPPath, "CodexPath": CodexPath, "CodexCatalogPath": CodexCatalogPath,"AlphaSearchPath": AlphaSearchPath, "HeapPath": HeapPath, "CPUPath": CPUPath,- "GoroutinesPath": GoroutinesPath, "SearchMCPPath": SearchMCPPath, "VisionMCPPath": VisionMCPPath,+ "GoroutinesPath": GoroutinesPath, "ClaudeRunsPath": ClaudeRunsPath, "SearchMCPPath": SearchMCPPath, "VisionMCPPath": VisionMCPPath,"ImageMCPPath": ImageMCPPath, "ImageMCPFiles": ImageMCPFiles,"ToolsMCPPath": ToolsMCPPath, "provider.RemoteCardsPath": provider.RemoteCardsPath,"provider.RemoteRefreshPath": provider.RemoteRefreshPath,