From c73679083a594b9b6e831d00b54319e70c6a1abe Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 20 Nov 2026 22:29:33 -0500 Subject: [PATCH 01/37] perf(agents): mount transcript detail bodies on first expansion Co-authored-by: Jello Signed-off-by: LordMelkor --- .../agents/ActivityTranscript.test.tsx | 23 +++++--- src/features/agents/ActivityTranscript.tsx | 59 +++++++++++++------ 2 files changed, 58 insertions(+), 24 deletions(-) diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index 99ced4a9b1..d0a9775be8 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -178,7 +178,7 @@ it("shows the recorded tool name, highlights tool calls, and keeps script text i expect(screen.queryByText("Raw details")).not.toBeInTheDocument(); }); -it("shows a failed nested call on the collapsed script while preserving the script's status", () => { +it("shows a failed nested call on the collapsed script while preserving the script's status", async () => { const turns = codexTurns( [ { @@ -224,6 +224,7 @@ it("shows a failed nested call on the collapsed script while preserving the scri const script = screen.getByText("exec", { exact: true }).closest("details"); expect(script).not.toHaveAttribute("open"); expect(script).toHaveAttribute("data-status", "completed"); + await userEvent.click(screen.getByText("exec", { exact: true })); // The script and its nested call each carry their own time. expect(script?.querySelectorAll("time")).toHaveLength(2); expect(script?.parentElement?.querySelectorAll("time")).toHaveLength(2); @@ -282,7 +283,7 @@ it("discloses tool arguments and results without raw details, including a posted expect(screen.queryByText("Raw details")).not.toBeInTheDocument(); }); -it("renders thought formatting and keeps entry times available, except the prompt", () => { +it("renders thought formatting and keeps entry times available, except the prompt", async () => { const at = Date.UTC(2026, 9, 20, 20, 1, 28); const { container } = render( "ended"} />, ); + await userEvent.click(screen.getByText("Inspecting the bootstrap script")); expect(screen.getByText("formatting", { selector: "strong" }).tagName).toBe( "STRONG", ); @@ -379,7 +381,7 @@ it("updates mounted transcript clocks while keeping elapsed time and navigation" } }); -it("shows no time for an entry with a zero, non-finite or invalid time", () => { +it("shows no time for an entry with a zero, non-finite or invalid time", async () => { const { container } = render( { state={() => "ended"} />, ); + await userEvent.click(screen.getByText("exec", { exact: true })); + expect(screen.getByText("d", { selector: "summary span" })).toBeVisible(); expect(container.querySelectorAll("time")).toHaveLength(0); }); @@ -550,6 +554,10 @@ it("shows the turn a message began, its prompt open, instead of the latest, once const shown: string[] = []; const margins: string[] = []; Element.prototype.scrollIntoView = function (this: HTMLElement) { + if (this.dataset.entry === "item:m6") + expect( + this.querySelector("[data-arrival-surface][data-arrived]"), + ).not.toBeNull(); shown.push(this.dataset.entry ?? ""); margins.push(this.style.scrollMarginBlockStart); }; @@ -708,7 +716,7 @@ it("shows the turn a message began, its prompt open, instead of the latest, once } }); -it("divides sessions, and shows each one's prompt once at its top", () => { +it("divides sessions, and shows each one's prompt once at its top", async () => { const turn = ( turnId: string, sessionId: string, @@ -751,7 +759,8 @@ it("divides sessions, and shows each one's prompt once at its top", () => { .map((line) => line.textContent), ).toEqual(["Session continued; earlier turns not shown", "New session"]); expect(screen.getAllByText(/System prompt/)).toHaveLength(1); - expect(screen.getByText("Agent instructions")).toBeInTheDocument(); + await userEvent.click(screen.getByText(/System prompt/)); + expect(screen.getByText("Agent instructions")).toBeVisible(); }); it("keeps the conversation readable while disclosing work and showing the current step", async () => { @@ -819,7 +828,7 @@ it("keeps the conversation readable while disclosing work and showing the curren expect( screen.queryByRole("button", { name: "2 activity steps" }), ).not.toBeInTheDocument(); - expect(screen.getByText("source")).not.toBeVisible(); + expect(screen.queryByText("source")).not.toBeInTheDocument(); await user.click(screen.getByText("renderer")); expect(screen.getByText("source")).toBeVisible(); await user.click(screen.getByText("renderer")); @@ -853,7 +862,7 @@ it("keeps thought details collapsed until requested and preserves them across up state={() => "working"} />, ); - expect(screen.getByText("formatting")).not.toBeVisible(); + expect(screen.queryByText("formatting")).not.toBeInTheDocument(); const disclosure = screen .getByText("Checking the view", { selector: "summary span" }) .closest("summary"); diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index 83dffc2f26..8795cf66cf 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -7,6 +7,7 @@ import { useLayoutEffect, useMemo, useRef, + useState, type ReactNode, } from "react"; import remarkGfm from "remark-gfm"; @@ -69,7 +70,10 @@ const PeopleContext = createContext<{ community?: string | undefined; }>({}); -const AgentAvatarSource = createContext(undefined); +const RowContext = createContext<{ + picture?: string | undefined; + focused?: string | undefined; +}>({}); /** The Buzz events a profile was opened for, most wanted first, and the * reader's input count then. A transcript showing one of their turns shows it @@ -277,6 +281,7 @@ function useShowFocused( }); focus.done(); }, [focus, entry, timeline, following]); + return entry; } /** Turn-by-turn transcript of the loaded activity, oldest first, opened at @@ -307,7 +312,7 @@ export function ActivityTranscript({ community?: string | undefined; }) { const { timeline, following } = useFollowLatest(transcript, follow); - useShowFocused(transcript, timeline, following); + const focused = useShowFocused(transcript, timeline, following); const agents = useContext(AgentsContext); const relay = useSyncExternalStore( agents?.subscribe ?? noSubscribe, @@ -327,9 +332,13 @@ export function ActivityTranscript({ community, "small", ); + const rowContext = useMemo( + () => ({ picture: poster ?? picture, focused }), + [poster, picture, focused], + ); return ( - +
{before} {!transcript.turns.length && ( @@ -357,7 +366,7 @@ export function ActivityTranscript({ ))}
-
+
); } @@ -511,8 +520,14 @@ function Sections({ title: string; sections: readonly PromptSection[]; }) { + const [visited, setVisited] = useState(false); return ( -
+
{ + if (event.currentTarget.open) setVisited(true); + }} + > - {sections.map((section, index) => ( - // biome-ignore lint/suspicious/noArrayIndexKey: sections are a positional, immutable parse of one prompt. -
-

- {sectionTitle(section.tag)} -

-
{section.body}
-
- ))} + {visited && + sections.map((section, index) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: sections are a positional, immutable parse of one prompt. +
+

+ {sectionTitle(section.tag)} +

+
{section.body}
+
+ ))}
); } @@ -555,9 +573,16 @@ function Disclosure({ footer?: ReactNode; children: ReactNode; }) { + const focused = useContext(RowContext).focused === `item:${item.id}`; + const [visited, setVisited] = useState(focused); + // A focused arrival needs its body in the commit that marks and scrolls it. + if (focused && !visited) setVisited(true); return (
{ + if (event.currentTarget.open) setVisited(true); + }} data-status={item.type === "tool" ? item.status : undefined} > @@ -574,8 +599,8 @@ function Disclosure({ /> - {children &&
{children}
} - {footer} + {visited && children &&
{children}
} + {visited && footer}
); } @@ -614,7 +639,7 @@ function Item({ item: TranscriptItem; agentName: string; }) { - const avatarSource = useContext(AgentAvatarSource); + const { picture: avatarSource } = useContext(RowContext); switch (item.type) { case "system": return ; From 2d5aec07ca63d6218b86e70f85e351f28a0b23ff Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 20 Nov 2026 22:53:57 -0500 Subject: [PATCH 02/37] test(goose): expand the transcript prompt before checking its body Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/goose/tabs.test.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/bundled/goose/tabs.test.tsx b/src/bundled/goose/tabs.test.tsx index e5db3d75bf..663b04680a 100644 --- a/src/bundled/goose/tabs.test.tsx +++ b/src/bundled/goose/tabs.test.tsx @@ -1045,7 +1045,10 @@ it("lists the agent's saved conversations and reads one's transcript by id, with expect( await screen.findByText("Hi from goose", { selector: "summary span" }), ).toBeInTheDocument(); - expect(screen.getAllByText(/@Gander what's up\?/).length).toBeGreaterThan(0); + await user.click(screen.getByText("Request", { selector: "summary span" })); + expect( + await screen.findByText(/@Gander what's up\?/, { selector: "p" }), + ).toBeVisible(); expect(listings(fake)).toEqual([]); }); From 69fbe752be6730ce9025ad29e98d18ba51d1023f Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Fri, 20 Nov 2026 22:58:04 -0500 Subject: [PATCH 03/37] test(markdown): check trust rules in the expanded transcript reply Co-authored-by: Jello Signed-off-by: LordMelkor --- src/features/markdown/trust.test.tsx | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/features/markdown/trust.test.tsx b/src/features/markdown/trust.test.tsx index 499f52b222..9cd8fbcf3b 100644 --- a/src/features/markdown/trust.test.tsx +++ b/src/features/markdown/trust.test.tsx @@ -1,7 +1,13 @@ // @vitest-environment jsdom // Each screen's raw-HTML, image and URL policy, recorded before the shared // renderer existed. Only Attention changes: it gained GFM autolinks. -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from "@testing-library/react"; import type { ReactElement } from "react"; import { afterEach, expect, it } from "vitest"; import { PluginReadme } from "../../app/PluginReadme"; @@ -133,11 +139,15 @@ async function observe(screenName: string, element: ReactElement) { const { container } = render(element, { wrapper: ToastProvider }); if (screenName === "memory") fireEvent.click(await screen.findByRole("button", { name: "core" })); + if (screenName === "transcript") + fireEvent.click(screen.getByText("Ada", { selector: "summary span" })); const selector = BODIES[screenName]; const root = selector - ? (((await screen.findAllByText(() => true)) && - container.querySelector(selector)) ?? - container) + ? await waitFor(() => { + const body = container.querySelector(selector); + if (!body) throw new Error(`Waiting for ${screenName} Markdown`); + return body; + }) : container; const record = { elements: ["script", "mark", "img"] From d93deb3f423e926a1a56b530656982545391e740 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 00:14:32 -0500 Subject: [PATCH 04/37] Show recent Claude activity before loading earlier turns Co-authored-by: Jello Signed-off-by: LordMelkor --- docs/buzz-help.md | 3 + src/bundled/claude-code/runtime.ts | 64 +++- src/bundled/claude-code/tabs.test.tsx | 82 +++++- src/bundled/claude-code/tabs.tsx | 95 +++++- src/bundled/claude-code/transcript.test.ts | 275 +++++++++++++++++- src/bundled/claude-code/transcript.ts | 105 ++++++- .../agents/ActivityTranscript.test.tsx | 163 ++++++++++- src/features/agents/ActivityTranscript.tsx | 99 ++++++- 8 files changed, 841 insertions(+), 45 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index e45c7e542a..83d6fc5c0e 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1856,6 +1856,9 @@ If an agent reports incompatible synced settings, choose the **Previous Versions - **Activity**, where the agent type provides it, shows sessions and their transcripts in the agent's profile. An open transcript updates by itself while the agent works; **Refresh transcript** stays at the top as you scroll. + A local Claude transcript can open on its latest activity. Choose **Load + earlier activity** to load the available history, up to 50 turns. Find on + screen searches the loaded rows. Once goose agents run through the agent gateway, a goose turn woken in a conversation by a plugin, watch or timer that ran without the gateway shows "Ran without the agent gateway" beside its prompt only while the app keeps diff --git a/src/bundled/claude-code/runtime.ts b/src/bundled/claude-code/runtime.ts index 1b40dc9029..b93caa084f 100644 --- a/src/bundled/claude-code/runtime.ts +++ b/src/bundled/claude-code/runtime.ts @@ -133,7 +133,9 @@ import { readLatestTurns, readSessionTitle, readTranscript, + readTranscriptPreview, withNotices, + type ClaudeTranscript, type Conversation, type SessionsPlace, } from "./transcript"; @@ -849,16 +851,62 @@ export class ClaudeRuntime { ? `${REMOTE_TRANSCRIPTS}. They aren't attributed in the agent gateway yet.` : `${REMOTE_TRANSCRIPTS}.`, ); + return this.readActivity( + readTranscript, + conversation, + workspace, + working, + signal, + ); + } + + async transcriptPreview( + conversation: Conversation, + workspace: string, + working: boolean, + signal: AbortSignal, + ) { + const { agent, sessionId } = conversation; + const key = conversation.community + ? COMMUNITY_SESSION + : conversationKey(conversation.channelId, conversation.root); + const saved = () => this.savedSessions(agent).get(key)?.id; + if ( + !sessionId || + saved() !== sessionId || + !this.host.spawn || + this.target || + this.bound(agent) || + (await this.inspect?.(agent)) + ) + return undefined; + signal.throwIfAborted(); + const preview: ClaudeTranscript | undefined = await this.readActivity( + readTranscriptPreview, + conversation, + workspace, + working, + signal, + key, + ); + signal.throwIfAborted(); + return saved() === sessionId && !this.bound(agent) ? preview : undefined; + } + + private readActivity( + read: typeof readTranscript, + conversation: Conversation, + workspace: string, + working: boolean, + signal: AbortSignal, + key = conversation.community + ? COMMUNITY_SESSION + : conversationKey(conversation.channelId, conversation.root), + ) { const prompts = this.prompts(conversation.agent); - return readTranscript( + return read( this.spawn, - this.place( - conversation.agent, - conversation.community - ? COMMUNITY_SESSION - : conversationKey(conversation.channelId, conversation.root), - workspace, - ), + this.place(conversation.agent, key, workspace), conversation, working, signal, diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 3b34d1e103..056ac29b00 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -44,7 +44,7 @@ import { ToastProvider } from "../../shared/design-system/ui/Toast"; import { AgentCreateDialog } from "../agents/AgentCreateDialog"; import { manifestProcesses } from "./claude-testing"; import { apply, inject } from "./index"; -import { type Config, DEFAULT_CONFIG } from "./runtime"; +import { ClaudeRuntime, type Config, DEFAULT_CONFIG } from "./runtime"; import { ClaudeSetup } from "./setup"; import { ClaudeAuth, KEY_ONCE } from "./auth"; import { ClaudeDefaults } from "./defaults"; @@ -236,7 +236,8 @@ function applied({ const name = step === "run" ? "claude" : (step ?? id); const args = (options.args ?? []).slice(step ? 3 : 0).join(" "); // The manifest's listing and search run for real on a copy of `files`. - if (name === "list" || name === "starts") return listed(name, options); + if (["list", "starts", "size", "read-page"].includes(name)) + return listed(name, options); if (name === "workspace" || name === "read") { const file = files[args]; queueMicrotask(() => @@ -487,6 +488,9 @@ it("lists saved conversations and shows one's transcript, or that it is gone", a expect( screen.getByText("Two files.", { selector: "summary span" }), ).toBeVisible(); + expect( + screen.queryByRole("button", { name: /earlier activity/i }), + ).toBeNull(); await user.click(screen.getByRole("button", { name: "Refresh transcript" })); await waitFor(() => expect( @@ -505,6 +509,77 @@ it("lists saved conversations and shows one's transcript, or that it is gone", a expect(save).not.toHaveBeenCalled(); }); +it("keeps an untouched tail on working changes until earlier activity is requested", async () => { + const key = "channel"; + localStorage.setItem( + "buzz.claude-code.sessions.v1", + JSON.stringify({ + [agent().key]: { [key]: { id: "kept", seen: 0, at: 1 } }, + }), + ); + const question = (uuid: string) => + JSON.stringify({ + uuid, + type: "user", + timestamp: "2026-10-09T10:00:00Z", + message: { + content: `\nEvent ID: ${uuid}\nContent: ${uuid}\nTags: []\n`, + }, + }); + const file = [ + question("earlier"), + JSON.stringify({ type: "progress", data: "x".repeat(2 ** 21) }), + question("newest"), + ].join("\n"); + const Activity = tab( + installed({ files: { "./-Users-me--buzz/kept.jsonl": file } }).type, + 1, + ); + const sessions = vi + .spyOn(ClaudeRuntime.prototype, "sessions") + .mockReturnValue([]); + const preview = vi.spyOn(ClaudeRuntime.prototype, "transcriptPreview"); + const canonical = vi.spyOn(ClaudeRuntime.prototype, "transcript"); + const page = () => ; + const view = render(page()); + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: /^View transcript/ })); + await screen.findByText("newest", { selector: "summary span" }); + for (const busy of [true, false]) { + const count = preview.mock.calls.length; + sessions.mockReturnValue([{ key, busy }]); + view.rerender(page()); + await waitFor(() => + expect( + preview.mock.calls.length + canonical.mock.calls.length, + ).toBeGreaterThan(count), + ); + expect(canonical).not.toHaveBeenCalled(); + await act(async () => { + await preview.mock.results.at(-1)?.value; + }); + expect( + screen.queryByText("earlier", { selector: "summary span" }), + ).toBeNull(); + } + const load = screen.getByRole("button", { name: /earlier activity/i }); + expect(load.closest('[data-transcript-history="partial"]')).toBeVisible(); + canonical.mockRejectedValueOnce(new Error("history unavailable")); + await user.click(load); + expect(await screen.findByRole("alert")).toHaveTextContent( + "history unavailable", + ); + expect( + screen.getByText("newest", { selector: "summary span" }), + ).toBeVisible(); + await user.click(load); + expect( + await screen.findByText("earlier", { selector: "summary span" }), + ).toBeVisible(); + expect(canonical).toHaveBeenCalledTimes(2); + expect(load).not.toBeInTheDocument(); +}); + it("reads an open transcript again in place when its conversation's session changes", async () => { const thread = `channel/${"e".repeat(64)}`; const saved = (id: string) => @@ -680,6 +755,9 @@ it("shows the transcript and that sessions may be missing when some history cann expect( screen.getByText(/sessions may be missing\. Refresh to try again\./), ).toHaveTextContent(/unreadable\.jsonl/); + expect( + screen.queryByRole("button", { name: /earlier activity/i }), + ).toBeNull(); expect(screen.queryByRole("alert")).toBeNull(); }); diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 515251fdff..57fd1f36fc 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -14,6 +14,7 @@ import { ProviderDialogActions } from "../../features/agents/ProviderDialogActio import { Fragment, type ReactNode, + useContext, useEffect, useRef, useId, @@ -21,6 +22,7 @@ import { useSyncExternalStore, } from "react"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; +import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; import { AgentInstructions } from "../../features/agents/AgentInstructions"; import { CreateModelChoices } from "../../features/agents/CreateModelChoices"; @@ -994,17 +996,79 @@ export function createTabs({ working: boolean; }) { const workspace = readConfig(agent.config).workspace; + const input = JSON.stringify([workspace, conversation.sessionId]); + const focus = useContext(TranscriptFocus); + const [history, setHistory] = useState({ + input, + attempt: focus ? 1 : 0, + loading: false, + }); + const canonical = useRef(undefined); + if (history.input !== input || (focus && !history.attempt)) { + setHistory({ input, attempt: focus ? 1 : 0, loading: false }); + } + const loadEarlier = () => + setHistory((old) => + old.loading + ? old + : { + ...old, + attempt: old.attempt + 1, + loading: true, + }, + ); return ( - runtime.transcript(conversation, workspace, working, signal) - } - readLatest={(signal, held) => - runtime.latestTurns(conversation, workspace, working, signal, held) - } + read={async (signal) => { + if (!history.attempt && canonical.current !== input) { + const tail = await runtime.transcriptPreview( + conversation, + workspace, + working, + signal, + ); + signal.throwIfAborted(); + if (tail) return { ...tail, historyPreview: true as const }; + } + try { + const result = await runtime.transcript( + conversation, + workspace, + working, + signal, + ); + signal.throwIfAborted(); + canonical.current = input; + return result; + } finally { + if (history.loading && !signal.aborted) { + setHistory((current) => + current === history ? { ...current, loading: false } : current, + ); + } + } + }} + readLatest={async (signal, held) => { + const turns = await runtime.latestTurns( + conversation, + workspace, + working, + signal, + held, + ); + signal.throwIfAborted(); + if ( + !turns || + (turns.length && + !held.some((turn) => turn.turnId === turns[0]?.turnId)) + ) { + canonical.current = input; + } + return turns; + }} readKey={`${conversation.key}\u0000${workspace}`} - readAgain={conversation.sessionId ?? ""} + readAgain={JSON.stringify([input, history.attempt])} working={working} reading="Reading the Claude session…" failed="Could not read the Claude session" @@ -1016,6 +1080,21 @@ export function createTabs({ } notes={(transcript) => ( <> + {"historyPreview" in transcript && ( +
+ + Earlier activity is not loaded.{" "} + + +
+ )} {transcript.incomplete && (

Some of this conversation’s sessions may be missing. Refresh to @@ -1025,7 +1104,7 @@ export function createTabs({

)} - {transcript.more && ( + {transcript.more && !("historyPreview" in transcript) && (

{transcript.turns.length ? `Showing the latest ${transcript.turns.length === 1 ? "turn" : `${transcript.turns.length} turns`}.` diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 03e09e5ba0..53be01a8dd 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -14,11 +14,13 @@ import type { HostProcessOptions } from "../../features/host/service"; import { manifestProcesses } from "./claude-testing"; import manifest from "./manifest.json"; import type { EventData } from "../../features/relay/events"; -import { localStore } from "../../features/agents/state"; +import { fileStore, localStore } from "../../features/agents/state"; import type { TranscriptTurn } from "../../features/agents/activity-transcript"; +import { conversationKey } from "../../features/agents/conversation-folders"; import { sessionPrompts } from "../../features/agents/session-prompts"; import { steerPrompt, turnPrompt } from "./prompt"; import { ClaudeRuntime } from "./runtime"; +import { localSessions } from "./sessions"; import { claudeTurns, projectName, @@ -364,6 +366,277 @@ function host(files: Record) { return { spawn, reads, home }; } +const savedPath = "./-Users-me--buzz/session-1.jsonl"; + +function previewHost(files: Record) { + const { spawn, reads } = host(files); + const storage = fileStore(new Map(), async () => {}); + const saved = localSessions(storage, agent); + saved.set(conversationKey(conversation.channelId, root), { + id: conversation.sessionId, + at: 1000, + seen: 0, + }); + const runtime = new ClaudeRuntime( + { spawn }, + () => undefined, + async () => null, + storage, + ); + const signal = new AbortController().signal; + return { runtime, spawn, reads, signal }; +} + +it("opens only the bound saved tail before reading canonical order across sessions", async () => { + const { runtime, spawn, reads, signal } = previewHost({ + [savedPath]: [ + line("user", turn("before the clock rolled back"), { + uuid: "before", + timestamp: "2026-01-03T00:00:00Z", + }), + line("assistant", [{ type: "text", text: "x".repeat(3 << 20) }]), + line("assistant", [{ type: "text", text: "part of the older turn" }]), + line("user", turn("recent saved prompt"), { + uuid: "recent", + timestamp: "2026-01-01T00:00:00Z", + }), + line("assistant", [{ type: "text", text: "recent saved reply" }]), + ].join("\n"), + "./-Users-me--buzz/discovered.jsonl": line( + "user", + turn("discovered prompt"), + { uuid: "discovered", timestamp: "2026-01-02T00:00:00Z" }, + ), + }); + const preview = await runtime.transcriptPreview( + conversation, + "~/.buzz", + false, + signal, + ); + expect(preview).toMatchObject({ + more: true, + turns: [ + { + turnId: "recent", + newSession: false, + continued: true, + partial: false, + items: [ + { type: "prompt", text: "recent saved prompt" }, + { type: "message", text: "recent saved reply" }, + ], + }, + ], + }); + expect(reads).toHaveLength(0); + expect( + spawn.mock.calls.some(([id]) => id === "list" || id === "starts"), + ).toBe(false); + expect( + spawn.mock.calls + .filter(([id]) => id === "read-page") + .map(([, options]) => options?.args?.[2]), + ).toEqual(["2"]); + + const canonical = await runtime.transcript( + conversation, + "~/.buzz", + false, + signal, + ); + expect(canonical?.turns.map(({ turnId }) => turnId)).toEqual([ + "recent", + "discovered", + "before", + ]); + expect(canonical?.more).toBe(false); +}); + +it("leaves a visible clock rollback to canonical timestamp order", async () => { + const { runtime, signal } = previewHost({ + [savedPath]: [ + line("system", "x".repeat(3 << 20)), + line("user", turn("before rollback"), { + uuid: "before", + timestamp: "2026-01-02T00:00:00Z", + }), + line("user", turn("after rollback"), { + uuid: "after", + timestamp: "2026-01-01T00:00:00Z", + }), + ].join("\n"), + }); + await expect( + runtime.transcriptPreview(conversation, "~/.buzz", false, signal), + ).resolves.toBeUndefined(); + const canonical = await runtime.transcript( + conversation, + "~/.buzz", + false, + signal, + ); + expect(canonical?.turns.map(({ turnId }) => turnId)).toEqual([ + "after", + "before", + ]); +}); + +it("does not preview an ID saved for another agent or conversation, or only discovered on disk", async () => { + const { runtime, spawn, signal } = previewHost({ + [savedPath]: line("user", turn("saved prompt")), + "./-Users-me--buzz/discovered.jsonl": line( + "user", + turn("discovered prompt"), + ), + }); + for (const mismatch of [ + { agent: sam }, + { root: sam }, + { sessionId: "discovered" }, + ]) { + await expect( + runtime.transcriptPreview( + { ...conversation, ...mismatch }, + "~/.buzz", + false, + signal, + ), + ).resolves.toBeUndefined(); + } + expect(spawn).not.toHaveBeenCalled(); +}); + +it.each(["queued steer", "user steer"] as const)( + "leaves a clipped %s for canonical history even when another prompt fits", + async (kind) => { + const steer = steerPrompt(turn("follow-up")); + const clipped = + kind === "queued steer" + ? line("attachment", undefined, { + attachment: { type: "queued_command", prompt: steer }, + }) + : line("user", steer); + const { runtime, signal } = previewHost({ + [savedPath]: [ + line("user", turn("opening prompt")), + line("assistant", [ + { type: "thinking", thinking: "x".repeat(3 << 20) }, + ]), + clipped, + line("user", turn("later complete prompt")), + ].join("\n"), + }); + await expect( + runtime.transcriptPreview(conversation, "~/.buzz", false, signal), + ).resolves.toBeUndefined(); + const canonical = await runtime.transcript( + conversation, + "~/.buzz", + false, + signal, + ); + expect(canonical?.turns).toHaveLength(2); + expect(canonical?.turns[0]?.items).toContainEqual( + expect.objectContaining({ + type: "prompt", + steer: true, + text: "follow-up", + }), + ); + }, +); + +it.each(["discarded", "retained"] as const)( + "handles an orphan result in the %s turn without inventing a tool", + async (location) => { + const clippedResult = [ + { type: "tool_result", tool_use_id: "earlier-tool", content: "result" }, + ]; + const follow = turn("visible complete prompt"); + const { runtime, signal } = previewHost({ + [savedPath]: [ + line("user", turn("opening prompt")), + line("assistant", [ + { type: "tool_use", id: "earlier-tool", name: "Read", input: {} }, + ]), + line("assistant", [ + { type: "thinking", thinking: "x".repeat(3 << 20) }, + ]), + ...(location === "discarded" ? [line("user", clippedResult)] : []), + line("user", follow), + ...(location === "retained" ? [line("user", clippedResult)] : []), + line("assistant", [{ type: "text", text: "visible reply" }]), + ].join("\n"), + }); + const preview = await runtime.transcriptPreview( + conversation, + "~/.buzz", + false, + signal, + ); + if (location === "retained") expect(preview).toBeUndefined(); + else + expect(preview?.turns).toMatchObject([ + { + partial: false, + items: [ + { type: "prompt", text: "visible complete prompt" }, + { type: "message", text: "visible reply" }, + ], + }, + ]); + }, +); + +it("uses canonical discovery directly for a saved file small enough to fit one page", async () => { + const { runtime, spawn, signal } = previewHost({ + [savedPath]: line("user", turn("saved prompt")), + "./-Users-me--buzz/discovered.jsonl": line( + "user", + turn("discovered prompt"), + ), + }); + await expect( + runtime.transcriptPreview(conversation, "~/.buzz", false, signal), + ).resolves.toBeUndefined(); + expect(spawn.mock.calls.some(([id]) => id === "read-page")).toBe(false); + const canonical = await runtime.transcript( + conversation, + "~/.buzz", + false, + signal, + ); + expect(canonical?.turns.map(({ sessionId }) => sessionId)).toEqual([ + "session-1", + "discovered", + ]); +}); + +it("leaves a 9 MiB session record for canonical history", async () => { + const reply = "x".repeat(9 << 20); + const { runtime, reads, signal } = previewHost({ + [savedPath]: [ + line("user", turn("opening prompt")), + line("assistant", [{ type: "text", text: reply }]), + ].join("\n"), + }); + await expect( + runtime.transcriptPreview(conversation, "~/.buzz", false, signal), + ).resolves.toBeUndefined(); + expect(reads).toHaveLength(0); + const canonical = await runtime.transcript( + conversation, + "~/.buzz", + false, + signal, + ); + expect(canonical?.turns[0]?.items[1]).toMatchObject({ + type: "message", + text: reply, + }); +}); + it("reads the session file from the project of the agent's workspace", async () => { const { spawn, reads } = host({ "./-Users-me--buzz/session-1.jsonl": file(), diff --git a/src/bundled/claude-code/transcript.ts b/src/bundled/claude-code/transcript.ts index c2a728fcbd..4dd451d071 100644 --- a/src/bundled/claude-code/transcript.ts +++ b/src/bundled/claude-code/transcript.ts @@ -116,6 +116,7 @@ export function claudeTurns( conversation: Session, working: boolean, name?: Names, + tail?: { uncertain: boolean }, ): TranscriptTurn[] { const turns: TranscriptTurn[] = []; const tools = new Map(); @@ -156,7 +157,8 @@ export function claudeTurns( if (!entry || entry.isSidechain || entry.isMeta) continue; const id = str(entry.uuid); if (!id) continue; - const at = Date.parse(str(entry.timestamp)) || last; + const timestamp = Date.parse(str(entry.timestamp)); + const at = timestamp || last; if (entry.type === "attachment") { const attachment = object(entry.attachment); if (attachment?.type !== "queued_command") continue; @@ -176,6 +178,8 @@ export function claudeTurns( if (entry.type === "user" && !results.length) { const { item } = prompt(id, at, text(message.content), name); const current = item.steer ? turns.at(-1) : undefined; + if (tail && (!timestamp || (item.steer && (!current || current.partial)))) + tail.uncertain = true; (current ?? turn(id, at, false)).items.push(item); last = at; continue; @@ -195,7 +199,10 @@ export function claudeTurns( }); } const tool = tools.get(str(result.tool_use_id)); - if (!tool) continue; + if (!tool) { + if (tail && !sent && !current.partial) tail.uncertain = true; + continue; + } tool.output = text(result.content); tool.status = result.is_error ? "failed" : "completed"; tool.completedAt = at; @@ -396,6 +403,83 @@ export const OVERSIZED_READ_MS = 30_000; /** When each such session was last left to a full read. */ const oversized = new Map(); +async function readTail( + spawn: Spawn, + path: string, + signal: AbortSignal, + size: number, +) { + const from = Math.max(0, Math.ceil(size / (1 << 20)) - LATEST_MIB); + const bytes = await readFile( + spawn, + "~/.claude/projects", + path, + signal, + undefined, + "read-page", + [String(from), String(LATEST_MIB)], + ); + const start = from ? bytes.indexOf(10) + 1 : 0; + return { + from, + text: from && !start ? undefined : decode(bytes.subarray(start)), + }; +} + +export async function readTranscriptPreview( + spawn: Spawn, + workspace: SessionsPlace, + conversation: Conversation, + working: boolean, + signal: AbortSignal, + nameOf?: Names, +) { + const { sessionId, channelId, root } = conversation; + if (!sessionId || !/^[\w-]+$/.test(sessionId)) return undefined; + try { + const project = await workspaceProject(spawn, workspace, signal); + if (!project) return undefined; + const path = `./${project}/${sessionId}.jsonl`; + const size = await sizeOf(spawn, path, signal); + if (size <= LATEST_MIB * (1 << 20)) return undefined; + const { from, text } = await readTail(spawn, path, signal, size); + signal.throwIfAborted(); + if (!text) return undefined; + const boundary = { uncertain: false }; + const turns = claudeTurns( + text, + { sessionId, channelId, ...(root ? { root } : {}) }, + working, + nameOf, + boundary, + ); + const first = turns[0]; + if ( + boundary.uncertain || + (first?.partial && + first.items.some((item) => item.type === "prompt" && item.steer)) + ) + return undefined; + const whole = turns.filter((turn) => !turn.partial); + const firstWhole = whole[0]; + if ( + !firstWhole || + whole.some( + (turn, index) => turn.startedAt < (whole[index - 1]?.startedAt ?? 0), + ) + ) + return undefined; + if (from) firstWhole.newSession = false; + return { + turns: whole.slice(-TURN_LIMIT), + more: true, + } satisfies ClaudeTranscript; + } catch { + signal.throwIfAborted(); + return undefined; + } +} + /** The whole turns in the last {@link LATEST_MIB} MiB of the conversation's * saved session, oldest first; undefined with no saved session. While a turn * is larger than that, none, so what is shown stays, except undefined every @@ -420,27 +504,16 @@ export async function readLatestTurns( if (!project || !sessionId) return undefined; const path = `./${project}/${sessionId}.jsonl`; const size = await sizeOf(spawn, path, signal); - const from = Math.max(0, Math.floor((size - 1) / (1 << 20)) - LATEST_MIB + 1); - const bytes = await readFile( - spawn, - "~/.claude/projects", - path, - signal, - undefined, - "read-page", - [String(from), String(LATEST_MIB)], - ); + const { from, text } = await readTail(spawn, path, signal, size); const tooLarge = () => { const last = oversized.get(path); if (last !== undefined && Date.now() - last < OVERSIZED_READ_MS) return []; oversized.set(path, Date.now()); return undefined; }; - // A chunk from partway through starts partway through a line. - const start = from ? bytes.indexOf(10) + 1 : 0; - if (from && !start) return tooLarge(); + if (text === undefined) return tooLarge(); const turns = claudeTurns( - decode(bytes.subarray(start)), + text, { sessionId, channelId: conversation.channelId, diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index d0a9775be8..04fdfc7edc 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -508,6 +508,162 @@ it("opens at the latest turn and follows new ones until the reader scrolls up", shared.remove(); }); +it.each([ + { + situation: "after the reader moves during loading", + fits: false, + appended: false, + shortened: false, + expectedTop: 205, + }, + { + situation: + "when the partial transcript fits and opens at the natural latest", + fits: true, + appended: false, + shortened: false, + expectedTop: 90, + }, + { + situation: "when the full read prepends history and appends live rows", + fits: true, + appended: true, + shortened: false, + expectedTop: 210, + }, + { + situation: "when native restoration scroll fires inside the follow margin", + fits: false, + appended: false, + shortened: true, + expectedTop: 205, + }, + { + situation: "when a tall read prepends history and appends live rows", + fits: false, + appended: true, + shortened: false, + expectedTop: 205, + }, +])( + "keeps the open disclosure and its viewport $situation", + async ({ fits, appended, shortened, expectedTop }) => { + const item = (id: string, text: string) => ({ + id, + text, + type: "thought" as const, + at: 1, + }); + const turn: TranscriptTurn = { + turnId: "ongoing", + channelId: null, + threadRootId: null, + triggeringEventIds: [], + newSession: false, + config: [], + startedAt: 1, + partial: false, + items: [ + item("first", "First"), + item("middle", "Middle\n\nDetails"), + item("last", "Last"), + ], + }; + const older = item("history", "Older"); + const newer = item("live", "Newer"); + const view = document.body.appendChild(document.createElement("div")); + view.style.overflowY = "auto"; + const prependHeight = () => + view.querySelector('[data-entry="item:history"]') ? 150 : 0; + const viewportHeight = 150; + const rowLengths = fits ? [20, 50, 20] : [80, 140, 100]; + const contentHeight = fits ? 90 : 320; + const naturalHeight = () => + contentHeight + + prependHeight() - + (view.querySelector('[data-entry="item:last"]') ? 0 : 100) + + (view.querySelector('[data-entry="item:live"]') ? 120 : 0); + Object.defineProperty(view, "clientHeight", { value: viewportHeight }); + Object.defineProperty(view, "scrollHeight", { + get: () => Math.max(viewportHeight, naturalHeight()), + }); + let scrollTop = 0; + Object.defineProperty(view, "scrollTop", { + get: () => scrollTop, + set: (desired: number) => { + scrollTop = Math.min( + Math.max(0, desired), + view.scrollHeight - viewportHeight, + ); + }, + }); + const canonicalItems = shortened ? turn.items.slice(0, -1) : turn.items; + const show = (history: boolean, live = appended) => ( + "working"} + /> + ); + try { + const { rerender } = render(show(false), { container: view }); + const timeline = view.firstElementChild; + const renderedTurn = timeline?.lastElementChild; + if (!timeline || !renderedTurn) + throw new Error("Missing transcript turn"); + Object.defineProperty(renderedTurn, "getBoundingClientRect", { + value: () => new DOMRect(0, -scrollTop, 100, naturalHeight()), + }); + const rowStarts = [0, rowLengths[0] ?? 0, fits ? 70 : 220]; + for (const [index, entry] of [ + ...renderedTurn.querySelectorAll("[data-entry]"), + ].entries()) { + Object.defineProperty(entry, "getBoundingClientRect", { + value: () => + new DOMRect( + 0, + (rowStarts[index] ?? 0) + prependHeight() - scrollTop, + 100, + rowLengths[index], + ), + }); + } + const summary = screen.getByText("Middle"); + await userEvent.click(summary); + expect(screen.getByText("Details")).toBeVisible(); + if (!fits) { + view.scrollTop = 95; + fireEvent.scroll(view); + view.scrollTop = 55; + } + + rerender(show(true)); + expect(view.scrollTop).toBe(expectedTop); + expect(screen.getByText("Middle")).toBe(summary); + expect(screen.getByText("Details")).toBeVisible(); + if (shortened) { + view.dispatchEvent(new Event("scroll")); + rerender(show(true, true)); + expect(view.scrollTop).toBe(expectedTop); + } + } finally { + view.remove(); + } + }, +); + it("shows the turn a message began, its prompt open, instead of the latest, once", async () => { const id = (n: number) => String(n).repeat(64); // A retry asks the same message again, so `event` can repeat. @@ -566,12 +722,12 @@ it("shows the turn a message began, its prompt open, instead of the latest, once const header = (node: HTMLDivElement | null) => { if (node) Object.defineProperty(node, "offsetHeight", { value: 40 }); }; - const show = (turns: TranscriptTurn[], events: string[]) => ( + const show = (turns: TranscriptTurn[], events: string[], partial = false) => (

"ended"} /> @@ -589,6 +745,9 @@ it("shows the turn a message began, its prompt open, instead of the latest, once // reader's own move. const trigger = document.body.appendChild(document.createElement("button")); trigger.focus(); + rerender(show([turn(1), turn(2), turn(3)], ["reply", id(2)], true)); + expect(done).not.toHaveBeenCalled(); + expect(shown).toEqual([]); rerender(show([turn(1), turn(2), turn(3)], ["reply", id(2)])); expect(shown).toEqual(["item:p2"]); // It starts below the sticky header, with room for its focus ring, and diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index 8795cf66cf..761dd478b1 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -1,4 +1,5 @@ import { + Component, Fragment, createContext, useContext, @@ -209,12 +210,16 @@ const END_SLACK = 32; function useFollowLatest(content: unknown, enabled: boolean) { const timeline = useRef(null); const following = useRef(true); + const restoredTop = useRef(undefined); useLayoutEffect(() => { const view = enabled ? scroller(timeline.current) : undefined; if (!view) return; const read = () => { + const top = view.scrollTop; + if (restoredTop.current === top) return; + restoredTop.current = undefined; following.current = - view.scrollHeight - view.scrollTop - view.clientHeight <= END_SLACK; + view.scrollHeight - top - view.clientHeight <= END_SLACK; }; view.addEventListener("scroll", read, { passive: true }); return () => view.removeEventListener("scroll", read); @@ -224,7 +229,73 @@ function useFollowLatest(content: unknown, enabled: boolean) { const view = enabled && following.current && scroller(timeline.current); if (view) view.scrollTop = view.scrollHeight; }, [content, enabled]); - return { timeline, following }; + return { timeline, following, restoredTop }; +} + +type HistoryAnchor = { view: HTMLElement; row: HTMLElement; offset: number }; + +class TranscriptTimeline extends Component<{ + scroll: ReturnType; + partial: boolean; + focused: boolean; + children: ReactNode; +}> { + getSnapshotBeforeUpdate({ partial }: { partial: boolean }) { + if (!partial || this.props.partial || this.props.focused) return null; + const { timeline, following } = this.props.scroll; + const body = timeline.current; + const view = scroller(body); + if (!body || !view || view.scrollHeight <= view.clientHeight) return null; + if ( + following.current && + view.scrollHeight - view.scrollTop - view.clientHeight <= END_SLACK + ) + return null; + following.current = false; + const top = view.getBoundingClientRect().top + view.clientTop; + const header = body + .closest("[data-transcript]") + ?.querySelector(":scope > [data-transcript-header]"); + const visibleTop = Math.max( + top, + header?.getBoundingClientRect().bottom ?? top, + ); + const first = (selector: string) => + [...body.querySelectorAll(selector)].find((row) => { + const rect = row.getBoundingClientRect(); + return rect.bottom > visibleTop && rect.top < top + view.clientHeight; + }); + const row = + first(":scope > article > [data-entry]") ?? first(":scope > article"); + if (!row) return null; + return { view, row, offset: row.getBoundingClientRect().top - top }; + } + + componentDidUpdate( + _previous: unknown, + _state: unknown, + anchor?: HistoryAnchor | null, + ) { + const { timeline, restoredTop } = this.props.scroll; + const body = timeline.current; + if (!anchor || !body?.contains(anchor.row)) return; + const { view, row, offset } = anchor; + const top = view.getBoundingClientRect().top + view.clientTop; + const shift = row.getBoundingClientRect().top - top - offset; + view.scrollTop += shift; + restoredTop.current = view.scrollTop; + } + + render() { + return ( +
+ {this.props.children} +
+ ); + } } /** Shows the focused entry once it is loaded, opening its prompt, instead of @@ -233,9 +304,11 @@ function useShowFocused( transcript: Transcript, timeline: { current: HTMLDivElement | null }, following: { current: boolean }, + partial: boolean, ) { const focus = useContext(TranscriptFocus); - const entry = focus && focusedEntry(transcript, focus.events); + const entry = + !partial && focus ? focusedEntry(transcript, focus.events) : undefined; useLayoutEffect(() => { if (!focus || !entry) return; const element = [ @@ -297,7 +370,7 @@ export function ActivityTranscript({ agentKey, community, }: { - transcript: Transcript; + transcript: Transcript & { historyPreview?: true }; agentName: string; state: (turnId: string) => TurnState | undefined; /** Paging controls shown above the oldest loaded turn. */ @@ -311,8 +384,14 @@ export function ActivityTranscript({ agentKey?: string; community?: string | undefined; }) { - const { timeline, following } = useFollowLatest(transcript, follow); - const focused = useShowFocused(transcript, timeline, following); + const partial = transcript.historyPreview === true; + const scroll = useFollowLatest(transcript, follow); + const focused = useShowFocused( + transcript, + scroll.timeline, + scroll.following, + partial, + ); const agents = useContext(AgentsContext); const relay = useSyncExternalStore( agents?.subscribe ?? noSubscribe, @@ -339,7 +418,11 @@ export function ActivityTranscript({ return ( -
+ {before} {!transcript.turns.length && (

@@ -365,7 +448,7 @@ export function ActivityTranscript({ /> ))} -

+
); From 30f1d7b13a6a234f7c9bb74cd3155d24bd3ca2b8 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 00:24:48 -0500 Subject: [PATCH 05/37] Hold the reading position when a session prompt moves Co-authored-by: Jello Signed-off-by: LordMelkor --- .../agents/ActivityTranscript.test.tsx | 71 +++++++++++++++++++ src/features/agents/ActivityTranscript.tsx | 40 +++++++---- 2 files changed, 99 insertions(+), 12 deletions(-) diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index 04fdfc7edc..1789e75cfa 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -664,6 +664,77 @@ it.each([ }, ); +it.each([ + { promptHeight: 40, expectedAnchor: "item:reading" }, + { promptHeight: 200, expectedAnchor: "turn:reading" }, +])( + "holds $expectedAnchor when the session prompt moves to an older turn", + ({ promptHeight, expectedAnchor }) => { + const turn = (id: string, startedAt: number) => + ({ + turnId: id, + startedAt, + sessionId: "s", + channelId: null, + threadRootId: null, + triggeringEventIds: [], + newSession: false, + config: [], + partial: false, + items: [{ type: "thought", id, at: startedAt, text: id }], + }) satisfies TranscriptTurn; + const reading = turn("reading", 2); + const show = (history: boolean) => ( + "ended"} + transcript={{ + ...(!history && { historyPreview: true }), + turns: withSessionPrompts( + history ? [turn("older", 1), reading] : [reading], + () => [{ label: "base", text: "Instructions" }], + ), + }} + /> + ); + const view = document.body.appendChild(document.createElement("div")); + view.style.overflowY = "auto"; + Object.defineProperty(view, "clientHeight", { value: 150 }); + const loaded = () => !!view.querySelector('[data-entry="turn:older"]'); + Object.defineProperty(view, "scrollHeight", { + get: () => (loaded() ? 700 : 500), + }); + try { + const { rerender } = render(show(false), { container: view }); + const entry = (id: string) => { + const el = view.querySelector(`[data-entry="${id}"]`); + if (!el) throw new Error(`Missing entry ${id}`); + return el; + }; + const rect = (top: number, height: number) => + new DOMRect(0, top - view.scrollTop, 100, height); + const prompt = entry("item:s:system-prompt"); + prompt.getBoundingClientRect = () => rect(20, promptHeight); + entry("turn:reading").getBoundingClientRect = () => + rect(loaded() ? 340 : 0, 360); + entry("item:reading").getBoundingClientRect = () => + rect(loaded() ? 360 : 20 + promptHeight, 130); + view.scrollTop = 25; + fireEvent.scroll(view); + const anchor = entry(expectedAnchor); + const offset = anchor.getBoundingClientRect().top; + rerender(show(true)); + expect(entry("item:s:system-prompt").closest("article")).toBe( + entry("turn:older"), + ); + expect(entry(expectedAnchor)).toBe(anchor); + expect(anchor.getBoundingClientRect().top).toBe(offset); + } finally { + view.remove(); + } + }, +); + it("shows the turn a message began, its prompt open, instead of the latest, once", async () => { const id = (n: number) => String(n).repeat(64); // A retry asks the same message again, so `event` can repeat. diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index 761dd478b1..1695aa6597 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -232,7 +232,10 @@ function useFollowLatest(content: unknown, enabled: boolean) { return { timeline, following, restoredTop }; } -type HistoryAnchor = { view: HTMLElement; row: HTMLElement; offset: number }; +type HistoryAnchor = { + view: HTMLElement; + candidates: { row: HTMLElement; offset: number }[]; +}; class TranscriptTimeline extends Component<{ scroll: ReturnType; @@ -260,15 +263,26 @@ class TranscriptTimeline extends Component<{ top, header?.getBoundingClientRect().bottom ?? top, ); - const first = (selector: string) => - [...body.querySelectorAll(selector)].find((row) => { - const rect = row.getBoundingClientRect(); - return rect.bottom > visibleTop && rect.top < top + view.clientHeight; - }); - const row = - first(":scope > article > [data-entry]") ?? first(":scope > article"); - if (!row) return null; - return { view, row, offset: row.getBoundingClientRect().top - top }; + const bottom = top + view.clientHeight; + const visible = (rect: DOMRect) => + rect.bottom > visibleTop && rect.top < bottom; + const turn = [ + ...body.querySelectorAll(":scope > article"), + ].find((article) => visible(article.getBoundingClientRect())); + if (!turn) return null; + const candidates: HistoryAnchor["candidates"] = []; + for (const row of turn.querySelectorAll( + ":scope > [data-entry]", + )) { + const rect = row.getBoundingClientRect(); + if (rect.top >= bottom) break; + if (visible(rect)) candidates.push({ row, offset: rect.top - top }); + } + candidates.push({ + row: turn, + offset: turn.getBoundingClientRect().top - top, + }); + return { view, candidates }; } componentDidUpdate( @@ -278,8 +292,10 @@ class TranscriptTimeline extends Component<{ ) { const { timeline, restoredTop } = this.props.scroll; const body = timeline.current; - if (!anchor || !body?.contains(anchor.row)) return; - const { view, row, offset } = anchor; + const survivor = anchor?.candidates.find(({ row }) => body?.contains(row)); + if (!anchor || !survivor) return; + const { view } = anchor; + const { row, offset } = survivor; const top = view.getBoundingClientRect().top + view.clientTop; const shift = row.getBoundingClientRect().top - top - offset; view.scrollTop += shift; From 2542d22cea499aa22d963b305738fec7f0786547 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 01:12:49 -0500 Subject: [PATCH 06/37] Contain transcript row painting while an agent works Co-authored-by: Jello Signed-off-by: LordMelkor --- src/features/agents/ActivityTranscript.module.css | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/features/agents/ActivityTranscript.module.css b/src/features/agents/ActivityTranscript.module.css index 9f3653891f..471dde5fd0 100644 --- a/src/features/agents/ActivityTranscript.module.css +++ b/src/features/agents/ActivityTranscript.module.css @@ -31,6 +31,10 @@ } .item { min-width: 0; + contain: paint; + /* Leave room for the summary's click target and keyboard outline. */ + padding: var(--space-1) var(--space-3); + margin: calc(-1 * var(--space-1)) calc(-1 * var(--space-3)); } .at { display: block; From a3e242410e24cbf3fe08275aed34f8f96d38fe2f Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 01:31:50 -0500 Subject: [PATCH 07/37] Contain transcript painting around each turn Co-authored-by: Jello Signed-off-by: LordMelkor --- src/features/agents/ActivityTranscript.module.css | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/features/agents/ActivityTranscript.module.css b/src/features/agents/ActivityTranscript.module.css index 471dde5fd0..d0e0c37915 100644 --- a/src/features/agents/ActivityTranscript.module.css +++ b/src/features/agents/ActivityTranscript.module.css @@ -13,6 +13,17 @@ max-width: 48rem; margin-inline: auto; } +/* Borrow panel inset so the turn can clip paint beyond the disclosure outlines. */ +[data-transcript] .timeline:has(> .turn) { + margin-inline: calc(-1 * var(--space-3)); +} +[data-transcript] .turn { + contain: paint; + box-sizing: border-box; + max-width: calc(48rem + 2 * var(--space-3)); + padding: var(--space-1) var(--space-3); + margin-block: calc(-1 * var(--space-1)); +} .session { display: flex; align-items: center; @@ -31,10 +42,6 @@ } .item { min-width: 0; - contain: paint; - /* Leave room for the summary's click target and keyboard outline. */ - padding: var(--space-1) var(--space-3); - margin: calc(-1 * var(--space-1)) calc(-1 * var(--space-3)); } .at { display: block; From 3d81b1ca0043ac0cbc8b871ddee3fd543dc3eeb0 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 02:24:08 -0500 Subject: [PATCH 08/37] Align transcript notes and exercise focused Claude history reads Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 234 ++++++++++++------ src/bundled/claude-code/transcript.test.ts | 12 +- .../agents/ActivityTranscript.module.css | 3 + .../agents/ActivityTranscript.test.tsx | 37 +-- 4 files changed, 172 insertions(+), 114 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 056ac29b00..97a1bf9819 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -1,5 +1,6 @@ import "../../../tests/sonner-dom"; import { + appendFileSync, chmodSync, mkdirSync, mkdtempSync, @@ -9,6 +10,9 @@ import { } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; +import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; +import { LIVE_READ_MS } from "../../features/agents/TranscriptPanel"; +import { readerInputs } from "../../features/profiles/target"; import { AgentTabs } from "../agents/AgentTabs"; import { useAgentSettingsHost } from "../agents/AgentSettingsHost"; import type { @@ -44,7 +48,7 @@ import { ToastProvider } from "../../shared/design-system/ui/Toast"; import { AgentCreateDialog } from "../agents/AgentCreateDialog"; import { manifestProcesses } from "./claude-testing"; import { apply, inject } from "./index"; -import { ClaudeRuntime, type Config, DEFAULT_CONFIG } from "./runtime"; +import { type Config, DEFAULT_CONFIG } from "./runtime"; import { ClaudeSetup } from "./setup"; import { ClaudeAuth, KEY_ONCE } from "./auth"; import { ClaudeDefaults } from "./defaults"; @@ -236,29 +240,12 @@ function applied({ const name = step === "run" ? "claude" : (step ?? id); const args = (options.args ?? []).slice(step ? 3 : 0).join(" "); // The manifest's listing and search run for real on a copy of `files`. - if (["list", "starts", "size", "read-page"].includes(name)) + if ( + ["list", "starts", "size", "read-page", "read", "workspace"].includes( + name, + ) + ) return listed(name, options); - if (name === "workspace" || name === "read") { - const file = files[args]; - queueMicrotask(() => - name === "workspace" - ? options.onStdout?.("/Users/me/.buzz\n") - : file === undefined - ? options.onStderr?.(`base64: ${args}: No such file or directory`) - : options.onStdout?.(btoa(file)), - ); - return { - write: async () => undefined, - end: async () => undefined, - kill: async () => undefined, - exited: new Promise((resolve) => - setTimeout( - () => resolve(name === "read" && file === undefined ? 1 : 0), - 0, - ), - ), - }; - } // Buzz's launcher answers 127 when it has no copy. const missing = name === "claude" && args === "--version" && !available; const streaming = args.includes("--input-format stream-json"); @@ -334,6 +321,8 @@ function applied({ }, agents: { storage, + core: async () => undefined, + tools: () => [], executionBinding: () => (remote ? { provider: "nexus/blox" } : undefined), inspectExecution: vi.fn(async () => remote ? { provider: "nexus/blox" } : undefined, @@ -509,77 +498,162 @@ it("lists saved conversations and shows one's transcript, or that it is gone", a expect(save).not.toHaveBeenCalled(); }); -it("keeps an untouched tail on working changes until earlier activity is requested", async () => { - const key = "channel"; +const earlierEvent = "e".repeat(64); +const sessionPrompt = (text: string, event = text) => + JSON.stringify({ + uuid: text, + type: "user", + timestamp: "2026-10-09T10:00:00Z", + message: { + content: `\n${JSON.stringify({ id: event, content: text })}\n`, + }, + }); + +function longTranscript() { localStorage.setItem( "buzz.claude-code.sessions.v1", JSON.stringify({ - [agent().key]: { [key]: { id: "kept", seen: 0, at: 1 } }, + [agent().key]: { channel: { id: "kept", seen: 0, at: 1 } }, }), ); - const question = (uuid: string) => - JSON.stringify({ - uuid, - type: "user", - timestamp: "2026-10-09T10:00:00Z", - message: { - content: `\nEvent ID: ${uuid}\nContent: ${uuid}\nTags: []\n`, - }, - }); - const file = [ - question("earlier"), - JSON.stringify({ type: "progress", data: "x".repeat(2 ** 21) }), - question("newest"), - ].join("\n"); - const Activity = tab( - installed({ files: { "./-Users-me--buzz/kept.jsonl": file } }).type, - 1, - ); - const sessions = vi - .spyOn(ClaudeRuntime.prototype, "sessions") - .mockReturnValue([]); - const preview = vi.spyOn(ClaudeRuntime.prototype, "transcriptPreview"); - const canonical = vi.spyOn(ClaudeRuntime.prototype, "transcript"); - const page = () => ; - const view = render(page()); + const file = "./-Users-me--buzz/kept.jsonl"; + const gap = JSON.stringify({ type: "progress", data: "x".repeat(2 ** 21) }); + const { home, type, spawn } = installed({ + channels: [], + files: { + [file]: [ + sessionPrompt("earlier", earlierEvent), + gap, + sessionPrompt("newest"), + ].join("\n"), + }, + }); + return { + Activity: tab(type, 1), + path: join(home, ".claude/projects", file), + gap, + startCompaction() { + if (!type.sessionControls) + throw new Error("Missing Claude session controls"); + const compact = type.sessionControls.run( + agent(), + { channelId: "channel" }, + "compact", + ); + return async () => { + const session = spawn.mock.calls.find(([, options]) => + options?.args?.includes("--resume"), + )?.[1]; + if (!session?.onStdout) + throw new Error("Claude did not resume the saved session"); + session.onStdout( + '{"type":"result","subtype":"success","session_id":"kept"}\n', + ); + await compact; + }; + }, + }; +} + +it("keeps an untouched tail on working changes until earlier activity is requested", async () => { + const { Activity, path, startCompaction } = longTranscript(); + render(); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: /^View transcript/ })); - await screen.findByText("newest", { selector: "summary span" }); - for (const busy of [true, false]) { - const count = preview.mock.calls.length; - sessions.mockReturnValue([{ key, busy }]); - view.rerender(page()); - await waitFor(() => - expect( - preview.mock.calls.length + canonical.mock.calls.length, - ).toBeGreaterThan(count), - ); - expect(canonical).not.toHaveBeenCalled(); - await act(async () => { - await preview.mock.results.at(-1)?.value; - }); - expect( - screen.queryByText("earlier", { selector: "summary span" }), - ).toBeNull(); - } - const load = screen.getByRole("button", { name: /earlier activity/i }); - expect(load.closest('[data-transcript-history="partial"]')).toBeVisible(); - canonical.mockRejectedValueOnce(new Error("history unavailable")); + const summary = { selector: "summary span" }; + await screen.findByText("newest", summary); + appendFileSync(path, `\n${sessionPrompt("while working")}`); + const finish = startCompaction(); + await screen.findByText("while working", summary); + expect(screen.queryByText("earlier", summary)).toBeNull(); + appendFileSync(path, `\n${sessionPrompt("after working")}`); + await act(finish); + await screen.findByText("after working", summary); + expect(screen.queryByText("earlier", summary)).toBeNull(); + expect(screen.getByText("Earlier activity is not loaded.")).toBeVisible(); + const load = screen.getByRole("button", { name: /load earlier activity/i }); + chmodSync(path, 0); await user.click(load); expect(await screen.findByRole("alert")).toHaveTextContent( - "history unavailable", + /permission denied/i, ); - expect( - screen.getByText("newest", { selector: "summary span" }), - ).toBeVisible(); + expect(screen.getByText("newest", summary)).toBeVisible(); + chmodSync(path, 0o600); await user.click(load); - expect( - await screen.findByText("earlier", { selector: "summary span" }), - ).toBeVisible(); - expect(canonical).toHaveBeenCalledTimes(2); + expect(await screen.findByText("earlier", summary)).toBeVisible(); expect(load).not.toBeInTheDocument(); }); +it("loads the missing history when a working session grows past the held tail", async () => { + const { Activity, path, gap, startCompaction } = longTranscript(); + render(); + await userEvent.click( + screen.getByRole("button", { name: /^View transcript/ }), + ); + await screen.findByText("Earlier activity is not loaded."); + appendFileSync(path, `\n${sessionPrompt("while working")}`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const finish = startCompaction(); + try { + await vi.waitFor(() => + screen.getByText("while working", { selector: "summary span" }), + ); + appendFileSync(path, `\n${gap}\n${sessionPrompt("after the gap")}`); + await act(async () => { + await vi.advanceTimersByTimeAsync(LIVE_READ_MS); + }); + vi.useRealTimers(); + expect( + await screen.findByText("after the gap", { selector: "summary span" }), + ).toBeVisible(); + expect( + screen.getByText("earlier", { selector: "summary span" }), + ).toBeVisible(); + expect(screen.queryByText("Earlier activity is not loaded.")).toBeNull(); + } finally { + vi.useRealTimers(); + await act(finish); + } +}); + +it.each(["on open", "after preview"])( + "shows the earlier focused turn %s", + async (when) => { + const { Activity } = longTranscript(); + const focus = { + events: [earlierEvent], + inputs: readerInputs(), + done: vi.fn(), + }; + const page = (focused: boolean) => ( + + + + ); + Element.prototype.scrollIntoView = () => {}; + try { + const { rerender } = render(page(when === "on open")); + await userEvent.click( + screen.getByRole("button", { name: /^View transcript/ }), + ); + if (when === "after preview") { + await screen.findByText("Earlier activity is not loaded."); + expect( + screen.queryByText("earlier", { selector: "summary span" }), + ).toBeNull(); + rerender(page(true)); + } + const earlier = await screen.findByText("earlier", { + selector: "summary span", + }); + expect(earlier.closest("details")).toHaveProperty("open", true); + expect(focus.done).toHaveBeenCalled(); + } finally { + Reflect.deleteProperty(Element.prototype, "scrollIntoView"); + } + }, +); + it("reads an open transcript again in place when its conversation's session changes", async () => { const thread = `channel/${"e".repeat(64)}`; const saved = (id: string) => diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 53be01a8dd..6ce324361c 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -394,13 +394,19 @@ it("opens only the bound saved tail before reading canonical order across sessio uuid: "before", timestamp: "2026-01-03T00:00:00Z", }), - line("assistant", [{ type: "text", text: "x".repeat(3 << 20) }]), - line("assistant", [{ type: "text", text: "part of the older turn" }]), + line("assistant", [{ type: "text", text: "x".repeat(3 << 20) }], { + timestamp: "2026-01-03T00:00:01Z", + }), + line("assistant", [{ type: "text", text: "part of the older turn" }], { + timestamp: "2026-01-03T00:00:02Z", + }), line("user", turn("recent saved prompt"), { uuid: "recent", timestamp: "2026-01-01T00:00:00Z", }), - line("assistant", [{ type: "text", text: "recent saved reply" }]), + line("assistant", [{ type: "text", text: "recent saved reply" }], { + timestamp: "2026-01-01T00:00:01Z", + }), ].join("\n"), "./-Users-me--buzz/discovered.jsonl": line( "user", diff --git a/src/features/agents/ActivityTranscript.module.css b/src/features/agents/ActivityTranscript.module.css index d0e0c37915..be3255abc9 100644 --- a/src/features/agents/ActivityTranscript.module.css +++ b/src/features/agents/ActivityTranscript.module.css @@ -17,6 +17,9 @@ [data-transcript] .timeline:has(> .turn) { margin-inline: calc(-1 * var(--space-3)); } +[data-transcript] .timeline:has(> .turn) > :not(.turn) { + padding-inline: var(--space-3); +} [data-transcript] .turn { contain: paint; box-sizing: border-box; diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index 1789e75cfa..cc993b679b 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -510,44 +510,18 @@ it("opens at the latest turn and follows new ones until the reader scrolls up", it.each([ { - situation: "after the reader moves during loading", - fits: false, - appended: false, - shortened: false, - expectedTop: 205, - }, - { - situation: - "when the partial transcript fits and opens at the natural latest", + situation: "when the partial transcript fits", fits: true, - appended: false, - shortened: false, expectedTop: 90, }, - { - situation: "when the full read prepends history and appends live rows", - fits: true, - appended: true, - shortened: false, - expectedTop: 210, - }, { situation: "when native restoration scroll fires inside the follow margin", fits: false, - appended: false, - shortened: true, - expectedTop: 205, - }, - { - situation: "when a tall read prepends history and appends live rows", - fits: false, - appended: true, - shortened: false, expectedTop: 205, }, ])( "keeps the open disclosure and its viewport $situation", - async ({ fits, appended, shortened, expectedTop }) => { + async ({ fits, expectedTop }) => { const item = (id: string, text: string) => ({ id, text, @@ -597,8 +571,8 @@ it.each([ ); }, }); - const canonicalItems = shortened ? turn.items.slice(0, -1) : turn.items; - const show = (history: boolean, live = appended) => ( + const canonicalItems = !fits ? turn.items.slice(0, -1) : turn.items; + const show = (history: boolean, live = false) => ( .map((line) => line.textContent), ).toEqual(["Session continued; earlier turns not shown", "New session"]); expect(screen.getAllByText(/System prompt/)).toHaveLength(1); + expect(screen.queryByText("Agent instructions")).not.toBeInTheDocument(); await userEvent.click(screen.getByText(/System prompt/)); expect(screen.getByText("Agent instructions")).toBeVisible(); }); From 290f1ffa56224d1a9385ecee309c5ec70f3bc792 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 02:38:42 -0500 Subject: [PATCH 09/37] Update loaded Claude history from the tail when work starts or stops Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 88 ++++++++++++++++++++ src/bundled/claude-code/tabs.tsx | 27 ++++-- src/features/agents/TranscriptPanel.test.tsx | 2 + src/features/agents/TranscriptPanel.tsx | 62 ++++++++++---- 4 files changed, 155 insertions(+), 24 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 97a1bf9819..155056334d 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -531,6 +531,10 @@ function longTranscript() { return { Activity: tab(type, 1), path: join(home, ".claude/projects", file), + fileReads: () => + spawn.mock.calls + .map(([id]) => id) + .filter((id) => id === "read" || id === "read-page"), gap, startCompaction() { if (!type.sessionControls) @@ -616,6 +620,90 @@ it("loads the missing history when a working session grows past the held tail", } }); +async function openLongTranscript() { + const fixture = longTranscript(); + const { Activity } = fixture; + render(); + await userEvent.click( + screen.getByRole("button", { name: /^View transcript/ }), + ); + const load = await screen.findByRole("button", { + name: /load earlier activity/i, + }); + const summary = (text: string) => + screen.findByText(text, { selector: "summary span" }); + return { ...fixture, load, summary }; +} + +it("reads only the tail at both working changes and keeps earlier turns", async () => { + const { load, path, fileReads, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + const earlier = await summary("earlier"); + const newest = await summary("newest"); + const before = fileReads().length; + appendFileSync(path, `\n${sessionPrompt("during")}`); + const finish = startCompaction(); + const during = await summary("during"); + expect(new Set(fileReads().slice(before))).toEqual(new Set(["read-page"])); + const afterStart = fileReads().length; + appendFileSync(path, `\n${sessionPrompt("finished")}`); + await act(finish); + await summary("finished"); + expect(new Set(fileReads().slice(afterStart))).toEqual( + new Set(["read-page"]), + ); + for (const turn of [earlier, newest, during]) expect(turn).toBeVisible(); +}); + +it("finishes a pending full Refresh when work starts", async () => { + const { load, path, gap, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + writeFileSync( + path, + [sessionPrompt("revised earlier"), gap, sessionPrompt("newest")].join("\n"), + ); + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + const finish = startCompaction(); + try { + expect(await summary("revised earlier")).toBeVisible(); + } finally { + await act(finish); + } +}); + +it("reads full history when the final tail has no overlap", async () => { + const { load, path, gap, fileReads, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + appendFileSync(path, `\n${sessionPrompt("during")}`); + const finish = startCompaction(); + await summary("during"); + const before = fileReads().length; + appendFileSync( + path, + `\n${sessionPrompt("between")}\n${gap}\n${sessionPrompt("last")}`, + ); + await act(finish); + await summary("last"); + expect(await summary("between")).toBeVisible(); + expect(fileReads().slice(before)).toEqual(["read-page", "read"]); +}); + +it("finishes Load earlier requested during work even when the turn ends", async () => { + const { load, path, startCompaction, summary } = await openLongTranscript(); + appendFileSync(path, `\n${sessionPrompt("during")}`); + const finish = startCompaction(); + await summary("during"); + fireEvent.click(load); + await act(finish); + expect(await summary("earlier")).toBeVisible(); + expect(load).not.toBeInTheDocument(); +}); + it.each(["on open", "after preview"])( "shows the earlier focused turn %s", async (when) => { diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 57fd1f36fc..3978ed492a 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -1003,7 +1003,7 @@ export function createTabs({ attempt: focus ? 1 : 0, loading: false, }); - const canonical = useRef(undefined); + const skipPreview = useRef(undefined); if (history.input !== input || (focus && !history.attempt)) { setHistory({ input, attempt: focus ? 1 : 0, loading: false }); } @@ -1021,7 +1021,7 @@ export function createTabs({ { - if (!history.attempt && canonical.current !== input) { + if (!history.attempt && skipPreview.current !== input) { const tail = await runtime.transcriptPreview( conversation, workspace, @@ -1039,7 +1039,7 @@ export function createTabs({ signal, ); signal.throwIfAborted(); - canonical.current = input; + skipPreview.current = input; return result; } finally { if (history.loading && !signal.aborted) { @@ -1049,6 +1049,9 @@ export function createTabs({ } } }} + latestOnWorkingChange={(held) => + !("historyPreview" in held) && !held.incomplete + } readLatest={async (signal, held) => { const turns = await runtime.latestTurns( conversation, @@ -1058,12 +1061,24 @@ export function createTabs({ held, ); signal.throwIfAborted(); + if (turns && !turns.length) return turns; + const from = held.findIndex( + (turn) => turn.turnId === turns?.[0]?.turnId, + ); if ( !turns || - (turns.length && - !held.some((turn) => turn.turnId === turns[0]?.turnId)) + from < 0 || + held + .slice(from) + .some((turn, index) => turn.turnId !== turns[index]?.turnId) || + turns.some( + (turn, index) => + turn.startedAt < + ((turns[index - 1] ?? held[from - 1])?.startedAt ?? -Infinity), + ) ) { - canonical.current = input; + skipPreview.current = input; + return undefined; } return turns; }} diff --git a/src/features/agents/TranscriptPanel.test.tsx b/src/features/agents/TranscriptPanel.test.tsx index fdedcbf4dd..59b030dfbf 100644 --- a/src/features/agents/TranscriptPanel.test.tsx +++ b/src/features/agents/TranscriptPanel.test.tsx @@ -383,10 +383,12 @@ it("swaps the latest turns over the end of the held transcript", () => { }); // It holds at most TURN_LIMIT turns. const full = { + more: false, turns: Array.from({ length: TURN_LIMIT }, (_, i) => turn(String(i))), }; const grown = withLatest(full, [turn(String(TURN_LIMIT - 1)), turn("new")]); expect(grown?.turns).toHaveLength(TURN_LIMIT); + expect(grown?.more).toBe(true); expect(grown?.turns.at(-1)).toEqual(turn("new")); // A turn it doesn't hold can't be placed. expect(withLatest(held, [turn("9")])).toBeUndefined(); diff --git a/src/features/agents/TranscriptPanel.tsx b/src/features/agents/TranscriptPanel.tsx index 1851a94673..d0d2715d1b 100644 --- a/src/features/agents/TranscriptPanel.tsx +++ b/src/features/agents/TranscriptPanel.tsx @@ -53,10 +53,11 @@ type Shown = Readonly<{ transcript?: T | null; error?: string; }>; -/** A full read, or one of only the latest turns. */ -type Kind = "full" | "latest"; -const either = (a: Kind | undefined, b: Kind): Kind => - a === "full" || b === "full" ? "full" : "latest"; +type Kind = "full" | "latest" | "working"; +function either(a: Kind | undefined, b: Kind) { + if (a === "full" || b === "full") return "full"; + return a === "working" ? a : b; +} /** `held` with `turns` over its end, from the first of them it holds, and * at most {@link TURN_LIMIT} turns; undefined when it holds none of them, or @@ -73,18 +74,23 @@ export function withLatest( const at = ids.get(turns[from]?.turnId ?? "") ?? 0; const kept = turns.slice(from); const sessions = new Set(kept.map((turn) => turn.sessionId)); - return held.turns.slice(at).every((turn) => sessions.has(turn.sessionId)) - ? { - ...held, - turns: [...held.turns.slice(0, at), ...kept].slice(-TURN_LIMIT), - } - : undefined; + if (!held.turns.slice(at).every((turn) => sessions.has(turn.sessionId))) + return undefined; + const merged = [...held.turns.slice(0, at), ...kept]; + return { + ...held, + ...("more" in held && held.more === false && merged.length > TURN_LIMIT + ? { more: true } + : {}), + turns: merged.slice(-TURN_LIMIT), + }; } -/** `read` for `key`: in full on open, on `refresh`, and when `again` or - * `working` changes; while working, `readLatest` (or `read` without it) - * {@link LIVE_READ_MS}, or twice the read's duration if longer, after each - * read finishes, and on the steps the agent reports, no sooner than +/** `read` for `key`: in full on open, Refresh and new inputs. When work + * starts or stops, an opted-in settled result can use the latest turns. + * While working, `readLatest` (or `read` without it) runs {@link LIVE_READ_MS}, + * or twice the read's duration if longer, after each read finishes, and on + * the steps the agent reports, no sooner than * {@link STEP_READ_MS} or that after one. Latest turns that don't continue * the held transcript read it in full. Automatic reads wait while the window * is hidden and run once it shows. One read runs at a time; asking during @@ -96,6 +102,7 @@ export function withLatest( export function useLiveTranscript({ read, readLatest, + latestOnWorkingChange, key, again, working, @@ -109,6 +116,7 @@ export function useLiveTranscript({ held: readonly TranscriptTurn[], ) => Promise) | undefined; + latestOnWorkingChange?: ((transcript: T) => boolean) | undefined; key: string; again: string; working: boolean; @@ -118,6 +126,7 @@ export function useLiveTranscript({ const agents = useContext(AgentsContext); const [shown, setShown] = useState>({ key }); const held = useRef>(shown); + const settledFullInput = useRef(undefined); const [loading, setLoading] = useState(true); const latest = useRef({ read, @@ -175,6 +184,7 @@ export function useLiveTranscript({ step(); return false; } + if (kind === "full") settledFullInput.current = undefined; if (auto && document.hidden) { owed.current = either(owed.current, kind); return false; @@ -201,13 +211,19 @@ export function useLiveTranscript({ setLoading(true); const began = Date.now(); const reading = - kind === "latest" && readLatest && prior - ? readLatest(abort.signal, prior.turns).then((turns) => - turns ? withLatest(prior, turns) : undefined, + kind !== "full" && readLatest && prior + ? readLatest(abort.signal, prior.turns).then( + (turns) => + turns && (turns.length || kind === "latest") + ? withLatest(prior, turns) + : undefined, + kind === "working" ? () => undefined : undefined, ) : read(abort.signal).then((transcript) => transcript ?? null); const settle = (next: Omit, "key">) => { if (abort.signal.aborted) return; + if (next.error !== undefined) settledFullInput.current = undefined; + else if (kind === "full") settledFullInput.current = again; running.current = undefined; finished.current = Date.now(); spent.current = 2 * (finished.current - began); @@ -257,7 +273,13 @@ export function useLiveTranscript({ running.current = undefined; queued.current = undefined; } - request(true); + const prior = held.current; + const useTail = + prior.key === key && + settledFullInput.current === again && + prior.transcript && + latestOnWorkingChange?.(prior.transcript); + request(true, useTail ? "working" : "full"); }, [key, again, working]); useEffect(() => { const shows = () => { @@ -297,6 +319,7 @@ export function TranscriptPanel({ agent, read, readLatest, + latestOnWorkingChange, readKey, readAgain = "", working, @@ -315,6 +338,8 @@ export function TranscriptPanel({ signal: AbortSignal, held: readonly TranscriptTurn[], ) => Promise; + /** Allows a nonempty tail to update this settled result when work starts or stops. */ + latestOnWorkingChange?: (transcript: T) => boolean; /** What `read` reads; another key never shows this one's result. */ readKey: string; /** Inputs that only make `read` read again, keeping what it shows. */ @@ -335,6 +360,7 @@ export function TranscriptPanel({ const { shown, loading, refresh } = useLiveTranscript({ read, readLatest, + latestOnWorkingChange, key: readKey, again: readAgain, working, From 01cb4c2f16f7cc5f0b31793d9c287d5e85fe69d5 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 02:53:23 -0500 Subject: [PATCH 10/37] Keep the Claude session prompt on the first visible turn Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/runtime.ts | 29 ++++++++++------- src/bundled/claude-code/tabs.test.tsx | 46 +++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 11 deletions(-) diff --git a/src/bundled/claude-code/runtime.ts b/src/bundled/claude-code/runtime.ts index b93caa084f..b02cdf91bf 100644 --- a/src/bundled/claude-code/runtime.ts +++ b/src/bundled/claude-code/runtime.ts @@ -130,6 +130,7 @@ import { } from "../../features/agents/gateway/contract"; import type { EligibleRoute } from "../../features/agents/gateway/route"; import { + TURN_LIMIT, readLatestTurns, readSessionTitle, readTranscript, @@ -969,19 +970,25 @@ export class ClaudeRuntime { 0, ), ); - const at = held.findIndex((turn) => turn.turnId === turns[0]?.turnId); - const kept = new Set( - held.slice(0, Math.max(at, 0)).map((t) => t.sessionId), - ); - // Decorated as a full read is, since these replace the turns it showed. - return withNotices( - this.prompts(conversation.agent) - .shown(turns) - .map((turn, index) => - kept.has(turn.sessionId) ? (turns[index] ?? turn) : turn, - ), + const overlap = held.findIndex((turn) => turn.turnId === turns[0]?.turnId); + const prefix = held.slice(0, Math.max(0, overlap)); + const tail = withNotices( + turns, this.notices.get(conversation.agent) ?? new Map(), ); + const merged = [...prefix, ...tail]; + const cut = Math.max(0, merged.length - TURN_LIMIT); + const prompts = this.prompts(conversation.agent); + const seen = new Set(); + for (let i = cut; i < merged.length; i++) { + const turn = merged[i]; + if (!turn?.sessionId || seen.has(turn.sessionId)) continue; + seen.add(turn.sessionId); + if (i < prefix.length && (turn.newSession || turn.continued)) continue; + merged[i] = prompts.shown([turn])[0] ?? turn; + } + const from = cut > 0 ? Math.min(cut, prefix.length) : prefix.length; + return merged.slice(from); } /** `sessions` with, for each a standalone turn started, the key it ran * under. */ diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 155056334d..76d14d6e89 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -11,6 +11,7 @@ import { import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; +import { sessionPrompts } from "../../features/agents/session-prompts"; import { LIVE_READ_MS } from "../../features/agents/TranscriptPanel"; import { readerInputs } from "../../features/profiles/target"; import { AgentTabs } from "../agents/AgentTabs"; @@ -656,6 +657,51 @@ it("reads only the tail at both working changes and keeps earlier turns", async for (const turn of [earlier, newest, during]) expect(turn).toBeVisible(); }); +it("keeps the session divider and prompt when a working turn shifts the 50-turn window", async () => { + await sessionPrompts(localStore(), "claude-code", agent().key).save("kept", [ + { label: "Instructions", text: "Saved session instructions" }, + ]); + const { load, path, gap, fileReads, startCompaction, summary } = + await openLongTranscript(); + const older = Array.from({ length: 50 }, (_, i) => + sessionPrompt(`turn ${i}`), + ); + writeFileSync(path, [...older, gap, sessionPrompt("newest")].join("\n")); + await userEvent.click(load); + await summary("turn 1"); + const before = fileReads().length; + appendFileSync(path, `\n${sessionPrompt("during")}`); + const finish = startCompaction(); + try { + await summary("during"); + appendFileSync(path, `\n${sessionPrompt("finished")}`); + } finally { + await act(finish); + } + await summary("finished"); + const first = (await summary("turn 3")).closest("article"); + expect(first?.previousElementSibling).toHaveTextContent( + "Session continued; earlier turns not shown", + ); + expect( + screen + .getByText(/System prompt/, { selector: "summary span" }) + .closest("article"), + ).toBe(first); + expect(new Set(fileReads().slice(before))).toEqual(new Set(["read-page"])); + const rows = () => + Array.from(document.querySelectorAll("[data-entry]"), (row) => + row.getAttribute("data-entry"), + ); + const afterTurn = rows(); + const region = first?.closest("[aria-busy]"); + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + expect(region).toHaveAttribute("aria-busy", "true"); + await waitFor(() => expect(region).toHaveAttribute("aria-busy", "false")); + expect(fileReads().at(-1)).toBe("read"); + expect(rows()).toEqual(afterTurn); +}); + it("finishes a pending full Refresh when work starts", async () => { const { load, path, gap, startCompaction, summary } = await openLongTranscript(); From 3f46b547af27cc702c47d8b21125ebb9e1652f1f Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 12:03:58 -0500 Subject: [PATCH 11/37] Keep Claude working transcript reads in the plugin Retry a failed history read once for each new focused opening. Use the last settled transcript for a working-state change, and fall back to a full read when the tail cannot continue that history. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 191 ++++++++++++++++++ src/bundled/claude-code/tabs.tsx | 157 +++++++++----- src/bundled/claude-code/transcript.test.ts | 48 ++++- .../agents/ActivityTranscript.test.tsx | 25 ++- src/features/agents/ActivityTranscript.tsx | 5 +- src/features/agents/TranscriptPanel.tsx | 46 ++--- 6 files changed, 375 insertions(+), 97 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 76d14d6e89..218197cddc 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -750,6 +750,197 @@ it("finishes Load earlier requested during work even when the turn ends", async expect(load).not.toBeInTheDocument(); }); +it("retries each focused opening once after Load earlier fails", async () => { + const { Activity, path, fileReads } = longTranscript(); + const focus = { + events: [earlierEvent], + inputs: readerInputs(), + done: vi.fn(), + }; + const page = (opening?: typeof focus) => ( + + + + ); + const { rerender } = render(page()); + await userEvent.click( + screen.getByRole("button", { name: /^View transcript/ }), + ); + const load = await screen.findByRole("button", { + name: /load earlier activity/i, + }); + chmodSync(path, 0); + await userEvent.click(load); + await screen.findByRole("alert"); + const before = fileReads().length; + rerender(page(focus)); + await waitFor(() => expect(fileReads().length).toBeGreaterThan(before)); + await waitFor(() => expect(screen.getByRole("alert")).toBeVisible()); + rerender(page(focus)); + expect(fileReads().length).toBe(before + 1); + chmodSync(path, 0o600); + Element.prototype.scrollIntoView = () => {}; + try { + rerender(page({ ...focus })); + await waitFor(() => expect(focus.done).toHaveBeenCalled()); + expect( + screen + .getByText("earlier", { selector: "summary span" }) + .closest("details"), + ).toHaveProperty("open", true); + } finally { + Reflect.deleteProperty(Element.prototype, "scrollIntoView"); + } +}); + +it("opens the replacement session's preview when its first turn starts while hidden", async () => { + const { load, path, gap, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + const hidden = vi.spyOn(document, "hidden", "get").mockReturnValue(true); + writeFileSync( + join(dirname(path), "replacement.jsonl"), + [ + sessionPrompt("replacement history"), + gap, + sessionPrompt("replacement tail"), + ].join("\n"), + ); + localStorage.setItem( + "buzz.claude-code.sessions.v1", + JSON.stringify({ + [agent().key]: { channel: { id: "replacement", seen: 0, at: 2 } }, + }), + ); + let finish!: () => Promise; + await act(async () => { + finish = startCompaction(); + }); + hidden.mockReturnValue(false); + fireEvent(document, new Event("visibilitychange")); + try { + await summary("replacement tail"); + expect(screen.getByText("Earlier activity is not loaded.")).toBeVisible(); + expect( + screen.queryByText("replacement history", { selector: "summary span" }), + ).toBeNull(); + } finally { + await act(finish); + } +}); + +it("finishes a Refresh interrupted while hidden when the window returns", async () => { + const { load, path, gap, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + writeFileSync( + path, + [sessionPrompt("corrected"), gap, sessionPrompt("newest")].join("\n"), + ); + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + const hidden = vi.spyOn(document, "hidden", "get").mockReturnValue(true); + let finish!: () => Promise; + await act(async () => { + finish = startCompaction(); + }); + hidden.mockReturnValue(false); + fireEvent(document, new Event("visibilitychange")); + try { + expect(await summary("corrected")).toBeVisible(); + } finally { + await act(finish); + } +}); + +it("reads earlier rows again when a working change follows a failed Refresh", async () => { + const { load, path, gap, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + chmodSync(path, 0); + await userEvent.click( + screen.getByRole("button", { name: "Refresh transcript" }), + ); + await screen.findByRole("alert"); + chmodSync(path, 0o600); + writeFileSync( + path, + [sessionPrompt("corrected"), gap, sessionPrompt("newest")].join("\n"), + ); + const finish = startCompaction(); + try { + expect(await summary("corrected")).toBeVisible(); + } finally { + await act(finish); + } +}); + +it.each([ + { file: "", reason: "file size read rejects on zero bytes" }, + { file: '{"type":"progress"}', reason: "tail has no turns" }, +])("replaces stale rows when the $reason at work start", async ({ file }) => { + const { load, path, startCompaction, summary } = await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + writeFileSync(path, file); + const finish = startCompaction(); + try { + expect( + await screen.findByText("No turns captured for this scope yet."), + ).toBeVisible(); + expect( + screen.queryByText("earlier", { selector: "summary span" }), + ).toBeNull(); + } finally { + await act(finish); + } +}); + +it("retries incomplete session discovery when work starts", async () => { + const { load, path, startCompaction, summary } = await openLongTranscript(); + chmodSync(dirname(path), 0o111); + try { + await userEvent.click(load); + await screen.findByText( + /Some of this conversation’s sessions may be missing/, + ); + } finally { + chmodSync(dirname(path), 0o700); + } + appendFileSync(path, `\n${sessionPrompt("during")}`); + const finish = startCompaction(); + try { + await summary("during"); + expect( + screen.queryByText(/Some of this conversation’s sessions may be missing/), + ).toBeNull(); + } finally { + await act(finish); + } +}); + +it("restores canonical turn order when a working tail's clock goes backwards", async () => { + const { load, path, startCompaction, summary } = await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + appendFileSync( + path, + `\n${sessionPrompt("clock rollback").replace("2026-10-09", "2026-10-08")}`, + ); + const finish = startCompaction(); + try { + const first = await summary("clock rollback"); + const earlier = await summary("earlier"); + expect( + first.compareDocumentPosition(earlier) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + } finally { + await act(finish); + } +}); + it.each(["on open", "after preview"])( "shows the earlier focused turn %s", async (when) => { diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 3978ed492a..1008551c2d 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -23,7 +23,12 @@ import { } from "react"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; -import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; +import type { TranscriptTurn } from "../../features/agents/activity-transcript"; +import type { ClaudeTranscript } from "./transcript"; +import { + TranscriptPanel, + withLatest, +} from "../../features/agents/TranscriptPanel"; import { AgentInstructions } from "../../features/agents/AgentInstructions"; import { CreateModelChoices } from "../../features/agents/CreateModelChoices"; import { Dialog } from "../../shared/design-system/ui/Dialog"; @@ -1000,12 +1005,19 @@ export function createTabs({ const focus = useContext(TranscriptFocus); const [history, setHistory] = useState({ input, + focus, attempt: focus ? 1 : 0, loading: false, }); - const skipPreview = useRef(undefined); - if (history.input !== input || (focus && !history.attempt)) { - setHistory({ input, attempt: focus ? 1 : 0, loading: false }); + const fullHistory = useRef<{ input: string; loaded: boolean }>(undefined); + if (history.input !== input) { + setHistory({ input, focus, attempt: focus ? 1 : 0, loading: false }); + } else if ( + focus && + history.focus !== focus && + !(fullHistory.current?.input === input && fullHistory.current.loaded) + ) { + setHistory({ ...history, focus, attempt: history.attempt + 1 }); } const loadEarlier = () => setHistory((old) => @@ -1017,29 +1029,90 @@ export function createTabs({ loading: true, }, ); + type History = ClaudeTranscript & { partial?: true }; + const again = JSON.stringify([input, history.attempt]); + const settled = useRef<{ + again: string; + working: boolean; + result: History; + }>(undefined); + async function latestTurns( + signal: AbortSignal, + held: readonly TranscriptTurn[], + ) { + const turns = await runtime.latestTurns( + conversation, + workspace, + working, + signal, + held, + ); + signal.throwIfAborted(); + if (turns && !turns.length) return turns; + const from = held.findIndex((turn) => turn.turnId === turns?.[0]?.turnId); + if ( + !turns || + from < 0 || + held + .slice(from) + .some((turn, index) => turn.turnId !== turns[index]?.turnId) || + turns.some( + (turn, index) => + turn.startedAt < + ((turns[index - 1] ?? held[from - 1])?.startedAt ?? -Infinity), + ) + ) { + if (fullHistory.current?.input !== input) + fullHistory.current = { input, loaded: false }; + return undefined; + } + return turns; + } return ( { - if (!history.attempt && skipPreview.current !== input) { - const tail = await runtime.transcriptPreview( - conversation, - workspace, - working, - signal, - ); - signal.throwIfAborted(); - if (tail) return { ...tail, historyPreview: true as const }; - } + const prior = settled.current; + settled.current = undefined; + let result: History | undefined; try { - const result = await runtime.transcript( - conversation, - workspace, - working, - signal, - ); - signal.throwIfAborted(); - skipPreview.current = input; + if ( + prior?.again === again && + prior.working !== working && + !prior.result.partial && + !prior.result.incomplete + ) { + const turns = await latestTurns(signal, prior.result.turns).catch( + () => undefined, + ); + signal.throwIfAborted(); + if (turns?.length) result = withLatest(prior.result, turns); + } + if ( + !result && + !history.attempt && + fullHistory.current?.input !== input + ) { + const tail = await runtime.transcriptPreview( + conversation, + workspace, + working, + signal, + ); + signal.throwIfAborted(); + if (tail) result = { ...tail, partial: true }; + } + if (!result) { + result = await runtime.transcript( + conversation, + workspace, + working, + signal, + ); + signal.throwIfAborted(); + fullHistory.current = { input, loaded: Boolean(result) }; + } + if (result) settled.current = { again, working, result }; return result; } finally { if (history.loading && !signal.aborted) { @@ -1049,41 +1122,19 @@ export function createTabs({ } } }} - latestOnWorkingChange={(held) => - !("historyPreview" in held) && !held.incomplete - } readLatest={async (signal, held) => { - const turns = await runtime.latestTurns( - conversation, - workspace, - working, - signal, - held, - ); + const prior = settled.current; + settled.current = undefined; + const turns = await latestTurns(signal, held); signal.throwIfAborted(); - if (turns && !turns.length) return turns; - const from = held.findIndex( - (turn) => turn.turnId === turns?.[0]?.turnId, - ); - if ( - !turns || - from < 0 || - held - .slice(from) - .some((turn, index) => turn.turnId !== turns[index]?.turnId) || - turns.some( - (turn, index) => - turn.startedAt < - ((turns[index - 1] ?? held[from - 1])?.startedAt ?? -Infinity), - ) - ) { - skipPreview.current = input; - return undefined; + if (prior && turns) { + const result = withLatest(prior.result, turns); + if (result) settled.current = { ...prior, result }; } return turns; }} readKey={`${conversation.key}\u0000${workspace}`} - readAgain={JSON.stringify([input, history.attempt])} + readAgain={again} working={working} reading="Reading the Claude session…" failed="Could not read the Claude session" @@ -1095,7 +1146,7 @@ export function createTabs({ } notes={(transcript) => ( <> - {"historyPreview" in transcript && ( + {transcript.partial && (
Earlier activity is not loaded.{" "} @@ -1119,7 +1170,7 @@ export function createTabs({

)} - {transcript.more && !("historyPreview" in transcript) && ( + {transcript.more && !transcript.partial && (

{transcript.turns.length ? `Showing the latest ${transcript.turns.length === 1 ? "turn" : `${transcript.turns.length} turns`}.` diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 6ce324361c..65b1de4cdb 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -368,7 +368,10 @@ function host(files: Record) { const savedPath = "./-Users-me--buzz/session-1.jsonl"; -function previewHost(files: Record) { +function previewHost( + files: Record, + remote?: "bound" | "inspected", +) { const { spawn, reads } = host(files); const storage = fileStore(new Map(), async () => {}); const saved = localSessions(storage, agent); @@ -382,6 +385,14 @@ function previewHost(files: Record) { () => undefined, async () => null, storage, + undefined, + undefined, + undefined, + undefined, + undefined, + async () => + remote === "inspected" ? { provider: "example/worker" } : undefined, + () => remote === "bound", ); const signal = new AbortController().signal; return { runtime, spawn, reads, signal }; @@ -459,6 +470,41 @@ it("opens only the bound saved tail before reading canonical order across sessio expect(canonical?.more).toBe(false); }); +it.each(["bound", "inspected"] as const)( + "skips local file reads for a %s remote session", + async (placement) => { + const { runtime, spawn, signal } = previewHost( + { [savedPath]: line("user", turn("local copy")) }, + placement, + ); + await expect( + runtime.transcriptPreview(conversation, "~/.buzz", false, signal), + ).resolves.toBeUndefined(); + expect(spawn).not.toHaveBeenCalled(); + }, +); + +it("leaves a prompt without a timestamp to the full reader's preceding turn clock", async () => { + const { runtime, signal } = previewHost({ + [savedPath]: [ + line("user", turn("earlier"), { timestamp: "2026-01-03T00:00:00Z" }), + line("system", "x".repeat(3 << 20)), + line("user", turn("after the cut"), { + uuid: "latest", + timestamp: undefined, + }), + ].join("\n"), + }); + await expect( + runtime.transcriptPreview(conversation, "~/.buzz", false, signal), + ).resolves.toBeUndefined(); + const full = await runtime.transcript(conversation, "~/.buzz", false, signal); + expect(full?.turns.at(-1)).toMatchObject({ + turnId: "latest", + startedAt: Date.parse("2026-01-03T00:00:00Z"), + }); +}); + it("leaves a visible clock rollback to canonical timestamp order", async () => { const { runtime, signal } = previewHost({ [savedPath]: [ diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index cc993b679b..e9542851b1 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -511,17 +511,25 @@ it("opens at the latest turn and follows new ones until the reader scrolls up", it.each([ { situation: "when the partial transcript fits", + resized: false, fits: true, expectedTop: 90, }, + { + situation: "when the viewport grows to fit after scrolling up", + resized: true, + fits: true, + expectedTop: 0, + }, { situation: "when native restoration scroll fires inside the follow margin", + resized: false, fits: false, expectedTop: 205, }, ])( "keeps the open disclosure and its viewport $situation", - async ({ fits, expectedTop }) => { + async ({ fits, resized, expectedTop }) => { const item = (id: string, text: string) => ({ id, text, @@ -549,7 +557,7 @@ it.each([ view.style.overflowY = "auto"; const prependHeight = () => view.querySelector('[data-entry="item:history"]') ? 150 : 0; - const viewportHeight = 150; + let viewportHeight = resized ? 35 : 150; const rowLengths = fits ? [20, 50, 20] : [80, 140, 100]; const contentHeight = fits ? 90 : 320; const naturalHeight = () => @@ -557,7 +565,7 @@ it.each([ prependHeight() - (view.querySelector('[data-entry="item:last"]') ? 0 : 100) + (view.querySelector('[data-entry="item:live"]') ? 120 : 0); - Object.defineProperty(view, "clientHeight", { value: viewportHeight }); + Object.defineProperty(view, "clientHeight", { get: () => viewportHeight }); Object.defineProperty(view, "scrollHeight", { get: () => Math.max(viewportHeight, naturalHeight()), }); @@ -575,7 +583,7 @@ it.each([ const show = (history: boolean, live = false) => ( "ended"} transcript={{ - ...(!history && { historyPreview: true }), + ...(!history && { partial: true }), turns: withSessionPrompts( history ? [turn("older", 1), reading] : [reading], () => [{ label: "base", text: "Instructions" }], @@ -772,7 +785,7 @@ it("shows the turn a message began, its prompt open, instead of the latest, once

"ended"} /> diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index 1695aa6597..f913afbb9e 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -386,7 +386,7 @@ export function ActivityTranscript({ agentKey, community, }: { - transcript: Transcript & { historyPreview?: true }; + transcript: Transcript & { partial?: true }; agentName: string; state: (turnId: string) => TurnState | undefined; /** Paging controls shown above the oldest loaded turn. */ @@ -400,7 +400,7 @@ export function ActivityTranscript({ agentKey?: string; community?: string | undefined; }) { - const partial = transcript.historyPreview === true; + const partial = transcript.partial === true; const scroll = useFollowLatest(transcript, follow); const focused = useShowFocused( transcript, @@ -674,7 +674,6 @@ function Disclosure({ }) { const focused = useContext(RowContext).focused === `item:${item.id}`; const [visited, setVisited] = useState(focused); - // A focused arrival needs its body in the commit that marks and scrolls it. if (focused && !visited) setVisited(true); return (
= Readonly<{ transcript?: T | null; error?: string; }>; -type Kind = "full" | "latest" | "working"; -function either(a: Kind | undefined, b: Kind) { - if (a === "full" || b === "full") return "full"; - return a === "working" ? a : b; -} +/** A full read, or one of only the latest turns. */ +type Kind = "full" | "latest"; +const either = (a: Kind | undefined, b: Kind): Kind => + a === "full" || b === "full" ? "full" : "latest"; /** `held` with `turns` over its end, from the first of them it holds, and * at most {@link TURN_LIMIT} turns; undefined when it holds none of them, or @@ -86,11 +85,10 @@ export function withLatest( }; } -/** `read` for `key`: in full on open, Refresh and new inputs. When work - * starts or stops, an opted-in settled result can use the latest turns. - * While working, `readLatest` (or `read` without it) runs {@link LIVE_READ_MS}, - * or twice the read's duration if longer, after each read finishes, and on - * the steps the agent reports, no sooner than +/** `read` for `key`: in full on open, on `refresh`, and when `again` or + * `working` changes; while working, `readLatest` (or `read` without it) + * {@link LIVE_READ_MS}, or twice the read's duration if longer, after each + * read finishes, and on the steps the agent reports, no sooner than * {@link STEP_READ_MS} or that after one. Latest turns that don't continue * the held transcript read it in full. Automatic reads wait while the window * is hidden and run once it shows. One read runs at a time; asking during @@ -102,7 +100,6 @@ export function withLatest( export function useLiveTranscript({ read, readLatest, - latestOnWorkingChange, key, again, working, @@ -116,7 +113,6 @@ export function useLiveTranscript({ held: readonly TranscriptTurn[], ) => Promise) | undefined; - latestOnWorkingChange?: ((transcript: T) => boolean) | undefined; key: string; again: string; working: boolean; @@ -126,7 +122,6 @@ export function useLiveTranscript({ const agents = useContext(AgentsContext); const [shown, setShown] = useState>({ key }); const held = useRef>(shown); - const settledFullInput = useRef(undefined); const [loading, setLoading] = useState(true); const latest = useRef({ read, @@ -184,7 +179,6 @@ export function useLiveTranscript({ step(); return false; } - if (kind === "full") settledFullInput.current = undefined; if (auto && document.hidden) { owed.current = either(owed.current, kind); return false; @@ -211,19 +205,13 @@ export function useLiveTranscript({ setLoading(true); const began = Date.now(); const reading = - kind !== "full" && readLatest && prior - ? readLatest(abort.signal, prior.turns).then( - (turns) => - turns && (turns.length || kind === "latest") - ? withLatest(prior, turns) - : undefined, - kind === "working" ? () => undefined : undefined, + kind === "latest" && readLatest && prior + ? readLatest(abort.signal, prior.turns).then((turns) => + turns ? withLatest(prior, turns) : undefined, ) : read(abort.signal).then((transcript) => transcript ?? null); const settle = (next: Omit, "key">) => { if (abort.signal.aborted) return; - if (next.error !== undefined) settledFullInput.current = undefined; - else if (kind === "full") settledFullInput.current = again; running.current = undefined; finished.current = Date.now(); spent.current = 2 * (finished.current - began); @@ -273,13 +261,7 @@ export function useLiveTranscript({ running.current = undefined; queued.current = undefined; } - const prior = held.current; - const useTail = - prior.key === key && - settledFullInput.current === again && - prior.transcript && - latestOnWorkingChange?.(prior.transcript); - request(true, useTail ? "working" : "full"); + request(true); }, [key, again, working]); useEffect(() => { const shows = () => { @@ -319,7 +301,6 @@ export function TranscriptPanel({ agent, read, readLatest, - latestOnWorkingChange, readKey, readAgain = "", working, @@ -338,8 +319,6 @@ export function TranscriptPanel({ signal: AbortSignal, held: readonly TranscriptTurn[], ) => Promise; - /** Allows a nonempty tail to update this settled result when work starts or stops. */ - latestOnWorkingChange?: (transcript: T) => boolean; /** What `read` reads; another key never shows this one's result. */ readKey: string; /** Inputs that only make `read` read again, keeping what it shows. */ @@ -360,7 +339,6 @@ export function TranscriptPanel({ const { shown, loading, refresh } = useLiveTranscript({ read, readLatest, - latestOnWorkingChange, key: readKey, again: readAgain, working, From 1b8171437d55134b81868e756b5c0f2a7834d0cd Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 12:36:22 -0500 Subject: [PATCH 12/37] Honor queued Claude transcript refreshes across working changes A read that finishes while the window is hidden may have a full Refresh queued behind it. Drop its tail-merge base so returning to the transcript rereads earlier rows. Preserve the visible row when history expands after a viewport resize. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 156 +++++++++++++++++- src/bundled/claude-code/tabs.tsx | 5 +- .../agents/ActivityTranscript.test.tsx | 2 +- src/features/agents/ActivityTranscript.tsx | 2 +- 4 files changed, 157 insertions(+), 8 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 218197cddc..adc12cb79a 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -561,13 +561,13 @@ function longTranscript() { } it("keeps an untouched tail on working changes until earlier activity is requested", async () => { - const { Activity, path, startCompaction } = longTranscript(); + const { Activity, path, gap, startCompaction } = longTranscript(); render(); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: /^View transcript/ })); const summary = { selector: "summary span" }; await screen.findByText("newest", summary); - appendFileSync(path, `\n${sessionPrompt("while working")}`); + appendFileSync(path, `\n${gap}\n${sessionPrompt("while working")}`); const finish = startCompaction(); await screen.findByText("while working", summary); expect(screen.queryByText("earlier", summary)).toBeNull(); @@ -582,7 +582,7 @@ it("keeps an untouched tail on working changes until earlier activity is request expect(await screen.findByRole("alert")).toHaveTextContent( /permission denied/i, ); - expect(screen.getByText("newest", summary)).toBeVisible(); + expect(screen.getByText("while working", summary)).toBeVisible(); chmodSync(path, 0o600); await user.click(load); expect(await screen.findByText("earlier", summary)).toBeVisible(); @@ -644,8 +644,21 @@ it("reads only the tail at both working changes and keeps earlier turns", async const newest = await summary("newest"); const before = fileReads().length; appendFileSync(path, `\n${sessionPrompt("during")}`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); const finish = startCompaction(); + try { + await vi.waitFor(() => + screen.getByText("during", { selector: "summary span" }), + ); + appendFileSync(path, `\n${sessionPrompt("polled")}`); + act(() => { + vi.advanceTimersByTime(LIVE_READ_MS); + }); + } finally { + vi.useRealTimers(); + } const during = await summary("during"); + const polled = await summary("polled"); expect(new Set(fileReads().slice(before))).toEqual(new Set(["read-page"])); const afterStart = fileReads().length; appendFileSync(path, `\n${sessionPrompt("finished")}`); @@ -654,7 +667,8 @@ it("reads only the tail at both working changes and keeps earlier turns", async expect(new Set(fileReads().slice(afterStart))).toEqual( new Set(["read-page"]), ); - for (const turn of [earlier, newest, during]) expect(turn).toBeVisible(); + for (const turn of [earlier, newest, during, polled]) + expect(turn).toBeVisible(); }); it("keeps the session divider and prompt when a working turn shifts the 50-turn window", async () => { @@ -720,6 +734,66 @@ it("finishes a pending full Refresh when work starts", async () => { } }); +it.each([ + "a poll settles hidden", + "a full read settles hidden", + "turn end aborts a poll", +])("honors queued Refresh when %s", async (outcome) => { + const { load, path, gap, fileReads, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + appendFileSync(path, `\n${sessionPrompt("during")}`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const finish = startCompaction(); + const revise = (earlier: string) => + writeFileSync( + path, + [ + sessionPrompt(earlier), + gap, + sessionPrompt("newest"), + sessionPrompt("during"), + sessionPrompt("polled"), + ].join("\n"), + ); + try { + await vi.waitFor(() => + screen.getByText("during", { selector: "summary span" }), + ); + revise("corrected"); + if (outcome === "a full read settles hidden") { + fireEvent.click( + screen.getByRole("button", { name: "Refresh transcript" }), + ); + } else { + act(() => { + vi.advanceTimersByTime(LIVE_READ_MS); + }); + } + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + } finally { + vi.useRealTimers(); + } + const hidden = vi.spyOn(document, "hidden", "get"); + if (outcome !== "turn end aborts a poll") { + hidden.mockReturnValue(true); + fireEvent(document, new Event("visibilitychange")); + await summary("polled"); + revise("corrected while hidden"); + } + const beforeEnd = fileReads().length; + await act(finish); + hidden.mockReturnValue(false); + fireEvent(document, new Event("visibilitychange")); + await summary( + outcome === "turn end aborts a poll" + ? "corrected" + : "corrected while hidden", + ); + expect(fileReads().slice(beforeEnd)).toContain("read"); +}); + it("reads full history when the final tail has no overlap", async () => { const { load, path, gap, fileReads, startCompaction, summary } = await openLongTranscript(); @@ -793,6 +867,51 @@ it("retries each focused opening once after Load earlier fails", async () => { } }); +it("retries a missing transcript on focus and reuses successfully loaded history", async () => { + const { Activity, path, fileReads } = longTranscript(); + const focus = { + events: [earlierEvent], + inputs: readerInputs(), + done: vi.fn(), + }; + const page = (opening?: typeof focus) => ( + + + + ); + const { rerender } = render(page()); + await userEvent.click( + screen.getByRole("button", { name: /^View transcript/ }), + ); + const load = await screen.findByRole("button", { + name: /load earlier activity/i, + }); + rmSync(path); + await userEvent.click(load); + await screen.findByText(/no transcript for this conversation/); + writeFileSync(path, sessionPrompt("restored", earlierEvent)); + Element.prototype.scrollIntoView = () => {}; + try { + rerender(page(focus)); + const row = await screen.findByText("restored", { + selector: "summary span", + }); + await waitFor(() => expect(focus.done).toHaveBeenCalled()); + const before = fileReads().length; + const second = { ...focus, done: vi.fn() }; + rerender(page(second)); + await waitFor(() => expect(second.done).toHaveBeenCalled()); + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + expect(row.closest("[aria-busy]")).toHaveAttribute("aria-busy", "true"); + await waitFor(() => + expect(row.closest("[aria-busy]")).toHaveAttribute("aria-busy", "false"), + ); + expect(fileReads().slice(before)).toEqual(["read"]); + } finally { + Reflect.deleteProperty(Element.prototype, "scrollIntoView"); + } +}); + it("opens the replacement session's preview when its first turn starts while hidden", async () => { const { load, path, gap, startCompaction, summary } = await openLongTranscript(); @@ -921,6 +1040,35 @@ it("retries incomplete session discovery when work starts", async () => { } }); +it("reloads earlier rows when two tail turns change places at the same timestamp", async () => { + const { load, path, gap, startCompaction, summary } = + await openLongTranscript(); + const write = (earlier: string, tail: string[]) => + writeFileSync( + path, + [ + sessionPrompt(earlier), + gap, + ...tail.map((text) => sessionPrompt(text)), + ].join("\n"), + ); + write("earlier", ["newest", "second", "third"]); + await userEvent.click(load); + await summary("third"); + write("corrected", ["newest", "third", "second"]); + const finish = startCompaction(); + try { + await summary("corrected"); + const third = await summary("third"); + const second = await summary("second"); + expect( + third.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING, + ).toBeTruthy(); + } finally { + await act(finish); + } +}); + it("restores canonical turn order when a working tail's clock goes backwards", async () => { const { load, path, startCompaction, summary } = await openLongTranscript(); await userEvent.click(load); diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 1008551c2d..6f57f4d18d 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -1112,7 +1112,8 @@ export function createTabs({ signal.throwIfAborted(); fullHistory.current = { input, loaded: Boolean(result) }; } - if (result) settled.current = { again, working, result }; + if (result && !document.hidden) + settled.current = { again, working, result }; return result; } finally { if (history.loading && !signal.aborted) { @@ -1127,7 +1128,7 @@ export function createTabs({ settled.current = undefined; const turns = await latestTurns(signal, held); signal.throwIfAborted(); - if (prior && turns) { + if (prior && turns && !document.hidden) { const result = withLatest(prior.result, turns); if (result) settled.current = { ...prior, result }; } diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index e9542851b1..b25a0dca6e 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -519,7 +519,7 @@ it.each([ situation: "when the viewport grows to fit after scrolling up", resized: true, fits: true, - expectedTop: 0, + expectedTop: 90, }, { situation: "when native restoration scroll fires inside the follow margin", diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index f913afbb9e..6c1a77dbf0 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -248,7 +248,7 @@ class TranscriptTimeline extends Component<{ const { timeline, following } = this.props.scroll; const body = timeline.current; const view = scroller(body); - if (!body || !view || view.scrollHeight <= view.clientHeight) return null; + if (!body || !view) return null; if ( following.current && view.scrollHeight - view.scrollTop - view.clientHeight <= END_SLACK From 737542aff44235d9e0c349cf95e743a91d23ab8f Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 13:36:33 -0500 Subject: [PATCH 13/37] Honor manual transcript refreshes across interrupted live reads Notify readers when a refresh is requested, including during a live poll. Keep the last accepted rows through cancellation so a turn ending in the background can resume with a tail read. A pending manual refresh still reloads earlier activity. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 234 ++++++++++++++----- src/bundled/claude-code/tabs.tsx | 27 ++- src/features/agents/TranscriptPanel.test.tsx | 8 +- src/features/agents/TranscriptPanel.tsx | 11 +- 4 files changed, 208 insertions(+), 72 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index adc12cb79a..cfb913656b 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -532,6 +532,23 @@ function longTranscript() { return { Activity: tab(type, 1), path: join(home, ".claude/projects", file), + holdNextSize() { + const run = spawn.getMockImplementation(); + if (!run) throw new Error("Missing manifest process fixture"); + let release!: () => void; + const held = new Promise((resolve) => { + release = resolve; + }); + const started = new Promise((resolve) => { + spawn.mockImplementationOnce(async (id, options) => { + const process = await run(id, options); + const code = await process.exited; + resolve(id); + return { ...process, exited: held.then(() => code) }; + }); + }); + return { started, release }; + }, fileReads: () => spawn.mock.calls .map(([id]) => id) @@ -642,6 +659,10 @@ it("reads only the tail at both working changes and keeps earlier turns", async await userEvent.click(load); const earlier = await summary("earlier"); const newest = await summary("newest"); + const padding = JSON.stringify({ + type: "progress", + data: "x".repeat(2 ** 20), + }); const before = fileReads().length; appendFileSync(path, `\n${sessionPrompt("during")}`); vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); @@ -650,7 +671,7 @@ it("reads only the tail at both working changes and keeps earlier turns", async await vi.waitFor(() => screen.getByText("during", { selector: "summary span" }), ); - appendFileSync(path, `\n${sessionPrompt("polled")}`); + appendFileSync(path, `\n${padding}\n${sessionPrompt("polled")}`); act(() => { vi.advanceTimersByTime(LIVE_READ_MS); }); @@ -661,7 +682,7 @@ it("reads only the tail at both working changes and keeps earlier turns", async const polled = await summary("polled"); expect(new Set(fileReads().slice(before))).toEqual(new Set(["read-page"])); const afterStart = fileReads().length; - appendFileSync(path, `\n${sessionPrompt("finished")}`); + appendFileSync(path, `\n${padding}\n${sessionPrompt("finished")}`); await act(finish); await summary("finished"); expect(new Set(fileReads().slice(afterStart))).toEqual( @@ -735,83 +756,176 @@ it("finishes a pending full Refresh when work starts", async () => { }); it.each([ - "a poll settles hidden", - "a full read settles hidden", - "turn end aborts a poll", -])("honors queued Refresh when %s", async (outcome) => { - const { load, path, gap, fileReads, startCompaction, summary } = + { outcome: "a poll settles hidden", queued: true }, + { outcome: "a full read settles hidden", queued: true }, + { outcome: "a poll settles hidden", queued: false }, + { outcome: "a full read settles hidden", queued: false }, +])( + "handles turn end after $outcome (queued Refresh: $queued)", + async ({ outcome, queued }) => { + const { load, path, gap, fileReads, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + appendFileSync(path, `\n${sessionPrompt("during")}`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const finish = startCompaction(); + const revise = (earlier: string) => + writeFileSync( + path, + [ + sessionPrompt(earlier), + gap, + sessionPrompt("newest"), + sessionPrompt("during"), + sessionPrompt("polled"), + ].join("\n"), + ); + try { + await vi.waitFor(() => + screen.getByText("during", { selector: "summary span" }), + ); + revise("corrected"); + if (outcome === "a full read settles hidden") { + fireEvent.click( + screen.getByRole("button", { name: "Refresh transcript" }), + ); + } else { + act(() => { + vi.advanceTimersByTime(LIVE_READ_MS); + }); + } + if (queued) + fireEvent.click( + screen.getByRole("button", { name: "Refresh transcript" }), + ); + } finally { + vi.useRealTimers(); + } + const hidden = vi.spyOn(document, "hidden", "get"); + hidden.mockReturnValue(true); + fireEvent(document, new Event("visibilitychange")); + await summary("polled"); + if (queued) { + revise("corrected while hidden"); + } else { + hidden.mockReturnValue(false); + fireEvent(document, new Event("visibilitychange")); + appendFileSync(path, `\n${sessionPrompt("finished")}`); + } + const beforeEnd = fileReads().length; + await act(finish); + if (queued) { + hidden.mockReturnValue(false); + fireEvent(document, new Event("visibilitychange")); + await summary("corrected while hidden"); + expect(fileReads().slice(beforeEnd)).toContain("read"); + } else { + await summary("finished"); + expect(fileReads().slice(beforeEnd)).toEqual(["read-page"]); + } + }, +); + +it.each([ + { refresh: false, hide: false, reads: "the tail" }, + { refresh: false, hide: true, reads: "the tail on return" }, + { refresh: true, hide: false, reads: "full history for a queued Refresh" }, +])("reads $reads when turn end aborts a poll", async ({ refresh, hide }) => { + const { load, path, gap, fileReads, holdNextSize, startCompaction, summary } = await openLongTranscript(); await userEvent.click(load); await summary("earlier"); appendFileSync(path, `\n${sessionPrompt("during")}`); vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); const finish = startCompaction(); - const revise = (earlier: string) => - writeFileSync( - path, - [ - sessionPrompt(earlier), - gap, - sessionPrompt("newest"), - sessionPrompt("during"), - sessionPrompt("polled"), - ].join("\n"), - ); try { await vi.waitFor(() => screen.getByText("during", { selector: "summary span" }), ); - revise("corrected"); - if (outcome === "a full read settles hidden") { - fireEvent.click( - screen.getByRole("button", { name: "Refresh transcript" }), - ); - } else { + const poll = holdNextSize(); + try { act(() => { vi.advanceTimersByTime(LIVE_READ_MS); }); + expect(await poll.started).toBe("size"); + vi.useRealTimers(); + writeFileSync( + path, + [ + sessionPrompt("corrected"), + gap, + sessionPrompt("newest"), + sessionPrompt("during"), + sessionPrompt("finished"), + ].join("\n"), + ); + if (refresh) + fireEvent.click( + screen.getByRole("button", { name: "Refresh transcript" }), + ); + const hidden = vi.spyOn(document, "hidden", "get"); + if (hide) { + hidden.mockReturnValue(true); + fireEvent(document, new Event("visibilitychange")); + } + const beforeEnd = fileReads().length; + await act(finish); + if (hide) { + await act(async () => poll.release()); + expect(fileReads()).toHaveLength(beforeEnd); + hidden.mockReturnValue(false); + fireEvent(document, new Event("visibilitychange")); + } + await summary("finished"); + if (refresh) { + await summary("corrected"); + expect(fileReads().slice(beforeEnd)).toContain("read"); + } else { + expect(fileReads().slice(beforeEnd)).toEqual(["read-page"]); + } + } finally { + poll.release(); } - fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); } finally { vi.useRealTimers(); } - const hidden = vi.spyOn(document, "hidden", "get"); - if (outcome !== "turn end aborts a poll") { - hidden.mockReturnValue(true); - fireEvent(document, new Event("visibilitychange")); - await summary("polled"); - revise("corrected while hidden"); - } - const beforeEnd = fileReads().length; - await act(finish); - hidden.mockReturnValue(false); - fireEvent(document, new Event("visibilitychange")); - await summary( - outcome === "turn end aborts a poll" - ? "corrected" - : "corrected while hidden", - ); - expect(fileReads().slice(beforeEnd)).toContain("read"); }); -it("reads full history when the final tail has no overlap", async () => { - const { load, path, gap, fileReads, startCompaction, summary } = - await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); - appendFileSync(path, `\n${sessionPrompt("during")}`); - const finish = startCompaction(); - await summary("during"); - const before = fileReads().length; - appendFileSync( - path, - `\n${sessionPrompt("between")}\n${gap}\n${sessionPrompt("last")}`, - ); - await act(finish); - await summary("last"); - expect(await summary("between")).toBeVisible(); - expect(fileReads().slice(before)).toEqual(["read-page", "read"]); -}); +it.each(["poll", "turn end"])( + "reads full history when the %s tail has no overlap", + async (when) => { + const { load, path, gap, fileReads, startCompaction, summary } = + await openLongTranscript(); + await userEvent.click(load); + await summary("earlier"); + appendFileSync(path, `\n${sessionPrompt("during")}`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const finish = startCompaction(); + try { + await vi.waitFor(() => + screen.getByText("during", { selector: "summary span" }), + ); + const before = fileReads().length; + appendFileSync( + path, + `\n${sessionPrompt("between")}\n${gap}\n${sessionPrompt("last")}`, + ); + if (when === "poll") + act(() => { + vi.advanceTimersByTime(LIVE_READ_MS); + }); + vi.useRealTimers(); + if (when === "turn end") await act(finish); + await summary("last"); + expect(await summary("between")).toBeVisible(); + expect(fileReads().slice(before)).toEqual(["read-page", "read"]); + } finally { + vi.useRealTimers(); + if (when === "poll") await act(finish); + } + }, +); it("finishes Load earlier requested during work even when the turn ends", async () => { const { load, path, startCompaction, summary } = await openLongTranscript(); diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 6f57f4d18d..db492a900d 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -1031,8 +1031,10 @@ export function createTabs({ ); type History = ClaudeTranscript & { partial?: true }; const again = JSON.stringify([input, history.attempt]); + const refreshCount = useRef(0); const settled = useRef<{ again: string; + refresh: number; working: boolean; result: History; }>(undefined); @@ -1071,13 +1073,18 @@ export function createTabs({ return ( { + refreshCount.current++; + }} read={async (signal) => { + const refresh = refreshCount.current; const prior = settled.current; settled.current = undefined; let result: History | undefined; try { if ( prior?.again === again && + prior.refresh === refresh && prior.working !== working && !prior.result.partial && !prior.result.incomplete @@ -1112,8 +1119,7 @@ export function createTabs({ signal.throwIfAborted(); fullHistory.current = { input, loaded: Boolean(result) }; } - if (result && !document.hidden) - settled.current = { again, working, result }; + if (result) settled.current = { again, working, refresh, result }; return result; } finally { if (history.loading && !signal.aborted) { @@ -1125,14 +1131,17 @@ export function createTabs({ }} readLatest={async (signal, held) => { const prior = settled.current; - settled.current = undefined; - const turns = await latestTurns(signal, held); - signal.throwIfAborted(); - if (prior && turns && !document.hidden) { - const result = withLatest(prior.result, turns); - if (result) settled.current = { ...prior, result }; + let result: History | undefined; + try { + const turns = await latestTurns(signal, held); + signal.throwIfAborted(); + if (prior && turns) result = withLatest(prior.result, turns); + return turns; + } finally { + if (!signal.aborted) + settled.current = + prior && result ? { ...prior, result } : undefined; } - return turns; }} readKey={`${conversation.key}\u0000${workspace}`} readAgain={again} diff --git a/src/features/agents/TranscriptPanel.test.tsx b/src/features/agents/TranscriptPanel.test.tsx index 59b030dfbf..4df7bb3309 100644 --- a/src/features/agents/TranscriptPanel.test.tsx +++ b/src/features/agents/TranscriptPanel.test.tsx @@ -49,7 +49,7 @@ function reads() { type Props = { key: string; again?: string; working: boolean }; -function setup() { +function setup(onRefreshRequested?: () => void) { const steps = new Set<() => void>(); const agents = { subscribeSteps: (_agent: string, listener: () => void) => { @@ -80,6 +80,7 @@ function setup() { again, working, agentKey: "agent", + onRefreshRequested, }), { wrapper, initialProps: { key: "a", working: false } as Props }, ); @@ -153,14 +154,17 @@ it("polls only while working, and stops when idle", async () => { }); it("never overlaps reads, and reads once more after one asked during it", async () => { - const { calls, view, step } = setup(); + const onRefreshRequested = vi.fn(); + const { calls, view, step } = setup(onRefreshRequested); await settle(nth(calls, 0), "first"); view.rerender({ key: "a", working: true }); act(() => vi.advanceTimersByTime(LIVE_READ_MS * 4)); // Automatic reads don't show as loading; Refresh does. expect(view.result.current.loading).toBe(false); step(); + expect(onRefreshRequested).not.toHaveBeenCalled(); act(() => view.result.current.refresh()); + expect(onRefreshRequested).toHaveBeenCalledOnce(); expect(view.result.current.loading).toBe(true); expect(calls).toHaveLength(2); await settle(nth(calls, 1), "second"); diff --git a/src/features/agents/TranscriptPanel.tsx b/src/features/agents/TranscriptPanel.tsx index 1d4c44367b..58f801aaeb 100644 --- a/src/features/agents/TranscriptPanel.tsx +++ b/src/features/agents/TranscriptPanel.tsx @@ -105,6 +105,7 @@ export function useLiveTranscript({ working, refreshWhileWorking = true, agentKey, + onRefreshRequested, }: { read: (signal: AbortSignal) => Promise; readLatest?: @@ -118,6 +119,7 @@ export function useLiveTranscript({ working: boolean; refreshWhileWorking?: boolean | undefined; agentKey: string; + onRefreshRequested?: (() => void) | undefined; }) { const agents = useContext(AgentsContext); const [shown, setShown] = useState>({ key }); @@ -291,7 +293,10 @@ export function useLiveTranscript({ return { shown: shown.key === key ? shown : ({ key } as Shown), loading, - refresh: () => void request(false), + refresh: () => { + onRefreshRequested?.(); + request(false); + }, }; } @@ -303,6 +308,7 @@ export function TranscriptPanel({ readLatest, readKey, readAgain = "", + onRefreshRequested, working, refreshWhileWorking, reading, @@ -323,6 +329,8 @@ export function TranscriptPanel({ readKey: string; /** Inputs that only make `read` read again, keeping what it shows. */ readAgain?: string; + /** Called immediately on manual Refresh, including when its read must queue. */ + onRefreshRequested?: () => void; working: boolean; /** Whether a working agent's transcript reads again on a timer and on its * steps; otherwise only when it starts or stops working. On by default. */ @@ -344,6 +352,7 @@ export function TranscriptPanel({ working, refreshWhileWorking, agentKey: agent.key, + onRefreshRequested, }); const { transcript, error } = shown; return ( From 2dfe27cda30b040f02943e07a56debb02cec7681 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 22:19:12 -0500 Subject: [PATCH 14/37] perf(agents): reuse unchanged transcript turns and reply Markdown Finishing the latest turn used to render earlier turns again. Skip that work when the turn and its display props are unchanged, and reuse rendered Markdown when an open reply keeps the same text. Co-authored-by: Jello Signed-off-by: LordMelkor --- .../agents/ActivityTranscript.test.tsx | 23 ++++++++++++++++--- src/features/agents/ActivityTranscript.tsx | 11 ++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index b25a0dca6e..9947463caa 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -1053,7 +1053,7 @@ it("keeps the conversation readable while disclosing work and showing the curren expect(screen.getByText("source")).not.toBeVisible(); }); -it("keeps thought details collapsed until requested and preserves them across updates", async () => { +it("keeps an expanded thought open at turn end without rereading earlier activity", async () => { const turn: TranscriptTurn = { turnId: "thought-turn", channelId: null, @@ -1072,10 +1072,23 @@ it("keeps thought details collapsed until requested and preserves them across up }, ], }; + const earlierItems: TranscriptTurn["items"] = [ + { id: "previous", at: 1, type: "status", text: "Previous activity" }, + ]; + let earlierReads = 0; + const earlier: TranscriptTurn = { + ...turn, + turnId: "earlier", + endedAt: 1, + get items() { + earlierReads++; + return earlierItems; + }, + }; const user = userEvent.setup(); const { rerender } = render( "working"} />, @@ -1088,13 +1101,17 @@ it("keeps thought details collapsed until requested and preserves them across up await user.click(disclosure); expect(screen.getByText("formatting")).toBeVisible(); expect(screen.getAllByText("Checking the view")).toHaveLength(1); + expect(screen.getByText("Previous activity")).toBeVisible(); + const readsBeforeStop = earlierReads; rerender( "ended"} />, ); + expect(screen.queryByText("Working")).not.toBeInTheDocument(); + expect(earlierReads).toBe(readsBeforeStop); expect(screen.getByText("formatting")).toBeVisible(); await user.click(disclosure); expect(screen.getByText("formatting")).not.toBeVisible(); diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index 6c1a77dbf0..1ed645a3e7 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -2,6 +2,7 @@ import { Component, Fragment, createContext, + memo, useContext, useEffect, useSyncExternalStore, @@ -454,7 +455,7 @@ export function ActivityTranscript({ : "Session continued; earlier turns not shown"}

)} - } label={{heading}} > - {body && } + {body && } ); } @@ -806,7 +809,7 @@ function Item({ >
- +
@@ -872,6 +875,8 @@ function Reply({ text }: { text: string }) { ); } +const MemoizedReply = memo(Reply); + /** A file's lines; a final newline does not start another line. */ const lines = (text: string) => text.replace(/\n$/, "").split("\n"); /** One hunk between the unchanged leading and trailing lines. */ From de3bf6dfc008284480800b033e7027fd69a5093b Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 23:17:29 -0500 Subject: [PATCH 15/37] Load earlier Claude activity when refreshing a preview Record the full-history request when Refresh is clicked so a queued or interrupted read can finish it. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 148 ++++++++++++++++++++++++-- src/bundled/claude-code/tabs.tsx | 2 + 2 files changed, 142 insertions(+), 8 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index cfb913656b..6db3f17fc7 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -532,7 +532,7 @@ function longTranscript() { return { Activity: tab(type, 1), path: join(home, ".claude/projects", file), - holdNextSize() { + holdNextFileProcess(...ids: string[]) { const run = spawn.getMockImplementation(); if (!run) throw new Error("Missing manifest process fixture"); let release!: () => void; @@ -540,7 +540,9 @@ function longTranscript() { release = resolve; }); const started = new Promise((resolve) => { - spawn.mockImplementationOnce(async (id, options) => { + spawn.mockImplementation(async (id, options) => { + if (!ids.includes(id)) return run(id, options); + spawn.mockImplementation(run); const process = await run(id, options); const code = await process.exited; resolve(id); @@ -638,13 +640,18 @@ it("loads the missing history when a working session grows past the held tail", } }); -async function openLongTranscript() { - const fixture = longTranscript(); - const { Activity } = fixture; +async function showLongTranscript( + Activity: ReturnType["Activity"], +) { render(); await userEvent.click( screen.getByRole("button", { name: /^View transcript/ }), ); +} + +async function openLongTranscript() { + const fixture = longTranscript(); + await showLongTranscript(fixture.Activity); const load = await screen.findByRole("button", { name: /load earlier activity/i, }); @@ -653,6 +660,124 @@ async function openLongTranscript() { return { ...fixture, load, summary }; } +const transcriptSummary = { selector: "summary span" }; +const partialHistory = "Earlier activity is not loaded."; + +async function expectFullPreviewHistory(first = "earlier") { + expect(await screen.findByText(first, transcriptSummary)).toBeVisible(); + expect(screen.getByText("newest", transcriptSummary)).toBeVisible(); + expect(screen.queryByText(partialHistory)).toBeNull(); +} + +it.each(["Refresh transcript", "Load earlier activity"])( + "expands a Claude preview with %s and reads only the tail when work starts", + async (action) => { + const { path, fileReads, holdNextFileProcess, startCompaction, summary } = + await openLongTranscript(); + const newest = await summary("newest"); + const before = fileReads().length; + const expansion = holdNextFileProcess("read", "read-page"); + try { + fireEvent.click(screen.getByRole("button", { name: action })); + await expansion.started; + expect(newest).toBeVisible(); + expect(screen.getByText(partialHistory)).toBeVisible(); + } finally { + await act(async () => expansion.release()); + } + await expectFullPreviewHistory(); + expect(fileReads().slice(before)).toEqual(["read"]); + + const after = fileReads().length; + appendFileSync(path, `\n${sessionPrompt("working after expansion")}`); + const finish = startCompaction(); + try { + expect(await summary("working after expansion")).toBeVisible(); + await expectFullPreviewHistory(); + expect(fileReads().slice(after)).toEqual(["read-page"]); + } finally { + await act(finish); + } + }, +); + +it("expands a Claude preview when Refresh queues during its initial read", async () => { + const { Activity, fileReads, holdNextFileProcess } = longTranscript(); + const opening = holdNextFileProcess("read-page"); + try { + await showLongTranscript(Activity); + expect(await opening.started).toBe("read-page"); + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + expect(screen.queryByText("newest", transcriptSummary)).toBeNull(); + expect(fileReads()).toEqual(["read-page"]); + } finally { + await act(async () => opening.release()); + } + await expectFullPreviewHistory(); + expect(fileReads()).toEqual(["read-page", "read"]); +}); + +it.each([false, true])( + "expands a Claude preview when work stops during Refresh (hidden: %s)", + async (hide) => { + const { + path, + gap, + fileReads, + holdNextFileProcess, + startCompaction, + summary, + } = await openLongTranscript(); + appendFileSync(path, `\n${sessionPrompt("during refresh")}`); + let finish: ReturnType | undefined = + startCompaction(); + const visibility = vi.spyOn(document, "hidden", "get"); + try { + await summary("during refresh"); + writeFileSync( + path, + [ + sessionPrompt("corrected earlier", earlierEvent), + gap, + sessionPrompt("newest"), + sessionPrompt("during refresh"), + ].join("\n"), + ); + const interrupted = holdNextFileProcess("read", "read-page"); + try { + fireEvent.click( + screen.getByRole("button", { name: "Refresh transcript" }), + ); + await interrupted.started; + expect(screen.getByText(partialHistory)).toBeVisible(); + appendFileSync(path, `\n${sessionPrompt("after interrupted refresh")}`); + if (hide) { + visibility.mockReturnValue(true); + fireEvent(document, new Event("visibilitychange")); + } + const beforeStop = fileReads().length; + await act(finish); + finish = undefined; + await act(async () => interrupted.release()); + if (hide) { + expect(fileReads()).toHaveLength(beforeStop); + expect(screen.getByText(partialHistory)).toBeVisible(); + visibility.mockReturnValue(false); + fireEvent(document, new Event("visibilitychange")); + } + expect(await summary("after interrupted refresh")).toBeVisible(); + await expectFullPreviewHistory("corrected earlier"); + expect(fileReads().slice(beforeStop)).toEqual(["read"]); + } finally { + interrupted.release(); + } + } finally { + visibility.mockRestore(); + if (finish) await act(finish); + } + }, +); + it("reads only the tail at both working changes and keeps earlier turns", async () => { const { load, path, fileReads, startCompaction, summary } = await openLongTranscript(); @@ -832,8 +957,15 @@ it.each([ { refresh: false, hide: true, reads: "the tail on return" }, { refresh: true, hide: false, reads: "full history for a queued Refresh" }, ])("reads $reads when turn end aborts a poll", async ({ refresh, hide }) => { - const { load, path, gap, fileReads, holdNextSize, startCompaction, summary } = - await openLongTranscript(); + const { + load, + path, + gap, + fileReads, + holdNextFileProcess, + startCompaction, + summary, + } = await openLongTranscript(); await userEvent.click(load); await summary("earlier"); appendFileSync(path, `\n${sessionPrompt("during")}`); @@ -843,7 +975,7 @@ it.each([ await vi.waitFor(() => screen.getByText("during", { selector: "summary span" }), ); - const poll = holdNextSize(); + const poll = holdNextFileProcess("size"); try { act(() => { vi.advanceTimersByTime(LIVE_READ_MS); diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index db492a900d..59df5aaea7 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -1075,6 +1075,8 @@ export function createTabs({ agent={agent} onRefreshRequested={() => { refreshCount.current++; + if (fullHistory.current?.input !== input) + fullHistory.current = { input, loaded: false }; }} read={async (signal) => { const refresh = refreshCount.current; From aa524c597a243d18cff2fe13e90afe5b5d325838 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 23:26:14 -0500 Subject: [PATCH 16/37] Model Claude transcript reads and refresh intent explicitly Keep entry stamps, overlap observation and publication tied to the active read. Preserve manual Refresh across cancellation and retry, and retain the observed overlap decision across a stop. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.reader.test.tsx | 225 ++++++++ src/bundled/claude-code/tabs.tsx | 329 ++++++++---- .../claude-code/transcript-reader.test.ts | 507 ++++++++++++++++++ 3 files changed, 948 insertions(+), 113 deletions(-) create mode 100644 src/bundled/claude-code/tabs.reader.test.tsx create mode 100644 src/bundled/claude-code/transcript-reader.test.ts diff --git a/src/bundled/claude-code/tabs.reader.test.tsx b/src/bundled/claude-code/tabs.reader.test.tsx new file mode 100644 index 0000000000..78a897e2be --- /dev/null +++ b/src/bundled/claude-code/tabs.reader.test.tsx @@ -0,0 +1,225 @@ +// @vitest-environment jsdom +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; +import type { TranscriptTurn } from "../../features/agents/activity-transcript"; +import type { Agent } from "../../features/agents/service"; +import { ClaudeDefaults } from "./defaults"; +import { ClaudeRuntime, type Config, DEFAULT_CONFIG } from "./runtime"; +import { ClaudeSetup } from "./setup"; +import { createTabs } from "./tabs"; +import type { ClaudeTranscript } from "./transcript"; + +vi.mock("../../features/agents/TranscriptPanel", { spy: true }); + +const agent: Agent = { + key: "c".repeat(64), + pubkey: "c".repeat(64), + owner: "a".repeat(64), + name: "Claude", + type: "buzz.claude-code/claude-code", + relay: "wss://example.org", + place: "here", + config: DEFAULT_CONFIG, + attention: {}, + skipped: {}, + timers: {}, + attentionEnabled: false, +}; + +afterEach(() => { + cleanup(); + vi.mocked(TranscriptPanel).mockReset(); + vi.restoreAllMocks(); + localStorage.clear(); +}); + +function openReader(working: boolean) { + localStorage.setItem( + "buzz.claude-code.sessions.v1", + JSON.stringify({ + [agent.key]: { channel: { id: "kept", seen: 0, at: 1 } }, + }), + ); + const runtime = new ClaudeRuntime( + {}, + () => undefined, + async () => undefined, + ); + const sessions = vi + .spyOn(runtime, "sessions") + .mockReturnValue([{ key: "channel", busy: working }]); + const preview = vi.spyOn(runtime, "transcriptPreview"); + const full = vi.spyOn(runtime, "transcript"); + const tail = vi.spyOn(runtime, "latestTurns"); + const panel = vi.mocked(TranscriptPanel).mockReturnValue(
); + const { ActivityTab } = createTabs({ + runtime, + defaults: new ClaudeDefaults(), + setup: new ClaudeSetup(undefined), + }); + const view = () => ; + const { rerender } = render(view()); + fireEvent.click(screen.getByRole("button", { name: /^View transcript/ })); + + function callbacks() { + const props = panel.mock.lastCall?.[0]; + if (!props?.readLatest) + throw new Error("Claude transcript reader did not open"); + return { read: props.read, readLatest: props.readLatest }; + } + function setWorking(next: boolean) { + sessions.mockReturnValue([{ key: "channel", busy: next }]); + rerender(view()); + expect(panel.mock.lastCall?.[0].working).toBe(next); + } + + return { callbacks, preview, full, tail, setWorking }; +} + +function turn(turnId: string, startedAt = 1) { + return { + turnId, + startedAt, + channelId: "channel", + threadRootId: null, + triggeringEventIds: [], + sessionId: "kept", + newSession: false, + config: [], + partial: false, + items: [], + } satisfies TranscriptTurn; +} + +const transcript = (...turns: TranscriptTurn[]) => ({ more: false, turns }); +const activeSignal = () => new AbortController().signal; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} + +async function cancelPoll( + reader: ReturnType, + held: readonly TranscriptTurn[], + reply: TranscriptTurn[], + timing: "before" | "after", +) { + const rawPoll = deferred(); + reader.tail.mockReturnValueOnce(rawPoll.promise); + const controller = new AbortController(); + const reason = new Error("Poll superseded"); + const cancel = () => rawPoll.promise.then(() => controller.abort(reason)); + const beforeObservation = timing === "before" ? cancel() : undefined; + const polling = reader.callbacks().readLatest(controller.signal, held); + const settlement = polling.catch((error: unknown) => error); + expect(reader.tail).toHaveBeenCalledOnce(); + const canceled = beforeObservation ?? cancel(); + rawPoll.resolve(reply); + await canceled; + expect(await settlement).toBe(reason); +} + +it.each([ + { timing: "before", mode: "preview" }, + { timing: "after", mode: "full" }, +] as const)( + "reads $mode when invalid overlap at the cancellation boundary is aborted $timing observation", + async ({ timing, mode }) => { + const reader = openReader(true); + const held = turn("previewed turn"); + const replacement = turn("new after cancellation", 2); + const nextPreview = transcript(replacement); + const nextFull = transcript(turn("earlier history"), replacement); + reader.preview + .mockResolvedValueOnce(transcript(held)) + .mockResolvedValueOnce(nextPreview); + reader.full.mockResolvedValue(nextFull); + const initial = await reader.callbacks().read(activeSignal()); + expect(initial).toEqual({ ...transcript(held), partial: true }); + if (!initial) throw new Error("Claude transcript preview did not load"); + + await cancelPoll(reader, initial.turns, [replacement], timing); + reader.setWorking(false); + const next = await reader.callbacks().read(activeSignal()); + expect(next).toEqual( + mode === "preview" ? { ...nextPreview, partial: true } : nextFull, + ); + }, +); + +it("keeps the last accepted rows when valid overlap at the cancellation boundary is aborted after observation", async () => { + const reader = openReader(true); + const held = turn("accepted turn"); + const obsolete = turn("obsolete poll turn", 2); + const fresh = turn("fresh working-change turn", 2); + reader.preview.mockResolvedValue(undefined); + reader.full.mockResolvedValue(transcript(held)); + reader.tail.mockResolvedValue([held, fresh]); + const initial = await reader.callbacks().read(activeSignal()); + expect(initial).toEqual(transcript(held)); + if (!initial) throw new Error("Claude transcript did not load"); + + await cancelPoll(reader, initial.turns, [held, obsolete], "after"); + reader.setWorking(false); + await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( + transcript(held, fresh), + ); +}); + +it("keeps the baseline when an ordinary read starts preaborted", async () => { + const reader = openReader(false); + const held = turn("settled baseline"); + const appended = turn("appended turn", 2); + reader.preview.mockResolvedValue(undefined); + reader.full.mockResolvedValue(transcript(held)); + reader.tail.mockResolvedValue([held, appended]); + await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( + transcript(held), + ); + + const reason = new Error("Read already superseded"); + await expect(reader.callbacks().read(AbortSignal.abort(reason))).rejects.toBe( + reason, + ); + + reader.setWorking(true); + await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( + transcript(held, appended), + ); +}); + +it("rejects a late ordinary read with its own abort reason", async () => { + const reader = openReader(false); + const latePreview = deferred(); + const current = turn("current history"); + const appended = turn("appended to current history", 2); + reader.preview + .mockReturnValueOnce(latePreview.promise) + .mockResolvedValue(undefined); + reader.full.mockResolvedValue(transcript(current)); + reader.tail.mockResolvedValue([current, appended]); + const controller = new AbortController(); + const reason = new Error("Read superseded in flight"); + const pending = reader.callbacks().read(controller.signal); + const settlement = pending.catch((error: unknown) => error); + expect(reader.preview).toHaveBeenCalledOnce(); + controller.abort(reason); + try { + await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( + transcript(current), + ); + } finally { + latePreview.resolve(transcript(turn("superseded preview"))); + } + expect(await settlement).toBe(reason); + + reader.setWorking(true); + await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( + transcript(current, appended), + ); +}); diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 59df5aaea7..55928ad2c1 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -13,6 +13,7 @@ import { ProviderDialogActions } from "../../features/agents/ProviderDialogActio // Claude's provider controls, New agent choices, and agent settings. import { Fragment, + type ContextType, type ReactNode, useContext, useEffect, @@ -86,6 +87,155 @@ import { type SettingGroup, } from "./settings-draft"; +type Focus = ContextType; +function initialHistory(input: string, focus: Focus) { + return { input, focus, attempt: focus ? 1 : 0, loading: false }; +} +type Turns = readonly TranscriptTurn[]; +type History = ClaudeTranscript & { partial?: true }; +type Stamp = { again: string; working: boolean; refresh: number }; +type Settled = Stamp & { result: History }; +type Begin = Omit & { + id: symbol; + input: string; + attempt: number; +}; +type Operation = Begin & + Stamp & + ( + | { phase: "tail"; held: Turns; prior: Settled } + | { phase: "poll"; held: Turns; prior?: Settled | undefined } + | { phase: "preview" | "full" } + ); +export type ReaderState = { + refresh: number; + full?: { input: string; loaded: boolean }; + active?: Operation | undefined; + settled?: Settled | undefined; +}; +type Outcome = { failed?: true } & ( + | { + type: "poll" | "tail"; + turns?: Turns | undefined; + overlap?: "observe" | "observed"; + } + | { type: "full" | "preview"; result?: History | undefined } +); +type ReaderEvent = + | (Outcome & { id: symbol }) + | ({ type: "begin"; held?: Turns | undefined } & Begin) + | { type: "refresh"; input: string } + | { type: "abort"; id: symbol }; + +export function focusHistory( + history: ReturnType | undefined, + input: string, + focus: Focus, + full?: ReaderState["full"], +) { + if (history?.input !== input) return initialHistory(input, focus); + if ( + focus && + history.focus !== focus && + !(full?.input === input && full.loaded) + ) + return { ...history, focus, attempt: history.attempt + 1 }; + return history; +} + +function validatedTail(held: Turns, turns?: Turns | undefined) { + if (!turns?.length) return turns; + const from = held.findIndex((turn) => turn.turnId === turns[0]?.turnId); + if ( + from < 0 || + held + .slice(from) + .some((turn, index) => turn.turnId !== turns[index]?.turnId) || + turns.some( + (turn, index) => + turn.startedAt < + ((turns[index - 1] ?? held[from - 1])?.startedAt ?? -Infinity), + ) + ) + return undefined; + return turns; +} + +/** Keep acquisition and publication tied to the same operation across a fallback read. */ +export function transition(state: ReaderState, event: ReaderEvent) { + const { active, refresh, settled: prior } = state; + const next = { ...state }; + const fallback = (op: Begin) => + !op.attempt && next.full?.input !== op.input ? "preview" : "full"; + if (event.type === "refresh") { + next.refresh++; + if (next.full?.input !== event.input) + next.full = { input: event.input, loaded: false }; + } else if (event.type === "begin") { + const { type: _type, held, ...start } = event; + const op = { ...start, refresh }; + if (held) next.active = { ...op, phase: "poll", held, prior }; + else { + next.settled = undefined; + next.active = + prior?.again === op.again && + prior.refresh === refresh && + prior.working !== op.working && + !prior.result.partial && + !prior.result.incomplete + ? { ...op, phase: "tail", held: prior.result.turns, prior } + : { ...op, phase: fallback(op) }; + } + } else { + if ( + !active || + active.id !== event.id || + (event.type !== "abort" && event.type !== active.phase) + ) + return { state, ignored: true as const }; + next.active = undefined; + if (event.type === "abort") return { state: next }; + const { input, again, working, refresh } = active; + let result: History | undefined; + if ("held" in active && (event.type === "poll" || event.type === "tail")) { + const { overlap } = event; + const turns = + overlap === "observed" + ? event.turns + : validatedTail(active.held, event.turns); + if ( + !turns && + !event.failed && + overlap !== "observed" && + next.full?.input !== input + ) + next.full = { input, loaded: false }; + if (overlap === "observe") return { state: { ...next, active }, turns }; + const prior = active.prior; + if (prior && turns) result = withLatest(prior.result, turns); + if (active.phase === "poll") { + next.settled = prior && result ? { ...prior, result } : undefined; + return { state: next, turns }; + } + if (!turns?.length || !result) { + const { held: _held, prior: _prior, ...start } = active; + next.active = { ...start, phase: fallback(active) }; + return { state: next }; + } + } else if (event.type === "preview" || event.type === "full") { + result = event.result; + if (!event.failed) { + if (event.type === "full") + next.full = { input, loaded: Boolean(result) }; + else if (result) result = { ...result, partial: true }; + else next.active = { ...active, phase: "full" }; + } + } + next.settled = result && { again, working, refresh, result }; + } + return { state: next }; +} + const message = (error: unknown) => error instanceof Error ? error.message : String(error); @@ -1003,22 +1153,17 @@ export function createTabs({ const workspace = readConfig(agent.config).workspace; const input = JSON.stringify([workspace, conversation.sessionId]); const focus = useContext(TranscriptFocus); - const [history, setHistory] = useState({ + const reader = useRef({ refresh: 0 }); + const [history, setHistory] = useState(() => + focusHistory(undefined, input, focus), + ); + const nextHistory = focusHistory( + history, input, focus, - attempt: focus ? 1 : 0, - loading: false, - }); - const fullHistory = useRef<{ input: string; loaded: boolean }>(undefined); - if (history.input !== input) { - setHistory({ input, focus, attempt: focus ? 1 : 0, loading: false }); - } else if ( - focus && - history.focus !== focus && - !(fullHistory.current?.input === input && fullHistory.current.loaded) - ) { - setHistory({ ...history, focus, attempt: history.attempt + 1 }); - } + reader.current.full, + ); + if (nextHistory !== history) setHistory(nextHistory); const loadEarlier = () => setHistory((old) => old.loading @@ -1029,100 +1174,71 @@ export function createTabs({ loading: true, }, ); - type History = ClaudeTranscript & { partial?: true }; const again = JSON.stringify([input, history.attempt]); - const refreshCount = useRef(0); - const settled = useRef<{ - again: string; - refresh: number; - working: boolean; - result: History; - }>(undefined); - async function latestTurns( - signal: AbortSignal, - held: readonly TranscriptTurn[], - ) { - const turns = await runtime.latestTurns( - conversation, - workspace, - working, - signal, - held, - ); + function dispatch(event: ReaderEvent) { + const step = transition(reader.current, event); + reader.current = step.state; + return step; + } + async function run(signal: AbortSignal, held?: Turns | undefined) { signal.throwIfAborted(); - if (turns && !turns.length) return turns; - const from = held.findIndex((turn) => turn.turnId === turns?.[0]?.turnId); - if ( - !turns || - from < 0 || - held - .slice(from) - .some((turn, index) => turn.turnId !== turns[index]?.turnId) || - turns.some( - (turn, index) => - turn.startedAt < - ((turns[index - 1] ?? held[from - 1])?.startedAt ?? -Infinity), - ) - ) { - if (fullHistory.current?.input !== input) - fullHistory.current = { input, loaded: false }; - return undefined; + const id = Symbol(); + const abort = () => dispatch({ type: "abort", id }); + signal.addEventListener("abort", abort); + const args = [conversation, workspace, working, signal] as const; + async function read(op: Operation) { + const type = op.phase; + if (type === "poll" || type === "tail") { + const turns = await runtime.latestTurns(...args, op.held); + signal.throwIfAborted(); + const observed = dispatch({ type, id, turns, overlap: "observe" }); + return { type, turns: observed.turns, overlap: "observed" as const }; + } + const result = + type === "full" + ? await runtime.transcript(...args) + : await runtime.transcriptPreview(...args); + return { type, result }; + } + try { + const start = { + id, + input, + again, + working, + attempt: history.attempt, + held, + }; + let step = dispatch({ type: "begin", ...start }); + while (step.state.active) { + const op = step.state.active; + let outcome: Outcome; + try { + outcome = await read(op); + } catch (error) { + step = dispatch({ type: op.phase, id, failed: true }); + signal.throwIfAborted(); + if (!step.state.active || step.ignored) throw error; + continue; + } + step = dispatch({ ...outcome, id }); + if (step.ignored) { + signal.throwIfAborted(); + throw new DOMException("Read superseded", "AbortError"); + } + } + return step; + } finally { + signal.removeEventListener("abort", abort); } - return turns; } return ( { - refreshCount.current++; - if (fullHistory.current?.input !== input) - fullHistory.current = { input, loaded: false }; - }} + onRefreshRequested={() => dispatch({ type: "refresh", input })} read={async (signal) => { - const refresh = refreshCount.current; - const prior = settled.current; - settled.current = undefined; - let result: History | undefined; try { - if ( - prior?.again === again && - prior.refresh === refresh && - prior.working !== working && - !prior.result.partial && - !prior.result.incomplete - ) { - const turns = await latestTurns(signal, prior.result.turns).catch( - () => undefined, - ); - signal.throwIfAborted(); - if (turns?.length) result = withLatest(prior.result, turns); - } - if ( - !result && - !history.attempt && - fullHistory.current?.input !== input - ) { - const tail = await runtime.transcriptPreview( - conversation, - workspace, - working, - signal, - ); - signal.throwIfAborted(); - if (tail) result = { ...tail, partial: true }; - } - if (!result) { - result = await runtime.transcript( - conversation, - workspace, - working, - signal, - ); - signal.throwIfAborted(); - fullHistory.current = { input, loaded: Boolean(result) }; - } - if (result) settled.current = { again, working, refresh, result }; - return result; + return (await run(signal)).state.settled?.result; } finally { if (history.loading && !signal.aborted) { setHistory((current) => @@ -1131,20 +1247,7 @@ export function createTabs({ } } }} - readLatest={async (signal, held) => { - const prior = settled.current; - let result: History | undefined; - try { - const turns = await latestTurns(signal, held); - signal.throwIfAborted(); - if (prior && turns) result = withLatest(prior.result, turns); - return turns; - } finally { - if (!signal.aborted) - settled.current = - prior && result ? { ...prior, result } : undefined; - } - }} + readLatest={async (signal, held) => (await run(signal, held)).turns} readKey={`${conversation.key}\u0000${workspace}`} readAgain={again} working={working} diff --git a/src/bundled/claude-code/transcript-reader.test.ts b/src/bundled/claude-code/transcript-reader.test.ts new file mode 100644 index 0000000000..752288e84f --- /dev/null +++ b/src/bundled/claude-code/transcript-reader.test.ts @@ -0,0 +1,507 @@ +import { strictEqual } from "node:assert/strict"; +import { expect, it } from "vitest"; +import type { TranscriptTurn } from "../../features/agents/activity-transcript"; +import { focusHistory, type ReaderState, transition } from "./tabs"; + +type Event = Parameters[1]; +type Active = Pick, "phase" | "id">; + +const initial: ReaderState = { refresh: 0 }; +const input = "session"; +const read = Symbol("read"); +const poll = Symbol("poll"); +const next = Symbol("next"); + +function turn(turnId: string, startedAt: number) { + return { + turnId, + startedAt, + channelId: null, + threadRootId: null, + triggeringEventIds: [], + newSession: false, + config: [], + partial: false, + items: [], + } satisfies TranscriptTurn; +} + +const earlier = turn("earlier", 1); +const latest = turn("latest", 2); +const tied = turn("tied", 2); +const finished = { ...latest, endedAt: 3 }; +const complete = { turns: [earlier, latest], more: false }; +const preview = { turns: [latest], more: true }; +const tail = [finished]; + +function begin( + id: symbol, + working: boolean, + attempt = 0, + held?: readonly TranscriptTurn[], + session = input, +) { + return { + type: "begin", + id, + input: session, + again: `${session}/${attempt}`, + attempt, + working, + ...(held && { held }), + } satisfies Event; +} + +function drive(state: ReaderState, ...events: Event[]) { + let result: ReturnType = { state }; + for (const event of events) result = transition(result.state, event); + return result; +} + +const phase = (state: ReaderState) => state.active?.phase; +const refresh = { type: "refresh", input } satisfies Event; +const abortPoll = { type: "abort", id: poll } as const; + +function fullSeed(result?: typeof complete & { incomplete?: string }) { + return drive( + initial, + begin(read, false), + { type: "preview", id: read }, + { type: "full", id: read, ...(result && { result }) }, + ).state; +} + +const seeds = { + complete: fullSeed(complete), + partial: drive(initial, begin(read, false), { + type: "preview", + id: read, + result: preview, + }).state, + incomplete: fullSeed({ ...complete, incomplete: "session unavailable" }), + absent: initial, +}; +const live = drive(seeds.complete, begin(read, true), { + type: "tail", + id: read, + turns: tail, +}).state; +const startPoll = begin(poll, true, 0, [earlier, finished]); + +it("expands a settled preview on manual Refresh and resumes with a working tail", () => { + const pending = drive(seeds.partial, refresh, begin(read, false)).state; + expect(phase(pending)).toBe("full"); + const { state } = drive(pending, { + type: "full", + id: read, + result: complete, + }); + expect(state.settled?.result).toEqual(complete); + expect(state.full?.loaded).toBe(true); + expect(phase(drive(state, begin(next, true)).state)).toBe("tail"); +}); + +it("keeps manual Refresh queued during the first preview", () => { + const pending = drive(initial, begin(read, false), refresh).state; + expect(phase(pending)).toBe("preview"); + const { state } = drive(pending, { + type: "preview", + id: read, + result: preview, + }); + expect(state.settled).toMatchObject({ + refresh: 0, + result: { partial: true }, + }); + expect(phase(drive(state, begin(next, false)).state)).toBe("full"); +}); + +it("preserves confirmed loaded history when manual Refresh is requested", () => { + const requested = drive(seeds.complete, refresh).state; + const nextFocus = opening(); + const idle = focusHistory(undefined, input, undefined); + expect(focusHistory(idle, input, nextFocus, requested.full)).toBe(idle); + expect(phase(drive(requested, begin(read, true)).state)).toBe("full"); +}); + +it("keeps manual Refresh scoped to the input it was requested for", () => { + const other = "replacement"; + const replacement = begin(next, false, 0, undefined, other); + const opened = drive(seeds.partial, refresh, replacement).state; + expect(phase(opened)).toBe("preview"); + + const refreshed = drive( + opened, + { type: "preview", id: next, result: preview }, + { type: "refresh", input: other }, + begin(read, false, 0, undefined, other), + ).state; + expect(phase(refreshed)).toBe("full"); +}); + +it("retries full history on the next working change after a failed manual Refresh", () => { + const pending = drive(seeds.partial, refresh, begin(read, true)).state; + expect(phase(pending)).toBe("full"); + const failed = drive(pending, { type: "full", id: read, failed: true }).state; + expect(failed.active).toBeUndefined(); + expect(failed.settled).toBeUndefined(); + expect(phase(drive(failed, begin(next, false)).state)).toBe("full"); +}); + +it.each([ + { request: "manual Refresh", events: [refresh], command: "full" }, + { request: "automatic read", events: [], command: "preview" }, +] as const)( + "retries $command when work stops during a $request", + ({ events, command }) => { + const pending = drive(seeds.partial, ...events, begin(read, true)).state; + expect(phase(pending)).toBe(command); + const stopped = drive(pending, { type: "abort", id: read }).state; + const stale = transition(stopped, { + type: command, + id: read, + result: command === "full" ? complete : preview, + }); + expect(stale.ignored).toBe(true); + expect(stale.state.settled).toBeUndefined(); + expect(phase(drive(stale.state, begin(next, false)).state)).toBe(command); + }, +); + +it.each([ + ["complete", "tail"], + ["partial", "preview"], + ["incomplete", "full"], + ["absent", "preview"], +] as const)( + "handles a working change with %s history by reading %s", + (seed, command) => { + expect(phase(drive(seeds[seed], begin(next, true)).state)).toBe(command); + }, +); + +it.each([ + ["reordered same-time rows", [earlier, tied, latest]], + [ + "a row dated before the retained prefix", + [{ ...latest, startedAt: 0 }, tied], + ], + ["an unrelated window", [turn("unrelated", 4)]], + ["an empty window", []], +] as const)("reads full history when the working tail has %s", (_, turns) => { + const seed = fullSeed({ ...complete, turns: [earlier, latest, tied] }); + const { state } = drive(seed, begin(next, true), { + type: "tail", + id: next, + turns, + }); + expect(phase(state)).toBe("full"); +}); + +it("carries rows accepted by a poll into the next working-edge tail", () => { + const appended = turn("appended", 4); + const turns = [finished, appended]; + const accepted = drive( + seeds.complete, + begin(poll, false, 0, complete.turns), + { type: "poll", id: poll, turns }, + ); + expect(accepted.turns).toEqual(turns); + const { state } = drive(accepted.state, begin(next, true), { + type: "tail", + id: next, + turns: [appended], + }); + expect(state.settled?.result.turns).toEqual([earlier, finished, appended]); +}); + +it("keeps the baseline after an aborted poll and ignores its late result", () => { + const stopped = drive(live, startPoll, abortPoll).state; + expect(stopped.active).toBeUndefined(); + const late = transition(stopped, { type: "poll", id: poll, turns: tail }); + expect(late.ignored).toBe(true); + expect(late.turns).toBeUndefined(); + expect(phase(drive(late.state, begin(next, false)).state)).toBe("tail"); +}); + +it("keeps a queued Refresh when work stops during a poll", () => { + const { state } = drive( + live, + startPoll, + refresh, + abortPoll, + begin(next, false), + ); + expect(phase(state)).toBe("full"); +}); + +it("does not preview again after a full read finds no transcript", () => { + const missing = fullSeed(); + expect(phase(drive(missing, begin(next, false)).state)).toBe("full"); + const idle = focusHistory(undefined, input, undefined); + expect(focusHistory(idle, input, opening(), missing.full).attempt).toBe(1); +}); + +it("keeps the full-read requirement if an invalid poll is followed by an abort", () => { + const rejected = drive(seeds.partial, begin(poll, false, 0, preview.turns), { + type: "poll", + id: poll, + turns: [turn("unrelated", 4)], + }); + expect(rejected.turns).toBeUndefined(); + const { state } = drive(rejected.state, abortPoll, begin(next, true)); + expect(phase(state)).toBe("full"); +}); + +it.each([ + { + scenario: "a successful tail", + responses: [{ type: "tail", id: read, turns: tail }], + }, + { + scenario: "a full fallback after a failed tail", + responses: [ + { type: "tail", id: read, failed: true }, + { type: "full", id: read, result: complete }, + ], + }, +] as const)("keeps a Refresh queued during $scenario", ({ responses }) => { + const { state } = drive( + seeds.complete, + begin(read, true), + refresh, + ...responses, + ); + expect(state.settled?.refresh).toBe(0); + expect(phase(drive(state, begin(next, false)).state)).toBe("full"); +}); + +const opening = () => ({ events: ["event"], inputs: 1, done() {} }); + +it("starts focused with a full read and retries once per new focus after a failure", () => { + const focus = opening(); + const first = focusHistory(undefined, input, focus); + const reading = transition(initial, begin(read, false, first.attempt)); + expect(phase(reading.state)).toBe("full"); + const failed = transition(reading.state, { + type: "full", + id: read, + failed: true, + }); + expect(failed.state.active).toBeUndefined(); + expect(focusHistory(first, input, focus, failed.state.full)).toBe(first); + expect(focusHistory(first, input, opening(), failed.state.full).attempt).toBe( + 2, + ); +}); + +it("keeps Load earlier in flight on the same focus and reuses loaded history on a new focus", () => { + const focus = opening(); + const loading = { ...focusHistory(undefined, input, focus), loading: true }; + expect(focusHistory(loading, input, focus)).toBe(loading); + expect(focusHistory(loading, input, opening())).toMatchObject({ + attempt: loading.attempt + 1, + loading: true, + }); + expect(focusHistory(loading, input, opening(), seeds.complete.full)).toBe( + loading, + ); +}); + +function success({ phase, id }: Active) { + return ( + phase === "tail" || phase === "poll" + ? { type: phase, id, turns: tail } + : { type: phase, id, result: phase === "preview" ? preview : complete } + ) satisfies Event; +} + +function alphabet( + state: ReaderState, + previous: Active | undefined, + depth: number, +) { + const current = state.active; + return [ + refresh, + begin(Symbol(), false), + begin(Symbol(), true), + begin(Symbol(), true, 0, state.settled?.result.turns ?? preview.turns), + current && { type: "abort", id: current.id }, + current && success(current), + previous && success(previous), + previous && { type: "abort", id: previous.id }, + current && { + type: current.phase, + id: current.id, + ...(depth % 2 === 0 && { failed: true as const }), + }, + ] satisfies (Event | undefined)[]; +} + +function verify( + before: ReaderState, + event: Event, + result: ReturnType, + refresh: number, + entryRefresh: number, + record: (witness: string) => void, + path: string, +) { + const { active, settled, full } = result.state; + strictEqual(result.state.refresh, refresh, path); + + if (event.type === "refresh") { + strictEqual(active, before.active, path); + strictEqual(settled, before.settled, path); + strictEqual(full?.input, event.input, path); + const alreadyLoaded = + before.full?.input === event.input && before.full.loaded; + strictEqual(full?.loaded, alreadyLoaded, path); + if (active) record("Refresh while a read is active"); + return; + } + if (event.type === "begin") { + strictEqual(active?.id, event.id, path); + strictEqual(full, before.full, path); + const prior = before.settled; + if (event.held) { + strictEqual(active?.phase, "poll", path); + strictEqual(settled, prior, path); + } else { + const usable = + prior && + prior.again === event.again && + prior.working !== event.working && + !prior.result.partial && + !prior.result.incomplete; + const eligible = !!usable && prior.refresh === refresh; + const command = eligible + ? "tail" + : event.attempt || full?.input === event.input + ? "full" + : "preview"; + strictEqual(active?.phase, command, path); + strictEqual(settled, undefined, path); + if (eligible) record("working tail"); + if (usable && !eligible) record("Refresh bypasses a working tail"); + } + return; + } + const stale = event.id !== before.active?.id; + if (stale || event.type === "abort") { + strictEqual(result.ignored, stale ? true : undefined, path); + strictEqual(result.turns, undefined, path); + strictEqual(settled, before.settled, path); + strictEqual(full, before.full, path); + strictEqual(active, stale ? before.active : undefined, path); + if (stale && active) record(`stale ${event.type}`); + if (!stale && before.active?.phase === "poll" && settled) + record("abort with poll baseline"); + return; + } + + const hasValue = + "turns" in event + ? !!event.turns?.length + : "result" in event && !!event.result; + if (event.type === "full" && !event.failed) { + strictEqual(full?.input, before.active?.input, path); + strictEqual(full?.loaded, hasValue, path); + } else if (event.type === "full" || event.type === "preview") { + strictEqual(full, before.full, path); + } + if (event.failed) record(`failed ${event.type}`); + else if (!hasValue) record(`missing ${event.type}`); + if (event.type === "poll") { + strictEqual(active, undefined, path); + const expected = hasValue ? before.settled?.refresh : undefined; + strictEqual(settled?.refresh, expected, path); + return; + } + + const fallback = + !hasValue && + (event.type === "tail" || (event.type === "preview" && !event.failed)); + strictEqual(active?.id, fallback ? event.id : undefined, path); + strictEqual(active?.phase, fallback ? "full" : undefined, path); + strictEqual(settled?.refresh, hasValue ? entryRefresh : undefined, path); + if (hasValue && entryRefresh < refresh) record("settles with Refresh queued"); +} + +it.each(Object.entries(seeds))( + "checks all five-event sequences from %s history", + (seed, initialState) => { + const witnesses = new Map(); + const record = (name: string) => + witnesses.set(name, (witnesses.get(name) ?? 0) + 1); + const path: string[] = []; + let leaves = 0; + + function visit( + state: ReaderState, + refresh: number, + entryRefresh: number, + previous?: Active, + ) { + if (path.length === 5) { + leaves++; + return; + } + for (const [index, event] of alphabet( + state, + previous, + path.length, + ).entries()) { + path.push( + event ? `${index + 1} ${event.type}` : `${index + 1} skipped`, + ); + if (event) { + const refreshed = refresh + Number(event.type === "refresh"); + const entered = event.type === "begin" ? refresh : entryRefresh; + const result = transition(state, event); + verify( + state, + event, + result, + refreshed, + entered, + record, + path.join(" → "), + ); + const retired = + state.active && result.state.active?.id !== state.active.id; + visit( + result.state, + refreshed, + entered, + retired ? state.active : previous, + ); + } else { + visit(state, refresh, entryRefresh, previous); + } + path.pop(); + } + } + + visit(initialState, 0, 0); + expect(leaves).toBe(59_049); + const first = + seed === "complete" || seed === "incomplete" ? "full" : "preview"; + for (const witness of [ + "Refresh while a read is active", + "working tail", + "Refresh bypasses a working tail", + "abort with poll baseline", + "stale abort", + `stale ${first}`, + "settles with Refresh queued", + "failed poll", + "missing poll", + `failed ${first}`, + `missing ${first}`, + ]) { + expect(witnesses.get(witness), witness).toBeGreaterThan(0); + } + }, +); From 87d47ca458874e9e98817936a6e139f64fd1af83 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 23:40:09 -0500 Subject: [PATCH 17/37] Exercise Claude overlap cancellation through the mounted panel Keep one mounted test for runtime observation ordering. Check the before and after cancellation decisions at the reader transition boundary. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.reader.test.tsx | 244 ++++++------------ .../claude-code/transcript-reader.test.ts | 47 +++- 2 files changed, 118 insertions(+), 173 deletions(-) diff --git a/src/bundled/claude-code/tabs.reader.test.tsx b/src/bundled/claude-code/tabs.reader.test.tsx index 78a897e2be..b261c29e87 100644 --- a/src/bundled/claude-code/tabs.reader.test.tsx +++ b/src/bundled/claude-code/tabs.reader.test.tsx @@ -1,16 +1,20 @@ // @vitest-environment jsdom -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import "@testing-library/jest-dom/vitest"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; import { afterEach, expect, it, vi } from "vitest"; -import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; +import { LIVE_READ_MS } from "../../features/agents/TranscriptPanel"; import type { TranscriptTurn } from "../../features/agents/activity-transcript"; import type { Agent } from "../../features/agents/service"; import { ClaudeDefaults } from "./defaults"; import { ClaudeRuntime, type Config, DEFAULT_CONFIG } from "./runtime"; import { ClaudeSetup } from "./setup"; import { createTabs } from "./tabs"; -import type { ClaudeTranscript } from "./transcript"; - -vi.mock("../../features/agents/TranscriptPanel", { spy: true }); const agent: Agent = { key: "c".repeat(64), @@ -29,12 +33,36 @@ const agent: Agent = { afterEach(() => { cleanup(); - vi.mocked(TranscriptPanel).mockReset(); vi.restoreAllMocks(); + vi.useRealTimers(); localStorage.clear(); }); -function openReader(working: boolean) { +function turn(text: string, at: number) { + return { + turnId: text, + startedAt: at, + channelId: "channel", + threadRootId: null, + triggeringEventIds: [], + sessionId: "kept", + newSession: false, + config: [], + partial: false, + items: [{ id: text, at, type: "prompt", text, sections: [], steer: false }], + } satisfies TranscriptTurn; +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((complete) => { + resolve = complete; + }); + return { promise, resolve }; +} + +it("loads full Claude history when work stops after a poll observes invalid overlap", async () => { + vi.useFakeTimers(); localStorage.setItem( "buzz.claude-code.sessions.v1", JSON.stringify({ @@ -48,11 +76,30 @@ function openReader(working: boolean) { ); const sessions = vi .spyOn(runtime, "sessions") - .mockReturnValue([{ key: "channel", busy: working }]); - const preview = vi.spyOn(runtime, "transcriptPreview"); - const full = vi.spyOn(runtime, "transcript"); - const tail = vi.spyOn(runtime, "latestTurns"); - const panel = vi.mocked(TranscriptPanel).mockReturnValue(
); + .mockReturnValue([{ key: "channel", busy: true }]); + const next = turn("Latest after the stop", 3); + const finish = deferred(); + vi.spyOn(runtime, "transcriptPreview") + .mockResolvedValueOnce({ + turns: [turn("Previewed activity", 2)], + more: true, + }) + .mockImplementation(async () => { + await finish.promise; + return { turns: [next], more: true }; + }); + vi.spyOn(runtime, "transcript").mockImplementation(async () => { + await finish.promise; + return { turns: [turn("Earlier history", 1), next], more: false }; + }); + const poll = deferred(); + let pollSignal: AbortSignal | undefined; + vi.spyOn(runtime, "latestTurns").mockImplementationOnce( + (_, _workspace, _working, signal) => { + pollSignal = signal; + return poll.promise; + }, + ); const { ActivityTab } = createTabs({ runtime, defaults: new ClaudeDefaults(), @@ -60,166 +107,29 @@ function openReader(working: boolean) { }); const view = () => ; const { rerender } = render(view()); - fireEvent.click(screen.getByRole("button", { name: /^View transcript/ })); + const load = "Load earlier activity"; + const summary = { selector: "summary span" }; + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: /^View transcript/ })); + }); + expect(screen.getByText("Previewed activity", summary)).toBeVisible(); + expect(screen.getByRole("button", { name: load })).toBeVisible(); - function callbacks() { - const props = panel.mock.lastCall?.[0]; - if (!props?.readLatest) - throw new Error("Claude transcript reader did not open"); - return { read: props.read, readLatest: props.readLatest }; - } - function setWorking(next: boolean) { - sessions.mockReturnValue([{ key: "channel", busy: next }]); + act(() => vi.advanceTimersByTime(LIVE_READ_MS)); + expect(pollSignal?.aborted).toBe(false); + const stop = poll.promise.then(() => { + sessions.mockReturnValue([{ key: "channel", busy: false }]); rerender(view()); - expect(panel.mock.lastCall?.[0].working).toBe(next); - } - - return { callbacks, preview, full, tail, setWorking }; -} - -function turn(turnId: string, startedAt = 1) { - return { - turnId, - startedAt, - channelId: "channel", - threadRootId: null, - triggeringEventIds: [], - sessionId: "kept", - newSession: false, - config: [], - partial: false, - items: [], - } satisfies TranscriptTurn; -} - -const transcript = (...turns: TranscriptTurn[]) => ({ more: false, turns }); -const activeSignal = () => new AbortController().signal; - -function deferred() { - let resolve!: (value: T) => void; - const promise = new Promise((done) => { - resolve = done; + expect(pollSignal?.aborted).toBe(true); }); - return { promise, resolve }; -} - -async function cancelPoll( - reader: ReturnType, - held: readonly TranscriptTurn[], - reply: TranscriptTurn[], - timing: "before" | "after", -) { - const rawPoll = deferred(); - reader.tail.mockReturnValueOnce(rawPoll.promise); - const controller = new AbortController(); - const reason = new Error("Poll superseded"); - const cancel = () => rawPoll.promise.then(() => controller.abort(reason)); - const beforeObservation = timing === "before" ? cancel() : undefined; - const polling = reader.callbacks().readLatest(controller.signal, held); - const settlement = polling.catch((error: unknown) => error); - expect(reader.tail).toHaveBeenCalledOnce(); - const canceled = beforeObservation ?? cancel(); - rawPoll.resolve(reply); - await canceled; - expect(await settlement).toBe(reason); -} - -it.each([ - { timing: "before", mode: "preview" }, - { timing: "after", mode: "full" }, -] as const)( - "reads $mode when invalid overlap at the cancellation boundary is aborted $timing observation", - async ({ timing, mode }) => { - const reader = openReader(true); - const held = turn("previewed turn"); - const replacement = turn("new after cancellation", 2); - const nextPreview = transcript(replacement); - const nextFull = transcript(turn("earlier history"), replacement); - reader.preview - .mockResolvedValueOnce(transcript(held)) - .mockResolvedValueOnce(nextPreview); - reader.full.mockResolvedValue(nextFull); - const initial = await reader.callbacks().read(activeSignal()); - expect(initial).toEqual({ ...transcript(held), partial: true }); - if (!initial) throw new Error("Claude transcript preview did not load"); - - await cancelPoll(reader, initial.turns, [replacement], timing); - reader.setWorking(false); - const next = await reader.callbacks().read(activeSignal()); - expect(next).toEqual( - mode === "preview" ? { ...nextPreview, partial: true } : nextFull, - ); - }, -); - -it("keeps the last accepted rows when valid overlap at the cancellation boundary is aborted after observation", async () => { - const reader = openReader(true); - const held = turn("accepted turn"); - const obsolete = turn("obsolete poll turn", 2); - const fresh = turn("fresh working-change turn", 2); - reader.preview.mockResolvedValue(undefined); - reader.full.mockResolvedValue(transcript(held)); - reader.tail.mockResolvedValue([held, fresh]); - const initial = await reader.callbacks().read(activeSignal()); - expect(initial).toEqual(transcript(held)); - if (!initial) throw new Error("Claude transcript did not load"); - - await cancelPoll(reader, initial.turns, [held, obsolete], "after"); - reader.setWorking(false); - await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( - transcript(held, fresh), - ); -}); - -it("keeps the baseline when an ordinary read starts preaborted", async () => { - const reader = openReader(false); - const held = turn("settled baseline"); - const appended = turn("appended turn", 2); - reader.preview.mockResolvedValue(undefined); - reader.full.mockResolvedValue(transcript(held)); - reader.tail.mockResolvedValue([held, appended]); - await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( - transcript(held), - ); - - const reason = new Error("Read already superseded"); - await expect(reader.callbacks().read(AbortSignal.abort(reason))).rejects.toBe( - reason, - ); - - reader.setWorking(true); - await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( - transcript(held, appended), - ); -}); - -it("rejects a late ordinary read with its own abort reason", async () => { - const reader = openReader(false); - const latePreview = deferred(); - const current = turn("current history"); - const appended = turn("appended to current history", 2); - reader.preview - .mockReturnValueOnce(latePreview.promise) - .mockResolvedValue(undefined); - reader.full.mockResolvedValue(transcript(current)); - reader.tail.mockResolvedValue([current, appended]); - const controller = new AbortController(); - const reason = new Error("Read superseded in flight"); - const pending = reader.callbacks().read(controller.signal); - const settlement = pending.catch((error: unknown) => error); - expect(reader.preview).toHaveBeenCalledOnce(); - controller.abort(reason); + poll.resolve([next]); try { - await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( - transcript(current), - ); + await stop; } finally { - latePreview.resolve(transcript(turn("superseded preview"))); + await act(async () => finish.resolve()); } - expect(await settlement).toBe(reason); - reader.setWorking(true); - await expect(reader.callbacks().read(activeSignal())).resolves.toEqual( - transcript(current, appended), - ); + expect(screen.getByText("Latest after the stop", summary)).toBeVisible(); + expect(screen.getByText("Earlier history", summary)).toBeVisible(); + expect(screen.queryByRole("button", { name: load })).toBeNull(); }); diff --git a/src/bundled/claude-code/transcript-reader.test.ts b/src/bundled/claude-code/transcript-reader.test.ts index 752288e84f..7334fc0380 100644 --- a/src/bundled/claude-code/transcript-reader.test.ts +++ b/src/bundled/claude-code/transcript-reader.test.ts @@ -216,9 +216,23 @@ it("carries rows accepted by a poll into the next working-edge tail", () => { }); it("keeps the baseline after an aborted poll and ignores its late result", () => { - const stopped = drive(live, startPoll, abortPoll).state; + const polled = [finished, turn("unpublished turn", 4)]; + const observed = drive(live, startPoll, { + type: "poll", + id: poll, + turns: polled, + overlap: "observe", + }); + expect(observed.turns).toEqual(polled); + expect(observed.state.settled).toBe(live.settled); + const stopped = drive(observed.state, abortPoll).state; expect(stopped.active).toBeUndefined(); - const late = transition(stopped, { type: "poll", id: poll, turns: tail }); + const late = transition(stopped, { + type: "poll", + id: poll, + turns: observed.turns, + overlap: "observed", + }); expect(late.ignored).toBe(true); expect(late.turns).toBeUndefined(); expect(phase(drive(late.state, begin(next, false)).state)).toBe("tail"); @@ -243,14 +257,35 @@ it("does not preview again after a full read finds no transcript", () => { }); it("keeps the full-read requirement if an invalid poll is followed by an abort", () => { - const rejected = drive(seeds.partial, begin(poll, false, 0, preview.turns), { + const observing = drive(seeds.partial, begin(poll, false, 0, preview.turns)); + const observation = { type: "poll", id: poll, turns: [turn("unrelated", 4)], + overlap: "observe", + } satisfies Event; + const observed = transition(observing.state, observation); + expect(observed.turns).toBeUndefined(); + expect(observed.state.active?.phase).toBe("poll"); + expect(observed.state.settled).toBe(seeds.partial.settled); + + const stopped = drive(observed.state, abortPoll).state; + const late = transition(stopped, { + type: "poll", + id: poll, + turns: observed.turns, + overlap: "observed", }); - expect(rejected.turns).toBeUndefined(); - const { state } = drive(rejected.state, abortPoll, begin(next, true)); - expect(phase(state)).toBe("full"); + expect(late.ignored).toBe(true); + expect(late.state.settled).toBe(seeds.partial.settled); + expect(phase(drive(late.state, begin(next, true)).state)).toBe("full"); + + const earlyStop = drive(observing.state, abortPoll).state; + const unobserved = transition(earlyStop, observation); + expect(unobserved.ignored).toBe(true); + expect(phase(drive(unobserved.state, begin(next, true)).state)).toBe( + "preview", + ); }); it.each([ From c4a20530cacad6dff861e65c4b6097b66432a2a3 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sat, 21 Nov 2026 23:48:08 -0500 Subject: [PATCH 18/37] Name the mounted Claude overlap regression for its behavior Co-authored-by: Jello Signed-off-by: LordMelkor --- .../claude-code/{tabs.reader.test.tsx => tabs-overlap.test.tsx} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/bundled/claude-code/{tabs.reader.test.tsx => tabs-overlap.test.tsx} (100%) diff --git a/src/bundled/claude-code/tabs.reader.test.tsx b/src/bundled/claude-code/tabs-overlap.test.tsx similarity index 100% rename from src/bundled/claude-code/tabs.reader.test.tsx rename to src/bundled/claude-code/tabs-overlap.test.tsx From 5ea965a9e099bbf485eaefe4cba9179ec92b2b61 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 00:03:43 -0500 Subject: [PATCH 19/37] Wait for the working Claude page in the divider test Wait for the real page process to exit before querying the shifted turn. The DOM query deadline previously included file I/O on a loaded worker. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 6db3f17fc7..454beed44e 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -821,8 +821,15 @@ it("keeps the session divider and prompt when a working turn shifts the 50-turn await sessionPrompts(localStore(), "claude-code", agent().key).save("kept", [ { label: "Instructions", text: "Saved session instructions" }, ]); - const { load, path, gap, fileReads, startCompaction, summary } = - await openLongTranscript(); + const { + load, + path, + gap, + fileReads, + holdNextFileProcess, + startCompaction, + summary, + } = await openLongTranscript(); const older = Array.from({ length: 50 }, (_, i) => sessionPrompt(`turn ${i}`), ); @@ -831,8 +838,11 @@ it("keeps the session divider and prompt when a working turn shifts the 50-turn await summary("turn 1"); const before = fileReads().length; appendFileSync(path, `\n${sessionPrompt("during")}`); + const page = holdNextFileProcess("read-page"); const finish = startCompaction(); try { + await page.started; + await act(async () => page.release()); await summary("during"); appendFileSync(path, `\n${sessionPrompt("finished")}`); } finally { From 066224c88366e41c9f928c7e4ea6a6ce0aa810b7 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 00:12:44 -0500 Subject: [PATCH 20/37] Wait for each real file read in the Claude divider test Release each held read in cleanup before querying the rendered rows. Cover expansion, work start, work end and manual refresh with the same fixture helper. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 38 ++++++++++++++------------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 454beed44e..ec94934d6f 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -657,7 +657,17 @@ async function openLongTranscript() { }); const summary = (text: string) => screen.findByText(text, { selector: "summary span" }); - return { ...fixture, load, summary }; + async function withFileRead(id: "read" | "read-page", action: () => T) { + const read = fixture.holdNextFileProcess(id); + try { + const result = await action(); + await read.started; + return result; + } finally { + await act(async () => read.release()); + } + } + return { ...fixture, load, summary, withFileRead }; } const transcriptSummary = { selector: "summary span" }; @@ -821,32 +831,22 @@ it("keeps the session divider and prompt when a working turn shifts the 50-turn await sessionPrompts(localStore(), "claude-code", agent().key).save("kept", [ { label: "Instructions", text: "Saved session instructions" }, ]); - const { - load, - path, - gap, - fileReads, - holdNextFileProcess, - startCompaction, - summary, - } = await openLongTranscript(); + const { load, path, gap, fileReads, withFileRead, startCompaction, summary } = + await openLongTranscript(); const older = Array.from({ length: 50 }, (_, i) => sessionPrompt(`turn ${i}`), ); writeFileSync(path, [...older, gap, sessionPrompt("newest")].join("\n")); - await userEvent.click(load); + await withFileRead("read", () => userEvent.click(load)); await summary("turn 1"); const before = fileReads().length; appendFileSync(path, `\n${sessionPrompt("during")}`); - const page = holdNextFileProcess("read-page"); - const finish = startCompaction(); + const finish = await withFileRead("read-page", startCompaction); try { - await page.started; - await act(async () => page.release()); await summary("during"); appendFileSync(path, `\n${sessionPrompt("finished")}`); } finally { - await act(finish); + await withFileRead("read-page", () => act(finish)); } await summary("finished"); const first = (await summary("turn 3")).closest("article"); @@ -865,8 +865,10 @@ it("keeps the session divider and prompt when a working turn shifts the 50-turn ); const afterTurn = rows(); const region = first?.closest("[aria-busy]"); - fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); - expect(region).toHaveAttribute("aria-busy", "true"); + await withFileRead("read", () => { + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + expect(region).toHaveAttribute("aria-busy", "true"); + }); await waitFor(() => expect(region).toHaveAttribute("aria-busy", "false")); expect(fileReads().at(-1)).toBe("read"); expect(rows()).toEqual(afterTurn); From 80ac8dfac77ac7029b9fa879abb053f991da9b6b Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 01:14:14 -0500 Subject: [PATCH 21/37] Keep equal transcript turns and snapshots across reads Co-authored-by: Jello Signed-off-by: LordMelkor --- docs/plugin-authoring-guide.md | 5 + src/features/agents/ActivityTranscript.tsx | 3 +- src/features/agents/TranscriptPanel.test.tsx | 324 ++++++++++++++++++- src/features/agents/TranscriptPanel.tsx | 38 +++ 4 files changed, 364 insertions(+), 6 deletions(-) diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index 52f7433229..14baa83417 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -391,6 +391,11 @@ file diffs, prompt sections and context use. The plugin still owns its conversation list and marks its own sent-message items with `posted: true` and `messageId`. Derive its props from `@buzz/author` with `ComponentProps["Transcript"]>`. +The panel compares each read with the one before and keeps the turns that did +not change, so only a changed turn draws again. Give each turn a `turnId` that +is unique in the transcript and the same on every read. Build turn data from +plain objects and arrays, as `JSON.parse` gives. Never change an object after a +read returned it: a turn that changed is a new object. ```js export const inject = ["react", "conversation", "panels", "pages"]; diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index 1ed645a3e7..d260987789 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -432,8 +432,9 @@ export function ActivityTranscript({ () => ({ picture: poster ?? picture, focused }), [poster, picture, focused], ); + const value = useMemo(() => ({ profiles, community }), [profiles, community]); return ( - + vi.useFakeTimers()); afterEach(() => { @@ -33,15 +37,15 @@ afterEach(() => { }); /** A read whose calls each settle when the test says. */ -function reads() { +function reads() { const calls: { key: string; signal: AbortSignal; - resolve(value: string | undefined): void; + resolve(value: T | undefined): void; reject(error: Error): void; }[] = []; const read = (key: string) => (signal: AbortSignal) => - new Promise((resolve, reject) => + new Promise((resolve, reject) => calls.push({ key, signal, resolve, reject }), ); return { calls, read }; @@ -95,7 +99,7 @@ function nth(items: readonly T[], index: number) { if (!item) throw new Error(`No read ${index}`); return item; } -const settle = (call: { resolve(value: string): void }, value: string) => +const settle = (call: { resolve(value: T): void }, value: T) => act(async () => call.resolve(value)); it("reads on open and keeps its result while the next read runs", async () => { @@ -373,6 +377,316 @@ const turn = (turnId: string, text = turnId) => items: [{ id: text }], }) as unknown as TranscriptTurn; +function reuseTurn(turnId: string, items: TranscriptItem[] = []) { + return { + turnId, + channelId: "channel", + threadRootId: null, + triggeringEventIds: ["request"], + sessionId: "session", + newSession: false, + config: ["model", "effort"], + startedAt: 1, + partial: false, + items, + } satisfies TranscriptTurn; +} + +function toolTurn(turnId: string, answer: string) { + return reuseTurn(turnId, [ + { + id: "run", + at: 1, + type: "tool", + toolCallId: "run", + title: "Run script", + kind: "execute", + status: "completed", + input: "script", + output: "done", + diffs: [], + paths: ["script.sh"], + truncated: false, + children: [{ id: "child", at: 2, type: "message", text: answer }], + }, + ]); +} + +type TurnSnapshot = Transcript & { + more: boolean; + details?: { author: string }; +}; + +function readTurnSnapshots(working = false) { + const full = reads(); + const latest = reads(); + const view = renderHook(() => + useLiveTranscript({ + read: full.read("conversation"), + readLatest: latest.read("conversation"), + key: "conversation", + again: "", + working, + agentKey: "agent", + }), + ); + function snapshot() { + const shown = view.result.current.shown.transcript; + if (!shown) throw new Error("Transcript did not settle"); + return shown; + } + return { + full: full.calls, + latest: latest.calls, + refresh: () => act(() => view.result.current.refresh()), + snapshot, + loading: () => view.result.current.loading, + }; +} + +it("reuses accepted transcript turns across a live send at the turn limit", async () => { + const reader = readTurnSnapshots(true); + const turns = Array.from({ length: TURN_LIMIT }, (_, index) => + toolTurn(`turn ${index}`, "before the send"), + ); + const details = { author: "provider" }; + await settle(nth(reader.full, 0), { turns, more: false, details }); + const previousLast = nth(turns, TURN_LIMIT - 1); + const sent = reuseTurn("sent", [ + { + id: "sent-message", + at: 3, + type: "message", + text: "A posted message", + posted: true, + messageId: "message", + }, + ]); + act(() => vi.advanceTimersByTime(LIVE_READ_MS)); + await settle(nth(reader.latest, 0), [ + toolTurn(previousLast.turnId, "before the send"), + sent, + ]); + + const accepted = reader.snapshot(); + expect(accepted.turns.map(({ turnId }) => turnId)).toEqual([ + ...turns.slice(1).map(({ turnId }) => turnId), + "sent", + ]); + expect(accepted.turns[0]).toBe(turns[1]); + expect(accepted.turns.at(-2)).toBe(previousLast); + expect(accepted.turns.at(-1)).toBe(sent); + expect(accepted.more).toBe(true); + expect(accepted.details).toBe(details); +}); + +it("reuses accepted transcript turns by unique ID on Refresh while preserving the incoming window", async () => { + const reader = readTurnSnapshots(); + const first = reuseTurn("first"); + const moved = reuseTurn("moved"); + const repeatedBefore = reuseTurn("repeated before"); + const repeatedAfter = reuseTurn("repeated after"); + await settle(nth(reader.full, 0), { + more: false, + turns: [ + first, + moved, + reuseTurn("removed"), + repeatedBefore, + reuseTurn(repeatedBefore.turnId), + repeatedAfter, + ], + details: { author: "previous" }, + }); + const incoming = Object.freeze([ + reuseTurn(moved.turnId), + reuseTurn("added"), + reuseTurn(repeatedAfter.turnId), + reuseTurn(repeatedBefore.turnId), + reuseTurn(first.turnId), + reuseTurn(repeatedAfter.turnId), + ]); + const details = { author: "refreshed" }; + reader.refresh(); + await settle(nth(reader.full, 1), { more: true, turns: incoming, details }); + + const accepted = reader.snapshot(); + expect(accepted.turns.map(({ turnId }) => turnId)).toEqual([ + "moved", + "added", + "repeated after", + "repeated before", + "first", + "repeated after", + ]); + expect(accepted.turns[0]).toBe(moved); + expect(accepted.turns[1]).toBe(incoming[1]); + expect(accepted.turns[2]).toBe(incoming[2]); + expect(accepted.turns[3]).toBe(incoming[3]); + expect(accepted.turns[4]).toBe(first); + expect(accepted.turns[5]).toBe(incoming[5]); + expect(accepted.more).toBe(true); + expect(accepted.details).toBe(details); +}); + +it.each(["cyclic data", "unreadable field"])( + "settles a Refresh containing %s and keeps the other equal turn", + async (kind) => { + function extensionTurn() { + const extension: Record = {}; + if (kind === "cyclic data") extension.self = extension; + else + Object.defineProperty(extension, "value", { + enumerable: true, + get() { + throw new Error("Field is unavailable"); + }, + }); + return { ...reuseTurn("extension"), extension }; + } + const reader = readTurnSnapshots(); + const stable = reuseTurn("stable"); + await settle(nth(reader.full, 0), { + more: false, + turns: [extensionTurn(), stable], + }); + const incoming = extensionTurn(); + reader.refresh(); + expect(reader.loading()).toBe(true); + await settle(nth(reader.full, 1), { + more: false, + turns: [incoming, reuseTurn("stable")], + }); + expect(reader.loading()).toBe(false); + expect(reader.snapshot().turns[0]).toBe(incoming); + expect(reader.snapshot().turns[1]).toBe(stable); + }, +); + +it("keeps a frozen transcript through an equal Refresh and updates changed metadata", async () => { + const reader = readTurnSnapshots(); + const held = Object.freeze({ + turns: [toolTurn("first", "same reply")], + more: false, + details: { author: "original" }, + }); + await settle(nth(reader.full, 0), held); + reader.refresh(); + await settle(nth(reader.full, 1), { + ...held, + turns: [toolTurn("first", "same reply")], + details: { author: "original" }, + }); + expect(reader.snapshot()).toBe(held); + + const details = { author: "updated" }; + reader.refresh(); + await settle(nth(reader.full, 2), { + ...held, + turns: [toolTurn("first", "same reply")], + details, + }); + expect(reader.snapshot().details).toBe(details); + expect(reader.snapshot().turns[0]).toBe(held.turns[0]); +}); + +it.each(["inherited", "non-enumerable"])( + "preserves %s metadata from the incoming transcript", + async (kind) => { + const reader = readTurnSnapshots(); + const stable = reuseTurn("stable"); + await settle(nth(reader.full, 0), { turns: [stable], more: false }); + const incoming: TurnSnapshot = { + turns: [reuseTurn("stable")], + more: false, + }; + const details = { author: "incoming" }; + if (kind === "inherited") Object.setPrototypeOf(incoming, { details }); + else Object.defineProperty(incoming, "details", { value: details }); + reader.refresh(); + await settle(nth(reader.full, 1), incoming); + + expect(reader.snapshot().details).toBe(details); + }, +); + +it("settles a Refresh whose metadata cannot be compared", async () => { + const reader = readTurnSnapshots(); + const stable = reuseTurn("stable"); + await settle(nth(reader.full, 0), { + turns: [stable], + more: false, + details: { author: "original" }, + }); + const details = Object.defineProperty({ author: "unavailable" }, "author", { + get() { + throw new Error("Author is unavailable"); + }, + }); + reader.refresh(); + await settle(nth(reader.full, 1), { + turns: [reuseTurn("stable")], + more: false, + details, + }); + expect(reader.loading()).toBe(false); + expect(reader.snapshot().details).toBe(details); + expect(reader.snapshot().turns[0]).toBe(stable); +}); + +it("reuses accepted transcript turns only when snapshot fields are equal", async () => { + const reader = readTurnSnapshots(); + const nullRecord = () => Object.assign(Object.create(null), { key: "value" }); + const opaque = [ + ["functions", () => "value", () => "value"], + ["dates", new Date(1), new Date(1)], + ["maps", new Map([["key", "value"]]), new Map([["key", "value"]])], + ["sets", new Set(["value"]), new Set(["value"])], + ["regular expressions", /value/u, /value/u], + ] as const; + const fields: readonly (readonly [string, unknown, unknown, boolean])[] = [ + ["equal dense arrays", ["first", "second"], ["first", "second"], true], + ["reordered dense arrays", ["first", "second"], ["second", "first"], false], + [ + "different undefined keys", + { before: undefined }, + { after: undefined }, + false, + ], + ["null-prototype records", nullRecord(), nullRecord(), true], + ["different record prototypes", nullRecord(), { key: "value" }, false], + ["NaN", { value: Number.NaN }, { value: Number.NaN }, true], + ...opaque.flatMap(([name, before, after]) => [ + [`distinct ${name}`, before, after, false] as const, + [`shared ${name}`, before, before, true] as const, + ]), + ]; + const before = fields.map(([id, extension]) => ({ + ...reuseTurn(id), + extension, + })); + const after = fields.map(([id, , extension]) => ({ + ...reuseTurn(id), + extension, + })); + const corrected = toolTurn("corrected child", "updated text"); + await settle(nth(reader.full, 0), { + more: false, + turns: [...before, toolTurn("corrected child", "old text")], + }); + reader.refresh(); + await settle(nth(reader.full, 1), { + more: false, + turns: [...after, corrected], + }); + + const { turns } = reader.snapshot(); + fields.forEach(([name, , , equal], index) => { + expect(turns[index], name).toBe(equal ? before[index] : after[index]); + }); + expect(turns.at(-1)).toBe(corrected); +}); + it("swaps the latest turns over the end of the held transcript", () => { const held = { turns: [turn("1"), turn("2", "open")], more: true }; expect(withLatest(held, [turn("2", "grown"), turn("3")])).toEqual({ diff --git a/src/features/agents/TranscriptPanel.tsx b/src/features/agents/TranscriptPanel.tsx index 58f801aaeb..eaeb78790f 100644 --- a/src/features/agents/TranscriptPanel.tsx +++ b/src/features/agents/TranscriptPanel.tsx @@ -85,6 +85,43 @@ export function withLatest( }; } +const dataPrototypes = new Set([Object.prototype, Array.prototype, null]); +const { get, getPrototypeOf, ownKeys } = Reflect; +const sameFields: (a: unknown, b: unknown) => boolean = (a, b) => { + if (Object.is(a, b)) return true; + if (!a || !b || typeof a !== "object" || typeof b !== "object") return false; + try { + const proto = getPrototypeOf(a); + if (proto !== getPrototypeOf(b) || !dataPrototypes.has(proto)) return false; + const keys = ownKeys(a); + if (keys.length !== ownKeys(b).length) return false; + if (!keys.every((key) => Object.hasOwn(b, key))) return false; + return keys.every((key) => sameFields(get(a, key), get(b, key))); + } catch { + return false; + } +}; +const enumerableFields = (value: Transcript) => + Object.keys(value).length === ownKeys(value).length; +function reuseTurns(prior: T, next: T) { + try { + if (prior === next || !enumerableFields(next)) return next; + const plain = getPrototypeOf(next) === Object.prototype; + const held = new Map(prior.turns.map((turn) => [turn.turnId, turn])); + const counts = new Map(); + for (const { turnId } of [...prior.turns, ...next.turns]) + counts.set(turnId, (counts.get(turnId) ?? 0) + 1); + const turns = next.turns.map((turn) => { + const old = counts.get(turn.turnId) === 2 && held.get(turn.turnId); + return old && sameFields(old, turn) ? old : turn; + }); + const shown = plain ? { ...next, turns } : next; + return enumerableFields(prior) && sameFields(prior, shown) ? prior : shown; + } catch { + return next; + } +} + /** `read` for `key`: in full on open, on `refresh`, and when `again` or * `working` changes; while working, `readLatest` (or `read` without it) * {@link LIVE_READ_MS}, or twice the read's duration if longer, after each @@ -235,6 +272,7 @@ export function useLiveTranscript({ reading.then( (transcript) => { if (abort.signal.aborted) return; + if (prior && transcript) transcript = reuseTurns(prior, transcript); if (transcript !== undefined) return settle({ transcript }); // The latest turns don't continue what it holds. running.current = undefined; From 31693ad7c12b1d5e39aa071895bf9f4d5d70f7d0 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 03:35:47 -0500 Subject: [PATCH 22/37] Read loaded Claude history in full when work starts or stops Keep preview expansion intent across queued refreshes and interrupted polls. Restore the shared rolling window and Claude session decoration to the upstream behavior. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/runtime.ts | 29 +- src/bundled/claude-code/tabs.test.tsx | 452 +-------------- src/bundled/claude-code/tabs.tsx | 292 +++------- .../claude-code/transcript-reader.test.ts | 542 ------------------ src/features/agents/TranscriptPanel.test.tsx | 4 - src/features/agents/TranscriptPanel.tsx | 16 +- 6 files changed, 100 insertions(+), 1235 deletions(-) delete mode 100644 src/bundled/claude-code/transcript-reader.test.ts diff --git a/src/bundled/claude-code/runtime.ts b/src/bundled/claude-code/runtime.ts index b02cdf91bf..b93caa084f 100644 --- a/src/bundled/claude-code/runtime.ts +++ b/src/bundled/claude-code/runtime.ts @@ -130,7 +130,6 @@ import { } from "../../features/agents/gateway/contract"; import type { EligibleRoute } from "../../features/agents/gateway/route"; import { - TURN_LIMIT, readLatestTurns, readSessionTitle, readTranscript, @@ -970,25 +969,19 @@ export class ClaudeRuntime { 0, ), ); - const overlap = held.findIndex((turn) => turn.turnId === turns[0]?.turnId); - const prefix = held.slice(0, Math.max(0, overlap)); - const tail = withNotices( - turns, + const at = held.findIndex((turn) => turn.turnId === turns[0]?.turnId); + const kept = new Set( + held.slice(0, Math.max(at, 0)).map((t) => t.sessionId), + ); + // Decorated as a full read is, since these replace the turns it showed. + return withNotices( + this.prompts(conversation.agent) + .shown(turns) + .map((turn, index) => + kept.has(turn.sessionId) ? (turns[index] ?? turn) : turn, + ), this.notices.get(conversation.agent) ?? new Map(), ); - const merged = [...prefix, ...tail]; - const cut = Math.max(0, merged.length - TURN_LIMIT); - const prompts = this.prompts(conversation.agent); - const seen = new Set(); - for (let i = cut; i < merged.length; i++) { - const turn = merged[i]; - if (!turn?.sessionId || seen.has(turn.sessionId)) continue; - seen.add(turn.sessionId); - if (i < prefix.length && (turn.newSession || turn.continued)) continue; - merged[i] = prompts.shown([turn])[0] ?? turn; - } - const from = cut > 0 ? Math.min(cut, prefix.length) : prefix.length; - return merged.slice(from); } /** `sessions` with, for each a standalone turn started, the key it ran * under. */ diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index ec94934d6f..a729909005 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -11,7 +11,6 @@ import { import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; -import { sessionPrompts } from "../../features/agents/session-prompts"; import { LIVE_READ_MS } from "../../features/agents/TranscriptPanel"; import { readerInputs } from "../../features/profiles/target"; import { AgentTabs } from "../agents/AgentTabs"; @@ -657,17 +656,7 @@ async function openLongTranscript() { }); const summary = (text: string) => screen.findByText(text, { selector: "summary span" }); - async function withFileRead(id: "read" | "read-page", action: () => T) { - const read = fixture.holdNextFileProcess(id); - try { - const result = await action(); - await read.started; - return result; - } finally { - await act(async () => read.release()); - } - } - return { ...fixture, load, summary, withFileRead }; + return { ...fixture, load, summary }; } const transcriptSummary = { selector: "summary span" }; @@ -680,9 +669,9 @@ async function expectFullPreviewHistory(first = "earlier") { } it.each(["Refresh transcript", "Load earlier activity"])( - "expands a Claude preview with %s and reads only the tail when work starts", + "keeps the preview visible while %s loads full history", async (action) => { - const { path, fileReads, holdNextFileProcess, startCompaction, summary } = + const { fileReads, holdNextFileProcess, summary } = await openLongTranscript(); const newest = await summary("newest"); const before = fileReads().length; @@ -697,17 +686,6 @@ it.each(["Refresh transcript", "Load earlier activity"])( } await expectFullPreviewHistory(); expect(fileReads().slice(before)).toEqual(["read"]); - - const after = fileReads().length; - appendFileSync(path, `\n${sessionPrompt("working after expansion")}`); - const finish = startCompaction(); - try { - expect(await summary("working after expansion")).toBeVisible(); - await expectFullPreviewHistory(); - expect(fileReads().slice(after)).toEqual(["read-page"]); - } finally { - await act(finish); - } }, ); @@ -788,289 +766,37 @@ it.each([false, true])( }, ); -it("reads only the tail at both working changes and keeps earlier turns", async () => { - const { load, path, fileReads, startCompaction, summary } = - await openLongTranscript(); - await userEvent.click(load); - const earlier = await summary("earlier"); - const newest = await summary("newest"); - const padding = JSON.stringify({ - type: "progress", - data: "x".repeat(2 ** 20), - }); - const before = fileReads().length; - appendFileSync(path, `\n${sessionPrompt("during")}`); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - const finish = startCompaction(); - try { - await vi.waitFor(() => - screen.getByText("during", { selector: "summary span" }), - ); - appendFileSync(path, `\n${padding}\n${sessionPrompt("polled")}`); - act(() => { - vi.advanceTimersByTime(LIVE_READ_MS); - }); - } finally { - vi.useRealTimers(); - } - const during = await summary("during"); - const polled = await summary("polled"); - expect(new Set(fileReads().slice(before))).toEqual(new Set(["read-page"])); - const afterStart = fileReads().length; - appendFileSync(path, `\n${padding}\n${sessionPrompt("finished")}`); - await act(finish); - await summary("finished"); - expect(new Set(fileReads().slice(afterStart))).toEqual( - new Set(["read-page"]), - ); - for (const turn of [earlier, newest, during, polled]) - expect(turn).toBeVisible(); -}); - -it("keeps the session divider and prompt when a working turn shifts the 50-turn window", async () => { - await sessionPrompts(localStore(), "claude-code", agent().key).save("kept", [ - { label: "Instructions", text: "Saved session instructions" }, - ]); - const { load, path, gap, fileReads, withFileRead, startCompaction, summary } = +it("advances the 50-turn window on a working poll", async () => { + const { load, path, gap, startCompaction, summary } = await openLongTranscript(); - const older = Array.from({ length: 50 }, (_, i) => + const older = Array.from({ length: 48 }, (_, i) => sessionPrompt(`turn ${i}`), ); writeFileSync(path, [...older, gap, sessionPrompt("newest")].join("\n")); - await withFileRead("read", () => userEvent.click(load)); - await summary("turn 1"); - const before = fileReads().length; - appendFileSync(path, `\n${sessionPrompt("during")}`); - const finish = await withFileRead("read-page", startCompaction); - try { - await summary("during"); - appendFileSync(path, `\n${sessionPrompt("finished")}`); - } finally { - await withFileRead("read-page", () => act(finish)); - } - await summary("finished"); - const first = (await summary("turn 3")).closest("article"); - expect(first?.previousElementSibling).toHaveTextContent( - "Session continued; earlier turns not shown", - ); - expect( - screen - .getByText(/System prompt/, { selector: "summary span" }) - .closest("article"), - ).toBe(first); - expect(new Set(fileReads().slice(before))).toEqual(new Set(["read-page"])); - const rows = () => - Array.from(document.querySelectorAll("[data-entry]"), (row) => - row.getAttribute("data-entry"), - ); - const afterTurn = rows(); - const region = first?.closest("[aria-busy]"); - await withFileRead("read", () => { - fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); - expect(region).toHaveAttribute("aria-busy", "true"); - }); - await waitFor(() => expect(region).toHaveAttribute("aria-busy", "false")); - expect(fileReads().at(-1)).toBe("read"); - expect(rows()).toEqual(afterTurn); -}); - -it("finishes a pending full Refresh when work starts", async () => { - const { load, path, gap, startCompaction, summary } = - await openLongTranscript(); await userEvent.click(load); - await summary("earlier"); - writeFileSync( - path, - [sessionPrompt("revised earlier"), gap, sessionPrompt("newest")].join("\n"), - ); - fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); - const finish = startCompaction(); - try { - expect(await summary("revised earlier")).toBeVisible(); - } finally { - await act(finish); - } -}); - -it.each([ - { outcome: "a poll settles hidden", queued: true }, - { outcome: "a full read settles hidden", queued: true }, - { outcome: "a poll settles hidden", queued: false }, - { outcome: "a full read settles hidden", queued: false }, -])( - "handles turn end after $outcome (queued Refresh: $queued)", - async ({ outcome, queued }) => { - const { load, path, gap, fileReads, startCompaction, summary } = - await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); - appendFileSync(path, `\n${sessionPrompt("during")}`); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - const finish = startCompaction(); - const revise = (earlier: string) => - writeFileSync( - path, - [ - sessionPrompt(earlier), - gap, - sessionPrompt("newest"), - sessionPrompt("during"), - sessionPrompt("polled"), - ].join("\n"), - ); - try { - await vi.waitFor(() => - screen.getByText("during", { selector: "summary span" }), - ); - revise("corrected"); - if (outcome === "a full read settles hidden") { - fireEvent.click( - screen.getByRole("button", { name: "Refresh transcript" }), - ); - } else { - act(() => { - vi.advanceTimersByTime(LIVE_READ_MS); - }); - } - if (queued) - fireEvent.click( - screen.getByRole("button", { name: "Refresh transcript" }), - ); - } finally { - vi.useRealTimers(); - } - const hidden = vi.spyOn(document, "hidden", "get"); - hidden.mockReturnValue(true); - fireEvent(document, new Event("visibilitychange")); - await summary("polled"); - if (queued) { - revise("corrected while hidden"); - } else { - hidden.mockReturnValue(false); - fireEvent(document, new Event("visibilitychange")); - appendFileSync(path, `\n${sessionPrompt("finished")}`); - } - const beforeEnd = fileReads().length; - await act(finish); - if (queued) { - hidden.mockReturnValue(false); - fireEvent(document, new Event("visibilitychange")); - await summary("corrected while hidden"); - expect(fileReads().slice(beforeEnd)).toContain("read"); - } else { - await summary("finished"); - expect(fileReads().slice(beforeEnd)).toEqual(["read-page"]); - } - }, -); - -it.each([ - { refresh: false, hide: false, reads: "the tail" }, - { refresh: false, hide: true, reads: "the tail on return" }, - { refresh: true, hide: false, reads: "full history for a queued Refresh" }, -])("reads $reads when turn end aborts a poll", async ({ refresh, hide }) => { - const { - load, - path, - gap, - fileReads, - holdNextFileProcess, - startCompaction, - summary, - } = await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); + await summary("turn 0"); appendFileSync(path, `\n${sessionPrompt("during")}`); vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); const finish = startCompaction(); try { - await vi.waitFor(() => - screen.getByText("during", { selector: "summary span" }), + await vi.waitFor(() => screen.getByText("during", transcriptSummary)); + appendFileSync(path, `\n${sessionPrompt("polled")}`); + await act(async () => { + await vi.advanceTimersByTimeAsync(LIVE_READ_MS); + }); + vi.useRealTimers(); + await summary("polled"); + expect(screen.queryByText("turn 0", transcriptSummary)).toBeNull(); + expect(screen.getByText("turn 1", transcriptSummary)).toBeVisible(); + expect(document.querySelectorAll("[data-transcript] article")).toHaveLength( + 50, ); - const poll = holdNextFileProcess("size"); - try { - act(() => { - vi.advanceTimersByTime(LIVE_READ_MS); - }); - expect(await poll.started).toBe("size"); - vi.useRealTimers(); - writeFileSync( - path, - [ - sessionPrompt("corrected"), - gap, - sessionPrompt("newest"), - sessionPrompt("during"), - sessionPrompt("finished"), - ].join("\n"), - ); - if (refresh) - fireEvent.click( - screen.getByRole("button", { name: "Refresh transcript" }), - ); - const hidden = vi.spyOn(document, "hidden", "get"); - if (hide) { - hidden.mockReturnValue(true); - fireEvent(document, new Event("visibilitychange")); - } - const beforeEnd = fileReads().length; - await act(finish); - if (hide) { - await act(async () => poll.release()); - expect(fileReads()).toHaveLength(beforeEnd); - hidden.mockReturnValue(false); - fireEvent(document, new Event("visibilitychange")); - } - await summary("finished"); - if (refresh) { - await summary("corrected"); - expect(fileReads().slice(beforeEnd)).toContain("read"); - } else { - expect(fileReads().slice(beforeEnd)).toEqual(["read-page"]); - } - } finally { - poll.release(); - } } finally { vi.useRealTimers(); + await act(finish); } }); -it.each(["poll", "turn end"])( - "reads full history when the %s tail has no overlap", - async (when) => { - const { load, path, gap, fileReads, startCompaction, summary } = - await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); - appendFileSync(path, `\n${sessionPrompt("during")}`); - vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - const finish = startCompaction(); - try { - await vi.waitFor(() => - screen.getByText("during", { selector: "summary span" }), - ); - const before = fileReads().length; - appendFileSync( - path, - `\n${sessionPrompt("between")}\n${gap}\n${sessionPrompt("last")}`, - ); - if (when === "poll") - act(() => { - vi.advanceTimersByTime(LIVE_READ_MS); - }); - vi.useRealTimers(); - if (when === "turn end") await act(finish); - await summary("last"); - expect(await summary("between")).toBeVisible(); - expect(fileReads().slice(before)).toEqual(["read-page", "read"]); - } finally { - vi.useRealTimers(); - if (when === "poll") await act(finish); - } - }, -); - it("finishes Load earlier requested during work even when the turn ends", async () => { const { load, path, startCompaction, summary } = await openLongTranscript(); appendFileSync(path, `\n${sessionPrompt("during")}`); @@ -1207,146 +933,6 @@ it("opens the replacement session's preview when its first turn starts while hid } }); -it("finishes a Refresh interrupted while hidden when the window returns", async () => { - const { load, path, gap, startCompaction, summary } = - await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); - writeFileSync( - path, - [sessionPrompt("corrected"), gap, sessionPrompt("newest")].join("\n"), - ); - fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); - const hidden = vi.spyOn(document, "hidden", "get").mockReturnValue(true); - let finish!: () => Promise; - await act(async () => { - finish = startCompaction(); - }); - hidden.mockReturnValue(false); - fireEvent(document, new Event("visibilitychange")); - try { - expect(await summary("corrected")).toBeVisible(); - } finally { - await act(finish); - } -}); - -it("reads earlier rows again when a working change follows a failed Refresh", async () => { - const { load, path, gap, startCompaction, summary } = - await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); - chmodSync(path, 0); - await userEvent.click( - screen.getByRole("button", { name: "Refresh transcript" }), - ); - await screen.findByRole("alert"); - chmodSync(path, 0o600); - writeFileSync( - path, - [sessionPrompt("corrected"), gap, sessionPrompt("newest")].join("\n"), - ); - const finish = startCompaction(); - try { - expect(await summary("corrected")).toBeVisible(); - } finally { - await act(finish); - } -}); - -it.each([ - { file: "", reason: "file size read rejects on zero bytes" }, - { file: '{"type":"progress"}', reason: "tail has no turns" }, -])("replaces stale rows when the $reason at work start", async ({ file }) => { - const { load, path, startCompaction, summary } = await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); - writeFileSync(path, file); - const finish = startCompaction(); - try { - expect( - await screen.findByText("No turns captured for this scope yet."), - ).toBeVisible(); - expect( - screen.queryByText("earlier", { selector: "summary span" }), - ).toBeNull(); - } finally { - await act(finish); - } -}); - -it("retries incomplete session discovery when work starts", async () => { - const { load, path, startCompaction, summary } = await openLongTranscript(); - chmodSync(dirname(path), 0o111); - try { - await userEvent.click(load); - await screen.findByText( - /Some of this conversation’s sessions may be missing/, - ); - } finally { - chmodSync(dirname(path), 0o700); - } - appendFileSync(path, `\n${sessionPrompt("during")}`); - const finish = startCompaction(); - try { - await summary("during"); - expect( - screen.queryByText(/Some of this conversation’s sessions may be missing/), - ).toBeNull(); - } finally { - await act(finish); - } -}); - -it("reloads earlier rows when two tail turns change places at the same timestamp", async () => { - const { load, path, gap, startCompaction, summary } = - await openLongTranscript(); - const write = (earlier: string, tail: string[]) => - writeFileSync( - path, - [ - sessionPrompt(earlier), - gap, - ...tail.map((text) => sessionPrompt(text)), - ].join("\n"), - ); - write("earlier", ["newest", "second", "third"]); - await userEvent.click(load); - await summary("third"); - write("corrected", ["newest", "third", "second"]); - const finish = startCompaction(); - try { - await summary("corrected"); - const third = await summary("third"); - const second = await summary("second"); - expect( - third.compareDocumentPosition(second) & Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - } finally { - await act(finish); - } -}); - -it("restores canonical turn order when a working tail's clock goes backwards", async () => { - const { load, path, startCompaction, summary } = await openLongTranscript(); - await userEvent.click(load); - await summary("earlier"); - appendFileSync( - path, - `\n${sessionPrompt("clock rollback").replace("2026-10-09", "2026-10-08")}`, - ); - const finish = startCompaction(); - try { - const first = await summary("clock rollback"); - const earlier = await summary("earlier"); - expect( - first.compareDocumentPosition(earlier) & Node.DOCUMENT_POSITION_FOLLOWING, - ).toBeTruthy(); - } finally { - await act(finish); - } -}); - it.each(["on open", "after preview"])( "shows the earlier focused turn %s", async (when) => { diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 55928ad2c1..bdb71c1457 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -13,7 +13,6 @@ import { ProviderDialogActions } from "../../features/agents/ProviderDialogActio // Claude's provider controls, New agent choices, and agent settings. import { Fragment, - type ContextType, type ReactNode, useContext, useEffect, @@ -24,12 +23,8 @@ import { } from "react"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; -import type { TranscriptTurn } from "../../features/agents/activity-transcript"; import type { ClaudeTranscript } from "./transcript"; -import { - TranscriptPanel, - withLatest, -} from "../../features/agents/TranscriptPanel"; +import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; import { AgentInstructions } from "../../features/agents/AgentInstructions"; import { CreateModelChoices } from "../../features/agents/CreateModelChoices"; import { Dialog } from "../../shared/design-system/ui/Dialog"; @@ -87,155 +82,6 @@ import { type SettingGroup, } from "./settings-draft"; -type Focus = ContextType; -function initialHistory(input: string, focus: Focus) { - return { input, focus, attempt: focus ? 1 : 0, loading: false }; -} -type Turns = readonly TranscriptTurn[]; -type History = ClaudeTranscript & { partial?: true }; -type Stamp = { again: string; working: boolean; refresh: number }; -type Settled = Stamp & { result: History }; -type Begin = Omit & { - id: symbol; - input: string; - attempt: number; -}; -type Operation = Begin & - Stamp & - ( - | { phase: "tail"; held: Turns; prior: Settled } - | { phase: "poll"; held: Turns; prior?: Settled | undefined } - | { phase: "preview" | "full" } - ); -export type ReaderState = { - refresh: number; - full?: { input: string; loaded: boolean }; - active?: Operation | undefined; - settled?: Settled | undefined; -}; -type Outcome = { failed?: true } & ( - | { - type: "poll" | "tail"; - turns?: Turns | undefined; - overlap?: "observe" | "observed"; - } - | { type: "full" | "preview"; result?: History | undefined } -); -type ReaderEvent = - | (Outcome & { id: symbol }) - | ({ type: "begin"; held?: Turns | undefined } & Begin) - | { type: "refresh"; input: string } - | { type: "abort"; id: symbol }; - -export function focusHistory( - history: ReturnType | undefined, - input: string, - focus: Focus, - full?: ReaderState["full"], -) { - if (history?.input !== input) return initialHistory(input, focus); - if ( - focus && - history.focus !== focus && - !(full?.input === input && full.loaded) - ) - return { ...history, focus, attempt: history.attempt + 1 }; - return history; -} - -function validatedTail(held: Turns, turns?: Turns | undefined) { - if (!turns?.length) return turns; - const from = held.findIndex((turn) => turn.turnId === turns[0]?.turnId); - if ( - from < 0 || - held - .slice(from) - .some((turn, index) => turn.turnId !== turns[index]?.turnId) || - turns.some( - (turn, index) => - turn.startedAt < - ((turns[index - 1] ?? held[from - 1])?.startedAt ?? -Infinity), - ) - ) - return undefined; - return turns; -} - -/** Keep acquisition and publication tied to the same operation across a fallback read. */ -export function transition(state: ReaderState, event: ReaderEvent) { - const { active, refresh, settled: prior } = state; - const next = { ...state }; - const fallback = (op: Begin) => - !op.attempt && next.full?.input !== op.input ? "preview" : "full"; - if (event.type === "refresh") { - next.refresh++; - if (next.full?.input !== event.input) - next.full = { input: event.input, loaded: false }; - } else if (event.type === "begin") { - const { type: _type, held, ...start } = event; - const op = { ...start, refresh }; - if (held) next.active = { ...op, phase: "poll", held, prior }; - else { - next.settled = undefined; - next.active = - prior?.again === op.again && - prior.refresh === refresh && - prior.working !== op.working && - !prior.result.partial && - !prior.result.incomplete - ? { ...op, phase: "tail", held: prior.result.turns, prior } - : { ...op, phase: fallback(op) }; - } - } else { - if ( - !active || - active.id !== event.id || - (event.type !== "abort" && event.type !== active.phase) - ) - return { state, ignored: true as const }; - next.active = undefined; - if (event.type === "abort") return { state: next }; - const { input, again, working, refresh } = active; - let result: History | undefined; - if ("held" in active && (event.type === "poll" || event.type === "tail")) { - const { overlap } = event; - const turns = - overlap === "observed" - ? event.turns - : validatedTail(active.held, event.turns); - if ( - !turns && - !event.failed && - overlap !== "observed" && - next.full?.input !== input - ) - next.full = { input, loaded: false }; - if (overlap === "observe") return { state: { ...next, active }, turns }; - const prior = active.prior; - if (prior && turns) result = withLatest(prior.result, turns); - if (active.phase === "poll") { - next.settled = prior && result ? { ...prior, result } : undefined; - return { state: next, turns }; - } - if (!turns?.length || !result) { - const { held: _held, prior: _prior, ...start } = active; - next.active = { ...start, phase: fallback(active) }; - return { state: next }; - } - } else if (event.type === "preview" || event.type === "full") { - result = event.result; - if (!event.failed) { - if (event.type === "full") - next.full = { input, loaded: Boolean(result) }; - else if (result) result = { ...result, partial: true }; - else next.active = { ...active, phase: "full" }; - } - } - next.settled = result && { again, working, refresh, result }; - } - return { state: next }; -} - const message = (error: unknown) => error instanceof Error ? error.message : String(error); @@ -1153,17 +999,22 @@ export function createTabs({ const workspace = readConfig(agent.config).workspace; const input = JSON.stringify([workspace, conversation.sessionId]); const focus = useContext(TranscriptFocus); - const reader = useRef({ refresh: 0 }); - const [history, setHistory] = useState(() => - focusHistory(undefined, input, focus), - ); - const nextHistory = focusHistory( - history, + const [history, setHistory] = useState({ input, focus, - reader.current.full, - ); - if (nextHistory !== history) setHistory(nextHistory); + attempt: focus ? 1 : 0, + loading: false, + }); + const fullHistory = useRef<{ input: string; loaded: boolean }>(undefined); + if (history.input !== input) { + setHistory({ input, focus, attempt: focus ? 1 : 0, loading: false }); + } else if ( + focus && + history.focus !== focus && + !(fullHistory.current?.input === input && fullHistory.current.loaded) + ) { + setHistory({ ...history, focus, attempt: history.attempt + 1 }); + } const loadEarlier = () => setHistory((old) => old.loading @@ -1174,71 +1025,26 @@ export function createTabs({ loading: true, }, ); - const again = JSON.stringify([input, history.attempt]); - function dispatch(event: ReaderEvent) { - const step = transition(reader.current, event); - reader.current = step.state; - return step; - } - async function run(signal: AbortSignal, held?: Turns | undefined) { - signal.throwIfAborted(); - const id = Symbol(); - const abort = () => dispatch({ type: "abort", id }); - signal.addEventListener("abort", abort); - const args = [conversation, workspace, working, signal] as const; - async function read(op: Operation) { - const type = op.phase; - if (type === "poll" || type === "tail") { - const turns = await runtime.latestTurns(...args, op.held); - signal.throwIfAborted(); - const observed = dispatch({ type, id, turns, overlap: "observe" }); - return { type, turns: observed.turns, overlap: "observed" as const }; - } - const result = - type === "full" - ? await runtime.transcript(...args) - : await runtime.transcriptPreview(...args); - return { type, result }; - } - try { - const start = { - id, - input, - again, - working, - attempt: history.attempt, - held, - }; - let step = dispatch({ type: "begin", ...start }); - while (step.state.active) { - const op = step.state.active; - let outcome: Outcome; - try { - outcome = await read(op); - } catch (error) { - step = dispatch({ type: op.phase, id, failed: true }); - signal.throwIfAborted(); - if (!step.state.active || step.ignored) throw error; - continue; - } - step = dispatch({ ...outcome, id }); - if (step.ignored) { - signal.throwIfAborted(); - throw new DOMException("Read superseded", "AbortError"); - } - } - return step; - } finally { - signal.removeEventListener("abort", abort); - } - } + const requireFullHistory = () => { + if (fullHistory.current?.input !== input) + fullHistory.current = { input, loaded: false }; + }; return ( - agent={agent} - onRefreshRequested={() => dispatch({ type: "refresh", input })} + onRefreshRequested={requireFullHistory} read={async (signal) => { + const args = [conversation, workspace, working, signal] as const; try { - return (await run(signal)).state.settled?.result; + if (!history.attempt && fullHistory.current?.input !== input) { + const preview = await runtime.transcriptPreview(...args); + signal.throwIfAborted(); + if (preview) return { ...preview, partial: true }; + } + const result = await runtime.transcript(...args); + signal.throwIfAborted(); + fullHistory.current = { input, loaded: Boolean(result) }; + return result; } finally { if (history.loading && !signal.aborted) { setHistory((current) => @@ -1247,9 +1053,39 @@ export function createTabs({ } } }} - readLatest={async (signal, held) => (await run(signal, held)).turns} + readLatest={async (signal, held) => { + const turns = await runtime.latestTurns( + conversation, + workspace, + working, + signal, + held, + ); + signal.throwIfAborted(); + if (turns && !turns.length) return turns; + const from = held.findIndex( + (turn) => turn.turnId === turns?.[0]?.turnId, + ); + if ( + !turns || + from < 0 || + held + .slice(from) + .some((turn, i) => turn.turnId !== turns[i]?.turnId) || + turns.some( + (turn, i) => + turn.startedAt < + ((turns[i - 1] ?? held[from - 1])?.startedAt ?? -Infinity), + ) + ) { + // A stop can cancel this poll before the panel starts its fallback. + requireFullHistory(); + return undefined; + } + return turns; + }} readKey={`${conversation.key}\u0000${workspace}`} - readAgain={again} + readAgain={JSON.stringify([input, history.attempt])} working={working} reading="Reading the Claude session…" failed="Could not read the Claude session" @@ -1262,7 +1098,7 @@ export function createTabs({ notes={(transcript) => ( <> {transcript.partial && ( -
+
Earlier activity is not loaded.{" "} diff --git a/src/bundled/claude-code/transcript-reader.test.ts b/src/bundled/claude-code/transcript-reader.test.ts deleted file mode 100644 index 7334fc0380..0000000000 --- a/src/bundled/claude-code/transcript-reader.test.ts +++ /dev/null @@ -1,542 +0,0 @@ -import { strictEqual } from "node:assert/strict"; -import { expect, it } from "vitest"; -import type { TranscriptTurn } from "../../features/agents/activity-transcript"; -import { focusHistory, type ReaderState, transition } from "./tabs"; - -type Event = Parameters[1]; -type Active = Pick, "phase" | "id">; - -const initial: ReaderState = { refresh: 0 }; -const input = "session"; -const read = Symbol("read"); -const poll = Symbol("poll"); -const next = Symbol("next"); - -function turn(turnId: string, startedAt: number) { - return { - turnId, - startedAt, - channelId: null, - threadRootId: null, - triggeringEventIds: [], - newSession: false, - config: [], - partial: false, - items: [], - } satisfies TranscriptTurn; -} - -const earlier = turn("earlier", 1); -const latest = turn("latest", 2); -const tied = turn("tied", 2); -const finished = { ...latest, endedAt: 3 }; -const complete = { turns: [earlier, latest], more: false }; -const preview = { turns: [latest], more: true }; -const tail = [finished]; - -function begin( - id: symbol, - working: boolean, - attempt = 0, - held?: readonly TranscriptTurn[], - session = input, -) { - return { - type: "begin", - id, - input: session, - again: `${session}/${attempt}`, - attempt, - working, - ...(held && { held }), - } satisfies Event; -} - -function drive(state: ReaderState, ...events: Event[]) { - let result: ReturnType = { state }; - for (const event of events) result = transition(result.state, event); - return result; -} - -const phase = (state: ReaderState) => state.active?.phase; -const refresh = { type: "refresh", input } satisfies Event; -const abortPoll = { type: "abort", id: poll } as const; - -function fullSeed(result?: typeof complete & { incomplete?: string }) { - return drive( - initial, - begin(read, false), - { type: "preview", id: read }, - { type: "full", id: read, ...(result && { result }) }, - ).state; -} - -const seeds = { - complete: fullSeed(complete), - partial: drive(initial, begin(read, false), { - type: "preview", - id: read, - result: preview, - }).state, - incomplete: fullSeed({ ...complete, incomplete: "session unavailable" }), - absent: initial, -}; -const live = drive(seeds.complete, begin(read, true), { - type: "tail", - id: read, - turns: tail, -}).state; -const startPoll = begin(poll, true, 0, [earlier, finished]); - -it("expands a settled preview on manual Refresh and resumes with a working tail", () => { - const pending = drive(seeds.partial, refresh, begin(read, false)).state; - expect(phase(pending)).toBe("full"); - const { state } = drive(pending, { - type: "full", - id: read, - result: complete, - }); - expect(state.settled?.result).toEqual(complete); - expect(state.full?.loaded).toBe(true); - expect(phase(drive(state, begin(next, true)).state)).toBe("tail"); -}); - -it("keeps manual Refresh queued during the first preview", () => { - const pending = drive(initial, begin(read, false), refresh).state; - expect(phase(pending)).toBe("preview"); - const { state } = drive(pending, { - type: "preview", - id: read, - result: preview, - }); - expect(state.settled).toMatchObject({ - refresh: 0, - result: { partial: true }, - }); - expect(phase(drive(state, begin(next, false)).state)).toBe("full"); -}); - -it("preserves confirmed loaded history when manual Refresh is requested", () => { - const requested = drive(seeds.complete, refresh).state; - const nextFocus = opening(); - const idle = focusHistory(undefined, input, undefined); - expect(focusHistory(idle, input, nextFocus, requested.full)).toBe(idle); - expect(phase(drive(requested, begin(read, true)).state)).toBe("full"); -}); - -it("keeps manual Refresh scoped to the input it was requested for", () => { - const other = "replacement"; - const replacement = begin(next, false, 0, undefined, other); - const opened = drive(seeds.partial, refresh, replacement).state; - expect(phase(opened)).toBe("preview"); - - const refreshed = drive( - opened, - { type: "preview", id: next, result: preview }, - { type: "refresh", input: other }, - begin(read, false, 0, undefined, other), - ).state; - expect(phase(refreshed)).toBe("full"); -}); - -it("retries full history on the next working change after a failed manual Refresh", () => { - const pending = drive(seeds.partial, refresh, begin(read, true)).state; - expect(phase(pending)).toBe("full"); - const failed = drive(pending, { type: "full", id: read, failed: true }).state; - expect(failed.active).toBeUndefined(); - expect(failed.settled).toBeUndefined(); - expect(phase(drive(failed, begin(next, false)).state)).toBe("full"); -}); - -it.each([ - { request: "manual Refresh", events: [refresh], command: "full" }, - { request: "automatic read", events: [], command: "preview" }, -] as const)( - "retries $command when work stops during a $request", - ({ events, command }) => { - const pending = drive(seeds.partial, ...events, begin(read, true)).state; - expect(phase(pending)).toBe(command); - const stopped = drive(pending, { type: "abort", id: read }).state; - const stale = transition(stopped, { - type: command, - id: read, - result: command === "full" ? complete : preview, - }); - expect(stale.ignored).toBe(true); - expect(stale.state.settled).toBeUndefined(); - expect(phase(drive(stale.state, begin(next, false)).state)).toBe(command); - }, -); - -it.each([ - ["complete", "tail"], - ["partial", "preview"], - ["incomplete", "full"], - ["absent", "preview"], -] as const)( - "handles a working change with %s history by reading %s", - (seed, command) => { - expect(phase(drive(seeds[seed], begin(next, true)).state)).toBe(command); - }, -); - -it.each([ - ["reordered same-time rows", [earlier, tied, latest]], - [ - "a row dated before the retained prefix", - [{ ...latest, startedAt: 0 }, tied], - ], - ["an unrelated window", [turn("unrelated", 4)]], - ["an empty window", []], -] as const)("reads full history when the working tail has %s", (_, turns) => { - const seed = fullSeed({ ...complete, turns: [earlier, latest, tied] }); - const { state } = drive(seed, begin(next, true), { - type: "tail", - id: next, - turns, - }); - expect(phase(state)).toBe("full"); -}); - -it("carries rows accepted by a poll into the next working-edge tail", () => { - const appended = turn("appended", 4); - const turns = [finished, appended]; - const accepted = drive( - seeds.complete, - begin(poll, false, 0, complete.turns), - { type: "poll", id: poll, turns }, - ); - expect(accepted.turns).toEqual(turns); - const { state } = drive(accepted.state, begin(next, true), { - type: "tail", - id: next, - turns: [appended], - }); - expect(state.settled?.result.turns).toEqual([earlier, finished, appended]); -}); - -it("keeps the baseline after an aborted poll and ignores its late result", () => { - const polled = [finished, turn("unpublished turn", 4)]; - const observed = drive(live, startPoll, { - type: "poll", - id: poll, - turns: polled, - overlap: "observe", - }); - expect(observed.turns).toEqual(polled); - expect(observed.state.settled).toBe(live.settled); - const stopped = drive(observed.state, abortPoll).state; - expect(stopped.active).toBeUndefined(); - const late = transition(stopped, { - type: "poll", - id: poll, - turns: observed.turns, - overlap: "observed", - }); - expect(late.ignored).toBe(true); - expect(late.turns).toBeUndefined(); - expect(phase(drive(late.state, begin(next, false)).state)).toBe("tail"); -}); - -it("keeps a queued Refresh when work stops during a poll", () => { - const { state } = drive( - live, - startPoll, - refresh, - abortPoll, - begin(next, false), - ); - expect(phase(state)).toBe("full"); -}); - -it("does not preview again after a full read finds no transcript", () => { - const missing = fullSeed(); - expect(phase(drive(missing, begin(next, false)).state)).toBe("full"); - const idle = focusHistory(undefined, input, undefined); - expect(focusHistory(idle, input, opening(), missing.full).attempt).toBe(1); -}); - -it("keeps the full-read requirement if an invalid poll is followed by an abort", () => { - const observing = drive(seeds.partial, begin(poll, false, 0, preview.turns)); - const observation = { - type: "poll", - id: poll, - turns: [turn("unrelated", 4)], - overlap: "observe", - } satisfies Event; - const observed = transition(observing.state, observation); - expect(observed.turns).toBeUndefined(); - expect(observed.state.active?.phase).toBe("poll"); - expect(observed.state.settled).toBe(seeds.partial.settled); - - const stopped = drive(observed.state, abortPoll).state; - const late = transition(stopped, { - type: "poll", - id: poll, - turns: observed.turns, - overlap: "observed", - }); - expect(late.ignored).toBe(true); - expect(late.state.settled).toBe(seeds.partial.settled); - expect(phase(drive(late.state, begin(next, true)).state)).toBe("full"); - - const earlyStop = drive(observing.state, abortPoll).state; - const unobserved = transition(earlyStop, observation); - expect(unobserved.ignored).toBe(true); - expect(phase(drive(unobserved.state, begin(next, true)).state)).toBe( - "preview", - ); -}); - -it.each([ - { - scenario: "a successful tail", - responses: [{ type: "tail", id: read, turns: tail }], - }, - { - scenario: "a full fallback after a failed tail", - responses: [ - { type: "tail", id: read, failed: true }, - { type: "full", id: read, result: complete }, - ], - }, -] as const)("keeps a Refresh queued during $scenario", ({ responses }) => { - const { state } = drive( - seeds.complete, - begin(read, true), - refresh, - ...responses, - ); - expect(state.settled?.refresh).toBe(0); - expect(phase(drive(state, begin(next, false)).state)).toBe("full"); -}); - -const opening = () => ({ events: ["event"], inputs: 1, done() {} }); - -it("starts focused with a full read and retries once per new focus after a failure", () => { - const focus = opening(); - const first = focusHistory(undefined, input, focus); - const reading = transition(initial, begin(read, false, first.attempt)); - expect(phase(reading.state)).toBe("full"); - const failed = transition(reading.state, { - type: "full", - id: read, - failed: true, - }); - expect(failed.state.active).toBeUndefined(); - expect(focusHistory(first, input, focus, failed.state.full)).toBe(first); - expect(focusHistory(first, input, opening(), failed.state.full).attempt).toBe( - 2, - ); -}); - -it("keeps Load earlier in flight on the same focus and reuses loaded history on a new focus", () => { - const focus = opening(); - const loading = { ...focusHistory(undefined, input, focus), loading: true }; - expect(focusHistory(loading, input, focus)).toBe(loading); - expect(focusHistory(loading, input, opening())).toMatchObject({ - attempt: loading.attempt + 1, - loading: true, - }); - expect(focusHistory(loading, input, opening(), seeds.complete.full)).toBe( - loading, - ); -}); - -function success({ phase, id }: Active) { - return ( - phase === "tail" || phase === "poll" - ? { type: phase, id, turns: tail } - : { type: phase, id, result: phase === "preview" ? preview : complete } - ) satisfies Event; -} - -function alphabet( - state: ReaderState, - previous: Active | undefined, - depth: number, -) { - const current = state.active; - return [ - refresh, - begin(Symbol(), false), - begin(Symbol(), true), - begin(Symbol(), true, 0, state.settled?.result.turns ?? preview.turns), - current && { type: "abort", id: current.id }, - current && success(current), - previous && success(previous), - previous && { type: "abort", id: previous.id }, - current && { - type: current.phase, - id: current.id, - ...(depth % 2 === 0 && { failed: true as const }), - }, - ] satisfies (Event | undefined)[]; -} - -function verify( - before: ReaderState, - event: Event, - result: ReturnType, - refresh: number, - entryRefresh: number, - record: (witness: string) => void, - path: string, -) { - const { active, settled, full } = result.state; - strictEqual(result.state.refresh, refresh, path); - - if (event.type === "refresh") { - strictEqual(active, before.active, path); - strictEqual(settled, before.settled, path); - strictEqual(full?.input, event.input, path); - const alreadyLoaded = - before.full?.input === event.input && before.full.loaded; - strictEqual(full?.loaded, alreadyLoaded, path); - if (active) record("Refresh while a read is active"); - return; - } - if (event.type === "begin") { - strictEqual(active?.id, event.id, path); - strictEqual(full, before.full, path); - const prior = before.settled; - if (event.held) { - strictEqual(active?.phase, "poll", path); - strictEqual(settled, prior, path); - } else { - const usable = - prior && - prior.again === event.again && - prior.working !== event.working && - !prior.result.partial && - !prior.result.incomplete; - const eligible = !!usable && prior.refresh === refresh; - const command = eligible - ? "tail" - : event.attempt || full?.input === event.input - ? "full" - : "preview"; - strictEqual(active?.phase, command, path); - strictEqual(settled, undefined, path); - if (eligible) record("working tail"); - if (usable && !eligible) record("Refresh bypasses a working tail"); - } - return; - } - const stale = event.id !== before.active?.id; - if (stale || event.type === "abort") { - strictEqual(result.ignored, stale ? true : undefined, path); - strictEqual(result.turns, undefined, path); - strictEqual(settled, before.settled, path); - strictEqual(full, before.full, path); - strictEqual(active, stale ? before.active : undefined, path); - if (stale && active) record(`stale ${event.type}`); - if (!stale && before.active?.phase === "poll" && settled) - record("abort with poll baseline"); - return; - } - - const hasValue = - "turns" in event - ? !!event.turns?.length - : "result" in event && !!event.result; - if (event.type === "full" && !event.failed) { - strictEqual(full?.input, before.active?.input, path); - strictEqual(full?.loaded, hasValue, path); - } else if (event.type === "full" || event.type === "preview") { - strictEqual(full, before.full, path); - } - if (event.failed) record(`failed ${event.type}`); - else if (!hasValue) record(`missing ${event.type}`); - if (event.type === "poll") { - strictEqual(active, undefined, path); - const expected = hasValue ? before.settled?.refresh : undefined; - strictEqual(settled?.refresh, expected, path); - return; - } - - const fallback = - !hasValue && - (event.type === "tail" || (event.type === "preview" && !event.failed)); - strictEqual(active?.id, fallback ? event.id : undefined, path); - strictEqual(active?.phase, fallback ? "full" : undefined, path); - strictEqual(settled?.refresh, hasValue ? entryRefresh : undefined, path); - if (hasValue && entryRefresh < refresh) record("settles with Refresh queued"); -} - -it.each(Object.entries(seeds))( - "checks all five-event sequences from %s history", - (seed, initialState) => { - const witnesses = new Map(); - const record = (name: string) => - witnesses.set(name, (witnesses.get(name) ?? 0) + 1); - const path: string[] = []; - let leaves = 0; - - function visit( - state: ReaderState, - refresh: number, - entryRefresh: number, - previous?: Active, - ) { - if (path.length === 5) { - leaves++; - return; - } - for (const [index, event] of alphabet( - state, - previous, - path.length, - ).entries()) { - path.push( - event ? `${index + 1} ${event.type}` : `${index + 1} skipped`, - ); - if (event) { - const refreshed = refresh + Number(event.type === "refresh"); - const entered = event.type === "begin" ? refresh : entryRefresh; - const result = transition(state, event); - verify( - state, - event, - result, - refreshed, - entered, - record, - path.join(" → "), - ); - const retired = - state.active && result.state.active?.id !== state.active.id; - visit( - result.state, - refreshed, - entered, - retired ? state.active : previous, - ); - } else { - visit(state, refresh, entryRefresh, previous); - } - path.pop(); - } - } - - visit(initialState, 0, 0); - expect(leaves).toBe(59_049); - const first = - seed === "complete" || seed === "incomplete" ? "full" : "preview"; - for (const witness of [ - "Refresh while a read is active", - "working tail", - "Refresh bypasses a working tail", - "abort with poll baseline", - "stale abort", - `stale ${first}`, - "settles with Refresh queued", - "failed poll", - "missing poll", - `failed ${first}`, - `missing ${first}`, - ]) { - expect(witnesses.get(witness), witness).toBeGreaterThan(0); - } - }, -); diff --git a/src/features/agents/TranscriptPanel.test.tsx b/src/features/agents/TranscriptPanel.test.tsx index c2cbc61415..e2b8d679a1 100644 --- a/src/features/agents/TranscriptPanel.test.tsx +++ b/src/features/agents/TranscriptPanel.test.tsx @@ -476,7 +476,6 @@ it("reuses accepted transcript turns across a live send at the turn limit", asyn expect(accepted.turns[0]).toBe(turns[1]); expect(accepted.turns.at(-2)).toBe(previousLast); expect(accepted.turns.at(-1)).toBe(sent); - expect(accepted.more).toBe(true); expect(accepted.details).toBe(details); }); @@ -525,7 +524,6 @@ it("reuses accepted transcript turns by unique ID on Refresh while preserving th expect(accepted.turns[3]).toBe(incoming[3]); expect(accepted.turns[4]).toBe(first); expect(accepted.turns[5]).toBe(incoming[5]); - expect(accepted.more).toBe(true); expect(accepted.details).toBe(details); }); @@ -701,12 +699,10 @@ it("swaps the latest turns over the end of the held transcript", () => { }); // It holds at most TURN_LIMIT turns. const full = { - more: false, turns: Array.from({ length: TURN_LIMIT }, (_, i) => turn(String(i))), }; const grown = withLatest(full, [turn(String(TURN_LIMIT - 1)), turn("new")]); expect(grown?.turns).toHaveLength(TURN_LIMIT); - expect(grown?.more).toBe(true); expect(grown?.turns.at(-1)).toEqual(turn("new")); // A turn it doesn't hold can't be placed. expect(withLatest(held, [turn("9")])).toBeUndefined(); diff --git a/src/features/agents/TranscriptPanel.tsx b/src/features/agents/TranscriptPanel.tsx index eaeb78790f..b132aefd42 100644 --- a/src/features/agents/TranscriptPanel.tsx +++ b/src/features/agents/TranscriptPanel.tsx @@ -73,16 +73,12 @@ export function withLatest( const at = ids.get(turns[from]?.turnId ?? "") ?? 0; const kept = turns.slice(from); const sessions = new Set(kept.map((turn) => turn.sessionId)); - if (!held.turns.slice(at).every((turn) => sessions.has(turn.sessionId))) - return undefined; - const merged = [...held.turns.slice(0, at), ...kept]; - return { - ...held, - ...("more" in held && held.more === false && merged.length > TURN_LIMIT - ? { more: true } - : {}), - turns: merged.slice(-TURN_LIMIT), - }; + return held.turns.slice(at).every((turn) => sessions.has(turn.sessionId)) + ? { + ...held, + turns: [...held.turns.slice(0, at), ...kept].slice(-TURN_LIMIT), + } + : undefined; } const dataPrototypes = new Set([Object.prototype, Array.prototype, null]); From 6fe2dc607fea608025aeb5193b9cc35f80ed9c86 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 03:44:13 -0500 Subject: [PATCH 23/37] Render expanded transcript replies directly Co-authored-by: Jello Signed-off-by: LordMelkor --- src/features/agents/ActivityTranscript.tsx | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index d260987789..6e27de4450 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -779,7 +779,7 @@ function Item({ icon={} label={{heading}} > - {body && } + {body && } ); } @@ -810,7 +810,7 @@ function Item({ >
- +
@@ -876,8 +876,6 @@ function Reply({ text }: { text: string }) { ); } -const MemoizedReply = memo(Reply); - /** A file's lines; a final newline does not start another line. */ const lines = (text: string) => text.replace(/\n$/, "").split("\n"); /** One hunk between the unchanged leading and trailing lines. */ From f333a009bee1b61d8ecf4b4f214eba920970e88c Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 03:46:23 -0500 Subject: [PATCH 24/37] Limit Claude preview fallback to missing or disjoint polls Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.tsx | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index bdb71c1457..7dfe520f83 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -1066,19 +1066,7 @@ export function createTabs({ const from = held.findIndex( (turn) => turn.turnId === turns?.[0]?.turnId, ); - if ( - !turns || - from < 0 || - held - .slice(from) - .some((turn, i) => turn.turnId !== turns[i]?.turnId) || - turns.some( - (turn, i) => - turn.startedAt < - ((turns[i - 1] ?? held[from - 1])?.startedAt ?? -Infinity), - ) - ) { - // A stop can cancel this poll before the panel starts its fallback. + if (!turns || from < 0) { requireFullHistory(); return undefined; } From 914edabe820abdfac2e229d4971a243ce398d37a Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 03:51:45 -0500 Subject: [PATCH 25/37] Use the transcript people context value directly Co-authored-by: Jello Signed-off-by: LordMelkor --- src/features/agents/ActivityTranscript.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/features/agents/ActivityTranscript.tsx b/src/features/agents/ActivityTranscript.tsx index 6e27de4450..0b92502f91 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -432,9 +432,8 @@ export function ActivityTranscript({ () => ({ picture: poster ?? picture, focused }), [poster, picture, focused], ); - const value = useMemo(() => ({ profiles, community }), [profiles, community]); return ( - + Date: Sun, 22 Nov 2026 05:26:22 -0500 Subject: [PATCH 26/37] Read recent Claude activity when a loaded turn finishes Keep the complete view while Claude works. At stop, update its final turns from the session tail when their identities and start times match. Read full history after a refresh, a change in the turn window, or an ambiguous boundary. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 189 ++++++++++++++++++++- src/bundled/claude-code/tabs.tsx | 122 ++++++++++--- src/bundled/claude-code/transcript.test.ts | 86 ++++++---- src/bundled/claude-code/transcript.ts | 4 + 4 files changed, 334 insertions(+), 67 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index a729909005..c59dde48e1 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -508,6 +508,13 @@ const sessionPrompt = (text: string, event = text) => content: `\n${JSON.stringify({ id: event, content: text })}\n`, }, }); +const sessionReply = (text: string) => + JSON.stringify({ + uuid: `reply: ${text.slice(0, 40)}`, + type: "assistant", + timestamp: "2026-10-09T10:01:00Z", + message: { content: [{ type: "text", text }] }, + }); function longTranscript() { localStorage.setItem( @@ -579,21 +586,27 @@ function longTranscript() { } it("keeps an untouched tail on working changes until earlier activity is requested", async () => { - const { Activity, path, gap, startCompaction } = longTranscript(); + const { Activity, path, gap, fileReads, startCompaction } = longTranscript(); render(); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: /^View transcript/ })); const summary = { selector: "summary span" }; await screen.findByText("newest", summary); + const before = fileReads().length; appendFileSync(path, `\n${gap}\n${sessionPrompt("while working")}`); const finish = startCompaction(); - await screen.findByText("while working", summary); - expect(screen.queryByText("earlier", summary)).toBeNull(); - appendFileSync(path, `\n${sessionPrompt("after working")}`); - await act(finish); + try { + await screen.findByText("while working", summary); + expect(screen.queryByText("earlier", summary)).toBeNull(); + expect(fileReads().slice(before)).toEqual(["read-page"]); + appendFileSync(path, `\n${sessionPrompt("after working")}`); + } finally { + await act(finish); + } await screen.findByText("after working", summary); expect(screen.queryByText("earlier", summary)).toBeNull(); expect(screen.getByText("Earlier activity is not loaded.")).toBeVisible(); + expect(fileReads().slice(before)).toEqual(["read-page", "read-page"]); const load = screen.getByRole("button", { name: /load earlier activity/i }); chmodSync(path, 0); await user.click(load); @@ -608,7 +621,7 @@ it("keeps an untouched tail on working changes until earlier activity is request }); it("loads the missing history when a working session grows past the held tail", async () => { - const { Activity, path, gap, startCompaction } = longTranscript(); + const { Activity, path, gap, fileReads, startCompaction } = longTranscript(); render(); await userEvent.click( screen.getByRole("button", { name: /^View transcript/ }), @@ -621,6 +634,15 @@ it("loads the missing history when a working session grows past the held tail", await vi.waitFor(() => screen.getByText("while working", { selector: "summary span" }), ); + const before = fileReads().length; + chmodSync(path, 0); + await act(async () => { + await vi.advanceTimersByTimeAsync(LIVE_READ_MS); + }); + await vi.waitFor(() => expect(screen.getByRole("alert")).toBeVisible()); + expect(screen.getByText(partialHistory)).toBeVisible(); + expect(fileReads().slice(before)).not.toContain("read"); + chmodSync(path, 0o600); appendFileSync(path, `\n${gap}\n${sessionPrompt("after the gap")}`); await act(async () => { await vi.advanceTimersByTimeAsync(LIVE_READ_MS); @@ -668,6 +690,141 @@ async function expectFullPreviewHistory(first = "earlier") { expect(screen.queryByText(partialHistory)).toBeNull(); } +function expectTurnStatus(item: HTMLElement, status: string) { + const turn = item.closest("article"); + if (!turn) throw new Error("Missing transcript turn"); + expect(within(turn).getByText(status)).toBeVisible(); +} + +async function openFortyNineTurnTranscript() { + const fixture = await openLongTranscript(); + const { load, path, gap, summary } = fixture; + const older = Array.from({ length: 48 }, (_, i) => + sessionPrompt(`older turn ${i + 1}`), + ); + writeFileSync(path, [...older, gap, sessionPrompt("newest")].join("\n")); + await userEvent.click(load); + expect(await summary("older turn 1")).toBeVisible(); + return fixture; +} + +it("keeps all 50 held turns when stopping with a two-turn tail", async () => { + const { path, startCompaction, fileReads, summary } = + await openFortyNineTurnTranscript(); + const before = fileReads().length; + appendFileSync(path, `\n${sessionPrompt("new request")}`); + const finish = startCompaction(); + try { + expectTurnStatus(await summary("new request"), "Working"); + expect(screen.getAllByRole("article")).toHaveLength(50); + expect(fileReads().slice(before)).toEqual(["read"]); + appendFileSync(path, `\n${sessionReply("final reply")}`); + } finally { + await act(finish); + } + expectTurnStatus(await summary("final reply"), "Completed"); + await expectFullPreviewHistory("older turn 1"); + expect(screen.getAllByRole("article")).toHaveLength(50); + expect(fileReads().slice(before)).toEqual(["read", "read-page"]); +}); + +it("reads canonical history when a 51st turn first appears at stop", async () => { + const { path, startCompaction, fileReads, summary } = + await openFortyNineTurnTranscript(); + const before = fileReads().length; + const latestWindow = "Showing the latest 50 turns."; + appendFileSync(path, `\n${sessionPrompt("working request")}`); + const finish = startCompaction(); + try { + expectTurnStatus(await summary("working request"), "Working"); + expect(screen.getAllByRole("article")).toHaveLength(50); + expect(screen.queryByText(latestWindow)).toBeNull(); + appendFileSync( + path, + `\n${sessionPrompt("request at stop")}\n${sessionReply("reply to the new request")}`, + ); + } finally { + await act(finish); + } + expectTurnStatus(await summary("reply to the new request"), "Completed"); + await expectFullPreviewHistory("older turn 2"); + expect(screen.getByText("working request", transcriptSummary)).toBeVisible(); + expect(screen.getByText("request at stop", transcriptSummary)).toBeVisible(); + expect(screen.queryByText("older turn 1", transcriptSummary)).toBeNull(); + expect(screen.getAllByRole("article")).toHaveLength(50); + expect(screen.getByText(latestWindow)).toBeVisible(); + expect(fileReads().slice(before)).toEqual(["read", "read-page", "read"]); +}); + +it("reads the final reply when an oversized turn stops", async () => { + const { load, path, startCompaction, summary } = await openLongTranscript(); + await userEvent.click(load); + await expectFullPreviewHistory(); + appendFileSync( + path, + `\n${sessionReply(`Long output\n${"x".repeat(3 << 20)}`)}\n${sessionReply("draft reply")}`, + ); + const finish = startCompaction(); + try { + expect(await summary("draft reply")).toBeVisible(); + appendFileSync(path, `\n${sessionReply("final oversized reply")}`); + } finally { + await act(finish); + } + expectTurnStatus(await summary("final oversized reply"), "Completed"); + await expectFullPreviewHistory(); +}); + +it("reads corrected earlier history when work stops with Refresh queued behind a poll", async () => { + const { + load, + path, + gap, + startCompaction, + fileReads, + holdNextFileProcess, + summary, + } = await openLongTranscript(); + await userEvent.click(load); + await expectFullPreviewHistory(); + const before = fileReads().length; + appendFileSync(path, `\n${sessionPrompt("working request")}`); + const poll = holdNextFileProcess("read-page"); + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + const finish = startCompaction(); + try { + await vi.waitFor(() => + screen.getByText("working request", transcriptSummary), + ); + await act(async () => { + await vi.advanceTimersByTimeAsync(LIVE_READ_MS); + }); + await poll.started; + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + writeFileSync( + path, + [ + sessionPrompt("corrected earlier", earlierEvent), + gap, + sessionPrompt("newest"), + sessionPrompt("working request"), + sessionReply("reply at stop"), + ].join("\n"), + ); + } finally { + vi.useRealTimers(); + try { + await act(finish); + } finally { + await act(async () => poll.release()); + } + } + expect(await summary("reply at stop")).toBeVisible(); + await expectFullPreviewHistory("corrected earlier"); + expect(screen.queryByText("earlier", transcriptSummary)).toBeNull(); + expect(fileReads().slice(before)).toEqual(["read", "read-page", "read"]); +}); + it.each(["Refresh transcript", "Load earlier activity"])( "keeps the preview visible while %s loads full history", async (action) => { @@ -852,7 +1009,8 @@ it("retries each focused opening once after Load earlier fails", async () => { }); it("retries a missing transcript on focus and reuses successfully loaded history", async () => { - const { Activity, path, fileReads } = longTranscript(); + const { Activity, path, fileReads, startCompaction, holdNextFileProcess } = + longTranscript(); const focus = { events: [earlierEvent], inputs: readerInputs(), @@ -870,8 +1028,23 @@ it("retries a missing transcript on focus and reuses successfully loaded history const load = await screen.findByRole("button", { name: /load earlier activity/i, }); - rmSync(path); await userEvent.click(load); + await expectFullPreviewHistory(); + appendFileSync(path, `\n${sessionPrompt("working request")}`); + const finish = startCompaction(); + expectTurnStatus( + await screen.findByText("working request", transcriptSummary), + "Working", + ); + appendFileSync(path, `\n${sessionPrompt("new turn at stop")}`); + const tail = holdNextFileProcess("read-page"); + await act(finish); + try { + await tail.started; + rmSync(path); + } finally { + await act(async () => tail.release()); + } await screen.findByText(/no transcript for this conversation/); writeFileSync(path, sessionPrompt("restored", earlierEvent)); Element.prototype.scrollIntoView = () => {}; diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 7dfe520f83..aa8eb6bd49 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -23,8 +23,11 @@ import { } from "react"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; -import type { ClaudeTranscript } from "./transcript"; -import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; +import { type ClaudeTranscript, TURN_LIMIT } from "./transcript"; +import { + TranscriptPanel, + withLatest, +} from "../../features/agents/TranscriptPanel"; import { AgentInstructions } from "../../features/agents/AgentInstructions"; import { CreateModelChoices } from "../../features/agents/CreateModelChoices"; import { Dialog } from "../../shared/design-system/ui/Dialog"; @@ -997,7 +1000,11 @@ export function createTabs({ working: boolean; }) { const workspace = readConfig(agent.config).workspace; - const input = JSON.stringify([workspace, conversation.sessionId]); + const input = JSON.stringify([ + agent.key, + workspace, + conversation.sessionId, + ]); const focus = useContext(TranscriptFocus); const [history, setHistory] = useState({ input, @@ -1005,7 +1012,12 @@ export function createTabs({ attempt: focus ? 1 : 0, loading: false, }); - const fullHistory = useRef<{ input: string; loaded: boolean }>(undefined); + const again = JSON.stringify([input, history.attempt]); + const fullHistory = useRef<{ + input: string; + loaded: boolean; + live?: { again: string; result: ClaudeTranscript } | undefined; + }>(undefined); if (history.input !== input) { setHistory({ input, focus, attempt: focus ? 1 : 0, loading: false }); } else if ( @@ -1026,16 +1038,81 @@ export function createTabs({ }, ); const requireFullHistory = () => { - if (fullHistory.current?.input !== input) - fullHistory.current = { input, loaded: false }; + const prior = fullHistory.current; + fullHistory.current = { + input, + loaded: prior?.input === input && prior.loaded, + }; }; + async function latest( + signal: AbortSignal, + held: ClaudeTranscript["turns"], + ) { + const intent = fullHistory.current; + let turns: ClaudeTranscript["turns"] | undefined; + try { + turns = await runtime.latestTurns( + conversation, + workspace, + working, + signal, + held, + ); + } catch (error) { + if (!signal.aborted && intent) intent.live = undefined; + throw error; + } + signal.throwIfAborted(); + if (turns && !turns.length) return turns; + const from = held.findIndex((turn) => turn.turnId === turns?.[0]?.turnId); + if ( + !turns || + from < 0 || + (intent?.loaded && from + turns.length > TURN_LIMIT) || + (!working && from + turns.length !== held.length) || + held + .slice(from) + .some( + (turn, i) => + turn.turnId !== turns[i]?.turnId || + turn.startedAt !== turns[i]?.startedAt, + ) || + turns.some( + (turn, i) => + turn.startedAt < + ((turns[i - 1] ?? held[from - 1])?.startedAt ?? -Infinity), + ) + ) { + if (fullHistory.current?.input !== input) requireFullHistory(); + if (intent) intent.live = undefined; + return undefined; + } + if (intent?.live) { + const result = withLatest(intent.live.result, turns); + intent.live = result ? { again, result } : undefined; + } + return turns; + } return ( agent={agent} onRefreshRequested={requireFullHistory} read={async (signal) => { const args = [conversation, workspace, working, signal] as const; + const intent = fullHistory.current; + const prior = intent?.live; + if (intent) intent.live = undefined; try { + if (!working && prior?.again === again) { + const turns = await latest(signal, prior.result.turns).catch( + () => undefined, + ); + signal.throwIfAborted(); + if (turns?.at(-1)?.endedAt !== undefined) { + const result = withLatest(prior.result, turns); + if (result) return result; + } + } if (!history.attempt && fullHistory.current?.input !== input) { const preview = await runtime.transcriptPreview(...args); signal.throwIfAborted(); @@ -1043,7 +1120,16 @@ export function createTabs({ } const result = await runtime.transcript(...args); signal.throwIfAborted(); - fullHistory.current = { input, loaded: Boolean(result) }; + if (fullHistory.current === intent) { + fullHistory.current = { + input, + loaded: Boolean(result), + live: + working && result && !result.incomplete + ? { again, result } + : undefined, + }; + } return result; } finally { if (history.loading && !signal.aborted) { @@ -1053,27 +1139,9 @@ export function createTabs({ } } }} - readLatest={async (signal, held) => { - const turns = await runtime.latestTurns( - conversation, - workspace, - working, - signal, - held, - ); - signal.throwIfAborted(); - if (turns && !turns.length) return turns; - const from = held.findIndex( - (turn) => turn.turnId === turns?.[0]?.turnId, - ); - if (!turns || from < 0) { - requireFullHistory(); - return undefined; - } - return turns; - }} + readLatest={latest} readKey={`${conversation.key}\u0000${workspace}`} - readAgain={JSON.stringify([input, history.attempt])} + readAgain={again} working={working} reading="Reading the Claude session…" failed="Could not read the Claude session" diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 65b1de4cdb..0f66a82b7b 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -600,7 +600,7 @@ it.each(["queued steer", "user steer"] as const)( ); it.each(["discarded", "retained"] as const)( - "handles an orphan result in the %s turn without inventing a tool", + "handles a clipped tool result in the %s turn on preview, poll and stop", async (location) => { const clippedResult = [ { type: "tool_result", tool_use_id: "earlier-tool", content: "result" }, @@ -627,17 +627,25 @@ it.each(["discarded", "retained"] as const)( false, signal, ); - if (location === "retained") expect(preview).toBeUndefined(); - else - expect(preview?.turns).toMatchObject([ - { - partial: false, - items: [ - { type: "prompt", text: "visible complete prompt" }, - { type: "message", text: "visible reply" }, - ], - }, - ]); + const visibleTurns = [ + { + partial: false, + items: [ + { type: "prompt", text: "visible complete prompt" }, + { type: "message", text: "visible reply" }, + ], + }, + ]; + const latest = (working: boolean) => + runtime.latestTurns(conversation, "~/.buzz", working, signal, []); + await expect(latest(true)).resolves.toMatchObject(visibleTurns); + if (location === "retained") { + expect(preview).toBeUndefined(); + await expect(latest(false)).resolves.toBeUndefined(); + } else { + expect(preview?.turns).toMatchObject(visibleTurns); + await expect(latest(false)).resolves.toMatchObject(visibleTurns); + } }, ); @@ -1348,30 +1356,44 @@ it("requests a full read when a clipped turn contains a delivered steer", async it("reads a turn larger than the chunk in full only every 30 s, keeping what is shown between", async () => { clock = 0; - const { spawn } = host({ - "./-Users-me--buzz/session-1.jsonl": [ - line("user", prompt("only")), - line("assistant", [{ type: "text", text: "x".repeat(3 << 20) }]), - line("assistant", [{ type: "text", text: "done" }]), - ].join("\n"), - }); - const now = vi.spyOn(Date, "now").mockReturnValue(1_000_000); - const latest = () => - readLatestTurns( + const files = { [savedPath]: line("user", prompt("only")) }; + const { spawn, home } = host(files); + const signal = new AbortController().signal; + const append = (content: string) => { + files[savedPath] += + `\n${line("assistant", [{ type: "text", text: content }])}`; + writeFileSync(join(home, ".claude/projects", savedPath), files[savedPath]); + }; + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(1_000_000); + const latest = (working = true) => + readLatestTurns(spawn, "~/.buzz", conversation, working, signal); + try { + expect((await latest())?.[0]?.turnId).toBe("u1"); + append("x".repeat(3 << 20)); + await expect(latest()).resolves.toBeUndefined(); + vi.setSystemTime(1_000_000 + OVERSIZED_READ_MS - 1); + await expect(latest()).resolves.toEqual([]); + vi.setSystemTime(1_000_000 + OVERSIZED_READ_MS); + await expect(latest()).resolves.toBeUndefined(); + await expect(latest()).resolves.toEqual([]); + append("final reply"); + await expect(latest(false)).resolves.toBeUndefined(); + const stopped = await readTranscript( spawn, "~/.buzz", conversation, - true, - new AbortController().signal, + false, + signal, ); - // Undefined reads it in full; none keeps what is shown. - await expect(latest()).resolves.toBeUndefined(); - now.mockReturnValue(1_000_000 + OVERSIZED_READ_MS - 1); - await expect(latest()).resolves.toEqual([]); - now.mockReturnValue(1_000_000 + OVERSIZED_READ_MS); - await expect(latest()).resolves.toBeUndefined(); - await expect(latest()).resolves.toEqual([]); - now.mockRestore(); + expect(stopped?.turns).toHaveLength(1); + expect(stopped?.turns[0]?.endedAt).toBe(3000); + expect(stopped?.turns[0]?.items.at(-1)).toMatchObject({ + text: "final reply", + }); + } finally { + vi.useRealTimers(); + } }); it("shows a session's prompt once over the latest turns it swaps in", async () => { diff --git a/src/bundled/claude-code/transcript.ts b/src/bundled/claude-code/transcript.ts index 4dd451d071..8427eac57f 100644 --- a/src/bundled/claude-code/transcript.ts +++ b/src/bundled/claude-code/transcript.ts @@ -506,12 +506,14 @@ export async function readLatestTurns( const size = await sizeOf(spawn, path, signal); const { from, text } = await readTail(spawn, path, signal, size); const tooLarge = () => { + if (!working) return undefined; const last = oversized.get(path); if (last !== undefined && Date.now() - last < OVERSIZED_READ_MS) return []; oversized.set(path, Date.now()); return undefined; }; if (text === undefined) return tooLarge(); + const boundary = from && !working ? { uncertain: false } : undefined; const turns = claudeTurns( text, { @@ -521,7 +523,9 @@ export async function readLatestTurns( }, working, nameOf, + boundary, ); + if (boundary?.uncertain) return undefined; const first = turns[0]; const whole = turns.filter((turn) => !turn.partial); if ( From 9e24fb6b6f8f5f2be8cd0b3db24e0f81b64e43c6 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 06:25:50 -0500 Subject: [PATCH 27/37] Guard the working transcript status row against horizontal overflow Co-authored-by: Jello Signed-off-by: LordMelkor --- tests/browser/markdown-documents.fixture.tsx | 32 +++++++++++++++----- tests/browser/markdown-documents.spec.mjs | 18 +++++++++++ 2 files changed, 43 insertions(+), 7 deletions(-) diff --git a/tests/browser/markdown-documents.fixture.tsx b/tests/browser/markdown-documents.fixture.tsx index a2aac081c8..effcc8cd7d 100644 --- a/tests/browser/markdown-documents.fixture.tsx +++ b/tests/browser/markdown-documents.fixture.tsx @@ -17,6 +17,7 @@ import { Body as RepoBody } from "../../src/bundled/repos/RepoPage"; import { InstructionsMarkdown } from "../../src/bundled/watching/InstructionsMarkdown"; import "../../src/bundled/watching/AttentionPage.css"; import { ActivityTranscript } from "../../src/features/agents/ActivityTranscript"; +import { TranscriptPanel } from "../../src/features/agents/TranscriptPanel"; import { activityTranscript } from "../../src/features/agents/activity-transcript"; import { createAgentMemories } from "../../src/features/agents/memory"; import { MemoryPanel } from "../../src/features/agents/MemoryPanel"; @@ -104,6 +105,7 @@ const reply = (seq: number, text: string, messageId: string) => }, }, }); +const working = params.has("working"); const transcript = activityTranscript( [ { @@ -125,7 +127,9 @@ const transcript = activityTranscript( }, }), reply(3, LONG_CODE, "m2"), - frame(4, "turn_completed", { outcome: "completed" }), + ...(working + ? [] + : [frame(4, "turn_completed", { outcome: "completed" })]), ], }, }), @@ -145,6 +149,7 @@ const memories = createAgentMemories( () => true, ); const memoryAgent = { + key: agent, pubkey: agent, name: "Ada", relay: "wss://current.example", @@ -235,12 +240,25 @@ createRoot(root).render( />
- "ended"} - follow={false} - /> + {working ? ( + transcript} + readKey="S" + working + refreshWhileWorking={false} + reading="Reading transcript…" + failed="Could not read transcript" + missing={null} + /> + ) : ( + "ended"} + follow={false} + /> + )}
diff --git a/tests/browser/markdown-documents.spec.mjs b/tests/browser/markdown-documents.spec.mjs index 8c78db0351..d23bc06ad2 100644 --- a/tests/browser/markdown-documents.spec.mjs +++ b/tests/browser/markdown-documents.spec.mjs @@ -102,6 +102,24 @@ async function expand(page) { while ((await replies.count()) > 0) await replies.first().click(); } +test("the working status row stays inside its transcript turn", async ({ + page, +}) => { + await page.goto(`${url}?working&width=419`); + const status = page.locator( + '[data-screen="transcript"] p[data-status="working"]', + ); + await status.scrollIntoViewIfNeeded(); + await expect(status).toBeInViewport(); + const inset = await status.evaluate((row) => { + const turn = row.closest("article").getBoundingClientRect(); + const box = row.getBoundingClientRect(); + return { left: box.left - turn.left, right: turn.right - box.right }; + }); + expect(inset.left, "left edge").toBeGreaterThanOrEqual(0); + expect(inset.right, "right edge").toBeGreaterThanOrEqual(0); +}); + // Layout and interaction: jsdom resolves neither type roles nor hover. test("document screens keep their roles, elements and code actions in their hosts", async ({ page, From ad0c8341143bfa6b5f84488e9922f633919d2b6b Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 07:21:36 -0500 Subject: [PATCH 28/37] Show the transcript window notice when a live read drops a turn Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/goose/tabs.test.tsx | 41 ++++++++++++++++++++ src/features/agents/TranscriptPanel.test.tsx | 1 + src/features/agents/TranscriptPanel.tsx | 16 +++++--- 3 files changed, 52 insertions(+), 6 deletions(-) diff --git a/src/bundled/goose/tabs.test.tsx b/src/bundled/goose/tabs.test.tsx index 663b04680a..1530adb330 100644 --- a/src/bundled/goose/tabs.test.tsx +++ b/src/bundled/goose/tabs.test.tsx @@ -22,6 +22,7 @@ import { fakeSpawn } from "./goose-testing"; import { type Config, DEFAULT_CONFIG, type GooseRuntime } from "./runtime"; import { GooseSetup } from "./setup"; import { createTabs } from "./tabs"; +import { LIVE_READ_MS } from "../../features/agents/TranscriptPanel"; import { GooseHistory } from "./transcript"; import { localSessions } from "./sessions"; import { @@ -1052,6 +1053,46 @@ it("lists the agent's saved conversations and reads one's transcript by id, with expect(listings(fake)).toEqual([]); }); +it("shows the window notice when a live session grows from 50 to 51 turns", async () => { + const prompt = (n: number) => ({ + role: "user", + created: n, + content: [{ type: "text", text: `Request ${n}` }], + }); + const conversation = Array.from({ length: 50 }, (_, i) => prompt(i + 1)); + const fake = fakeSpawn({ + history: [ + { + sessionId: "s1", + title: "Session", + cwd: "/w", + updatedAt: "", + conversation, + }, + ], + }); + const key = `chan/${ROOT}`; + const notice = "Showing the latest 50 turns."; + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] }); + try { + activity(fake, { + saved: [{ key, at: 1, sessions: ["s1"] }], + live: [{ key, at: 1, busy: true, sessionId: "s1" }], + }); + await act(async () => { + fireEvent.click(screen.getByRole("button", { name: /^View transcript/ })); + }); + expect(screen.getAllByRole("article")).toHaveLength(50); + expect(screen.queryByText(notice)).toBeNull(); + conversation.push(prompt(51)); + await act(async () => vi.advanceTimersByTimeAsync(LIVE_READ_MS)); + expect(screen.getByText(notice)).toBeVisible(); + expect(screen.getAllByRole("article")).toHaveLength(50); + } finally { + vi.useRealTimers(); + } +}); + it("finds a conversation with no saved session by its goose tags", async () => { const fake = gooseHistory(); const done = vi.fn(); diff --git a/src/features/agents/TranscriptPanel.test.tsx b/src/features/agents/TranscriptPanel.test.tsx index e2b8d679a1..0b3a5eb3e7 100644 --- a/src/features/agents/TranscriptPanel.test.tsx +++ b/src/features/agents/TranscriptPanel.test.tsx @@ -473,6 +473,7 @@ it("reuses accepted transcript turns across a live send at the turn limit", asyn ...turns.slice(1).map(({ turnId }) => turnId), "sent", ]); + expect(accepted.more).toBe(true); expect(accepted.turns[0]).toBe(turns[1]); expect(accepted.turns.at(-2)).toBe(previousLast); expect(accepted.turns.at(-1)).toBe(sent); diff --git a/src/features/agents/TranscriptPanel.tsx b/src/features/agents/TranscriptPanel.tsx index b132aefd42..eaeb78790f 100644 --- a/src/features/agents/TranscriptPanel.tsx +++ b/src/features/agents/TranscriptPanel.tsx @@ -73,12 +73,16 @@ export function withLatest( const at = ids.get(turns[from]?.turnId ?? "") ?? 0; const kept = turns.slice(from); const sessions = new Set(kept.map((turn) => turn.sessionId)); - return held.turns.slice(at).every((turn) => sessions.has(turn.sessionId)) - ? { - ...held, - turns: [...held.turns.slice(0, at), ...kept].slice(-TURN_LIMIT), - } - : undefined; + if (!held.turns.slice(at).every((turn) => sessions.has(turn.sessionId))) + return undefined; + const merged = [...held.turns.slice(0, at), ...kept]; + return { + ...held, + ...("more" in held && held.more === false && merged.length > TURN_LIMIT + ? { more: true } + : {}), + turns: merged.slice(-TURN_LIMIT), + }; } const dataPrototypes = new Set([Object.prototype, Array.prototype, null]); From 7fa2a3900dcf18599ad90546ddca17a1e08bb545 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 07:09:44 -0500 Subject: [PATCH 29/37] Open large Codex transcripts on the latest activity Co-authored-by: Jello Signed-off-by: LordMelkor --- docs/buzz-help.md | 3 + src/bundled/codex/tabs.test.tsx | 227 +++++++++++++++++++++++++++++++- src/bundled/codex/tabs.tsx | 139 +++++++++++++++++-- 3 files changed, 358 insertions(+), 11 deletions(-) diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 83d6fc5c0e..e427a05897 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1859,6 +1859,9 @@ If an agent reports incompatible synced settings, choose the **Previous Versions A local Claude transcript can open on its latest activity. Choose **Load earlier activity** to load the available history, up to 50 turns. Find on screen searches the loaded rows. + A large local Codex transcript can open on its newest turn, showing up to 128 + entries from a completed turn. A working turn stays visible in full. Choose + **Load earlier activity** or **Refresh transcript** to see up to 20 turns. Once goose agents run through the agent gateway, a goose turn woken in a conversation by a plugin, watch or timer that ran without the gateway shows "Ran without the agent gateway" beside its prompt only while the app keeps diff --git a/src/bundled/codex/tabs.test.tsx b/src/bundled/codex/tabs.test.tsx index b3c50286cf..e8930643b9 100644 --- a/src/bundled/codex/tabs.test.tsx +++ b/src/bundled/codex/tabs.test.tsx @@ -1,4 +1,5 @@ import type { AgentExecutionBinding } from "../../features/agents/execution"; +import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; import { AgentTabs } from "../agents/AgentTabs"; import type { Agent, @@ -86,6 +87,7 @@ function fixture({ installed = true, saved = {}, turns = () => ({ result: { data: [] } }), + rolloutPath, threads = [], configured = {}, voices = ["cove", "maple"], @@ -114,7 +116,8 @@ function fixture({ requiresOpenaiAuth?: boolean; installed?: boolean; saved?: Record; - turns?: (threadId: string) => Wire; + turns?: (threadId: string) => Wire | Promise; + rolloutPath?: () => string | null; threads?: { id: string; name: string; updatedAt: number }[] | string; configured?: { model?: string; @@ -136,6 +139,15 @@ function fixture({ const logins: ReturnType>[] = []; const spawn = vi.fn(async (id: string, options?: HostProcessOptions) => { const exit = deferred(); + if (id === "read" || id === "read-from" || id === "rollout-stat") { + if (id === "rollout-stat") options?.onStdout?.("0 1:1 1"); + return { + write: async () => {}, + end: async () => {}, + kill: async () => {}, + exited: Promise.resolve(0), + }; + } if (id === "codex" || id === "login") { const args = options?.args?.join(" "); if (id === "login") logins.push(exit); @@ -161,7 +173,9 @@ function fixture({ const wire: Wire = JSON.parse(text); if (wire.id == null) return; if (wire.method === "thread/turns/list") { - const reply = turns((wire.params as { threadId: string }).threadId); + const reply = await turns( + (wire.params as { threadId: string }).threadId, + ); // Kept for `thread/items/list`, which Buzz reads them through. const listed = reply.result as { data?: Record[] }; for (const turn of listed?.data ?? []) @@ -177,6 +191,8 @@ function fixture({ nextCursor: null, }; } + if (wire.method === "thread/read") + result = { thread: { path: rolloutPath?.() ?? null } }; if (wire.method === "config/read") { await configGate; result = { config: configured }; @@ -402,6 +418,213 @@ it("lists saved conversations and shows one's Codex thread, or that Codex no lon expect(save).not.toHaveBeenCalled(); }); +function recordedTurn(id: string, count: number, startedAt = 1, live = false) { + return { + id, + startedAt, + completedAt: live ? null : startedAt + 1, + status: live ? "inProgress" : "completed", + items: Array.from({ length: count }, (_, i) => ({ + type: "agentMessage", + id: `${id}-${i}`, + text: `Message ${id}-${i}`, + })), + }; +} + +const savedKey = JSON.stringify(["channel", "channel"]); +function previewFixture( + turns: (thread: string) => Wire | Promise, + rolloutPath: () => string | null = () => "/sessions/thread.jsonl", +) { + return fixture({ + saved: { [savedKey]: { threadId: "thread", workspace: "/w", at: 1 } }, + turns, + rolloutPath, + }); +} + +const loadedEntries = () => + Array.from( + document.querySelectorAll("[data-transcript] [data-entry^='item:']"), + (row) => row.getAttribute("data-entry"), + ); + +it("expands the clipped session opener without rereading it, and Refresh reads new rows in full", async () => { + let count = 130; + const f = previewFixture(() => ({ + result: { data: [recordedTurn("first", count)] }, + })); + const props = f.props(); + render(); + fireEvent.click( + await screen.findByRole("button", { name: /^View transcript/ }), + ); + const expand = await screen.findByRole("button", { + name: "Load earlier activity", + }); + expect(loadedEntries()).toEqual( + Array.from({ length: 128 }, (_, i) => `item:first-${i + 2}`), + ); + expect( + screen.getByText("The start of this turn isn't loaded."), + ).toBeVisible(); + expect(screen.getByText("Earlier activity is not loaded.")).toBeVisible(); + expect(screen.queryByText("New session")).toBeNull(); + const reads = f.spawn.mock.calls.length; + fireEvent.click(expand); + expect(await screen.findByText("New session")).toBeVisible(); + expect(loadedEntries()).toEqual( + Array.from({ length: 130 }, (_, i) => `item:first-${i}`), + ); + expect(f.spawn.mock.calls).toHaveLength(reads); + count++; + fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); + await screen.findByText("Message first-130", { selector: "summary span" }); + expect(f.spawn.mock.calls.filter(([id]) => id === "app-server")).toHaveLength( + 2, + ); + expect(loadedEntries()).toHaveLength(131); +}); + +it.each(["Load earlier activity", "Refresh transcript", "linked message"])( + "keeps the prior turn and all live rows, and honors %s during a stop read", + async (action) => { + const event = "d".repeat(64); + const history = recordedTurn("previous", 130); + const previous = { + ...history, + items: [ + { + type: "dynamicToolCall", + id: "sent", + namespace: "buzz", + tool: "send", + arguments: { text: "Linked reply" }, + status: "completed", + contentItems: [{ type: "inputText", text: `sent ${event}` }], + success: true, + }, + ...history.items.slice(1), + ], + }; + const live = recordedTurn("live", 135, 3, true); + const stopped = deferred(); + const started = deferred(); + let served: Wire | Promise = { result: { data: [previous] } }; + const f = previewFixture(() => { + if (served === stopped.promise) started.resolve(); + return served; + }); + const sessions = vi.spyOn(f.runtime, "sessions").mockReturnValue([]); + const focus = { events: [event], inputs: 0, done() {} }; + const panel = (opening?: typeof focus) => ( + + + + ); + const mounted = render(panel()); + fireEvent.click( + await screen.findByRole("button", { name: /^View transcript/ }), + ); + await screen.findByRole("button", { name: "Load earlier activity" }); + const prior = loadedEntries(); + served = { result: { data: [live, previous] } }; + sessions.mockReturnValue([ + { key: savedKey, status: "Working", detail: "" }, + ]); + mounted.rerender(panel()); + await screen.findByText("Message live-134", { selector: "summary span" }); + expect(loadedEntries()).toEqual([ + ...prior, + ...live.items.map((item) => `item:${item.id}`), + ]); + served = stopped.promise; + sessions.mockReturnValue([]); + mounted.rerender(panel()); + await started.promise; + const full = { result: { data: [recordedTurn("live", 136, 3), previous] } }; + if (action === "linked message") { + served = full; + const original = Object.getOwnPropertyDescriptor( + Element.prototype, + "scrollIntoView", + ); + Element.prototype.scrollIntoView = () => {}; + try { + mounted.rerender(panel(focus)); + await act(async () => + stopped.resolve({ + error: { code: -32603, message: "Stop read failed" }, + }), + ); + await waitFor(() => + expect( + document.querySelector('[data-entry="item:sent"] [data-arrived]'), + ).toBeVisible(), + ); + expect(screen.queryByRole("alert")).toBeNull(); + } finally { + if (original) + Object.defineProperty(Element.prototype, "scrollIntoView", original); + else Reflect.deleteProperty(Element.prototype, "scrollIntoView"); + } + } else { + fireEvent.click(screen.getByRole("button", { name: action })); + await act(async () => stopped.resolve(full)); + } + await screen.findByText("Message live-135", { selector: "summary span" }); + expect(loadedEntries()).toHaveLength(266); + expect( + screen.queryByRole("button", { name: "Load earlier activity" }), + ).toBeNull(); + expect( + f.spawn.mock.calls.filter(([id]) => id === "app-server"), + ).toHaveLength(action === "Load earlier activity" ? 3 : 4); + }, +); + +it.each(["linked message", "unavailable tools", "working turn"])( + "opens a large transcript for a %s", + async (mode) => { + const old = recordedTurn("old", 1); + const newest = recordedTurn("latest", 130, 3, mode === "working turn"); + const f = previewFixture( + () => ({ result: { data: [newest, old] } }), + () => (mode === "unavailable tools" ? null : "/sessions/thread.jsonl"), + ); + const focus = + mode === "linked message" + ? { events: ["message"], inputs: 0, done() {} } + : undefined; + render( + + + , + ); + fireEvent.click( + await screen.findByRole("button", { name: /^View transcript/ }), + ); + await screen.findByText("Message latest-129", { selector: "summary span" }); + expect(loadedEntries()).toContain("item:latest-0"); + if (mode === "working turn") { + expect(loadedEntries()).not.toContain("item:old-0"); + expect( + screen.getByRole("button", { name: "Load earlier activity" }), + ).toBeVisible(); + } else { + expect(loadedEntries()).toContain("item:old-0"); + expect( + screen.queryByRole("button", { name: "Load earlier activity" }), + ).toBeNull(); + if (mode === "unavailable tools") + expect(loadedEntries()).toContain( + "item:thread:recorded-tools-unavailable", + ); + } + }, +); + it("sets the conversation the profile was opened from apart from recent conversations", async () => { const root = "e".repeat(64); const f = fixture({ diff --git a/src/bundled/codex/tabs.tsx b/src/bundled/codex/tabs.tsx index b1066463fb..983304e49f 100644 --- a/src/bundled/codex/tabs.tsx +++ b/src/bundled/codex/tabs.tsx @@ -23,12 +23,15 @@ import { // The type's tabs: Codex's setup on this computer, and the agent's settings; // and its part of the New agent dialog. import { + useContext, useEffect, + useLayoutEffect, useRef, useId, useState, useSyncExternalStore, } from "react"; +import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; import { AgentInstructions } from "../../features/agents/AgentInstructions"; import { CreateModelChoices } from "../../features/agents/CreateModelChoices"; @@ -85,7 +88,7 @@ import { } from "./rpc"; import type { CodexRuntime, SavedConversation } from "./runtime"; import type { CodexSetup } from "./setup"; -import { readTranscript, TURN_LIMIT } from "./transcript"; +import { type CodexTranscript, readTranscript, TURN_LIMIT } from "./transcript"; import { VoicePreview } from "./VoicePreview"; import { discoverPreviews, @@ -123,6 +126,72 @@ const STORAGE_KEY = "buzz.codex.provider-defaults.v1"; const SIGN_IN_ERROR = "Codex needs you to sign in."; const NOT_INSTALLED = "The Codex integration isn't installed yet."; const CONVERSATION_LIMIT = 30; + +const PREVIEW_ITEMS = 128; +type TranscriptViewState = { + start?: undefined | "full" | { turn: string; item?: string | undefined }; + snapshot?: { transcript: CodexTranscript; working: boolean } | undefined; + reading?: AbortSignal | undefined; +}; + +function previewTranscript( + transcript: CodexTranscript, + view: TranscriptViewState, + working: boolean, +) { + const { turns } = transcript; + const last = turns.at(-1); + if ( + view.start !== "full" && + last && + !turns.some((turn) => + turn.items.some( + (item) => item.id === `${turn.sessionId}:recorded-tools-unavailable`, + ), + ) + ) { + if ( + !view.start && + turns.reduce((n, turn) => n + turn.items.length, 0) > PREVIEW_ITEMS + ) + view.start = { + turn: last.turnId, + item: + !working && + !transcript.working && + last.endedAt !== undefined && + last.items.length > PREVIEW_ITEMS + ? last.items.at(-PREVIEW_ITEMS)?.id + : undefined, + }; + const start = view.start; + const index = turns.findIndex((turn) => turn.turnId === start?.turn); + const first = turns[index]; + if (first && start) { + const offset = + start.item === undefined + ? 0 + : first.items.findIndex((item) => item.id === start.item); + if (offset >= 0 && (index > 0 || offset > 0)) { + const visible = turns.slice(index); + if (offset > 0) + visible[0] = { + ...first, + newSession: false, + continued: false, + config: [], + partial: true, + items: first.items.slice(offset), + }; + view.snapshot = { transcript, working }; + return { ...transcript, partial: true as const, turns: visible }; + } + } + } + view.start = "full"; + return transcript; +} + /** Read-only setup/catalog discovery uses the same declared native transport. */ async function catalog(spawn: Spawn, signal: AbortSignal, host?: PreviewHost) { const rpc = new AppServer(); @@ -1188,10 +1257,41 @@ export function createTabs( conversation: SavedConversation; working: boolean; }) { + const focus = useContext(TranscriptFocus); + const view = useRef({ + start: focus ? "full" : undefined, + }).current; + const [again, setAgain] = useState(0); + useLayoutEffect(() => { + if (view.snapshot?.working !== working) view.snapshot = undefined; + if (focus && view.start !== "full") { + view.start = "full"; + setAgain((n) => n + 1); + } + }, [working, focus, view]); + const loadEarlier = () => { + view.start = "full"; + if (!view.reading || view.reading.aborted) setAgain((n) => n + 1); + }; + const project = + (read: (signal: AbortSignal) => Promise) => + async (signal: AbortSignal) => { + const saved = view.start === "full" ? view.snapshot : undefined; + view.snapshot = undefined; + if (saved) return saved.transcript; + view.reading = signal; + try { + const full = await read(signal); + signal.throwIfAborted(); + return full && previewTranscript(full, view, working); + } finally { + if (view.reading === signal) view.reading = undefined; + } + }; return ( - agent={agent} - read={async (signal) => { + read={project(async (signal) => { if (await binding(agent.key)) throw new Error( "Transcripts are unavailable for remote Codex agents.", @@ -1208,6 +1308,11 @@ export function createTabs( turns: runtime.prompts(agent.key).shown(transcript.turns), } ); + })} + readAgain={String(again)} + onRefreshRequested={() => { + view.snapshot = undefined; + view.start = "full"; }} readKey={conversation.key} working={working} @@ -1220,10 +1325,19 @@ export function createTabs(

} notes={(transcript) => - transcript.more && ( -

- Showing the latest {TURN_LIMIT} turns. -

+ transcript.partial ? ( +
+ Earlier activity is not loaded.{" "} + +
+ ) : ( + transcript.more && ( +

+ Showing the latest {TURN_LIMIT} turns. +

+ ) ) } /> @@ -1307,12 +1421,19 @@ export function createTabs( const recent = conversations .filter((item) => item.key !== here?.key) .slice(0, CONVERSATION_LIMIT); - const { open, show, back } = useOpenTranscript( + const { + open: selected, + show, + back, + } = useOpenTranscript( conversation, label, initialTranscript && { initial: here, searching, ...initialTranscript }, close, ); + const open = + selected && + (conversations.find((row) => row.key === selected.key) ?? selected); const saved = new Set(conversations.map((row) => row.key)); const views = new Map(sessions.map((view) => [view.key, view])); const unbound = sessions.filter((view) => !saved.has(view.key)); @@ -1415,7 +1536,7 @@ export function createTabs( onBack={back} > Date: Sun, 22 Nov 2026 08:02:26 -0500 Subject: [PATCH 30/37] Keep the visible Codex turns when a conversation starts another thread A new binding requests fresh history and drops the saved expansion snapshot. Keep the mounted transcript and its first visible item for the same agent and conversation. Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/codex/tabs.test.tsx | 42 +++++++++++++++++++++++++++++++++ src/bundled/codex/tabs.tsx | 16 +++++++------ 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/src/bundled/codex/tabs.test.tsx b/src/bundled/codex/tabs.test.tsx index e8930643b9..a7c6d75dcb 100644 --- a/src/bundled/codex/tabs.test.tsx +++ b/src/bundled/codex/tabs.test.tsx @@ -487,6 +487,48 @@ it("expands the clipped session opener without rereading it, and Refresh reads n expect(loadedEntries()).toHaveLength(131); }); +it("keeps the first preview row when a send starts a new Codex thread for the same conversation", async () => { + const binding = { threadId: "missing", workspace: "/w" }; + const previous = recordedTurn("previous", 130); + const live = recordedTurn("live", 3, 3, true); + const started = deferred(); + const pending = deferred(); + const tag = sessionTag("a".repeat(64), { channelId: "channel" }); + const f = fixture({ + saved: { [savedKey]: binding }, + threads: [{ id: "archive", name: `Sol · ${tag}`, updatedAt: 1 }], + turns: (thread) => { + if (thread === "new") { + started.resolve(); + return pending.promise; + } + return { result: { data: thread === "archive" ? [previous] : [] } }; + }, + rolloutPath: () => "/sessions/test.jsonl", + }); + const sessions = vi.spyOn(f.runtime, "sessions").mockReturnValue([]); + const mounted = render(); + fireEvent.click( + await screen.findByRole("button", { name: /^View transcript/ }), + ); + await screen.findByRole("button", { name: "Load earlier activity" }); + const prior = loadedEntries(); + expect(prior[0]).toBe("item:previous-2"); + + binding.threadId = "new"; + sessions.mockReturnValue([{ key: savedKey, status: "Working", detail: "" }]); + mounted.rerender(); + await started.promise; + const whileReading = loadedEntries(); + await act(async () => pending.resolve({ result: { data: [live] } })); + await screen.findByText("Message live-2", { selector: "summary span" }); + expect.soft(whileReading).toEqual(prior); + expect(loadedEntries()).toEqual([ + ...prior, + ...live.items.map((item) => `item:${item.id}`), + ]); +}); + it.each(["Load earlier activity", "Refresh transcript", "linked message"])( "keeps the prior turn and all live rows, and honors %s during a stop read", async (action) => { diff --git a/src/bundled/codex/tabs.tsx b/src/bundled/codex/tabs.tsx index 983304e49f..636dba9654 100644 --- a/src/bundled/codex/tabs.tsx +++ b/src/bundled/codex/tabs.tsx @@ -130,7 +130,7 @@ const CONVERSATION_LIMIT = 30; const PREVIEW_ITEMS = 128; type TranscriptViewState = { start?: undefined | "full" | { turn: string; item?: string | undefined }; - snapshot?: { transcript: CodexTranscript; working: boolean } | undefined; + snapshot?: { transcript: CodexTranscript; source: string } | undefined; reading?: AbortSignal | undefined; }; @@ -138,6 +138,7 @@ function previewTranscript( transcript: CodexTranscript, view: TranscriptViewState, working: boolean, + source: string, ) { const { turns } = transcript; const last = turns.at(-1); @@ -183,7 +184,7 @@ function previewTranscript( partial: true, items: first.items.slice(offset), }; - view.snapshot = { transcript, working }; + view.snapshot = { transcript, source }; return { ...transcript, partial: true as const, turns: visible }; } } @@ -1262,13 +1263,14 @@ export function createTabs( start: focus ? "full" : undefined, }).current; const [again, setAgain] = useState(0); + const source = JSON.stringify([conversation.threadId, working]); useLayoutEffect(() => { - if (view.snapshot?.working !== working) view.snapshot = undefined; + if (view.snapshot?.source !== source) view.snapshot = undefined; if (focus && view.start !== "full") { view.start = "full"; setAgain((n) => n + 1); } - }, [working, focus, view]); + }, [source, focus, view]); const loadEarlier = () => { view.start = "full"; if (!view.reading || view.reading.aborted) setAgain((n) => n + 1); @@ -1283,7 +1285,7 @@ export function createTabs( try { const full = await read(signal); signal.throwIfAborted(); - return full && previewTranscript(full, view, working); + return full && previewTranscript(full, view, working, source); } finally { if (view.reading === signal) view.reading = undefined; } @@ -1309,7 +1311,7 @@ export function createTabs( } ); })} - readAgain={String(again)} + readAgain={JSON.stringify([conversation.threadId, again])} onRefreshRequested={() => { view.snapshot = undefined; view.start = "full"; @@ -1536,7 +1538,7 @@ export function createTabs( onBack={back} > Date: Sun, 22 Nov 2026 08:15:21 -0500 Subject: [PATCH 31/37] Read appended records in an oversized working Claude turn Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/runtime.ts | 8 ++ src/bundled/claude-code/tabs.test.tsx | 92 +++++++++++++++++++-- src/bundled/claude-code/tabs.tsx | 19 +++-- src/bundled/claude-code/transcript.test.ts | 64 +++++++++++++++ src/bundled/claude-code/transcript.ts | 96 ++++++++++++++++++++-- 5 files changed, 258 insertions(+), 21 deletions(-) diff --git a/src/bundled/claude-code/runtime.ts b/src/bundled/claude-code/runtime.ts index b93caa084f..ae85cd2b3f 100644 --- a/src/bundled/claude-code/runtime.ts +++ b/src/bundled/claude-code/runtime.ts @@ -136,6 +136,7 @@ import { readTranscriptPreview, withNotices, type ClaudeTranscript, + type WorkingPoll, type Conversation, type SessionsPlace, } from "./transcript"; @@ -843,6 +844,7 @@ export class ClaudeRuntime { workspace: string, working: boolean, signal: AbortSignal, + poll?: WorkingPoll, ) { if (await this.inspect?.(conversation.agent)) // Where the gateway would attribute it, also say that it isn't. @@ -857,6 +859,8 @@ export class ClaudeRuntime { workspace, working, signal, + undefined, + poll, ); } @@ -902,6 +906,7 @@ export class ClaudeRuntime { key = conversation.community ? COMMUNITY_SESSION : conversationKey(conversation.channelId, conversation.root), + poll?: WorkingPoll, ) { const prompts = this.prompts(conversation.agent); return read( @@ -911,6 +916,7 @@ export class ClaudeRuntime { working, signal, (pubkey) => this.reads(conversation.agent)?.name(pubkey), + poll, ).then( (transcript) => transcript && { @@ -944,6 +950,7 @@ export class ClaudeRuntime { working: boolean, signal: AbortSignal, held: readonly TranscriptTurn[], + poll?: WorkingPoll, ) { if (await this.inspect?.(conversation.agent)) return undefined; const read = await readLatestTurns( @@ -959,6 +966,7 @@ export class ClaudeRuntime { working, signal, (pubkey) => this.reads(conversation.agent)?.name(pubkey), + poll, ); if (!read) return undefined; // Turns older than all `held` keeps are left. diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index c59dde48e1..01bc769a6d 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -756,19 +756,95 @@ it("reads canonical history when a 51st turn first appears at stop", async () => expect(fileReads().slice(before)).toEqual(["read", "read-page", "read"]); }); -it("reads the final reply when an oversized turn stops", async () => { - const { load, path, startCompaction, summary } = await openLongTranscript(); +it("updates a tool outside the working tail and resumes polling after a late send result", async () => { + const { load, path, gap, fileReads, startCompaction, summary } = + await openLongTranscript(); await userEvent.click(load); await expectFullPreviewHistory(); - appendFileSync( - path, - `\n${sessionReply(`Long output\n${"x".repeat(3 << 20)}`)}\n${sessionReply("draft reply")}`, - ); + const calls = JSON.stringify({ + uuid: "calls", + type: "assistant", + message: { + content: [ + { + type: "tool_use", + name: "Read", + id: "r", + input: { file_path: "/work/sample.txt" }, + }, + { + type: "tool_use", + name: "mcp__buzz__send", + id: "s", + input: { text: "Sample report" }, + }, + ], + }, + }); + const result = (id: string, content: string, is_error = false) => + JSON.stringify({ + uuid: `result-${id}`, + type: "user", + message: { + content: [{ type: "tool_result", tool_use_id: id, content, is_error }], + }, + }); + appendFileSync(path, `\n${calls}\n${gap}\n${sessionReply("draft reply")}\n`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const poll = async () => + act(async () => { + await vi.advanceTimersByTimeAsync(LIVE_READ_MS); + }); const finish = startCompaction(); try { - expect(await summary("draft reply")).toBeVisible(); - appendFileSync(path, `\n${sessionReply("final oversized reply")}`); + await vi.waitFor(() => + expectTurnStatus( + screen.getByText("draft reply", transcriptSummary), + "Working", + ), + ); + const tool = document.querySelector( + '[data-entry="item:calls:0"] details', + ); + if (!tool) throw new Error("Missing original tool row"); + expect(tool).toHaveAttribute("data-status", "in_progress"); + tool.open = true; + fireEvent(tool, new Event("toggle")); + const before = fileReads().length; + appendFileSync(path, `${result("r", "original output")}\n`); + await poll(); + await vi.waitFor(() => + expect(within(tool).getByText("original output")).toBeVisible(), + ); + expect(tool).toHaveAttribute("data-status", "completed"); + expect(fileReads().slice(before)).not.toContain("read"); + + appendFileSync(path, `${result("s", "channel missing", true)}\n`); + await poll(); + await vi.waitFor(() => + expect( + screen.getByText(/The message above was not posted: channel missing/), + ).toBeVisible(), + ); + expect( + fileReads() + .slice(before) + .filter((id) => id === "read"), + ).toHaveLength(1); + + const afterFallback = fileReads().length; + appendFileSync(path, `${sessionReply("after the late result")}\n`); + await poll(); + await vi.waitFor(() => + expectTurnStatus( + screen.getByText("after the late result", transcriptSummary), + "Working", + ), + ); + expect(fileReads().slice(afterFallback)).not.toContain("read"); + appendFileSync(path, `${sessionReply("final oversized reply")}\n`); } finally { + vi.useRealTimers(); await act(finish); } expectTurnStatus(await summary("final oversized reply"), "Completed"); diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index aa8eb6bd49..3448eefba3 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -23,7 +23,11 @@ import { } from "react"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; -import { type ClaudeTranscript, TURN_LIMIT } from "./transcript"; +import { + type ClaudeTranscript, + type WorkingPoll, + TURN_LIMIT, +} from "./transcript"; import { TranscriptPanel, withLatest, @@ -1016,7 +1020,9 @@ export function createTabs({ const fullHistory = useRef<{ input: string; loaded: boolean; - live?: { again: string; result: ClaudeTranscript } | undefined; + live?: + | { again: string; result: ClaudeTranscript; poll: WorkingPoll } + | undefined; }>(undefined); if (history.input !== input) { setHistory({ input, focus, attempt: focus ? 1 : 0, loading: false }); @@ -1049,6 +1055,7 @@ export function createTabs({ held: ClaudeTranscript["turns"], ) { const intent = fullHistory.current; + const poll = { ...intent?.live?.poll }; let turns: ClaudeTranscript["turns"] | undefined; try { turns = await runtime.latestTurns( @@ -1057,6 +1064,7 @@ export function createTabs({ working, signal, held, + poll, ); } catch (error) { if (!signal.aborted && intent) intent.live = undefined; @@ -1089,7 +1097,7 @@ export function createTabs({ } if (intent?.live) { const result = withLatest(intent.live.result, turns); - intent.live = result ? { again, result } : undefined; + intent.live = result ? { again, result, poll } : undefined; } return turns; } @@ -1118,7 +1126,8 @@ export function createTabs({ signal.throwIfAborted(); if (preview) return { ...preview, partial: true }; } - const result = await runtime.transcript(...args); + const poll: WorkingPoll = {}; + const result = await runtime.transcript(...args, poll); signal.throwIfAborted(); if (fullHistory.current === intent) { fullHistory.current = { @@ -1126,7 +1135,7 @@ export function createTabs({ loaded: Boolean(result), live: working && result && !result.incomplete - ? { again, result } + ? { again, result, poll } : undefined, }; } diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 0f66a82b7b..2baf9c201b 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -1,5 +1,6 @@ import { execFileSync } from "node:child_process"; import { + appendFileSync, chmodSync, mkdirSync, mkdtempSync, @@ -29,6 +30,7 @@ import { readTranscript, TURN_LIMIT, withNotices, + type WorkingPoll, } from "./transcript"; const root = "c".repeat(64); @@ -1354,6 +1356,68 @@ it("requests a full read when a clipped turn contains a delivered steer", async expect(latest?.map(({ turnId }) => turnId)).toEqual(["u5"]); }); +it("keeps an incomplete UTF-8 record across working polls and retries from the accepted byte", async () => { + clock = 0; + const { spawn, home } = host({ + [savedPath]: [ + line("user", prompt("check deployment")), + line("assistant", [ + { type: "tool_use", name: "Read", id: "r", input: { path: "/log" } }, + ]), + JSON.stringify({ type: "progress", text: "x".repeat(3 << 20) }), + "", + ].join("\n"), + }); + const signal = new AbortController().signal; + const accepted: WorkingPoll = {}; + const full = await readTranscript( + spawn, + "~/.buzz", + conversation, + true, + signal, + undefined, + accepted, + ); + const path = join(home, ".claude/projects", savedPath); + const result = Buffer.from( + `${line( + "user", + [{ type: "tool_result", tool_use_id: "r", content: "ready ✓" }], + { timestamp: undefined }, + )}\n`, + ); + const split = result.indexOf("✓") + 1; + const latest = (poll: WorkingPoll) => + readLatestTurns( + spawn, + "~/.buzz", + conversation, + true, + signal, + undefined, + poll, + ); + appendFileSync(path, result.subarray(0, split)); + expect(await latest({ ...accepted })).toEqual([]); + appendFileSync(path, result.subarray(split)); + const staged = { ...accepted }; + const changed = await latest(staged); + expect(changed?.[0]?.items.at(-1)).toMatchObject({ + output: "ready ✓", + status: "completed", + completedAt: 2000, + }); + expect(full?.turns[0]?.items.at(-1)).toMatchObject({ + status: "in_progress", + output: "", + }); + expect(await latest({ ...accepted })).toEqual(changed); + expect(await latest(staged)).toEqual([]); + appendFileSync(path, `${line("user", prompt("next request"))}\n`); + expect(await latest(staged)).toBeUndefined(); +}); + it("reads a turn larger than the chunk in full only every 30 s, keeping what is shown between", async () => { clock = 0; const files = { [savedPath]: line("user", prompt("only")) }; diff --git a/src/bundled/claude-code/transcript.ts b/src/bundled/claude-code/transcript.ts index 8427eac57f..dd1d1fcf6a 100644 --- a/src/bundled/claude-code/transcript.ts +++ b/src/bundled/claude-code/transcript.ts @@ -26,6 +26,11 @@ export type ClaudeTranscript = Transcript & { incomplete?: string; }; +/** The last complete working turn and file boundary from an accepted read. */ +export type WorkingPoll = { + cursor?: { path: string; offset: number; turn: TranscriptTurn; last: number }; +}; + type Json = Record; /** A person's display name, if known. */ type Names = (pubkey: string) => string | undefined; @@ -116,7 +121,8 @@ export function claudeTurns( conversation: Session, working: boolean, name?: Names, - tail?: { uncertain: boolean }, + tail?: { uncertain: boolean; last?: number; opener?: number }, + prior?: TranscriptTurn, ): TranscriptTurn[] { const turns: TranscriptTurn[] = []; const tools = new Map(); @@ -128,7 +134,17 @@ export function claudeTurns( message: { posted?: boolean; messageId?: string }; } >(); - let last = 0; + if (prior) { + const items = prior.items.map((item) => { + if (item.type !== "tool" || item.status !== "in_progress") return item; + const copy = { ...item }; + tools.set(copy.toolCallId, copy); + return copy; + }); + turns.push({ ...prior, items }); + } + let last = tail?.last ?? 0; + let position = 0; const turn = (id: string, at: number, partial: boolean) => { const current = turns.at(-1); if (current) current.endedAt = Math.max(last, current.startedAt); @@ -148,6 +164,8 @@ export function claudeTurns( return next; }; for (const line of file.split("\n")) { + const start = position; + position += line.length + 1; let entry: Json | undefined; try { entry = object(JSON.parse(line)); @@ -180,6 +198,7 @@ export function claudeTurns( const current = item.steer ? turns.at(-1) : undefined; if (tail && (!timestamp || (item.steer && (!current || current.partial)))) tail.uncertain = true; + if (tail && !current) tail.opener = start; (current ?? turn(id, at, false)).items.push(item); last = at; continue; @@ -265,7 +284,8 @@ export function claudeTurns( const current = turns.at(-1); if (current && !working) current.endedAt = Math.max(last, current.startedAt); // A session file holds the whole session, from its start. - if (turns[0] && !turns[0].partial) turns[0].newSession = true; + if (tail) tail.last = last; + if (!prior && turns[0] && !turns[0].partial) turns[0].newSession = true; return turns; } @@ -393,6 +413,7 @@ async function sizeOf(spawn: Spawn, path: string, signal: AbortSignal) { /** MiB read from the end of a session for its latest turns. */ const LATEST_MIB = 2; +const MIB = 1 << 20; /** Each workspace's project, found once for the latest-turn reads. */ const projects = new Map(); @@ -408,8 +429,9 @@ async function readTail( path: string, signal: AbortSignal, size: number, + from = Math.max(0, Math.ceil(size / MIB) - LATEST_MIB), + count = LATEST_MIB, ) { - const from = Math.max(0, Math.ceil(size / (1 << 20)) - LATEST_MIB); const bytes = await readFile( spawn, "~/.claude/projects", @@ -417,12 +439,15 @@ async function readTail( signal, undefined, "read-page", - [String(from), String(LATEST_MIB)], + [String(from), String(count)], ); const start = from ? bytes.indexOf(10) + 1 : 0; return { from, - text: from && !start ? undefined : decode(bytes.subarray(start)), + bytes, + get text() { + return from && !start ? undefined : decode(bytes.subarray(start)); + }, }; } @@ -492,6 +517,7 @@ export async function readLatestTurns( working: boolean, signal: AbortSignal, nameOf?: Names, + poll?: WorkingPoll, ): Promise { // A folder's project is known without a lookup to keep. if (typeof workspace === "string" && !projects.has(workspace)) @@ -504,6 +530,32 @@ export async function readLatestTurns( if (!project || !sessionId) return undefined; const path = `./${project}/${sessionId}.jsonl`; const size = await sizeOf(spawn, path, signal); + const cursor = working && poll?.cursor; + if (cursor) { + if (path !== cursor.path || size < cursor.offset) return undefined; + if (size === cursor.offset) return []; + const page = Math.floor(cursor.offset / MIB); + const count = Math.ceil(size / MIB) - page; + if (count > PAGE_MIB) return undefined; + const { bytes } = await readTail(spawn, path, signal, size, page, count); + const start = cursor.offset - page * MIB; + if (bytes.length < start) return undefined; + const end = bytes.lastIndexOf(10) + 1; + if (end <= start) return []; + const state = { uncertain: false, last: cursor.last }; + const turns = claudeTurns( + decode(bytes.subarray(start, end)), + { ...conversation, sessionId }, + true, + nameOf, + state, + cursor.turn, + ); + const turn = turns[0]; + if (state.uncertain || turns.length !== 1 || !turn) return undefined; + poll.cursor = { path, offset: page * MIB + end, turn, last: state.last }; + return turns; + } const { from, text } = await readTail(spawn, path, signal, size); const tooLarge = () => { if (!working) return undefined; @@ -565,8 +617,9 @@ async function readSession( args, ); try { - const text = decode(await read()); - return { text, cut: false, start: async () => text }; + const bytes = await read(); + const text = decode(bytes); + return { text, end: bytes.length, cut: false, start: async () => text }; } catch (error) { signal.throwIfAborted(); if (!/larger than 50 MB/.test(error instanceof Error ? error.message : "")) @@ -575,6 +628,7 @@ async function readSession( const size = await sizeOf(spawn, path, signal); let page = Math.floor((size - 1) / (PAGE_MIB << 20)); let text = ""; + let end = 0; // A page starts partway through a line, which ends the page before it. let rest = new Uint8Array(); for (let pages = 1; page >= 0; page--, pages++) { @@ -583,6 +637,7 @@ async function readSession( String(page * PAGE_MIB), String(PAGE_MIB), ); + if (pages === 1) end = page * (PAGE_MIB << 20) + chunk.length; const bytes = new Uint8Array(chunk.length + rest.length); bytes.set(chunk); bytes.set(rest, chunk.length); @@ -594,6 +649,7 @@ async function readSession( const cut = page > 0; return { text, + end, cut, start: async () => (cut ? decode(await read("read-page", "0", "4")) : text), }; @@ -647,6 +703,7 @@ export async function readTranscript( working: boolean, signal: AbortSignal, nameOf?: Names, + poll?: WorkingPoll, ): Promise { const project = await workspaceProject(spawn, workspace, signal); if (!project) return undefined; @@ -703,12 +760,35 @@ export async function readTranscript( if (name !== saved && !startedFor(await file.start(), conversation)) continue; found = true; + const state = + working && name === saved && poll && file.text.endsWith("\n") + ? { uncertain: false, last: 0, opener: -1 } + : undefined; const own = claudeTurns( file.text, session, working && name === saved, nameOf, + state, ); + const active = own.at(-1); + if (poll && state && state.opener >= 0 && active && !active.partial) { + const from = Math.ceil(file.end / MIB) - LATEST_MIB; + const room = file.end - from * MIB; + if ( + from > 0 && + (file.text.length - state.opener >= room || + new TextEncoder().encode(file.text.slice(state.opener)).length >= + room) + ) { + poll.cursor = { + path: `./${project}/${name}`, + offset: file.end, + turn: active, + last: state.last, + }; + } + } cut ||= file.cut; if (file.cut) { // Its first kept turn did not start the session, and with none kept From e8184dcde6d6647c58ddf1281933c0aec1f39b5f Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 08:37:33 -0500 Subject: [PATCH 32/37] Clear the oversized read cooldown when a working turn can resume Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/transcript.test.ts | 30 ++++++++++++++++++++++ src/bundled/claude-code/transcript.ts | 1 + 2 files changed, 31 insertions(+) diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 2baf9c201b..216524ae20 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -1418,6 +1418,36 @@ it("keeps an incomplete UTF-8 record across working polls and retries from the a expect(await latest(staged)).toBeUndefined(); }); +it("requests a full read immediately for a second oversized working turn", async () => { + clock = 0; + const session = { ...conversation, sessionId: "consecutive-oversized" }; + const path = "./-Users-me--buzz/consecutive-oversized.jsonl"; + const progress = JSON.stringify({ + type: "progress", + text: "x".repeat(3 << 20), + }); + const oversizedTurn = (text: string) => + `${line("user", prompt(text))}\n${progress}\n`; + const { spawn, home } = host({ [path]: oversizedTurn("first") }); + const signal = new AbortController().signal; + const args = [spawn, "~/.buzz", session, true, signal] as const; + vi.useFakeTimers({ toFake: ["Date"] }); + try { + vi.setSystemTime(1_000_000); + await expect(readLatestTurns(...args)).resolves.toBeUndefined(); + const poll: WorkingPoll = {}; + await readTranscript(...args, undefined, poll); + expect(poll.cursor).toBeDefined(); + vi.setSystemTime(1_001_000); + const file = join(home, ".claude/projects", path); + appendFileSync(file, oversizedTurn("second")); + const next = await readLatestTurns(...args, undefined, {}); + expect(next).toBeUndefined(); + } finally { + vi.useRealTimers(); + } +}); + it("reads a turn larger than the chunk in full only every 30 s, keeping what is shown between", async () => { clock = 0; const files = { [savedPath]: line("user", prompt("only")) }; diff --git a/src/bundled/claude-code/transcript.ts b/src/bundled/claude-code/transcript.ts index dd1d1fcf6a..d17946a7cb 100644 --- a/src/bundled/claude-code/transcript.ts +++ b/src/bundled/claude-code/transcript.ts @@ -787,6 +787,7 @@ export async function readTranscript( turn: active, last: state.last, }; + oversized.delete(poll.cursor.path); } } cut ||= file.cut; From adc8a03b2eb2a8dcc13e63f37c15b972040d5d10 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 08:59:08 -0500 Subject: [PATCH 33/37] Cover a successful send across Claude transcript polls Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/tabs.test.tsx | 74 +++++++++++++++++++++------ 1 file changed, 58 insertions(+), 16 deletions(-) diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 01bc769a6d..f5642e3d40 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -756,6 +756,22 @@ it("reads canonical history when a 51st turn first appears at stop", async () => expect(fileReads().slice(before)).toEqual(["read", "read-page", "read"]); }); +const reportCall = { + type: "tool_use", + name: "mcp__buzz__send", + id: "s", + input: { text: "Sample report" }, +}; + +const toolResult = (id: string, content: string, is_error = false) => + JSON.stringify({ + uuid: `result-${id}`, + type: "user", + message: { + content: [{ type: "tool_result", tool_use_id: id, content, is_error }], + }, + }); + it("updates a tool outside the working tail and resumes polling after a late send result", async () => { const { load, path, gap, fileReads, startCompaction, summary } = await openLongTranscript(); @@ -772,23 +788,10 @@ it("updates a tool outside the working tail and resumes polling after a late sen id: "r", input: { file_path: "/work/sample.txt" }, }, - { - type: "tool_use", - name: "mcp__buzz__send", - id: "s", - input: { text: "Sample report" }, - }, + reportCall, ], }, }); - const result = (id: string, content: string, is_error = false) => - JSON.stringify({ - uuid: `result-${id}`, - type: "user", - message: { - content: [{ type: "tool_result", tool_use_id: id, content, is_error }], - }, - }); appendFileSync(path, `\n${calls}\n${gap}\n${sessionReply("draft reply")}\n`); vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); const poll = async () => @@ -811,7 +814,7 @@ it("updates a tool outside the working tail and resumes polling after a late sen tool.open = true; fireEvent(tool, new Event("toggle")); const before = fileReads().length; - appendFileSync(path, `${result("r", "original output")}\n`); + appendFileSync(path, `${toolResult("r", "original output")}\n`); await poll(); await vi.waitFor(() => expect(within(tool).getByText("original output")).toBeVisible(), @@ -819,7 +822,7 @@ it("updates a tool outside the working tail and resumes polling after a late sen expect(tool).toHaveAttribute("data-status", "completed"); expect(fileReads().slice(before)).not.toContain("read"); - appendFileSync(path, `${result("s", "channel missing", true)}\n`); + appendFileSync(path, `${toolResult("s", "channel missing", true)}\n`); await poll(); await vi.waitFor(() => expect( @@ -851,6 +854,45 @@ it("updates a tool outside the working tail and resumes polling after a late sen await expectFullPreviewHistory(); }); +it("marks a prior-batch send as posted when its full read returns", async () => { + const { path, gap, load, startCompaction, holdNextFileProcess } = + await openLongTranscript(); + await userEvent.click(load); + await expectFullPreviewHistory(); + const call = JSON.stringify({ + uuid: "report", + type: "assistant", + message: { content: [reportCall] }, + }); + appendFileSync(path, `\n${call}\n${gap}\n`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const finish = startCompaction(); + try { + const report = () => + screen.getByText("Sample report", transcriptSummary).closest("summary"); + await vi.waitFor(() => expect(report()).toBeVisible()); + const read = holdNextFileProcess("read"); + try { + appendFileSync(path, `${toolResult("s", `sent ${"a".repeat(64)}`)}\n`); + await act(async () => { + await vi.advanceTimersByTimeAsync(LIVE_READ_MS); + }); + await read.started; + expect(report()).not.toHaveTextContent("Posted"); + } finally { + read.release(); + } + await vi.waitFor(() => expect(report()).toHaveTextContent("Posted")); + expectTurnStatus( + screen.getByText("Sample report", transcriptSummary), + "Working", + ); + } finally { + vi.useRealTimers(); + await act(finish); + } +}); + it("reads corrected earlier history when work stops with Refresh queued behind a poll", async () => { const { load, From bd430307379ad9e407b4a5bf9ffd211a43a782bb Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 09:39:25 -0500 Subject: [PATCH 34/37] Compare working Claude transcript polls with full reads Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/transcript.test.ts | 123 ++++++++++++++++++++- 1 file changed, 117 insertions(+), 6 deletions(-) diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 216524ae20..6b2cbbe6e1 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -5,6 +5,7 @@ import { mkdirSync, mkdtempSync, rmSync, + statSync, utimesSync, writeFileSync, } from "node:fs"; @@ -148,14 +149,15 @@ it("groups a session file into prompted turns with steering, tools and replies", ); }); +const send = (id: string, text: string, tool = "send") => + line("assistant", [ + { type: "tool_use", id, name: `mcp__buzz__${tool}`, input: { text } }, + ]); +const result = (id: string, content: string, is_error = false) => + line("user", [{ type: "tool_result", tool_use_id: id, content, is_error }]); + it("shows what the agent posted as its reply once sent, and names Buzz tools as Codex does", () => { clock = 0; - const send = (id: string, text: string, tool = "send") => - line("assistant", [ - { type: "tool_use", id, name: `mcp__buzz__${tool}`, input: { text } }, - ]); - const result = (id: string, content: string, is_error = false) => - line("user", [{ type: "tool_result", tool_use_id: id, content, is_error }]); const [turn] = claudeTurns( [ line("user", prompt("review it")), @@ -1418,6 +1420,115 @@ it("keeps an incomplete UTF-8 record across working polls and retries from the a expect(await latest(staged)).toBeUndefined(); }); +it("matches each accepted working poll to a full read of the same session bytes", async () => { + const { home, spawn, reads } = host({ + [savedPath]: [ + line("user", turn("Check the report")), + line("progress", "x".repeat(2 << 20)), + "", + ].join("\n"), + }); + const path = join(home, ".claude/projects", savedPath); + const disk = manifestProcesses(home); + const args = [ + "~/.buzz", + conversation, + true, + new AbortController().signal, + ] as const; + let poll: WorkingPoll = {}; + const seed = async () => { + poll = {}; + await readTranscript(disk, ...args, undefined, poll); + expect(poll.cursor?.offset).toBe(statSync(path).size); + }; + const append = (...records: string[]) => + appendFileSync(path, records.join("\n") + "\n"); + const latest = () => readLatestTurns(spawn, ...args, undefined, poll); + const accept = async (shape: string, ...records: string[]) => { + append(...records); + const polled = await latest(); + expect(polled, shape).toHaveLength(1); + expect(poll.cursor?.offset, shape).toBe(statSync(path).size); + expect(reads, shape).toHaveLength(0); + const full = await readTranscript(disk, ...args); + expect(polled, shape).toStrictEqual(full?.turns); + return polled?.[0]?.items.at(-1); + }; + const text = (value: string, extra = {}) => + line("assistant", [{ type: "text", text: value }], extra); + const read = (id: string) => + line("assistant", [ + { type: "tool_use", id, name: "Read", input: { path: id } }, + ]); + await seed(); + await accept("assistant text", text("Checking")); + await accept( + "thinking", + line("assistant", [{ type: "thinking", thinking: "Compare reports" }]), + ); + await accept("open tool", read("report")); + await accept("complete tool", result("report", "ready")); + await accept("open second tool", read("missing")); + await accept("failed tool", result("missing", "file missing", true)); + await accept( + "posted send", + send("post", "Report ready"), + result("post", `sent ${"a".repeat(64)}`), + ); + await accept( + "failed send", + send("error", "Second report"), + result("error", "send failed", true), + ); + + const userSteer = await accept( + "timestamped user steer", + line("user", steerPrompt(turn("Check totals"))), + ); + const queuedSteer = await accept( + "untimed queued steer", + line("attachment", undefined, { + timestamp: undefined, + attachment: { + type: "queued_command", + prompt: steerPrompt(turn("Check dates")), + }, + }), + ); + expect(userSteer).toMatchObject({ steer: true, text: "Check totals" }); + expect(queuedSteer).toMatchObject({ + steer: true, + text: "Check dates", + at: userSteer?.at, + }); + + await accept("meta", line("user", turn("Hidden"), { isMeta: true })); + await accept("sidechain", text("Hidden", { isSidechain: true })); + await accept("missing uuid", text("Hidden", { uuid: undefined })); + await accept( + "other attachment", + line("attachment", undefined, { + attachment: { type: "other", prompt: steerPrompt(turn("Hidden")) }, + }), + ); + await accept("progress", line("progress", "Checking")); + await accept("system", line("system", "Notice")); + await accept( + "multiple pages", + text("Report complete", { padding: "x".repeat(1 << 20) }), + ); + const [process, options] = spawn.mock.calls.at(-1) ?? []; + expect(process).toBe("read-page"); + expect(Number(options?.args?.[2])).toBeGreaterThan(1); + + await accept("pending send", send("late", "Final report")); + append(result("late", `sent ${"b".repeat(64)}`)); + expect(await latest(), "receipt from an earlier poll").toBeUndefined(); + await seed(); + await accept("after the full read", text("Finished")); +}); + it("requests a full read immediately for a second oversized working turn", async () => { clock = 0; const session = { ...conversation, sessionId: "consecutive-oversized" }; From 44795829d28eaad6942bc8399abdca4c3d6be2dc Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 11:12:17 -0500 Subject: [PATCH 35/37] Keep focus in the transcript when earlier activity opens Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/TranscriptPreviewNotice.tsx | 66 +++++++++++++++++++++++++ src/bundled/claude-code/tabs.test.tsx | 32 +++++++++--- src/bundled/claude-code/tabs.tsx | 21 +++----- src/bundled/codex/tabs.test.tsx | 17 ++++++- src/bundled/codex/tabs.tsx | 24 +++++---- 5 files changed, 124 insertions(+), 36 deletions(-) create mode 100644 src/bundled/TranscriptPreviewNotice.tsx diff --git a/src/bundled/TranscriptPreviewNotice.tsx b/src/bundled/TranscriptPreviewNotice.tsx new file mode 100644 index 0000000000..f30d26b22e --- /dev/null +++ b/src/bundled/TranscriptPreviewNotice.tsx @@ -0,0 +1,66 @@ +import { Component, createRef } from "react"; +import { Button } from "../shared/design-system/ui/Button"; + +type FocusTarget = { refresh: HTMLButtonElement; focusVisible: boolean }; + +export class TranscriptPreviewNotice extends Component<{ + partial: boolean; + loading?: boolean; + onLoad(): void; +}> { + private load = createRef(); + + getSnapshotBeforeUpdate() { + const button = this.load.current; + if ( + this.props.partial || + !button || + button.ownerDocument.activeElement !== button + ) + return null; + const refresh = button + .closest("[data-transcript]") + ?.querySelector( + '[data-transcript-header] button[aria-label="Refresh transcript"]', + ); + return refresh + ? { refresh, focusVisible: button.matches(":focus-visible") } + : null; + } + + componentDidUpdate( + _previous: unknown, + _state: unknown, + target?: FocusTarget | null, + ) { + if ( + target?.refresh.isConnected && + target.refresh.ownerDocument.activeElement === + target.refresh.ownerDocument.body + ) { + const options = { + preventScroll: true, + focusVisible: target.focusVisible, + }; + target.refresh.focus(options); + } + } + + render() { + if (!this.props.partial) return null; + return ( +
+ Earlier activity is not loaded.{" "} + +
+ ); + } +} diff --git a/src/bundled/claude-code/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index f5642e3d40..4b5c6f9da4 100644 --- a/src/bundled/claude-code/tabs.test.tsx +++ b/src/bundled/claude-code/tabs.test.tsx @@ -609,15 +609,20 @@ it("keeps an untouched tail on working changes until earlier activity is request expect(fileReads().slice(before)).toEqual(["read-page", "read-page"]); const load = screen.getByRole("button", { name: /load earlier activity/i }); chmodSync(path, 0); - await user.click(load); + load.focus(); + await user.keyboard("{Enter}"); expect(await screen.findByRole("alert")).toHaveTextContent( /permission denied/i, ); expect(screen.getByText("while working", summary)).toBeVisible(); + expect(document.activeElement).toBe(load); chmodSync(path, 0o600); - await user.click(load); + await user.keyboard("{Enter}"); expect(await screen.findByText("earlier", summary)).toBeVisible(); expect(load).not.toBeInTheDocument(); + expect(document.activeElement).toBe( + screen.getByRole("button", { name: "Refresh transcript" }), + ); }); it("loads the missing history when a working session grows past the held tail", async () => { @@ -943,23 +948,38 @@ it("reads corrected earlier history when work stops with Refresh queued behind a expect(fileReads().slice(before)).toEqual(["read", "read-page", "read"]); }); -it.each(["Refresh transcript", "Load earlier activity"])( - "keeps the preview visible while %s loads full history", - async (action) => { +it.each([ + ["Refresh transcript", false], + ["Load earlier activity", false], + ["Load earlier activity", true], +] as const)( + "keeps the preview visible while %s loads full history (tab away: %s)", + async (action, tabAway) => { const { fileReads, holdNextFileProcess, summary } = await openLongTranscript(); const newest = await summary("newest"); const before = fileReads().length; const expansion = holdNextFileProcess("read", "read-page"); + const user = userEvent.setup(); + const control = screen.getByRole("button", { name: action }); + const refresh = screen.getByRole("button", { name: "Refresh transcript" }); + const expectedFocus = tabAway ? newest.closest("summary") : refresh; try { - fireEvent.click(screen.getByRole("button", { name: action })); + control.focus(); + await user.keyboard("{Enter}"); await expansion.started; + expect(document.activeElement).toBe(control); + if (tabAway) { + await user.tab(); + expect(document.activeElement).toBe(expectedFocus); + } expect(newest).toBeVisible(); expect(screen.getByText(partialHistory)).toBeVisible(); } finally { await act(async () => expansion.release()); } await expectFullPreviewHistory(); + expect(document.activeElement).toBe(expectedFocus); expect(fileReads().slice(before)).toEqual(["read"]); }, ); diff --git a/src/bundled/claude-code/tabs.tsx b/src/bundled/claude-code/tabs.tsx index 3448eefba3..76ba1800c9 100644 --- a/src/bundled/claude-code/tabs.tsx +++ b/src/bundled/claude-code/tabs.tsx @@ -22,6 +22,7 @@ import { useSyncExternalStore, } from "react"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; +import { TranscriptPreviewNotice } from "../TranscriptPreviewNotice"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; import { type ClaudeTranscript, @@ -1162,21 +1163,11 @@ export function createTabs({ } notes={(transcript) => ( <> - {transcript.partial && ( -
- - Earlier activity is not loaded.{" "} - - -
- )} + {transcript.incomplete && (

Some of this conversation’s sessions may be missing. Refresh to diff --git a/src/bundled/codex/tabs.test.tsx b/src/bundled/codex/tabs.test.tsx index a7c6d75dcb..ead73ee541 100644 --- a/src/bundled/codex/tabs.test.tsx +++ b/src/bundled/codex/tabs.test.tsx @@ -472,11 +472,17 @@ it("expands the clipped session opener without rereading it, and Refresh reads n expect(screen.getByText("Earlier activity is not loaded.")).toBeVisible(); expect(screen.queryByText("New session")).toBeNull(); const reads = f.spawn.mock.calls.length; - fireEvent.click(expand); + const user = userEvent.setup(); + const refresh = screen.getByRole("button", { name: "Refresh transcript" }); + refresh.focus(); + await user.tab(); + expect(document.activeElement).toBe(expand); + await user.keyboard("{Enter}"); expect(await screen.findByText("New session")).toBeVisible(); expect(loadedEntries()).toEqual( Array.from({ length: 130 }, (_, i) => `item:first-${i}`), ); + expect(document.activeElement).toBe(refresh); expect(f.spawn.mock.calls).toHaveLength(reads); count++; fireEvent.click(screen.getByRole("button", { name: "Refresh transcript" })); @@ -612,8 +618,15 @@ it.each(["Load earlier activity", "Refresh transcript", "linked message"])( else Reflect.deleteProperty(Element.prototype, "scrollIntoView"); } } else { - fireEvent.click(screen.getByRole("button", { name: action })); + const user = userEvent.setup(); + const control = screen.getByRole("button", { name: action }); + control.focus(); + await user.keyboard("{Enter}"); + expect(document.activeElement).toBe(control); await act(async () => stopped.resolve(full)); + expect(document.activeElement).toBe( + screen.getByRole("button", { name: "Refresh transcript" }), + ); } await screen.findByText("Message live-135", { selector: "summary span" }); expect(loadedEntries()).toHaveLength(266); diff --git a/src/bundled/codex/tabs.tsx b/src/bundled/codex/tabs.tsx index 636dba9654..6d66595dcd 100644 --- a/src/bundled/codex/tabs.tsx +++ b/src/bundled/codex/tabs.tsx @@ -31,6 +31,7 @@ import { useState, useSyncExternalStore, } from "react"; +import { TranscriptPreviewNotice } from "../TranscriptPreviewNotice"; import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; import { AgentInstructions } from "../../features/agents/AgentInstructions"; @@ -1326,22 +1327,19 @@ export function createTabs( session may have been deleted.

} - notes={(transcript) => - transcript.partial ? ( -
- Earlier activity is not loaded.{" "} - -
- ) : ( - transcript.more && ( + notes={(transcript) => ( + <> + + {!transcript.partial && transcript.more && (

Showing the latest {TURN_LIMIT} turns.

- ) - ) - } + )} + + )} /> ); } From 8d1289d98bfa83a6a15f4e5f7b65c1509c8c1f8d Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 14:29:09 -0500 Subject: [PATCH 36/37] Prune duplicate transcript assertions and exercise the linked reply body Co-authored-by: Jello Signed-off-by: LordMelkor --- src/bundled/claude-code/transcript.test.ts | 4 - src/bundled/codex/tabs.test.tsx | 1 - .../agents/ActivityTranscript.test.tsx | 6 +- src/features/agents/TranscriptPanel.test.tsx | 161 ++---------------- 4 files changed, 18 insertions(+), 154 deletions(-) diff --git a/src/bundled/claude-code/transcript.test.ts b/src/bundled/claude-code/transcript.test.ts index 6b2cbbe6e1..e3e28116a2 100644 --- a/src/bundled/claude-code/transcript.test.ts +++ b/src/bundled/claude-code/transcript.test.ts @@ -5,7 +5,6 @@ import { mkdirSync, mkdtempSync, rmSync, - statSync, utimesSync, writeFileSync, } from "node:fs"; @@ -1440,7 +1439,6 @@ it("matches each accepted working poll to a full read of the same session bytes" const seed = async () => { poll = {}; await readTranscript(disk, ...args, undefined, poll); - expect(poll.cursor?.offset).toBe(statSync(path).size); }; const append = (...records: string[]) => appendFileSync(path, records.join("\n") + "\n"); @@ -1449,7 +1447,6 @@ it("matches each accepted working poll to a full read of the same session bytes" append(...records); const polled = await latest(); expect(polled, shape).toHaveLength(1); - expect(poll.cursor?.offset, shape).toBe(statSync(path).size); expect(reads, shape).toHaveLength(0); const full = await readTranscript(disk, ...args); expect(polled, shape).toStrictEqual(full?.turns); @@ -1548,7 +1545,6 @@ it("requests a full read immediately for a second oversized working turn", async await expect(readLatestTurns(...args)).resolves.toBeUndefined(); const poll: WorkingPoll = {}; await readTranscript(...args, undefined, poll); - expect(poll.cursor).toBeDefined(); vi.setSystemTime(1_001_000); const file = join(home, ".claude/projects", path); appendFileSync(file, oversizedTurn("second")); diff --git a/src/bundled/codex/tabs.test.tsx b/src/bundled/codex/tabs.test.tsx index 9f860233e5..f64fec1d4d 100644 --- a/src/bundled/codex/tabs.test.tsx +++ b/src/bundled/codex/tabs.test.tsx @@ -469,7 +469,6 @@ it("expands the clipped session opener without rereading it, and Refresh reads n expect( screen.getByText("The start of this turn isn't loaded."), ).toBeVisible(); - expect(screen.getByText("Earlier activity is not loaded.")).toBeVisible(); expect(screen.queryByText("New session")).toBeNull(); const reads = f.spawn.mock.calls.length; const user = userEvent.setup(); diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index 9947463caa..2cc1be8082 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -769,9 +769,7 @@ it("shows the turn a message began, its prompt open, instead of the latest, once const margins: string[] = []; Element.prototype.scrollIntoView = function (this: HTMLElement) { if (this.dataset.entry === "item:m6") - expect( - this.querySelector("[data-arrival-surface][data-arrived]"), - ).not.toBeNull(); + expect(this).toHaveTextContent("Details of the linked reply"); shown.push(this.dataset.entry ?? ""); margins.push(this.style.scrollMarginBlockStart); }; @@ -863,7 +861,7 @@ it("shows the turn a message began, its prompt open, instead of the latest, once id: "m6", at: 7, type: "message", - text: "Reply 6", + text: "Reply 6\n\nDetails of the linked reply", messageId: "reply", }, ], diff --git a/src/features/agents/TranscriptPanel.test.tsx b/src/features/agents/TranscriptPanel.test.tsx index 0b3a5eb3e7..256925b7d3 100644 --- a/src/features/agents/TranscriptPanel.test.tsx +++ b/src/features/agents/TranscriptPanel.test.tsx @@ -495,9 +495,11 @@ it("reuses accepted transcript turns by unique ID on Refresh while preserving th repeatedBefore, reuseTurn(repeatedBefore.turnId), repeatedAfter, + toolTurn("corrected child", "old text"), ], details: { author: "previous" }, }); + const corrected = toolTurn("corrected child", "updated text"); const incoming = Object.freeze([ reuseTurn(moved.turnId), reuseTurn("added"), @@ -505,6 +507,7 @@ it("reuses accepted transcript turns by unique ID on Refresh while preserving th reuseTurn(repeatedBefore.turnId), reuseTurn(first.turnId), reuseTurn(repeatedAfter.turnId), + corrected, ]); const details = { author: "refreshed" }; reader.refresh(); @@ -518,6 +521,7 @@ it("reuses accepted transcript turns by unique ID on Refresh while preserving th "repeated before", "first", "repeated after", + "corrected child", ]); expect(accepted.turns[0]).toBe(moved); expect(accepted.turns[1]).toBe(incoming[1]); @@ -525,165 +529,32 @@ it("reuses accepted transcript turns by unique ID on Refresh while preserving th expect(accepted.turns[3]).toBe(incoming[3]); expect(accepted.turns[4]).toBe(first); expect(accepted.turns[5]).toBe(incoming[5]); + expect(accepted.turns.at(-1)).toBe(corrected); expect(accepted.details).toBe(details); }); -it.each(["cyclic data", "unreadable field"])( - "settles a Refresh containing %s and keeps the other equal turn", - async (kind) => { - function extensionTurn() { - const extension: Record = {}; - if (kind === "cyclic data") extension.self = extension; - else - Object.defineProperty(extension, "value", { - enumerable: true, - get() { - throw new Error("Field is unavailable"); - }, - }); - return { ...reuseTurn("extension"), extension }; - } - const reader = readTurnSnapshots(); - const stable = reuseTurn("stable"); - await settle(nth(reader.full, 0), { - more: false, - turns: [extensionTurn(), stable], - }); - const incoming = extensionTurn(); - reader.refresh(); - expect(reader.loading()).toBe(true); - await settle(nth(reader.full, 1), { - more: false, - turns: [incoming, reuseTurn("stable")], - }); - expect(reader.loading()).toBe(false); - expect(reader.snapshot().turns[0]).toBe(incoming); - expect(reader.snapshot().turns[1]).toBe(stable); - }, -); - -it("keeps a frozen transcript through an equal Refresh and updates changed metadata", async () => { - const reader = readTurnSnapshots(); - const held = Object.freeze({ - turns: [toolTurn("first", "same reply")], - more: false, - details: { author: "original" }, - }); - await settle(nth(reader.full, 0), held); - reader.refresh(); - await settle(nth(reader.full, 1), { - ...held, - turns: [toolTurn("first", "same reply")], - details: { author: "original" }, - }); - expect(reader.snapshot()).toBe(held); - - const details = { author: "updated" }; - reader.refresh(); - await settle(nth(reader.full, 2), { - ...held, - turns: [toolTurn("first", "same reply")], - details, - }); - expect(reader.snapshot().details).toBe(details); - expect(reader.snapshot().turns[0]).toBe(held.turns[0]); -}); - -it.each(["inherited", "non-enumerable"])( - "preserves %s metadata from the incoming transcript", - async (kind) => { - const reader = readTurnSnapshots(); - const stable = reuseTurn("stable"); - await settle(nth(reader.full, 0), { turns: [stable], more: false }); - const incoming: TurnSnapshot = { - turns: [reuseTurn("stable")], - more: false, - }; - const details = { author: "incoming" }; - if (kind === "inherited") Object.setPrototypeOf(incoming, { details }); - else Object.defineProperty(incoming, "details", { value: details }); - reader.refresh(); - await settle(nth(reader.full, 1), incoming); - - expect(reader.snapshot().details).toBe(details); - }, -); +it("settles a Refresh containing cyclic extension data and keeps the other equal turn", async () => { + function extensionTurn() { + const extension: Record = {}; + extension.self = extension; + return { ...reuseTurn("extension"), extension }; + } -it("settles a Refresh whose metadata cannot be compared", async () => { const reader = readTurnSnapshots(); const stable = reuseTurn("stable"); await settle(nth(reader.full, 0), { - turns: [stable], more: false, - details: { author: "original" }, - }); - const details = Object.defineProperty({ author: "unavailable" }, "author", { - get() { - throw new Error("Author is unavailable"); - }, + turns: [extensionTurn(), stable], }); + const incoming = extensionTurn(); reader.refresh(); await settle(nth(reader.full, 1), { - turns: [reuseTurn("stable")], more: false, - details, + turns: [incoming, reuseTurn("stable")], }); expect(reader.loading()).toBe(false); - expect(reader.snapshot().details).toBe(details); - expect(reader.snapshot().turns[0]).toBe(stable); -}); - -it("reuses accepted transcript turns only when snapshot fields are equal", async () => { - const reader = readTurnSnapshots(); - const nullRecord = () => Object.assign(Object.create(null), { key: "value" }); - const opaque = [ - ["functions", () => "value", () => "value"], - ["dates", new Date(1), new Date(1)], - ["maps", new Map([["key", "value"]]), new Map([["key", "value"]])], - ["sets", new Set(["value"]), new Set(["value"])], - ["regular expressions", /value/u, /value/u], - ] as const; - const fields: readonly (readonly [string, unknown, unknown, boolean])[] = [ - ["equal dense arrays", ["first", "second"], ["first", "second"], true], - ["reordered dense arrays", ["first", "second"], ["second", "first"], false], - [ - "different undefined keys", - { before: undefined }, - { after: undefined }, - false, - ], - ["null-prototype records", nullRecord(), nullRecord(), true], - ["different record prototypes", nullRecord(), { key: "value" }, false], - ["NaN", { value: Number.NaN }, { value: Number.NaN }, true], - ...opaque.flatMap(([name, before, after]) => [ - [`distinct ${name}`, before, after, false] as const, - [`shared ${name}`, before, before, true] as const, - ]), - ]; - const before = fields.map(([id, extension]) => ({ - ...reuseTurn(id), - extension, - })); - const after = fields.map(([id, , extension]) => ({ - ...reuseTurn(id), - extension, - })); - const corrected = toolTurn("corrected child", "updated text"); - await settle(nth(reader.full, 0), { - more: false, - turns: [...before, toolTurn("corrected child", "old text")], - }); - reader.refresh(); - await settle(nth(reader.full, 1), { - more: false, - turns: [...after, corrected], - }); - - const { turns } = reader.snapshot(); - fields.forEach(([name, , , equal], index) => { - expect(turns[index], name).toBe(equal ? before[index] : after[index]); - }); - expect(turns.at(-1)).toBe(corrected); + expect(reader.snapshot().turns[0]).toBe(incoming); + expect(reader.snapshot().turns[1]).toBe(stable); }); it("swaps the latest turns over the end of the held transcript", () => { From 3cb371b2c105e30377088b0831f3d664d3ebb9d8 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Sun, 22 Nov 2026 19:10:01 -0500 Subject: [PATCH 37/37] Restore equal Refresh and linked arrival regression checks Signed-off-by: LordMelkor Co-authored-by: Jello --- src/features/agents/ActivityTranscript.test.tsx | 6 +++++- src/features/agents/TranscriptPanel.test.tsx | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index 2cc1be8082..0fcb64111f 100644 --- a/src/features/agents/ActivityTranscript.test.tsx +++ b/src/features/agents/ActivityTranscript.test.tsx @@ -768,8 +768,12 @@ it("shows the turn a message began, its prompt open, instead of the latest, once const shown: string[] = []; const margins: string[] = []; Element.prototype.scrollIntoView = function (this: HTMLElement) { - if (this.dataset.entry === "item:m6") + if (this.dataset.entry === "item:m6") { + expect( + this.querySelector("[data-arrival-surface][data-arrived]"), + ).not.toBeNull(); expect(this).toHaveTextContent("Details of the linked reply"); + } shown.push(this.dataset.entry ?? ""); margins.push(this.style.scrollMarginBlockStart); }; diff --git a/src/features/agents/TranscriptPanel.test.tsx b/src/features/agents/TranscriptPanel.test.tsx index 256925b7d3..1346c981ca 100644 --- a/src/features/agents/TranscriptPanel.test.tsx +++ b/src/features/agents/TranscriptPanel.test.tsx @@ -533,6 +533,23 @@ it("reuses accepted transcript turns by unique ID on Refresh while preserving th expect(accepted.details).toBe(details); }); +it("keeps a frozen transcript through an equal Refresh", async () => { + const reader = readTurnSnapshots(); + const held = Object.freeze({ + turns: [toolTurn("first", "same reply")], + more: false, + details: { author: "original" }, + }); + await settle(nth(reader.full, 0), held); + reader.refresh(); + await settle(nth(reader.full, 1), { + ...held, + turns: [toolTurn("first", "same reply")], + details: { author: "original" }, + }); + expect(reader.snapshot()).toBe(held); +}); + it("settles a Refresh containing cyclic extension data and keeps the other equal turn", async () => { function extensionTurn() { const extension: Record = {};