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]);
|
||||
|
||||
|
||||
@@ -46,9 +46,9 @@ import {
|
||||
newElementContextId,
|
||||
} from "./lib/elementContext";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { persist } from "zustand/middleware";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
|
||||
import { createDebouncedJsonStorage, createMemoryStorage } from "./lib/storage";
|
||||
import { getDefaultServerModel } from "./providerModels";
|
||||
import { UnifiedSettings } from "@t3tools/contracts/settings";
|
||||
import { ReviewCommentContextSchema, type ReviewCommentContext } from "./reviewCommentContext";
|
||||
@@ -66,7 +66,7 @@ export type DraftId = typeof DraftId.Type;
|
||||
|
||||
const COMPOSER_PERSIST_DEBOUNCE_MS = 300;
|
||||
|
||||
const composerDebouncedStorage = createDebouncedStorage(
|
||||
const composerDebouncedStorage = createDebouncedJsonStorage<PersistedComposerDraftStoreState>(
|
||||
typeof localStorage !== "undefined" ? localStorage : createMemoryStorage(),
|
||||
COMPOSER_PERSIST_DEBOUNCE_MS,
|
||||
);
|
||||
@@ -1815,6 +1815,14 @@ function migratePersistedComposerDraftStoreState(
|
||||
};
|
||||
}
|
||||
|
||||
// Runs on every store update (each prompt keystroke); drafts are immutable
|
||||
// snapshots, so unchanged drafts reuse their previously partialized form
|
||||
// instead of re-cloning nested contexts/annotations/comments per update.
|
||||
const partializedDraftCache = new WeakMap<
|
||||
ComposerThreadDraftState,
|
||||
PersistedComposerThreadDraftState | null
|
||||
>();
|
||||
|
||||
function partializeComposerDraftStoreState(
|
||||
state: ComposerDraftStoreState,
|
||||
): PersistedComposerDraftStoreState {
|
||||
@@ -1825,78 +1833,20 @@ function partializeComposerDraftStoreState(
|
||||
if (typeof threadKey !== "string" || threadKey.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const hasModelData =
|
||||
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.elementContexts.length === 0 &&
|
||||
draft.previewAnnotations.length === 0 &&
|
||||
draft.reviewComments.length === 0 &&
|
||||
!hasModelData &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
) {
|
||||
const cached = partializedDraftCache.get(draft);
|
||||
if (cached !== undefined) {
|
||||
if (cached !== null) {
|
||||
persistedDraftsByThreadKey[threadKey] =
|
||||
cached as DeepMutable<PersistedComposerThreadDraftState>;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const persistedDraft: DeepMutable<PersistedComposerThreadDraftState> = {
|
||||
prompt: draft.prompt,
|
||||
attachments: draft.persistedAttachments,
|
||||
...(draft.terminalContexts.length > 0
|
||||
? {
|
||||
terminalContexts: draft.terminalContexts.map((context) => ({
|
||||
id: context.id,
|
||||
threadId: context.threadId,
|
||||
createdAt: context.createdAt,
|
||||
terminalId: context.terminalId,
|
||||
terminalLabel: context.terminalLabel,
|
||||
lineStart: context.lineStart,
|
||||
lineEnd: context.lineEnd,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(draft.elementContexts.length > 0
|
||||
? {
|
||||
elementContexts: draft.elementContexts.map((context) => ({
|
||||
id: context.id,
|
||||
threadId: context.threadId,
|
||||
pickedAt: context.pickedAt,
|
||||
pageUrl: context.pageUrl,
|
||||
pageTitle: context.pageTitle,
|
||||
tagName: context.tagName,
|
||||
selector: context.selector,
|
||||
htmlPreview: context.htmlPreview,
|
||||
componentName: context.componentName,
|
||||
source: context.source,
|
||||
styles: context.styles,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(draft.previewAnnotations.length > 0
|
||||
? {
|
||||
previewAnnotations: draft.previewAnnotations.map(
|
||||
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(draft.reviewComments.length > 0
|
||||
? {
|
||||
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
|
||||
}
|
||||
: {}),
|
||||
...(hasModelData
|
||||
? {
|
||||
modelSelectionByProvider: compactModelSelectionByProvider(
|
||||
draft.modelSelectionByProvider,
|
||||
),
|
||||
activeProvider: draft.activeProvider,
|
||||
}
|
||||
: {}),
|
||||
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
||||
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
||||
};
|
||||
persistedDraftsByThreadKey[threadKey] = persistedDraft;
|
||||
const persisted = partializeComposerThreadDraft(draft);
|
||||
partializedDraftCache.set(draft, persisted);
|
||||
if (persisted !== null) {
|
||||
persistedDraftsByThreadKey[threadKey] =
|
||||
persisted as DeepMutable<PersistedComposerThreadDraftState>;
|
||||
}
|
||||
}
|
||||
return {
|
||||
draftsByThreadKey: persistedDraftsByThreadKey,
|
||||
@@ -1910,6 +1860,80 @@ function partializeComposerDraftStoreState(
|
||||
};
|
||||
}
|
||||
|
||||
function partializeComposerThreadDraft(
|
||||
draft: ComposerThreadDraftState,
|
||||
): PersistedComposerThreadDraftState | null {
|
||||
const hasModelData =
|
||||
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.elementContexts.length === 0 &&
|
||||
draft.previewAnnotations.length === 0 &&
|
||||
draft.reviewComments.length === 0 &&
|
||||
!hasModelData &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
prompt: draft.prompt,
|
||||
attachments: draft.persistedAttachments,
|
||||
...(draft.terminalContexts.length > 0
|
||||
? {
|
||||
terminalContexts: draft.terminalContexts.map((context) => ({
|
||||
id: context.id,
|
||||
threadId: context.threadId,
|
||||
createdAt: context.createdAt,
|
||||
terminalId: context.terminalId,
|
||||
terminalLabel: context.terminalLabel,
|
||||
lineStart: context.lineStart,
|
||||
lineEnd: context.lineEnd,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(draft.elementContexts.length > 0
|
||||
? {
|
||||
elementContexts: draft.elementContexts.map((context) => ({
|
||||
id: context.id,
|
||||
threadId: context.threadId,
|
||||
pickedAt: context.pickedAt,
|
||||
pageUrl: context.pageUrl,
|
||||
pageTitle: context.pageTitle,
|
||||
tagName: context.tagName,
|
||||
selector: context.selector,
|
||||
htmlPreview: context.htmlPreview,
|
||||
componentName: context.componentName,
|
||||
source: context.source,
|
||||
styles: context.styles,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(draft.previewAnnotations.length > 0
|
||||
? {
|
||||
previewAnnotations: draft.previewAnnotations.map(
|
||||
(annotation) => ({ ...annotation }) as DeepMutable<PreviewAnnotationPayload>,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(draft.reviewComments.length > 0
|
||||
? {
|
||||
reviewComments: draft.reviewComments.map((comment) => ({ ...comment })),
|
||||
}
|
||||
: {}),
|
||||
...(hasModelData
|
||||
? {
|
||||
modelSelectionByProvider: compactModelSelectionByProvider(draft.modelSelectionByProvider),
|
||||
activeProvider: draft.activeProvider,
|
||||
}
|
||||
: {}),
|
||||
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
||||
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeCurrentPersistedComposerDraftStoreState(
|
||||
persistedState: unknown,
|
||||
): PersistedComposerDraftStoreState {
|
||||
@@ -3341,7 +3365,7 @@ const composerDraftStore = create<ComposerDraftStoreState>()(
|
||||
{
|
||||
name: COMPOSER_DRAFT_STORAGE_KEY,
|
||||
version: COMPOSER_DRAFT_STORAGE_VERSION,
|
||||
storage: createJSONStorage(() => composerDebouncedStorage),
|
||||
storage: composerDebouncedStorage,
|
||||
migrate: migratePersistedComposerDraftStoreState,
|
||||
partialize: partializeComposerDraftStoreState,
|
||||
merge: (persistedState, currentState) => {
|
||||
|
||||
@@ -1,10 +1,71 @@
|
||||
import type { DesktopEnvironmentBootstrap } from "@t3tools/contracts";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSyncExternalStore } from "react";
|
||||
|
||||
import { readDesktopSecondaryBootstraps } from "./desktopLocal";
|
||||
|
||||
const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;
|
||||
|
||||
function bootstrapsEqual(
|
||||
left: ReadonlyArray<DesktopEnvironmentBootstrap>,
|
||||
right: ReadonlyArray<DesktopEnvironmentBootstrap>,
|
||||
): boolean {
|
||||
if (left.length !== right.length) {
|
||||
return false;
|
||||
}
|
||||
return left.every((entry, index) => {
|
||||
const other = right[index];
|
||||
return (
|
||||
other !== undefined &&
|
||||
entry.id === other.id &&
|
||||
entry.label === other.label &&
|
||||
entry.runningDistro === other.runningDistro &&
|
||||
entry.httpBaseUrl === other.httpBaseUrl &&
|
||||
entry.wsBaseUrl === other.wsBaseUrl &&
|
||||
entry.bootstrapToken === other.bootstrapToken
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
// One shared poller for all consumers (sidebar, command palette, ...): a single
|
||||
// interval runs only while someone is subscribed, and listeners are notified
|
||||
// only when the topology actually changed — each poll returns a fresh array,
|
||||
// so publishing it unconditionally would re-render every consumer per tick.
|
||||
const listeners = new Set<() => void>();
|
||||
let currentSnapshot: ReadonlyArray<DesktopEnvironmentBootstrap> | null = null;
|
||||
let pollInterval: ReturnType<typeof setInterval> | null = null;
|
||||
|
||||
function poll(): void {
|
||||
const next = readDesktopSecondaryBootstraps();
|
||||
if (currentSnapshot !== null && bootstrapsEqual(currentSnapshot, next)) {
|
||||
return;
|
||||
}
|
||||
currentSnapshot = next;
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
if (pollInterval === null) {
|
||||
poll();
|
||||
pollInterval = setInterval(poll, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);
|
||||
}
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size === 0 && pollInterval !== null) {
|
||||
clearInterval(pollInterval);
|
||||
pollInterval = null;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getSnapshot(): ReadonlyArray<DesktopEnvironmentBootstrap> {
|
||||
// First read happens during render, before subscribe() has polled.
|
||||
currentSnapshot ??= readDesktopSecondaryBootstraps();
|
||||
return currentSnapshot;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reactively track the desktop's secondary local backends (e.g. a parallel WSL
|
||||
* backend). The bridge exposes no change event, so we re-read on an interval;
|
||||
@@ -13,16 +74,5 @@ const DESKTOP_LOCAL_BOOTSTRAP_POLL_MS = 2_000;
|
||||
* renderer consumer reads the same topology.
|
||||
*/
|
||||
export function useDesktopLocalBootstraps(): ReadonlyArray<DesktopEnvironmentBootstrap> {
|
||||
const [bootstraps, setBootstraps] = useState<ReadonlyArray<DesktopEnvironmentBootstrap>>(
|
||||
readDesktopSecondaryBootstraps,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const read = () => setBootstraps(readDesktopSecondaryBootstraps());
|
||||
read();
|
||||
const interval = setInterval(read, DESKTOP_LOCAL_BOOTSTRAP_POLL_MS);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
return bootstraps;
|
||||
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import type { PersistStorage, StorageValue } from "zustand/middleware";
|
||||
|
||||
export interface StateStorage<R = unknown> {
|
||||
getItem: (name: string) => string | null | Promise<string | null>;
|
||||
@@ -65,3 +66,45 @@ export function createDebouncedStorage(
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface DebouncedPersistStorage<S> extends PersistStorage<S> {
|
||||
flush: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* A zustand `PersistStorage` that debounces the JSON serialization as well as
|
||||
* the storage write. `createJSONStorage` + a debounced `StateStorage` only
|
||||
* delays the write — the full state is still stringified on every store
|
||||
* update; here it happens once per debounce window instead.
|
||||
*/
|
||||
export function createDebouncedJsonStorage<S>(
|
||||
baseStorage: Partial<StateStorage> | null | undefined,
|
||||
debounceMs: number = 300,
|
||||
): DebouncedPersistStorage<S> {
|
||||
const resolvedStorage = resolveStorage(baseStorage);
|
||||
const debouncedSetItem = new Debouncer(
|
||||
(name: string, value: StorageValue<S>) => {
|
||||
resolvedStorage.setItem(name, JSON.stringify(value));
|
||||
},
|
||||
{ wait: debounceMs },
|
||||
);
|
||||
|
||||
return {
|
||||
getItem: (name) => {
|
||||
const raw = resolvedStorage.getItem(name);
|
||||
const parse = (value: string | null): StorageValue<S> | null =>
|
||||
value === null ? null : (JSON.parse(value) as StorageValue<S>);
|
||||
return raw instanceof Promise ? raw.then(parse) : parse(raw);
|
||||
},
|
||||
setItem: (name, value) => {
|
||||
debouncedSetItem.maybeExecute(name, value);
|
||||
},
|
||||
removeItem: (name) => {
|
||||
debouncedSetItem.cancel();
|
||||
resolvedStorage.removeItem(name);
|
||||
},
|
||||
flush: () => {
|
||||
debouncedSetItem.flush();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -356,7 +356,7 @@ export function derivePendingApprovals(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingApproval[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
||||
const ordered = orderActivities(activities);
|
||||
|
||||
for (const activity of ordered) {
|
||||
const payload =
|
||||
@@ -462,7 +462,7 @@ export function derivePendingUserInputs(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): PendingUserInput[] {
|
||||
const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
||||
const ordered = orderActivities(activities);
|
||||
|
||||
for (const activity of ordered) {
|
||||
const payload =
|
||||
@@ -511,7 +511,7 @@ export function deriveActivePlanState(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
latestTurnId: TurnId | undefined,
|
||||
): ActivePlanState | null {
|
||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
||||
const ordered = orderActivities(activities);
|
||||
const allPlanActivities = ordered.filter((activity) => activity.kind === "turn.plan.updated");
|
||||
// Prefer plan from the current turn; fall back to the most recent plan from any turn
|
||||
// so that TodoWrite tasks persist across follow-up messages.
|
||||
@@ -627,7 +627,7 @@ export function hasActionableProposedPlan(
|
||||
export function deriveWorkLogEntries(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
||||
const ordered = orderActivities(activities);
|
||||
const entries: DerivedWorkLogEntry[] = [];
|
||||
for (const activity of ordered) {
|
||||
if (activity.kind === "tool.started") continue;
|
||||
@@ -1296,6 +1296,35 @@ function extractChangedFiles(payload: Record<string, unknown> | null): string[]
|
||||
return changedFiles;
|
||||
}
|
||||
|
||||
// Several independent derivations (work log, pending approvals, pending user
|
||||
// inputs, active plan) order the same activities array per render. The reducer
|
||||
// appends in order, so the input is almost always already sorted — detect that
|
||||
// in O(n) and share the result per array identity instead of copying and
|
||||
// re-sorting the whole history in each derivation.
|
||||
const orderedActivitiesCache = new WeakMap<
|
||||
ReadonlyArray<OrchestrationThreadActivity>,
|
||||
ReadonlyArray<OrchestrationThreadActivity>
|
||||
>();
|
||||
|
||||
function orderActivities(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
const cached = orderedActivitiesCache.get(activities);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
let isSorted = true;
|
||||
for (let index = 1; index < activities.length; index += 1) {
|
||||
if (compareActivitiesByOrder(activities[index - 1]!, activities[index]!) > 0) {
|
||||
isSorted = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const ordered = isSorted ? activities : [...activities].toSorted(compareActivitiesByOrder);
|
||||
orderedActivitiesCache.set(activities, ordered);
|
||||
return ordered;
|
||||
}
|
||||
|
||||
function compareActivitiesByOrder(
|
||||
left: OrchestrationThreadActivity,
|
||||
right: OrchestrationThreadActivity,
|
||||
@@ -1337,6 +1366,42 @@ function compareActivityLifecycleRank(kind: string): number {
|
||||
return 1;
|
||||
}
|
||||
|
||||
function isSortedByCreatedAt(rows: ReadonlyArray<TimelineEntry>): boolean {
|
||||
for (let index = 1; index < rows.length; index += 1) {
|
||||
if (rows[index - 1]!.createdAt.localeCompare(rows[index]!.createdAt) > 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stable k-way merge of per-kind rows that are each already in createdAt order
|
||||
// (the reducers maintain that invariant). Equal timestamps keep the same order
|
||||
// a stable sort of the concatenation would produce.
|
||||
function mergeTimelineRows(sources: ReadonlyArray<ReadonlyArray<TimelineEntry>>): TimelineEntry[] {
|
||||
const merged: TimelineEntry[] = [];
|
||||
const cursors = sources.map(() => 0);
|
||||
const total = sources.reduce((sum, rows) => sum + rows.length, 0);
|
||||
while (merged.length < total) {
|
||||
let nextSource = -1;
|
||||
for (let index = 0; index < sources.length; index += 1) {
|
||||
const candidate = sources[index]![cursors[index]!];
|
||||
if (candidate === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
nextSource === -1 ||
|
||||
candidate.createdAt.localeCompare(sources[nextSource]![cursors[nextSource]!]!.createdAt) < 0
|
||||
) {
|
||||
nextSource = index;
|
||||
}
|
||||
}
|
||||
merged.push(sources[nextSource]![cursors[nextSource]!]!);
|
||||
cursors[nextSource] = cursors[nextSource]! + 1;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function deriveTimelineEntries(
|
||||
messages: ReadonlyArray<ChatMessage>,
|
||||
proposedPlans: ReadonlyArray<ProposedPlan>,
|
||||
@@ -1360,9 +1425,10 @@ export function deriveTimelineEntries(
|
||||
createdAt: entry.createdAt,
|
||||
entry,
|
||||
}));
|
||||
return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) =>
|
||||
a.createdAt.localeCompare(b.createdAt),
|
||||
);
|
||||
const sources = [messageRows, proposedPlanRows, workRows];
|
||||
return sources.every(isSortedByCreatedAt)
|
||||
? mergeTimelineRows(sources)
|
||||
: sources.flat().toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
|
||||
}
|
||||
|
||||
export function inferCheckpointTurnCountByTurnId(
|
||||
|
||||
Reference in new issue
Block a user