:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(desktop): start bounded workers only for mounted diffs (#98930)
Charles Vien0324ca086a13
diff --git a/products/desktop/docs/PERFORMANCE.md b/products/desktop/docs/PERFORMANCE.mdnew file mode 100644index 000000000000..5b976d9950c6--- /dev/null+++ b/products/desktop/docs/PERFORMANCE.md@@ -0,0 +1,18 @@+# Desktop performance++## Diff workers++Diff components own the lifetime of the syntax-highlighting worker pool.+Opening a conversation without a diff does not start workers.+Mounted diffs share one pool per renderer, capped at two workers and 200 entries in each AST cache.+The last diff unmounting releases the pool.+Languages load as files need them instead of preloading a review-wide language list.++`DiffWorkerPool` supplies the same configuration to conversation previews and code review.+Place new diff renderers inside this boundary, rather than adding a provider around a whole page.+This keeps the worker budget independent of which view opens first.++`DiffWorkerPool.test.tsx` guards the pool budget, the sharing, and the release.+To check the lifecycle in the development app, open a plain conversation, open a diff, and then leave the diff.+Inspect worker targets in Chromium DevTools: the plain conversation should have no diff workers, the diff should have two, and leaving all diffs should release them.+Check syntax highlighting and large file scrolling in both conversation previews and code review.diff --git a/products/desktop/packages/agent/e2e/README.md b/products/desktop/packages/agent/e2e/README.mdindex 1cac7a150361..69c9d05aa7ef 100644--- a/products/desktop/packages/agent/e2e/README.md+++ b/products/desktop/packages/agent/e2e/README.md@@ -7,6 +7,9 @@ host/UI client (a recording `sessionUpdate`, an auto-allow `requestPermission`,and real file read/write against a throwaway git repo). Nothing in theagent/model/tool path is stubbed.+The test host answers questions and approves tools, but declines plan implementation handoffs so tests do not start extra model turns.+The startup test waits for its Claude processes to exit before removing their temporary configuration.+## What it coversFour suites. The two adapter-parametrized ones loop with `describe.skipIf` overdiff --git a/products/desktop/packages/agent/e2e/driver.e2e.test.ts b/products/desktop/packages/agent/e2e/driver.e2e.test.tsnew file mode 100644index 000000000000..d4d58560fb82--- /dev/null+++ b/products/desktop/packages/agent/e2e/driver.e2e.test.ts@@ -0,0 +1,56 @@+import type {+ Client,+ RequestPermissionRequest,+} from "@agentclientprotocol/sdk";+import { describe, expect, it, vi } from "vitest";+import { openConnection } from "./driver";++const host = vi.hoisted(() => ({ client: undefined as Client | undefined }));++vi.mock("@agentclientprotocol/sdk", () => ({+ ClientSideConnection: class {+ constructor(createClient: () => Client) {+ host.client = createClient();+ }+ },+ ndJsonStream: vi.fn(),+}));++vi.mock("../src/adapters/acp-connection", () => ({+ createAcpConnection: () => ({ clientStreams: {} }),+}));++describe("live e2e host permissions", () => {+ it.each([+ {+ kind: "switch_mode",+ optionId: "auto",+ outcome: { outcome: "cancelled" },+ },+ {+ kind: "other",+ optionId: "option_0",+ outcome: { outcome: "selected", optionId: "option_0" },+ },+ {+ kind: "edit",+ optionId: "allow",+ outcome: { outcome: "selected", optionId: "allow" },+ },+ ] as const)(+ "responds to $kind without starting unrequested implementation turns",+ async ({ kind, optionId, outcome }) => {+ const { capture } = openConnection({ adapter: "claude", cwd: "/tmp" });+ const request = {+ sessionId: "session",+ toolCall: { toolCallId: "tool", title: "Test permission", kind },+ options: [{ kind: "allow_once", optionId, name: "Allow" }],+ } as unknown as RequestPermissionRequest;++ expect(await host.client?.requestPermission(request)).toEqual({+ outcome,+ });+ expect(capture.approvals()).toHaveLength(1);+ },+ );+});diff --git a/products/desktop/packages/agent/e2e/driver.ts b/products/desktop/packages/agent/e2e/driver.tsindex d0b4c81d50ba..637bf1b1ee02 100644--- a/products/desktop/packages/agent/e2e/driver.ts+++ b/products/desktop/packages/agent/e2e/driver.ts@@ -15,8 +15,13 @@ import {} from "node:fs";import { tmpdir } from "node:os";import { join, resolve } from "node:path";-// @ts-expect-error - runtime ESM export resolved by vitest-import { ClientSideConnection, ndJsonStream } from "@agentclientprotocol/sdk";+import {+ ClientSideConnection,+ ndJsonStream,+ type ReadTextFileResponse,+ type RequestPermissionResponse,+ type WriteTextFileResponse,+} from "@agentclientprotocol/sdk";import { createAcpConnection } from "../src/adapters/acp-connection";import { Logger } from "../src/utils/logger";import { type Adapter, E2E } from "./config";@@ -104,7 +109,7 @@ export function openConnection(opts: {data: p?.update,});},- async requestPermission(p: any): Promise<unknown> {+ async requestPermission(p: any): Promise<RequestPermissionResponse> {events.push({kind: "requestPermission",data: {@@ -114,6 +119,10 @@ export function openConnection(opts: {codeToolKind: p?.toolCall?._meta?.codeToolKind,},});+ // Accepting a plan starts extra model turns outside the test's scenario.+ if (p?.toolCall?.kind === "switch_mode") {+ return { outcome: { outcome: "cancelled" } };+ }const options = p?.options ?? [];const allow =options.find(@@ -123,10 +132,10 @@ export function openConnection(opts: {outcome: { outcome: "selected", optionId: allow?.optionId ?? "allow" },};},- async readTextFile(p: any): Promise<unknown> {+ async readTextFile(p: any): Promise<ReadTextFileResponse> {return { content: await fsp.readFile(resolve(cwd, p.path), "utf8") };},- async writeTextFile(p: any): Promise<unknown> {+ async writeTextFile(p: any): Promise<WriteTextFileResponse> {await fsp.writeFile(resolve(cwd, p.path), p.content);return {};},diff --git a/products/desktop/packages/agent/e2e/session-lifecycle.e2e.test.ts b/products/desktop/packages/agent/e2e/session-lifecycle.e2e.test.tsindex 695de7ed2ab1..2d18fe22d842 100644--- a/products/desktop/packages/agent/e2e/session-lifecycle.e2e.test.ts+++ b/products/desktop/packages/agent/e2e/session-lifecycle.e2e.test.ts@@ -279,9 +279,11 @@ for (const adapter of ADAPTERS) {meta: meta(),});const askToUseTool =- "Before doing anything else, you MUST call the request_user_input tool " ++ "If the request_user_input tool is available, call it once " +"to ask the user a single question: whether to proceed with approach A " +- "or approach B. Ask exactly that one question via the tool, then stop.";+ "or approach B. After the answer, reply in one sentence and stop. " ++ "If the tool is unavailable, say so in one sentence and stop. " ++ "Do not call other tools or propose an implementation plan.";const questionCount = () =>s.capture.approvals()diff --git a/products/desktop/packages/agent/e2e/session-startup.e2e.test.ts b/products/desktop/packages/agent/e2e/session-startup.e2e.test.tsindex 384190b7e509..27f0204c5e60 100644--- a/products/desktop/packages/agent/e2e/session-startup.e2e.test.ts+++ b/products/desktop/packages/agent/e2e/session-startup.e2e.test.ts@@ -76,10 +76,23 @@ it("runs repository setup in a new worktree beyond the connection deadline", asy]) {const onLog = vi.fn();const onNotification = vi.fn();+ const processExits: Promise<void>[] = [];+ const pendingExits = new Map<number, () => void>();const transport = createAcpConnection({adapter: "claude",deviceType: "local",logger: new Logger({ onLog }),+ processCallbacks: {+ onProcessSpawned: ({ pid }) => {+ processExits.push(+ new Promise<void>((resolve) => pendingExits.set(pid, resolve)),+ );+ },+ onProcessExited: (pid) => {+ pendingExits.get(pid)?.();+ pendingExits.delete(pid);+ },+ },});const connection = new ClientSideConnection(() => ({@@ -143,6 +156,10 @@ it("runs repository setup in a new worktree beyond the connection deadline", asy);} finally {await transport.cleanup();+ // Aborting the SDK does not wait for its child to stop writing config.+ expect(+ (await withTimeout(Promise.all(processExits), 5_000)).result,+ ).toBe("success");}}expect(readFileSync(join(repository, ".setup-runs"), "utf8")).toBe(diff --git a/products/desktop/packages/ui/src/features/code-review/DiffWorkerPool.test.tsx b/products/desktop/packages/ui/src/features/code-review/DiffWorkerPool.test.tsxnew file mode 100644index 000000000000..4153083703a9--- /dev/null+++ b/products/desktop/packages/ui/src/features/code-review/DiffWorkerPool.test.tsx@@ -0,0 +1,111 @@+import { ServiceProvider } from "@posthog/di/react";+import { CodePreview } from "@posthog/ui/features/sessions/components/session-update/CodePreview";+import { DIFF_WORKER_FACTORY } from "@posthog/ui/shell/diffWorkerHost";+import { render, waitFor } from "@testing-library/react";+import { Container } from "inversify";+import type { ReactNode } from "react";+import { describe, expect, it, vi } from "vitest";+import { DiffWorkerPool } from "./DiffWorkerPool";++// The pool manager only ever calls these four members on a worker, and it never+// reads a reply, so a stub is enough to observe how many workers a mount starts+// and when they stop.+function createWorkerStub() {+ return {+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ postMessage: vi.fn(),+ terminate: vi.fn(),+ };+}++function renderWithFactory(children: ReactNode) {+ const workers: ReturnType<typeof createWorkerStub>[] = [];+ const workerFactory = vi.fn(() => {+ const worker = createWorkerStub();+ workers.push(worker);+ return worker as unknown as Worker;+ });+ const container = new Container();+ container.bind(DIFF_WORKER_FACTORY).toConstantValue(workerFactory);++ const view = render(+ <ServiceProvider container={container}>{children}</ServiceProvider>,+ );+ return { ...view, workers, workerFactory };+}++describe("DiffWorkerPool", () => {+ it("starts no workers for a preview that renders no diff", async () => {+ const { workerFactory, findByText } = renderWithFactory(+ <CodePreview+ content="const answer = 42;"+ filePath="answer.ts"+ showPath+ />,+ );++ await findByText("answer.ts", { exact: false });+ // A conversation that shows code but no diff must not pay for the pool.+ expect(workerFactory).not.toHaveBeenCalled();+ });++ it("caps a mounted pool at two workers and shares it across concurrent diffs", async () => {+ const { workers, unmount } = renderWithFactory(+ <>+ <DiffWorkerPool>+ <span>first diff</span>+ </DiffWorkerPool>+ <DiffWorkerPool>+ <span>second diff</span>+ </DiffWorkerPool>+ </>,+ );++ // Two mounted diffs, one renderer-wide pool: two workers, not four.+ await waitFor(() => expect(workers).toHaveLength(2));+ unmount();+ });++ it("stops the workers only once the last diff unmounts", async () => {+ function Diffs({ second }: { second: boolean }) {+ return (+ <>+ <DiffWorkerPool>+ <span>first diff</span>+ </DiffWorkerPool>+ {second && (+ <DiffWorkerPool>+ <span>second diff</span>+ </DiffWorkerPool>+ )}+ </>+ );+ }++ const { workers, rerender, unmount, workerFactory } = renderWithFactory(+ <Diffs second={true} />,+ );+ await waitFor(() => expect(workers).toHaveLength(2));++ const container = new Container();+ container.bind(DIFF_WORKER_FACTORY).toConstantValue(workerFactory);+ rerender(+ <ServiceProvider container={container}>+ <Diffs second={false} />+ </ServiceProvider>,+ );+ for (const worker of workers) {+ expect(worker.terminate).not.toHaveBeenCalled();+ }++ unmount();+ await waitFor(() => {+ for (const worker of workers) {+ expect(worker.terminate).toHaveBeenCalled();+ }+ });+ // Releasing the pool must not quietly restart it.+ expect(workerFactory).toHaveBeenCalledTimes(2);+ });+});diff --git a/products/desktop/packages/ui/src/features/code-review/DiffWorkerPool.tsx b/products/desktop/packages/ui/src/features/code-review/DiffWorkerPool.tsxnew file mode 100644index 000000000000..aa3c07c186b4--- /dev/null+++ b/products/desktop/packages/ui/src/features/code-review/DiffWorkerPool.tsx@@ -0,0 +1,30 @@+import { WorkerPoolContextProvider } from "@pierre/diffs/react";+import { useService } from "@posthog/di/react";+import { DIFFS_HIGHLIGHTER_OPTIONS } from "@posthog/ui/features/sessions/diffHighlighterOptions";+import {+ DIFF_WORKER_FACTORY,+ type DiffWorkerFactory,+} from "@posthog/ui/shell/diffWorkerHost";+import { type ReactElement, type ReactNode, useMemo } from "react";++export function DiffWorkerPool({+ children,+}: {+ children: ReactNode;+}): ReactElement {+ const workerFactory = useService<DiffWorkerFactory>(DIFF_WORKER_FACTORY);+ // The library shares one pool per renderer; every caller must use the same budget.+ const poolOptions = useMemo(+ () => ({ workerFactory, poolSize: 2, totalASTLRUCacheSize: 200 }),+ [workerFactory],+ );++ return (+ <WorkerPoolContextProvider+ poolOptions={poolOptions}+ highlighterOptions={DIFFS_HIGHLIGHTER_OPTIONS}+ >+ {children}+ </WorkerPoolContextProvider>+ );+}diff --git a/products/desktop/packages/ui/src/features/code-review/components/InteractiveFileDiff.tsx b/products/desktop/packages/ui/src/features/code-review/components/InteractiveFileDiff.tsxindex b6a65c2d4067..c81286f18e9a 100644--- a/products/desktop/packages/ui/src/features/code-review/components/InteractiveFileDiff.tsx+++ b/products/desktop/packages/ui/src/features/code-review/components/InteractiveFileDiff.tsx@@ -10,6 +10,7 @@ import { buildFileAnnotations } from "@posthog/core/code-review/prCommentAnnotatimport { useCallback, useMemo, useRef, useState } from "react";import { useInView } from "../../../primitives/hooks/useInView";import { DIFF_METRICS, REVIEW_PREFETCH_ROOT_MARGIN } from "../constants";+import { DiffWorkerPool } from "../DiffWorkerPool";import {type CommentEditSeed,useCommentState,@@ -322,15 +323,17 @@ function PatchDiffView({renderCustomHeader={renderCustomHeader}/>) : (- <FileDiff- fileDiff={fileDiff}- options={mergedOptions}- lineAnnotations={annotations}- selectedLines={selectedRange}- renderAnnotation={renderAnnotation}- renderCustomHeader={renderCustomHeader}- metrics={DIFF_METRICS}- />+ <DiffWorkerPool>+ <FileDiff+ fileDiff={fileDiff}+ options={mergedOptions}+ lineAnnotations={annotations}+ selectedLines={selectedRange}+ renderAnnotation={renderAnnotation}+ renderCustomHeader={renderCustomHeader}+ metrics={DIFF_METRICS}+ />+ </DiffWorkerPool>)}{tooLarge && (<div className="border-(--gray-5) border-t bg-(--gray-2) px-3 py-1.5 text-(--gray-10) text-[12px]">@@ -414,15 +417,17 @@ function FilesDiffView({);return (- <MultiFileDiff- oldFile={oldFile}- newFile={newFile}- options={mergedOptions}- lineAnnotations={annotations}- selectedLines={selectedRange}- renderAnnotation={renderAnnotation}- renderCustomHeader={renderCustomHeader}- metrics={DIFF_METRICS}- />+ <DiffWorkerPool>+ <MultiFileDiff+ oldFile={oldFile}+ newFile={newFile}+ options={mergedOptions}+ lineAnnotations={annotations}+ selectedLines={selectedRange}+ renderAnnotation={renderAnnotation}+ renderCustomHeader={renderCustomHeader}+ metrics={DIFF_METRICS}+ />+ </DiffWorkerPool>);}diff --git a/products/desktop/packages/ui/src/features/code-review/components/ReviewShell.tsx b/products/desktop/packages/ui/src/features/code-review/components/ReviewShell.tsxindex 24e02139e962..cbb48d9afbc8 100644--- a/products/desktop/packages/ui/src/features/code-review/components/ReviewShell.tsx+++ b/products/desktop/packages/ui/src/features/code-review/components/ReviewShell.tsx@@ -1,4 +1,3 @@-import { WorkerPoolContextProvider } from "@pierre/diffs/react";import { useService } from "@posthog/di/react";import { cn } from "@posthog/quill";import type { Task } from "@posthog/shared/domain-types";@@ -121,7 +120,6 @@ export function ReviewShell({prSourceAvailable,defaultBranch,}: ReviewShellProps) {- const reviewHost = useService<ReviewHost>(REVIEW_HOST);const taskId = task.id;const listRef = useRef<VListHandle | null>(null);const listContainerRef = useRef<HTMLDivElement | null>(null);@@ -173,11 +171,6 @@ export function ReviewShell({[filteredItems],);- const workerFactory = useCallback(- () => reviewHost.diffWorkerFactory(),- [reviewHost],- );-// The room the review was given, not the mode it was opened in: the same// review is a column, a widened panel, and a scene of its own.const hasRoomForFileBrowser = useIsWiderThan(@@ -395,82 +388,56 @@ export function ReviewShell({}return (- <WorkerPoolContextProvider- // poolSize: each highlighter worker is a full V8 isolate with shiki- // grammars loaded (~40MB RSS); the library default of 8 is oversized.- poolOptions={{ workerFactory, poolSize: 2 }}- highlighterOptions={{- theme: { dark: "github-dark", light: "github-light" },- langs: [- "typescript",- "tsx",- "javascript",- "jsx",- "json",- "css",- "html",- "markdown",- "python",- "ruby",- "go",- "rust",- "shell",- "yaml",- "sql",- ],- }}- >- <ReviewViewedContext.Provider value={viewedContextValue}>- <Flex ref={shellRef} direction="column" height="100%" id="review-shell">- <ReviewToolbar- taskId={taskId}- fileCount={fileCount}- viewedCount={viewedCount}- commentedFileCount={commentedFileCount}- unresolvedCommentedFileCount={unresolvedCommentedFileCount}- commentFilter={activeCommentFilter}- hasFileBrowserRoom={hasRoomForFileBrowser}- fileBrowserCollapsed={fileBrowserCollapsed}- onCommentFilterChange={- commentedFilePaths && unresolvedCommentedFilePaths- ? (filter) => setCommentFileFilter(taskId, filter)- : undefined- }- hideViewedFiles={hideViewedFiles}- filteredFileCount={filteredFileCount}- onHideViewedFilesChange={(hideViewed) =>- setHideViewedFiles(taskId, hideViewed)- }- linesAdded={linesAdded}- linesRemoved={linesRemoved}- allExpanded={allExpanded}- onExpandAll={onExpandAll}- onCollapseAll={onCollapseAll}- onRefresh={onRefresh}- onDiscardAll={onDiscardAll}- effectiveSource={effectiveSource}- branchSourceAvailable={branchSourceAvailable}- prSourceAvailable={prSourceAvailable}- defaultBranch={defaultBranch}- />- <Flex className="min-h-0 flex-1">- <Flex- ref={listContainerRef}- direction="column"- className="min-w-0 flex-1"- >- {reviewContent}- <PendingReviewBar taskId={taskId} />- </Flex>+ <ReviewViewedContext.Provider value={viewedContextValue}>+ <Flex ref={shellRef} direction="column" height="100%" id="review-shell">+ <ReviewToolbar+ taskId={taskId}+ fileCount={fileCount}+ viewedCount={viewedCount}+ commentedFileCount={commentedFileCount}+ unresolvedCommentedFileCount={unresolvedCommentedFileCount}+ commentFilter={activeCommentFilter}+ hasFileBrowserRoom={hasRoomForFileBrowser}+ fileBrowserCollapsed={fileBrowserCollapsed}+ onCommentFilterChange={+ commentedFilePaths && unresolvedCommentedFilePaths+ ? (filter) => setCommentFileFilter(taskId, filter)+ : undefined+ }+ hideViewedFiles={hideViewedFiles}+ filteredFileCount={filteredFileCount}+ onHideViewedFilesChange={(hideViewed) =>+ setHideViewedFiles(taskId, hideViewed)+ }+ linesAdded={linesAdded}+ linesRemoved={linesRemoved}+ allExpanded={allExpanded}+ onExpandAll={onExpandAll}+ onCollapseAll={onCollapseAll}+ onRefresh={onRefresh}+ onDiscardAll={onDiscardAll}+ effectiveSource={effectiveSource}+ branchSourceAvailable={branchSourceAvailable}+ prSourceAvailable={prSourceAvailable}+ defaultBranch={defaultBranch}+ />+ <Flex className="min-h-0 flex-1">+ <Flex+ ref={listContainerRef}+ direction="column"+ className="min-w-0 flex-1"+ >+ {reviewContent}+ <PendingReviewBar taskId={taskId} />+ </Flex>- {/* Width auto-hides the browser (unmounts). An explicit collapse+ {/* Width auto-hides the browser (unmounts). An explicit collapsekeeps it mounted but hidden so its state persists. */}- {hasRoomForFileBrowser && (- <FileBrowser task={task} collapsed={fileBrowserCollapsed} />- )}- </Flex>+ {hasRoomForFileBrowser && (+ <FileBrowser task={task} collapsed={fileBrowserCollapsed} />+ )}</Flex>- </ReviewViewedContext.Provider>- </WorkerPoolContextProvider>+ </Flex>+ </ReviewViewedContext.Provider>);}diff --git a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsxindex 37f97ab923de..175408b70dde 100644--- a/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/ConversationView.tsx@@ -1,6 +1,4 @@import { ArrowDown, XCircle } from "@phosphor-icons/react";-import { WorkerPoolContextProvider } from "@pierre/diffs/react";-import { useService } from "@posthog/di/react";import {Button,cn,@@ -45,7 +43,6 @@ import {type VirtualizedListHandle,} from "@posthog/ui/features/sessions/components/VirtualizedList";import { CHAT_CONTENT_MAX_WIDTH } from "@posthog/ui/features/sessions/constants";-import { DIFFS_HIGHLIGHTER_OPTIONS } from "@posthog/ui/features/sessions/diffHighlighterOptions";import { useConversationItems } from "@posthog/ui/features/sessions/hooks/useConversationItems";import { useConversationSearch } from "@posthog/ui/features/sessions/hooks/useConversationSearch";import {@@ -63,10 +60,6 @@ import { SessionTaskIdProvider } from "@posthog/ui/features/sessions/useSessionTimport { useSettingsStore } from "@posthog/ui/features/settings/settingsStore";import { TIP_KEYS } from "@posthog/ui/features/settings/tipKeys";import { SkillButtonActionMessage } from "@posthog/ui/features/skill-buttons/components/SkillButtonActionMessage";-import {- DIFF_WORKER_FACTORY,- type DiffWorkerFactory,-} from "@posthog/ui/shell/diffWorkerHost";import { Box, Flex, Text } from "@radix-ui/themes";import {memo,@@ -117,19 +110,6 @@ export function ConversationView({scrollX = true,promptRecallRef,}: ConversationViewProps) {- const diffWorkerFactory = useService<DiffWorkerFactory>(DIFF_WORKER_FACTORY);- const diffsPoolOptions = useMemo(- () => ({- workerFactory: () => diffWorkerFactory(),- totalASTLRUCacheSize: 200,- // Each pooled highlighter worker is a full V8 isolate with shiki- // grammars loaded (~40MB RSS); the library default of 8 costs hundreds- // of MB for parallelism conversation diffs don't need.- poolSize: 2,- }),- [diffWorkerFactory],- );-const listRef = useRef<VirtualizedListHandle>(null);const isAtBottomRef = useRef(true);const [showScrollButton, setShowScrollButton] = useState(false);@@ -506,70 +486,65 @@ export function ConversationView({);return (- <WorkerPoolContextProvider- poolOptions={diffsPoolOptions}- highlighterOptions={DIFFS_HIGHLIGHTER_OPTIONS}+ <div+ ref={containerRef}+ className="group/thread relative flex-1"+ onPointerDownCapture={clearKeyboardFocus}>- <div- ref={containerRef}- className="group/thread relative flex-1"- onPointerDownCapture={clearKeyboardFocus}- >- {search.open && (- <ConversationSearchBar- ref={search.searchBarRef}- query={search.query}- currentMatch={search.currentIndex}- totalMatches={search.totalMatches}- onQueryChange={search.setQuery}- onNext={search.next}- onPrev={search.prev}- onClose={search.close}- />- )}-- <MessageJumpPicker- open={jumpPickerOpen}- onOpenChange={setJumpPickerOpen}- items={items}- onJumpToMessage={handleJumpToMessage}+ {search.open && (+ <ConversationSearchBar+ ref={search.searchBarRef}+ query={search.query}+ currentMatch={search.currentIndex}+ totalMatches={search.totalMatches}+ onQueryChange={search.setQuery}+ onNext={search.next}+ onPrev={search.prev}+ onClose={search.close}/>+ )}- <SessionTaskIdProvider taskId={taskId}>- <VirtualizedList<ConversationTurn>- ref={listRef}- items={turns}- getItemKey={getTurnKey}- renderItem={renderTurn}- onScrollStateChange={handleScrollStateChange}- keepMounted={turnKeepMounted}- className="absolute inset-0 bg-background"- itemClassName="mx-auto px-2"- itemStyle={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}- footer={footer}- scrollX={scrollX}- />- </SessionTaskIdProvider>- {showScrollButton && (- <Box className="absolute right-6 bottom-4 z-10">- <Tooltip>- <TooltipTrigger- render={- <Button- size="icon-lg"- variant="outline"- onClick={scrollToBottom}- >- <ArrowDown size={14} weight="bold" />- </Button>- }- />- <TooltipContent>Scroll to bottom</TooltipContent>- </Tooltip>- </Box>- )}- </div>- </WorkerPoolContextProvider>+ <MessageJumpPicker+ open={jumpPickerOpen}+ onOpenChange={setJumpPickerOpen}+ items={items}+ onJumpToMessage={handleJumpToMessage}+ />++ <SessionTaskIdProvider taskId={taskId}>+ <VirtualizedList<ConversationTurn>+ ref={listRef}+ items={turns}+ getItemKey={getTurnKey}+ renderItem={renderTurn}+ onScrollStateChange={handleScrollStateChange}+ keepMounted={turnKeepMounted}+ className="absolute inset-0 bg-background"+ itemClassName="mx-auto px-2"+ itemStyle={{ maxWidth: CHAT_CONTENT_MAX_WIDTH }}+ footer={footer}+ scrollX={scrollX}+ />+ </SessionTaskIdProvider>+ {showScrollButton && (+ <Box className="absolute right-6 bottom-4 z-10">+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ size="icon-lg"+ variant="outline"+ onClick={scrollToBottom}+ >+ <ArrowDown size={14} weight="bold" />+ </Button>+ }+ />+ <TooltipContent>Scroll to bottom</TooltipContent>+ </Tooltip>+ </Box>+ )}+ </div>);}diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsxindex de9472f16e35..3238b525aba5 100644--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatThread.tsx@@ -6,9 +6,7 @@ import {ThumbsDown,ThumbsUp,} from "@phosphor-icons/react";-import { WorkerPoolContextProvider } from "@pierre/diffs/react";import { buildTurnRatingMetric } from "@posthog/core/analytics/aiFeedback";-import { useService } from "@posthog/di/react";import {Button,ChatBubble,@@ -106,7 +104,6 @@ import {CHAT_CONTENT_MAX_WIDTH,CHAT_CONTENT_PADDING_INLINE,} from "@posthog/ui/features/sessions/constants";-import { DIFFS_HIGHLIGHTER_OPTIONS } from "@posthog/ui/features/sessions/diffHighlighterOptions";import { useAgentConversationItems } from "@posthog/ui/features/sessions/hooks/useAgentConversationItems";import { useConversationItems } from "@posthog/ui/features/sessions/hooks/useConversationItems";import {@@ -131,10 +128,6 @@ import { SkillButtonActionMessage } from "@posthog/ui/features/skill-buttons/comimport { toast } from "@posthog/ui/primitives/toast";import { useCopy } from "@posthog/ui/primitives/useCopy";import { track } from "@posthog/ui/shell/analytics";-import {- DIFF_WORKER_FACTORY,- type DiffWorkerFactory,-} from "@posthog/ui/shell/diffWorkerHost";import {createContext,type FocusEvent,@@ -1354,15 +1347,6 @@ function ChatThreadRenderer({isLoadingOlderHistory,onLoadOlderHistory,}: ChatThreadRendererProps) {- const diffWorkerFactory = useService<DiffWorkerFactory>(DIFF_WORKER_FACTORY);- const diffsPoolOptions = useMemo(- () => ({- workerFactory: () => diffWorkerFactory(),- totalASTLRUCacheSize: 200,- }),- [diffWorkerFactory],- );-const optimisticItems = useOptimisticItemsForTask(taskId);const isCloud = useSessionIsCloud(taskId);@@ -1526,56 +1510,51 @@ function ChatThreadRenderer({);return (- <WorkerPoolContextProvider- poolOptions={diffsPoolOptions}- highlighterOptions={DIFFS_HIGHLIGHTER_OPTIONS}- >- <SessionTaskIdProvider taskId={taskId}>- <ChatThreadChromeProvider value={true}>- <ChatMessageScrollerProvider- // The windowed body owns following itself (anchorTo end + followOnAppend) — the- // engine's own follow would fight it, so it only auto-scrolls when non-virtualized.- autoScroll={!virtualized}- defaultScrollPosition="end"- // `scrollEdgeThreshold` is left at the engine's tight default on purpose. The engine- // re-enters "following-bottom" on *every* scroll event taken within the band, which- // overrides the free-scrolling its own wheel handler just set — so a wide band traps a- // reader scrolling up out of the bottom, and streamed content yanks them back each- // frame. `ThreadAutoFollow` is what keeps the thread pinned across the band's width;- // unlike the engine it only lets go on a real gesture.- scrollPreviousItemPeek={SCROLL_PREVIOUS_ITEM_PEEK}- >- {virtualized ? (- <VirtualThreadScrollBody+ <SessionTaskIdProvider taskId={taskId}>+ <ChatThreadChromeProvider value={true}>+ <ChatMessageScrollerProvider+ // The windowed body owns following itself (anchorTo end + followOnAppend) — the+ // engine's own follow would fight it, so it only auto-scrolls when non-virtualized.+ autoScroll={!virtualized}+ defaultScrollPosition="end"+ // `scrollEdgeThreshold` is left at the engine's tight default on purpose. The engine+ // re-enters "following-bottom" on *every* scroll event taken within the band, which+ // overrides the free-scrolling its own wheel handler just set — so a wide band traps a+ // reader scrolling up out of the bottom, and streamed content yanks them back each+ // frame. `ThreadAutoFollow` is what keeps the thread pinned across the band's width;+ // unlike the engine it only lets go on a real gesture.+ scrollPreviousItemPeek={SCROLL_PREVIOUS_ITEM_PEEK}+ >+ {virtualized ? (+ <VirtualThreadScrollBody+ items={items}+ flatRows={flatRows}+ renderRow={renderWindowedRow}+ onUserInteract={clearKeyboardFocus}+ footer={footer}+ renderNav={renderNav}+ resumeRef={threadResumeRef}+ olderHistoryCursor={olderHistoryCursor}+ isLoadingOlderHistory={isLoadingOlderHistory}+ onLoadOlderHistory={onLoadOlderHistory}+ />+ ) : (+ <>+ <ThreadScrollBody+ autoFollowRef={autoFollowRef}items={items}- flatRows={flatRows}- renderRow={renderWindowedRow}+ rows={rows}+ renderItem={renderItem}+ keyboardFocusedMessageId={keyboardFocusedMessageId}onUserInteract={clearKeyboardFocus}footer={footer}- renderNav={renderNav}- resumeRef={threadResumeRef}- olderHistoryCursor={olderHistoryCursor}- isLoadingOlderHistory={isLoadingOlderHistory}- onLoadOlderHistory={onLoadOlderHistory}+ resumeStateRef={threadResumeRef}/>- ) : (- <>- <ThreadScrollBody- autoFollowRef={autoFollowRef}- items={items}- rows={rows}- renderItem={renderItem}- keyboardFocusedMessageId={keyboardFocusedMessageId}- onUserInteract={clearKeyboardFocus}- footer={footer}- resumeStateRef={threadResumeRef}- />- {renderNav()}- </>- )}- </ChatMessageScrollerProvider>- </ChatThreadChromeProvider>- </SessionTaskIdProvider>- </WorkerPoolContextProvider>+ {renderNav()}+ </>+ )}+ </ChatMessageScrollerProvider>+ </ChatThreadChromeProvider>+ </SessionTaskIdProvider>);}diff --git a/products/desktop/packages/ui/src/features/sessions/components/session-update/CodePreview.tsx b/products/desktop/packages/ui/src/features/sessions/components/session-update/CodePreview.tsxindex 9859c8ea7116..b1dcd9e1da4b 100644--- a/products/desktop/packages/ui/src/features/sessions/components/session-update/CodePreview.tsx+++ b/products/desktop/packages/ui/src/features/sessions/components/session-update/CodePreview.tsx@@ -1,6 +1,7 @@import { EditorView } from "@codemirror/view";import { MultiFileDiff } from "@pierre/diffs/react";import { compactHomePath, parseImageDataUrl } from "@posthog/shared";+import { DiffWorkerPool } from "@posthog/ui/features/code-review/DiffWorkerPool";import { DIFFS_HIGHLIGHTER_OPTIONS } from "@posthog/ui/features/sessions/diffHighlighterOptions";import { Code } from "@radix-ui/themes";import { useEffect, useMemo, useRef } from "react";@@ -173,7 +174,13 @@ function DiffPreview({className="scroll-mask-2"style={maxHeight ? { maxHeight, overflow: "auto" } : undefined}>- <MultiFileDiff oldFile={oldFile} newFile={newFile} options={options} />+ <DiffWorkerPool>+ <MultiFileDiff+ oldFile={oldFile}+ newFile={newFile}+ options={options}+ />+ </DiffWorkerPool></div></div>);