Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
claude: a run on a new account's first turn keeps its tool results
yetone5214d5114f7d
diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.mdindex f31bdd686..ab327bd18 100644--- a/docs/subsystems/claude-subscription-bridge.md+++ b/docs/subsystems/claude-subscription-bridge.md@@ -358,6 +358,27 @@ is either refused or kept and then taken out by `removeRun`.copies it, with the tool names the run's agent had, to the`savedSession`.+### Claude Code's own sign-in before it has a name++The owner in every key is the provider, the account's name and, for Claude+Code's own sign-in, `own` (`ownHome`). `claude auth status` gives no email+until Claude Code puts the account's profile (`oauthAccount`) in its+config, which its first run does. Until then the account is named from its+plan ("Claude Max", `Account.Unnamed`), and its owner ends in `unnamed`+(`unnamedOwner`).++The first run on such an account then names it, mid-turn. Its tool+results came under the email, the owner no longer matched, and the run+was let go ("tool results account changed"). A new run was told the whole+conversation again, about 8k more cache writes. Now a run whose owner is+unnamed takes the named owner of the same provider's own sign-in+(`takeNamedOwner`), and goes on: a run in Claude Code's own home runs as+whatever that home is signed in to. A turn that ends without a tool call+takes the name before its keys are made (`nameOwner`, from+`provider.ClaudeOwnName`), so the next turn finds the idle run. Every+other change of owner still lets the run go. The owner is an atomic+pointer (`owned`), read by the run's reader without a lock.+### A conversation the client rewrote (#912)Some clients send a turn's conversation back changed. Alma takes thediff --git a/internal/gateway/claude_account_handoff_test.go b/internal/gateway/claude_account_handoff_test.goindex c81c5ffec..39fd407aa 100644--- a/internal/gateway/claude_account_handoff_test.go+++ b/internal/gateway/claude_account_handoff_test.go@@ -4,6 +4,7 @@ import ("encoding/json""net/http/httptest""strings"+ "sync""testing""time"@@ -15,13 +16,21 @@ import (// must answer, including when the same account moved out of the agent's home.func TestClaudeToolResultsKeepTheSelectedAccount(t *testing.T) {for _, ids := range []string{"exact", "remapped"} {- for _, mode := range []string{"same owner", "another account", "another home"} {+ // "named since": the run started on Claude Code's own sign-in before+ // it had a name (the first run on a new account writes the profile+ // that names it), and its tool results come back under that name.+ // "unnamed, another account": no such rename covers a saved account.+ for _, mode := range []string{"same owner", "another account", "another home", "named since", "unnamed, another account"} {t.Run(ids+"/"+mode, func(t *testing.T) {claudeMadeFirst(t, false)h := newRemapHarness(t)received := make(chan bool, 1)h.first = func(run *subscriptionRun, req *Request) {- run.owner = "claude\[email protected]\x00" + ownHome+ o := "claude\[email protected]\x00" + ownHome+ if strings.HasPrefix(mode, "named since") || strings.HasPrefix(mode, "unnamed") {+ o = "claude\x00Claude Max\x00" + ownHome + "\x00" + unnamedOwner+ }+ run.owner.Store(&o)waiters := h.calls(run, true, shownCall{"call-a", "read", `{}`})go func() {_, ok := <-waiters[0]@@ -34,7 +43,10 @@ func TestClaudeToolResultsKeepTheSelectedAccount(t *testing.T) {h.ask(remapUser("read"))p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "[email protected]"}}want := "kept run"- if mode == "another account" {+ if mode == "unnamed, another account" {+ want = "tok-b turn 1"+ }+ if mode == "another account" || mode == "unnamed, another account" {for _, saved := range p.AlsoOn() {if saved.Account.User == "[email protected]" {p = saved@@ -77,7 +89,7 @@ func TestClaudeToolResultsKeepTheSelectedAccount(t *testing.T) {}select {case got := <-received:- if got != (mode == "same owner") {+ if got != (mode == "same owner" || mode == "named since") {t.Fatalf("old process received the result: %v, mode %s", got, mode)}case <-time.After(2 * time.Second):@@ -87,3 +99,95 @@ func TestClaudeToolResultsKeepTheSelectedAccount(t *testing.T) {}}}++// Only a run started on Claude Code's own sign-in while it had no name+// takes a new owner, and only that sign-in named: every other change of+// account still ends the run.+func TestClaudeRunTakesOnlyItsOwnSignInsName(t *testing.T) {+ unnamed := "claude\x00Claude Max\x00" + ownHome + "\x00" + unnamedOwner+ named := "claude\[email protected]\x00" + ownHome+ for _, c := range []struct {+ was, now string+ takes bool+ }{+ {unnamed, named, true},+ {named, "claude\[email protected]\x00" + ownHome, false},+ {unnamed, "claude\[email protected]", false},+ {unnamed, "other\[email protected]\x00" + ownHome, false},+ {"claude\x00Claude Max\x00" + ownHome, named, false},+ } {+ r := &subscriptionRun{}+ was := c.was+ r.owner.Store(&was)+ if got := r.takeNamedOwner(c.now); got != c.takes {+ t.Fatalf("%q -> %q: took %v, want %v", c.was, c.now, got, c.takes)+ }+ want := c.was+ if c.takes {+ want = c.now+ }+ if r.owned() != want {+ t.Fatalf("%q -> %q: owner %q", c.was, c.now, r.owned())+ }+ }+}++// turnWriter is a run's stdin that has its agent answer the next turn it+// is told.+type turnWriter struct {+ once *sync.Once+ turn func()+}++func (w turnWriter) Write(p []byte) (int, error) {+ w.once.Do(func() { go w.turn() })+ return len(p), nil+}++func (turnWriter) Close() error { return nil }++// A run begun on Claude Code's own sign-in before it had a name, whose+// first turn ends without a tool call, waits for the next turn under the+// name that sign-in has since: the next turn comes by it.+func TestClaudeIdleRunKeptUnderItsOwnSignInsName(t *testing.T) {+ for _, named := range []bool{true, false} {+ t.Run(map[bool]string{true: "named since", false: "still unnamed"}[named], func(t *testing.T) {+ claudeMadeFirst(t, false)+ h := newRemapHarness(t)+ old := claudeOwnName+ claudeOwnName = func() (string, bool) {+ if named {+ return "[email protected]", true+ }+ return "", false+ }+ t.Cleanup(func() { claudeOwnName = old })+ h.first = func(run *subscriptionRun, req *Request) {+ o := "claude\x00Claude Max\x00" + ownHome + "\x00" + unnamedOwner+ run.owner.Store(&o)+ run.stdin = turnWriter{once: &sync.Once{}, turn: func() { h.says(run, "kept run") }}+ run.timer = time.AfterFunc(time.Hour, func() { run.abort() })+ h.says(run, "hello")+ }+ if got := h.ask(remapUser("hi")); len(got) != 1 || got[0] != "text hello" {+ t.Fatalf("first turn: %v", got)+ }+ p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "[email protected]"}}+ body := `{"model":"claude-sonnet-5","max_tokens":100,"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[` + remapUser("hi") + `,{"role":"assistant","content":"hello"},` + remapUser("next") + `]}`+ rec := httptest.NewRecorder()+ code, msg := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &Usage{})+ if code != 200 {+ t.Fatalf("%d %s", code, msg)+ }+ var reply struct{ Content []struct{ Text string } }+ json.Unmarshal(rec.Body.Bytes(), &reply)+ want := "kept run"+ if !named {+ want = "tok-a turn 1"+ }+ if len(reply.Content) != 1 || reply.Content[0].Text != want {+ t.Fatalf("next turn replied %s; want %q", rec.Body, want)+ }+ })+ }+}diff --git a/internal/gateway/claude_handover_test.go b/internal/gateway/claude_handover_test.goindex 036f1ce8c..8f3b1acc5 100644--- a/internal/gateway/claude_handover_test.go+++ b/internal/gateway/claude_handover_test.go@@ -15,7 +15,8 @@ import (func TestClaudeHandOverLetsGoOfTheAccountsRuns(t *testing.T) {b := newSubscriptionBridge()run := func(owner string) *subscriptionRun {- r := &subscriptionRun{bridge: b, owner: owner, pending: map[string]chan mcpToolResult{}}+ r := &subscriptionRun{bridge: b, pending: map[string]chan mcpToolResult{}}+ r.owner.Store(&owner)b.mu.Lock()b.idle[owner] = rr.idleKey = ownerdiff --git a/internal/gateway/claude_idle_test.go b/internal/gateway/claude_idle_test.goindex 0d0d1317f..0ab2b860a 100644--- a/internal/gateway/claude_idle_test.go+++ b/internal/gateway/claude_idle_test.go@@ -127,7 +127,9 @@ func TestClaudeRunEndedMidReplyIsNotKeptIdle(t *testing.T) {b := idleTestBridge()in, out := io.Pipe()defer in.Close()- r := &subscriptionRun{bridge: b, stdin: out, owner: "owner"}+ r := &subscriptionRun{bridge: b, stdin: out}+ owner := "owner"+ r.owner.Store(&owner)fired := make(chan struct{}, 2)r.timer = time.AfterFunc(time.Hour, func() { r.abort(); fired <- struct{}{} })// the timer fires while the reply is going out, and abort is throughdiff --git a/internal/gateway/claude_ratelimit_headers_test.go b/internal/gateway/claude_ratelimit_headers_test.goindex 5a8dd903a..7aeefeeee 100644--- a/internal/gateway/claude_ratelimit_headers_test.go+++ b/internal/gateway/claude_ratelimit_headers_test.go@@ -40,7 +40,8 @@ func TestClaudeSubscriptionReplySaysTheAllowance(t *testing.T) {t.Helper()s := New()start := func(_ context.Context, req *Request) (*subscriptionRun, <-chan Event, error) {- run := &subscriptionRun{bridge: s.subscription, owner: owner, token: "hud", pending: map[string]chan mcpToolResult{}}+ run := &subscriptionRun{bridge: s.subscription, token: "hud", pending: map[string]chan mcpToolResult{}}+ run.owner.Store(&owner)events := run.attach()go run.readOutput(strings.NewReader(strings.Join(lines, "\n") + "\n"))return run, events, nildiff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.goindex ac1a277a7..9c32e4c50 100644--- a/internal/gateway/claude_subscription.go+++ b/internal/gateway/claude_subscription.go@@ -179,10 +179,12 @@ type subscriptionRun struct {timer *time.Timer// Claude Code's input, kept open for the next turn; owner is the account- // it runs as, and idleKey and idleAt say it is waiting for one. convKey- // is the conversation it has had, whatever the model (conversationKeys).+ // it runs as (owned, named once in its life when it started unnamed:+ // takeNamedOwner), and idleKey and idleAt say it is waiting for one.+ // convKey is the conversation it has had, whatever the model+ // (conversationKeys).stdin io.WriteCloser- owner string+ owner atomic.Pointer[string]idleKey stringidleAt time.TimeconvKey string@@ -474,7 +476,7 @@ func (b *subscriptionBridge) handedOver(user string) {var drop []*subscriptionRunb.mu.Lock()for key, run := range b.idle {- if u, own := ownerAccount(run.owner); !own && strings.EqualFold(u, user) {+ if u, own := ownerAccount(run.owned()); !own && strings.EqualFold(u, user) {delete(b.idle, key)run.idleKey = ""drop = append(drop, run)@@ -814,7 +816,8 @@ 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, owner: owner, 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}+ run.owner.Store(&owner)run.names = bridgeNames(req.Tools)run.safeguardBeta = req.SafeguardBetarun.clientMarks = req.clientCache != nil@@ -1246,7 +1249,7 @@ func (b *subscriptionBridge) rewritten(req *Request, owner string) (*subscriptiovar saved *savedSessionfound := 0for _, r := range b.idle {- if r.owner == owner && r.loose != nil && r.loose.key == l.key && r.loose.rewrote(l) {+ if r.owned() == owner && r.loose != nil && r.loose.key == l.key && r.loose.rewrote(l) {run, found = r, found+1}}@@ -1307,7 +1310,7 @@ func (b *subscriptionBridge) retire(owner string, msgs []Message) {var drop []*subscriptionRunb.mu.Lock()for key, run := range b.idle {- if run.owner == owner && run.convKey != "" && slices.Contains(keys, run.convKey) {+ if run.owned() == owner && run.convKey != "" && slices.Contains(keys, run.convKey) {delete(b.idle, key)run.idleKey = ""drop = append(drop, run)@@ -1368,14 +1371,17 @@ func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) {r.abort()return}+ // kept under the name the next turn comes by: a run that began on+ // Claude Code's own sign-in before it had one has named it since+ r.nameOwner()reply := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: said}}}msgs := append(req.Messages[:len(req.Messages):len(req.Messages)], reply)- key := turnKey(r.owner, req, msgs)+ key := turnKey(r.owned(), req, msgs)conv := ""- if keys := conversationKeys(r.owner, msgs); len(keys) > 0 {+ if keys := conversationKeys(r.owned(), msgs); len(keys) > 0 {conv = keys[len(keys)-1]}- loose := newLooseTurn(r.owner, req, msgs, true)+ loose := newLooseTurn(r.owned(), req, msgs, true)r.bridge.mu.Lock()r.loose = loose// the conversation before this turn, when the run was resumed for@@ -1497,7 +1503,7 @@ func (b *subscriptionBridge) shelve(run *subscriptionRun) {return}key := run.idleKey- s := &savedSession{session: sid, sessions: sessions, owner: run.owner, conv: run.convKey, key: key, loose: run.loose, tools: tools, at: run.idleAt, cachePrefix: run.cachePrefix}+ s := &savedSession{session: sid, sessions: sessions, owner: run.owned(), conv: run.convKey, key: key, loose: run.loose, tools: tools, at: run.idleAt, cachePrefix: run.cachePrefix}if old := b.shelf[key]; old != nil {go old.discard()}@@ -2395,7 +2401,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {// a run in Claude Code's own home is on whatever account// Claude Code is signed in to by now: switched off the// owner's, what it says is another's (nil_1024)- if user, own := ownerAccount(r.owner); user != "" && !(own && provider.ClaudeCodeMovedOff(user)) {+ if user, own := ownerAccount(r.owned()); user != "" && !(own && provider.ClaudeCodeMovedOff(user)) {provider.NoteClaudeLimits(user, claudeLimits(envelope.RateLimitInfo))}return@@ -2435,7 +2441,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {// it isn't run again on that one (provider/claude_auth.go) —// not when Claude Code's own run went on as another account,// which is read only for such an error- if user, own := ownerAccount(r.owner); user != "" && provider.ClaudeSignInRequired(text) &&+ if user, own := ownerAccount(r.owned()); user != "" && provider.ClaudeSignInRequired(text) &&!(own && provider.ClaudeCodeMovedOff(user)) {provider.NoteClaudeSignInFailure(user, r.loginVersion, text)}@@ -4159,6 +4165,59 @@ func (b *subscriptionBridge) removeRun(run *subscriptionRun) {}}+// owned is the account the run runs as (serveClaudeSubscription's owner).+func (r *subscriptionRun) owned() string {+ if o := r.owner.Load(); o != nil {+ return *o+ }+ return ""+}++// takeNamedOwner has a run started on Claude Code's own sign-in while it+// was known by no name (unnamedOwner) go on as owner, that sign-in named+// since: a run in Claude Code's own home runs as whatever it is signed in+// to, as a new run there would. It says whether the run took it.+func (r *subscriptionRun) takeNamedOwner(owner string) bool {+ o := r.owner.Load()+ if o == nil {+ return false+ }+ w, n := strings.Split(*o, "\x00"), strings.Split(owner, "\x00")+ if len(w) != 4 || w[2] != ownHome || w[3] != unnamedOwner || len(n) < 3 || n[0] != w[0] || n[2] != ownHome {+ return false+ }+ if !r.owner.CompareAndSwap(o, &owner) {+ return false+ }+ log.Printf("claude: the run on Claude Code's own sign-in, %q until it was named, goes on as %q", w[1], n[1])+ return true+}++// nameOwner has a run begun on Claude Code's own sign-in while it had no+// name take the name that sign-in has now, when it has one: the turn the+// run waits for comes by it (takeNamedOwner).+func (r *subscriptionRun) nameOwner() {+ o := r.owner.Load()+ if o == nil {+ return+ }+ f := strings.Split(*o, "\x00")+ if len(f) != 4 || f[2] != ownHome || f[3] != unnamedOwner {+ return+ }+ if user, ok := claudeOwnName(); ok {+ r.takeNamedOwner(f[0] + "\x00" + user + "\x00" + ownHome)+ }+}++// claudeOwnName is provider.ClaudeOwnName; tests name the sign-in.+var claudeOwnName = provider.ClaudeOwnName++// unnamedOwner marks a run's owner as Claude Code's own sign-in while it+// is known by no name (provider's Account.Unnamed): the name in the owner+// is made from its plan, and the next turn may come named by its email.+const unnamedOwner = "unnamed"+// ownHome marks a run's owner as Claude Code's own sign-in, run in its// own home.const ownHome = "own"@@ -4201,7 +4260,7 @@ func (b *subscriptionBridge) whyNoRun(req *Request, owner string) string {if r.behindKey == key {return "its run went on with a turn this one doesn't follow, and wasn't taken back"}- if r.owner != owner || r.convKey == "" || !slices.Contains(keys, r.convKey) {+ if r.owned() != owner || r.convKey == "" || !slices.Contains(keys, r.convKey) {continue}if r.convKey == keys[len(keys)-1] {@@ -4210,7 +4269,7 @@ func (b *subscriptionBridge) whyNoRun(req *Request, owner string) string {return "its run waits at an earlier turn of the conversation"}for _, r := range b.runs {- if r.owner == owner && r.idleKey == "" && r.convKey != "" && slices.Contains(keys, r.convKey) {+ if r.owned() == owner && r.idleKey == "" && r.convKey != "" && slices.Contains(keys, r.convKey) {return "its run is busy with another request"}}@@ -4250,6 +4309,9 @@ func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request,// A process in the agent's home reads that home's current sign-in.// A saved account must not resume it after the sign-in moves.owner += "\x00" + ownHome+ if p.Account.Unnamed() {+ owner += "\x00" + unnamedOwner+ }}}start := func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error) {@@ -4387,7 +4449,11 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from// Tool-call IDs find the process that made them, independently of the// account routing selected. Continuing a different owner's process would// spend its quota and report its reply or limit against the chosen account.- if run != nil && run.owner != owner {+ // The first turn on Claude Code's own sign-in, known by no name yet, is+ // the exception: its run's Claude Code puts the account's profile in+ // Claude Code's config, so its tool results come back on the same+ // sign-in named by its email, and the run goes on under that name.+ if run != nil && run.owned() != owner && !run.takeNamedOwner(owner) {run.abort()run, how = nil, accountChanged}diff --git a/internal/provider/account.go b/internal/provider/account.goindex 0ce7ff4fd..2248bc5a7 100644--- a/internal/provider/account.go+++ b/internal/provider/account.go@@ -66,6 +66,11 @@ type Account struct {// Code's own while Claude Code is signed out (claude_dirs.go).standIn bool+ // unnamed is Claude Code's own sign-in while it is known by no name:+ // User is a name made from its plan ("Claude Max") until Claude Code+ // puts the account's profile in its config, as its first run does.+ unnamed bool+// codeAssist is where a Gemini CLI or Antigravity account's requests// go (google.go).codeAssist string@@ -786,13 +791,29 @@ func claudeAccount() (Provider, bool) {}user = claudeSignInOwner(readLogins(), l).User}- if user == "" {+ unnamed := user == ""+ if unnamed {user = "Claude account"if plan != "" {user = "Claude " + strings.ToUpper(plan[:1]) + plan[1:]}}- return claudeProvider(&Account{Agent: "claude", User: user, Plan: plan}), true+ return claudeProvider(&Account{Agent: "claude", User: user, Plan: plan, unnamed: unnamed}), true+}++// Unnamed says the account is Claude Code's own sign-in known by no name+// yet: its User is made from its plan, and it is named by its email once+// Claude Code's first run has put its profile in Claude Code's config.+func (a *Account) Unnamed() bool { return a != nil && a.unnamed }++// ClaudeOwnName is the name Claude Code's own sign-in is served by now,+// and false while it has none (Unnamed) or Claude Code is signed out.+func ClaudeOwnName() (string, bool) {+ p, ok := claudeAccount()+ if !ok || p.Account == nil || !p.Account.AgentsOwn() || p.Account.standIn || p.Account.unnamed {+ return "", false+ }+ return p.Account.User, true}// StandIn says the account is a saved one served in the place of thediff --git a/internal/provider/account_test.go b/internal/provider/account_test.goindex af677c910..885e27e59 100644--- a/internal/provider/account_test.go+++ b/internal/provider/account_test.go@@ -301,7 +301,7 @@ func TestClaudeAccountIsProvider(t *testing.T) {t.Cleanup(catalog.Reset)p, ok := find(All(), "claude")- if !ok || p.Account == nil || p.Account.User != "Claude Max" || p.Account.Plan != "max" || !p.Ready() {+ if !ok || p.Account == nil || p.Account.User != "Claude Max" || !p.Account.Unnamed() || p.Account.Plan != "max" || !p.Ready() {t.Fatalf("claude: %+v %v", p, ok)}if p.Anthropic != claudeBase || p.Chat != "" || p.Responses != "" || p.Host() == "" {diff --git a/internal/provider/claude_auth_test.go b/internal/provider/claude_auth_test.goindex 4f393dad5..727589cb5 100644--- a/internal/provider/claude_auth_test.go+++ b/internal/provider/claude_auth_test.go@@ -33,6 +33,9 @@ func claudeAuthFixture(t *testing.T, lapse string) (Provider, savedLogin) {if !ok {t.Fatal("own Claude account missing")}+ if p.Account.User != "[email protected]" || p.Account.Unnamed() {+ t.Fatalf("own account named by its profile: %q unnamed %v", p.Account.User, p.Account.Unnamed())+ }return p, side}