Server: serve a Claude chat's history page from a per-file line index

Reading a history page parsed the whole session file (tens of MB) on every
chat_messages. A per-file index now records which lines build each shown
message; a page re-reads and replays only its own messages' lines, and the
index follows appends by reading only the new bytes. Results match the
whole-file read (compared page by page on synthetic transcripts); shapes the
index cannot replay exactly fall back to the whole-file read.

chat_subscribe may ask (history: true) for the newest page in its reply,
read once the subscription is attached, saving the client a round trip.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 14:58:57 +00:00
parent 17baa9e24c
commit 686690f7b4
8 changed files with 1303 additions and 251 deletions
+370 -245
View File
@@ -35,8 +35,8 @@ type transcriptEntry struct {
Model string `json:"model"`
Content json.RawMessage `json:"content"`
} `json:"message"`
ToolUseResult json.RawMessage `json:"toolUseResult"`
Compact json.RawMessage `json:"compactMetadata"`
// toolUseResult (a tool's structured output, often a whole file) is not
// read: decoding skips it instead of copying it.
// Attachment is set on "attachment" entries; a queued_command with
// commandMode "prompt" is a user message the CLI read mid-turn. Prompt is
// either a string or an array of content blocks.
@@ -124,29 +124,46 @@ func transcriptSession(id string) (protocol.ChatSession, bool) {
return protocol.ChatSession{}, false
}
session := protocol.ChatSession{ID: id, Backend: Backend, ModelProvider: Backend, Tag: protocol.ChatSessionTagOperator}
entries, err := readTranscript(path)
if err != nil {
return session, true
}
for _, entry := range entries {
if entry.Cwd != "" && session.Directory == "" {
session.Directory = entry.Cwd
meta, ok := indexedTranscriptMeta(path)
if !ok {
entries, err := readTranscript(path)
if err != nil {
return session, true
}
if stamp, ok := transcriptTime(entry.Timestamp); ok {
if session.CreatedAt == 0 || stamp < session.CreatedAt {
session.CreatedAt = stamp
}
if stamp > session.UpdatedAt {
session.UpdatedAt = stamp
}
}
if entry.Type == "assistant" && entry.Message.Model != "" && !entry.IsSidechain {
session.Model = entry.Message.Model
meta = transcriptMeta{}
for _, entry := range entries {
meta.note(entry)
}
}
session.Directory, session.CreatedAt, session.UpdatedAt, session.Model = meta.directory, meta.created, meta.updated, meta.model
return session, true
}
// transcriptMeta is what a session file says about its session: the first
// working directory, the first and last times, and the main thread's model.
type transcriptMeta struct {
directory string
created, updated int64
model string
}
func (m *transcriptMeta) note(entry transcriptEntry) {
if entry.Cwd != "" && m.directory == "" {
m.directory = entry.Cwd
}
if stamp, ok := transcriptTime(entry.Timestamp); ok {
if m.created == 0 || stamp < m.created {
m.created = stamp
}
if stamp > m.updated {
m.updated = stamp
}
}
if entry.Type == "assistant" && entry.Message.Model != "" && !entry.IsSidechain {
m.model = entry.Message.Model
}
}
func transcriptTime(text string) (int64, bool) {
if strings.TrimSpace(text) == "" {
return 0, false
@@ -178,35 +195,25 @@ func (s *session) transcriptPage(limit int, cursor string) (protocol.ChatHistory
if path == "" {
return protocol.ChatHistoryPage{Messages: []protocol.ChatMessage{}}, nil
}
s.mu.Lock()
prompts := append([]promptRecord(nil), s.prompts...)
s.mu.Unlock()
// The file's message index serves a page by re-reading only that page's
// lines; the whole file is read only when the index cannot serve it.
if page, ok, err := indexedTranscriptPage(path, s.id, prompts, limit, cursor); ok || err != nil {
return page, err
}
return fullTranscriptPage(path, s.id, prompts, limit, cursor)
}
// fullTranscriptPage builds every message of the session file and pages them.
// It is the reference the indexed read matches, and its fallback.
func fullTranscriptPage(path, sessionID string, prompts []promptRecord, limit int, cursor string) (protocol.ChatHistoryPage, error) {
entries, skipped, err := readTranscriptTail(path)
if err != nil {
return protocol.ChatHistoryPage{}, err
}
s.mu.Lock()
prompts := append([]promptRecord(nil), s.prompts...)
s.mu.Unlock()
promptIDs := map[string][]string{}
for _, prompt := range prompts {
if prompt.id == "" || prompt.text == "" {
continue
}
promptIDs[prompt.text] = append(promptIDs[prompt.text], prompt.id)
}
usedPrompts := map[string]int{}
takePromptID := func(text string) string {
text = strings.TrimSpace(text)
ids := promptIDs[text]
if len(ids) == 0 {
return ""
}
index := usedPrompts[text]
if index >= len(ids) {
return ""
}
usedPrompts[text] = index + 1
return ids[index]
}
messages := []protocol.ChatMessage{}
builder := newTranscriptBuilder(sessionID, promptMatcher(prompts))
if skipped > 0 {
created := int64(0)
for _, entry := range entries {
@@ -215,229 +222,347 @@ func (s *session) transcriptPage(limit int, cursor string) (protocol.ChatHistory
break
}
}
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)
if id == "" {
id = entry.UUID
}
if id == "" {
return
}
created, _ := transcriptTime(entry.Timestamp)
parts := []protocol.ChatPart{}
if text != "" {
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#text", Text: text})
}
parts = append(parts, files...)
messages = append(messages, protocol.ChatMessage{ID: id, SessionID: s.id, Role: protocol.ChatRoleUser, CreatedAt: created, Parts: parts})
}
injectedSeen := map[string]bool{}
addInjected := func(entry transcriptEntry, item injected) {
if item.id == "" || injectedSeen[item.id] {
return
}
injectedSeen[item.id] = true
created, _ := transcriptTime(entry.Timestamp)
messages = append(messages, item.message(s.id, created))
builder.messages = append(builder.messages, earlierHistoryNotice(sessionID, skipped, created))
}
for _, entry := range entries {
if entry.IsSidechain {
continue
}
switch entry.Type {
case "assistant":
messageID := strings.TrimSpace(entry.Message.ID)
if messageID == "" {
messageID = entry.UUID
}
if messageID == "" {
continue
}
created, _ := transcriptTime(entry.Timestamp)
index, exists := messageIndex[messageID]
if !exists {
messages = append(messages, protocol.ChatMessage{ID: messageID, SessionID: s.id, Role: protocol.ChatRoleAssistant, Model: entry.Message.Model, CreatedAt: created, Parts: []protocol.ChatPart{}})
index = len(messages) - 1
messageIndex[messageID] = index
}
if entry.Message.Model != "" {
messages[index].Model = entry.Message.Model
}
blocks := decodeBlocks(entry.Message.Content)
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
}
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
}
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":
if block.ID == "" {
continue
}
part := protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: block.ID,
Name: block.Name,
State: &protocol.ChatToolState{
Status: protocol.ChatToolRunning,
Input: truncateJSON(block.Input, 64<<10),
},
}
messages[index].Parts = append(messages[index].Parts, part)
toolIndex[block.ID] = [2]int{index, len(messages[index].Parts) - 1}
}
}
case "user":
origin := decodeOrigin(entry.Origin)
if len(entry.Message.Content) > 0 && entry.Message.Content[0] == '"' {
// A string user entry is harness input (local command output, a
// reminder, a task notification or an agent's report), never a
// turn the operator sent. Reports and notices are shown as such.
var raw string
if json.Unmarshal(entry.Message.Content, &raw) == nil {
if item := classifyInjected(raw, origin, entry.IsMeta); item.class == classAgentReport || item.class == classNotice {
addInjected(entry, item)
}
}
continue
}
blocks := decodeBlocks(entry.Message.Content)
var text string
files := []protocol.ChatPart{}
hasResult := false
for _, block := range blocks {
switch block.Type {
case "tool_result":
hasResult = true
applyTranscriptToolResult(&messages, toolIndex, block)
case "text":
if strings.TrimSpace(block.Text) == "" {
continue
}
if text != "" {
text += "\n"
}
text += block.Text
case "image":
if block.Source != nil && block.Source.Data != "" && len(block.Source.Data) <= 512<<10 {
files = append(files, protocol.ChatPart{Type: protocol.ChatPartFile, Mime: block.Source.MediaType, Name: "image", URI: "data:" + block.Source.MediaType + ";base64," + block.Source.Data})
}
}
}
if hasResult || (text == "" && len(files) == 0) {
continue
}
if text != "" {
switch item := classifyInjected(text, origin, entry.IsMeta); item.class {
case classAgentReport, classNotice:
addInjected(entry, item)
continue
case classHidden:
continue
default:
text = item.text
}
} else if entry.IsMeta {
continue
}
addUser(entry, text, files)
case "attachment":
// A message the operator sent while the turn was running is recorded
// as a queued_command attachment where the CLI surfaced it to the
// model, so it is the user's turn at that point of the transcript.
// Other queued commands (task notifications, and agent reports the
// CLI also queues as "prompt" with an origin) are harness input:
// they are shown as notices and report cards, never as the operator's.
if entry.Attachment.Type != "queued_command" {
continue
}
mode := entry.Attachment.CommandMode
if mode != "prompt" && mode != "task-notification" {
continue
}
var text string
for _, block := range decodeBlocks(entry.Attachment.Prompt) {
if block.Type == "text" && strings.TrimSpace(block.Text) != "" {
if text != "" {
text += "\n"
}
text += block.Text
}
}
if strings.TrimSpace(text) == "" {
continue
}
origin := decodeOrigin(entry.Attachment.Origin)
if mode == "task-notification" && origin.Kind == "" {
origin.Kind = "task-notification"
}
switch item := classifyInjected(text, origin, entry.Attachment.IsMeta); item.class {
case classAgentReport, classNotice:
addInjected(entry, item)
continue
case classHidden:
continue
default:
text = item.text
}
addUser(entry, text, []protocol.ChatPart{})
}
builder.add(entry)
}
// Drop assistant messages that ended with no renderable part (for example a
// signature-only thinking entry).
filtered := messages[:0]
for _, message := range messages {
if len(message.Parts) > 0 {
filtered = append(filtered, message)
}
}
messages = filtered
messages := builder.shown()
start, end, offset := pageBounds(len(messages), limit, cursor)
return historyPage(messages[start:end], start, offset), nil
}
// pageBounds selects, out of total messages, the newest limit below cursor (the
// count of newest messages already served).
func pageBounds(total, limit int, cursor string) (start, end, offset int) {
if limit <= 0 {
limit = 50
}
if limit > 100 {
limit = 100
}
offset := 0
if strings.TrimSpace(cursor) != "" {
if parsed, err := strconv.Atoi(cursor); err == nil && parsed >= 0 {
offset = parsed
}
}
if offset > len(messages) {
offset = len(messages)
if offset > total {
offset = total
}
end := len(messages) - offset
start := end - limit
end = total - offset
start = end - limit
if start < 0 {
start = 0
}
page := protocol.ChatHistoryPage{Messages: append([]protocol.ChatMessage{}, messages[start:end]...)}
return start, end, offset
}
func historyPage(messages []protocol.ChatMessage, start, offset int) protocol.ChatHistoryPage {
page := protocol.ChatHistoryPage{Messages: append([]protocol.ChatMessage{}, messages...)}
if start > 0 {
page.HasMore = true
page.NextCursor = strconv.Itoa(offset + len(page.Messages))
}
return page, nil
return page
}
// promptIDs lists, per prompt text, the ids the operator's client sent that
// text with, oldest first.
func promptIDs(prompts []promptRecord) map[string][]string {
ids := map[string][]string{}
for _, prompt := range prompts {
if prompt.id == "" || prompt.text == "" {
continue
}
ids[prompt.text] = append(ids[prompt.text], prompt.id)
}
return ids
}
// promptMatcher names user turns in file order: the n-th turn with a prompt's
// text takes that text's n-th recorded id, any other turn its entry's uuid.
func promptMatcher(prompts []promptRecord) func(entry transcriptEntry, text string) string {
ids := promptIDs(prompts)
used := map[string]int{}
return func(entry transcriptEntry, text string) string {
text = strings.TrimSpace(text)
index := used[text]
if index >= len(ids[text]) {
return entry.UUID
}
used[text] = index + 1
return ids[text][index]
}
}
// transcriptBuilder maps the CLI's session file entries, in file order, into
// chat messages. It 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.
type transcriptBuilder struct {
sessionID string
messages []protocol.ChatMessage
messageIndex map[string]int
ordinals blockOrdinals
toolIndex map[string][2]int // tool id -> message/part index
injectedSeen map[string]bool
// userID names a user turn; an empty name drops the turn.
userID func(entry transcriptEntry, text string) string
}
func newTranscriptBuilder(sessionID string, userID func(transcriptEntry, string) string) *transcriptBuilder {
return &transcriptBuilder{
sessionID: sessionID,
messages: []protocol.ChatMessage{},
messageIndex: map[string]int{},
ordinals: blockOrdinals{},
toolIndex: map[string][2]int{},
injectedSeen: map[string]bool{},
userID: userID,
}
}
// shown is the built messages less assistant messages that ended with no
// renderable part (for example a signature-only thinking entry).
func (b *transcriptBuilder) shown() []protocol.ChatMessage {
filtered := b.messages[:0]
for _, message := range b.messages {
if len(message.Parts) > 0 {
filtered = append(filtered, message)
}
}
return filtered
}
func (b *transcriptBuilder) add(entry transcriptEntry) {
if entry.IsSidechain {
return
}
switch entry.Type {
case "assistant":
b.addAssistant(entry)
case "user", "attachment":
input := entryInputOf(entry)
for _, block := range input.results {
applyTranscriptToolResult(&b.messages, b.toolIndex, block)
}
if input.injected.id != "" {
b.addInjected(entry, input.injected)
} else if input.user {
b.addUser(entry, input.text, input.files)
}
}
}
func (b *transcriptBuilder) addUser(entry transcriptEntry, text string, files []protocol.ChatPart) {
id := b.userID(entry, text)
if id == "" {
return
}
created, _ := transcriptTime(entry.Timestamp)
parts := []protocol.ChatPart{}
if text != "" {
parts = append(parts, protocol.ChatPart{Type: protocol.ChatPartText, ID: id + "#text", Text: text})
}
parts = append(parts, files...)
b.messages = append(b.messages, protocol.ChatMessage{ID: id, SessionID: b.sessionID, Role: protocol.ChatRoleUser, CreatedAt: created, Parts: parts})
}
func (b *transcriptBuilder) addInjected(entry transcriptEntry, item injected) {
if b.injectedSeen[item.id] {
return
}
b.injectedSeen[item.id] = true
created, _ := transcriptTime(entry.Timestamp)
b.messages = append(b.messages, item.message(b.sessionID, created))
}
func (b *transcriptBuilder) addAssistant(entry transcriptEntry) {
messageID := assistantMessageID(entry)
if messageID == "" {
return
}
created, _ := transcriptTime(entry.Timestamp)
index, exists := b.messageIndex[messageID]
if !exists {
b.messages = append(b.messages, protocol.ChatMessage{ID: messageID, SessionID: b.sessionID, Role: protocol.ChatRoleAssistant, Model: entry.Message.Model, CreatedAt: created, Parts: []protocol.ChatPart{}})
index = len(b.messages) - 1
b.messageIndex[messageID] = index
}
if entry.Message.Model != "" {
b.messages[index].Model = entry.Message.Model
}
for _, block := range decodeBlocks(entry.Message.Content) {
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 := b.ordinals.next(messageID, protocol.ChatPartText)
if !shownAssistantBlock(block) {
continue
}
part := protocol.ChatPart{Type: protocol.ChatPartText, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartText, ordinal), Text: block.Text}
b.messages[index].Parts = append(b.messages[index].Parts, part)
case "thinking":
// An empty (display-omitted) thinking block often precedes the
// one with text; it is counted, not shown.
ordinal := b.ordinals.next(messageID, protocol.ChatPartReasoning)
if !shownAssistantBlock(block) {
continue
}
part := protocol.ChatPart{Type: protocol.ChatPartReasoning, ID: protocol.ChatDeltaPartID(messageID, protocol.ChatPartReasoning, ordinal), Text: block.Thinking}
b.messages[index].Parts = append(b.messages[index].Parts, part)
case "tool_use":
if !shownAssistantBlock(block) {
continue
}
part := protocol.ChatPart{
Type: protocol.ChatPartTool,
ID: block.ID,
Name: block.Name,
State: &protocol.ChatToolState{
Status: protocol.ChatToolRunning,
Input: truncateJSON(block.Input, 64<<10),
},
}
b.messages[index].Parts = append(b.messages[index].Parts, part)
b.toolIndex[block.ID] = [2]int{index, len(b.messages[index].Parts) - 1}
}
}
}
// assistantMessageID is the id an assistant entry's blocks merge under.
func assistantMessageID(entry transcriptEntry) string {
if messageID := strings.TrimSpace(entry.Message.ID); messageID != "" {
return messageID
}
return entry.UUID
}
// shownAssistantBlock reports whether an assistant content block becomes a part.
func shownAssistantBlock(block contentBlock) bool {
switch block.Type {
case "text":
return strings.TrimSpace(block.Text) != ""
case "thinking":
return strings.TrimSpace(block.Thinking) != ""
case "tool_use":
return block.ID != ""
}
return false
}
// entryInput is what one user or attachment entry contributes: results for
// earlier tool calls, then at most one message, either an injected report or
// notice (injected.id set) or the operator's turn (user set).
type entryInput struct {
results []contentBlock
injected injected
user bool
text string
files []protocol.ChatPart
}
func entryInputOf(entry transcriptEntry) entryInput {
if entry.Type == "attachment" {
return attachmentEntryInput(entry)
}
return userEntryInput(entry)
}
func userEntryInput(entry transcriptEntry) (input entryInput) {
origin := decodeOrigin(entry.Origin)
if len(entry.Message.Content) > 0 && entry.Message.Content[0] == '"' {
// A string user entry is harness input (local command output, a
// reminder, a task notification or an agent's report), never a turn
// the operator sent. Reports and notices are shown as such.
var raw string
if json.Unmarshal(entry.Message.Content, &raw) == nil {
if item := classifyInjected(raw, origin, entry.IsMeta); item.class == classAgentReport || item.class == classNotice {
input.injected = item
}
}
return input
}
var text string
files := []protocol.ChatPart{}
for _, block := range decodeBlocks(entry.Message.Content) {
switch block.Type {
case "tool_result":
input.results = append(input.results, block)
case "text":
if strings.TrimSpace(block.Text) == "" {
continue
}
if text != "" {
text += "\n"
}
text += block.Text
case "image":
if block.Source != nil && block.Source.Data != "" && len(block.Source.Data) <= 512<<10 {
files = append(files, protocol.ChatPart{Type: protocol.ChatPartFile, Mime: block.Source.MediaType, Name: "image", URI: "data:" + block.Source.MediaType + ";base64," + block.Source.Data})
}
}
}
if len(input.results) > 0 || (text == "" && len(files) == 0) {
return input
}
if text != "" {
switch item := classifyInjected(text, origin, entry.IsMeta); item.class {
case classAgentReport, classNotice:
input.injected = item
return input
case classHidden:
return input
default:
text = item.text
}
} else if entry.IsMeta {
return input
}
input.user, input.text, input.files = true, text, files
return input
}
// attachmentEntryInput reads an attachment entry. A message the operator sent
// while the turn was running is recorded as a queued_command attachment where
// the CLI surfaced it to the model, so it is the user's turn at that point of
// the transcript. Other queued commands (task notifications, and agent reports
// the CLI also queues as "prompt" with an origin) are harness input: they are
// shown as notices and report cards, never as the operator's.
func attachmentEntryInput(entry transcriptEntry) (input entryInput) {
if entry.Attachment.Type != "queued_command" {
return input
}
mode := entry.Attachment.CommandMode
if mode != "prompt" && mode != "task-notification" {
return input
}
var text string
for _, block := range decodeBlocks(entry.Attachment.Prompt) {
if block.Type == "text" && strings.TrimSpace(block.Text) != "" {
if text != "" {
text += "\n"
}
text += block.Text
}
}
if strings.TrimSpace(text) == "" {
return input
}
origin := decodeOrigin(entry.Attachment.Origin)
if mode == "task-notification" && origin.Kind == "" {
origin.Kind = "task-notification"
}
switch item := classifyInjected(text, origin, entry.Attachment.IsMeta); item.class {
case classAgentReport, classNotice:
input.injected = item
case classHidden:
default:
input.user, input.text, input.files = true, item.text, []protocol.ChatPart{}
}
return input
}
// blockOrdinals counts each message's text and thinking blocks by kind.
+431
View File
@@ -0,0 +1,431 @@
package claude
import (
"bufio"
"bytes"
"container/list"
"encoding/json"
"io"
"os"
"sort"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// A Claude session file grows to tens of megabytes, and reading a history
// page used to parse all of it. A transcriptIndex records, per message the
// history would show, which lines of the file build it. A page then re-reads
// and replays only its own messages' lines, so the newest page costs about as
// much as its messages. The index is kept per file and brought up to date by
// reading only what was appended since; a file that was replaced, truncated or
// rewritten is indexed again from the start.
//
// The replay must give exactly what building the whole file gives
// (fullTranscriptPage). Where the index cannot promise that (a user turn with
// no uuid, one tool id used by two messages, a parseable last line that has no
// newline yet), the page is built from the whole file as before.
// transcriptIndexesRetained bounds how many session files keep an index.
const transcriptIndexesRetained = 64
type lineRef struct {
offset int64
length int64
}
type indexedMessage struct {
// lines build the message, in file order: its own entries and the tool
// results that land on it.
lines []lineRef
shown bool
// A user turn's trimmed text and how many earlier turns had that text name
// it after the prompt the operator's client sent (promptMatcher).
user bool
text string
ordinal int
}
type transcriptIndex struct {
mu sync.Mutex
path string
// The indexed file: its identity, size and time when last read, where the
// index starts (past an oversized file's skipped head), where the last
// whole line ends, and the bytes just before that end.
info os.FileInfo
size int64
modTime time.Time
start int64
offset int64
boundary []byte
// fragment is set while the file ends with a parseable line that has no
// newline yet: a whole-file read includes it, the index does not.
fragment bool
// exact is cleared once the file holds a shape the index cannot replay
// exactly.
exact bool
firstStamp int64
hasStamp bool
meta transcriptMeta
messages []indexedMessage
messageIndex map[string]int
toolIndex map[string]int
injectedSeen map[string]bool
textCount map[string]int
}
var transcriptIndexes = struct {
sync.Mutex
byPath map[string]*list.Element
order *list.List
}{byPath: map[string]*list.Element{}, order: list.New()}
func transcriptIndexFor(path string) *transcriptIndex {
transcriptIndexes.Lock()
defer transcriptIndexes.Unlock()
if element, ok := transcriptIndexes.byPath[path]; ok {
transcriptIndexes.order.MoveToFront(element)
return element.Value.(*transcriptIndex)
}
index := &transcriptIndex{path: path}
transcriptIndexes.byPath[path] = transcriptIndexes.order.PushFront(index)
for transcriptIndexes.order.Len() > transcriptIndexesRetained {
oldest := transcriptIndexes.order.Back()
transcriptIndexes.order.Remove(oldest)
delete(transcriptIndexes.byPath, oldest.Value.(*transcriptIndex).path)
}
return index
}
func forgetTranscriptIndex(path string) {
transcriptIndexes.Lock()
defer transcriptIndexes.Unlock()
if element, ok := transcriptIndexes.byPath[path]; ok {
transcriptIndexes.order.Remove(element)
delete(transcriptIndexes.byPath, path)
}
}
func (x *transcriptIndex) reset(start int64) {
x.info, x.size, x.modTime, x.boundary, x.fragment = nil, 0, time.Time{}, nil, false
x.start, x.offset, x.exact = start, start, true
x.firstStamp, x.hasStamp, x.meta = 0, false, transcriptMeta{}
x.messages = nil
x.messageIndex = map[string]int{}
x.toolIndex = map[string]int{}
x.injectedSeen = map[string]bool{}
x.textCount = map[string]int{}
}
// windowStart is where a read of the file begins: 0, or for a file larger
// than maxTranscriptBytes the first whole line of its newest bytes
// (readTranscriptTail).
func windowStart(file *os.File, size int64) (int64, error) {
if size <= maxTranscriptBytes {
return 0, nil
}
skipped := size - maxTranscriptBytes
reader := bufio.NewReaderSize(io.NewSectionReader(file, skipped, size-skipped), 64<<10)
partial, err := reader.ReadBytes('\n')
if err != nil && err != io.EOF {
return 0, err
}
return skipped + int64(len(partial)), nil
}
// update brings the index up to date with the file, reading only what was
// appended since the last update when the file is the same one grown.
func (x *transcriptIndex) update() error {
file, err := os.Open(x.path)
if err != nil {
return err
}
defer file.Close()
info, err := file.Stat()
if err != nil {
return err
}
size := info.Size()
start, err := windowStart(file, size)
if err != nil {
return err
}
if x.info != nil && os.SameFile(x.info, info) && start == x.start && size == x.size && info.ModTime().Equal(x.modTime) {
return nil
}
if x.info == nil || !os.SameFile(x.info, info) || start != x.start || size < x.offset || size == x.size || !x.sameBoundary(file) {
x.reset(start)
}
if err := x.read(file, size); err != nil {
return err
}
x.info, x.size, x.modTime = info, size, info.ModTime()
return nil
}
// sameBoundary checks the bytes before the indexed end are unchanged, so the
// file only grew past them.
func (x *transcriptIndex) sameBoundary(file *os.File) bool {
if len(x.boundary) == 0 {
return x.offset == x.start
}
held := make([]byte, len(x.boundary))
if _, err := file.ReadAt(held, x.offset-int64(len(held))); err != nil {
return false
}
return bytes.Equal(held, x.boundary)
}
// read indexes the whole lines between the indexed end and size.
func (x *transcriptIndex) read(file *os.File, size int64) error {
reader := bufio.NewReaderSize(io.NewSectionReader(file, x.offset, size-x.offset), 256<<10)
position := x.offset
var long []byte
for {
chunk, err := reader.ReadSlice('\n')
if err == bufio.ErrBufferFull {
long = append(long, chunk...)
if len(long) > maxLineBytes {
return bufio.ErrTooLong
}
continue
}
line := chunk
if long != nil {
line = append(long, chunk...)
long = nil
}
if err == io.EOF {
// A last line with no newline yet is not indexed: it is either
// still being written or will be followed by one.
var entry transcriptEntry
trimmed := bytes.TrimSpace(line)
x.fragment = len(trimmed) > 0 && json.Unmarshal(trimmed, &entry) == nil
if len(line) > maxLineBytes {
return bufio.ErrTooLong
}
break
}
if err != nil {
return err
}
if len(line) > maxLineBytes {
return bufio.ErrTooLong
}
ref := lineRef{offset: position, length: int64(len(line) - 1)}
position += int64(len(line))
if ref.length > 0 {
var entry transcriptEntry
if json.Unmarshal(line[:ref.length], &entry) == nil {
x.add(entry, ref)
}
}
}
x.offset = position
if position > x.start {
count := min(position-x.start, 64)
x.boundary = make([]byte, count)
if _, err := file.ReadAt(x.boundary, position-count); err != nil {
return err
}
}
return nil
}
// add mirrors transcriptBuilder.add, recording which message each line builds
// instead of building it.
func (x *transcriptIndex) add(entry transcriptEntry, ref lineRef) {
if stamp, ok := transcriptTime(entry.Timestamp); ok && !x.hasStamp {
x.firstStamp, x.hasStamp = stamp, true
}
x.meta.note(entry)
if entry.IsSidechain {
return
}
switch entry.Type {
case "assistant":
messageID := assistantMessageID(entry)
if messageID == "" {
return
}
index, exists := x.messageIndex[messageID]
if !exists {
x.messages = append(x.messages, indexedMessage{})
index = len(x.messages) - 1
x.messageIndex[messageID] = index
}
x.attach(index, ref)
for _, block := range decodeBlocks(entry.Message.Content) {
if !shownAssistantBlock(block) {
continue
}
x.messages[index].shown = true
if block.Type == "tool_use" {
if held, ok := x.toolIndex[block.ID]; ok && held != index {
x.exact = false
}
x.toolIndex[block.ID] = index
}
}
case "user", "attachment":
input := entryInputOf(entry)
for _, block := range input.results {
if index, ok := x.toolIndex[block.ToolUseID]; ok {
x.attach(index, ref)
}
}
if input.injected.id != "" {
if !x.injectedSeen[input.injected.id] {
x.injectedSeen[input.injected.id] = true
x.messages = append(x.messages, indexedMessage{lines: []lineRef{ref}, shown: true})
}
} else if input.user {
if entry.UUID == "" {
// Whether such a turn is shown depends on the prompts sent.
x.exact = false
}
text := strings.TrimSpace(input.text)
x.messages = append(x.messages, indexedMessage{lines: []lineRef{ref}, shown: true, user: true, text: text, ordinal: x.textCount[text]})
x.textCount[text]++
}
}
}
func (x *transcriptIndex) attach(index int, ref lineRef) {
lines := x.messages[index].lines
if len(lines) > 0 && lines[len(lines)-1] == ref {
return
}
x.messages[index].lines = append(lines, ref)
}
// indexedTranscriptMeta is the session description transcriptSession reads,
// from the file's index. ok is false when the index cannot answer exactly.
func indexedTranscriptMeta(path string) (transcriptMeta, bool) {
x := transcriptIndexFor(path)
x.mu.Lock()
defer x.mu.Unlock()
if err := x.update(); err != nil {
x.reset(0)
forgetTranscriptIndex(path)
return transcriptMeta{}, false
}
return x.meta, !x.fragment
}
// indexedTranscriptPage serves a history page from the file's index. ok is
// false (with no error) when the page must be built from the whole file.
func indexedTranscriptPage(path, sessionID string, prompts []promptRecord, limit int, cursor string) (protocol.ChatHistoryPage, bool, error) {
x := transcriptIndexFor(path)
x.mu.Lock()
if err := x.update(); err != nil {
// The whole-file read reports the error as it always did.
x.reset(0)
x.mu.Unlock()
forgetTranscriptIndex(path)
return protocol.ChatHistoryPage{}, false, nil
}
if x.fragment || !x.exact {
x.mu.Unlock()
return protocol.ChatHistoryPage{}, false, nil
}
notice := x.start > 0
shown := make([]int, 0, len(x.messages)+1)
if notice {
shown = append(shown, -1)
}
for index, message := range x.messages {
if message.shown {
shown = append(shown, index)
}
}
start, end, offset := pageBounds(len(shown), limit, cursor)
var refs []lineRef
users := map[int64]indexedMessage{}
wanted := 0
for _, index := range shown[start:end] {
if index < 0 {
continue
}
wanted++
message := x.messages[index]
refs = append(refs, message.lines...)
if message.user {
users[message.lines[0].offset] = message
}
}
skipped, firstStamp := x.start, x.firstStamp
x.mu.Unlock()
lines, err := readLines(path, refs)
if err != nil {
return protocol.ChatHistoryPage{}, false, nil
}
ids := promptIDs(prompts)
var current int64
builder := newTranscriptBuilder(sessionID, func(entry transcriptEntry, _ string) string {
if message, ok := users[current]; ok && message.ordinal < len(ids[message.text]) {
return ids[message.text][message.ordinal]
}
return entry.UUID
})
for _, line := range lines {
var entry transcriptEntry
if json.Unmarshal(line.data, &entry) != nil {
return protocol.ChatHistoryPage{}, false, nil
}
current = line.offset
builder.add(entry)
}
messages := builder.shown()
if len(messages) != wanted {
// The file changed under the read: build it whole.
return protocol.ChatHistoryPage{}, false, nil
}
if notice && start == 0 && end > 0 {
messages = append([]protocol.ChatMessage{earlierHistoryNotice(sessionID, skipped, firstStamp)}, messages...)
}
return historyPage(messages, start, offset), true, nil
}
type readLine struct {
offset int64
data []byte
}
// readLines reads the given lines in file order, each once, joining reads of
// lines that lie close together.
func readLines(path string, refs []lineRef) ([]readLine, error) {
sort.Slice(refs, func(i, j int) bool { return refs[i].offset < refs[j].offset })
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
const gap = 64 << 10
var lines []readLine
for i := 0; i < len(refs); {
first := refs[i].offset
last := i
end := refs[i].offset + refs[i].length
for last+1 < len(refs) && refs[last+1].offset-end <= gap {
last++
end = max(end, refs[last].offset+refs[last].length)
}
buffer := make([]byte, end-first)
if _, err := file.ReadAt(buffer, first); err != nil {
return nil, err
}
for ; i <= last; i++ {
ref := refs[i]
if len(lines) > 0 && lines[len(lines)-1].offset == ref.offset {
continue
}
lines = append(lines, readLine{offset: ref.offset, data: buffer[ref.offset-first : ref.offset-first+ref.length]})
}
}
return lines, nil
}
+437
View File
@@ -0,0 +1,437 @@
package claude
import (
"encoding/json"
"fmt"
"math/rand"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"time"
)
// synthTranscript writes a synthetic, real-shaped Claude session file: turns
// of prompts, thinking, text and parallel tool calls whose results carry large
// toolUseResult payloads, with sidechain (subagent) entries, compaction,
// queued prompts, task notifications and agent reports (some delivered twice),
// image prompts, signature-only thinking, malformed and blank lines. No real
// transcript is read.
type synthTranscript struct {
rand *rand.Rand
lines []string
clock time.Time
turn int
tool int
}
func newSynthTranscript(seed int64) *synthTranscript {
return &synthTranscript{rand: rand.New(rand.NewSource(seed)), clock: time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)}
}
func (g *synthTranscript) emit(entry map[string]any) {
g.clock = g.clock.Add(time.Duration(1+g.rand.Intn(2000)) * time.Millisecond)
base := map[string]any{
"parentUuid": nil, "isSidechain": false, "userType": "external", "cwd": "/home/op/work",
"sessionId": "ses_synth", "version": "2.1.0", "gitBranch": "main",
"uuid": fmt.Sprintf("uuid-%d", len(g.lines)), "timestamp": g.clock.Format(time.RFC3339Nano),
}
for key, value := range entry {
base[key] = value
}
raw, err := json.Marshal(base)
if err != nil {
panic(err)
}
g.lines = append(g.lines, string(raw))
}
func (g *synthTranscript) words(n int) string {
vocabulary := []string{"build", "the", "server", "reads", "a", "page", "of", "chat", "history", "quickly", "and", "tests", "pass", "<tag>", "\"quoted\"", "naïve", "→"}
var builder strings.Builder
for i := 0; i < n; i++ {
if i > 0 {
builder.WriteByte(' ')
}
builder.WriteString(vocabulary[g.rand.Intn(len(vocabulary))])
}
return builder.String()
}
func (g *synthTranscript) assistant(messageID string, sidechain bool, blocks ...map[string]any) {
for _, block := range blocks {
g.emit(map[string]any{
"type": "assistant", "isSidechain": sidechain, "requestId": "req_" + messageID,
"message": map[string]any{
"id": messageID, "type": "message", "role": "assistant", "model": "claude-opus-4-5",
"content": []any{block}, "stop_reason": nil,
"usage": map[string]any{"input_tokens": 3, "output_tokens": 120, "cache_read_input_tokens": 51234},
},
})
}
}
func (g *synthTranscript) user(content any, extra map[string]any) {
entry := map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": content}}
for key, value := range extra {
entry[key] = value
}
g.emit(entry)
}
// addTurn appends one turn; resultBytes sizes the tool payloads.
func (g *synthTranscript) addTurn(prompt string, resultBytes int) {
g.turn++
turn := g.turn
switch g.rand.Intn(10) {
case 0:
g.emit(queued(fmt.Sprintf("q-%d", len(g.lines)), "prompt", textBlocks(prompt), nil))
case 1:
g.user([]any{map[string]any{"type": "text", "text": prompt}, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": "image/png", "data": strings.Repeat("iVBO", 50)}}}, nil)
default:
g.user(textBlocks(prompt), map[string]any{"promptSource": "sdk"})
}
for step := 0; step < 1+g.rand.Intn(4); step++ {
messageID := fmt.Sprintf("msg_%d_%d", turn, step)
g.assistant(messageID, false, map[string]any{"type": "thinking", "thinking": "", "signature": strings.Repeat("s", 300)})
if g.rand.Intn(2) == 0 {
g.assistant(messageID, false, map[string]any{"type": "thinking", "thinking": g.words(40), "signature": "sig"})
}
g.assistant(messageID, false, map[string]any{"type": "text", "text": g.words(30 + g.rand.Intn(80))})
var calls []string
for call := 0; call < g.rand.Intn(3); call++ {
g.tool++
toolID := fmt.Sprintf("toolu_%06d", g.tool)
calls = append(calls, toolID)
g.assistant(messageID, false, map[string]any{"type": "tool_use", "id": toolID, "name": "Bash", "input": map[string]any{"command": "go test ./... " + g.words(5), "description": "Run tests"}})
if call == 0 && g.rand.Intn(3) == 0 {
// A result landing between two blocks of one message.
g.result(toolID, resultBytes)
calls = calls[:0]
}
}
for _, toolID := range calls {
g.result(toolID, resultBytes)
}
if g.rand.Intn(6) == 0 {
// A subagent's work is a sidechain of the same file.
g.assistant(fmt.Sprintf("msg_side_%d_%d", turn, step), true, map[string]any{"type": "text", "text": "subagent " + g.words(20)})
g.user(textBlocks("subagent prompt"), map[string]any{"isSidechain": true})
}
}
switch g.rand.Intn(12) {
case 0:
notice := strings.Replace(taskNotification, "toolu_bg1", fmt.Sprintf("toolu_bg%d", turn%5), 1)
g.user(notice, map[string]any{"origin": map[string]any{"kind": "task-notification"}})
g.emit(queued(fmt.Sprintf("q-%d", len(g.lines)), "task-notification", notice, map[string]any{"origin": map[string]any{"kind": "task-notification"}}))
case 1:
g.emit(queued(fmt.Sprintf("q-%d", len(g.lines)), "prompt", subagentReport, map[string]any{"isMeta": true, "origin": peerOrigin(fmt.Sprintf("a%d", turn%3), true, "## Report "+strconv.Itoa(turn%4))}))
case 2:
g.user("<system-reminder>\nnothing for the operator\n</system-reminder>", map[string]any{"isMeta": true})
case 3:
g.emit(map[string]any{"type": "system", "subtype": "compact_boundary", "content": "Conversation compacted", "compactMetadata": map[string]any{"trigger": "auto", "preTokens": 160000}})
g.user(textBlocks("This session is being continued from a previous conversation. "+g.words(200)), map[string]any{"isCompactSummary": true, "isVisibleInTranscriptOnly": true})
case 4:
g.lines = append(g.lines, `{"type":"assistant","message":{"id":"broken`, "")
case 5:
g.user(textBlocks(midTurnWrapped), nil)
case 6:
g.emit(map[string]any{"type": "file-history-snapshot", "snapshot": map[string]any{"files": g.words(50)}})
}
}
func (g *synthTranscript) result(toolID string, size int) {
output := strings.Repeat(g.words(12)+"\n", 1+size/80)
content := any(output)
isError := g.rand.Intn(9) == 0
if g.rand.Intn(4) == 0 {
content = []any{map[string]any{"type": "text", "text": output + "\nexit code 1"}}
}
g.user([]any{map[string]any{"type": "tool_result", "tool_use_id": toolID, "content": content, "is_error": isError}},
map[string]any{"toolUseResult": map[string]any{"stdout": output, "stderr": "", "interrupted": false, "file": map[string]any{"content": output}}})
}
func (g *synthTranscript) build(turns, resultBytes int) *synthTranscript {
prompts := []string{"continue", "run the tests", "ship it now", "also check the docs"}
for i := 0; i < turns; i++ {
prompt := prompts[g.rand.Intn(len(prompts))]
if g.rand.Intn(2) == 0 {
prompt = fmt.Sprintf("turn %d: %s", i, g.words(10))
}
g.addTurn(prompt, resultBytes)
}
return g
}
func (g *synthTranscript) text() string { return strings.Join(g.lines, "\n") + "\n" }
func writeSynthFile(t testing.TB, id, text string) string {
t.Helper()
config := t.TempDir()
t.Setenv("CLAUDE_CONFIG_DIR", config)
dir := filepath.Join(config, "projects", "-home-op-work")
if err := os.MkdirAll(dir, 0o755); err != nil {
t.Fatal(err)
}
path := filepath.Join(dir, id+".jsonl")
if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
t.Fatal(err)
}
return path
}
func appendFile(t testing.TB, path, text string) {
t.Helper()
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
defer file.Close()
if _, err := file.WriteString(text); err != nil {
t.Fatal(err)
}
}
// assertIndexedMatchesFull compares every page of the file, served by the
// index, with the same page built from the whole file.
func assertIndexedMatchesFull(t *testing.T, path string, prompts []promptRecord) {
t.Helper()
for _, limit := range []int{7, 20, 50, 100, 200} {
cursor := ""
for pages := 0; ; pages++ {
want, err := fullTranscriptPage(path, "ses_synth", prompts, limit, cursor)
if err != nil {
t.Fatal(err)
}
got, ok, err := indexedTranscriptPage(path, "ses_synth", prompts, limit, cursor)
if err != nil || !ok {
t.Fatalf("limit %d cursor %q: indexed page not served (ok=%v err=%v)", limit, cursor, ok, err)
}
wantJSON, _ := json.Marshal(want)
gotJSON, _ := json.Marshal(got)
if string(wantJSON) != string(gotJSON) {
t.Fatalf("limit %d cursor %q: indexed page differs\n got %.600s\nwant %.600s", limit, cursor, gotJSON, wantJSON)
}
if !want.HasMore || pages > 400 {
break
}
cursor = want.NextCursor
}
}
for _, cursor := range []string{"0", "3", "-2", "x", "999999"} {
want, _ := fullTranscriptPage(path, "ses_synth", prompts, 20, cursor)
got, _, _ := indexedTranscriptPage(path, "ses_synth", prompts, 20, cursor)
wantJSON, _ := json.Marshal(want)
gotJSON, _ := json.Marshal(got)
if string(wantJSON) != string(gotJSON) {
t.Fatalf("cursor %q: indexed page differs", cursor)
}
}
}
func synthPrompts() []promptRecord {
return []promptRecord{
{id: "op-1", text: "continue"}, {id: "op-2", text: "continue"}, {id: "op-3", text: "run the tests"},
{id: "op-4", text: "also check the docs"}, {id: "op-5", text: "ship it now"}, {id: "op-6", text: "continue"},
}
}
func TestIndexedHistoryMatchesTheWholeFileRead(t *testing.T) {
for seed := int64(1); seed <= 4; seed++ {
text := newSynthTranscript(seed).build(60, 300).text()
path := writeSynthFile(t, fmt.Sprintf("ses_seed%d", seed), text)
assertIndexedMatchesFull(t, path, nil)
assertIndexedMatchesFull(t, path, synthPrompts())
if seed == 1 {
assertFixtureCoverage(t, path)
}
}
}
// assertFixtureCoverage checks the synthetic file exercises what the
// comparison is meant to cover.
func assertFixtureCoverage(t *testing.T, path string) {
t.Helper()
seen := map[string]int{}
cursor := ""
for {
page, err := fullTranscriptPage(path, "ses_synth", synthPrompts(), 100, cursor)
if err != nil {
t.Fatal(err)
}
for _, message := range page.Messages {
seen["kind:"+message.Kind]++
if strings.HasPrefix(message.ID, "op-") {
seen["prompt id"]++
}
if strings.HasPrefix(message.ID, "q-") {
seen["queued prompt"]++
}
for _, part := range message.Parts {
seen["part:"+part.Type]++
if part.State != nil && len(part.State.Content) > 0 {
seen["tool result"]++
}
if part.State != nil && part.State.Error != nil {
seen["tool error"]++
}
}
}
if !page.HasMore {
break
}
cursor = page.NextCursor
}
for _, want := range []string{"kind:notice", "kind:agent_report", "prompt id", "queued prompt", "part:reasoning", "part:file", "tool result", "tool error"} {
if seen[want] == 0 {
t.Fatalf("fixture lacks %q: %v", want, seen)
}
}
}
// Appending turns, a half-written last line and its completion, are read
// incrementally and still match the whole-file read.
func TestIndexedHistoryFollowsAppends(t *testing.T) {
g := newSynthTranscript(7).build(30, 200)
path := writeSynthFile(t, "ses_append", g.text())
assertIndexedMatchesFull(t, path, synthPrompts())
written := len(g.lines)
for round := 0; round < 4; round++ {
g.build(3, 200)
appendFile(t, path, strings.Join(g.lines[written:], "\n")+"\n")
written = len(g.lines)
assertIndexedMatchesFull(t, path, synthPrompts())
}
before := transcriptIndexFor(path).offset
// A line still being written is left for the next read.
appendFile(t, path, `{"type":"assistant","uuid":"tail","message":{"id":"msg_tail","role":"assistant","content":[{"type":"text","text":"half`)
assertIndexedMatchesFull(t, path, nil)
appendFile(t, path, ` done"}]}}`)
// A parseable line with no newline yet is read whole, as before.
if _, ok, _ := indexedTranscriptPage(path, "ses_synth", nil, 20, ""); ok {
t.Fatal("a parseable unterminated last line must be read from the whole file")
}
appendFile(t, path, "\n")
assertIndexedMatchesFull(t, path, nil)
if index := transcriptIndexFor(path); index.offset <= before || index.start != 0 {
t.Fatalf("index did not grow incrementally: offset %d (was %d)", index.offset, before)
}
}
// A file rewritten in place (same size or shorter) is indexed again.
func TestIndexedHistoryNoticesARewrite(t *testing.T) {
first := newSynthTranscript(8).build(20, 100).text()
path := writeSynthFile(t, "ses_rewrite", first)
assertIndexedMatchesFull(t, path, nil)
second := newSynthTranscript(9).build(10, 100).text()
if err := os.WriteFile(path, []byte(second), 0o644); err != nil {
t.Fatal(err)
}
assertIndexedMatchesFull(t, path, nil)
// Same length, different content: the boundary check catches it.
third := []byte(second)
copy(third[len(third)-40:], strings.Repeat(" ", 38))
if err := os.WriteFile(path, third, 0o644); err != nil {
t.Fatal(err)
}
future := time.Now().Add(time.Hour)
_ = os.Chtimes(path, future, future)
assertIndexedMatchesFull(t, path, nil)
}
// An oversized file is indexed from its newest maxTranscriptBytes, with the
// same earlier-history notice.
func TestIndexedHistoryOfAnOversizedFile(t *testing.T) {
g := newSynthTranscript(10).build(40, 200)
path := writeSynthFile(t, "ses_big", g.text())
defer func(limit int64) { maxTranscriptBytes = limit }(maxTranscriptBytes)
maxTranscriptBytes = int64(len(g.text()) / 3)
assertIndexedMatchesFull(t, path, synthPrompts())
written := len(g.lines)
g.build(2, 200)
appendFile(t, path, strings.Join(g.lines[written:], "\n")+"\n")
assertIndexedMatchesFull(t, path, synthPrompts())
}
// The session description read from the index matches the whole-file read.
func TestIndexedTranscriptMetaMatches(t *testing.T) {
text := newSynthTranscript(11).build(20, 100).text()
path := writeSynthFile(t, "ses_meta", text)
entries, err := readTranscript(path)
if err != nil {
t.Fatal(err)
}
want := transcriptMeta{}
for _, entry := range entries {
want.note(entry)
}
got, ok := indexedTranscriptMeta(path)
if !ok || got != want {
t.Fatalf("meta = %+v ok=%v, want %+v", got, ok, want)
}
}
// benchmarkFile synthesizes a transcript of about 40 MB, shaped like a long
// working session.
func benchmarkFile(b *testing.B) string {
b.Helper()
text := newSynthTranscript(42).build(1100, 6000).text()
path := writeSynthFile(b, "ses_bench", text)
b.Logf("synthetic transcript: %.1f MB", float64(len(text))/(1<<20))
return path
}
func BenchmarkTranscriptNewestPageWholeFile(b *testing.B) {
path := benchmarkFile(b)
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, err := fullTranscriptPage(path, "ses_bench", nil, 100, ""); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkTranscriptNewestPageIndexed(b *testing.B) {
path := benchmarkFile(b)
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
b.Fatal("index not served")
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
b.Fatal("index not served")
}
}
}
func BenchmarkTranscriptNewestPageIndexedAfterAppend(b *testing.B) {
path := benchmarkFile(b)
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
b.Fatal("index not served")
}
g := newSynthTranscript(43)
g.turn, g.tool = 100000, 1000000
b.ResetTimer()
for i := 0; i < b.N; i++ {
b.StopTimer()
g.lines = g.lines[:0]
g.addTurn("continue", 6000)
appendFile(b, path, g.text())
b.StartTimer()
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
b.Fatal("index not served")
}
}
}
func BenchmarkTranscriptIndexColdBuild(b *testing.B) {
path := benchmarkFile(b)
b.ResetTimer()
for i := 0; i < b.N; i++ {
forgetTranscriptIndex(path)
if _, ok, err := indexedTranscriptPage(path, "ses_bench", nil, 100, ""); !ok || err != nil {
b.Fatal("index not served")
}
}
}
+5
View File
@@ -523,6 +523,11 @@ type ChatQuery struct {
// Cursor is the opaque continuation returned by OpenCode's descending
// message listing. It is deliberately not interpreted by the broker.
Cursor string `json:"cursor,omitempty"`
// History, on chat_subscribe, asks the reply to also carry the newest
// history page (Limit messages), as a chat_messages reply would, read once
// the subscription is attached. It saves the client a second round trip;
// a server that ignores it simply leaves the page out.
History bool `json:"history,omitempty"`
}
// ChatHistoryPage describes the bounded slice returned by chat_messages. The
+1 -1
View File
@@ -184,7 +184,7 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
handleChatPrompt(ctx, request, broker, hub, registry, clientID, write)
return true
case protocol.ChatSubscribe:
handleChatSubscribe(request, broker, hub, clientID, write)
handleChatSubscribe(ctx, request, broker, hub, clientID, write)
return true
case protocol.ChatUnqueue:
handleChatUnqueue(ctx, request, hub, write)
+12 -3
View File
@@ -20,18 +20,27 @@ func handleChatMessages(ctx context.Context, request protocol.Message, broker ch
_ = write(response)
return
}
page, err := broker.Messages(ctx, query.SessionID, query.Limit, query.Cursor)
if err != nil {
if err := addChatHistory(ctx, &response, broker, hub, *query); err != nil {
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
return
}
_ = write(response)
}
// addChatHistory reads one history page into a reply: a chat_messages reply,
// or a chat_subscribe reply that asked for the newest page.
func addChatHistory(ctx context.Context, response *protocol.Message, broker chatBroker, hub *chatHub, query protocol.ChatQuery) error {
page, err := broker.Messages(ctx, query.SessionID, query.Limit, query.Cursor)
if err != nil {
return err
}
page.Messages = hub.reconcileHistory(query.SessionID, page.Messages)
response.ChatMessages = page.Messages // legacy peers keep working.
response.ChatHistory = &page
// The session's recorded per-turn changes ride with its history, so the
// transcript's change chips survive a reload and a server restart.
response.ChatTurnDiffList = hub.turnDiffList(ctx, query.SessionID)
_ = write(response)
return nil
}
func handleChatSimple(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, write func(protocol.Message) error) {
+16 -2
View File
@@ -2,6 +2,7 @@ package server
import (
"context"
"log"
"strings"
"time"
@@ -233,7 +234,7 @@ func handleChatModelSwitch(ctx context.Context, request protocol.Message, broker
// receives every frame any client's turn produces, its own or another device's.
// It replays the session's still-pending approval requests, if the room holds
// any, so a device that joins late still shows the cards.
func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatHub, clientID string, write func(protocol.Message) error) {
func handleChatSubscribe(ctx context.Context, request protocol.Message, broker chatBroker, hub *chatHub, clientID string, write func(protocol.Message) error) {
// The wire body of chat_subscribe is the chat_subscribe field (the app's
// subscribeRequest and docs/cli.md both use it), not the chat_query body the
// other session-scoped commands carry.
@@ -265,7 +266,20 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH
// session, so a reloaded client draws them as Queued without any device
// storage.
queue := hub.queueFrame(query.SessionID)
_ = write(protocol.Message{Type: protocol.ChatSubscribe, ID: request.ID, ChatQueue: &queue, ChatShown: hub.shownFrame(query.SessionID)})
reply := protocol.Message{Type: protocol.ChatSubscribe, ID: request.ID, ChatQueue: &queue, ChatShown: hub.shownFrame(query.SessionID)}
if query.History {
// Read after attaching, as a chat_messages sent after this reply would
// be: a frame produced meanwhile waits in the subscription's queue.
// A failed read leaves the page out; the client then asks for it with
// chat_messages, which reports the error.
history := protocol.Message{}
if err := addChatHistory(ctx, &history, broker, hub, protocol.ChatQuery{SessionID: query.SessionID, Limit: query.Limit}); err == nil {
reply.ChatMessages, reply.ChatHistory, reply.ChatTurnDiffList = history.ChatMessages, history.ChatHistory, history.ChatTurnDiffList
} else {
log.Printf("chat session %s: history for the subscribe reply: %v", query.SessionID, err)
}
}
_ = write(reply)
if fresh {
go sub.run()
}
+31
View File
@@ -732,6 +732,37 @@ func TestChatMessagesReturnsBrokerHistory(t *testing.T) {
}
}
// A chat_subscribe that asks for history carries the newest page in its reply,
// read once attached, so opening a chat takes one round trip. Without the flag
// the reply carries no history and the broker is not read.
func TestChatSubscribeCarriesTheNewestPageWhenAsked(t *testing.T) {
broker := scriptedChat()
broker.block = true
broker.messages = seededChatMessages()
ctx, _, conn := dialChat(t, broker)
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "plain", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1"}}); err != nil {
t.Fatal(err)
}
plain := readUntil(t, ctx, conn, protocol.ChatSubscribe)
if plain.ChatHistory != nil || len(plain.ChatMessages) != 0 {
t.Fatalf("a plain subscribe reply carried history: %+v", plain)
}
if calls, _, _ := broker.messageQuery(); calls != 0 {
t.Fatalf("a plain subscribe read history %d times", calls)
}
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSubscribe, ID: "with", ChatSubscribe: &protocol.ChatQuery{SessionID: "ses_1", History: true, Limit: 9}}); err != nil {
t.Fatal(err)
}
reply := readUntil(t, ctx, conn, protocol.ChatSubscribe)
if reply.ID != "with" || reply.ChatHistory == nil || reply.ChatQueue == nil {
t.Fatalf("subscribe reply = %+v, want the queue and a history page", reply)
}
assertSeededChatMessages(t, reply.ChatHistory.Messages)
if calls, sessionID, limit := broker.messageQuery(); calls != 1 || sessionID != "ses_1" || limit != 9 {
t.Fatalf("broker query = %d/%q/%d, want 1/ses_1/9", calls, sessionID, limit)
}
}
// TestChatMessagesThroughRealAdapter loads a seeded session through the real
// opencode.Chat broker: the chat_messages handler reads the V2
// GET /api/session/{id}/message fixture once and returns the user + assistant +