From 77860f7e4514db7aba8182c8dee383ff1b93bf37 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 4 Oct 2026 19:22:20 +0800 Subject: [PATCH] =?UTF-8?q?claude:=20a=20turn=20stopped=20mid-reply=20is?= =?UTF-8?q?=20taken=20back=20in=20the=20same=20Claude=20Code,=20so=20the?= =?UTF-8?q?=20resend=20reads=20the=20cache=20it=20wrote=20(#780,=20Kenoia)?= =?UTF-8?q?=20=E2=80=94=20a=20499=20(the=20user=20pressed=20Esc=20and=20re?= =?UTF-8?q?worded=20the=20message)=20ended=20the=20Claude=20Code=20run,=20?= =?UTF-8?q?and=20the=20resend=20found=20no=20run=20waiting,=20started=20a?= =?UTF-8?q?=20new=20one=20and=20told=20it=20the=20whole=20conversation=20i?= =?UTF-8?q?n=20one=20message:=20a=20prefix=20the=20cache=20had=20never=20s?= =?UTF-8?q?een,=20written=20again=20whole=20(~119k=20tokens=20in=20the=20r?= =?UTF-8?q?eport).=20A=20turn=20resumed=20in=20a=20run=20kept=20for=20it?= =?UTF-8?q?=20now=20sends=20its=20user=20line=20with=20a=20uuid;=20when=20?= =?UTF-8?q?the=20client=20goes=20away,=20magpie=20tells=20that=20Claude=20?= =?UTF-8?q?Code=20a=20rewind=5Fconversation=20control=20request=20to=20tha?= =?UTF-8?q?t=20uuid=20with=20interrupt=5Fif=5Frunning=20(as=20its=20SDK's?= =?UTF-8?q?=20rewindConversation=20does),=20which=20stops=20the=20reply=20?= =?UTF-8?q?and=20leaves=20its=20conversation=20as=20it=20was=20before=20th?= =?UTF-8?q?e=20turn,=20and=20the=20run=20waits=20again=20where=20it=20wait?= =?UTF-8?q?ed=20before,=20so=20the=20resend=20goes=20on=20in=20it=20with?= =?UTF-8?q?=20only=20its=20new=20message.=20A=20run=20started=20for=20the?= =?UTF-8?q?=20turn,=20one=20with=20tool=20calls=20in=20the=20client's=20ha?= =?UTF-8?q?nds,=20a=20continuation=20after=20tool=20results=20(the=20turn'?= =?UTF-8?q?s=20id=20is=20dropped=20when=20its=20reply=20ends),=20or=20a=20?= =?UTF-8?q?Claude=20Code=20that=20refuses=20or=20doesn't=20answer=20in=201?= =?UTF-8?q?0s=20is=20ended=20as=20before;=20a=20reply=20that=20ended=20as?= =?UTF-8?q?=20the=20client=20went=20away=20is=20left=20to=20the=20rewind.?= =?UTF-8?q?=20With=20the=20owner's=20real=20Claude=20account=20in=20a=20sa?= =?UTF-8?q?ndbox=20(Claude=20Code=202.1.289,=20haiku=204.5):=20two=20turns?= =?UTF-8?q?,=20a=20third=20streamed=20and=20dropped=20after=203=20deltas,?= =?UTF-8?q?=20then=20the=20resend=20reworded:=20the=20same=20Claude=20Code?= =?UTF-8?q?=20pids=20throughout,=20the=20log=20said=20"the=20turn=20the=20?= =?UTF-8?q?client=20gave=20up=20on=20was=20taken=20back",=20and=20the=20re?= =?UTF-8?q?send=20read=206667=20tokens=20from=20the=20cache=20(the=20whole?= =?UTF-8?q?=20prefix=20before)=20and=20wrote=2091.=20TestClaudeTurnGivenUp?= =?UTF-8?q?OnIsRewound,=20TestClaudeTurnGivenUpOnNotRewound=20(refuse,=20s?= =?UTF-8?q?ilent)=20and=20TestClaudeFirstTurnGivenUpOnEnds;=20the=20Claude?= =?UTF-8?q?=20tests=20pass=20under=20-race.=20go=20vet,=20builds=20(darwin?= =?UTF-8?q?,=20GOOS=3Dlinux,=20GOOS=3Dwindows)=20and=20go=20test=20-tags?= =?UTF-8?q?=20nogui=20-count=3D1=20./...=20under=20a=20temp=20HOME=20pass.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/claude_subscription.go | 207 +++++++++++++- .../claude_subscription_rewind_test.go | 261 ++++++++++++++++++ 2 files changed, 459 insertions(+), 9 deletions(-) create mode 100644 internal/gateway/claude_subscription_rewind_test.go diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 2cfe601dc..cd8f96493 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -18,6 +18,15 @@ package gateway // prompt it has cached is read again. A new run would start from the whole // history in one message, which shares nothing with what was cached but // Claude Code's own prompt. +// +// A turn the client gives up on mid-reply (a 499: the user stopped it) is +// taken back in the same Claude Code, not ended with it (#780): Claude +// Code is told to rewind its conversation to before that turn's message, +// stopping the reply, and the run waits again as it did before the turn. +// The client's resend — the same conversation, its last message reworded +// — goes on from there, and the prefix it sends Anthropic is the one +// already cached. Ended, the run's conversation was told to a new one in +// one message, written to the cache again whole. import ( "bufio" @@ -40,6 +49,7 @@ import ( "slices" "strings" "sync" + "sync/atomic" "time" "github.com/yetone/magpie/internal/netproxy" @@ -128,6 +138,16 @@ type subscriptionRun struct { idleAt time.Time convKey string + // turnUUID is the id the turn it was resumed for gave its user message, + // and backKey the conversation it was waiting at before (turnKey): + // a turn the client gives up on is rewound to that message, and the + // run waits at backKey again (letGo). rewinding is open while it is + // told to; controls are its control requests waiting on an answer. + turnUUID string + backKey string + rewinding chan struct{} + controls map[string]chan controlReply + // effort is the level its Claude Code thinks at, as it started (its // --effort) or was told since (setEffort); "" is Claude Code's own effort string @@ -490,7 +510,18 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu if run == nil { return nil, nil } - line, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": renderClaudeTurn(since)}}) + // a run still taking back the turn the client gave up on (letGo) is + // waited for: it goes on from before that turn, or ended + run.mu.Lock() + rewinding := run.rewinding + run.mu.Unlock() + if rewinding != nil { + <-rewinding + } + // the message's id is the turn's, to rewind to if the client gives up + // on it + turn := newUUID() + line, _ := json.Marshal(map[string]any{"type": "user", "uuid": turn, "message": map[string]any{"role": "user", "content": renderClaudeTurn(since)}}) run.mu.Lock() if run.closed { run.mu.Unlock() @@ -498,6 +529,7 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu } ch := make(chan Event, 64) run.segment = ch + run.turnUUID, run.backKey = turn, key run.mu.Unlock() run.timer.Reset(30 * time.Minute) // a turn the router picked another effort for (#502) goes on in the @@ -556,6 +588,11 @@ func (b *subscriptionBridge) retire(owner string, msgs []Message) { // asked for nothing more waits for the conversation's next turn; one that // failed, was cut short or went unheard is let go, as is a one-off ask. func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) { + // the turn's reply is over: nothing after it (its tool calls' answers + // going on) is taken back to before it (letGo) + r.mu.Lock() + r.turnUUID, r.backKey = "", "" + r.mu.Unlock() switch { case !ok: // the caller has no whole reply, so no tool calls to answer @@ -580,16 +617,27 @@ func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) { } reply := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: said}}} key := turnKey(r.owner, req, append(req.Messages[:len(req.Messages):len(req.Messages)], reply)) - b := r.bridge + conv := "" + if keys := conversationKeys(r.owner, append(req.Messages[:len(req.Messages):len(req.Messages)], reply)); len(keys) > 0 { + conv = keys[len(keys)-1] + } + r.bridge.keepIdle(r, key, conv) + r.timer.Reset(idleLongest) +} + +// keepIdle leaves run waiting for the turn after the conversation key +// names, the longest waiting let go past idleMost; conv, when set, is that +// conversation whatever the model (convKey). +func (b *subscriptionBridge) keepIdle(r *subscriptionRun, key, conv string) { var drop []*subscriptionRun b.mu.Lock() - if old := b.idle[key]; old != nil { + if old := b.idle[key]; old != nil && old != r { drop = append(drop, old) } b.idle[key] = r r.idleKey, r.idleAt = key, time.Now() - if keys := conversationKeys(r.owner, append(req.Messages[:len(req.Messages):len(req.Messages)], reply)); len(keys) > 0 { - r.convKey = keys[len(keys)-1] + if conv != "" { + r.convKey = conv } for len(b.idle) > idleMost { var oldest *subscriptionRun @@ -603,12 +651,130 @@ func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) { drop = append(drop, oldest) } b.mu.Unlock() - r.timer.Reset(idleLongest) for _, run := range drop { run.abort() } } +// rewindLongest is how long Claude Code may take to answer a rewind +// before its run is let go. +var rewindLongest = 10 * time.Second + +// controlReply is Claude Code's control_response to a control request. +type controlReply struct { + Subtype string `json:"subtype"` + RequestID string `json:"request_id"` + Error string `json:"error"` + Response struct { + Rewound bool `json:"rewound"` + } `json:"response"` +} + +// letGo is told the client went away mid-reply (#780). A turn resumed in +// a run kept for it is taken back: Claude Code is told to rewind to the +// turn's message, which stops the reply and leaves its conversation as it +// was before the turn, and the run waits there again, for the client's +// resend to go on from the prefix it cached. Any other run — one started +// for the turn, one with a tool call in the client's hands, one whose +// Claude Code refuses or doesn't answer — is ended, as before. +func (r *subscriptionRun) letGo() { + r.mu.Lock() + turn, back := r.turnUUID, r.backKey + can := !r.closed && r.stdin != nil && r.bridge != nil && r.timer != nil && + turn != "" && back != "" && len(r.pending) == 0 && r.rewinding == nil + done := make(chan struct{}) + if can { + r.rewinding = done + r.turnUUID, r.backKey = "", "" // once a turn + } + r.mu.Unlock() + if !can { + r.abort() + return + } + defer func() { + r.mu.Lock() + r.rewinding = nil + r.mu.Unlock() + close(done) + }() + // the reply goes to no one from here: what Claude Code says as it + // stops (an interrupted result) is read past + r.endSegment() + // found at once by a resend, which waits for the rewind (resume) + r.bridge.keepIdle(r, back, "") + if err := r.rewind(turn); err != nil { + log.Printf("claude: a turn the client gave up on could not be taken back, its run let go: %v", err) + r.abort() + return + } + r.mu.Lock() + r.asked, r.shown, r.parkedAt = nil, nil, time.Time{} + clear(r.early) + r.mu.Unlock() + r.timer.Reset(idleLongest) + log.Printf("claude: the turn the client gave up on was taken back; its run waits for the conversation's next turn") +} + +// rewind tells the run's Claude Code to take its conversation back to +// before the user message turn, stopping a reply under way, as its SDK's +// rewindConversation does. +func (r *subscriptionRun) rewind(turn string) error { + id := "rewind-" + randomToken()[:12] + ch := make(chan controlReply, 1) + r.mu.Lock() + if r.closed { + r.mu.Unlock() + return errors.New("the run ended") + } + if r.controls == nil { + r.controls = map[string]chan controlReply{} + } + r.controls[id] = ch + r.mu.Unlock() + defer func() { + r.mu.Lock() + delete(r.controls, id) + r.mu.Unlock() + }() + line, _ := json.Marshal(map[string]any{"type": "control_request", "request_id": id, + "request": map[string]any{"subtype": "rewind_conversation", "target_message_uuid": turn, "interrupt_if_running": true}}) + if _, err := r.stdin.Write(append(line, '\n')); err != nil { + return err + } + t := time.NewTimer(rewindLongest) + defer t.Stop() + select { + case reply, ok := <-ch: + switch { + case !ok: + return errors.New("the run ended") + case reply.Subtype != "success": + return fmt.Errorf("Claude Code refused it: %s", reply.Error) + case !reply.Response.Rewound: + return errors.New("Claude Code did not rewind") + } + return nil + case <-t.C: + return errors.New("Claude Code did not answer in " + rewindLongest.String()) + } +} + +// answered hands a control_response to the request waiting on it. +func (r *subscriptionRun) answered(raw json.RawMessage) { + var reply controlReply + if json.Unmarshal(raw, &reply) != nil { + return + } + r.mu.Lock() + ch := r.controls[reply.RequestID] + delete(r.controls, reply.RequestID) + r.mu.Unlock() + if ch != nil { + ch <- reply + } +} + // park leaves the run waiting on its reply's tool calls: parkLongest for // a run started anew for each turn, finalGrace when they end the caller's // turn, and among the parkedMost longest waiting otherwise. @@ -1029,6 +1195,8 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { ToolUseResult json.RawMessage `json:"tool_use_result"` // what the account has left, as Anthropic told Claude Code RateLimitInfo json.RawMessage `json:"rate_limit_info"` + // Claude Code's answer to a control request (rewind) + Response json.RawMessage `json:"response"` // an assistant message, one of its blocks at a time; raw, as // a user message's content may be a string Message json.RawMessage `json:"message"` @@ -1086,6 +1254,10 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { if unstreamed != "" && !(next && whole.ID == unstreamed) { settle() } + if envelope.Type == "control_response" { + r.answered(envelope.Response) + return + } if envelope.Type == "rate_limit_event" { // a run in Claude Code's own home is on whatever account // Claude Code is signed in to by now: switched off the @@ -1865,12 +2037,17 @@ func (r *subscriptionRun) finish() { } pending := r.pending r.pending = map[string]chan mcpToolResult{} + controls := r.controls + r.controls = nil ch := r.segment r.segment = nil r.mu.Unlock() for _, waiter := range pending { close(waiter) } + for _, waiter := range controls { + close(waiter) + } if ch != nil { close(ch) } @@ -2060,14 +2237,26 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from // is stopped at once, not left to answer no one and wait on tool calls // it never handed over began := time.Now() + // A turn resumed in a run kept for it is taken back instead, the run + // left waiting where it was before it (letGo, #780); the reply's end, + // which comes of that, leaves the run to it. + var letting atomic.Bool gone := context.AfterFunc(r.Context(), func() { + letting.Store(true) // said in the log, as the routing trace says it with a 499 (#751) log.Printf("%s run on %s stopped: the client went away %s into the reply", name, model, time.Since(began).Round(time.Millisecond)) - run.abort() + run.letGo() }) defer gone() - return relay(w, r, from, name, req, events, usage, run.abort, func(said, stop string, ok bool) { - gone() + abort := func() { + if !letting.Load() { + run.abort() + } + } + return relay(w, r, from, name, req, events, usage, abort, func(said, stop string, ok bool) { + if !gone() { + return // the client went first: letGo has the run + } run.ended(req, said, stop, ok) }) } diff --git a/internal/gateway/claude_subscription_rewind_test.go b/internal/gateway/claude_subscription_rewind_test.go new file mode 100644 index 000000000..8bd91e976 --- /dev/null +++ b/internal/gateway/claude_subscription_rewind_test.go @@ -0,0 +1,261 @@ +package gateway + +import ( + "context" + "encoding/json" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// rewindClaude stands in for Claude Code: it logs its arguments and each +// line it is told, answers each user message with its pid and turn, and +// leaves a message saying SLOW mid-reply, for the client to give up on. A +// rewind_conversation request is answered as mode says: "ok" rewinds, +// "refuse" fails, "silent" says nothing. It gives the log's path. +func rewindClaude(t *testing.T, mode string) string { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + dir := t.TempDir() + log := filepath.Join(dir, "stdin.log") + script := `#!/bin/sh +echo "args $*" >> ` + log + ` +n=0 +while read -r line; do + printf '%s\n' "$line" >> ` + log + ` + case "$line" in *rewind_conversation*) + id=$(printf '%s' "$line" | sed -n 's/.*"request_id":"\([^"]*\)".*/\1/p') + echo '{"type":"result","subtype":"error_during_execution","is_error":true,"result":""}' + case ` + mode + ` in + ok) echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'","response":{"rewound":true}}}';; + refuse) echo '{"type":"control_response","response":{"subtype":"error","request_id":"'$id'","error":"no such message"}}';; + esac + continue;; + esac + case "$line" in *control_request*) continue;; esac + n=$((n+1)) + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m'$n'","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pid '$$' turn '$n'"}}}' + case "$line" in *SLOW*) continue;; esac + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"result","subtype":"success","is_error":false,"result":""}' +done +` + os.WriteFile(filepath.Join(dir, "claude"), []byte(script), 0o755) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + return log +} + +type rewindHarness struct { + t *testing.T + s *Server + p provider.Provider + log string +} + +func newRewindHarness(t *testing.T, mode string) *rewindHarness { + log := rewindClaude(t, mode) + s := New() + t.Cleanup(s.subscription.abortAll) + return &rewindHarness{t: t, s: s, log: log, + p: provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}} +} + +func (h *rewindHarness) body(msgs string) string { + return `{"model":"claude-sonnet-5","max_tokens":100,"system":"be brief","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":` + msgs + `}` +} + +func (h *rewindHarness) ask(msgs string) string { + h.t.Helper() + body := h.body(msgs) + rec := httptest.NewRecorder() + var u Usage + if code, msg := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u); code != 200 { + h.t.Fatalf("%d %s", code, msg) + } + var res struct { + Content []struct{ Text 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].Text +} + +// giveUp asks msgs, whose last message says SLOW, and goes away once +// Claude Code is mid-reply, as a user stopping it does (a 499). +func (h *rewindHarness) giveUp(msgs string) { + h.t.Helper() + body := h.body(msgs) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + var u Usage + h.s.serveClaudeSubscription(httptest.NewRecorder(), httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)).WithContext(ctx), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u) + }() + deadline := time.Now().Add(10 * time.Second) + for !strings.Contains(h.read(), "SLOW") { + if time.Now().After(deadline) { + h.t.Fatalf("Claude Code was never told the turn:\n%s", h.read()) + } + time.Sleep(10 * time.Millisecond) + } + time.Sleep(100 * time.Millisecond) // its reply under way + cancel() + select { + case <-done: + case <-time.After(10 * time.Second): + h.t.Fatal("the request given up on never returned") + } +} + +func (h *rewindHarness) read() string { + b, _ := os.ReadFile(h.log) + return string(b) +} + +// lines are what Claude Code was told, its arguments left out. +func (h *rewindHarness) lines() []map[string]any { + var out []map[string]any + for _, l := range strings.Split(strings.TrimSpace(h.read()), "\n") { + var m map[string]any + if json.Unmarshal([]byte(l), &m) == nil { + out = append(out, m) + } + } + return out +} + +func rmsg(role, text string) string { + return `{"role":"` + role + `","content":` + strconv.Quote(text) + `}` +} + +func pidOf(t *testing.T, answer string) string { + t.Helper() + pid, _, ok := strings.Cut(strings.TrimPrefix(answer, "pid "), " ") + if !ok { + t.Fatalf("answer %q", answer) + } + return pid +} + +// A turn the client gave up on mid-reply is taken back in the same Claude +// Code (#780): it is told to rewind to that turn's message, and the +// client's resend — the same conversation, its last message reworded — goes +// on in it, told only the new message, so the prefix Claude Code sends +// Anthropic is the one it cached. Ended, a new Claude Code was told the +// whole conversation in one message, written to the cache again. +func TestClaudeTurnGivenUpOnIsRewound(t *testing.T) { + h := newRewindHarness(t, "ok") + first := h.ask(`[` + rmsg("user", "hi") + `]`) + pid := pidOf(t, first) + conv := rmsg("user", "hi") + `,` + rmsg("assistant", first) + `,` + rmsg("user", "and?") + second := h.ask(`[` + conv + `]`) + if second != "pid "+pid+" turn 2" { + t.Fatalf("second: %q", second) + } + conv += `,` + rmsg("assistant", second) + h.giveUp(`[` + conv + `,` + rmsg("user", "SLOW, go on") + `]`) + again := h.ask(`[` + conv + `,` + rmsg("user", "go on instead") + `]`) + if again != "pid "+pid+" turn 4" { + t.Fatalf("the resend went to another Claude Code: %q (first %q)\n%s", again, first, h.read()) + } + + var slow, rewind, resend map[string]any + for _, m := range h.lines() { + b, _ := json.Marshal(m) + switch s := string(b); { + case m["type"] == "user" && strings.Contains(s, "SLOW"): + slow = m + case m["type"] == "control_request" && strings.Contains(s, "rewind_conversation"): + rewind = m + case m["type"] == "user" && strings.Contains(s, "go on instead"): + resend = m + } + } + if slow == nil || rewind == nil || resend == nil { + t.Fatalf("Claude Code was told:\n%s", h.read()) + } + req, _ := rewind["request"].(map[string]any) + if slow["uuid"] == nil || req["target_message_uuid"] != slow["uuid"] || req["interrupt_if_running"] != true { + t.Fatalf("rewound to %v, the turn given up on was %v", req, slow["uuid"]) + } + if b, _ := json.Marshal(resend); strings.Contains(string(b), "and?") || strings.Contains(string(b), "SLOW") { + t.Fatalf("the resend was told more than its new message: %s", b) + } + // and it goes on as any kept run does + conv += `,` + rmsg("user", "go on instead") + `,` + rmsg("assistant", again) + if next := h.ask(`[` + conv + `,` + rmsg("user", "thanks") + `]`); next != "pid "+pid+" turn 5" { + t.Fatalf("next: %q", next) + } +} + +// A run whose Claude Code refuses the rewind, or doesn't answer it, is let +// go, as every run given up on was: the resend is told the conversation in +// a new one. +func TestClaudeTurnGivenUpOnNotRewound(t *testing.T) { + for _, mode := range []string{"refuse", "silent"} { + t.Run(mode, func(t *testing.T) { + if mode == "silent" { + old := rewindLongest + rewindLongest = 300 * time.Millisecond + t.Cleanup(func() { rewindLongest = old }) + } + h := newRewindHarness(t, mode) + first := h.ask(`[` + rmsg("user", "hi") + `]`) + pid := pidOf(t, first) + conv := rmsg("user", "hi") + `,` + rmsg("assistant", first) + `,` + rmsg("user", "and?") + second := h.ask(`[` + conv + `]`) + conv += `,` + rmsg("assistant", second) + h.giveUp(`[` + conv + `,` + rmsg("user", "SLOW, go on") + `]`) + again := h.ask(`[` + conv + `,` + rmsg("user", "go on instead") + `]`) + if pidOf(t, again) == pid || !strings.HasSuffix(again, " turn 1") { + t.Fatalf("the resend: %q, first %q", again, first) + } + if !strings.Contains(h.read(), "rewind_conversation") { + t.Fatalf("no rewind asked:\n%s", h.read()) + } + h.s.subscription.mu.Lock() + n := len(h.s.subscription.runs) + h.s.subscription.mu.Unlock() + if n != 1 { + t.Fatalf("%d runs, the one given up on kept", n) + } + }) + } +} + +// A run started for the turn given up on has no conversation before it to +// go back to: it is ended, as before, and nothing is rewound. +func TestClaudeFirstTurnGivenUpOnEnds(t *testing.T) { + h := newRewindHarness(t, "ok") + h.giveUp(`[` + rmsg("user", "SLOW hi") + `]`) + if strings.Contains(h.read(), "rewind_conversation") { + t.Fatalf("rewound a run started for the turn:\n%s", h.read()) + } + deadline := time.Now().Add(5 * time.Second) + for { + h.s.subscription.mu.Lock() + n := len(h.s.subscription.runs) + h.s.subscription.mu.Unlock() + if n == 0 { + break + } + if time.Now().After(deadline) { + t.Fatalf("%d runs left", n) + } + time.Sleep(10 * time.Millisecond) + } +}