diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx index 87b5961..b54b409 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.spec.tsx @@ -285,6 +285,86 @@ describe("ChatThreadPanel", () => { expect(scrollAnchor).toBeInTheDocument(); }); + it("virtualizes a 2000-turn history to a bounded number of mounted turns", () => { + const messages: AgentMessageSnapshot[] = []; + for (let index = 0; index < 2000; index += 1) { + messages.push({ + id: `user-${index}`, + role: "user", + text: `Question ${index}`, + status: "complete", + timestamp: index * 2, + }); + messages.push({ + id: `assistant-${index}`, + role: "assistant", + text: `Answer ${index}`, + status: "complete", + timestamp: index * 2 + 1, + }); + } + + const { container } = render( + + + , + ); + + const mountedTurns = container.querySelectorAll("[data-turn-id]"); + expect(mountedTurns.length).toBeGreaterThan(0); + expect(mountedTurns.length).toBeLessThanOrEqual(30); + expect( + container.querySelector('[data-message-id="assistant-1999"]'), + ).not.toBeNull(); + expect( + container.querySelector('[data-message-id="assistant-0"]'), + ).toBeNull(); + }); + + it("reveals a targeted message inside an unmounted turn (search reveal)", async () => { + const messages: AgentMessageSnapshot[] = []; + for (let index = 0; index < 2000; index += 1) { + messages.push({ + id: `user-${index}`, + role: "user", + text: `Question ${index}`, + status: "complete", + timestamp: index * 2, + }); + messages.push({ + id: `assistant-${index}`, + role: "assistant", + text: `Answer ${index}`, + status: "complete", + timestamp: index * 2 + 1, + }); + } + const onTargetMessageNavigated = vi.fn(); + + render( + + + , + ); + + await waitFor(() => { + expect(onTargetMessageNavigated).toHaveBeenCalledWith("assistant-123"); + }); + expect(HTMLElement.prototype.scrollIntoView).toHaveBeenCalled(); + }); + it("scrolls to a targeted message when message navigation is requested", async () => { const onTargetMessageNavigated = vi.fn(); diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.tsx index 37f59dc..9978b36 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-panel.tsx @@ -4,7 +4,7 @@ import * as React from "react"; import { StreamingIndicator } from "@/components/ui/activity-indicator"; import { ScrollButton } from "@/components/ui/scroll-button"; import { toast } from "@/lib/toast"; -import { buildChatTurns } from "./chat/chat-thread-turns"; +import { createChatTurnsBuilder } from "./chat/chat-thread-turns"; import type { InlineModelPickerProps } from "./chat/thread-header"; import { ChatThreadTranscript, @@ -13,6 +13,8 @@ import { export interface ChatThreadPanelProps { threadTitle: string; + /** Stable thread identity, used to preserve scroll position per thread. */ + threadId?: string | null; messages: AgentMessageSnapshot[]; isStreaming: boolean; isLoading?: boolean; @@ -46,6 +48,7 @@ export interface ChatThreadPanelProps { export function ChatThreadPanel({ threadTitle: _threadTitle, + threadId, messages, isStreaming, isLoading, @@ -106,7 +109,13 @@ export function ChatThreadPanel({ [messages], ); - const turns = React.useMemo(() => buildChatTurns(messages), [messages]); + // One builder per mounted panel: unchanged turns keep their identity + // across streaming updates (issue #11). + const turnsBuilderRef = React.useRef(createChatTurnsBuilder()); + const turns = React.useMemo( + () => turnsBuilderRef.current.build(messages), + [messages], + ); React.useEffect(() => { if (!targetMessageId) { @@ -158,6 +167,8 @@ export function ChatThreadPanel({ isLoading={isLoading} isStreaming={isStreaming} lastError={lastError} + targetMessageId={targetMessageId} + threadId={threadId} onCopyMessage={handleCopyMessage} onRetryLastUserMessage={onRetryLastUserMessage} onResubmitUserMessage={onResubmitUserMessage} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript.tsx index 2283b91..948de19 100644 --- a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript.tsx +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-transcript.tsx @@ -5,13 +5,13 @@ import { cn, } from "@pi-desktop/ui"; import { Skeleton } from "boneyard-js/react"; -import * as React from "react"; import type { ActivityIndicatorProps } from "@/components/ui/activity-indicator"; import { SystemMessage } from "@/components/ui/system-message"; import { describeChatError } from "./chat/chat-error"; import type { ChatThreadTurn } from "./chat/chat-thread-turns"; import { ResponseDivider } from "./chat/response-divider"; -import { ChatThreadTranscriptTurn } from "./chat-thread-transcript-turn"; +import { ChatThreadTurnSlot } from "./chat-thread-turn-slot"; +import { ChatThreadVirtualTurnList } from "./chat-thread-virtual-turn-list"; const CHAT_SUGGESTIONS: ReadonlyArray = [ "Explain this repo", @@ -43,6 +43,8 @@ export interface ChatThreadTranscriptProps { onRetryLastUserMessage?: (text: string) => void; onResubmitUserMessage?: (messageId: string, nextText: string) => void; getMessageTokens?: (messageId: string) => number | null | undefined; + targetMessageId?: string | null; + threadId?: string | null; } export function detectRunningActivities( @@ -103,6 +105,8 @@ export function ChatThreadTranscript({ onRetryLastUserMessage, onResubmitUserMessage, getMessageTokens, + targetMessageId, + threadId, }: ChatThreadTranscriptProps) { const lastTurn = turns.length > 0 ? turns[turns.length - 1] : undefined; const lastTurnDividerWorking = @@ -186,30 +190,25 @@ export function ChatThreadTranscript({ ) : null} - {turns.length > 0 - ? turns.map((turn, turnIndex) => { - const isLastTurn = turnIndex === turns.length - 1; - const failedLastUser = - isLastTurn && canRetryLastUser && turn.userMessage !== null; - - return ( - - - - ); - }) - : null} + {turns.length > 0 ? ( + ( + + )} + /> + ) : null} {lastError && errorPresentation ? (
void; + onRetryLastUserMessage?: (text: string) => void; + onResubmitUserMessage?: (messageId: string, nextText: string) => void; + getMessageTokens?: (messageId: string) => number | null | undefined; +} + +/** + * One transcript turn with the transcript-level actions wired in: retry + * is only offered on a failed last user message, and edit/resubmit only + * on the last turn. Used as the render slot of the virtual turn list. + */ +export function ChatThreadTurnSlot({ + turn, + isLastTurn, + canRetryLastUser, + onCopyMessage, + onRetryLastUserMessage, + onResubmitUserMessage, + getMessageTokens, +}: ChatThreadTurnSlotProps) { + const failedLastUser = + isLastTurn && canRetryLastUser && turn.userMessage !== null; + + return ( + + ); +} diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.spec.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.spec.tsx new file mode 100644 index 0000000..bdd77d7 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.spec.tsx @@ -0,0 +1,136 @@ +// @vitest-environment jsdom +import type { AgentMessageSnapshot } from "@pi-desktop/shared"; +import { cleanup, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import { buildChatTurns } from "./chat/chat-thread-turns"; +import { ChatThreadVirtualTurnList } from "./chat-thread-virtual-turn-list"; + +function createMessages(count: number): AgentMessageSnapshot[] { + const messages: AgentMessageSnapshot[] = []; + for (let index = 0; index < count; index += 1) { + messages.push({ + id: `user-${index}`, + role: "user", + text: `Question ${index}`, + status: "complete", + timestamp: index * 2, + }); + messages.push({ + id: `assistant-${index}`, + role: "assistant", + text: `Answer ${index}`, + status: "complete", + timestamp: index * 2 + 1, + }); + } + return messages; +} + +function renderList( + turnCount: number, + overrides: Partial[0]> = {}, +) { + const turns = buildChatTurns(createMessages(turnCount)); + return render( + ( +
{turn.id}
+ )} + {...overrides} + />, + ); +} + +afterEach(() => { + cleanup(); +}); + +describe("ChatThreadVirtualTurnList", () => { + it("mounts a bounded number of rows for a 2000-turn fixture", () => { + renderList(2000); + + const rows = screen.getAllByTestId("chat-turn-row"); + expect(rows.length).toBeGreaterThan(0); + expect(rows.length).toBeLessThanOrEqual(30); + // The latest turns are mounted on first paint; early history is not. + expect(screen.getByTestId("turn-content-user-1999")).toBeInTheDocument(); + expect(screen.queryByTestId("turn-content-user-0")).not.toBeInTheDocument(); + // Skipped history is represented by spacers, keeping the total + // scroll height (and therefore the scroll position) meaningful. + expect(screen.getAllByTestId("virtual-turn-spacer").length).toBeGreaterThan( + 0, + ); + }); + + it("re-renders only the trailing window when a streaming turn appends", () => { + const messages = createMessages(2000); + const turns = buildChatTurns(messages); + const { rerender } = render( +
{turn.id}
} + />, + ); + const before = screen + .getAllByTestId("chat-turn-row") + .map((row) => row.dataset.turnId); + + const nextTurns = buildChatTurns([ + ...messages, + { + id: "assistant-1999", + role: "assistant", + text: "Answer 1999 (streaming more)", + status: "streaming", + timestamp: 4000, + }, + ]); + rerender( +
{turn.id}
} + />, + ); + + const after = screen + .getAllByTestId("chat-turn-row") + .map((row) => row.dataset.turnId); + expect(after).toEqual(before); + expect(after[after.length - 1]).toBe("user-1999"); + }); + + it("force-mounts the turn containing a targeted (search) message", () => { + renderList(2000, { targetMessageId: "assistant-123" }); + + // Turn 123 is far outside the trailing window but must be mounted so + // the panel can scroll it into view. + expect(screen.getByTestId("turn-content-user-123")).toBeInTheDocument(); + expect(screen.getByTestId("turn-content-user-1999")).toBeInTheDocument(); + expect(screen.getAllByTestId("chat-turn-row").length).toBeLessThanOrEqual( + 31, + ); + }); + + it("renders every turn when the history is short", () => { + renderList(5); + expect(screen.getAllByTestId("chat-turn-row")).toHaveLength(5); + expect(screen.queryByTestId("virtual-turn-spacer")).not.toBeInTheDocument(); + }); + + it("renders nothing for an empty history", () => { + render( +
{turn.id}
} + />, + ); + expect( + screen.queryByTestId("chat-virtual-turn-list"), + ).not.toBeInTheDocument(); + }); +}); diff --git a/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.tsx b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.tsx new file mode 100644 index 0000000..21cb4c2 --- /dev/null +++ b/apps/desktop/src/renderer/src/features/workspace/components/chat-thread-virtual-turn-list.tsx @@ -0,0 +1,114 @@ +import * as React from "react"; +import type { ChatThreadTurn } from "./chat/chat-thread-turns"; +import { useVirtualTurnListScroll } from "./chat/use-virtual-turn-list-scroll"; +import { + buildMountedSegments, + computeMountedTurnIndices, + findTurnIndexForMessage, +} from "./chat/virtual-turn-window"; + +export interface ChatThreadVirtualTurnListProps { + turns: ChatThreadTurn[]; + isStreaming: boolean; + /** Message to reveal (e.g. a search result): its turn is force-mounted. */ + targetMessageId?: string | null; + /** Thread id used to save/restore the reading position across switches. */ + scrollStoreKey?: string | null; + renderTurn: (turn: ChatThreadTurn, turnIndex: number) => React.ReactNode; +} + +function TurnSpacer({ height }: { height: number }) { + return ( +