diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 173286e28..f2b66acca 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -334,6 +334,13 @@ type subscriptionRun struct { // compares it, for a client that took its images out since (#1382). told string toldRuns []heardRun + // opening is the first message of that conversation (historyKey): + // a client that compacted it begins it with its summary instead + // (opensWith). resent says a request sent the turn the run answers + // again while the run had it (supersede): it waits parkLongest at most + // on its calls, until results of its own come (continueWith). + opening string + resent bool // A run whose output may not carry a call before it is made (Claude // Code's interactive mode, readOutput) learns of it here, as the MCP @@ -2430,6 +2437,81 @@ func (b *subscriptionBridge) retire(owner string, req *Request) { } } +// supersede ends, or bounds, the runs waiting on tool calls whose +// conversation req carries on in run, the one started or resumed for it +// (Kling__Lab on X). A run left waiting on calls no client will answer +// holds a Claude Code that, in the interactive mode, moves a call to the +// background after 120s and goes on working for no one, writing its +// session, until runTimeout ends it: 30 to 80 minutes, in which the next +// run's model read its session as another one at the same work. +// +// - Its client compacted the conversation: req names calls the run made +// (its pending calls, the ones last answered in it, or those its +// session has lines for) but begins with another message than the +// conversation the run heard (opensWith), the client's summary. Its +// results, if they come, are in this conversation, and the run is +// ended now. A fork or a resumed session of Claude Code (#2933) +// begins with its lead's own first message, and the run is left to +// its parkLongest (released). +// - The very turn the run answers is sent again (a sub-agent's Task a +// client sent twice): the client may have given up on the first +// answer, or asked two sub-agents the same thing. The run is not +// ended, but waits parkLongest at most on its calls (resent), as one +// whose caller stopped does, and goes on as before if its results +// come. +func (b *subscriptionBridge) supersede(req *Request, run *subscriptionRun) { + owner := run.owned() + named := map[string]bool{} + for _, m := range req.Messages { + for _, p := range m.Parts { + switch { + case p.Kind == ToolCall && p.ID != "": + named[p.ID] = true + case p.Kind == ToolResult && p.CallID != "": + named[p.CallID] = true + } + } + } + want := historyKey(req.Messages) + b.mu.Lock() + var runs []*subscriptionRun + for _, r := range b.runs { + // one kept for its conversation's next turn waits on no call + if r != run && r.idleKey == "" && r.owned() == owner { + runs = append(runs, r) + } + } + b.mu.Unlock() + for _, r := range runs { + r.mu.Lock() + waiting := !r.closed && !r.resuming && r.segment == nil && len(r.pending) > 0 + mine := false + for id := range r.pending { + mine = mine || named[id] + } + for _, id := range r.results { + mine = mine || named[id] + } + for id := range r.lines { + mine = mine || named[id] + } + again := !r.closed && r.told != "" && r.told == want + if again { + r.resent = true + } + long := r.timer != nil && time.Until(r.ends) > parkLongest + r.mu.Unlock() + switch { + case waiting && mine && !r.opensWith(req.Messages): + log.Printf("claude: Claude Code pid %d (%s) is let go while it waits on tool calls: its client compacted the conversation, which goes on in a new run", r.pid(), r.model) + r.abortFor("its client compacted the conversation, which went on in a new run") + case again && waiting && long: + log.Printf("claude: Claude Code pid %d (%s) waits %s more at most on its tool calls: its turn was sent again, and goes on in another run", r.pid(), r.model, parkLongest) + r.endIn(parkLongest) + } + } +} + // aside says req may call none of the client's tools: a tool_choice of // none, or no tools. func aside(req *Request) bool { @@ -3645,6 +3727,7 @@ func (r *subscriptionRun) park() { } } r.parkedSeq = r.lineSeq + resent := r.resent r.mu.Unlock() switch { case r.timer == nil: @@ -3655,6 +3738,9 @@ func (r *subscriptionRun) park() { case r.stdin == nil: r.endIn(parkLongest) return + case resent: + // its turn was sent again: its client may have given up on it + r.endIn(parkLongest) } if why, over := r.oversized(3); over { log.Printf("claude: Claude Code pid %d (%s) is let go while it waits on tool calls: %s; their results go to a new one told the whole conversation", r.pid(), r.model, why) @@ -3736,11 +3822,24 @@ func historyKey(msgs []Message) string { // heard keeps the conversation of the request the run now answers. func (r *subscriptionRun) heard(msgs []Message) { key, runs := historyKey(msgs), heardRuns(msgs, true) + opening := "" + if len(msgs) > 0 { + opening = historyKey(msgs[:1]) + } r.mu.Lock() - r.told, r.toldRuns = key, runs + r.told, r.toldRuns, r.opening = key, runs, opening r.mu.Unlock() } +// opensWith says msgs begin with the message the conversation the run +// last heard began with, or that the run heard none. +func (r *subscriptionRun) opensWith(msgs []Message) bool { + r.mu.Lock() + opening := r.opening + r.mu.Unlock() + return opening == "" || len(msgs) > 0 && historyKey(msgs[:1]) == opening +} + // follows says msgs go on from the conversation the run last heard: that // one whole, then the reply and what came since. A client that rewrote it // meanwhile — Pi compacting between a tool call and its result, a rewind — @@ -6302,6 +6401,7 @@ func (r *subscriptionRun) continueWith(results []Part, said string, tools []brid for _, p := range results { r.results = append(r.results, p.CallID) } + r.resent = false // its own client's results came: it is no one's leftover r.mu.Unlock() if r.resume != nil { r.resume() @@ -7486,6 +7586,9 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro // a run resumed is told this request's too req.runTold(run) run.adviseOn(r.Context(), req, s.adviceRound) + if name == "Claude Code" { + s.subscription.supersede(req, run) + } } } if err != nil { diff --git a/internal/gateway/claude_subscription_rewrite_test.go b/internal/gateway/claude_subscription_rewrite_test.go index e54eff64b..91534568e 100644 --- a/internal/gateway/claude_subscription_rewrite_test.go +++ b/internal/gateway/claude_subscription_rewrite_test.go @@ -108,10 +108,12 @@ func TestRunLetGoWhenTheClientRewroteTheConversation(t *testing.T) { if got := ask(`[` + conv + `]`); got != "tool_use call_2" || len(started) != 1 { t.Fatalf("a conversation that went on: %q from %d runs", got, len(started)) } - // the client compacts, and sends call_2's result after its summary; the - // rewrite is answered by a run of its own, and the run that made the - // calls goes on waiting for the results of the client that has not - // rewritten anything + // a fork of the conversation, an earlier result cleared in it, sends + // call_2's result; the rewrite is answered by a run of its own, and + // the run that made the calls goes on waiting for the results of the + // client that has not rewritten anything. (A client that compacted + // it, beginning it with a summary, has the run ended instead: + // TestCompactedConversationEndsTheRunThatWaitedOnItsCalls.) go func(run *subscriptionRun, waiter chan mcpToolResult) { if r, ok := <-waiter; !ok { t.Errorf("the run's call was closed before its own results came") @@ -121,11 +123,11 @@ func TestRunLetGoWhenTheClientRewroteTheConversation(t *testing.T) { } says(run, "from the conversation it was told") }(started[0], <-second) - rewritten := `[` + user("a summary of the conversation so far") + `,` + call("call_2") + `,` + result("call_2", "B") + `]` + rewritten := `[` + user("read a, then b") + `,` + call("call_1") + `,` + result("call_1", "[cleared]") + `,` + call("call_2") + `,` + result("call_2", "B") + `]` if got := ask(rewritten); got != "text from the conversation as it now is" { t.Fatalf("after the rewrite: %q", got) } - if len(started) != 2 || len(told[1]) != 3 || told[1][0].Parts[0].Text != "a summary of the conversation so far" { + if len(started) != 2 || len(told[1]) != 5 || told[1][2].Parts[0].Text != "[cleared]" { t.Fatalf("%d runs, the last told %+v", len(started), told[len(told)-1]) } started[0].mu.Lock() @@ -229,12 +231,14 @@ func TestRewrittenRunWaitsParkLongestForItsOwnResults(t *testing.T) { return `{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":` + strconv.Quote(text) + `}]}` } - if got := ask(`[` + user("read a") + `]`); got != "tool_use call_1" { + reply := func(text string) string { return `{"role":"assistant","content":` + strconv.Quote(text) + `}` } + if got := ask(`[` + user("read a") + `,` + reply("which a?") + `,` + user("the first") + `]`); got != "tool_use call_1" { t.Fatalf("the first turn: %q", got) } - // a rewritten request for the same call's results: answered by a run of - // its own, and the run that made the call is not ended for it - rewritten := `[` + user("a summary of the conversation so far") + `,` + call("call_1") + `,` + result("call_1", "A") + `]` + // a rewritten request for the same call's results, a fork's with an + // earlier message of its own: answered by a run of its own, and the + // run that made the call is not ended for it + rewritten := `[` + user("read a") + `,` + reply("which one?") + `,` + user("the first") + `,` + call("call_1") + `,` + result("call_1", "A") + `]` if got := ask(rewritten); got != "text from the conversation as it now is" || len(started) != 2 { t.Fatalf("after the rewrite: %q from %d runs", got, len(started)) } diff --git a/internal/gateway/claude_subscription_supersede_test.go b/internal/gateway/claude_subscription_supersede_test.go new file mode 100644 index 000000000..80d570c8c --- /dev/null +++ b/internal/gateway/claude_subscription_supersede_test.go @@ -0,0 +1,243 @@ +package gateway + +import ( + "context" + "encoding/json" + "net/http/httptest" + "strconv" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// supersedeHarness drives serveSubscription with runs that call a tool or +// say a word, each with Claude Code's open input and a timer as a real +// run has, so park leaves the timer as it was. +type supersedeHarness struct { + t *testing.T + s *Server + started []*subscriptionRun + // what the run started next does: call the tool, by this id, or say + // a word when "" + next string +} + +func newSupersedeHarness(t *testing.T) *supersedeHarness { + return &supersedeHarness{t: t, s: New()} +} + +func (h *supersedeHarness) calls(run *subscriptionRun, id string) chan mcpToolResult { + b := h.s.subscription + waiter := make(chan mcpToolResult, 1) + run.mu.Lock() + run.pending[id] = waiter + run.mu.Unlock() + b.mu.Lock() + b.calls[id] = run + b.mu.Unlock() + run.emit(Event{Kind: KStart, MsgID: "m", Model: "claude-sonnet-5"}) + run.emit(Event{Kind: KToolStart, ID: id, Name: "read"}) + run.emit(Event{Kind: KToolArgs, Text: "{}"}) + run.emit(Event{Kind: KStop, Stop: "tool"}) + run.endSegment() + return waiter +} + +func (h *supersedeHarness) says(run *subscriptionRun, text string) { + run.emit(Event{Kind: KStart, MsgID: "m", Model: "claude-sonnet-5"}) + run.emit(Event{Kind: KText, Text: text}) + run.emit(Event{Kind: KStop, Stop: "stop"}) + run.endSegment() +} + +func (h *supersedeHarness) start(_ context.Context, req *Request) (*subscriptionRun, <-chan Event, error) { + b := h.s.subscription + run := &subscriptionRun{bridge: b, token: "run" + strconv.Itoa(len(h.started)), pending: map[string]chan mcpToolResult{}, stdin: nopStdin{}} + b.mu.Lock() + b.runs[run.token] = run + b.mu.Unlock() + events := run.attach() + // as a run started for real: runTimeout, which park leaves as it is + run.timer = time.AfterFunc(runTimeout, func() { run.abortFor("it waited as long as it may") }) + run.ends = time.Now().Add(runTimeout) + h.t.Cleanup(func() { run.abort() }) + if h.next != "" { + h.calls(run, h.next) + } else { + h.says(run, "from the conversation as it now is") + } + h.started = append(h.started, run) + return run, events, nil +} + +func (h *supersedeHarness) ask(msgs string) string { + h.t.Helper() + body := `{"model":"claude-sonnet-5","max_tokens":100,"tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":` + msgs + `}` + rec := httptest.NewRecorder() + var u Usage + if code, msg := h.s.serveSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, "Claude Code", "claude-sonnet-5", "", []byte(body), &u, h.start); code != 200 { + h.t.Fatalf("%d %s", code, msg) + } + var res struct { + Content []struct{ Type, Text, ID string } `json:"content"` + } + json.Unmarshal(rec.Body.Bytes(), &res) + if len(res.Content) == 0 { + h.t.Fatalf("no answer: %s", rec.Body) + } + return res.Content[0].Type + " " + res.Content[0].Text + res.Content[0].ID +} + +func closedRun(run *subscriptionRun) bool { + run.mu.Lock() + defer run.mu.Unlock() + return run.closed +} + +func endsIn(run *subscriptionRun) time.Duration { + run.mu.Lock() + defer run.mu.Unlock() + return time.Until(run.ends) +} + +func supUser(text string) string { return `{"role":"user","content":` + strconv.Quote(text) + `}` } +func supCall(id string) string { + return `{"role":"assistant","content":[{"type":"tool_use","id":"` + id + `","name":"read","input":{}}]}` +} +func supResult(id, text string) string { + return `{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":` + strconv.Quote(text) + `}]}` +} + +// The client compacted the conversation while a run waited on its tool +// calls, and sends their results after its summary (Kling__Lab on X: Alma's +// autoCompact, Claude Code in its interactive mode): the summary is answered +// by a new run, and the run that made the calls is ended there and then. No +// client will send it results any more: its own client has the +// conversation as the summary. Left waiting, its Claude Code moved the calls +// to the background after 120s and went on working for no one, writing its +// session for 30 to 80 minutes, which the new run's model read as another +// session at the same work. +func TestCompactedConversationEndsTheRunThatWaitedOnItsCalls(t *testing.T) { + h := newSupersedeHarness(t) + h.next = "call_1" + if got := h.ask(`[` + supUser("read a") + `]`); got != "tool_use call_1" { + t.Fatalf("the first turn: %q", got) + } + h.next = "" + rewritten := `[` + supUser("a summary of the conversation so far") + `,` + supCall("call_1") + `,` + supResult("call_1", "A") + `]` + if got := h.ask(rewritten); got != "text from the conversation as it now is" || len(h.started) != 2 { + t.Fatalf("after the compaction: %q from %d runs", got, len(h.started)) + } + if !closedRun(h.started[0]) { + t.Fatalf("the run whose conversation was compacted still waits on its calls, ending in %s", endsIn(h.started[0]).Round(time.Second)) + } + if closedRun(h.started[1]) { + t.Fatal("the run the compacted conversation goes on in was ended") + } +} + +// The compacted conversation may not carry the waiting calls' results at +// all: the client dropped the call it was running and went on with the +// next turn, its summary and the recent messages, which hold calls the run +// made and was answered for before. No request finds the run (no run waits +// for this turn), and it is ended all the same when the new run starts. +func TestCompactedConversationWithoutTheResultsEndsTheRun(t *testing.T) { + h := newSupersedeHarness(t) + h.next = "call_1" + if got := h.ask(`[` + supUser("read a, then b") + `]`); got != "tool_use call_1" { + t.Fatalf("the first turn: %q", got) + } + // its results go on in it, and it calls again + first := h.started[0] + conv := supUser("read a, then b") + `,` + supCall("call_1") + `,` + supResult("call_1", "A") + first.mu.Lock() + waiter := first.pending["call_1"] + first.mu.Unlock() + go func() { + if _, ok := <-waiter; ok { + h.calls(first, "call_2") + } + }() + if got := h.ask(`[` + conv + `]`); got != "tool_use call_2" || len(h.started) != 1 { + t.Fatalf("a conversation that went on: %q from %d runs", got, len(h.started)) + } + // compacted while call_2 runs: the summary, the recent messages and + // the user's next words, call_2 dropped + h.next = "" + compacted := `[` + supUser("a summary of the conversation so far") + `,` + supCall("call_1") + `,` + supResult("call_1", "A") + `,` + supUser("go on") + `]` + if got := h.ask(compacted); got != "text from the conversation as it now is" || len(h.started) != 2 { + t.Fatalf("after the compaction: %q from %d runs", got, len(h.started)) + } + if !closedRun(first) { + t.Fatalf("the run whose conversation was compacted still waits on call_2, ending in %s", endsIn(first).Round(time.Second)) + } +} + +// A conversation that names none of a waiting run's calls is another +// one: a run of the same account, waiting on its own calls, is left as it +// was, however its conversation began. +func TestAnotherConversationLeavesAWaitingRunAlone(t *testing.T) { + h := newSupersedeHarness(t) + h.next = "call_1" + if got := h.ask(`[` + supUser("read a") + `]`); got != "tool_use call_1" { + t.Fatalf("the first turn: %q", got) + } + h.next = "" + if got := h.ask(`[` + supUser("something else") + `]`); got != "text from the conversation as it now is" { + t.Fatalf("another conversation: %q", got) + } + if closedRun(h.started[0]) { + t.Fatal("a run waiting on its calls was ended by another conversation") + } + if d := endsIn(h.started[0]); d < runTimeout-time.Minute { + t.Fatalf("a run waiting on its calls was cut to %s by another conversation", d.Round(time.Second)) + } +} + +// A turn sent again while the run it started waits on its calls (Alma +// sending a sub-agent's Task request again): the new request gets a run of +// its own, as before, and the first one isn't left waiting runTimeout on +// calls whose client gave up on the turn. It isn't ended at once either, +// since two of a client's sub-agents may be asked the very same thing: it +// waits parkLongest, as a run whose caller stopped does, and goes on if +// its results come. +func TestTurnSentAgainBoundsTheRunWaitingOnIt(t *testing.T) { + h := newSupersedeHarness(t) + h.next = "call_1" + task := `[` + supUser("review the change") + `]` + if got := h.ask(task); got != "tool_use call_1" { + t.Fatalf("the first turn: %q", got) + } + h.next = "call_2" + if got := h.ask(task); got != "tool_use call_2" || len(h.started) != 2 { + t.Fatalf("the turn sent again: %q from %d runs", got, len(h.started)) + } + first := h.started[0] + if closedRun(first) { + t.Fatal("the run of a turn sent again was ended at once: it may be a sub-agent asked the same thing") + } + if d := endsIn(first); d > parkLongest { + t.Fatalf("the run of a turn sent again waits %s more on its calls, past parkLongest (%s)", d.Round(time.Second), parkLongest) + } + if d := endsIn(h.started[1]); d < runTimeout-time.Minute { + t.Fatalf("the run the turn went on in waits only %s", d.Round(time.Second)) + } + // its own results come all the same: it goes on, its wait a turn's + first.mu.Lock() + waiter := first.pending["call_1"] + first.mu.Unlock() + go func() { + if _, ok := <-waiter; ok { + h.says(first, "the first one's answer") + } + }() + h.next = "" + if got := h.ask(`[` + supUser("review the change") + `,` + supCall("call_1") + `,` + supResult("call_1", "ok") + `]`); got != "text the first one's answer" || len(h.started) != 2 { + t.Fatalf("the first run's own results: %q from %d runs", got, len(h.started)) + } + if closedRun(first) { + t.Fatal("the first run was ended though its results came") + } +}