Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: Claude Code processes are held to what the machine's memory holds; a full room is a 503 the next provider takes (#2956)

yetone20c068831633
diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md
index 09d6c1ca0..e5d1e70e1 100644
--- a/docs/subsystems/claude-subscription-bridge.md
+++ b/docs/subsystems/claude-subscription-bridge.md
@@ -422,6 +422,57 @@ A client that drops the images' message without adding text to a result
goes on only when that message held images alone, no text. A tool result of an image alone (pi-ai's "(see attached image)")
whose text is replaced by the line is not this shape, and starts anew.
+## How many Claude Code processes run (`claudeRoom`, #2956)
+
+Every Claude Code magpie starts for a Claude subscription takes a place in
+`claudeRoom` (`claude_room.go`) before it starts, and frees it once its
+process has exited: each conversation's run (`startRun`), busy, idle or
+parked on tool results, and each one-off test, warm-up and /usage read
+(`runClaudeTree`). Nothing bounded them before. Claude Code 2.1.303 holds
+about 205 MiB RSS idle on Linux arm64, 86–112 MiB of it its own, and a
+512 MiB systemd service had 2 busy runs and 14 starting at once when the
+kernel's OOM killer ended them. In Docker under a 512 MiB memory cgroup,
+six idle runs were enough for two OOM kills.
+
+How many may run (`claudeRunsMost`):
+
+- the user's `claudeRunsMost` in settings.json, set with
+ `magpie claude-code runs N` (`auto` clears it). It is this machine's own
+ setting (`KeepOwn`): a sync never brings a desktop's number to a server.
+- otherwise, on Linux, `(limit − 256 MiB) / 128 MiB`, at least 1, where
+ the limit is the least of MemTotal, the cgroup v2 `memory.max` and
+ `memory.high` of magpie's cgroup and every one above it, and the cgroup v1
+ `memory.limit_in_bytes` (`memLimit`). 512 MiB gives 2, 1 GiB 6, a 964 MiB
+ machine with no cgroup limit 5. It is read once per process.
+- otherwise no bound: macOS, Windows, and a Linux whose limits can't be
+ read. A limit not known is not a small one.
+
+An ask that finds no room (`take`):
+
+1. lets go of the run idle longest, of any bridge. Its session is shelved,
+ as a run pushed past `idleMost` is, so its conversation's next turn
+ resumes it (`--resume`) and is told only the new messages.
+2. otherwise lets go of the run parked longest on tool results, once it has
+ waited `parkLongest`. Busy runs, and runs waiting on tool calls made
+ recently, are never let go.
+3. otherwise waits for one to end: woken when a process exits or a run
+ goes idle (`nudge`), and it looks again every `roomLook` (5s) for a
+ parked run that has come to wait `parkLongest`.
+
+A run being ended counts as `leaving`, so several waiting asks don't each
+let one go for the same room. After `claudeRoomWait` (2 minutes), or once
+the request's context ends, the ask gives up. A conversation's turn is
+answered 503 with "N Claude Code processes are running, as many as may run
+at once (why); none ended within …" and how to set the number. `start`
+doesn't retry without the saved session after such an error. A /usage read
+returns it as its error.
+
+Routing treats that 503 (`claudeNoRoom`) as a protected failure. No
+account is rested, no other Claude account is asked next (each would wait
+for the same room), and the request isn't tried again after a moment. A
+member of the group at another provider answers it. Alone, the client gets
+the 503.
+
## Files a run leaves
- Its session: `<config>/projects/<work project>/<session>.jsonl`, for
@@ -548,6 +599,9 @@ go test -tags nogui ./internal/gateway/ -run '^TestClaudeCodeGivenTheBridgeForAS
go test -tags nogui ./internal/provider/ -run '^TestClaudeSignInBridgesASOCKSProxy$' -count=1
go test -tags nogui ./internal/netproxy/ -run '^TestEnvForBunWith' -count=1
go test -tags nogui ./internal/gateway/ -run '^TestClaudeToolNamesComeBackAsDeclared$' -count=1
+go 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/settings/ -run '^TestClaudeRunsMostIsMachineLocal$' -count=1
go 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' -count=1
```
diff --git a/internal/cli/claude_code_cli.go b/internal/cli/claude_code_cli.go
index 94109ca0e..32b2da651 100644
--- a/internal/cli/claude_code_cli.go
+++ b/internal/cli/claude_code_cli.go
@@ -4,16 +4,20 @@ import (
"context"
"fmt"
"os"
+ "strconv"
"strings"
"time"
"github.com/yetone/magpie/internal/claudecode"
+ "github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/proc"
+ "github.com/yetone/magpie/internal/settings"
)
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"
+ " 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)"
// claudeCodeCmd: magpie claude-code [install [--yes]|remove]. A Claude
// subscription is answered by Claude Code, and signed in to through it; a
@@ -46,6 +50,8 @@ func claudeCodeCmd(args []string) error {
}
fmt.Println(green.Render("✓"), "removed Claude Code", v, muted.Render("("+claudecode.Root()+")"))
return nil
+ case "runs":
+ return claudeCodeRuns(args[1:])
case "-h", "--help", "help":
fmt.Println(claudeCodeUsage)
return nil
@@ -53,6 +59,52 @@ func claudeCodeCmd(args []string) error {
return fmt.Errorf("magpie claude-code: unknown %q\n%s", args[0], claudeCodeUsage)
}
+// claudeCodeRuns: magpie claude-code runs [N|auto]. Each Claude
+// subscription conversation, test and /usage read is a Claude Code process
+// of about 100 MiB; a 512 MiB service ran 16 and the kernel killed them
+// (#2956). magpie holds them to what the machine's memory holds unless the
+// user says how many (claudeRunsMost).
+func claudeCodeRuns(args []string) error {
+ s := settings.Load()
+ switch {
+ case len(args) > 1:
+ return fmt.Errorf("magpie claude-code runs takes one value\n%s", claudeCodeUsage)
+ case len(args) == 1 && (args[0] == "-h" || args[0] == "--help"):
+ fmt.Println(claudeCodeUsage)
+ return nil
+ case len(args) == 1:
+ n := 0
+ if args[0] != "auto" {
+ v, err := strconv.Atoi(args[0])
+ if err != nil || v < 1 {
+ return fmt.Errorf("magpie claude-code runs takes a number from 1, or auto, not %q", args[0])
+ }
+ n = v
+ }
+ s.ClaudeRunsMost = n
+ if err := settings.Save(s); err != nil {
+ return err
+ }
+ }
+ auto, why := gateway.ClaudeMemRuns()
+ autoSaid := "no bound: this machine's memory isn't known to magpie"
+ if auto > 0 {
+ autoSaid = why
+ }
+ if 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 {
+ fmt.Println(green.Render("●"), auto, "Claude Code processes may run at once", muted.Render("· "+why))
+ } else {
+ 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"))
+ return nil
+}
+
// claudeCode is what the command reads of the machine; tests stand in for it.
var claudeCode = struct {
own func() string
diff --git a/internal/cli/claude_code_cli_test.go b/internal/cli/claude_code_cli_test.go
index 941ef7bb6..017ba6d8c 100644
--- a/internal/cli/claude_code_cli_test.go
+++ b/internal/cli/claude_code_cli_test.go
@@ -14,6 +14,7 @@ import (
"github.com/yetone/magpie/internal/claudecode"
"github.com/yetone/magpie/internal/libc"
+ "github.com/yetone/magpie/internal/settings"
)
// claudeCodeOut runs `magpie claude-code args…` and gives what it printed.
@@ -101,3 +102,47 @@ func TestClaudeCodeInstallDownloadsTheRelease(t *testing.T) {
t.Errorf("remove left %s", p)
}
}
+
+// `magpie claude-code runs N` is the user's own bound on Claude Code
+// processes (#2956), which the gateway's 503 names; auto gives it back to
+// the machine's memory, and a value that isn't a count is refused and
+// writes nothing.
+func TestClaudeCodeRunsSetsTheUsersOwn(t *testing.T) {
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("USERPROFILE", os.Getenv("HOME"))
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ out, err := claudeCodeOut(t, "runs", "3")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := settings.Load().ClaudeRunsMost; got != 3 {
+ t.Fatalf("claudeRunsMost is %d after `runs 3`", got)
+ }
+ if !strings.Contains(out, "3 Claude Code processes may run at once") || !strings.Contains(out, "your setting") {
+ t.Fatalf("runs 3 said:\n%s", out)
+ }
+ for _, bad := range []string{"0", "-2", "lots", "--yes"} {
+ if _, err := claudeCodeOut(t, "runs", bad); err == nil {
+ t.Fatalf("runs %s was taken", bad)
+ }
+ if got := settings.Load().ClaudeRunsMost; got != 3 {
+ t.Fatalf("runs %s wrote %d", bad, got)
+ }
+ }
+ if _, err := claudeCodeOut(t, "runs", "--help"); err != nil {
+ t.Fatal(err)
+ }
+ if got := settings.Load().ClaudeRunsMost; got != 3 {
+ t.Fatalf("runs --help wrote %d", got)
+ }
+ if _, err := claudeCodeOut(t, "runs", "auto"); err != nil {
+ t.Fatal(err)
+ }
+ if got := settings.Load().ClaudeRunsMost; got != 0 {
+ t.Fatalf("runs auto left %d", got)
+ }
+ out, err = claudeCodeOut(t, "runs")
+ if err != nil || strings.Contains(out, "your setting") {
+ t.Fatalf("runs after auto said (%v):\n%s", err, out)
+ }
+}
diff --git a/internal/gateway/claude_room.go b/internal/gateway/claude_room.go
new file mode 100644
index 000000000..00bded5d2
--- /dev/null
+++ b/internal/gateway/claude_room.go
@@ -0,0 +1,353 @@
+package gateway
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "log"
+ "os"
+ "path/filepath"
+ "runtime"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// claudeRoom counts the Claude Code processes magpie has running for
+// Claude subscriptions: each conversation's run, busy, waiting for its next
+// turn or on its caller's tool results, and each one-off test, warm-up and
+// /usage read. Each holds about 100 MiB of its own (Claude Code 2.1.303 on
+// Linux arm64: 86–112 MiB anonymous, the 285 MB binary's pages shared), and
+// nothing bounded how many ran: a 512 MiB service had 2 busy runs and 14
+// starting at once, and the kernel killed them (#2956). A new one waits for
+// room (take): an idle run is let go for it first, its session shelved for
+// its next turn, then one waiting parkLongest on tool results; with neither,
+// it waits for one to end, claudeRoomWait at most, and is answered 503,
+// which routing passes to the next account or provider.
+type claudeRoomT struct {
+ mu sync.Mutex
+ // live is how many Claude Code processes run; leaving how many of them
+ // magpie has asked to end, not ended yet; waiting how many asks wait
+ // for room
+ live, leaving, waiting int
+ // freed is closed, and made anew, each time one ends, or a run comes
+ // to wait for its next turn (nudge), which may be let go for room
+ freed chan struct{}
+}
+
+var claudeRoom = &claudeRoomT{freed: make(chan struct{})}
+
+// claudeRoomWait is how long a Claude Code waits for room before its
+// request is answered 503.
+var claudeRoomWait = 2 * time.Minute
+
+// claudeFull is the error of an ask that found no room in claudeRoomWait.
+type claudeFull struct {
+ live, most int
+ why string
+ waited time.Duration
+}
+
+// claudeNoRoomSaid is in every claudeFull's words, as routing finds it
+// (claudeNoRoom).
+const claudeNoRoomSaid = "Claude Code processes are running, as many as may run at once"
+
+// claudeNoRoom says whether a failed reply is the bridge's 503 for a full
+// claudeRoom.
+func claudeNoRoom(status int, body []byte) bool {
+ return status == 503 && bytes.Contains(body, []byte(claudeNoRoomSaid))
+}
+
+func (e *claudeFull) Error() string {
+ return fmt.Sprintf("%d "+claudeNoRoomSaid+" (%s); none ended within %s. "+
+ "Set how many may run with `magpie claude-code runs N` (claudeRunsMost in settings.json)",
+ e.live, e.why, e.waited)
+}
+
+// claudeRunsMost is how many Claude Code processes may run at once, and
+// what says so: the user's claudeRunsMost, else what this machine's memory
+// holds (claudeMemRuns), else 0, no bound.
+func claudeRunsMost() (int, string) {
+ if n := settings.Load().ClaudeRunsMost; n > 0 {
+ return n, "claudeRunsMost in settings"
+ }
+ return claudeMemRuns()
+}
+
+// ClaudeMemRuns is how many Claude Code processes this machine's memory
+// holds, and why; 0 when not bounded by it (`magpie claude-code runs`).
+func ClaudeMemRuns() (int, string) { return claudeMemRuns() }
+
+// The memory a Claude Code process is given, and what is kept for magpie
+// and the rest of the machine, as the bound is sized from memory: 512 MiB
+// holds 2, 1 GiB 6.
+const (
+ claudeRunMiB = 128
+ claudeReserveMiB = 256
+)
+
+var memRuns struct {
+ sync.Mutex
+ known bool
+ n int
+ why string
+}
+
+// claudeMemRuns is how many Claude Code processes this machine's memory
+// holds: (limit - claudeReserveMiB) / claudeRunMiB, 1 at least, the
+// limit the least of the cgroup's memory.max and memory.high (v1: its
+// memory.limit_in_bytes) and MemTotal. A machine whose memory can't be
+// read, or that isn't Linux, has no bound from it (0): a limit not known
+// is not a small one. It is read once.
+func claudeMemRuns() (int, string) {
+ memRuns.Lock()
+ defer memRuns.Unlock()
+ if !memRuns.known {
+ memRuns.known = true
+ if limit, why := memLimit(memGOOS, memRoot); limit > 0 {
+ n := runsFor(limit)
+ memRuns.n = n
+ memRuns.why = fmt.Sprintf("%d MiB of memory (%s) holds %d", limit>>20, why, n)
+ }
+ }
+ return memRuns.n, memRuns.why
+}
+
+// runsFor is how many Claude Code processes limit bytes of memory hold.
+func runsFor(limit int64) int {
+ return max(int((limit>>20-claudeReserveMiB)/claudeRunMiB), 1)
+}
+
+// memGOOS and memRoot are the system memLimit reads, and the root its
+// files are under, for tests.
+var (
+ memGOOS = runtime.GOOS
+ memRoot = "/"
+)
+
+// memLimit is the memory magpie's processes may use, in bytes, and where
+// that is said; 0 when not known.
+func memLimit(goos, root string) (int64, string) {
+ if goos != "linux" {
+ return 0, ""
+ }
+ var limit int64
+ var why string
+ least := func(n int64, from string) {
+ if n > 0 && (limit == 0 || n < limit) {
+ limit, why = n, from
+ }
+ }
+ if b, err := os.ReadFile(filepath.Join(root, "proc/meminfo")); err == nil {
+ for _, line := range strings.Split(string(b), "\n") {
+ if f := strings.Fields(line); len(f) >= 2 && f[0] == "MemTotal:" {
+ if kb, err := strconv.ParseInt(f[1], 10, 64); err == nil {
+ least(kb<<10, "MemTotal")
+ }
+ }
+ }
+ }
+ b, err := os.ReadFile(filepath.Join(root, "proc/self/cgroup"))
+ if err != nil {
+ return limit, why
+ }
+ cgroups := filepath.Join(root, "sys/fs/cgroup")
+ for _, line := range strings.Split(strings.TrimSpace(string(b)), "\n") {
+ parts := strings.SplitN(line, ":", 3)
+ if len(parts) != 3 {
+ continue
+ }
+ switch {
+ case parts[0] == "0" && parts[1] == "":
+ // v2: this cgroup's limits and every one above it
+ for dir := filepath.Clean("/" + parts[2]); ; dir = filepath.Dir(dir) {
+ for _, name := range []string{"memory.max", "memory.high"} {
+ if n, ok := readLimit(filepath.Join(cgroups, dir, name)); ok {
+ least(n, "cgroup "+filepath.Join(dir, name))
+ }
+ }
+ if dir == "/" {
+ break
+ }
+ }
+ case slices.Contains(strings.Split(parts[1], ","), "memory"):
+ // v1: the memory controller's group, or the container's root
+ // where the host's path isn't mounted
+ for _, dir := range []string{filepath.Join(cgroups, "memory", parts[2]), filepath.Join(cgroups, "memory")} {
+ if n, ok := readLimit(filepath.Join(dir, "memory.limit_in_bytes")); ok {
+ least(n, "cgroup memory.limit_in_bytes")
+ break
+ }
+ }
+ }
+ }
+ return limit, why
+}
+
+// readLimit is a cgroup memory limit file's bytes; "max", a file not
+// there or not read, is none.
+func readLimit(path string) (int64, bool) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return 0, false
+ }
+ n, err := strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64)
+ if err != nil || n <= 0 {
+ return 0, false
+ }
+ return n, true
+}
+
+// take waits for room for one Claude Code process, what naming it in the
+// log, and gives the func that frees it once the process has ended; left
+// says magpie ended it (leave). An ask that finds the room full lets go of
+// an idle or long-parked run for it, unless enough are ending already, and
+// waits for one to end: claudeRoomWait at most, or as long as ctx lasts.
+func (c *claudeRoomT) take(ctx context.Context, what string) (func(left bool), error) {
+ var deadline <-chan time.Time
+ var timer *time.Timer
+ began := time.Now()
+ waiting := false
+ defer func() {
+ if timer != nil {
+ timer.Stop()
+ }
+ if waiting {
+ c.mu.Lock()
+ c.waiting--
+ c.mu.Unlock()
+ }
+ }()
+ for {
+ most, why := claudeRunsMost()
+ c.mu.Lock()
+ if most <= 0 || c.live < most {
+ c.live++
+ c.mu.Unlock()
+ if waiting {
+ log.Printf("claude: %s had room after %s", what, time.Since(began).Round(time.Millisecond))
+ }
+ return c.release, nil
+ }
+ if !waiting {
+ waiting = true
+ c.waiting++
+ log.Printf("claude: %s waits for room: %d Claude Code processes run, %d may (%s)", what, c.live, most, why)
+ }
+ freed, live := c.freed, c.live
+ evict := c.live-c.leaving >= most && c.leaving < c.waiting
+ c.mu.Unlock()
+ if evict && letGoForRoom(most) {
+ continue // what it let go ends soon: waited for below
+ }
+ if timer == nil {
+ timer = time.NewTimer(claudeRoomWait)
+ deadline = timer.C
+ }
+ select {
+ case <-freed:
+ case <-time.After(roomLook):
+ // a run parked since before comes to have waited parkLongest
+ case <-deadline:
+ log.Printf("claude: %s found no room in %s", what, claudeRoomWait)
+ return nil, &claudeFull{live: live, most: most, why: why, waited: claudeRoomWait}
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+ }
+}
+
+// leave counts a process magpie has asked to end as ending, so asks
+// waiting for room don't let go of another for it.
+func (c *claudeRoomT) leave() {
+ c.mu.Lock()
+ c.leaving++
+ c.mu.Unlock()
+}
+
+// roomLook is how often an ask waiting for room looks again for a run to
+// let go, unasked.
+var roomLook = 5 * time.Second
+
+// nudge has the asks waiting for room look again: a run has come to wait
+// for its next turn.
+func (c *claudeRoomT) nudge() {
+ c.mu.Lock()
+ if c.waiting > 0 {
+ close(c.freed)
+ c.freed = make(chan struct{})
+ }
+ c.mu.Unlock()
+}
+
+// release frees a process's room once it has ended.
+func (c *claudeRoomT) release(left bool) {
+ c.mu.Lock()
+ c.live--
+ if left {
+ c.leaving--
+ }
+ close(c.freed)
+ c.freed = make(chan struct{})
+ c.mu.Unlock()
+}
+
+// letGoForRoom lets go of one run for room, of any bridge: the one idle
+// longest, its session shelved for its conversation's next turn as when
+// more than idleMost wait, else the one waiting longest on tool results
+// past parkLongest. It says whether it found one. Busy runs, and those
+// waiting on tool calls made recently, are kept.
+func letGoForRoom(most int) bool {
+ var idle, parked *subscriptionRun
+ var parkedAt time.Time
+ var idleBridge *subscriptionBridge
+ var idleKey string
+ now := time.Now()
+ bridges.Range(func(k, _ any) bool {
+ b := k.(*subscriptionBridge)
+ b.mu.Lock()
+ for key, run := range b.idle {
+ if idle == nil || run.idleAt.Before(idle.idleAt) {
+ idle, idleBridge, idleKey = run, b, key
+ }
+ }
+ for _, run := range b.runs {
+ run.mu.Lock()
+ at, closed, killed := run.parkedAt, run.closed, run.killed
+ run.mu.Unlock()
+ if !closed && !killed && !at.IsZero() && now.Sub(at) >= parkLongest && (parked == nil || at.Before(parkedAt)) {
+ parked, parkedAt = run, at
+ }
+ }
+ b.mu.Unlock()
+ return true
+ })
+ why := "magpie let it go to make room for another Claude Code (" + strconv.Itoa(most) + " may run at once)"
+ if idle != nil {
+ b := idleBridge
+ b.mu.Lock()
+ if b.idle[idleKey] != idle {
+ b.mu.Unlock()
+ return true // taken meanwhile: the room is looked at again
+ }
+ b.shelve(idle)
+ delete(b.idle, idleKey)
+ if idle.idleKey == idleKey {
+ idle.idleKey = ""
+ }
+ b.mu.Unlock()
+ log.Printf("claude: an idle run on %s is let go to make room (%d may run at once); its conversation's next turn resumes its session", idle.model, most)
+ idle.abortFor(why)
+ return true
+ }
+ if parked != nil {
+ log.Printf("claude: a run on %s waiting on tool results since %s is let go to make room (%d may run at once)", parked.model, parkedAt.Format(time.TimeOnly), most)
+ parked.abortFor(why)
+ return true
+ }
+ return false
+}
diff --git a/internal/gateway/claude_room_test.go b/internal/gateway/claude_room_test.go
new file mode 100644
index 000000000..df859e838
--- /dev/null
+++ b/internal/gateway/claude_room_test.go
@@ -0,0 +1,400 @@
+package gateway
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+ "github.com/yetone/magpie/internal/testenv"
+)
+
+// freshRoom gives the test a claudeRoom of its own, at most runs at once
+// (claudeRunsMost in settings), what the machine's memory holds left out.
+func freshRoom(t *testing.T, most int) {
+ t.Helper()
+ old := claudeRoom
+ claudeRoom = &claudeRoomT{freed: make(chan struct{})}
+ memRuns.Lock()
+ known, n, why := memRuns.known, memRuns.n, memRuns.why
+ memRuns.known, memRuns.n, memRuns.why = true, 0, ""
+ memRuns.Unlock()
+ // the package's tests share one settings.json: the bound is put back
+ // as it was, or later tests' runs wait for room
+ was := settings.Load().ClaudeRunsMost
+ t.Cleanup(func() {
+ claudeRoom = old
+ memRuns.Lock()
+ memRuns.known, memRuns.n, memRuns.why = known, n, why
+ memRuns.Unlock()
+ setRunsMost(t, was)
+ })
+ setRunsMost(t, most)
+}
+
+// setRunsMost sets claudeRunsMost, the rest of settings.json as it is.
+func setRunsMost(t *testing.T, n int) {
+ t.Helper()
+ s := settings.Load()
+ s.ClaudeRunsMost = n
+ if err := settings.Save(s); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// aliveCount is a fake Claude Code's start that logs how many of the runs
+// started so far are alive, itself among them.
+const aliveCount = `n=0
+for f in $(dirname $log)/*; do kill -0 $(basename $f) 2>/dev/null && n=$((n+1)); done
+echo "alive $n" >> $log
+`
+
+// mostAlive is the most runs alive at once that any run's start saw.
+func (h *resumeHarness) mostAlive() int {
+ most := 0
+ for _, l := range h.runs() {
+ for _, line := range strings.Split(l, "\n") {
+ if n, ok := strings.CutPrefix(line, "alive "); ok {
+ v, _ := strconv.Atoi(n)
+ most = max(most, v)
+ }
+ }
+ }
+ return most
+}
+
+// askCode is ask, its status and message given back rather than fatal.
+func (h *resumeHarness) askCode(system string, said ...string) (int, string) {
+ var msgs []string
+ for i, m := range said {
+ if i > 0 {
+ msgs = append(msgs, `{"role":"assistant","content":"ok"}`)
+ }
+ msgs = append(msgs, fmt.Sprintf(`{"role":"user","content":%q}`, m))
+ }
+ body := `{"model":"claude-sonnet-5","max_tokens":100,"system":"` + system + `","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[` + strings.Join(msgs, ",") + `]}`
+ var u Usage
+ return h.s.serveClaudeSubscription(httptest.NewRecorder(), httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u)
+}
+
+// No more Claude Code processes run than the machine is said to hold:
+// six conversations asked at once on a room of two each get their answer,
+// the runs before them let go as they wait, and no run's start finds more
+// than two alive. Unbounded, all six ran at once: on a 512 MiB service
+// the kernel killed them (#2956).
+func TestClaudeRunsHeldToTheRoom(t *testing.T) {
+ h := newScriptHarness(t, "ok", aliveCount)
+ freshRoom(t, 2)
+ var wg sync.WaitGroup
+ codes := make([]int, 6)
+ msgs := make([]string, 6)
+ for i := range 6 {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ codes[i], msgs[i] = h.askCode("rules "+strconv.Itoa(i), "hi")
+ }()
+ }
+ wg.Wait()
+ for i, c := range codes {
+ if c != 200 {
+ t.Fatalf("conversation %d: %d %s", i, c, msgs[i])
+ }
+ }
+ if n := len(h.runs()); n != 6 {
+ t.Fatalf("%d runs started, want 6", n)
+ }
+ if most := h.mostAlive(); most > 2 {
+ t.Fatalf("%d Claude Code processes were alive at once, 2 may be", most)
+ }
+}
+
+// A run waiting for its conversation's next turn is let go to make room,
+// its session shelved: that next turn resumes it (--resume), told only
+// the new message, not the whole conversation again.
+func TestClaudeRoomLetsAnIdleRunGoAndItResumes(t *testing.T) {
+ h := newScriptHarness(t, "ok", aliveCount)
+ freshRoom(t, 1)
+ h.ask("rules A", "a1")
+ var pidA string
+ for pid := range h.runs() {
+ pidA = pid
+ }
+ h.ask("rules B", "b1")
+ if most := h.mostAlive(); most > 1 {
+ t.Fatalf("%d alive at once, 1 may be", most)
+ }
+ h.ask("rules A", "a1", "a2")
+ runs := h.runs()
+ if len(runs) != 3 {
+ t.Fatalf("runs: %v", runs)
+ }
+ resumed := false
+ for pid, l := range runs {
+ if pid != pidA && strings.Contains(l, "--resume s"+pidA) {
+ resumed = true
+ // Only what the run was told: the log's random request ids
+ // can spell "a1" too.
+ for _, line := range strings.Split(l, "\n") {
+ if strings.HasPrefix(line, "told ") && strings.Contains(line, "a1") {
+ t.Fatalf("the resumed run was told the conversation again:\n%s", l)
+ }
+ }
+ }
+ }
+ if !resumed {
+ t.Fatalf("A's next turn didn't resume its session s%s: %v", pidA, runs)
+ }
+ if most := h.mostAlive(); most > 1 {
+ t.Fatalf("%d alive at once, 1 may be", most)
+ }
+}
+
+// With no run to let go and none ending, a turn waits claudeRoomWait and
+// is answered 503, which routing passes to the next account, with what
+// held it and how to change it; once room is freed, the next turn runs.
+func TestClaudeRoomFullIs503(t *testing.T) {
+ h := newScriptHarness(t, "ok", "")
+ freshRoom(t, 1)
+ old := claudeRoomWait
+ claudeRoomWait = 50 * time.Millisecond
+ t.Cleanup(func() { claudeRoomWait = old })
+ release, err := claudeRoom.take(context.Background(), "a test holding the room")
+ if err != nil {
+ t.Fatal(err)
+ }
+ code, msg := h.askCode("rules", "hi")
+ if code != 503 || !strings.Contains(msg, "1 Claude Code processes are running") || !strings.Contains(msg, "claudeRunsMost") {
+ t.Fatalf("%d %s", code, msg)
+ }
+ if !claudeNoRoom(code, []byte(msg)) {
+ t.Fatal("routing doesn't know a full room's 503")
+ }
+ if n := len(h.runs()); n != 0 {
+ t.Fatalf("%d runs started with no room", n)
+ }
+ release(false)
+ if code, msg := h.askCode("rules", "hi"); code != 200 {
+ t.Fatalf("%d %s", code, msg)
+ }
+}
+
+// A one-off Claude Code — a model test, a warm-up, a /usage read — takes
+// a place too, and waits for one.
+func TestClaudeOneOffsTakeRoom(t *testing.T) {
+ if _, err := exec.LookPath("true"); err != nil {
+ t.Skip("no true")
+ }
+ testenv.SetHome(t, t.TempDir())
+ freshRoom(t, 1)
+ release, err := claudeRoom.take(context.Background(), "a test holding the room")
+ if err != nil {
+ t.Fatal(err)
+ }
+ marker := filepath.Join(t.TempDir(), "ran")
+ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
+ defer cancel()
+ err = runClaudeTree(ctx, exec.Command("touch", marker), "a one-off")
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("a one-off with no room: %v", err)
+ }
+ if _, err := os.Stat(marker); err == nil {
+ t.Fatal("the one-off ran with no room")
+ }
+ release(false)
+ if err := runClaudeTree(context.Background(), exec.Command("touch", marker), "a one-off"); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(marker); err != nil {
+ t.Fatal("the one-off didn't run with room")
+ }
+ claudeRoom.mu.Lock()
+ live := claudeRoom.live
+ claudeRoom.mu.Unlock()
+ if live != 0 {
+ t.Fatalf("%d places still taken after the one-off", live)
+ }
+}
+
+// memFixture is a machine's /proc and /sys/fs/cgroup under a folder.
+func memFixture(t *testing.T, files map[string]string) string {
+ t.Helper()
+ root := t.TempDir()
+ for name, body := range files {
+ p := filepath.Join(root, name)
+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(p, []byte(body), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return root
+}
+
+// The reporter's service (#2956): systemd's MemoryMax=512M on
+// magpie.service, cgroup v2, on a machine of 987728 kB. It holds 2.
+func TestClaudeMemRunsFromTheCgroup(t *testing.T) {
+ root := memFixture(t, map[string]string{
+ "proc/meminfo": "MemTotal: 987728 kB\nMemFree: 81200 kB\n",
+ "proc/self/cgroup": "0::/system.slice/magpie.service\n",
+ "sys/fs/cgroup/system.slice/magpie.service/memory.max": "536870912\n",
+ "sys/fs/cgroup/system.slice/magpie.service/memory.high": "max\n",
+ "sys/fs/cgroup/system.slice/memory.max": "max\n",
+ })
+ limit, why := memLimit("linux", root)
+ if limit != 536870912 || !strings.Contains(why, "memory.max") {
+ t.Fatalf("limit %d (%s)", limit, why)
+ }
+ if n := runsFor(limit); n != 2 {
+ t.Fatalf("512 MiB holds %d", n)
+ }
+
+ // the machine alone (#2294's small server): MemTotal
+ root = memFixture(t, map[string]string{
+ "proc/meminfo": "MemTotal: 987728 kB\n",
+ "proc/self/cgroup": "0::/user.slice\n",
+ "sys/fs/cgroup/user.slice/memory.max": "max\n",
+ })
+ limit, why = memLimit("linux", root)
+ if limit != 987728<<10 || why != "MemTotal" {
+ t.Fatalf("limit %d (%s)", limit, why)
+ }
+ if n := runsFor(limit); n != 5 {
+ t.Fatalf("964 MiB holds %d", n)
+ }
+
+ // cgroup v1, the container's own root mounted
+ root = memFixture(t, map[string]string{
+ "proc/meminfo": "MemTotal: 8000000 kB\n",
+ "proc/self/cgroup": "12:memory:/docker/abc\n11:cpu,cpuacct:/docker/abc\n",
+ "sys/fs/cgroup/memory/memory.limit_in_bytes": "1073741824\n",
+ })
+ if limit, why = memLimit("linux", root); limit != 1<<30 {
+ t.Fatalf("v1 limit %d (%s)", limit, why)
+ }
+ if n := runsFor(limit); n != 6 {
+ t.Fatalf("1 GiB holds %d", n)
+ }
+
+ // so little the reserve takes it all: 1 still runs
+ if n := runsFor(200 << 20); n != 1 {
+ t.Fatalf("200 MiB holds %d", n)
+ }
+}
+
+// Memory not read is not known, and bounds nothing: never 0 or 1 places
+// from files that weren't there, nor on another system.
+func TestClaudeMemRunsUnknownBoundsNothing(t *testing.T) {
+ if limit, _ := memLimit("linux", t.TempDir()); limit != 0 {
+ t.Fatalf("nothing readable gave %d", limit)
+ }
+ root := memFixture(t, map[string]string{"proc/meminfo": "MemTotal: 987728 kB\n"})
+ if limit, _ := memLimit("darwin", root); limit != 0 {
+ t.Fatalf("darwin gave %d", limit)
+ }
+ testenv.SetHome(t, t.TempDir())
+ freshRoom(t, 0)
+ memRuns.Lock()
+ memRuns.known = false
+ memRuns.Unlock()
+ oldGOOS, oldRoot := memGOOS, memRoot
+ memGOOS, memRoot = "linux", t.TempDir()
+ t.Cleanup(func() { memGOOS, memRoot = oldGOOS, oldRoot })
+ if n, why := claudeRunsMost(); n != 0 {
+ t.Fatalf("unknown memory bounded runs to %d (%s)", n, why)
+ }
+}
+
+// The user's claudeRunsMost wins over what the memory holds.
+func TestClaudeRunsMostTheUsersOwn(t *testing.T) {
+ testenv.SetHome(t, t.TempDir())
+ freshRoom(t, 0)
+ memRuns.Lock()
+ memRuns.known = false
+ memRuns.Unlock()
+ oldGOOS, oldRoot := memGOOS, memRoot
+ memGOOS, memRoot = "linux", memFixture(t, map[string]string{
+ "proc/meminfo": "MemTotal: 987728 kB\n",
+ "proc/self/cgroup": "0::/system.slice/magpie.service\n",
+ "sys/fs/cgroup/system.slice/magpie.service/memory.max": "536870912\n",
+ })
+ t.Cleanup(func() { memGOOS, memRoot = oldGOOS, oldRoot })
+ if n, why := claudeRunsMost(); n != 2 || !strings.Contains(why, "512 MiB") {
+ t.Fatalf("auto: %d (%s)", n, why)
+ }
+ setRunsMost(t, 5)
+ if n, why := claudeRunsMost(); n != 5 || !strings.Contains(why, "settings") {
+ t.Fatalf("the user's 5 gave %d (%s)", n, why)
+ }
+}
+
+// A full room's 503 is no account's fault, and every Claude account would
+// wait for the same room: in a group the next provider answers at once,
+// no other Claude account is asked, none rests, and the Claude account
+// isn't asked again after a moment; alone, the agent is told why.
+func TestClaudeNoRoomPassesOnAndRestsNobody(t *testing.T) {
+ fresh(t)
+ claudeMadeFirst(t, false) // two Claude accounts
+ freshRoom(t, 1)
+ old := claudeRoomWait
+ claudeRoomWait = 50 * time.Millisecond
+ t.Cleanup(func() { claudeRoomWait = old })
+ release, err := claudeRoom.take(context.Background(), "a test holding the room")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer release(false)
+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ io.ReadAll(r.Body)
+ w.Header().Set("Content-Type", "application/json")
+ io.WriteString(w, `{"id":"m","type":"message","role":"assistant","model":"claude-sonnet-5","content":[{"type":"text","text":"from key"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":2}}`)
+ }))
+ defer up.Close()
+ if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Key: "k", Anthropic: up.URL, Models: []string{"claude-sonnet-5"}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := provider.SaveGroup(provider.Group{Name: "Two", Members: []string{"claude/claude-sonnet-5", "other/claude-sonnet-5"}, Routing: provider.Ordered, Patience: -1}); err != nil {
+ t.Fatal(err)
+ }
+ s := New()
+ t.Cleanup(s.subscription.abortAll)
+ post := func(model string) *httptest.ResponseRecorder {
+ r := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"`+model+`","max_tokens":100,"messages":[{"role":"user","content":"hello"}]}`))
+ r.Header.Set("x-api-key", Token)
+ r.RemoteAddr = "127.0.0.1:12345"
+ w := httptest.NewRecorder()
+ lanGuard(s.Handler()).ServeHTTP(w, r)
+ return w
+ }
+ w := post("group/two")
+ if w.Code != 200 || !strings.Contains(w.Body.String(), "from key") {
+ t.Fatalf("group: %d %s", w.Code, w.Body)
+ }
+ tries := s.trace.routes[len(s.trace.routes)-1].Tries
+ if len(tries) != 2 || tries[0].Status != 503 || tries[0].Rest != nil {
+ t.Fatalf("tries %+v", tries)
+ }
+ noneRested(t, "claude")
+
+ w = post("claude/claude-sonnet-5")
+ if w.Code != 503 || !strings.Contains(w.Body.String(), claudeNoRoomSaid) {
+ t.Fatalf("alone: %d %s", w.Code, w.Body)
+ }
+ if tries := s.trace.routes[len(s.trace.routes)-1].Tries; len(tries) != 1 {
+ t.Fatalf("alone, asked %d times: %+v", len(tries), tries)
+ }
+ noneRested(t, "claude")
+}
diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go
index 0532121e3..656d9a862 100644
--- a/internal/gateway/claude_subscription.go
+++ b/internal/gateway/claude_subscription.go
@@ -142,6 +142,10 @@ type subscriptionRun struct {
exit error
killed bool
tmp string
+ // room frees the process's place in claudeRoom once it has exited,
+ // roomLeft telling it magpie ended it (abort)
+ room func(left bool)
+ roomLeft bool
// schema says the client asked for an answer fitting a JSON schema,
// which Claude Code gives as its StructuredOutput call
schema bool
@@ -590,7 +594,8 @@ const claudeMCPPath = "/_magpie/claude-mcp/"
// (FrierenF on Discord).
func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, configDir, owner string, from *savedSession) (*subscriptionRun, <-chan Event, error) {
run, events, err := b.startRun(ctx, req, model, configDir, owner, from)
- if err != nil && from != nil {
+ var full *claudeFull
+ if err != nil && from != nil && !errors.As(err, &full) && ctx.Err() == nil {
log.Printf("claude: Claude Code could not go on from the conversation's saved session (%v); a new one is told the whole conversation", err)
return b.startRun(ctx, req, model, configDir, owner, nil)
}
@@ -607,6 +612,18 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
if err != nil {
return nil, nil, err
}
+ // a place among the Claude Code processes this machine holds (#2956),
+ // freed as the process exits, or here if it never starts
+ room, err := claudeRoom.take(ctx, "a Claude Code run on "+model)
+ if err != nil {
+ return nil, nil, err
+ }
+ launched := false
+ defer func() {
+ if !launched {
+ room(false)
+ }
+ }()
b.sweep.Do(func() {
go func() {
sweepBridgeProjects(claudeConfigDir(), os.TempDir())
@@ -761,7 +778,9 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
run.outputs = []*os.File{stdout, stderr}
run.reading.Add(2)
+ run.room = room
err = run.launch()
+ launched = err == nil
_, _ = stdoutW.Close(), stderrW.Close() // Claude Code has its own
if err != nil {
_, _ = stdout.Close(), stderr.Close()
@@ -1372,6 +1391,7 @@ func (b *subscriptionBridge) keepIdle(r *subscriptionRun, key, conv string) bool
for _, run := range drop {
run.abortFor("another run was kept in its place (" + strconv.Itoa(idleMost) + " wait at most)")
}
+ claudeRoom.nudge() // an ask waiting for room may let it go
return true
}
@@ -3638,10 +3658,17 @@ func (r *subscriptionRun) launch() error {
go func() {
err := t.Wait()
r.drain()
+ // exited closes under mu, which abort reads it under: a run it
+ // counts as leaving the room is one whose room is freed here
r.mu.Lock()
r.exit = err
- r.mu.Unlock()
close(exited)
+ room, left := r.room, r.roomLeft
+ r.room = nil
+ r.mu.Unlock()
+ if room != nil {
+ room(left)
+ }
r.finish()
}()
return nil
@@ -3753,6 +3780,11 @@ func (r *subscriptionRun) abort() <-chan struct{} {
select {
case <-r.exited:
default:
+ if !r.killed && r.room != nil {
+ // asks waiting for room count it as ending
+ r.roomLeft = true
+ claudeRoom.leave()
+ }
r.killed = true
}
}
@@ -4182,7 +4214,14 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
}
}
if err != nil {
- return writeError(w, from, 502, name+": "+err.Error()), err.Error()
+ // no room for another Claude Code on this machine is no fault of
+ // the account: a 503 passes it to the next (#2956)
+ code := 502
+ var full *claudeFull
+ if errors.As(err, &full) {
+ code = 503
+ }
+ return writeError(w, from, code, name+": "+err.Error()), err.Error()
}
cacheDropped(w, req)
run.heard(req.Messages)
diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go
index 007c63051..e1f80725e 100644
--- a/internal/gateway/claude_warmup.go
+++ b/internal/gateway/claude_warmup.go
@@ -57,7 +57,7 @@ func askClaude(ctx context.Context, configDir, model string) error {
cmd.Env = binary.env(env, configDir)
var out, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &stderr
- runErr := runClaudeTree(cmd)
+ runErr := runClaudeTree(ctx, cmd, "a Claude Code test on "+model)
if res, ok := claudeResult(out.Bytes()); ok && res.IsError {
return errors.New("Claude Code: " + clip(res.Result))
}
@@ -112,7 +112,11 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) {
cmd.Env = binary.env(env, configDir)
var out, stderr bytes.Buffer
cmd.Stdout, cmd.Stderr = &out, &stderr
- runErr := runClaudeTree(cmd)
+ runErr := runClaudeTree(ctx, cmd, "a Claude Code /usage read")
+ var full *claudeFull
+ if errors.As(runErr, &full) {
+ return "", runErr
+ }
if res, ok := claudeResult(out.Bytes()); ok {
if res.IsError {
return "", errors.New("Claude Code: " + clip(res.Result))
@@ -136,7 +140,12 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) {
// (#1894). In a tree, a job on Windows and a session elsewhere, what is
// left once the head is gone is ended with it, and on Windows when magpie
// exits mid-run.
-func runClaudeTree(cmd *exec.Cmd) error {
+func runClaudeTree(ctx context.Context, cmd *exec.Cmd, what string) error {
+ room, err := claudeRoom.take(ctx, what)
+ if err != nil {
+ return err
+ }
+ defer room(false)
t, err := proc.StartTree(cmd)
if err != nil {
return err
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 14aa0a3d8..4ce78f92f 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -3131,7 +3131,12 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// rests — it answers as soon as the switch is off. Another member,
// its other models among them, is asked
zdr := !hw.passing && !hw.refused && hw.code() >= 400 && hw.header.Get(zdrHeader) != ""
- if protected || zdr {
+ // no room on this computer for another Claude Code process
+ // (#2956): no account's fault, and each Claude account would wait
+ // for the same room, so none rests, none is asked next, nor this
+ // one again after a moment. Another provider left is asked
+ noRoom := hw.failed() && claudeNoRoom(hw.code(), hw.errBody())
+ if protected || zdr || noRoom {
if other == nil {
other = &Try{Status: call.Status, Error: call.Error}
}
@@ -3141,7 +3146,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
left = notMates(cands[i+1:], c)
}
if len(left) > 0 {
- try.Fail = failShape
+ if !noRoom {
+ try.Fail = failShape
+ }
s.trace.update(tr, func(t *Route) { t.Tries[len(t.Tries)-1] = try })
skipped = append(skipped, c.label()+": "+call.Error)
cands = append(cands[:i+1:i+1], left...)
@@ -3151,7 +3158,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
last = true
}
// nor is it asked again after a moment
- protected = protected || zdr
+ protected = protected || zdr || noRoom
if wait, ok := passing(hw.code(), hw.header, hw.errBody(), again); ok && !protected && !last && hw.failed() && spentAfter(cands[i+1:]) {
// the others left are out of their allowance (Discord, waroy: a
// Codex account run out, Grok busy a moment): this one is the
diff --git a/internal/gui/api.go b/internal/gui/api.go
index 9e563e478..c2b109805 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -1213,6 +1213,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
in.GitHubToken = cur.GitHubToken // set on its own (github-token below), never sent to the page
in.RequestArchive = cur.RequestArchive // the Gateway page's, set on its own
in.RequestArchiveMaxMB = cur.RequestArchiveMaxMB // in settings.json only
+ in.ClaudeRunsMost = cur.ClaudeRunsMost // magpie claude-code runs, or settings.json (#2956)
in.GatewayConversations = cur.GatewayConversations // Sessions' explicit recording consent
in.RedactRules = cur.RedactRules // the masking rules, set on their own
in.RedactModel = cur.RedactModel // set on its own (privacy-model)
diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go
index 237709662..93b1cfc28 100644
--- a/internal/gui/settings_keep_test.go
+++ b/internal/gui/settings_keep_test.go
@@ -181,6 +181,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
}
was.DesktopSubagentEffort = "high"
was.CodexAsyncCompact, was.CodexAsyncCompactPercent = true, 70
+ was.ClaudeRunsMost = 3
if err := settings.Save(was); err != nil {
t.Fatal(err)
}
diff --git a/internal/settings/claude_runs_test.go b/internal/settings/claude_runs_test.go
new file mode 100644
index 000000000..ded5a45de
--- /dev/null
+++ b/internal/settings/claude_runs_test.go
@@ -0,0 +1,19 @@
+package settings
+
+import "testing"
+
+// How many Claude Code processes may run is sized to this machine's memory
+// (#2956): a sync or backup from a big desktop never brings its number to a
+// 512 MiB server, nor clears the server's own.
+func TestClaudeRunsMostIsMachineLocal(t *testing.T) {
+ from := Settings{ClaudeRunsMost: 12}
+ from.KeepOwn(Settings{ClaudeRunsMost: 2})
+ if from.ClaudeRunsMost != 2 {
+ t.Fatalf("a sync brought %d Claude Code runs, this machine's own is 2", from.ClaudeRunsMost)
+ }
+ from = Settings{}
+ from.KeepOwn(Settings{ClaudeRunsMost: 3})
+ if from.ClaudeRunsMost != 3 {
+ t.Fatalf("a sync cleared this machine's 3 Claude Code runs (%d)", from.ClaudeRunsMost)
+ }
+}
diff --git a/internal/settings/settings.go b/internal/settings/settings.go
index 28f97edd3..50077408a 100644
--- a/internal/settings/settings.go
+++ b/internal/settings/settings.go
@@ -240,6 +240,15 @@ type Settings struct {
// real Claude Code, its billing line and identity line kept; off, as by
// default, the run is the shape every Claude Code run has.
ClaudeLeanPrompt bool `json:"claudeLeanPrompt,omitempty"`
+ // ClaudeRunsMost is how many Claude Code processes a Claude
+ // subscription may have running at once: conversations' runs, those
+ // waiting for a next turn or on tool results, and one-off tests and
+ // allowance reads alike. 0, as by default, has magpie size it from
+ // this machine's memory on Linux (its cgroup's limit, else MemTotal),
+ // and leaves it unbounded elsewhere: each Claude Code holds about
+ // 100 MiB of its own, and a 512 MiB service was OOM-killed (#2956).
+ // It is this machine's, not taken from another's settings.
+ ClaudeRunsMost int `json:"claudeRunsMost,omitempty"`
// RefusalRetries is how many more times a request the vendor's safety
// filter refused, with nothing said, is asked of another account or
// routing group member (#248), unset for every one left. 0 hands the
@@ -991,7 +1000,8 @@ func (s Settings) Compact() int {
// Dock, gateway mode, whether WSL is looked in, whether agents' sign-ins
// are read, when allowances are read, the terminal app a session resumes
// in, whether the local masking model is on (it is downloaded on this
-// computer alone), and what the menu bar or tray shows beside magpie's icon (yoooo on
+// computer alone), how many Claude Code processes may run (its memory),
+// and what the menu bar or tray shows beside magpie's icon (yoooo on
// Discord: usage turned off on a Mac came back from a Windows box that
// shows it; Lullaby: sharing turned on at home came on at work).
func (s *Settings) KeepOwn(cur Settings) {
@@ -1008,6 +1018,7 @@ func (s *Settings) KeepOwn(cur Settings) {
s.FetchPrivate = cur.FetchPrivate
s.SessionTerminal = cur.SessionTerminal
s.RedactModel = cur.RedactModel
+ s.ClaudeRunsMost = cur.ClaudeRunsMost
}
// RenamePerModel moves what the user said of a provider's models to the id