diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index b15f0ab6d..2dee4dcdd 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -1473,11 +1473,35 @@ else changed: - at least one image or file was taken out. `follows` checks it when the hash misses (`toldRuns`, logged "tool results -go on in their run, the images before them taken out by the client"), and -`looseTurn.rewrote` when `cut` doesn't match; the looseTurn key no longer -has the message count, which `cut` compares itself. The run's Claude Code +go on in their run, the images before them taken out or sent again by the +client"), and `looseTurn.rewrote` when `cut` doesn't match (both through +`mediaMoved`, below); the looseTurn key no longer has the message count, +which `cut` compares itself. The run's Claude Code still holds the images; it is told only what came since. +A client may also keep its history's images and take them out of some +requests only, so a later request sends back images the one before had +taken out, in any turn (Yqihotaru on X: the history's image count +flipped between 2 and 4, and every turn was told to a new Claude Code, +"no run here has had this conversation"). `mediaMoved` compares the +conversation a role's run of messages at a time and takes each run as +`lostMedia` would, either way: images taken out, or put back where +nothing or a line of text stood. A tool result the run kept keeps the end +of its words (`heardPart.tail`, 2 KB), so a result sent back without the +line its client had added is told apart from one changed otherwise. +`follows` uses it for tool results, with the request going on after the +conversation the run heard. `looseTurn` keeps the whole conversation so +(`all`) and its settings without it (`settings`), and `rewrote` takes a +request with the same settings and the same number of runs whose images +alone moved, in any turn, not only the last. A run whose agent never had +an image the client sends back (it was started from a request without +it) goes on all the same: it answers from the line or the gap it was +told, as it did the turn before. `branch` and `whyNoRun` still compare +exact hashes. `TestClaudeImagesComingAndGoingInEarlierTurnsGoOnInTheRun` +sends a 90-message conversation five turns, the images of its earlier +turns taken out and sent back in turn, both with a line in their place +and with nothing. + 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. diff --git a/internal/gateway/claude_lost_media.go b/internal/gateway/claude_lost_media.go index 89bc9f925..fa8c685a8 100644 --- a/internal/gateway/claude_lost_media.go +++ b/internal/gateway/claude_lost_media.go @@ -17,6 +17,11 @@ import ( // anew, it would write all of it to the prompt cache again, at each step // after one that read an image. lostMedia tells this rewrite from any // other by its shape, not the client's words for it. +// +// A client may also send the images back in a later request, and take +// them out again in the next (Yqihotaru on X): its history keeps them, +// and only some of its requests take them out. mediaMoved tells either +// way apart from any other change, in any turn of the conversation. // wordPart is a part of a message as hashMessages reads it: its kind and // its words, and for a tool result how many images it carried beside them. @@ -67,15 +72,23 @@ func messageParts(msgs []Message) [][]wordPart { // heardPart is a wordPart as a run keeps it: the hash and length of its // words. words is set only on the conversation compared with what a run -// kept, which is a request's own. +// kept, which is a request's own. tail is a tool result's last words, as +// a run keeps them too: a request that sent the images back has a +// result's words without the text its client had added in their place, +// and the kept words are those with it (grown). type heardPart struct { kind Kind n int sum [sha256.Size]byte media int words string + tail string } +// heardTail is how much of a tool result's words a run keeps: room for +// the lines a client adds in place of a result's images. +const heardTail = 2048 + // heardRun is a role's messages in a row, as hashMessages runs them // together: how a reply is split into messages is left out. type heardRun struct { @@ -98,6 +111,8 @@ func heardRuns(msgs []Message, sealed bool) []heardRun { h := heardPart{kind: p.kind, n: len(p.words), sum: sha256.Sum256([]byte(p.words)), media: p.media} if !sealed { h.words = p.words + } else if p.kind == ToolResult { + h.tail = p.words[max(0, len(p.words)-heardTail):] } r.parts = append(r.parts, h) } @@ -134,6 +149,33 @@ func lostMedia(was, now []heardRun) bool { return lost > 0 } +// mediaMoved says now, a request's conversation (heardRuns unsealed), is +// kept, the one a run had (sealed), with images or files taken out of it +// or put back into it, as lostMedia tells them, a role's run of messages +// at a time, and nothing else changed: now may go on after it. A client +// that keeps its history's images and takes them out of some requests +// (Yqihotaru on X) sends back what the run had been told, then what it +// was told the turn before. +func mediaMoved(kept, now []heardRun) bool { + if len(now) < len(kept) { + return false + } + moved := 0 + for i, k := range kept { + if now[i].role != k.role { + return false + } + if n, ok := lostFromRun(k.parts, now[i].parts); ok { + moved += n + } else if n, ok := lostFromRun(now[i].parts, k.parts); ok { + moved += n // put back + } else { + return false + } + } + return moved > 0 +} + // lostFromRun is lostMedia for a role's run of messages: how many images // or files were taken out of was to make now, and whether that is all // that changed. @@ -158,12 +200,12 @@ func lostFromRun(was, now []heardPart) (int, bool) { for j < len(now) && now[j].kind == Text && (next == len(was) || !same(was[next], now[j])) { j++ } - case w.kind == ToolResult && j < len(now) && now[j].kind == ToolResult && w.media > now[j].media && grown(w, now[j].words): + case w.kind == ToolResult && j < len(now) && now[j].kind == ToolResult && w.media > now[j].media && grown(w, now[j]): // its images, text in their place lost += w.media - now[j].media grew = true j++ - case w.kind == ToolResult && j < len(now) && now[j].kind == ToolResult && w.media == now[j].media && mediaAfter(was, i) && grown(w, now[j].words): + case w.kind == ToolResult && j < len(now) && now[j].kind == ToolResult && w.media == now[j].media && mediaAfter(was, i) && grown(w, now[j]): // the images sent after the results, text in their place grew = true j++ @@ -192,10 +234,22 @@ func mediaAfter(was []heardPart, i int) bool { // same says now's part is w. func same(w, now heardPart) bool { - return w.kind == now.kind && w.n == len(now.words) && w.sum == sha256.Sum256([]byte(now.words)) + return w.kind == now.kind && w.n == now.n && w.sum == now.sum } -// grown says words are w's with text added to their end. -func grown(w heardPart, words string) bool { - return len(words) > w.n && w.sum == sha256.Sum256([]byte(words[:w.n])) +// grown says now's words are w's with text added to their end: read from +// now's words when it has them, else, for a part a run kept (sealed), +// from w's words and the end of now's (tail). +func grown(w, now heardPart) bool { + if now.n <= w.n { + return false + } + if now.words != "" { + return w.sum == sha256.Sum256([]byte(now.words[:w.n])) + } + d := now.n - w.n + if len(w.words) != w.n || d > len(now.tail) { + return false + } + return now.sum == sha256.Sum256([]byte(w.words+now.tail[len(now.tail)-d:])) } diff --git a/internal/gateway/claude_lost_media_test.go b/internal/gateway/claude_lost_media_test.go index c039154b5..9b923769e 100644 --- a/internal/gateway/claude_lost_media_test.go +++ b/internal/gateway/claude_lost_media_test.go @@ -303,3 +303,127 @@ func TestClaudeToolResultsAfterTheImagesTakenOutGoOn(t *testing.T) { }) } } + +// A long conversation whose earlier turns hold images, a user's and a +// tool's, which its client takes out of some requests and sends again in +// others (Yqihotaru on X): each turn whose reply called nothing goes on in +// the run that had the conversation, told the new turn alone, whichever +// way the images went since. It was told to a new Claude Code each turn, +// all of it written to the prompt cache again, the image count of the +// history flipping between requests. +func TestClaudeImagesComingAndGoingInEarlierTurnsGoOnInTheRun(t *testing.T) { + read := "Read image file [image/png]" + // with is the history as the client first had it, without as it sends + // it with the images taken out: gone is what stands in their place + history := func(images bool, gone string) []string { + ask, result, after := piUserParts(piText("这是什么"), piImage()), piResult("call_1", read), []string{piImages(1)} + if !images { + ask, result, after = piUserParts(piText("这是什么")), piResult("call_1", read), nil + if gone != "" { + ask = piUserParts(piText("这是什么"), piText(gone)) + result = piResult("call_1", read+"\n"+gone) + } else { + after = []string{piUserParts(piText("Attached image(s) from tool result:"))} + } + } + var h []string + for i := range 40 { + h = append(h, piUser(fmt.Sprintf("第 %d 个问题", i)), piSays(fmt.Sprintf("第 %d 个回答", i))) + } + h = append(h, ask, piSays("一只猫"), piUser("看看截图"), piCalls("call_1"), result) + h = append(h, after...) + return append(h, piSays("截图里是一只猫")) + } + for _, c := range []struct{ name, gone string }{ + {"taken out with nothing in their place", ""}, + {"taken out with a line in their place, as Hana does", hanaImageGone}, + } { + t.Run(c.name, func(t *testing.T) { + h := newReplyHarness(t, "好的") + var since []string // the turns after the history + for turn, images := range []bool{true, false, true, false, true} { + since = append(since, piUser(fmt.Sprintf("more %d", turn))) + h.sendChat(append(history(images, c.gone), since...)...) + since = append(since, piSays("好的")) + if n := len(h.runs()); n != 1 { + t.Fatalf("turn %d (images %t): %d runs, want the one that had the conversation", turn, images, n) + } + if turn == 0 { + continue + } + told := h.toldLast() + if !strings.Contains(told, fmt.Sprintf("more %d", turn)) || strings.Contains(told, "第 3 个问题") { + t.Fatalf("turn %d: the run was told more than the turn:\n%s", turn, told) + } + } + }) + } +} + +// Tool results whose conversation has images sent back that the request +// before had taken out, or taken out again, are the run's: it goes on +// (follows), told the results alone. Any other change is still not. +func TestClaudeToolResultsAfterTheImagesSentBackGoOn(t *testing.T) { + read := "Read image file [image/png]" + steps := func(images bool, gone string, more ...string) []string { + ask, result, after := piUserParts(piText("这是什么"), piImage()), piResult("call_1", read), []string{piImages(1)} + if !images { + ask, result, after = piUserParts(piText("这是什么"), piText(gone)), piResult("call_1", read+"\n"+gone), nil + } + msgs := append([]string{ask, piSays("一只猫"), piUser("看看截图"), piCalls("call_1"), result}, after...) + return append(msgs, more...) + } + next := []string{piCalls("call_2"), piResult("call_2", "B")} + for _, c := range []struct { + name string + told, now []string + want bool + }{ + {"sent back", steps(false, hanaImageGone), steps(true, "", next...), true}, + {"taken out again", steps(true, ""), steps(false, hanaImageGone, next...), true}, + {"sent back, the user's words changed", steps(false, hanaImageGone), append([]string{piUserParts(piText("这是谁"), piImage())}, steps(true, "", next...)[1:]...), false}, + {"sent back, the result's text changed", steps(false, hanaImageGone), append([]string{piUserParts(piText("这是什么"), piImage()), piSays("一只猫"), piUser("看看截图"), piCalls("call_1"), piResult("call_1", "Read image file [image/jpeg]"), piImages(1)}, next...), false}, + } { + t.Run(c.name, func(t *testing.T) { + r := &subscriptionRun{} + r.heard(piMessages(t, c.told...)) + if got := r.follows(piMessages(t, c.now...)); got != c.want { + t.Fatalf("follows: %t, want %t", got, c.want) + } + }) + } +} + +// Images taken out or sent back, and only that, in any turn and either +// way, are told from every other change (mediaMoved). +func TestMediaMovedIsOnlyImagesComingAndGoing(t *testing.T) { + read := "Read image file [image/png]" + gone := read + "\n" + hanaImageGone + ask := piUser("看看截图") + with := []string{piUserParts(piText("这是什么"), piImage()), piSays("一只猫"), ask, piCalls("call_1"), piResult("call_1", read), piImages(1), piSays("截图")} + without := []string{piUserParts(piText("这是什么"), piText(hanaImageGone)), piSays("一只猫"), ask, piCalls("call_1"), piResult("call_1", gone), piSays("截图")} + bare := []string{piUserParts(piText("这是什么")), piSays("一只猫"), ask, piCalls("call_1"), piResult("call_1", read), piUserParts(piText("Attached image(s) from tool result:")), piSays("截图")} + for _, c := range []struct { + name string + kept, now []string + want bool + }{ + {"taken out, a line in their place", with, without, true}, + {"sent back where a line was", without, with, true}, + {"sent back where nothing was", bare, with, true}, + {"taken out, nothing in their place", with, bare, true}, + {"sent back, the conversation going on", without, append(with[:len(with):len(with)], piUser("more")), true}, + {"nothing changed", with, with, false}, + {"sent back, the reply changed", without, append(with[:len(with)-1:len(with)-1], piSays("一只狗")), false}, + {"sent back, the user's words changed", without, append([]string{piUserParts(piText("这是谁"), piImage())}, with[1:]...), false}, + {"sent back, a result's text changed", without, []string{with[0], with[1], ask, piCalls("call_1"), piResult("call_1", "Read image file [image/jpeg]"), piImages(1), piSays("截图")}, false}, + {"a line where no image was", bare[:2], append([]string{piUserParts(piText("这是什么"), piText(hanaImageGone))}, bare[1:2]...), false}, + } { + t.Run(c.name, func(t *testing.T) { + kept, now := heardRuns(piMessages(t, c.kept...), true), heardRuns(piMessages(t, c.now...), false) + if got := mediaMoved(kept, now); got != c.want { + t.Fatalf("mediaMoved: %t, want %t", got, c.want) + } + }) + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index cb012f705..d508e0430 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -2136,9 +2136,13 @@ func nextTurn(req *Request, owner string) (string, []Message) { type looseTurn struct { key string turn []turnWords - // runs is the turn as lostMedia compares it (#1382): sealed as a run - // keeps it, with its words as a request has it - runs []heardRun + // settings is key without the conversation, and all the conversation + // as mediaMoved compares it (#1382): sealed as a run keeps it, with its + // words as a request has it. A client may take the images out of any + // turn, or send them back, which changes the conversation before the + // last turn as key has it. + settings string + all []heardRun } // turnWords is a message of a turn as hashMessages reads it: its role, @@ -2164,10 +2168,12 @@ func newLooseTurn(owner string, req *Request, msgs []Message, sealed bool) *loos } } h := sha256.New() - fmt.Fprintf(h, "%s\x00%s\x00%t\x00%t\x00%s\x00%s\x00%t\x00%s\x00%d", owner, req.Model, req.Effort != "", req.ThinkOff, req.ToolChoice, withoutBillingHeader(req.System), req.WebSearch, req.Format.schema(), start) + fmt.Fprintf(h, "%s\x00%s\x00%t\x00%t\x00%s\x00%s\x00%t\x00%s", owner, req.Model, req.Effort != "", req.ThinkOff, req.ToolChoice, withoutBillingHeader(req.System), req.WebSearch, req.Format.schema()) cacheIdentity(h, req) + settings := hex.EncodeToString(h.Sum(nil)) + fmt.Fprintf(h, "\x00%d", start) hashMessages(h, msgs[:start], nil) - l := &looseTurn{key: hex.EncodeToString(h.Sum(nil)), runs: heardRuns(msgs[start:], sealed)} + l := &looseTurn{key: hex.EncodeToString(h.Sum(nil)), settings: settings, all: heardRuns(msgs, sealed)} words := messageWords(msgs) for i := start; i < len(msgs); i++ { tools := false @@ -2182,13 +2188,14 @@ func newLooseTurn(owner string, req *Request, msgs []Message, sealed bool) *loos // rewrote says now's turn is the one l kept as a client sends it back: // the same messages, calls and results, a user's message no more than cut // (a part of it taken out, but not all), and the reply's start (its end -// taken out, but not all of it); or the same turn with images taken out -// of it, and only those (lostMedia, #1382). +// taken out, but not all of it); or the same conversation, with the same +// settings, whose images were taken out of any turn or put back, and only +// those (mediaMoved, #1382). func (l *looseTurn) rewrote(now *looseTurn) bool { - if l.cut(now.turn) { + if l.key == now.key && l.cut(now.turn) { return true } - return len(now.runs) == len(l.runs) && lostMedia(l.runs, now.runs) + return l.settings == now.settings && len(now.all) == len(l.all) && mediaMoved(l.all, now.all) } // cut is rewrote for a client that cut a user's message or the reply. @@ -2246,12 +2253,12 @@ func (b *subscriptionBridge) rewritten(req *Request, owner string) (*subscriptio var saved *savedSession found := 0 for _, r := range b.idle { - if r.owned() == owner && r.loose != nil && r.loose.key == l.key && r.loose.rewrote(l) { + if r.owned() == owner && r.loose != nil && r.loose.rewrote(l) { run, found = r, found+1 } } for _, s := range b.shelf { - if s.owner == owner && s.loose != nil && s.loose.key == l.key && s.loose.rewrote(l) { + if s.owner == owner && s.loose != nil && s.loose.rewrote(l) { saved, found = s, found+1 } } @@ -3673,8 +3680,9 @@ func (r *subscriptionRun) heard(msgs []Message) { // 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 — // sends another, while the run's agent still holds the one it was told. -// One whose client only took the images out of it (lostMedia, #1382) goes -// on: the run's agent holds them, and nothing else changed. +// One whose client only took the images out of it (lostMedia, #1382), or +// put back those it took out before (mediaMoved), goes on: the run's +// agent holds them, and nothing else changed. func (r *subscriptionRun) follows(msgs []Message) bool { r.mu.Lock() told, runs := r.told, r.toldRuns @@ -3687,8 +3695,8 @@ func (r *subscriptionRun) follows(msgs []Message) bool { hashMessages(h, msgs, func(int) { found = found || hex.EncodeToString(h.Sum(nil)) == told }) - if !found && runs != nil && lostMedia(runs, heardRuns(msgs, false)) { - log.Printf("claude: tool results go on in their run, the images before them taken out by the client") + if !found && runs != nil && mediaMoved(runs, heardRuns(msgs, false)) { + log.Printf("claude: tool results go on in their run, the images before them taken out or sent again by the client") return true } return found