From daa35e810ea74fc962f50621451026fc5d09f11e Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 22:43:52 +0900 Subject: [PATCH 1/6] feat(chat): page Claude transcripts from the tail --- internal/chat/service.go | 6 +- internal/chat/transcript_page.go | 486 ++++++++++++++++++++++++++ internal/chat/transcript_page_test.go | 155 ++++++++ 3 files changed, 645 insertions(+), 2 deletions(-) create mode 100644 internal/chat/transcript_page.go create mode 100644 internal/chat/transcript_page_test.go diff --git a/internal/chat/service.go b/internal/chat/service.go index 9a667265b..90aac076a 100644 --- a/internal/chat/service.go +++ b/internal/chat/service.go @@ -32,8 +32,9 @@ type Service struct { sessions map[tabKey]*session closedTabs map[closedTabGeneration]struct{} // closedOrder lets expiry and capacity discard the oldest closes first. - closedOrder list.List - closed bool + closedOrder list.List + closed bool + transcriptPages transcriptSnapshotCache } type tabKey struct { @@ -128,6 +129,7 @@ func Register(d *dispatch.Dispatcher, service *Service) { d.Register("chat.list", service.List) d.Register("chat.exec", service.Exec) d.Register("chat.transcript", service.Transcript) + d.Register("chat.transcriptPage", service.TranscriptPage) d.Register("chat.subagentTranscript", service.SubagentTranscript) d.Register("chat.sessionFile", service.SessionFile) d.Register("chat.stageThread", service.StageThread) diff --git a/internal/chat/transcript_page.go b/internal/chat/transcript_page.go new file mode 100644 index 000000000..627ea5ae0 --- /dev/null +++ b/internal/chat/transcript_page.go @@ -0,0 +1,486 @@ +package chat + +import ( + "bufio" + "bytes" + "context" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/binary" + "encoding/json" + "io" + "os" + "sync" + + "github.com/nexus-code/nexus-code/internal/proto" +) + +const ( + transcriptPageBytes = 512 * 1024 + transcriptPageTurns = 20 + transcriptPageOverhead = 384 + transcriptReadBlock = 64 * 1024 + transcriptAnchorBytes = 2048 + transcriptSnapshots = 128 +) + +type transcriptPageParams struct { + TranscriptParams + Cursor string `json:"cursor,omitempty"` + UpTo string `json:"upTo,omitempty"` + Before []string `json:"before,omitempty"` +} + +type transcriptPage struct { + Found bool `json:"found"` + Lines []json.RawMessage `json:"lines"` + Positions []int64 `json:"positions"` + Truncated bool `json:"truncated"` + Snapshot string `json:"snapshot,omitempty"` + Cursor string `json:"cursor,omitempty"` + Fragment *transcriptFragment `json:"fragment,omitempty"` +} + +type transcriptFragment struct { + Position int64 `json:"position"` + Data []byte `json:"data"` + First bool `json:"first"` + Last bool `json:"last"` +} + +type transcriptSnapshot struct { + key [32]byte + session, dir, path string + info os.FileInfo + floor, end int64 + anchor [32]byte +} + +type transcriptSnapshotCache struct { + mu sync.Mutex + entries [transcriptSnapshots]*transcriptSnapshot + next int +} + +func (c *transcriptSnapshotCache) add(snapshot *transcriptSnapshot) { + c.mu.Lock() + defer c.mu.Unlock() + c.entries[c.next] = snapshot + c.next = (c.next + 1) % len(c.entries) +} + +func (s *transcriptSnapshot) id() string { + return base64.RawURLEncoding.EncodeToString(s.key[:16]) +} + +// The cursor carries a signed, exclusive file position and the start of a +// large row if the preceding page stopped inside it. The file identity and +// profile stay in the agent's bounded snapshot cache. +func (s *transcriptSnapshot) cursor(pos, fragment int64, anchor [32]byte) string { + var token [80]byte + copy(token[:16], s.key[:16]) + binary.BigEndian.PutUint64(token[16:24], uint64(pos)) + binary.BigEndian.PutUint64(token[24:32], uint64(fragment)) + copy(token[32:64], anchor[:]) + copy(token[64:], s.sign(token[:64])) + return base64.RawURLEncoding.EncodeToString(token[:]) +} + +func (s *transcriptSnapshot) sign(data []byte) []byte { + mac := hmac.New(sha256.New, s.key[16:]) + _, _ = mac.Write(data) + return mac.Sum(nil)[:16] +} + +func (c *transcriptSnapshotCache) decode(encoded string) (*transcriptSnapshot, int64, int64, [32]byte) { + var anchor [32]byte + if len(encoded) != base64.RawURLEncoding.EncodedLen(80) { + return nil, 0, 0, anchor + } + token, err := base64.RawURLEncoding.DecodeString(encoded) + if err != nil || len(token) != 80 { + return nil, 0, 0, anchor + } + c.mu.Lock() + defer c.mu.Unlock() + for _, snapshot := range c.entries { + if snapshot != nil && bytes.Equal(snapshot.key[:16], token[:16]) && hmac.Equal(snapshot.sign(token[:64]), token[64:]) { + copy(anchor[:], token[32:64]) + return snapshot, int64(binary.BigEndian.Uint64(token[16:24])), int64(binary.BigEndian.Uint64(token[24:32])), anchor + } + } + return nil, 0, 0, anchor +} + +var errStaleTranscriptCursor = proto.NewError("chat.transcript-cursor-stale", "the transcript changed or its snapshot expired") + +// TranscriptPage reads a bounded page of the same retained transcript window +// as Transcript. Append-only changes remain beyond the snapshot's fixed end. +func (s *Service) TranscriptPage(ctx context.Context, raw json.RawMessage) (any, error) { + var p transcriptPageParams + if err := decodeParams(raw, &p, "chat.transcriptPage params must include sessionId"); err != nil { + return nil, err + } + if !sessionIDPattern.MatchString(p.SessionID) || (p.Cursor != "" && (len(p.Before) > 0 || p.UpTo != "")) { + return nil, protocolError("invalid chat.transcriptPage params") + } + page, err := s.readTranscriptPage(ctx, p, transcriptCapBytes, transcriptPageBytes) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + if err == errStaleTranscriptCursor { + return nil, err + } + return nil, requestFailed("chat.transcriptPage: %s", err) + } + return page, nil +} + +func (s *Service) readTranscriptPage(ctx context.Context, p transcriptPageParams, retention int64, budget int) (transcriptPage, error) { + page := transcriptPage{Lines: []json.RawMessage{}, Positions: []int64{}} + if err := ctx.Err(); err != nil { + return page, err + } + dir := configDir(p.ConfigDir) + path := transcriptPath(dir, p.SessionID) + var snapshot *transcriptSnapshot + var pos, fragment int64 + var boundary [32]byte + if p.Cursor != "" { + snapshot, pos, fragment, boundary = s.transcriptPages.decode(p.Cursor) + if snapshot == nil || snapshot.session != p.SessionID || snapshot.dir != dir || snapshot.path != path { + return page, errStaleTranscriptCursor + } + } + if path == "" { + return page, nil + } + file, err := os.Open(path) + if err != nil { + if snapshot != nil && os.IsNotExist(err) { + return page, errStaleTranscriptCursor + } + return page, err + } + defer file.Close() + info, err := file.Stat() + if err != nil { + return page, err + } + if snapshot == nil { + snapshot = &transcriptSnapshot{session: p.SessionID, dir: dir, path: path, info: info, floor: max(0, info.Size()-retention), end: info.Size()} + if _, err := rand.Read(snapshot.key[:]); err != nil { + return page, err + } + snapshot.anchor, err = snapshotAnchor(file, snapshot.floor, info.Size()) + if err != nil { + return page, err + } + if p.UpTo != "" || len(p.Before) > 0 { + snapshot.end, err = transcriptCutEnd(ctx, file, snapshot, p) + if err != nil { + return page, err + } + } + pos = snapshot.end + } else { + if err := snapshot.check(file, info); err != nil { + return page, err + } + actual, err := cursorAnchor(file, snapshot, pos) + if err != nil || actual != boundary { + return page, errStaleTranscriptCursor + } + } + page.Found = true + page.Truncated = snapshot.floor > 0 + page.Snapshot = snapshot.id() + scanner := transcriptReverseReader{ctx: ctx, file: file, floor: snapshot.floor} + if fragment >= 0 && p.Cursor != "" { + if pos, fragment, err = page.readFragment(&scanner, pos, fragment, budget, false); err != nil { + return page, err + } + } else { + if pos, fragment, err = page.readLines(&scanner, pos, budget); err != nil { + return page, err + } + } + if err := ctx.Err(); err != nil { + return page, err + } + current, err := os.Stat(path) + if os.IsNotExist(err) { + return page, errStaleTranscriptCursor + } + if err != nil { + return page, err + } + if err := snapshot.check(file, current); err != nil { + return page, err + } + if pos > snapshot.floor { + boundary, err := cursorAnchor(file, snapshot, pos) + if err != nil { + return page, err + } + page.Cursor = snapshot.cursor(pos, fragment, boundary) + if p.Cursor == "" { + s.transcriptPages.add(snapshot) + } + } + return page, nil +} + +func (s *transcriptSnapshot) check(file *os.File, info os.FileInfo) error { + if !os.SameFile(s.info, info) || info.Size() < s.info.Size() || + (info.Size() == s.info.Size() && info.ModTime() != s.info.ModTime()) { + return errStaleTranscriptCursor + } + anchor, err := snapshotAnchor(file, s.floor, s.info.Size()) + if err != nil || anchor != s.anchor { + return errStaleTranscriptCursor + } + return nil +} + +func snapshotAnchor(file *os.File, floor, end int64) ([32]byte, error) { + hash := sha256.New() + for _, offset := range []int64{floor, max(floor, end-transcriptAnchorBytes)} { + var buf [transcriptAnchorBytes]byte + part := buf[:min(transcriptAnchorBytes, end-offset)] + if _, err := file.ReadAt(part, offset); err != nil { + return [32]byte{}, err + } + _, _ = hash.Write(part) + } + return [32]byte(hash.Sum(nil)), nil +} + +func cursorAnchor(file *os.File, snapshot *transcriptSnapshot, pos int64) ([32]byte, error) { + var buf [transcriptAnchorBytes]byte + start := max(snapshot.floor, pos-transcriptAnchorBytes/2) + part := buf[:min(transcriptAnchorBytes, snapshot.end-start)] + _, err := file.ReadAt(part, start) + return sha256.Sum256(part), err +} + +// A cut uses the first matching UUID in the retained window, as the +// renderer's full-transcript cut did. It does not transfer the scan. +func transcriptCutEnd(ctx context.Context, file *os.File, snapshot *transcriptSnapshot, p transcriptPageParams) (int64, error) { + reader := bufio.NewReaderSize(io.NewSectionReader(file, snapshot.floor, snapshot.end-snapshot.floor), transcriptReadBlock) + before := make(map[string]bool, len(p.Before)) + for _, uuid := range p.Before { + before[uuid] = true + } + pos := snapshot.floor + for pos < snapshot.end { + start := pos + var line []byte + for { + if err := ctx.Err(); err != nil { + return 0, err + } + chunk, err := reader.ReadSlice('\n') + pos += int64(len(chunk)) + if start != snapshot.floor || snapshot.floor == 0 { + line = append(line, chunk...) + } + if err != bufio.ErrBufferFull { + if err != nil && err != io.EOF { + return 0, err + } + break + } + } + var entry struct { + UUID string `json:"uuid"` + Attachment struct { + Type string `json:"type"` + Source *string `json:"source_uuid"` + } `json:"attachment"` + } + if json.Unmarshal(line, &entry) != nil { + continue + } + if entry.Attachment.Type == "queued_command" && entry.Attachment.Source != nil { + entry.UUID = *entry.Attachment.Source + } + if before[entry.UUID] { + return start, nil + } + if p.UpTo != "" && p.UpTo == entry.UUID { + return pos, nil + } + } + return snapshot.end, nil +} + +type transcriptReverseReader struct { + ctx context.Context + file *os.File + floor, blockAt int64 + block []byte +} + +func (r *transcriptReverseReader) blockBefore(pos int64) ([]byte, error) { + if err := r.ctx.Err(); err != nil { + return nil, err + } + if len(r.block) == 0 || pos <= r.blockAt || pos > r.blockAt+int64(len(r.block)) { + r.blockAt = max(r.floor, pos-transcriptReadBlock) + if r.block == nil { + r.block = make([]byte, transcriptReadBlock) + } + r.block = r.block[:pos-r.blockAt] + if _, err := r.file.ReadAt(r.block, r.blockAt); err != nil { + return nil, err + } + } + return r.block[:pos-r.blockAt], nil +} + +func (r *transcriptReverseReader) previous(pos int64) (int64, int64, error) { + block, err := r.blockBefore(pos) + if err != nil { + return 0, 0, err + } + end := pos + if block[len(block)-1] == '\n' { + end-- + } + for at := end; at > r.floor; at = r.blockAt { + block, err := r.blockBefore(at) + if err != nil { + return 0, 0, err + } + if lf := bytes.LastIndexByte(block, '\n'); lf >= 0 { + return r.blockAt + int64(lf) + 1, end, nil + } + } + return r.floor, end, nil +} + +func (r *transcriptReverseReader) read(start, end int64) ([]byte, error) { + if start >= r.blockAt && end <= r.blockAt+int64(len(r.block)) { + return r.block[start-r.blockAt : end-r.blockAt], nil + } + data := make([]byte, end-start) + for pos := start; pos < end; pos += transcriptReadBlock { + if err := r.ctx.Err(); err != nil { + return nil, err + } + part := data[pos-start : min(end, pos+transcriptReadBlock)-start] + if _, err := r.file.ReadAt(part, pos); err != nil { + return nil, err + } + } + return data, nil +} + +func (p *transcriptPage) readLines(r *transcriptReverseReader, pos int64, budget int) (int64, int64, error) { + // Allow space for the RPC envelope, cursor and per-row positions. + remaining := budget - transcriptPageOverhead + turns, turnRows, turnPos := 0, 0, int64(0) + for pos > r.floor { + start, end, err := r.previous(pos) + if err != nil { + return 0, 0, err + } + if start == r.floor && r.floor != 0 { + pos = r.floor + break + } + line, err := r.read(start, end) + if err != nil { + return 0, 0, err + } + line = bytes.TrimSpace(line) + if !json.Valid(line) { + pos = start + continue + } + cost := len(line) + 24 + var wire []byte + if cost <= remaining { + wire, err = json.Marshal(json.RawMessage(line)) + if err != nil { + return 0, 0, err + } + cost = len(wire) + 24 + } + if cost > remaining { + if len(p.Lines) == 0 { + return p.readFragment(r, end, start, budget, true) + } + if turnRows > 0 { + p.Lines = p.Lines[:turnRows] + p.Positions = p.Positions[:turnRows] + pos = turnPos + } + break + } + remaining -= cost + p.Lines = append(p.Lines, wire) + p.Positions = append(p.Positions, start) + pos = start + if transcriptTurnStart(line) { + turns++ + turnRows, turnPos = len(p.Lines), pos + if turns == transcriptPageTurns { + break + } + } + } + for i, j := 0, len(p.Lines)-1; i < j; i, j = i+1, j-1 { + p.Lines[i], p.Lines[j] = p.Lines[j], p.Lines[i] + p.Positions[i], p.Positions[j] = p.Positions[j], p.Positions[i] + } + return pos, -1, nil +} + +func (p *transcriptPage) readFragment(r *transcriptReverseReader, end, start int64, budget int, last bool) (int64, int64, error) { + // Base64 keeps a cut through a UTF-8 character or JSON escape reversible. + pos := max(start, end-int64((budget-transcriptPageOverhead)/4*3)) + data, err := r.read(pos, end) + if err != nil { + return 0, 0, err + } + p.Fragment = &transcriptFragment{Position: start, Data: bytes.Clone(data), First: pos == start, Last: last} + if pos == start { + return pos, -1, nil + } + return pos, start, nil +} + +func transcriptTurnStart(line []byte) bool { + var row struct { + Type string `json:"type"` + IsSidechain bool `json:"isSidechain"` + IsMeta bool `json:"isMeta"` + PromptSource string `json:"promptSource"` + Message struct { + Content json.RawMessage `json:"content"` + } `json:"message"` + } + if json.Unmarshal(line, &row) != nil || row.Type != "user" || row.IsSidechain || row.IsMeta || row.PromptSource == "system" || len(row.Message.Content) == 0 { + return false + } + if row.Message.Content[0] == '"' { + return true + } + var blocks []struct { + Type string `json:"type"` + } + if json.Unmarshal(row.Message.Content, &blocks) != nil || len(blocks) == 0 { + return false + } + for _, block := range blocks { + if block.Type == "tool_result" { + return false + } + } + return true +} diff --git a/internal/chat/transcript_page_test.go b/internal/chat/transcript_page_test.go new file mode 100644 index 000000000..dfd10c292 --- /dev/null +++ b/internal/chat/transcript_page_test.go @@ -0,0 +1,155 @@ +package chat + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/nexus-code/nexus-code/internal/proto" +) + +func TestTranscriptPages(t *testing.T) { + const budget = 768 + const session = "session-for-test" + line := func(uuid, content string) string { + encoded, _ := json.Marshal(content) + return `{"type":"user","uuid":"` + uuid + `","message":{"content":` + string(encoded) + `}}` + } + old := line("old", "처음") + big := line("large", strings.Repeat("한<", 150)) + tip := line("recent", "최근") + base := old + "\r\n" + big + "\r\n" + tip + "\r\n" + withPartial := base + `{"type":` + + for _, tc := range []struct { + name, input, change string + retention int64 + upTo string + before []string + want []string + stale bool + }{ + {name: "UTF-8 CRLF large row and partial tail", input: withPartial, want: []string{old, big, tip}}, + {name: "complete row at EOF", input: strings.TrimSuffix(base, "\r\n"), want: []string{old, big, tip}}, + {name: "append preserves the old end", input: withPartial, change: "append", want: []string{old, big, tip}}, + {name: "retention discards the first fragment", input: base, retention: int64(len(base) - len(old)/2), want: []string{big, tip}}, + {name: "fork ends at the first inclusive UUID", input: base + old + "\n", upTo: "old", want: []string{old}}, + {name: "resume uses the first exclusive UUID", input: base + big + "\n", before: []string{"large", "recent"}, want: []string{old}}, + {name: "truncate", input: base, change: "truncate", stale: true}, + {name: "replace at the same size", input: base, change: "replace", stale: true}, + {name: "profile mismatch", input: base, change: "profile", stale: true}, + {name: "new agent", input: base, change: "agent", stale: true}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + project := filepath.Join(dir, "projects", "workspace") + if err := os.MkdirAll(project, 0700); err != nil { + t.Fatal(err) + } + path := filepath.Join(project, session+".jsonl") + write := func(path, data string) { + if err := os.WriteFile(path, []byte(data), 0600); err != nil { + t.Fatal(err) + } + } + write(path, tc.input) + service := New() + params := transcriptPageParams{TranscriptParams: TranscriptParams{SessionID: session, ConfigDir: dir}, UpTo: tc.upTo, Before: tc.before} + retention := tc.retention + if retention == 0 { + retention = transcriptCapBytes + } + ctx := context.Background() + page, err := service.readTranscriptPage(ctx, params, retention, budget) + if err != nil { + t.Fatal(err) + } + params.UpTo, params.Before = "", nil + switch tc.change { + case "append": + write(path, tc.input+`"added"}`+"\n"+old+"\n") + case "truncate": + write(path, old+"\n") + case "replace": + write(path+".new", tc.input) + if err := os.Rename(path+".new", path); err != nil { + t.Fatal(err) + } + case "profile": + params.ConfigDir = t.TempDir() + case "agent": + service = New() + } + if tc.stale { + if page.Cursor == "" { + t.Fatal("fixture did not page") + } + params.Cursor = page.Cursor + _, err := service.readTranscriptPage(ctx, params, retention, budget) + if !errors.Is(err, errStaleTranscriptCursor) { + t.Fatalf("expected stale cursor, got %v", err) + } + return + } + var actual []string + var fragments []byte + snapshot := page.Snapshot + for count := 0; ; count++ { + if count > 16 { + t.Fatal("cursor did not advance") + } + if !page.Found || page.Snapshot != snapshot || len(page.Positions) != len(page.Lines) { + t.Fatal("page metadata changed") + } + wire, err := proto.MarshalFrame(proto.Success("request-id", page)) + if err != nil || len(wire) > budget { + t.Fatalf("response length %d, %v", len(wire), err) + } + if page.Fragment != nil { + fragments = append(bytes.Clone(page.Fragment.Data), fragments...) + if page.Fragment.First { + actual = append([]string{string(bytes.TrimSpace(fragments))}, actual...) + fragments = nil + } + } + for i := len(page.Lines) - 1; i >= 0; i-- { + var compact bytes.Buffer + if err := json.Compact(&compact, page.Lines[i]); err != nil { + t.Fatal(err) + } + actual = append([]string{compact.String()}, actual...) + } + if page.Cursor == "" { + break + } + params.Cursor = page.Cursor + page, err = service.readTranscriptPage(ctx, params, retention, budget) + if err != nil { + t.Fatal(err) + } + } + if len(fragments) != 0 || !equalRows(actual, tc.want) { + t.Fatalf("assembled rows differ: %d vs %d", len(actual), len(tc.want)) + } + }) + } +} + +func equalRows(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i, want := range b { + wire, _ := json.Marshal(json.RawMessage(want)) + got, _ := json.Marshal(json.RawMessage(a[i])) + if !bytes.Equal(got, wire) { + return false + } + } + return true +} From 1de19b86042420f64cf3ef97e1584c47c929dc69 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 22:45:47 +0900 Subject: [PATCH 2/6] feat(chat): expose transcript pages over desktop IPC --- src/main/features/chat/host.ts | 27 ++++++++++++++++++++++ src/main/features/chat/ipc.ts | 24 ++++++++++++++++++++ src/shared/ipc/contract.ts | 31 ++++++++++++++++++++++++++ tests/unit/main/chat/host.test.ts | 37 ++++++++++++++++++++++++++++++- 4 files changed, 118 insertions(+), 1 deletion(-) diff --git a/src/main/features/chat/host.ts b/src/main/features/chat/host.ts index e58a07ed4..e077ca5c9 100644 --- a/src/main/features/chat/host.ts +++ b/src/main/features/chat/host.ts @@ -15,6 +15,7 @@ import { SHAREABLE, } from "../../../shared/agent-profiles/profiles"; import { type ClaudeTurnResult, claudeTurnResult } from "../../../shared/claude/turn-result"; +import type { TranscriptPageResult } from "../../../shared/ipc/contract"; import { createLogger } from "../../../shared/log/main"; import type { ChatAgent } from "../../../shared/sessions/task-agent"; import type { AgentChannel, ChannelLifecycleEvent } from "../../infra/agent/channel"; @@ -410,6 +411,32 @@ export class ChatHost { }); } + async transcriptPage( + workspaceId: string, + sessionId: string, + profileId: string | undefined, + page: { cursor?: string; upTo?: string; before?: string[] }, + ): Promise { + const args = { sessionId, ...this.configDir(workspaceId, profileId) }; + const channel = await this.channelFor(workspaceId); + try { + return await channel.call("chat.transcriptPage", { ...args, ...page }); + } catch (error) { + if (page.cursor || (error as { code?: unknown } | null)?.code !== "unsupported-method") { + throw error; + } + const result = await channel.call< + Pick + >("chat.transcript", args); + // The renderer applies its cut to the old agent's unpaged result. + return { + found: result.found === true, + lines: result.lines ?? [], + truncated: result.truncated === true, + }; + } + } + async subagentTranscript( workspaceId: string, sessionId: string, diff --git a/src/main/features/chat/ipc.ts b/src/main/features/chat/ipc.ts index eed19ec72..1fe074d98 100644 --- a/src/main/features/chat/ipc.ts +++ b/src/main/features/chat/ipc.ts @@ -3,6 +3,7 @@ import { ipcContract } from "../../../shared/ipc/contract"; import { type IpcResult, ipcErr, ipcOk } from "../../../shared/ipc/result"; import { broadcast, register, validateArgs } from "../../infra/ipc-router"; +import { agentCallError } from "../../infra/ipc-router/agent-errors"; import { AgentProfileSelectionError, ChatHost, type ChatHostOptions } from "./host"; import { OAuthCallbacksClosedError } from "./oauth-callback"; @@ -107,6 +108,29 @@ export function registerChatChannel(options: Omit) truncated: result.truncated === true, }); }), + transcriptPage: withProfileError(async (args: unknown) => { + const { workspaceId, sessionId, profileId, ...page } = validateArgs( + c.transcriptPage.args, + args, + ); + try { + return ipcOk(await host.transcriptPage(workspaceId, sessionId, profileId, page)); + } catch (error) { + const code = (error as { code?: unknown } | null)?.code; + if (code === "chat.transcript-cursor-stale") { + return ipcErr( + code, + "The chat history changed. Reopen the conversation to read it again.", + { + category: "failed", + }, + ); + } + const failure = agentCallError(error); + if (failure) return failure; + throw error; + } + }), subagentTranscript: withProfileError(async (args: unknown) => { const { workspaceId, sessionId, agentId, toolUseId, profileId } = validateArgs( c.subagentTranscript.args, diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index 5ebfc0a45..1ca4f2387 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -590,6 +590,25 @@ const SshConfigHostSchema = z.object({ // IPC contract map // --------------------------------------------------------------------------- +const transcriptPageResult = z.object({ + found: z.boolean(), + lines: z.array(z.unknown()), + truncated: z.boolean(), + positions: z.array(z.number().int().nonnegative()).optional(), + snapshot: z.string().optional(), + cursor: z.string().optional(), + fragment: z + .object({ + position: z.number().int().nonnegative(), + data: z.string(), + first: z.boolean(), + last: z.boolean(), + }) + .optional(), +}); + +export type TranscriptPageResult = z.infer; + export const ipcContract = { workspace: { call: { @@ -1016,6 +1035,18 @@ export const ipcContract = { truncated: z.boolean(), }), ), + /** An internal page of a Claude transcript, from newest to oldest. */ + transcriptPage: call( + z.object({ + workspaceId: WorkspaceIdPrimitive, + sessionId: z.string().max(128), + profileId: z.string().max(64).optional(), + cursor: z.string().max(128).optional(), + upTo: z.string().max(128).optional(), + before: z.array(z.string().max(128)).optional(), + }), + transcriptPageResult, + ), /** * One subagent's messages, which Claude Code keeps apart from its * session's transcript: found by its agent id (its Agent call's result diff --git a/tests/unit/main/chat/host.test.ts b/tests/unit/main/chat/host.test.ts index 8d1f58e52..9a25e838a 100644 --- a/tests/unit/main/chat/host.test.ts +++ b/tests/unit/main/chat/host.test.ts @@ -40,6 +40,7 @@ class FakeChannel implements AgentChannel { }; versionOutput = "2.1.318 (Claude Code)\n"; versionWait?: Promise; + transcriptPageError?: string; private readonly listeners = new Map>(); private readonly lifecycle = new Set(); @@ -51,6 +52,10 @@ class FakeChannel implements AgentChannel { return { code: 0, stdout: this.versionOutput, stderr: "" } as T; } if (method === "chat.start") return { pid: 42 } as T; + if (method === "chat.transcriptPage" && this.transcriptPageError) { + throw Object.assign(new Error("transcript page failed"), { code: this.transcriptPageError }); + } + if (method === "chat.transcript") return { found: true, lines: [] } as T; return {} as T; } fire(): void {} @@ -112,6 +117,27 @@ function setup( return { channel, events, status, host, providerReady: (id: string) => providerReady?.(id) }; } +test.each([ + ["unsupported-method", undefined, true], + ["unsupported-method", "snapshot-cursor", false], + ["server.request-failed", undefined, false], + ["transport.timeout", undefined, false], +] as const)("transcript page fallback with %s and cursor %s", async (code, cursor, fallback) => { + const { host, channel } = setup(); + channel.transcriptPageError = code; + const page = host.transcriptPage(WS, "session-id", undefined, { cursor }); + if (fallback) { + expect(await page).toEqual({ found: true, lines: [], truncated: false }); + expect(channel.calls.map((call) => call.method)).toEqual([ + "chat.transcriptPage", + "chat.transcript", + ]); + } else { + await expect(page).rejects.toMatchObject({ code }); + expect(channel.calls.map((call) => call.method)).toEqual(["chat.transcriptPage"]); + } +}); + describe("chat launch", () => { test("resume and fork add their flags after the stream-json ones", () => { expect(claudeTabArgs({})).toEqual([ @@ -326,16 +352,24 @@ describe("ChatHost", () => { }); expect((start as { env: Record }).env).not.toHaveProperty("NEXUS_OTHER"); await host.transcript(WS, "session"); + await host.transcriptPage(WS, "session", undefined, {}); await host.deleteSession(WS, "/repo", "session"); expect( channel.calls.filter( - ({ method }) => method === "chat.transcript" || method === "chat.deleteSession", + ({ method }) => + method === "chat.transcript" || + method === "chat.transcriptPage" || + method === "chat.deleteSession", ), ).toEqual([ { method: "chat.transcript", params: { sessionId: "session", configDir: "/profiles/default" }, }, + { + method: "chat.transcriptPage", + params: { sessionId: "session", configDir: "/profiles/default" }, + }, { method: "chat.deleteSession", params: { sessionId: "session", cwd: "/repo", configDir: "/profiles/default" }, @@ -351,6 +385,7 @@ describe("ChatHost", () => { reason: "failed", }); await expect(host.transcript(WS, "session", id)).rejects.toThrow(/profile/i); + await expect(host.transcriptPage(WS, "session", id, {})).rejects.toThrow(/profile/i); await expect(host.deleteSession(WS, "/repo", "session", id)).rejects.toThrow(/profile/i); } await expect(host.stageThread(WS, "thread", { fromProfileId: "missing" })).rejects.toThrow( From abbe91f91b9d21e9648976a72148272b9cc3e4ae Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 22:57:10 +0900 Subject: [PATCH 3/6] feat(chat): show Claude transcript history on demand --- src/renderer/components/chat/claude-tab.tsx | 30 +- src/renderer/components/chat/message-list.tsx | 78 ++++- .../services/chat/claude/controller.ts | 275 +++++++++++++++--- src/renderer/services/chat/claude/history.ts | 37 ++- .../services/chat/claude/transcript-pages.ts | 86 ++++++ src/renderer/services/chat/store.ts | 2 + src/renderer/services/cli/chat-actions.ts | 19 +- src/shared/i18n/locales/en/common.json | 1 + src/shared/i18n/locales/ko/common.json | 1 + .../chat/claude/controller-mode.test.ts | 2 +- .../claude/controller-open-to-read.test.ts | 168 ++++++++++- .../services/chat/claude/history.test.ts | 47 +++ .../services/chat/controller-card.test.ts | 2 +- .../chat/controller-switch-profile.test.ts | 4 +- 14 files changed, 676 insertions(+), 76 deletions(-) create mode 100644 src/renderer/services/chat/claude/transcript-pages.ts diff --git a/src/renderer/components/chat/claude-tab.tsx b/src/renderer/components/chat/claude-tab.tsx index df8f8dc1f..e21217488 100644 --- a/src/renderer/components/chat/claude-tab.tsx +++ b/src/renderer/components/chat/claude-tab.tsx @@ -17,6 +17,7 @@ import { type PermissionAnswer, pruneAttachmentsOnce, } from "../../services/chat/claude/controller"; +import { historyForDisplay } from "../../services/chat/claude/history"; import { runAppCommand } from "../../services/chat/claude/run-command"; import { MIN_CLAUDE_VERSION } from "../../services/chat/claude/versions"; import { filesThere } from "../../services/chat/file-presence"; @@ -223,19 +224,25 @@ export function ClaudeTabView({ workspaceId, tabId, props, isVisible }: ClaudeTa const running = state.model.running; const canFork = controller.forkPoint("", { before: false }) !== null; const asking = state.model.permissions; + const unverifiedStart = controller.unverifiedHistoryStart(); // Set below, where the agents are known; read when a row renders. const taskShower = useRef>(() => undefined); const actions = useMemo( () => ({ running, canFork, + canForkItem: (item) => + !!item.uuid && + (item.kind !== "user" || (item.state === "taken" && item.uuid !== unverifiedStart)), + canRewindItem: (item) => + item.state === "taken" && !!item.uuid && item.uuid !== unverifiedStart, onRewind: (item) => setRewinding(item), onFork: (item) => forkFrom(controller, workspaceId, props.cwd, item), onBackground: (toolUseId) => backgroundCall(controller, toolUseId), waiting: new Set(asking.flatMap((p) => (p.toolUseId ? [p.toolUseId] : []))), taskShower: (item) => taskShower.current(item), }), - [running, canFork, controller, workspaceId, props.cwd, asking], + [running, canFork, controller, workspaceId, props.cwd, asking, unverifiedStart], ); // Where the side panel goes follows the tab's width. @@ -303,7 +310,11 @@ export function ClaudeTabView({ workspaceId, tabId, props, isVisible }: ClaudeTa const printRuns = usePrintRuns(workspaceId, tabId, isVisible); const runRows = useMemo(() => printRunRows(printRuns), [printRuns]); // Its history's subagents too, which ended: a conversation resumed shows them. - const pastModel = state.history; + const pastHistory = state.history; + const pastModel = useMemo( + () => (pastHistory ? historyForDisplay(pastHistory) : null), + [pastHistory], + ); const { tasks: agentTasks, tools: agentTools, agentItems, items: agentCalls } = state.model; const pastAgents = useMemo(() => (pastModel ? pastAgentsOf(pastModel) : []), [pastModel]); const liveAgents = useMemo( @@ -668,13 +679,26 @@ export function ClaudeTabView({ workspaceId, tabId, props, isVisible }: ClaudeTa tabId={tabId} cwd={props.cwd} rootPath={rootPath} - history={state.history} + history={pastModel} model={state.model} actions={shown ? undefined : actions} items={shownTranscript} reveal={shown ? null : callAsk} moves={props.moves} relayed={props.relayed} + older={ + !shown && state.historyPage + ? { + ...state.historyPage, + load: () => + void controller + .loadEarlier() + .catch((error: Error) => + showToast({ kind: "error", message: error.message }), + ), + } + : undefined + } empty={ state.phase === "ready" || state.phase === "ended" ? (
diff --git a/src/renderer/components/chat/message-list.tsx b/src/renderer/components/chat/message-list.tsx index a28b070f5..d46e948cf 100644 --- a/src/renderer/components/chat/message-list.tsx +++ b/src/renderer/components/chat/message-list.tsx @@ -126,7 +126,9 @@ interface MessageListProps { } export interface OlderMessages { - count: number; + count?: number; + /** A local transcript cursor has an unknown number of preceding messages. */ + hasEarlier?: boolean; loading: boolean; load(): void; } @@ -239,7 +241,13 @@ export function MessageList({ // Earlier messages asked for beyond the last WINDOW_ITEMS, and where the // view was when they were, to stay on what it showed. const [more, setMore] = useState(0); - const anchor = useRef<{ height: number; top: number } | null>(null); + const anchor = useRef<{ + height: number; + top: number; + row?: HTMLElement; + rowTop?: number; + historyCount?: number; + } | null>(null); const toBottom = useCallback(() => { const el = scrollRef.current; @@ -315,7 +323,8 @@ export function MessageList({ [items, model.items, relayed], ); const streaming = items ? null : model.streaming; - const nothing = historyItems.length === 0 && liveItems.length === 0 && !streaming; + const nothing = + historyItems.length === 0 && liveItems.length === 0 && !streaming && !older?.hasEarlier; emptyShown.current = nothing && empty !== undefined; const tools = useMemo( () => (history ? { ...history.tools, ...model.tools } : model.tools), @@ -419,25 +428,60 @@ export function MessageList({ const unread = older?.count ?? 0; const showEarlier = useCallback(() => { const el = scrollRef.current; - if (el) anchor.current = { height: el.scrollHeight, top: el.scrollTop }; + if (el) { + const top = el.getBoundingClientRect().top; + const row = Array.from( + contentRef.current?.querySelectorAll("[data-chat-row]") ?? [], + ) + .map((wrapper) => wrapper.firstElementChild) + .find( + (node): node is HTMLElement => + node instanceof HTMLElement && node.getBoundingClientRect().bottom > top, + ); + anchor.current = { + height: el.scrollHeight, + top: el.scrollTop, + row, + rowTop: row?.getBoundingClientRect().top, + historyCount: start === 0 && older?.hasEarlier ? historyItems.length : undefined, + }; + } stuck.current = false; if (start > 0) setMore((m) => m + WINDOW_ITEMS); else older?.load(); - }, [start, older]); + }, [start, older, historyItems.length]); // Messages read in before the first ones render at once. const wasUnread = useRef(unread); useLayoutEffect(() => { - const read = wasUnread.current - unread; + const count = wasUnread.current - unread; wasUnread.current = unread; - if (read > 0) setMore((m) => m + read); + if (count > 0) setMore((m) => m + count); }, [unread]); - // The messages put above keep the view on what it showed. + const historyRead = useRef(false); + useLayoutEffect(() => { + const before = anchor.current?.historyCount; + if (before === undefined || older?.loading) return; + const added = historyItems.length - before; + // A page that completed a tool or only carried part of a large row can add no items. + if (added > 0) { + historyRead.current = true; + setMore((m) => m + added); + } else { + anchor.current = null; + } + }, [historyItems.length, older?.loading]); + // Keep the same row at the same height, even when live items also arrived below it. useLayoutEffect(() => { const el = scrollRef.current; const was = anchor.current; - if (!el || !was || more === 0) return; + if (!el || !was || more === 0 || (was.historyCount !== undefined && !historyRead.current)) + return; anchor.current = null; - el.scrollTop = was.top + (el.scrollHeight - was.height); + historyRead.current = false; + el.scrollTop = + was.row?.isConnected && was.rowTop !== undefined + ? el.scrollTop + was.row.getBoundingClientRect().top - was.rowTop + : was.top + (el.scrollHeight - was.height); ownTop.current = el.scrollTop; lastTop.current = el.scrollTop; }, [more]); @@ -477,19 +521,23 @@ export function MessageList({ )} > {nothing && empty} - {start + unread > 0 && ( + {(start + unread > 0 || older?.hasEarlier) && ( )} {historyItems.slice(Math.min(start, historyItems.length)).map((item) => ( - +
+ +
{movesAfter.get(item)?.map((move) => ( ))} @@ -497,7 +545,9 @@ export function MessageList({ ))} {liveItems.slice(Math.max(0, start - historyItems.length)).map((item) => ( - +
+ +
{movesAfter.get(item)?.map((move) => ( ))} diff --git a/src/renderer/services/chat/claude/controller.ts b/src/renderer/services/chat/claude/controller.ts index 425decdb1..5994ecbdb 100644 --- a/src/renderer/services/chat/claude/controller.ts +++ b/src/renderer/services/chat/claude/controller.ts @@ -62,6 +62,7 @@ import { } from "./history"; import { effortToApply, remoteAtStartup } from "./settings-defaults"; import { applyLines, endGoal } from "./stream-model"; +import { TranscriptPages } from "./transcript-pages"; import { isSupportedClaude, supportsControl, usageSkipsBehaviors } from "./versions"; const log = createLogger("chat"); @@ -108,6 +109,15 @@ const CONTEXT_RETRY_MS = 3_000; const MCP_EMPTY_RETRY_MS = 2_000; const MCP_EMPTY_ASKS = 4; +interface TranscriptSource { + sessionId: string; + profileId?: string; + cut?: HistoryCut; + title?: string; + /** The live log kept after the agent that held it was replaced. */ + appended?: ChatModel; +} + interface ReplayResult { found: boolean; running: boolean; @@ -264,6 +274,13 @@ export class ChatController { /** While opening: resolves once the conversation is shown, perhaps before its program is ready. */ private shown: Promise | null = null; private disposed = false; + private transcriptSource: TranscriptSource | undefined; + private transcriptPages: TranscriptPages | undefined; + private earlierHistoryUnknown = false; + private liveGoalChanged = false; + private fullTranscript: Promise | undefined; + /** Public pages and watches use complete history and its original item keys. */ + private publicHistory = false; private titled = false; /** Subagents whose file is being read (loadSubagent), and those found nowhere. */ private subagentsReading = new Set(); @@ -372,9 +389,13 @@ export class ChatController { * shown: the transcript read, while a program started on it may still be * starting. Another device reading the chat sees it without waiting. */ - openToRead(): Promise { - const opening = this.open(); - return this.shown ? Promise.race([opening, this.shown]) : opening; + async openToRead(waitForProgram = false): Promise { + this.publicHistory = true; + if (this.opening || this.state.phase === "idle") { + const opening = this.open(); + await (!waitForProgram && this.shown ? Promise.race([opening, this.shown]) : opening); + } + await this.completeTranscript(); } private async doOpen(shown: () => void): Promise { @@ -403,7 +424,8 @@ export class ChatController { // is in the transcript. if (this.state.model.resumed) await this.loadResumedHistory(); // A goal met while no window looked on. - if (!this.state.model.running) void this.syncGoal(); + if (!this.state.model.running) void this.syncGoal(!this.publicHistory); + shown(); return; } // The agent has no log: a new tab, or one whose agent restarted. @@ -447,52 +469,183 @@ export class ChatController { return from && !sameProfile(from, this.target.profileId) ? from : undefined; } + private transcriptArgs({ sessionId, profileId }: TranscriptSource) { + return { workspaceId: this.target.workspaceId, sessionId, ...profileArg(profileId) }; + } + private async loadTranscript( sessionId: string, cut?: HistoryCut, profileId = this.target.profileId, ): Promise { + this.resetTranscript(); + const fork = this.target.fork; + const source = { + sessionId, + profileId, + cut, + title: fork?.sessionId === sessionId ? fork.title : undefined, + }; + this.transcriptSource = source; + const args = this.transcriptArgs(source); try { - const result = unwrapIpcResult( - await ipcCallResult("chat", "transcript", { - workspaceId: this.target.workspaceId, - sessionId, - ...profileArg(profileId), + if (this.publicHistory) { + await this.readFullTranscript(source); + return; + } + const page = unwrapIpcResult( + await ipcCallResult("chat", "transcriptPage", { + ...args, + upTo: cut?.upTo, + before: cut?.before ? [...cut.before] : undefined, }), ); - if (!result.found) return; - const read = historyModel(result.lines, cut); - // A task's end the log tells too is the log's: it has no uuid to cut at. - const told = new Set( - this.state.model.items.flatMap((item) => (item.kind === "task_end" ? [item.key] : [])), - ); - const history = - told.size > 0 ? { ...read, items: read.items.filter((item) => !told.has(item.key)) } : read; + if (this.disposed || this.transcriptSource !== source || !page.found) return; + if (page.snapshot) { + const pages = new TranscriptPages(page, page.snapshot); + this.transcriptPages = pages; + this.publishTranscript(source, pages.project(), pages.lines, page.truncated, true); + } else { + this.publishTranscript( + source, + historyModel(page.lines, cut), + page.lines, + page.truncated, + true, + ); + } + } catch (error) { + log.warn(`transcript of ${sessionId} not read: ${(error as Error).message}`); + } + } + + private async readFullTranscript(source: TranscriptSource): Promise { + const result = unwrapIpcResult( + await ipcCallResult("chat", "transcript", this.transcriptArgs(source)), + ); + if (this.disposed || this.transcriptSource !== source) return; + if (!result.found && this.transcriptPages) + throw new Error("The transcript is no longer available"); + if (!result.found) return; + const live = source.appended ?? this.state.model; + const before = + this.transcriptPages && + !source.cut && + (source.appended || live.sessionId === source.sessionId) + ? modelUuids(live) + : undefined; + const history = historyModel( + result.lines, + source.cut ?? (before?.size ? { before } : undefined), + ); + this.transcriptPages = undefined; + this.publishTranscript( + source, + source.appended ? { ...joinHistory(history, source.appended), goal: history.goal } : history, + result.lines, + result.truncated, + true, + ); + } + + private completeTranscript(): Promise | undefined { + if (this.fullTranscript) return this.fullTranscript; + const source = this.transcriptSource; + if (!source || !this.transcriptPages) return; + const read = this.readFullTranscript(source).finally(() => { + if (this.fullTranscript === read) this.fullTranscript = undefined; + }); + this.fullTranscript = read; + return read; + } + + async loadEarlier(): Promise { + const source = this.transcriptSource; + const pages = this.transcriptPages; + const cursor = pages?.cursor; + if (!source || !pages || !cursor || this.state.historyPage?.loading) return; + const current = () => + !this.disposed && + !this.changingSession && + this.transcriptSource === source && + this.transcriptPages === pages; + this.update((prev) => ({ ...prev, historyPage: { hasEarlier: true, loading: true } })); + try { + const result = await ipcCallResult("chat", "transcriptPage", { + ...this.transcriptArgs(source), + cursor, + }); + if (!current()) return; + if (!result.ok && result.kind === "chat.transcript-cursor-stale") pages.cursor = undefined; + const page = unwrapIpcResult(result); + pages.prepend(page); + this.publishTranscript(source, pages.project(), pages.lines, pages.truncated, false); + } catch (error) { + if (current()) throw error; + } finally { + if (this.transcriptPages === pages && this.transcriptSource === source) { + this.update((prev) => ({ + ...prev, + historyPage: { hasEarlier: !!pages.cursor, loading: false }, + })); + } + } + } + + private publishTranscript( + source: TranscriptSource, + read: ChatModel, + lines: readonly unknown[], + truncated: boolean, + initial: boolean, + ): void { + const pages = this.transcriptPages; + this.earlierHistoryUnknown = truncated || pages?.cursor !== undefined; + // A task's end the log tells too is the log's: it has no uuid to cut at. + const told = new Set( + this.state.model.items.flatMap((item) => (item.kind === "task_end" ? [item.key] : [])), + ); + const history = + told.size > 0 ? { ...read, items: read.items.filter((item) => !told.has(item.key)) } : read; + const title = source.title ?? (source.cut ? undefined : sessionTitleOf(lines)); + if (!this.titled && title) { + this.titled = true; + this.hooks.onTitle?.(title); + } else if (!this.titled && (!pages || !this.earlierHistoryUnknown)) { const first = history.items.find((item) => item.kind === "user" && item.text.trim()); - // A session that was named, by the user or by Claude, is called by its - // name; a branch, by the one it is to take. - const fork = this.target.fork; - const branch = fork?.sessionId === sessionId ? fork.title : undefined; - const title = branch ?? (cut ? undefined : sessionTitleOf(result.lines)); - if (!this.titled && title) { - this.titled = true; - this.hooks.onTitle?.(title); - } else if (!this.titled && first?.kind === "user") { + if (first?.kind === "user") { this.titled = true; this.hooks.onFirstMessage?.(first.text.trim()); } - this.update((prev) => ({ + } + this.update((prev) => { + const agentItems = { ...history.agentItems, ...prev.history?.agentItems }; + return { ...prev, - history: history.items.length > 0 ? history : null, - // The goal the session had goes on with it: Claude Code sets it again. + history: + history.items.length > 0 || Object.keys(agentItems).length > 0 + ? { ...history, agentItems } + : null, + historyPage: pages ? { hasEarlier: !!pages.cursor, loading: false } : undefined, + // A previously unread page must not replace a goal that the live log set or cleared. model: - prev.model.goal === undefined && history.goal + (initial || !prev.history?.goal) && + !this.liveGoalChanged && + prev.model.goal === undefined && + history.goal ? { ...prev.model, goal: history.goal } : prev.model, - })); - } catch (err) { - log.warn(`transcript of ${sessionId} not read: ${(err as Error).message}`); - } + }; + }); + } + + private resetTranscript(): void { + this.transcriptSource = undefined; + this.transcriptPages = undefined; + this.fullTranscript = undefined; + this.earlierHistoryUnknown = false; + this.liveGoalChanged = false; + if (this.state.historyPage) this.update((prev) => ({ ...prev, historyPage: undefined })); } /** @@ -744,11 +897,26 @@ export class ChatController { if (!sessionId) return null; if (!before) return { sessionId, at: uuid }; const at = uuidBefore(joinHistory(this.state.history, this.state.model), uuid); + if (!at && this.earlierHistoryUnknown) { + throw new Error("Read earlier messages before using this point"); + } return at ? { sessionId, at } : null; } + /** The oldest visible message has no verified predecessor yet. */ + unverifiedHistoryStart(): string | undefined { + if (!this.earlierHistoryUnknown) return; + const { history, model } = this.state; + for (const items of [history?.items ?? [], model.items]) { + for (const item of items) { + if ((item.kind === "user" || item.kind === "assistant") && item.uuid) return item.uuid; + } + } + } + /** What rewinding the files to before a message would change. */ async previewRewind(uuid: string): Promise { + this.forkPoint(uuid, { before: true }); if (!(await this.ensureRunning())) throw new Error("the program is not running"); return rewindOf(await this.request("rewind_files", { user_message_id: uuid, dry_run: true })); } @@ -766,18 +934,20 @@ export class ChatController { const uuid = item.uuid; if (!uuid) throw new Error("the message has no uuid yet"); if (this.state.model.running) throw new Error("a turn is running"); + const fork = this.forkPoint(uuid, { before: true }) ?? undefined; + const incomplete = this.earlierHistoryUnknown; if (files) { if (!(await this.ensureRunning())) throw new Error("the program is not running"); const result = rewindOf(await this.request("rewind_files", { user_message_id: uuid })); if (!result.canRewind) throw new Error(result.error ?? "the files were not rewound"); } const all = joinHistory(this.state.history, this.state.model); - const fork = this.forkPoint(uuid, { before: true }) ?? undefined; const { workspaceId, tabId } = this.target; if (this.state.model.process === "running") { await ipcCallResult("chat", "stop", { workspaceId, tabId }); } this.flushNow(); + this.resetTranscript(); this.sessionId = undefined; this.target = { ...this.target, sessionId: undefined, fork }; this.hooks.onTarget?.(fork ? { fork } : {}); @@ -789,6 +959,8 @@ export class ChatController { model: { ...emptyModel(), lastSeq: prev.model.lastSeq }, ...(draft ? { draft: { text: item.text, images: item.images, nonce: Date.now() } } : {}), })); + if (incomplete && fork) + await this.loadTranscript(fork.sessionId, forkCut(fork), this.forkProfile()); if (await this.start({ ...this.startArgs(), resetLog: true })) await this.rebuild(); } @@ -877,6 +1049,10 @@ export class ChatController { this.flushNow(); if (this.disposed) throw new Error("the tab closed"); const source = this.state; + const transcriptSource = this.transcriptSource; + const transcriptPages = this.transcriptPages; + const earlierHistoryUnknown = this.earlierHistoryUnknown; + const liveGoalChanged = this.liveGoalChanged; const target = this.target; const sessionId = this.sessionId; const sessionName = this.sessionName; @@ -884,9 +1060,15 @@ export class ChatController { const pendingName = this.pendingName; const named = this.named; const lastMode = this.lastMode; + this.resetTranscript(); try { await change(shown); } catch (error) { + this.resetTranscript(); + this.transcriptSource = transcriptSource && { ...transcriptSource }; + this.transcriptPages = transcriptPages; + this.earlierHistoryUnknown = earlierHistoryUnknown; + this.liveGoalChanged = liveGoalChanged; this.target = target; this.sessionId = sessionId; this.sessionName = sessionName; @@ -897,6 +1079,7 @@ export class ChatController { this.startup.failed = true; this.update((prev) => ({ ...source, + historyPage: source.historyPage && { ...source.historyPage, loading: false }, phase: "failed", error: (error as Error).message, model: { @@ -944,6 +1127,7 @@ export class ChatController { await this.switchProfile(profileId); return; } + await this.completeTranscript(); await this.changeSession(async (shown) => { // The program stopped here told of its exit; the conversation goes on. const model = this.state.model; @@ -1094,7 +1278,20 @@ export class ChatController { this.update((prev) => ({ ...prev, phase: replay.running ? "ready" : "ended" })); return; } - // A new agent: what the tab showed becomes its history. + // A new agent: what the tab showed becomes its history. Its cursor died with the old agent. + const earlierHistoryUnknown = this.earlierHistoryUnknown; + const source = this.transcriptSource; + const pages = this.transcriptPages; + this.resetTranscript(); + this.earlierHistoryUnknown = earlierHistoryUnknown; + if (source && pages) { + this.transcriptSource = { + ...source, + appended: joinHistory(source.appended ?? null, this.state.model), + }; + pages.cursor = undefined; + this.transcriptPages = pages; + } this.update((prev) => ({ ...prev, phase: "ended", @@ -1778,12 +1975,12 @@ export class ChatController { * has it running: a check that finds it met, or impossible, ends the * turn, and only the transcript says so. */ - private async syncGoal(): Promise { + private async syncGoal(latestPage = false): Promise { const sessionId = this.state.model.sessionId ?? this.sessionId; if (this.disposed || this.state.model.goal?.status !== "active" || !sessionId) return; try { const result = unwrapIpcResult( - await ipcCallResult("chat", "transcript", { + await ipcCallResult("chat", latestPage ? "transcriptPage" : "transcript", { workspaceId: this.target.workspaceId, sessionId, ...profileArg(this.target.profileId), @@ -2055,6 +2252,7 @@ export class ChatController { } private afterModel(before: ChatModel, model: ChatModel): void { + if (before.goal !== model.goal) this.liveGoalChanged = true; // The mode the program is in, for one started again in the tab to go on in. if (model.permissionMode) this.lastMode = model.permissionMode; if (model.sessionId && model.sessionId !== this.sessionId) { @@ -2072,6 +2270,7 @@ export class ChatController { } // What the tab showed before a /clear, a command's card too, is another session's. if ((model.clears ?? 0) !== (before.clears ?? 0)) { + this.resetTranscript(); this.update((prev) => prev.history || prev.card ? { ...prev, history: null, card: undefined } : prev, ); diff --git a/src/renderer/services/chat/claude/history.ts b/src/renderer/services/chat/claude/history.ts index c27480b2c..92693353b 100644 --- a/src/renderer/services/chat/claude/history.ts +++ b/src/renderer/services/chat/claude/history.ts @@ -29,13 +29,17 @@ function rec(value: unknown): Rec | null { } /** Turns transcript entries into stream-json lines. */ -export function transcriptLines(entries: readonly unknown[]): TranscriptLine[] { +export function transcriptLines( + entries: readonly unknown[], + positions?: readonly number[], +): TranscriptLine[] { const lines: TranscriptLine[] = []; - for (const raw of entries) { + for (const [index, raw] of entries.entries()) { + const seq = positions ? positions[index] + 1 : lines.length + 1; const entry = rec(raw); if (!entry || entry.isSidechain === true) continue; // A message that came while a turn ran is kept apart from the others. - const queued = queuedLine(entry, lines.length + 1); + const queued = queuedLine(entry, seq); if (queued) { lines.push(queued); continue; @@ -48,7 +52,7 @@ export function transcriptLines(entries: readonly unknown[]): TranscriptLine[] { origin !== undefined && (SENDER_KINDS.has(origin) || origin === "task-notification"); if (entry.isMeta === true && !told) continue; if (entry.type === "user" && entry.promptSource === "system" && !told) continue; - const goal = goalLine(entry, lines.length + 1); + const goal = goalLine(entry, seq); if (goal) { lines.push(goal); continue; @@ -66,7 +70,7 @@ export function transcriptLines(entries: readonly unknown[]): TranscriptLine[] { } if (entry.type === "assistant") { lines.push({ - seq: lines.length + 1, + seq, dir: "out", replay: true, message: { type: "assistant", message, uuid: entry.uuid, timestamp: entry.timestamp }, @@ -75,7 +79,7 @@ export function transcriptLines(entries: readonly unknown[]): TranscriptLine[] { const content = message.content; const results = Array.isArray(content) && content.some((b) => rec(b)?.type === "tool_result"); lines.push({ - seq: lines.length + 1, + seq, dir: "out", replay: true, message: results @@ -290,11 +294,28 @@ export function cutEntries(entries: readonly unknown[], cut: HistoryCut = {}): u } /** The model of a transcript: its items and tools, nothing running. */ -export function historyModel(entries: readonly unknown[], cut?: HistoryCut): ChatModel { - const model = applyTranscriptLines(transcriptLines(cut ? cutEntries(entries, cut) : entries)); +export function historyModel( + entries: readonly unknown[], + cut?: HistoryCut, + positions?: readonly number[], +): ChatModel { + const model = applyTranscriptLines( + cut ? transcriptLines(cutEntries(entries, cut)) : transcriptLines(entries, positions), + ); return { ...model, running: false, turn: null, streaming: null, permissions: [] }; } +/** A historical call without a recorded result cannot be treated as still running. */ +export function historyForDisplay(history: ChatModel): ChatModel { + let tools = history.tools; + for (const [id, tool] of Object.entries(history.tools)) { + if (tool.status !== "running" && tool.status !== "streaming") continue; + if (tools === history.tools) tools = { ...tools }; + tools[id] = { ...tool, status: "stopped" }; + } + return tools === history.tools ? history : { ...history, tools }; +} + /** * The title a session was given (/rename), the last one standing; else the * last one Claude made for it. diff --git a/src/renderer/services/chat/claude/transcript-pages.ts b/src/renderer/services/chat/claude/transcript-pages.ts new file mode 100644 index 000000000..1d31b514b --- /dev/null +++ b/src/renderer/services/chat/claude/transcript-pages.ts @@ -0,0 +1,86 @@ +import type { TranscriptPageResult } from "../../../../shared/ipc/contract"; +import { historyModel } from "./history"; + +/** An agent snapshot's rows, from oldest to newest. The live log is kept separately. */ +export class TranscriptPages { + readonly snapshot: string; + readonly truncated: boolean; + cursor: string | undefined; + private entries: unknown[] = []; + private positions: number[] = []; + private partial: { position: number; parts: Uint8Array[] } | undefined; + + constructor(page: TranscriptPageResult, snapshot: string) { + this.snapshot = snapshot; + this.truncated = page.truncated; + this.prepend(page); + } + + prepend(page: TranscriptPageResult): void { + if ( + !page.found || + page.snapshot !== this.snapshot || + page.truncated !== this.truncated || + !page.positions || + page.positions.length !== page.lines.length || + (page.cursor !== undefined && page.cursor === this.cursor) + ) { + throw new Error("The transcript page no longer joins this conversation"); + } + const entries = [...page.lines]; + const positions = [...page.positions]; + let partial = this.partial; + const fragment = page.fragment; + if (fragment) { + if ( + entries.length !== 0 || + (fragment.last ? partial !== undefined : partial?.position !== fragment.position) || + (!fragment.first && !page.cursor) + ) { + throw new Error("The transcript page has an incomplete row"); + } + const bytes = Uint8Array.from(atob(fragment.data), (char) => char.charCodeAt(0)); + const parts = [bytes, ...(partial?.parts ?? [])]; + if (fragment.first) { + const row = new Uint8Array(parts.reduce((total, part) => total + part.length, 0)); + let at = 0; + for (const part of parts) { + row.set(part, at); + at += part.length; + } + entries.push(JSON.parse(new TextDecoder().decode(row))); + positions.push(fragment.position); + partial = undefined; + } else { + partial = { position: fragment.position, parts }; + } + } else if (partial) { + throw new Error("The transcript page omitted part of a row"); + } + const newest = positions.at(-1); + if ( + positions.some((position, i) => i > 0 && position <= positions[i - 1]) || + (newest !== undefined && this.positions.length > 0 && newest >= this.positions[0]) + ) { + throw new Error("The transcript page overlaps previously read rows"); + } + this.entries = entries.concat(this.entries); + this.positions = positions.concat(this.positions); + this.partial = partial; + this.cursor = page.cursor; + } + + project() { + const history = historyModel(this.entries, undefined, this.positions); + return { + ...history, + items: history.items.map((item) => + item.kind === "task_end" ? item : { ...item, key: `${this.snapshot}:${item.key}` }, + ), + }; + } + + get lines(): readonly unknown[] { + return this.entries; + } +} diff --git a/src/renderer/services/chat/store.ts b/src/renderer/services/chat/store.ts index 4594c6655..5fe8f03d7 100644 --- a/src/renderer/services/chat/store.ts +++ b/src/renderer/services/chat/store.ts @@ -29,6 +29,8 @@ export interface ChatTabState { model: ChatModel; /** What the tab showed before its program's log: a transcript, an earlier agent's log. */ history: ChatModel | null; + /** A private transcript snapshot can have unread pages before the displayed tail. */ + historyPage?: { hasEarlier: boolean; loading: boolean }; /** Messages the app holds for a tool completion or the end of the turn. */ queue: QueuedMessage[]; /** Authenticated remote user submissions, keyed by the host-generated message ID. */ diff --git a/src/renderer/services/cli/chat-actions.ts b/src/renderer/services/cli/chat-actions.ts index c0c1e9b05..66e85b8d2 100644 --- a/src/renderer/services/cli/chat-actions.ts +++ b/src/renderer/services/cli/chat-actions.ts @@ -74,10 +74,16 @@ function opened(workspaceId: string, tabId: string): boolean { return useChatStore.getState().tabs[chatKey(workspaceId, tabId)] !== undefined; } -async function openedTab(workspaceId: string, tabId: string): Promise { +async function openedTab( + workspaceId: string, + tabId: string, + fullTranscript = false, +): Promise { const target = agentTabController(workspaceId, tabId); if (!target) throw new UiRequestError("that tab is not a Claude or Codex tab"); - if (!opened(workspaceId, tabId)) await target.controller.open(); + const cold = !opened(workspaceId, tabId); + if (target.agent === "claude" && fullTranscript) await target.controller.openToRead(cold); + else if (cold) await target.controller.open(); return target; } @@ -90,9 +96,8 @@ async function openedTab(workspaceId: string, tabId: string): Promise { const target = agentTabController(workspaceId, tabId); if (!target) throw new UiRequestError("that tab is not a Claude or Codex tab"); - if (!opened(workspaceId, tabId)) { - await (target.agent === "claude" ? target.controller.openToRead() : target.controller.open()); - } + if (target.agent === "claude") await target.controller.openToRead(); + else if (!opened(workspaceId, tabId)) await target.controller.open(); return target; } @@ -431,7 +436,7 @@ export const chatHandlers: { [K in ChatOp]: CliUiHandler } = { }, "chat.read": async ({ workspaceId, tabId, messages, since, subagents }) => { - const target = await openedTab(workspaceId, tabId); + const target = await openedTab(workspaceId, tabId, true); const chat = useChatStore.getState().tabs[chatKey(workspaceId, tabId)]; return { ...infoOf(workspaceId, tabId, target), @@ -609,7 +614,7 @@ export const chatHandlers: { [K in ChatOp]: CliUiHandler } = { "chat.entryItem": async ({ workspaceId, tabId, i }) => { // Opened as chat.read opens it, so that the entries are counted alike. - const { agent } = await openedTab(workspaceId, tabId); + const { agent } = await openedTab(workspaceId, tabId, true); const chat = useChatStore.getState().tabs[chatKey(workspaceId, tabId)]; const index = chatItemIndexOf(chat, i, extrasOf(workspaceId, tabId, agent)); const item = diff --git a/src/shared/i18n/locales/en/common.json b/src/shared/i18n/locales/en/common.json index 6ef8aed26..9075529ef 100644 --- a/src/shared/i18n/locales/en/common.json +++ b/src/shared/i18n/locales/en/common.json @@ -826,6 +826,7 @@ "copy": "Copy", "jump_to_bottom": "Scroll to the latest message", "show_earlier": "Show earlier messages ({{count}})", + "show_earlier_unknown": "Show earlier messages", "thinking": "Thinking", "thinking_live": "Thinking…", "received": { diff --git a/src/shared/i18n/locales/ko/common.json b/src/shared/i18n/locales/ko/common.json index 8406bab3b..c686c21c4 100644 --- a/src/shared/i18n/locales/ko/common.json +++ b/src/shared/i18n/locales/ko/common.json @@ -826,6 +826,7 @@ "copy": "복사", "jump_to_bottom": "최근 메시지로 이동", "show_earlier": "이전 메시지 더 보기 ({{count}})", + "show_earlier_unknown": "이전 메시지 더 보기", "thinking": "생각", "thinking_live": "생각 중…", "received": { diff --git a/tests/unit/renderer/services/chat/claude/controller-mode.test.ts b/tests/unit/renderer/services/chat/claude/controller-mode.test.ts index 1b255cb55..fdbce1f9e 100644 --- a/tests/unit/renderer/services/chat/claude/controller-mode.test.ts +++ b/tests/unit/renderer/services/chat/claude/controller-mode.test.ts @@ -91,7 +91,7 @@ mock.module("../../../../../../src/renderer/ipc/client", () => ({ if (method === "sessionFile") { return Promise.resolve({ ok: true, value: { found: true, path: `/h/${args.sessionId}` } }); } - if (method === "transcript") { + if (method === "transcriptPage") { return Promise.resolve({ ok: true, value: { found: false, lines: [], truncated: false } }); } return Promise.resolve({ ok: true, value: undefined }); diff --git a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts index c56d64ae2..ffa3d8f94 100644 --- a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts +++ b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts @@ -5,11 +5,16 @@ * files keep its other exports. */ import { afterEach, describe, expect, mock, test } from "bun:test"; +import { historyModel } from "../../../../../../src/renderer/services/chat/claude/history"; +import type { TranscriptPageResult } from "../../../../../../src/shared/ipc/contract"; let releaseStart: () => void = () => {}; let started = false; let replyToInitialize: ((requestId: string) => void) | undefined; let onStartRequested: (() => void) | undefined; +let transcriptPage: ((cursor?: string) => Promise) | undefined; +let completeLines: readonly unknown[] | undefined; +let completeReads = 0; const realIpc = await import("../../../../../../src/renderer/ipc/client"); mock.module("../../../../../../src/renderer/ipc/client", () => ({ @@ -17,17 +22,22 @@ mock.module("../../../../../../src/renderer/ipc/client", () => ({ ipcCallResult: ( _channel: string, method: string, - args: { message?: { request_id?: string } }, + args: { message?: { request_id?: string }; cursor?: string }, ) => { if (method === "replay") { return Promise.resolve({ ok: true, value: { found: false } }); } + if (method === "transcriptPage" && transcriptPage) { + return transcriptPage(args.cursor).then((value) => ({ ok: true, value })); + } if (method === "transcript") { + completeReads++; return Promise.resolve({ ok: true, value: { found: true, - lines: [ + truncated: false, + lines: completeLines ?? [ { type: "user", uuid: "u1", @@ -71,6 +81,9 @@ afterEach(() => { started = false; replyToInitialize = undefined; onStartRequested = undefined; + transcriptPage = undefined; + completeLines = undefined; + completeReads = 0; }); describe("opening a Claude tab to read it", () => { @@ -113,3 +126,154 @@ describe("opening a Claude tab to read it", () => { expect(useChatStore.getState().tabs[chatKey("ws-read", "t-new")]?.history ?? null).toBeNull(); }); }); + +function user(uuid: string, content: string) { + return { type: "user", uuid, message: { role: "user", content } }; +} + +function goal(condition: string) { + return { + type: "attachment", + timestamp: "2026-11-10T13:52:53.172Z", + attachment: { type: "goal_status", met: true, condition }, + }; +} + +function page(lines: unknown[], positions: number[], cursor?: string): TranscriptPageResult { + return { found: true, truncated: false, snapshot: "same-snapshot", lines, positions, cursor }; +} + +function openTail(hooks = {}) { + const controller = new ChatController( + { + workspaceId: "ws-tail", + tabId: "tail", + cwd: "/p", + sessionId: "session-tail", + }, + hooks, + ); + live.push(controller); + const started = Promise.withResolvers(); + onStartRequested = started.resolve; + void controller.open(); + return { controller, shown: started.promise }; +} + +test("the tail and previous pages reconstruct the full history while live output stays separate", async () => { + const first = user("first", "first"); + const recent = user("recent", "recent"); + const call = { + type: "assistant", + uuid: "calling", + message: { + id: "tool-message", + content: [{ type: "tool_use", id: "read", name: "Read", input: { file_path: "/p/a" } }], + }, + }; + const result = { + type: "user", + message: { content: [{ type: "tool_result", tool_use_id: "read", content: "file result" }] }, + }; + const oldLines = [ + { type: "custom-title", customTitle: "old title" }, + goal("old goal"), + first, + call, + ]; + const newLines = [ + result, + recent, + goal("new goal"), + { type: "custom-title", customTitle: "new title" }, + ]; + const pending = Promise.withResolvers(); + const requested: string[] = []; + transcriptPage = (cursor) => { + if (!cursor) return Promise.resolve(page(newLines, [500, 660, 750, 810], "older")); + requested.push(cursor); + return pending.promise; + }; + completeLines = [...oldLines, ...newLines]; + + const onTitle = mock((_title: string) => {}); + const onFirstMessage = mock((_text: string) => {}); + const { controller, shown } = openTail({ onTitle, onFirstMessage }); + await shown; + expect(completeReads).toBe(0); + expect(controller.state.history?.items.find((item) => item.kind === "user")?.key).toBe( + "same-snapshot:u661", + ); + expect(() => controller.forkPoint("recent", { before: true })).toThrow("Read earlier messages"); + await expect(controller.previewRewind("recent")).rejects.toThrow("Read earlier messages"); + const replayedUser = controller.state.history?.items[0]; + if (replayedUser?.kind !== "user") throw new Error("expected a recorded user item"); + await expect(controller.rewind(replayedUser, { files: true })).rejects.toThrow( + "Read earlier messages", + ); + + const older = controller.loadEarlier(); + await controller.loadEarlier(); + expect(requested).toEqual(["older"]); + controller.receive({ + dir: "out", + seq: 50, + message: { + type: "assistant", + uuid: "new-live", + message: { id: "live", content: [{ type: "text", text: "new live output" }] }, + }, + }); + controller.flushNow(); + const liveModel = controller.state.model; + pending.resolve(page(oldLines, [0, 100, 200, 350])); + await older; + + const expected = historyModel(completeLines); + const actual = controller.state.history; + // File offsets give the private pages stable row keys when a prefix is added. + const content = (model: ReturnType | null) => + model?.items.map(({ key: _key, ...item }) => item); + expect(content(actual)).toEqual(content(expected)); + expect(actual?.tools).toEqual(expected.tools); + expect(actual?.goal).toEqual(expected.goal); + expect(actual?.items.find((item) => item.kind === "user" && item.uuid === "recent")?.key).toBe( + "same-snapshot:u661", + ); + expect(controller.state.model).toBe(liveModel); + expect(liveModel.goal?.condition).toBe("new goal"); + expect(onTitle.mock.calls).toEqual([["new title"]]); + expect(onFirstMessage).not.toHaveBeenCalled(); + expect(controller.forkPoint("recent", { before: true })).toMatchObject({ at: "calling" }); + expect(controller.forkPoint("first", { before: true })).toBeNull(); + + await controller.openToRead(); + expect(completeReads).toBe(1); + expect(controller.state.history?.items.map((item) => item.key)).toEqual( + expected.items.map((item) => item.key), + ); +}); + +test.each([ + "different snapshot", + "conversation reset", +])("an earlier page cannot replace the current history after %s", async (change) => { + const pending = Promise.withResolvers(); + transcriptPage = (cursor) => + cursor ? pending.promise : Promise.resolve(page([user("recent", "recent")], [250], "older")); + const { controller, shown } = openTail(); + await shown; + const older = controller.loadEarlier(); + if (change === "conversation reset") { + controller.receive({ dir: "out", seq: 1, message: { type: "conversation_reset" } }); + controller.flushNow(); + } + const before = controller.state.history; + pending.resolve({ + ...page([user("old", "old")], [0]), + snapshot: change === "different snapshot" ? "other-snapshot" : "same-snapshot", + }); + if (change === "different snapshot") await expect(older).rejects.toThrow("no longer joins"); + else await older; + expect(controller.state.history).toBe(before); +}); diff --git a/tests/unit/renderer/services/chat/claude/history.test.ts b/tests/unit/renderer/services/chat/claude/history.test.ts index 6bf79acc5..be4972865 100644 --- a/tests/unit/renderer/services/chat/claude/history.test.ts +++ b/tests/unit/renderer/services/chat/claude/history.test.ts @@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"; import { cutEntries, type HistoryCut, + historyForDisplay, historyModel, joinHistory, modelBefore, @@ -16,6 +17,7 @@ import { withSubagentLog, } from "../../../../../../src/renderer/services/chat/claude/history"; import { applyLines } from "../../../../../../src/renderer/services/chat/claude/stream-model"; +import { TranscriptPages } from "../../../../../../src/renderer/services/chat/claude/transcript-pages"; import { emptyModel } from "../../../../../../src/renderer/services/chat/model"; // A transcript's entries as Claude Code writes them: bookkeeping between @@ -387,3 +389,48 @@ describe("a subagent's file", () => { ]); }); }); + +test("a bounded row split at a UTF-8 boundary is rebuilt before projecting its tool", () => { + const entry = { + type: "assistant", + uuid: "callSliced", + message: { + id: "messageSliced", + content: [{ type: "tool_use", id: "sliced", name: "Read", input: { file_path: "한글" } }], + }, + }; + const wire = Buffer.from(JSON.stringify(entry)); + const boundary = wire.indexOf(Buffer.from("한")) + 1; + const base = { found: true, snapshot: "example", truncated: false, lines: [], positions: [] }; + const history = new TranscriptPages( + { + ...base, + cursor: "remaining-fragment", + fragment: { + position: 0, + data: wire.subarray(boundary).toString("base64"), + first: false, + last: true, + }, + }, + base.snapshot, + ); + expect(history.project().items).toEqual([]); + history.prepend({ + ...base, + fragment: { + position: 0, + data: wire.subarray(0, boundary).toString("base64"), + first: true, + last: false, + }, + }); + expect(history.lines).toEqual([entry]); + const projected = history.project(); + expect(projected.tools).toEqual(historyModel([entry]).tools); + expect(historyForDisplay(projected).tools.sliced).toMatchObject({ + name: "Read", + status: "stopped", + input: { file_path: "한글" }, + }); +}); diff --git a/tests/unit/renderer/services/chat/controller-card.test.ts b/tests/unit/renderer/services/chat/controller-card.test.ts index a1088cdb6..d1ec77700 100644 --- a/tests/unit/renderer/services/chat/controller-card.test.ts +++ b/tests/unit/renderer/services/chat/controller-card.test.ts @@ -40,7 +40,7 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ } as never); } } - if (method === "transcript") return Promise.resolve({ ok: true, value: { found: false } }); + if (method === "transcriptPage") return Promise.resolve({ ok: true, value: { found: false } }); return Promise.resolve({ ok: true, value: undefined }); }, })); diff --git a/tests/unit/renderer/services/chat/controller-switch-profile.test.ts b/tests/unit/renderer/services/chat/controller-switch-profile.test.ts index 680e6b8fb..a303b9be9 100644 --- a/tests/unit/renderer/services/chat/controller-switch-profile.test.ts +++ b/tests/unit/renderer/services/chat/controller-switch-profile.test.ts @@ -67,7 +67,7 @@ mock.module("../../../../../src/renderer/ipc/client", () => ({ : { found }, }); } - if (method === "transcript") { + if (method === "transcriptPage") { return Promise.resolve({ ok: true, value: { found: false, lines: [], truncated: false } }); } if (method === "start") { @@ -415,7 +415,7 @@ describe("a Claude tab's conversation gone on with in another profile", () => { expect(seen.profile).toBeUndefined(); expect(c.profileId).toBe("work"); expect(seen.target).toEqual({ fork: { sessionId: "theirs", profileId: "claude-default" } }); - const transcript = calls.find((call) => call.method === "transcript")?.args ?? {}; + const transcript = calls.find((call) => call.method === "transcriptPage")?.args ?? {}; expect(transcript.profileId).toBe("claude-default"); const start = calls.find((call) => call.method === "start")?.args ?? {}; expect(start.resume).toBe("/home/claude-default/theirs.jsonl"); From d505241ae27c0ff863384fdea7e378ee1808d571 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 23:04:51 +0900 Subject: [PATCH 4/6] fix(chat): finish fragmented transcript rows within one read --- .../services/chat/claude/controller.ts | 59 ++++++++-- .../services/chat/claude/transcript-pages.ts | 4 + .../claude/controller-open-to-read.test.ts | 108 +++++++++++++++++- 3 files changed, 158 insertions(+), 13 deletions(-) diff --git a/src/renderer/services/chat/claude/controller.ts b/src/renderer/services/chat/claude/controller.ts index 5994ecbdb..3d044f8cd 100644 --- a/src/renderer/services/chat/claude/controller.ts +++ b/src/renderer/services/chat/claude/controller.ts @@ -17,6 +17,7 @@ import { type ChatModel, emptyModel, type ImageBlock, + opensTurn, type PermissionRequest, type UserItem, } from "../model"; @@ -504,7 +505,22 @@ export class ChatController { if (page.snapshot) { const pages = new TranscriptPages(page, page.snapshot); this.transcriptPages = pages; - this.publishTranscript(source, pages.project(), pages.lines, page.truncated, true); + const current = () => + !this.disposed && this.transcriptSource === source && this.transcriptPages === pages; + let history: ChatModel | undefined; + try { + history = await this.readTranscriptBatch(source, pages, current, "opening"); + } finally { + if (current()) { + this.publishTranscript( + source, + history ?? pages.project(), + pages.lines, + pages.truncated, + true, + ); + } + } } else { this.publishTranscript( source, @@ -559,6 +575,34 @@ export class ChatController { return read; } + /** A click or first open reads a meaningful part of the transcript, across fragment frames. */ + private async readTranscriptBatch( + source: TranscriptSource, + pages: TranscriptPages, + current: () => boolean, + action: "opening" | "earlier", + ): Promise { + const args = this.transcriptArgs(source); + const requested = new Set(); + const shown = this.state.history?.items.length ?? 0; + while (current()) { + const cursor = pages.cursor; + if (!pages.hasPartialRow && (action === "opening" || requested.size > 0)) { + const read = pages.project(); + const enough = + action === "opening" ? read.items.some(opensTurn) : read.items.length > shown; + if (enough || !cursor) return read; + } + if (!cursor || requested.has(cursor)) + throw new Error("The transcript cursor did not advance"); + requested.add(cursor); + const result = await ipcCallResult("chat", "transcriptPage", { ...args, cursor }); + if (!current()) return; + if (!result.ok && result.kind === "chat.transcript-cursor-stale") pages.cursor = undefined; + pages.prepend(unwrapIpcResult(result)); + } + } + async loadEarlier(): Promise { const source = this.transcriptSource; const pages = this.transcriptPages; @@ -571,15 +615,10 @@ export class ChatController { this.transcriptPages === pages; this.update((prev) => ({ ...prev, historyPage: { hasEarlier: true, loading: true } })); try { - const result = await ipcCallResult("chat", "transcriptPage", { - ...this.transcriptArgs(source), - cursor, - }); - if (!current()) return; - if (!result.ok && result.kind === "chat.transcript-cursor-stale") pages.cursor = undefined; - const page = unwrapIpcResult(result); - pages.prepend(page); - this.publishTranscript(source, pages.project(), pages.lines, pages.truncated, false); + const history = await this.readTranscriptBatch(source, pages, current, "earlier"); + if (current() && history) { + this.publishTranscript(source, history, pages.lines, pages.truncated, false); + } } catch (error) { if (current()) throw error; } finally { diff --git a/src/renderer/services/chat/claude/transcript-pages.ts b/src/renderer/services/chat/claude/transcript-pages.ts index 1d31b514b..125cc52de 100644 --- a/src/renderer/services/chat/claude/transcript-pages.ts +++ b/src/renderer/services/chat/claude/transcript-pages.ts @@ -80,6 +80,10 @@ export class TranscriptPages { }; } + get hasPartialRow(): boolean { + return this.partial !== undefined; + } + get lines(): readonly unknown[] { return this.entries; } diff --git a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts index ffa3d8f94..40f20ab20 100644 --- a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts +++ b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts @@ -259,21 +259,123 @@ test.each([ "conversation reset", ])("an earlier page cannot replace the current history after %s", async (change) => { const pending = Promise.withResolvers(); - transcriptPage = (cursor) => - cursor ? pending.promise : Promise.resolve(page([user("recent", "recent")], [250], "older")); + const continued = Promise.withResolvers(); + const wire = Buffer.from(JSON.stringify(user("old", "old"))); + transcriptPage = async (cursor) => { + if (!cursor) return page([user("recent", "recent")], [250], "older"); + if (cursor === "older") { + return { + ...page([], [], "finish-row"), + fragment: { + position: 0, + data: wire.subarray(10).toString("base64"), + first: false, + last: true, + }, + }; + } + expect(cursor).toBe("finish-row"); + continued.resolve(); + return pending.promise; + }; const { controller, shown } = openTail(); await shown; const older = controller.loadEarlier(); + await continued.promise; if (change === "conversation reset") { controller.receive({ dir: "out", seq: 1, message: { type: "conversation_reset" } }); controller.flushNow(); } const before = controller.state.history; pending.resolve({ - ...page([user("old", "old")], [0]), + ...page([], []), + fragment: { + position: 0, + data: wire.subarray(0, 10).toString("base64"), + first: true, + last: false, + }, snapshot: change === "different snapshot" ? "other-snapshot" : "same-snapshot", }); if (change === "different snapshot") await expect(older).rejects.toThrow("no longer joins"); else await older; expect(controller.state.history).toBe(before); }); + +test.each([ + "opening", + "earlier", +] as const)("%s completes a fragmented row in one action", async (action) => { + const opening = action === "opening"; + const entry = opening + ? { + type: "user", + message: { + content: [{ type: "tool_result", tool_use_id: "read", content: "large result" }], + }, + } + : user("fragmented", "large message"); + const bytes = Buffer.from(JSON.stringify(entry)); + const fragment = (start: number, end: number, cursor: string): TranscriptPageResult => ({ + ...page([], [], cursor), + fragment: { + position: 250, + data: bytes.subarray(start, end).toString("base64"), + first: start === 0, + last: end === bytes.length, + }, + }); + const trailing = fragment(20, bytes.length, "middle"); + const requested: (string | undefined)[] = []; + transcriptPage = async (cursor) => { + requested.push(cursor); + switch (cursor) { + case undefined: + return opening ? trailing : page([user("recent", "recent")], [400], "large"); + case "large": + return trailing; + case "middle": + return fragment(10, 20, "beginning"); + case "beginning": + return fragment(0, 10, "before-row"); + case "before-row": + if (!opening) throw new Error("an earlier read went past the completed row"); + return page( + [ + user("prompt", "read the file"), + { + type: "assistant", + uuid: "calling", + message: { + id: "tool-message", + content: [{ type: "tool_use", id: "read", name: "Read", input: {} }], + }, + }, + ], + [50, 100], + "stop-at-turn", + ); + default: + throw new Error("the read went past the last turn"); + } + }; + const { controller, shown } = openTail(); + await shown; + if (opening) { + expect(controller.state.history?.items.map((item) => item.kind)).toEqual(["user", "assistant"]); + expect(controller.state.history?.tools.read).toMatchObject({ + name: "Read", + status: "done", + result: { text: "large result" }, + }); + expect(requested).toEqual([undefined, "middle", "beginning", "before-row"]); + } else { + expect(controller.state.history?.items).toHaveLength(1); + await controller.loadEarlier(); + expect( + controller.state.history?.items.map((item) => item.kind === "user" && item.uuid), + ).toEqual(["fragmented", "recent"]); + expect(requested).toEqual([undefined, "large", "middle", "beginning"]); + } + expect(completeReads).toBe(0); +}); From 2f9de32b24386a31fb3beb6e40c7a0fa0113be1a Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 23:44:04 +0900 Subject: [PATCH 5/6] fix(chat): load earlier transcript through a turn boundary --- .../services/chat/claude/controller.ts | 10 +++- .../claude/controller-open-to-read.test.ts | 53 ++++++++++++++----- 2 files changed, 47 insertions(+), 16 deletions(-) diff --git a/src/renderer/services/chat/claude/controller.ts b/src/renderer/services/chat/claude/controller.ts index 3d044f8cd..84840a123 100644 --- a/src/renderer/services/chat/claude/controller.ts +++ b/src/renderer/services/chat/claude/controller.ts @@ -584,13 +584,19 @@ export class ChatController { ): Promise { const args = this.transcriptArgs(source); const requested = new Set(); - const shown = this.state.history?.items.length ?? 0; + const shown = this.state.history?.items ?? []; while (current()) { const cursor = pages.cursor; if (!pages.hasPartialRow && (action === "opening" || requested.size > 0)) { const read = pages.project(); + const first = read.items[0]; const enough = - action === "opening" ? read.items.some(opensTurn) : read.items.length > shown; + action === "opening" + ? read.items.some(opensTurn) + : read.items.length > shown.length && + first !== undefined && + first.key !== shown[0]?.key && + opensTurn(first); if (enough || !cursor) return read; } if (!cursor || requested.has(cursor)) diff --git a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts index 40f20ab20..c15714b6b 100644 --- a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts +++ b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts @@ -305,16 +305,19 @@ test.each([ test.each([ "opening", "earlier", + "earlier with an answer before its question", ] as const)("%s completes a fragmented row in one action", async (action) => { const opening = action === "opening"; - const entry = opening - ? { - type: "user", - message: { - content: [{ type: "tool_result", tool_use_id: "read", content: "large result" }], - }, - } - : user("fragmented", "large message"); + const acrossTurn = action === "earlier with an answer before its question"; + const entry = + opening || acrossTurn + ? { + type: "user", + message: { + content: [{ type: "tool_result", tool_use_id: "read", content: "large result" }], + }, + } + : user("fragmented", "large message"); const bytes = Buffer.from(JSON.stringify(entry)); const fragment = (start: number, end: number, cursor: string): TranscriptPageResult => ({ ...page([], [], cursor), @@ -333,13 +336,27 @@ test.each([ case undefined: return opening ? trailing : page([user("recent", "recent")], [400], "large"); case "large": + return acrossTurn + ? page( + [ + { + type: "assistant", + uuid: "answer", + message: { id: "answer", content: [{ type: "text", text: "the answer" }] }, + }, + ], + [350], + "result", + ) + : trailing; + case "result": return trailing; case "middle": return fragment(10, 20, "beginning"); case "beginning": return fragment(0, 10, "before-row"); case "before-row": - if (!opening) throw new Error("an earlier read went past the completed row"); + if (!opening && !acrossTurn) throw new Error("an earlier read went past the completed row"); return page( [ user("prompt", "read the file"), @@ -361,17 +378,25 @@ test.each([ }; const { controller, shown } = openTail(); await shown; - if (opening) { - expect(controller.state.history?.items.map((item) => item.kind)).toEqual(["user", "assistant"]); + if (!opening) { + expect(controller.state.history?.items).toHaveLength(1); + await controller.loadEarlier(); + } + if (opening || acrossTurn) { + expect(controller.state.history?.items.map((item) => item.kind)).toEqual( + acrossTurn ? ["user", "assistant", "assistant", "user"] : ["user", "assistant"], + ); expect(controller.state.history?.tools.read).toMatchObject({ name: "Read", status: "done", result: { text: "large result" }, }); - expect(requested).toEqual([undefined, "middle", "beginning", "before-row"]); + expect(requested).toEqual( + acrossTurn + ? [undefined, "large", "result", "middle", "beginning", "before-row"] + : [undefined, "middle", "beginning", "before-row"], + ); } else { - expect(controller.state.history?.items).toHaveLength(1); - await controller.loadEarlier(); expect( controller.state.history?.items.map((item) => item.kind === "user" && item.uuid), ).toEqual(["fragmented", "recent"]); From 334f1b93d44d037978d4071390973adf809f5259 Mon Sep 17 00:00:00 2001 From: moreih29 Date: Thu, 19 Nov 2026 23:56:28 +0900 Subject: [PATCH 6/6] fix(chat): resume earlier history after an agent change --- internal/chat/transcript_page.go | 85 +++++++++++++--- internal/chat/transcript_page_test.go | 27 ++++++ src/main/features/chat/host.ts | 2 +- src/main/features/chat/ipc.ts | 10 +- .../services/chat/claude/controller.ts | 97 ++++++++++++------- .../services/chat/claude/transcript-pages.ts | 50 ++++++++-- src/shared/ipc/contract.ts | 3 + .../claude/controller-open-to-read.test.ts | 81 +++++++++++++++- 8 files changed, 291 insertions(+), 64 deletions(-) diff --git a/internal/chat/transcript_page.go b/internal/chat/transcript_page.go index 627ea5ae0..7d769fcbf 100644 --- a/internal/chat/transcript_page.go +++ b/internal/chat/transcript_page.go @@ -20,7 +20,7 @@ import ( const ( transcriptPageBytes = 512 * 1024 transcriptPageTurns = 20 - transcriptPageOverhead = 384 + transcriptPageOverhead = 448 transcriptReadBlock = 64 * 1024 transcriptAnchorBytes = 2048 transcriptSnapshots = 128 @@ -28,19 +28,22 @@ const ( type transcriptPageParams struct { TranscriptParams - Cursor string `json:"cursor,omitempty"` - UpTo string `json:"upTo,omitempty"` - Before []string `json:"before,omitempty"` + Cursor string `json:"cursor,omitempty"` + BeforeAnchor string `json:"beforeAnchor,omitempty"` + UpTo string `json:"upTo,omitempty"` + Before []string `json:"before,omitempty"` } type transcriptPage struct { - Found bool `json:"found"` - Lines []json.RawMessage `json:"lines"` - Positions []int64 `json:"positions"` - Truncated bool `json:"truncated"` - Snapshot string `json:"snapshot,omitempty"` - Cursor string `json:"cursor,omitempty"` - Fragment *transcriptFragment `json:"fragment,omitempty"` + Found bool `json:"found"` + Lines []json.RawMessage `json:"lines"` + Positions []int64 `json:"positions"` + Truncated bool `json:"truncated"` + Snapshot string `json:"snapshot,omitempty"` + Cursor string `json:"cursor,omitempty"` + BeforeAnchor string `json:"beforeAnchor,omitempty"` + Anchored bool `json:"anchored,omitempty"` + Fragment *transcriptFragment `json:"fragment,omitempty"` } type transcriptFragment struct { @@ -123,7 +126,9 @@ func (s *Service) TranscriptPage(ctx context.Context, raw json.RawMessage) (any, if err := decodeParams(raw, &p, "chat.transcriptPage params must include sessionId"); err != nil { return nil, err } - if !sessionIDPattern.MatchString(p.SessionID) || (p.Cursor != "" && (len(p.Before) > 0 || p.UpTo != "")) { + if !sessionIDPattern.MatchString(p.SessionID) || + (p.Cursor != "" && p.BeforeAnchor != "") || + ((p.Cursor != "" || p.BeforeAnchor != "") && (len(p.Before) > 0 || p.UpTo != "")) { return nil, protocolError("invalid chat.transcriptPage params") } page, err := s.readTranscriptPage(ctx, p, transcriptCapBytes, transcriptPageBytes) @@ -179,7 +184,14 @@ func (s *Service) readTranscriptPage(ctx context.Context, p transcriptPageParams if err != nil { return page, err } - if p.UpTo != "" || len(p.Before) > 0 { + if p.BeforeAnchor != "" { + var matched bool + snapshot.end, matched, err = transcriptEndBeforeAnchor(file, snapshot, p.BeforeAnchor) + if err != nil || !matched { + return page, err + } + page.Anchored = true + } else if p.UpTo != "" || len(p.Before) > 0 { snapshot.end, err = transcriptCutEnd(ctx, file, snapshot, p) if err != nil { return page, err @@ -227,6 +239,12 @@ func (s *Service) readTranscriptPage(ctx context.Context, p transcriptPageParams return page, err } page.Cursor = snapshot.cursor(pos, fragment, boundary) + if fragment < 0 { + page.BeforeAnchor, err = transcriptBeforeAnchor(file, pos, snapshot.end) + if err != nil { + return page, err + } + } if p.Cursor == "" { s.transcriptPages.add(snapshot) } @@ -267,6 +285,47 @@ func cursorAnchor(file *os.File, snapshot *transcriptSnapshot, pos int64) ([32]b return sha256.Sum256(part), err } +// A finished page can be resumed across agent lifetimes. Fingerprint bytes +// on the displayed side of its exclusive boundary so an append leaves it +// valid. The new agent still verifies that boundary against the session file. +const transcriptBeforeAnchorSize = 8 + 2 + sha256.Size + +func transcriptBeforeAnchor(file *os.File, pos, end int64) (string, error) { + var block [transcriptAnchorBytes]byte + sample := block[:min(transcriptAnchorBytes, end-pos)] + if _, err := file.ReadAt(sample, pos); err != nil { + return "", err + } + var token [transcriptBeforeAnchorSize]byte + binary.BigEndian.PutUint64(token[:8], uint64(pos)) + binary.BigEndian.PutUint16(token[8:10], uint16(len(sample))) + digest := sha256.Sum256(sample) + copy(token[10:], digest[:]) + return base64.RawURLEncoding.EncodeToString(token[:]), nil +} + +func transcriptEndBeforeAnchor(file *os.File, snapshot *transcriptSnapshot, anchor string) (int64, bool, error) { + if len(anchor) != base64.RawURLEncoding.EncodedLen(transcriptBeforeAnchorSize) { + return 0, false, nil + } + token, err := base64.RawURLEncoding.DecodeString(anchor) + if err != nil || len(token) != transcriptBeforeAnchorSize { + return 0, false, nil + } + pos := int64(binary.BigEndian.Uint64(token[:8])) + length := int64(binary.BigEndian.Uint16(token[8:10])) + if pos <= 0 || pos < snapshot.floor || pos >= snapshot.end || + length <= 0 || length > transcriptAnchorBytes || length > snapshot.end-pos { + return 0, false, nil + } + var block [transcriptAnchorBytes + 1]byte + if _, err := file.ReadAt(block[:length+1], pos-1); err != nil { + return 0, false, err + } + hash := sha256.Sum256(block[1 : length+1]) + return pos, block[0] == '\n' && bytes.Equal(hash[:], token[10:]), nil +} + // A cut uses the first matching UUID in the retained window, as the // renderer's full-transcript cut did. It does not transfer the scan. func transcriptCutEnd(ctx context.Context, file *os.File, snapshot *transcriptSnapshot, p transcriptPageParams) (int64, error) { diff --git a/internal/chat/transcript_page_test.go b/internal/chat/transcript_page_test.go index dfd10c292..aeb155147 100644 --- a/internal/chat/transcript_page_test.go +++ b/internal/chat/transcript_page_test.go @@ -44,6 +44,8 @@ func TestTranscriptPages(t *testing.T) { {name: "replace at the same size", input: base, change: "replace", stale: true}, {name: "profile mismatch", input: base, change: "profile", stale: true}, {name: "new agent", input: base, change: "agent", stale: true}, + {name: "new agent resumes exclusively before the displayed page after append", input: base, change: "resume", want: []string{old, big}}, + {name: "resume rejects an overwritten boundary", input: base, change: "anchor changed"}, } { t.Run(tc.name, func(t *testing.T) { dir := t.TempDir() @@ -84,6 +86,31 @@ func TestTranscriptPages(t *testing.T) { params.ConfigDir = t.TempDir() case "agent": service = New() + case "resume", "anchor changed": + if len(page.Lines) != 1 || !equalRows([]string{string(page.Lines[0])}, []string{tip}) || page.BeforeAnchor == "" { + t.Fatal("fixture did not return an anchor before the displayed last row") + } + if tc.change == "resume" { + write(path, tc.input+line("appended", "new text")+"\n") + } else { + write(path, strings.Replace(tc.input, tip, line("recent", "다른"), 1)) + } + service = New() + params.BeforeAnchor = page.BeforeAnchor + page, err = service.readTranscriptPage(ctx, params, retention, budget) + if err != nil { + t.Fatal(err) + } + params.BeforeAnchor = "" + if tc.change == "anchor changed" { + if page.Found || page.Anchored { + t.Fatal("a different row matched the old anchor") + } + return + } + if !page.Anchored { + t.Fatal("the new agent could not verify the boundary") + } } if tc.stale { if page.Cursor == "" { diff --git a/src/main/features/chat/host.ts b/src/main/features/chat/host.ts index e077ca5c9..e0b290595 100644 --- a/src/main/features/chat/host.ts +++ b/src/main/features/chat/host.ts @@ -415,7 +415,7 @@ export class ChatHost { workspaceId: string, sessionId: string, profileId: string | undefined, - page: { cursor?: string; upTo?: string; before?: string[] }, + page: { cursor?: string; beforeAnchor?: string; upTo?: string; before?: string[] }, ): Promise { const args = { sessionId, ...this.configDir(workspaceId, profileId) }; const channel = await this.channelFor(workspaceId); diff --git a/src/main/features/chat/ipc.ts b/src/main/features/chat/ipc.ts index 1fe074d98..a96e1ef2e 100644 --- a/src/main/features/chat/ipc.ts +++ b/src/main/features/chat/ipc.ts @@ -118,13 +118,9 @@ export function registerChatChannel(options: Omit) } catch (error) { const code = (error as { code?: unknown } | null)?.code; if (code === "chat.transcript-cursor-stale") { - return ipcErr( - code, - "The chat history changed. Reopen the conversation to read it again.", - { - category: "failed", - }, - ); + return ipcErr(code, "The chat history changed. Try reading earlier messages again.", { + category: "failed", + }); } const failure = agentCallError(error); if (failure) return failure; diff --git a/src/renderer/services/chat/claude/controller.ts b/src/renderer/services/chat/claude/controller.ts index 84840a123..0573ca978 100644 --- a/src/renderer/services/chat/claude/controller.ts +++ b/src/renderer/services/chat/claude/controller.ts @@ -8,6 +8,7 @@ import { defaultProfileId, isDefaultProfileId } from "../../../../shared/agent-profiles/profiles"; import { type RelayedMessage, type RelaySender, relayedText } from "../../../../shared/chat/relay"; +import type { TranscriptPageResult } from "../../../../shared/ipc/contract"; import { createLogger } from "../../../../shared/log/renderer"; import type { ChatChosen, ProfileMove } from "../../../../shared/types/layout"; import { ipcCallResult, unwrapIpcResult } from "../../../ipc/client"; @@ -535,10 +536,13 @@ export class ChatController { } } - private async readFullTranscript(source: TranscriptSource): Promise { - const result = unwrapIpcResult( - await ipcCallResult("chat", "transcript", this.transcriptArgs(source)), - ); + private async readFullTranscript( + source: TranscriptSource, + legacy?: TranscriptPageResult, + ): Promise { + const result = + legacy ?? + unwrapIpcResult(await ipcCallResult("chat", "transcript", this.transcriptArgs(source))); if (this.disposed || this.transcriptSource !== source) return; if (!result.found && this.transcriptPages) throw new Error("The transcript is no longer available"); @@ -555,13 +559,7 @@ export class ChatController { source.cut ?? (before?.size ? { before } : undefined), ); this.transcriptPages = undefined; - this.publishTranscript( - source, - source.appended ? { ...joinHistory(history, source.appended), goal: history.goal } : history, - result.lines, - result.truncated, - true, - ); + this.publishTranscript(source, history, result.lines, result.truncated, true); } private completeTranscript(): Promise | undefined { @@ -581,22 +579,20 @@ export class ChatController { pages: TranscriptPages, current: () => boolean, action: "opening" | "earlier", + pageRead = action === "opening", ): Promise { const args = this.transcriptArgs(source); const requested = new Set(); - const shown = this.state.history?.items ?? []; + const shownFirst = this.state.history?.items[0]?.key; while (current()) { const cursor = pages.cursor; - if (!pages.hasPartialRow && (action === "opening" || requested.size > 0)) { + if (!pages.hasPartialRow && pageRead) { const read = pages.project(); const first = read.items[0]; const enough = action === "opening" ? read.items.some(opensTurn) - : read.items.length > shown.length && - first !== undefined && - first.key !== shown[0]?.key && - opensTurn(first); + : first !== undefined && first.key !== shownFirst && opensTurn(first); if (enough || !cursor) return read; } if (!cursor || requested.has(cursor)) @@ -604,34 +600,60 @@ export class ChatController { requested.add(cursor); const result = await ipcCallResult("chat", "transcriptPage", { ...args, cursor }); if (!current()) return; - if (!result.ok && result.kind === "chat.transcript-cursor-stale") pages.cursor = undefined; + if (!result.ok && result.kind === "chat.transcript-cursor-stale") { + pages.expireCursor(); + return; + } pages.prepend(unwrapIpcResult(result)); + pageRead = true; } } async loadEarlier(): Promise { const source = this.transcriptSource; - const pages = this.transcriptPages; - const cursor = pages?.cursor; - if (!source || !pages || !cursor || this.state.historyPage?.loading) return; + const visible = this.transcriptPages; + if (!source || !visible?.hasEarlier || this.state.historyPage?.loading) return; const current = () => !this.disposed && !this.changingSession && this.transcriptSource === source && - this.transcriptPages === pages; + this.transcriptPages === visible; this.update((prev) => ({ ...prev, historyPage: { hasEarlier: true, loading: true } })); try { - const history = await this.readTranscriptBatch(source, pages, current, "earlier"); + let pages = visible.copy(); + let history = pages.cursor + ? await this.readTranscriptBatch(source, pages, current, "earlier") + : undefined; + if (!current()) return; + if (pages.cursorExpired) { + visible.expireCursor(); + const page = visible.beforeAnchor + ? unwrapIpcResult( + await ipcCallResult("chat", "transcriptPage", { + ...this.transcriptArgs(source), + beforeAnchor: visible.beforeAnchor, + }), + ) + : undefined; + if (!current()) return; + if (!page?.anchored || !page.snapshot) { + await this.readFullTranscript(source, page?.found && !page.snapshot ? page : undefined); + return; + } + pages = new TranscriptPages(page, page.snapshot, visible); + history = await this.readTranscriptBatch(source, pages, current, "earlier", true); + } if (current() && history) { + this.transcriptPages = pages; this.publishTranscript(source, history, pages.lines, pages.truncated, false); } } catch (error) { if (current()) throw error; } finally { - if (this.transcriptPages === pages && this.transcriptSource === source) { + if (this.transcriptPages === visible && this.transcriptSource === source) { this.update((prev) => ({ ...prev, - historyPage: { hasEarlier: !!pages.cursor, loading: false }, + historyPage: { hasEarlier: visible.hasEarlier, loading: false }, })); } } @@ -639,13 +661,16 @@ export class ChatController { private publishTranscript( source: TranscriptSource, - read: ChatModel, + projected: ChatModel, lines: readonly unknown[], truncated: boolean, initial: boolean, ): void { const pages = this.transcriptPages; - this.earlierHistoryUnknown = truncated || pages?.cursor !== undefined; + this.earlierHistoryUnknown = truncated || pages?.hasEarlier === true; + const read = source.appended + ? { ...joinHistory(projected, source.appended), goal: projected.goal } + : projected; // A task's end the log tells too is the log's: it has no uuid to cut at. const told = new Set( this.state.model.items.flatMap((item) => (item.kind === "task_end" ? [item.key] : [])), @@ -671,7 +696,7 @@ export class ChatController { history.items.length > 0 || Object.keys(agentItems).length > 0 ? { ...history, agentItems } : null, - historyPage: pages ? { hasEarlier: !!pages.cursor, loading: false } : undefined, + historyPage: pages ? { hasEarlier: pages.hasEarlier, loading: false } : undefined, // A previously unread page must not replace a goal that the live log set or cleared. model: (initial || !prev.history?.goal) && @@ -1313,34 +1338,38 @@ export class ChatController { /** The agent is back: replay what the tab missed, or find its program gone. */ async resync(): Promise { this.flushNow(); + const source = this.transcriptSource; let replay: ReplayResult; try { replay = await this.replay(this.state.model.lastSeq); } catch { return; } + if (this.disposed || this.changingSession || this.transcriptSource !== source) return; if (replay.found) { this.update((prev) => ({ ...prev, phase: replay.running ? "ready" : "ended" })); return; } // A new agent: what the tab showed becomes its history. Its cursor died with the old agent. - const earlierHistoryUnknown = this.earlierHistoryUnknown; - const source = this.transcriptSource; const pages = this.transcriptPages; - this.resetTranscript(); - this.earlierHistoryUnknown = earlierHistoryUnknown; + if (!pages && this.opening) return; if (source && pages) { + this.fullTranscript = undefined; this.transcriptSource = { ...source, appended: joinHistory(source.appended ?? null, this.state.model), }; - pages.cursor = undefined; - this.transcriptPages = pages; + pages.expireCursor(); + } else { + const earlierHistoryUnknown = this.earlierHistoryUnknown; + this.resetTranscript(); + this.earlierHistoryUnknown = earlierHistoryUnknown; } this.update((prev) => ({ ...prev, phase: "ended", history: joinHistory(prev.history, prev.model), + historyPage: pages ? { hasEarlier: pages.hasEarlier, loading: false } : undefined, model: emptyModel(), })); this.rejectPending("the program is gone"); diff --git a/src/renderer/services/chat/claude/transcript-pages.ts b/src/renderer/services/chat/claude/transcript-pages.ts index 125cc52de..03f2cbae4 100644 --- a/src/renderer/services/chat/claude/transcript-pages.ts +++ b/src/renderer/services/chat/claude/transcript-pages.ts @@ -6,16 +6,51 @@ export class TranscriptPages { readonly snapshot: string; readonly truncated: boolean; cursor: string | undefined; - private entries: unknown[] = []; - private positions: number[] = []; + beforeAnchor: string | undefined; + cursorExpired = false; + private readonly keySnapshot: string; + private entries: unknown[]; + private positions: number[]; private partial: { position: number; parts: Uint8Array[] } | undefined; - constructor(page: TranscriptPageResult, snapshot: string) { + constructor(page: TranscriptPageResult, snapshot: string, retained?: TranscriptPages) { this.snapshot = snapshot; this.truncated = page.truncated; + this.keySnapshot = retained?.keySnapshot ?? snapshot; + this.entries = retained?.entries ?? []; + this.positions = retained?.positions ?? []; this.prepend(page); } + /** A batch can be abandoned without moving the displayed history's boundary. */ + copy(): TranscriptPages { + const batch = new TranscriptPages( + { + found: true, + lines: [], + positions: [], + snapshot: this.snapshot, + truncated: this.truncated, + cursor: this.cursor, + beforeAnchor: this.beforeAnchor, + }, + this.snapshot, + this, + ); + batch.partial = this.partial; + batch.cursorExpired = this.cursorExpired; + return batch; + } + + expireCursor(): void { + if (this.cursor) this.cursorExpired = true; + this.cursor = undefined; + } + + get hasEarlier(): boolean { + return this.cursor !== undefined || this.cursorExpired; + } + prepend(page: TranscriptPageResult): void { if ( !page.found || @@ -64,10 +99,13 @@ export class TranscriptPages { ) { throw new Error("The transcript page overlaps previously read rows"); } - this.entries = entries.concat(this.entries); - this.positions = positions.concat(this.positions); + if (entries.length > 0) { + this.entries = entries.concat(this.entries); + this.positions = positions.concat(this.positions); + } this.partial = partial; this.cursor = page.cursor; + if (!partial) this.beforeAnchor = page.beforeAnchor; } project() { @@ -75,7 +113,7 @@ export class TranscriptPages { return { ...history, items: history.items.map((item) => - item.kind === "task_end" ? item : { ...item, key: `${this.snapshot}:${item.key}` }, + item.kind === "task_end" ? item : { ...item, key: `${this.keySnapshot}:${item.key}` }, ), }; } diff --git a/src/shared/ipc/contract.ts b/src/shared/ipc/contract.ts index 1ca4f2387..7210cefae 100644 --- a/src/shared/ipc/contract.ts +++ b/src/shared/ipc/contract.ts @@ -597,6 +597,8 @@ const transcriptPageResult = z.object({ positions: z.array(z.number().int().nonnegative()).optional(), snapshot: z.string().optional(), cursor: z.string().optional(), + beforeAnchor: z.string().optional(), + anchored: z.boolean().optional(), fragment: z .object({ position: z.number().int().nonnegative(), @@ -1042,6 +1044,7 @@ export const ipcContract = { sessionId: z.string().max(128), profileId: z.string().max(64).optional(), cursor: z.string().max(128).optional(), + beforeAnchor: z.string().max(64).optional(), upTo: z.string().max(128).optional(), before: z.array(z.string().max(128)).optional(), }), diff --git a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts index c15714b6b..a191abfd0 100644 --- a/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts +++ b/tests/unit/renderer/services/chat/claude/controller-open-to-read.test.ts @@ -8,11 +8,15 @@ import { afterEach, describe, expect, mock, test } from "bun:test"; import { historyModel } from "../../../../../../src/renderer/services/chat/claude/history"; import type { TranscriptPageResult } from "../../../../../../src/shared/ipc/contract"; +import { type IpcErrResult, ipcErr } from "../../../../../../src/shared/ipc/result"; + let releaseStart: () => void = () => {}; let started = false; let replyToInitialize: ((requestId: string) => void) | undefined; let onStartRequested: (() => void) | undefined; -let transcriptPage: ((cursor?: string) => Promise) | undefined; +let transcriptPage: + | ((cursor?: string, beforeAnchor?: string) => Promise) + | undefined; let completeLines: readonly unknown[] | undefined; let completeReads = 0; @@ -22,13 +26,15 @@ mock.module("../../../../../../src/renderer/ipc/client", () => ({ ipcCallResult: ( _channel: string, method: string, - args: { message?: { request_id?: string }; cursor?: string }, + args: { message?: { request_id?: string }; cursor?: string; beforeAnchor?: string }, ) => { if (method === "replay") { return Promise.resolve({ ok: true, value: { found: false } }); } if (method === "transcriptPage" && transcriptPage) { - return transcriptPage(args.cursor).then((value) => ({ ok: true, value })); + return transcriptPage(args.cursor, args.beforeAnchor).then((value) => + "ok" in value ? value : { ok: true, value }, + ); } if (method === "transcript") { completeReads++; @@ -404,3 +410,72 @@ test.each([ } expect(completeReads).toBe(0); }); + +test.each([ + "agent replaced", + "stale cursor", + "anchor missing", + "legacy agent", +] as const)("earlier history resumes at the displayed boundary after %s", async (cause) => { + const recent = user("recent", "recent"); + const old = user("old", "old"); + const liveRow = { + type: "assistant", + uuid: "live", + message: { id: "live", content: [{ type: "text", text: "live output" }] }, + }; + completeLines = [old, recent, liveRow]; + const answer = { + type: "assistant", + uuid: "answer", + message: { id: "answer", content: [{ type: "text", text: "older answer" }] }, + }; + const requests: { cursor?: string; beforeAnchor?: string }[] = []; + transcriptPage = async (cursor, beforeAnchor) => { + requests.push({ cursor, beforeAnchor }); + if (beforeAnchor) { + expect(beforeAnchor).toBe("displayed-boundary"); + if (cause === "anchor missing") return { found: false, truncated: false, lines: [] }; + if (cause === "legacy agent") + return { found: true, truncated: false, lines: [old, recent, liveRow] }; + return { ...page([old, answer], [50, 150]), anchored: true, snapshot: "new-snapshot" }; + } + if (cursor === "previous") { + return { ...page([answer], [150], "next"), beforeAnchor: "unpublished-boundary" }; + } + if (cursor === "next") return ipcErr("chat.transcript-cursor-stale", "expired"); + return { ...page([recent], [250], "previous"), beforeAnchor: "displayed-boundary" }; + }; + + const { controller, shown } = openTail(); + await shown; + const recentKey = controller.state.history?.items[0]?.key; + if (cause !== "stale cursor") { + controller.receive({ + dir: "out", + seq: 1, + message: liveRow, + }); + await controller.resync(); + expect(controller.state.historyPage?.hasEarlier).toBe(true); + } + + await controller.loadEarlier(); + const items = controller.state.history?.items ?? []; + const uuid = (item: (typeof items)[number]) => "uuid" in item && item.uuid; + const fallback = cause === "anchor missing" || cause === "legacy agent"; + expect(items.map(uuid)).toEqual([ + "old", + ...(fallback ? [] : ["answer"]), + "recent", + ...(cause === "stale cursor" ? [] : ["live"]), + ]); + if (!fallback) expect(items.find((item) => uuid(item) === "recent")?.key).toBe(recentKey); + expect(requests.map((request) => request.cursor ?? request.beforeAnchor)).toEqual( + cause === "stale cursor" + ? [undefined, "previous", "next", "displayed-boundary"] + : [undefined, "displayed-boundary"], + ); + expect(completeReads).toBe(cause === "anchor missing" ? 1 : 0); + expect(controller.state.historyPage?.hasEarlier ?? false).toBe(false); +});