Claude chat: a history read mid-reply carries the streaming block's beginning

Claude Code writes a content block to its session file only once the block
is complete. A client that read history while a block streamed (opening the
chat mid-reply, a reconnect, a resync) got only the deltas after its read,
and nothing re-sent the block's beginning, so the reply showed with its first
part cut off. Deltas are now numbered (seq) and their text retained for the
newest assistant messages; the newest history page adds every retained part
the transcript lacks and reports the last included seq (live_seq) and the
overlaid parts (live_parts).

History now numbers empty text/thinking blocks as the live stream does, so a
thinking block after an empty display-omitted one keeps one part id live and
in history. Text a content_block_start carries is published, not dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-30 15:41:57 +00:00
parent 1772100af2
commit ea25cf504f
6 changed files with 408 additions and 29 deletions
+7
View File
@@ -390,6 +390,13 @@ type session struct {
streamClaimed map[int]bool
toolMessages map[string]string
// liveSeq numbers the text and reasoning deltas this session publishes;
// live holds the text they carried for the newest assistant messages, so
// a history read can include a block the transcript does not hold yet
// (see live.go).
liveSeq int64
live []*liveMessage
// injectedSeen holds the identities of agent reports and notices already
// published live, so a delivery the stream repeats is shown once.
injectedSeen map[string]bool
+144
View File
@@ -0,0 +1,144 @@
package claude
import (
"strings"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Claude Code writes an assistant content block to its session file only once
// the block is complete. A client that reads history while a block streams
// (it opened the chat mid-reply, or its socket reconnected) would otherwise
// get only the deltas after its read, and nothing ever sends the block's
// beginning again: the completed assistant event repeats nothing already
// streamed. So every published delta is numbered and its text retained for
// the newest assistant messages, and the newest history page carries the
// retained text of every part the transcript lacks, with the number of the
// last delta it includes (protocol.ChatHistoryPage.LiveSeq).
// liveMessagesRetained bounds the retained messages: the one streaming now and
// the one before it, whose last block may not be written yet when the next
// message starts.
const liveMessagesRetained = 2
type liveMessage struct {
id string
parts []*livePart
}
type livePart struct {
id string
kind string
text strings.Builder
}
// liveOverlay is a copy of the retained live text taken at one Seq.
type liveOverlay struct {
seq int64
running bool
messages []liveOverlayMessage
}
type liveOverlayMessage struct {
id string
parts []protocol.ChatPart
}
// recordLiveLocked numbers a text or reasoning delta frame about to be
// published and retains its text. It runs for silent replays too, so the
// retained text stays whole after a reattached host goes live mid-block.
func (s *session) recordLiveLocked(frame *protocol.ChatEventFrame) {
if frame.Part == nil || frame.Part.ID == "" || frame.Delta == "" || frame.MessageID == "" {
return
}
if s.liveSeq == 0 {
// Start from the clock so numbers keep increasing across a server
// restart. Microseconds stay exact as a JavaScript number.
s.liveSeq = time.Now().UnixMicro()
}
s.liveSeq++
frame.Seq = s.liveSeq
var message *liveMessage
for _, held := range s.live {
if held.id == frame.MessageID {
message = held
break
}
}
if message == nil {
message = &liveMessage{id: frame.MessageID}
s.live = append(s.live, message)
if len(s.live) > liveMessagesRetained {
s.live = append([]*liveMessage(nil), s.live[len(s.live)-liveMessagesRetained:]...)
}
}
var part *livePart
for _, held := range message.parts {
if held.id == frame.Part.ID {
part = held
break
}
}
if part == nil {
part = &livePart{id: frame.Part.ID, kind: frame.Kind}
message.parts = append(message.parts, part)
}
part.text.WriteString(frame.Delta)
}
// liveOverlaySnapshot copies the retained live text. A history read takes it
// before reading the transcript, so a block that completes in between is
// found whole in the transcript rather than lost from both.
func (s *session) liveOverlaySnapshot() liveOverlay {
s.mu.Lock()
defer s.mu.Unlock()
overlay := liveOverlay{seq: s.liveSeq, running: s.running}
for _, message := range s.live {
copied := liveOverlayMessage{id: message.id}
for _, part := range message.parts {
copied.parts = append(copied.parts, protocol.ChatPart{ID: part.id, Type: part.kind, Text: part.text.String()})
}
overlay.messages = append(overlay.messages, copied)
}
return overlay
}
// apply adds to the newest page every retained part its transcript lacks,
// while a turn runs. Once the turn ended the transcript is complete, and an
// interrupted block the CLI never wrote is not invented into history.
func (overlay liveOverlay) apply(page *protocol.ChatHistoryPage, sessionID string) {
page.LiveSeq = overlay.seq
if !overlay.running {
return
}
for _, live := range overlay.messages {
index := -1
for i := range page.Messages {
if page.Messages[i].ID == live.id {
index = i
break
}
}
for _, part := range live.parts {
if index >= 0 && hasPart(page.Messages[index].Parts, part.ID) {
continue
}
if index < 0 {
page.Messages = append(page.Messages, protocol.ChatMessage{ID: live.id, SessionID: sessionID, Role: protocol.ChatRoleAssistant, CreatedAt: time.Now().UnixMilli(), Parts: []protocol.ChatPart{}})
index = len(page.Messages) - 1
}
page.Messages[index].Parts = append(page.Messages[index].Parts, part)
page.LiveParts = append(page.LiveParts, part.ID)
}
}
}
func hasPart(parts []protocol.ChatPart, id string) bool {
for _, part := range parts {
if part.ID == id {
return true
}
}
return false
}
+169
View File
@@ -0,0 +1,169 @@
package claude
import (
"context"
"testing"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func liveStream(event map[string]any) map[string]any {
return map[string]any{"type": "stream_event", "event": event}
}
func liveTextDelta(index int, text string) map[string]any {
return liveStream(map[string]any{"type": "content_block_delta", "index": index, "delta": map[string]any{"type": "text_delta", "text": text}})
}
// A client that reads history while a reply's text block streams (it opened
// the chat mid-reply, or reconnected) used to get only the deltas after its
// read: Claude Code writes a block to its file once it is complete, and the
// completed assistant event repeats nothing already streamed, so the reply's
// beginning was never shown. The newest page now carries the streaming block's
// text so far under its live part id, with the number of the last delta.
func TestHistoryReadMidBlockCarriesTheStreamedBeginning(t *testing.T) {
const id = "ses_live_overlay"
const message = "msg_live"
assistant := func(uuid string, block map[string]any) map[string]any {
return map[string]any{"type": "assistant", "uuid": uuid, "timestamp": "2026-11-30T10:00:01Z", "message": map[string]any{
"id": message, "role": "assistant", "content": []any{block}}}
}
// The file holds what the CLI wrote so far: the prompt and the message's
// two completed thinking blocks (an empty, display-omitted one first).
writeTranscript(t, id, []map[string]any{
{"type": "user", "uuid": "u-1", "timestamp": "2026-11-30T10:00:00Z", "message": map[string]any{"role": "user", "content": []any{map[string]any{"type": "text", "text": "Why?"}}}},
assistant("a-1", map[string]any{"type": "thinking", "thinking": "", "signature": "sig"}),
assistant("a-2", map[string]any{"type": "thinking", "thinking": "Considering the cause.", "signature": "sig"}),
})
chat := New(context.Background())
t.Cleanup(chat.Close)
s := chat.sessionFor(id, t.TempDir())
subs := attachTestSubs(s, 1)
s.mu.Lock()
s.running = true
s.mu.Unlock()
feedLines(t, s, []map[string]any{
liveStream(map[string]any{"type": "message_start", "message": map[string]any{"id": message}}),
liveStream(map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "thinking", "thinking": ""}}),
liveStream(map[string]any{"type": "content_block_stop", "index": 0}),
liveStream(map[string]any{"type": "content_block_start", "index": 1, "content_block": map[string]any{"type": "thinking", "thinking": ""}}),
liveStream(map[string]any{"type": "content_block_delta", "index": 1, "delta": map[string]any{"type": "thinking_delta", "thinking": "Considering the cause."}}),
liveStream(map[string]any{"type": "content_block_stop", "index": 1}),
liveStream(map[string]any{"type": "content_block_start", "index": 2, "content_block": map[string]any{"type": "text", "text": "The "}}),
liveTextDelta(2, "first part. "),
})
page, err := s.transcriptMessages(200, "")
if err != nil {
t.Fatal(err)
}
feedLines(t, s, []map[string]any{liveTextDelta(2, "And the rest.")})
detachTestSubs(s, subs)
textID := protocol.ChatDeltaPartID(message, protocol.ChatPartText, 0)
reasoningID := protocol.ChatDeltaPartID(message, protocol.ChatPartReasoning, 1)
var frames []protocol.ChatEventFrame
for frame := range subs[0] {
frames = append(frames, frame)
}
// reasoning, the block's starting text, its first delta, and the late delta.
if len(frames) != 4 {
t.Fatalf("frames = %+v", frames)
}
if frames[0].Part.ID != reasoningID {
t.Fatalf("live reasoning id %q, want %q (history's id for the same block)", frames[0].Part.ID, reasoningID)
}
if frames[1].Delta != "The " || frames[1].Part.ID != textID {
t.Fatalf("a block's starting text was not published: %+v", frames[1])
}
for i := 1; i < len(frames); i++ {
if frames[i].Seq <= frames[i-1].Seq {
t.Fatalf("deltas are not numbered in order: %+v", frames)
}
}
last := page.Messages[len(page.Messages)-1]
if last.ID != message {
t.Fatalf("newest message %q", last.ID)
}
parts := map[string]string{}
for _, part := range last.Parts {
parts[part.ID] = part.Text
}
if parts[reasoningID] != "Considering the cause." {
t.Fatalf("history reasoning ids differ from live ones: %+v", last.Parts)
}
if parts[textID] != "The first part. " {
t.Fatalf("streaming block text = %q, want its beginning", parts[textID])
}
if len(page.LiveParts) != 1 || page.LiveParts[0] != textID {
t.Fatalf("live parts = %v", page.LiveParts)
}
if page.LiveSeq != frames[2].Seq {
t.Fatalf("live seq %d, want the last included delta %d", page.LiveSeq, frames[2].Seq)
}
// An older page is pure history, and so is any page once the turn ended.
s.mu.Lock()
s.running = false
s.mu.Unlock()
ended, err := s.transcriptMessages(200, "")
if err != nil {
t.Fatal(err)
}
if len(ended.LiveParts) != 0 {
t.Fatalf("an idle session overlaid live text: %v", ended.LiveParts)
}
}
// A brand-new session has no file yet while its first reply streams; the
// newest page still carries the reply so far.
func TestHistoryBeforeTheFileExistsCarriesTheStreamingReply(t *testing.T) {
writeTranscript(t, "ses_other", nil)
chat := New(context.Background())
t.Cleanup(chat.Close)
s := chat.sessionFor("ses_no_file", t.TempDir())
s.mu.Lock()
s.running = true
s.mu.Unlock()
feedLines(t, s, []map[string]any{
liveStream(map[string]any{"type": "message_start", "message": map[string]any{"id": "msg_first"}}),
liveStream(map[string]any{"type": "content_block_start", "index": 0, "content_block": map[string]any{"type": "text"}}),
liveTextDelta(0, "Hello"),
})
page, err := s.transcriptMessages(200, "")
if err != nil {
t.Fatal(err)
}
if len(page.Messages) != 1 || page.Messages[0].Parts[0].Text != "Hello" || page.Messages[0].Role != protocol.ChatRoleAssistant {
t.Fatalf("page = %+v", page)
}
}
// History numbers an unstreamed empty block like the stream does, so the text
// block after it keeps one id live and in history.
func TestUnstreamedEmptyBlocksKeepHistoryOrdinals(t *testing.T) {
chat := testChat(t)
s := chat.session(newCreatedChat(t, chat).ID)
subs := attachTestSubs(s, 1)
assistant := func(block map[string]any) map[string]any {
return map[string]any{"type": "assistant", "message": map[string]any{"id": "msg_plain", "role": "assistant", "content": []any{block}}}
}
feedLines(t, s, []map[string]any{
assistant(map[string]any{"type": "thinking", "thinking": "", "signature": "sig"}),
assistant(map[string]any{"type": "thinking", "thinking": "Hmm.", "signature": "sig"}),
assistant(map[string]any{"type": "text", "text": "Answer."}),
})
detachTestSubs(s, subs)
var ids []string
for frame := range subs[0] {
if frame.Part != nil {
ids = append(ids, frame.Part.ID)
}
}
want := []string{protocol.ChatDeltaPartID("msg_plain", protocol.ChatPartReasoning, 1), protocol.ChatDeltaPartID("msg_plain", protocol.ChatPartText, 0)}
if len(ids) != 2 || ids[0] != want[0] || ids[1] != want[1] {
t.Fatalf("ids = %v, want %v", ids, want)
}
}
+31 -9
View File
@@ -162,6 +162,18 @@ func transcriptTime(text string) (int64, bool) {
// merges the JSONL's one-entry-per-content-block shape by message id, attaches
// tool results to the call that produced them, and never invents a turn.
func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHistoryPage, error) {
newest := strings.TrimSpace(cursor) == "" || cursor == "0"
// Taken before the file is read: a block completing in between is then
// whole in the file, never missing from both (see live.go).
overlay := s.liveOverlaySnapshot()
page, err := s.transcriptPage(limit, cursor)
if err == nil && newest {
overlay.apply(&page, s.id)
}
return page, err
}
func (s *session) transcriptPage(limit int, cursor string) (protocol.ChatHistoryPage, error) {
path := findTranscriptFile(s.id)
if path == "" {
return protocol.ChatHistoryPage{Messages: []protocol.ChatMessage{}}, nil
@@ -206,6 +218,7 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
messages = append(messages, earlierHistoryNotice(s.id, skipped, created))
}
messageIndex := map[string]int{}
ordinals := blockOrdinals{}
toolIndex := map[string][2]int{} // tool id -> message/part index
addUser := func(entry transcriptEntry, text string, files []protocol.ChatPart) {
id := takePromptID(text)
@@ -259,17 +272,22 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
for _, block := range blocks {
switch block.Type {
case "text":
// Every block of a kind takes an ordinal, empty or not, as
// the live stream numbers them when they start: a part keeps
// one id live and in history.
ordinal := ordinals.next(messageID, protocol.ChatPartText)
if strings.TrimSpace(block.Text) == "" {
continue
}
ordinal := textOrdinal(messages[index].Parts, protocol.ChatPartText)
part := protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartText, ordinal), Text: block.Text}
messages[index].Parts = append(messages[index].Parts, part)
case "thinking":
// An empty (display-omitted) thinking block often precedes
// the one with text; it is counted, not shown.
ordinal := ordinals.next(messageID, protocol.ChatPartReasoning)
if strings.TrimSpace(block.Thinking) == "" {
continue
}
ordinal := textOrdinal(messages[index].Parts, protocol.ChatPartReasoning)
part := protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartReasoning, ordinal), Text: block.Thinking}
messages[index].Parts = append(messages[index].Parts, part)
case "tool_use":
@@ -422,14 +440,18 @@ func (s *session) transcriptMessages(limit int, cursor string) (protocol.ChatHis
return page, nil
}
func textOrdinal(parts []protocol.ChatPart, kind string) int {
count := 0
for _, part := range parts {
if part.Type == kind {
count++
}
// blockOrdinals counts each message's text and thinking blocks by kind.
type blockOrdinals map[string]map[string]int
func (o blockOrdinals) next(messageID, kind string) int {
counts := o[messageID]
if counts == nil {
counts = map[string]int{}
o[messageID] = counts
}
return count
ordinal := counts[kind]
counts[kind] = ordinal + 1
return ordinal
}
func applyTranscriptToolResult(messages *[]protocol.ChatMessage, toolIndex map[string][2]int, block contentBlock) {
+44 -20
View File
@@ -244,7 +244,15 @@ func (s *session) handleStreamEvent(envelope lineEnvelope) {
}
ordinal := s.streamOrdinals[kind]
s.streamOrdinals[kind] = ordinal + 1
s.streamBlocks[event.Index] = blockState{kind: kind, ordinal: ordinal}
block := blockState{kind: kind, ordinal: ordinal}
s.streamBlocks[event.Index] = block
// The API starts a block empty, but text a block starts with is the
// beginning of the answer, never something to drop.
initial := event.ContentBlock.Text
if kind == protocol.ChatPartReasoning {
initial = event.ContentBlock.Thinking
}
s.streamDeltaLocked(event.Index, block, initial)
case "content_block_delta":
if event.Delta == nil {
return
@@ -275,23 +283,7 @@ func (s *session) handleStreamEvent(envelope lineEnvelope) {
default:
return
}
if delta == "" {
return
}
s.streamText[event.Index] += delta
messageID := s.streamID
if messageID == "" {
return
}
partID := protocol.ChatDeltaPartID(messageID, block.kind, block.ordinal)
s.broadcastLocked(protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: s.turnID,
MessageID: messageID,
Kind: block.kind,
Delta: delta,
Part: &protocol.ChatPart{ID: partID, Type: block.kind},
})
s.streamDeltaLocked(event.Index, block, delta)
case "message_stop":
// Keep the assembled blocks: the CLI sends the completed assistant
// message after message_stop, and that message must not repeat text
@@ -299,6 +291,29 @@ func (s *session) handleStreamEvent(envelope lineEnvelope) {
}
}
// streamDeltaLocked assembles one streamed piece of a block and publishes it,
// numbered and retained for history reads (see live.go).
func (s *session) streamDeltaLocked(index int, block blockState, delta string) {
if delta == "" {
return
}
s.streamText[index] += delta
messageID := s.streamID
if messageID == "" {
return
}
frame := protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: s.turnID,
MessageID: messageID,
Kind: block.kind,
Delta: delta,
Part: &protocol.ChatPart{ID: protocol.ChatDeltaPartID(messageID, block.kind, block.ordinal), Type: block.kind},
}
s.recordLiveLocked(&frame)
s.broadcastLocked(frame)
}
func streamKind(blockType string) string {
switch blockType {
case "text":
@@ -415,6 +430,7 @@ func (s *session) handleAssistant(envelope lineEnvelope) {
}
// Align the completed message with what was streamed, then emit only the
// remainder: the CLI sends deltas first and the full block afterwards.
streamedMessage := len(s.streamBlocks) > 0
var frames []protocol.ChatEventFrame
for index, block := range blocks {
switch block.Type {
@@ -426,6 +442,12 @@ func (s *session) handleAssistant(envelope lineEnvelope) {
full = block.Thinking
}
if strings.TrimSpace(full) == "" {
// A streamed block took its ordinal when it started. An empty
// block of a message that was not streamed takes one too, as
// history counts it, so the next block's id matches history's.
if !streamedMessage {
s.streamOrdinals[kind]++
}
continue
}
state, streamed, matched := s.claimStreamedLocked(kind, full, index)
@@ -444,14 +466,16 @@ func (s *session) handleAssistant(envelope lineEnvelope) {
if delta == "" {
continue
}
frames = append(frames, protocol.ChatEventFrame{
frame := protocol.ChatEventFrame{
SessionID: s.id,
NativeTurnID: s.turnID,
MessageID: messageID,
Kind: kind,
Delta: delta,
Part: &protocol.ChatPart{ID: protocol.ChatDeltaPartID(messageID, kind, state.ordinal), Type: kind},
})
}
s.recordLiveLocked(&frame)
frames = append(frames, frame)
case "tool_use":
if block.ID == "" {
continue
+13
View File
@@ -528,6 +528,16 @@ type ChatHistoryPage struct {
Messages []ChatMessage `json:"messages"`
NextCursor string `json:"next_cursor,omitempty"`
HasMore bool `json:"has_more,omitempty"`
// LiveSeq is the Seq of the last streamed text or reasoning delta the
// newest page includes. A harness whose stored transcript lacks the content
// block still streaming (Claude Code writes a block only once it is
// complete) adds that block's text so far to the newest page, under its
// live part id, and names it in LiveParts. A client folds a delta frame
// with a greater Seq onto a live part or onto a part the page lacks; every
// delta with Seq <= LiveSeq is already in the page. Zero when the harness
// does not number its deltas.
LiveSeq int64 `json:"live_seq,omitempty"`
LiveParts []string `json:"live_parts,omitempty"`
}
// ChatPromptRequest is the chat_prompt request body: the text to send, with an
@@ -745,6 +755,9 @@ type ChatEventFrame struct {
// MessageKind is the ChatMessage.Kind of the message a text frame starts,
// so a live agent report or notice is never drawn as an answer or a prompt.
MessageKind string `json:"message_kind,omitempty"`
// Seq numbers a text or reasoning delta within its session, increasing;
// see ChatHistoryPage.LiveSeq. Zero when the harness does not number them.
Seq int64 `json:"seq,omitempty"`
}
// ChatCompaction is session activity, never a transcript message or tool.