perf: fix sustained-CPU hot paths from the July 2026 web performance audit
Addresses the audit's findings with minimal, desktop-first changes (no payload deferral, no streaming-path work since streaming is off by default): - Sidebar: replace the 10-thread bulk detail prewarm with a single hover-based prewarm; at idle one shell stream + at most one detail stream - Server replay: thread catch-up reads only the thread's aggregate stream via the (aggregate_kind, stream_id, sequence) index instead of scanning the global log; shell catch-up is bounded (500 events) with a shell snapshot fallback for stale cursors - Shell summaries: thread.message-sent updates latestUserMessageAt incrementally; activity-appended triggers the history-wide summary rebuild only for approval/user-input activity kinds; streaming assistant chunks no longer fan out per-chunk shell upserts - Client runtime: O(1) activity appends when order is preserved; skip IndexedDB full-snapshot encodes while a turn is running (settle event and scope finalizer persist the final state) - Timeline derivation: share one ordered activities view across the four derivations (identity-cached, O(n) sorted check); k-way merge for the combined timeline instead of concat+sort - Composer drafts: debounce JSON serialization itself, and cache per-draft partialization by object identity so typing doesn't re-clone every retained draft - Shiki: negative-cache languages without grammars (sh, yaml) so those fences stop retrying and throwing on every render - Bootstrap polling: one shared change-detecting poller instead of one 2s interval per consumer; minimap only writes data-in-view on change Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
3201e00ad4
commit
bc23ec5073
24 files changed
+963
-173
No files matched your search
@@ -140,6 +140,9 @@ const highlightedCodeCache = new LRUCache<string>(
|
||||
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
|
||||
);
|
||||
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
|
||||
// Languages Shiki has no grammar for (e.g. `sh` fences). Without this negative
|
||||
// cache every render of such a block retries the grammar load and throws again.
|
||||
const fallbackHighlightLanguages = new Set<string>();
|
||||
|
||||
function findTaskListMarkerOffset(markdown: string, listItemStart: number): number | null {
|
||||
const firstLineEnd = markdown.indexOf("\n", listItemStart);
|
||||
@@ -281,12 +284,15 @@ function getHighlighterPromise(language: string): Promise<DiffsHighlighter> {
|
||||
langs: [language as SupportedLanguages],
|
||||
preferredHighlighter: "shiki-js",
|
||||
}).catch((err) => {
|
||||
highlighterPromiseCache.delete(language);
|
||||
if (language === "text") {
|
||||
// "text" itself failed — Shiki cannot initialize at all, surface the error
|
||||
highlighterPromiseCache.delete(language);
|
||||
throw err;
|
||||
}
|
||||
// Language not supported by Shiki — fall back to "text"
|
||||
// Language not supported by Shiki — remember that and fall back to "text",
|
||||
// keeping the resolved promise cached so the grammar load isn't retried on
|
||||
// every render of a block with that language.
|
||||
fallbackHighlightLanguages.add(language);
|
||||
return getHighlighterPromise("text");
|
||||
});
|
||||
highlighterPromiseCache.set(language, promise);
|
||||
@@ -684,15 +690,17 @@ function UncachedShikiCodeBlock({
|
||||
}: UncachedShikiCodeBlockProps) {
|
||||
const highlighter = use(getHighlighterPromise(language));
|
||||
const highlightedHtml = useMemo(() => {
|
||||
const effectiveLanguage = fallbackHighlightLanguages.has(language) ? "text" : language;
|
||||
try {
|
||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
||||
return highlighter.codeToHtml(code, { lang: effectiveLanguage, theme: themeName });
|
||||
} catch (error) {
|
||||
// Log highlighting failures for debugging while falling back to plain text
|
||||
console.warn(
|
||||
`Code highlighting failed for language "${language}", falling back to plain text.`,
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
// If highlighting fails for this language, render as plain text
|
||||
// Remember the failure so subsequent renders skip the throwing path.
|
||||
fallbackHighlightLanguages.add(language);
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
}, [code, highlighter, language, themeName]);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
createSidebarHoverPrewarmController,
|
||||
createThreadJumpHintVisibilityController,
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
getVisibleSidebarThreadIds,
|
||||
resolveAdjacentThreadId,
|
||||
getFallbackThreadIdAfterDelete,
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import {
|
||||
@@ -181,17 +182,80 @@ describe("createThreadJumpHintVisibilityController", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSidebarThreadIdsToPrewarm", () => {
|
||||
it("returns only the first visible thread ids up to the prewarm limit", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2", "t3"], 2)).toEqual(["t1", "t2"]);
|
||||
describe("createSidebarHoverPrewarmController", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
it("returns all visible thread ids when they fit within the limit", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 10)).toEqual(["t1", "t2"]);
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("returns no thread ids when the limit is zero", () => {
|
||||
expect(getSidebarThreadIdsToPrewarm(["t1", "t2"], 0)).toEqual([]);
|
||||
const makeController = () => {
|
||||
const targets: Array<string | null> = [];
|
||||
const controller = createSidebarHoverPrewarmController({
|
||||
delayMs: SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||
onPrewarmTargetChange: (threadKey) => {
|
||||
targets.push(threadKey);
|
||||
},
|
||||
});
|
||||
return { controller, targets };
|
||||
};
|
||||
|
||||
it("prewarms a row only after the pointer rests on it", () => {
|
||||
const { controller, targets } = makeController();
|
||||
|
||||
controller.hover("t1");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS - 1);
|
||||
expect(targets).toEqual([]);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(targets).toEqual(["t1"]);
|
||||
});
|
||||
|
||||
it("prewarms at most one thread while sweeping across rows", () => {
|
||||
const { controller, targets } = makeController();
|
||||
|
||||
controller.hover("t1");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
|
||||
controller.hover("t2");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
|
||||
controller.hover("t3");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||
|
||||
expect(targets).toEqual(["t3"]);
|
||||
});
|
||||
|
||||
it("keeps an established prewarm when re-entering the same row", () => {
|
||||
const { controller, targets } = makeController();
|
||||
|
||||
controller.hover("t1");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||
controller.hover("t1");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||
|
||||
expect(targets).toEqual(["t1"]);
|
||||
});
|
||||
|
||||
it("releases the prewarm target when the pointer leaves thread rows", () => {
|
||||
const { controller, targets } = makeController();
|
||||
|
||||
controller.hover("t1");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||
controller.hover(null);
|
||||
|
||||
expect(targets).toEqual(["t1", null]);
|
||||
});
|
||||
|
||||
it("cancels a pending prewarm when the pointer leaves early", () => {
|
||||
const { controller, targets } = makeController();
|
||||
|
||||
controller.hover("t1");
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS / 2);
|
||||
controller.hover(null);
|
||||
vi.advanceTimersByTime(SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS);
|
||||
|
||||
expect(targets).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -13,9 +13,9 @@ import { resolveServerBackedAppStageLabel } from "../branding.logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||
// Visible sidebar rows are prewarmed into the thread-detail cache so opening a
|
||||
// nearby thread usually reuses an already-hot subscription.
|
||||
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
|
||||
// A pointer resting on a row signals intent to open it; sweeping past rows must
|
||||
// not open a detail subscription per row.
|
||||
export const SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS = 120;
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
@@ -283,11 +283,68 @@ export function getVisibleSidebarThreadIds<TThreadId>(
|
||||
);
|
||||
}
|
||||
|
||||
export function getSidebarThreadIdsToPrewarm<TThreadId>(
|
||||
visibleThreadIds: readonly TThreadId[],
|
||||
limit = SIDEBAR_THREAD_PREWARM_LIMIT,
|
||||
): TThreadId[] {
|
||||
return visibleThreadIds.slice(0, Math.max(0, limit));
|
||||
export interface SidebarHoverPrewarmController {
|
||||
hover: (threadKey: string | null) => void;
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
// Prewarms at most one thread at a time: the row the pointer has rested on.
|
||||
// The route mounts the active thread's detail subscription itself, so this is
|
||||
// the only sidebar-driven detail stream.
|
||||
export function createSidebarHoverPrewarmController(input: {
|
||||
delayMs: number;
|
||||
onPrewarmTargetChange: (threadKey: string | null) => void;
|
||||
setTimeoutFn?: typeof globalThis.setTimeout;
|
||||
clearTimeoutFn?: typeof globalThis.clearTimeout;
|
||||
}): SidebarHoverPrewarmController {
|
||||
const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
|
||||
const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
|
||||
let target: string | null = null;
|
||||
let pendingKey: string | null = null;
|
||||
let timeoutId: NodeJS.Timeout | null = null;
|
||||
|
||||
const clearPending = () => {
|
||||
if (timeoutId === null) {
|
||||
return;
|
||||
}
|
||||
clearTimeoutFn(timeoutId);
|
||||
timeoutId = null;
|
||||
pendingKey = null;
|
||||
};
|
||||
|
||||
return {
|
||||
hover: (threadKey) => {
|
||||
if (threadKey === null) {
|
||||
clearPending();
|
||||
if (target !== null) {
|
||||
target = null;
|
||||
input.onPrewarmTargetChange(null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (threadKey === target) {
|
||||
clearPending();
|
||||
return;
|
||||
}
|
||||
|
||||
if (threadKey === pendingKey) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearPending();
|
||||
pendingKey = threadKey;
|
||||
timeoutId = setTimeoutFn(() => {
|
||||
timeoutId = null;
|
||||
pendingKey = null;
|
||||
target = threadKey;
|
||||
input.onPrewarmTargetChange(threadKey);
|
||||
}, input.delayMs);
|
||||
},
|
||||
dispose: () => {
|
||||
clearPending();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAdjacentThreadId<T>(input: {
|
||||
|
||||
@@ -184,7 +184,8 @@ import {
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { useOpenAddProjectCommandPalette } from "../commandPaletteContext";
|
||||
import {
|
||||
getSidebarThreadIdsToPrewarm,
|
||||
createSidebarHoverPrewarmController,
|
||||
SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||
resolveAdjacentThreadId,
|
||||
isContextMenuPointerDown,
|
||||
isTrailingDoubleClick,
|
||||
@@ -248,6 +249,37 @@ function SidebarThreadDetailPrewarmer({ threadRef }: { readonly threadRef: Scope
|
||||
return null;
|
||||
}
|
||||
|
||||
// Self-contained so hover changes re-render only this component, never the
|
||||
// sidebar tree. Delegated `pointerover` avoids per-row handler props.
|
||||
function SidebarHoverThreadPrewarmer() {
|
||||
const [prewarmThreadKey, setPrewarmThreadKey] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = createSidebarHoverPrewarmController({
|
||||
delayMs: SIDEBAR_THREAD_HOVER_PREWARM_DELAY_MS,
|
||||
onPrewarmTargetChange: setPrewarmThreadKey,
|
||||
});
|
||||
const onPointerOver = (event: globalThis.PointerEvent) => {
|
||||
const target = event.target instanceof HTMLElement ? event.target : null;
|
||||
controller.hover(
|
||||
target?.closest("[data-thread-prewarm-key]")?.getAttribute("data-thread-prewarm-key") ??
|
||||
null,
|
||||
);
|
||||
};
|
||||
window.addEventListener("pointerover", onPointerOver, { passive: true });
|
||||
return () => {
|
||||
window.removeEventListener("pointerover", onPointerOver);
|
||||
controller.dispose();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const prewarmThreadRef = useMemo(
|
||||
() => (prewarmThreadKey === null ? null : parseScopedThreadKey(prewarmThreadKey)),
|
||||
[prewarmThreadKey],
|
||||
);
|
||||
return prewarmThreadRef ? <SidebarThreadDetailPrewarmer threadRef={prewarmThreadRef} /> : null;
|
||||
}
|
||||
|
||||
function clampSidebarThreadPreviewCount(value: number): SidebarThreadPreviewCount {
|
||||
return Math.min(
|
||||
MAX_SIDEBAR_THREAD_PREVIEW_COUNT,
|
||||
@@ -673,6 +705,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
|
||||
<SidebarMenuSubItem
|
||||
className="w-full"
|
||||
data-thread-item
|
||||
data-thread-prewarm-key={threadKey}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onBlurCapture={handleBlurCapture}
|
||||
>
|
||||
@@ -3491,18 +3524,6 @@ export default function Sidebar() {
|
||||
? threadJumpLabelByKey
|
||||
: EMPTY_THREAD_JUMP_LABELS;
|
||||
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
|
||||
const prewarmedSidebarThreadKeys = useMemo(
|
||||
() => getSidebarThreadIdsToPrewarm(visibleSidebarThreadKeys),
|
||||
[visibleSidebarThreadKeys],
|
||||
);
|
||||
const prewarmedSidebarThreadRefs = useMemo(
|
||||
() =>
|
||||
prewarmedSidebarThreadKeys.flatMap((threadKey) => {
|
||||
const ref = parseScopedThreadKey(threadKey);
|
||||
return ref ? [ref] : [];
|
||||
}),
|
||||
[prewarmedSidebarThreadKeys],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
updateThreadJumpHintsVisibility(shouldShowThreadJumpHintsNow);
|
||||
@@ -3695,9 +3716,7 @@ export default function Sidebar() {
|
||||
|
||||
return (
|
||||
<>
|
||||
{prewarmedSidebarThreadRefs.map((threadRef) => (
|
||||
<SidebarThreadDetailPrewarmer key={scopedThreadKey(threadRef)} threadRef={threadRef} />
|
||||
))}
|
||||
<SidebarHoverThreadPrewarmer />
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
|
||||
{isOnSettings ? (
|
||||
|
||||
@@ -373,7 +373,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
rowTop < scrollBottom &&
|
||||
rowTop + Math.max(1, rowHeight ?? 1) > scrollTop;
|
||||
|
||||
strip.dataset.inView = inView ? "true" : "false";
|
||||
// Scroll fires per frame; unconditional writes would dirty every strip's
|
||||
// attributes each frame even though only rows crossing the viewport edge
|
||||
// change.
|
||||
const nextInView = inView ? "true" : "false";
|
||||
if (strip.dataset.inView !== nextInView) {
|
||||
strip.dataset.inView = nextInView;
|
||||
}
|
||||
}
|
||||
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
|
||||
|
||||
|
||||
Reference in new issue
Block a user