claude: a turn stopped mid-reply is taken back in the same Claude Code, so the resend reads the cache it wrote (#780, Kenoia) — a 499 (the user pressed Esc and reworded the message) ended the Claude Code run, and the resend found no run waiting, started a new one and told it the whole conversation in one message: a prefix the cache had never seen, written again whole (~119k tokens in the report). A turn resumed in a run kept for it now sends its user line with a uuid; when the client goes away, magpie tells that Claude Code a rewind_conversation control request to that uuid with interrupt_if_running (as its SDK's rewindConversation does), which stops the reply and leaves its conversation as it was before the turn, and the run waits again where it waited before, so the resend goes on in it with only its new message. A run started for the turn, one with tool calls in the client's hands, a continuation after tool results (the turn's id is dropped when its reply ends), or a Claude Code that refuses or doesn't answer in 10s is ended as before; a reply that ended as the client went away is left to the rewind. With the owner's real Claude account in a sandbox (Claude Code 2.1.289, haiku 4.5): two turns, a third streamed and dropped after 3 deltas, then the resend reworded: the same Claude Code pids throughout, the log said "the turn the client gave up on was taken back", and the resend read 6667 tokens from the cache (the whole prefix before) and wrote 91. TestClaudeTurnGivenUpOnIsRewound, TestClaudeTurnGivenUpOnNotRewound (refuse, silent) and TestClaudeFirstTurnGivenUpOnEnds; the Claude tests pass under -race. go vet, builds (darwin, GOOS=linux, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass.
This commit is contained in:
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user