diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 7ffd97f8be..6c022dccdf 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -127,6 +127,8 @@ if that desktop app is up and running. **Settings → Agent setup → Harness defaults**. - **An agent's page** has its identity and instructions, settings, **Memory**, **Activity** (its past sessions) and plugin tabs such as **Attention**. + Local Claude and Codex transcripts can open on recent activity. Choose + **Load earlier activity** to see more history. - **Instructions** change how an agent behaves. They don't give it new tools, accounts or permissions. - **Sessions.** By default an agent starts a fresh conversation for each diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index a9c5ba9d00..4ad3e0adfc 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -86,6 +86,8 @@ entry has a unique `id`, a `label`, and an `onSelect` callback. heading. With `placement: "team-row"`, the channel group uses the native Team menu and ignores these entries. +For `ctx.agents.ui.Transcript`, give each turn a unique `turnId` that stays the same across reads. Return a new turn when it changes. Leave previously returned turns and their items untouched. + ## Migration writes Check `ctx.relay.snapshot().session.supportsMigrationWrites === true` before 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/runtime.ts b/src/bundled/claude-code/runtime.ts index 1b40dc9029..ae85cd2b3f 100644 --- a/src/bundled/claude-code/runtime.ts +++ b/src/bundled/claude-code/runtime.ts @@ -133,7 +133,10 @@ import { readLatestTurns, readSessionTitle, readTranscript, + readTranscriptPreview, withNotices, + type ClaudeTranscript, + type WorkingPoll, type Conversation, type SessionsPlace, } from "./transcript"; @@ -841,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. @@ -849,20 +853,70 @@ export class ClaudeRuntime { ? `${REMOTE_TRANSCRIPTS}. They aren't attributed in the agent gateway yet.` : `${REMOTE_TRANSCRIPTS}.`, ); + return this.readActivity( + readTranscript, + conversation, + workspace, + working, + signal, + undefined, + poll, + ); + } + + 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), + poll?: WorkingPoll, + ) { 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, (pubkey) => this.reads(conversation.agent)?.name(pubkey), + poll, ).then( (transcript) => transcript && { @@ -896,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( @@ -911,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-overlap.test.tsx b/src/bundled/claude-code/tabs-overlap.test.tsx new file mode 100644 index 0000000000..b261c29e87 --- /dev/null +++ b/src/bundled/claude-code/tabs-overlap.test.tsx @@ -0,0 +1,135 @@ +// @vitest-environment jsdom +import "@testing-library/jest-dom/vitest"; +import { + act, + cleanup, + fireEvent, + render, + screen, +} from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +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"; + +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.restoreAllMocks(); + vi.useRealTimers(); + localStorage.clear(); +}); + +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({ + [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: 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(), + setup: new ClaudeSetup(undefined), + }); + const view = () => ; + const { rerender } = render(view()); + 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(); + + 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(pollSignal?.aborted).toBe(true); + }); + poll.resolve([next]); + try { + await stop; + } finally { + await act(async () => finish.resolve()); + } + + 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/tabs.test.tsx b/src/bundled/claude-code/tabs.test.tsx index 3b34d1e103..4b5c6f9da4 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 { @@ -236,28 +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 (name === "list" || name === "starts") 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, - ), - ), - }; - } + if ( + ["list", "starts", "size", "read-page", "read", "workspace"].includes( + name, + ) + ) + return listed(name, options); // 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"); @@ -333,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, @@ -487,6 +477,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 +498,790 @@ it("lists saved conversations and shows one's transcript, or that it is gone", a expect(save).not.toHaveBeenCalled(); }); +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`, + }, + }); +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( + "buzz.claude-code.sessions.v1", + JSON.stringify({ + [agent().key]: { channel: { id: "kept", seen: 0, at: 1 } }, + }), + ); + 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), + holdNextFileProcess(...ids: string[]) { + 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.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); + return { ...process, exited: held.then(() => code) }; + }); + }); + return { started, release }; + }, + fileReads: () => + spawn.mock.calls + .map(([id]) => id) + .filter((id) => id === "read" || id === "read-page"), + 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, 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(); + 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); + 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.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 () => { + const { Activity, path, gap, fileReads, 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" }), + ); + 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); + }); + 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); + } +}); + +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, + }); + const summary = (text: string) => + screen.findByText(text, { selector: "summary span" }); + 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(); +} + +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"]); +}); + +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(); + await userEvent.click(load); + await expectFullPreviewHistory(); + const calls = JSON.stringify({ + uuid: "calls", + type: "assistant", + message: { + content: [ + { + type: "tool_use", + name: "Read", + id: "r", + input: { file_path: "/work/sample.txt" }, + }, + reportCall, + ], + }, + }); + 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 { + 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, `${toolResult("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, `${toolResult("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"); + 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, + 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", 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 { + 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"]); + }, +); + +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("advances the 50-turn window on a working poll", async () => { + const { load, path, gap, startCompaction, summary } = + await openLongTranscript(); + const older = Array.from({ length: 48 }, (_, i) => + sessionPrompt(`turn ${i}`), + ); + writeFileSync(path, [...older, gap, sessionPrompt("newest")].join("\n")); + await userEvent.click(load); + await summary("turn 0"); + appendFileSync(path, `\n${sessionPrompt("during")}`); + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const finish = startCompaction(); + try { + 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, + ); + } finally { + vi.useRealTimers(); + 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")}`); + const finish = startCompaction(); + await summary("during"); + fireEvent.click(load); + await act(finish); + expect(await summary("earlier")).toBeVisible(); + 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("retries a missing transcript on focus and reuses successfully loaded history", async () => { + const { Activity, path, fileReads, startCompaction, holdNextFileProcess } = + 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, + }); + 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 = () => {}; + 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(); + 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.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) => @@ -680,6 +1457,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..76ba1800c9 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,7 +22,17 @@ import { useSyncExternalStore, } from "react"; import { PreferenceRow } from "../../shared/design-system/ui/PreferenceRow"; -import { TranscriptPanel } from "../../features/agents/TranscriptPanel"; +import { TranscriptPreviewNotice } from "../TranscriptPreviewNotice"; +import { TranscriptFocus } from "../../features/agents/ActivityTranscript"; +import { + type ClaudeTranscript, + type WorkingPoll, + 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"; @@ -994,17 +1005,153 @@ export function createTabs({ working: boolean; }) { const workspace = readConfig(agent.config).workspace; + const input = JSON.stringify([ + agent.key, + workspace, + conversation.sessionId, + ]); + const focus = useContext(TranscriptFocus); + const [history, setHistory] = useState({ + input, + focus, + attempt: focus ? 1 : 0, + loading: false, + }); + const again = JSON.stringify([input, history.attempt]); + const fullHistory = useRef<{ + input: string; + loaded: boolean; + live?: + | { again: string; result: ClaudeTranscript; poll: WorkingPoll } + | undefined; + }>(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 + ? old + : { + ...old, + attempt: old.attempt + 1, + loading: true, + }, + ); + const requireFullHistory = () => { + 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; + const poll = { ...intent?.live?.poll }; + let turns: ClaudeTranscript["turns"] | undefined; + try { + turns = await runtime.latestTurns( + conversation, + workspace, + working, + signal, + held, + poll, + ); + } 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, poll } : undefined; + } + return turns; + } return ( - agent={agent} - read={(signal) => - runtime.transcript(conversation, workspace, working, signal) - } - readLatest={(signal, held) => - runtime.latestTurns(conversation, workspace, working, signal, held) - } + 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(); + if (preview) return { ...preview, partial: true }; + } + const poll: WorkingPoll = {}; + const result = await runtime.transcript(...args, poll); + signal.throwIfAborted(); + if (fullHistory.current === intent) { + fullHistory.current = { + input, + loaded: Boolean(result), + live: + working && result && !result.incomplete + ? { again, result, poll } + : undefined, + }; + } + return result; + } finally { + if (history.loading && !signal.aborted) { + setHistory((current) => + current === history ? { ...current, loading: false } : current, + ); + } + } + }} + readLatest={latest} readKey={`${conversation.key}\u0000${workspace}`} - readAgain={conversation.sessionId ?? ""} + readAgain={again} working={working} reading="Reading the Claude session…" failed="Could not read the Claude session" @@ -1016,6 +1163,11 @@ export function createTabs({ } notes={(transcript) => ( <> + {transcript.incomplete && (

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

)} - {transcript.more && ( + {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 03e09e5ba0..e3e28116a2 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, @@ -14,11 +15,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, @@ -27,6 +30,7 @@ import { readTranscript, TURN_LIMIT, withNotices, + type WorkingPoll, } from "./transcript"; const root = "c".repeat(64); @@ -144,14 +148,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")), @@ -364,6 +369,337 @@ function host(files: Record) { return { spawn, reads, home }; } +const savedPath = "./-Users-me--buzz/session-1.jsonl"; + +function previewHost( + files: Record, + remote?: "bound" | "inspected", +) { + 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, + undefined, + undefined, + undefined, + undefined, + undefined, + async () => + remote === "inspected" ? { provider: "example/worker" } : undefined, + () => remote === "bound", + ); + 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) }], { + 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" }], { + timestamp: "2026-01-01T00:00:01Z", + }), + ].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.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]: [ + 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 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" }, + ]; + 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, + ); + 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); + } + }, +); + +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(), @@ -1021,32 +1357,244 @@ it("requests a full read when a clipped turn contains a delivered steer", async expect(latest?.map(({ turnId }) => turnId)).toEqual(["u5"]); }); -it("reads a turn larger than the chunk in full only every 30 s, keeping what is shown between", async () => { +it("keeps an incomplete UTF-8 record across working polls and retries from the accepted byte", 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" }]), + 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 now = vi.spyOn(Date, "now").mockReturnValue(1_000_000); - const latest = () => + 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, - new AbortController().signal, + 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("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); + }; + 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(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" }; + 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); + 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")) }; + 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, + 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 c2a728fcbd..d17946a7cb 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,6 +121,8 @@ export function claudeTurns( conversation: Session, working: boolean, name?: Names, + tail?: { uncertain: boolean; last?: number; opener?: number }, + prior?: TranscriptTurn, ): TranscriptTurn[] { const turns: TranscriptTurn[] = []; const tools = new Map(); @@ -127,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); @@ -147,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)); @@ -156,7 +175,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 +196,9 @@ 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; + if (tail && !current) tail.opener = start; (current ?? turn(id, at, false)).items.push(item); last = at; continue; @@ -195,7 +218,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; @@ -258,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; } @@ -386,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(); @@ -396,6 +424,87 @@ 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, + from = Math.max(0, Math.ceil(size / MIB) - LATEST_MIB), + count = LATEST_MIB, +) { + const bytes = await readFile( + spawn, + "~/.claude/projects", + path, + signal, + undefined, + "read-page", + [String(from), String(count)], + ); + const start = from ? bytes.indexOf(10) + 1 : 0; + return { + from, + bytes, + get text() { + return 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 @@ -408,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)) @@ -420,27 +530,44 @@ 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 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; 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 boundary = from && !working ? { uncertain: false } : undefined; const turns = claudeTurns( - decode(bytes.subarray(start)), + text, { sessionId, channelId: conversation.channelId, @@ -448,7 +575,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 ( @@ -488,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 : "")) @@ -498,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++) { @@ -506,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); @@ -517,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), }; @@ -570,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; @@ -626,12 +760,36 @@ 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, + }; + oversized.delete(poll.cursor.path); + } + } cut ||= file.cut; if (file.cut) { // Its first kept turn did not start the session, and with none kept diff --git a/src/bundled/codex/tabs.test.tsx b/src/bundled/codex/tabs.test.tsx index 589176ec74..f64fec1d4d 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,267 @@ 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.queryByText("New session")).toBeNull(); + const reads = f.spawn.mock.calls.length; + 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" })); + 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("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) => { + 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 { + 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); + 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..6d66595dcd 100644 --- a/src/bundled/codex/tabs.tsx +++ b/src/bundled/codex/tabs.tsx @@ -23,12 +23,16 @@ 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 { TranscriptPreviewNotice } from "../TranscriptPreviewNotice"; +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 +89,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 +127,73 @@ 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; source: string } | undefined; + reading?: AbortSignal | undefined; +}; + +function previewTranscript( + transcript: CodexTranscript, + view: TranscriptViewState, + working: boolean, + source: string, +) { + 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, source }; + 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 +1259,42 @@ export function createTabs( conversation: SavedConversation; working: boolean; }) { + const focus = useContext(TranscriptFocus); + const view = useRef({ + start: focus ? "full" : undefined, + }).current; + const [again, setAgain] = useState(0); + const source = JSON.stringify([conversation.threadId, working]); + useLayoutEffect(() => { + if (view.snapshot?.source !== source) view.snapshot = undefined; + if (focus && view.start !== "full") { + view.start = "full"; + setAgain((n) => n + 1); + } + }, [source, 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, source); + } 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 +1311,11 @@ export function createTabs( turns: runtime.prompts(agent.key).shown(transcript.turns), } ); + })} + readAgain={JSON.stringify([conversation.threadId, again])} + onRefreshRequested={() => { + view.snapshot = undefined; + view.start = "full"; }} readKey={conversation.key} working={working} @@ -1219,13 +1327,19 @@ export function createTabs( session may have been deleted.

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

- Showing the latest {TURN_LIMIT} turns. -

- ) - } + notes={(transcript) => ( + <> + + {!transcript.partial && 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} > { + 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/ActivityTranscript.module.css b/src/features/agents/ActivityTranscript.module.css index 9f3653891f..be3255abc9 100644 --- a/src/features/agents/ActivityTranscript.module.css +++ b/src/features/agents/ActivityTranscript.module.css @@ -13,6 +13,20 @@ 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] .timeline:has(> .turn) > :not(.turn) { + padding-inline: 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; diff --git a/src/features/agents/ActivityTranscript.test.tsx b/src/features/agents/ActivityTranscript.test.tsx index 99ced4a9b1..0fcb64111f 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); }); @@ -504,6 +508,220 @@ it("opens at the latest turn and follows new ones until the reader scrolls up", shared.remove(); }); +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: 90, + }, + { + 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, resized, 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; + let viewportHeight = resized ? 35 : 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", { get: () => 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 = !fits ? turn.items.slice(0, -1) : turn.items; + const show = (history: boolean, live = false) => ( + "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 (resized) { + view.scrollTop = 0; + fireEvent.scroll(view); + viewportHeight = 150; + } + 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 (!fits) { + view.dispatchEvent(new Event("scroll")); + rerender(show(true, true)); + expect(view.scrollTop).toBe(expectedTop); + } + } finally { + view.remove(); + } + }, +); + +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 && { partial: 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. @@ -550,6 +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") { + 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); }; @@ -558,12 +782,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"} /> @@ -581,6 +805,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 @@ -638,7 +865,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", }, ], @@ -708,7 +935,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 +978,9 @@ 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(); + expect(screen.queryByText("Agent instructions")).not.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,14 +1048,14 @@ 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")); 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, @@ -845,15 +1074,28 @@ 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"} />, ); - expect(screen.getByText("formatting")).not.toBeVisible(); + expect(screen.queryByText("formatting")).not.toBeInTheDocument(); const disclosure = screen .getByText("Checking the view", { selector: "summary span" }) .closest("summary"); @@ -861,13 +1103,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 83dffc2f26..0b92502f91 100644 --- a/src/features/agents/ActivityTranscript.tsx +++ b/src/features/agents/ActivityTranscript.tsx @@ -1,12 +1,15 @@ import { + Component, Fragment, createContext, + memo, useContext, useEffect, useSyncExternalStore, useLayoutEffect, useMemo, useRef, + useState, type ReactNode, } from "react"; import remarkGfm from "remark-gfm"; @@ -69,7 +72,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 @@ -205,12 +211,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); @@ -220,7 +230,89 @@ 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; + candidates: { 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) 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 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( + _previous: unknown, + _state: unknown, + anchor?: HistoryAnchor | null, + ) { + const { timeline, restoredTop } = this.props.scroll; + const body = timeline.current; + 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; + restoredTop.current = view.scrollTop; + } + + render() { + return ( +
+ {this.props.children} +
+ ); + } } /** Shows the focused entry once it is loaded, opening its prompt, instead of @@ -229,9 +321,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 = [ @@ -277,6 +371,7 @@ function useShowFocused( }); focus.done(); }, [focus, entry, timeline, following]); + return entry; } /** Turn-by-turn transcript of the loaded activity, oldest first, opened at @@ -292,7 +387,7 @@ export function ActivityTranscript({ agentKey, community, }: { - transcript: Transcript; + transcript: Transcript & { partial?: true }; agentName: string; state: (turnId: string) => TurnState | undefined; /** Paging controls shown above the oldest loaded turn. */ @@ -306,8 +401,14 @@ export function ActivityTranscript({ agentKey?: string; community?: string | undefined; }) { - const { timeline, following } = useFollowLatest(transcript, follow); - useShowFocused(transcript, timeline, following); + const partial = transcript.partial === 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, @@ -327,10 +428,18 @@ export function ActivityTranscript({ community, "small", ); + const rowContext = useMemo( + () => ({ picture: poster ?? picture, focused }), + [poster, picture, focused], + ); return ( - -
+ + {before} {!transcript.turns.length && (

@@ -346,7 +455,7 @@ export function ActivityTranscript({ : "Session continued; earlier turns not shown"}

)} - ))} -
-
+ +
); } @@ -473,6 +582,8 @@ function Turn({ ); } +const MemoizedTurn = memo(Turn); + /** The same live-work treatment at the start and end of the turn. */ function WorkingLabel() { return ( @@ -511,8 +622,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 +675,15 @@ function Disclosure({ footer?: ReactNode; children: ReactNode; }) { + const focused = useContext(RowContext).focused === `item:${item.id}`; + const [visited, setVisited] = useState(focused); + if (focused && !visited) setVisited(true); return (
{ + if (event.currentTarget.open) setVisited(true); + }} data-status={item.type === "tool" ? item.status : undefined} > @@ -574,8 +700,8 @@ function Disclosure({ /> - {children &&
{children}
} - {footer} + {visited && children &&
{children}
} + {visited && footer}
); } @@ -614,7 +740,7 @@ function Item({ item: TranscriptItem; agentName: string; }) { - const avatarSource = useContext(AgentAvatarSource); + const { picture: avatarSource } = useContext(RowContext); switch (item.type) { case "system": return ; diff --git a/src/features/agents/TranscriptPanel.test.tsx b/src/features/agents/TranscriptPanel.test.tsx index fdedcbf4dd..1346c981ca 100644 --- a/src/features/agents/TranscriptPanel.test.tsx +++ b/src/features/agents/TranscriptPanel.test.tsx @@ -23,7 +23,11 @@ import { useLiveTranscript, withLatest, } from "./TranscriptPanel"; -import type { Transcript, TranscriptTurn } from "./activity-transcript"; +import type { + Transcript, + TranscriptItem, + TranscriptTurn, +} from "./activity-transcript"; beforeEach(() => 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 }; @@ -49,7 +53,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 +84,7 @@ function setup() { again, working, agentKey: "agent", + onRefreshRequested, }), { wrapper, initialProps: { key: "a", working: false } as Props }, ); @@ -94,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 () => { @@ -153,14 +158,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"); @@ -369,6 +377,203 @@ 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.more).toBe(true); + expect(accepted.turns[0]).toBe(turns[1]); + expect(accepted.turns.at(-2)).toBe(previousLast); + expect(accepted.turns.at(-1)).toBe(sent); + 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, + toolTurn("corrected child", "old text"), + ], + details: { author: "previous" }, + }); + const corrected = toolTurn("corrected child", "updated text"); + const incoming = Object.freeze([ + reuseTurn(moved.turnId), + reuseTurn("added"), + reuseTurn(repeatedAfter.turnId), + reuseTurn(repeatedBefore.turnId), + reuseTurn(first.turnId), + reuseTurn(repeatedAfter.turnId), + corrected, + ]); + 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", + "corrected child", + ]); + 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.turns.at(-1)).toBe(corrected); + 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 = {}; + extension.self = extension; + 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(); + 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("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 1851a94673..eaeb78790f 100644 --- a/src/features/agents/TranscriptPanel.tsx +++ b/src/features/agents/TranscriptPanel.tsx @@ -73,12 +73,53 @@ 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]); +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 @@ -101,6 +142,7 @@ export function useLiveTranscript({ working, refreshWhileWorking = true, agentKey, + onRefreshRequested, }: { read: (signal: AbortSignal) => Promise; readLatest?: @@ -114,6 +156,7 @@ export function useLiveTranscript({ working: boolean; refreshWhileWorking?: boolean | undefined; agentKey: string; + onRefreshRequested?: (() => void) | undefined; }) { const agents = useContext(AgentsContext); const [shown, setShown] = useState>({ key }); @@ -229,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; @@ -287,7 +331,10 @@ export function useLiveTranscript({ return { shown: shown.key === key ? shown : ({ key } as Shown), loading, - refresh: () => void request(false), + refresh: () => { + onRefreshRequested?.(); + request(false); + }, }; } @@ -299,6 +346,7 @@ export function TranscriptPanel({ readLatest, readKey, readAgain = "", + onRefreshRequested, working, refreshWhileWorking, reading, @@ -319,6 +367,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. */ @@ -340,6 +390,7 @@ export function TranscriptPanel({ working, refreshWhileWorking, agentKey: agent.key, + onRefreshRequested, }); const { transcript, error } = shown; return ( 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"] 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,