Skip to content

Commit bb538d7

Browse files
committed
Optimize thread navigation render work
1 parent 3572118 commit bb538d7

7 files changed

Lines changed: 257 additions & 138 deletions

File tree

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 139 additions & 99 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
22
import { CheckIcon, CopyIcon } from "lucide-react";
3-
import React, {
3+
import {
44
Children,
5-
Suspense,
65
type MouseEvent as ReactMouseEvent,
76
isValidElement,
8-
use,
97
useCallback,
108
memo,
119
useEffect,
@@ -34,27 +32,6 @@ import {
3432
import { readLocalApi } from "../localApi";
3533
import { cn } from "../lib/utils";
3634

37-
class CodeHighlightErrorBoundary extends React.Component<
38-
{ fallback: ReactNode; children: ReactNode },
39-
{ hasError: boolean }
40-
> {
41-
constructor(props: { fallback: ReactNode; children: ReactNode }) {
42-
super(props);
43-
this.state = { hasError: false };
44-
}
45-
46-
static getDerivedStateFromError() {
47-
return { hasError: true };
48-
}
49-
50-
override render() {
51-
if (this.state.hasError) {
52-
return this.props.fallback;
53-
}
54-
return this.props.children;
55-
}
56-
}
57-
5835
interface ChatMarkdownProps {
5936
text: string;
6037
cwd: string | undefined;
@@ -69,12 +46,26 @@ const highlightedCodeCache = new LRUCache<string>(
6946
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
7047
);
7148
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
49+
const unsupportedHighlightLanguages = new Set<string>();
50+
const HIGHLIGHT_LANGUAGE_ALIASES: Readonly<Record<string, string>> = {
51+
baml: "text",
52+
gitignore: "ini",
53+
plaintext: "text",
54+
txt: "text",
55+
};
56+
57+
function normalizeHighlightLanguage(language: string): string {
58+
const normalizedLanguage = language.trim().toLowerCase();
59+
if (!normalizedLanguage) {
60+
return "text";
61+
}
62+
return HIGHLIGHT_LANGUAGE_ALIASES[normalizedLanguage] ?? normalizedLanguage;
63+
}
7264

7365
function extractFenceLanguage(className: string | undefined): string {
7466
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
7567
const raw = match?.[1] ?? "text";
76-
// Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
77-
return raw === "gitignore" ? "ini" : raw;
68+
return normalizeHighlightLanguage(raw);
7869
}
7970

8071
function nodeToPlainText(node: ReactNode): string {
@@ -121,27 +112,70 @@ function estimateHighlightedSize(html: string, code: string): number {
121112
}
122113

123114
function getHighlighterPromise(language: string, themeName: string): Promise<DiffsHighlighter> {
124-
const cacheKey = `${language}:${themeName}`;
115+
const highlighterLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
116+
const cacheKey = `${highlighterLanguage}:${themeName}`;
125117
const cached = highlighterPromiseCache.get(cacheKey);
126118
if (cached) return cached;
127119

128120
const promise = getSharedHighlighter({
129121
themes: [themeName],
130-
langs: [language as SupportedLanguages],
122+
langs: [highlighterLanguage as SupportedLanguages],
131123
preferredHighlighter: "shiki-js",
132124
}).catch((err) => {
133125
highlighterPromiseCache.delete(cacheKey);
134-
if (language === "text") {
126+
if (highlighterLanguage === "text") {
135127
// "text" itself failed — Shiki cannot initialize at all, surface the error
136128
throw err;
137129
}
138130
// Language not supported by Shiki — fall back to "text"
131+
unsupportedHighlightLanguages.add(highlighterLanguage);
139132
return getHighlighterPromise("text", themeName);
140133
});
141134
highlighterPromiseCache.set(cacheKey, promise);
142135
return promise;
143136
}
144137

138+
function renderHighlightedHtml(
139+
highlighter: DiffsHighlighter,
140+
code: string,
141+
language: string,
142+
themeName: string,
143+
): string {
144+
const highlightLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
145+
try {
146+
return highlighter.codeToHtml(code, {
147+
lang: highlightLanguage as SupportedLanguages,
148+
theme: themeName,
149+
});
150+
} catch (error) {
151+
if (highlightLanguage === "text") {
152+
throw error;
153+
}
154+
unsupportedHighlightLanguages.add(highlightLanguage);
155+
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
156+
}
157+
}
158+
159+
function scheduleHighlightWork(callback: () => void): () => void {
160+
if (typeof window === "undefined") {
161+
callback();
162+
return () => undefined;
163+
}
164+
165+
const idleWindow = window as Window & {
166+
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
167+
cancelIdleCallback?: (handle: number) => void;
168+
};
169+
170+
if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {
171+
const idleHandle = idleWindow.requestIdleCallback(callback, { timeout: 1500 });
172+
return () => idleWindow.cancelIdleCallback?.(idleHandle);
173+
}
174+
175+
const timeoutHandle = window.setTimeout(callback, 0);
176+
return () => window.clearTimeout(timeoutHandle);
177+
}
178+
145179
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
146180
const [copied, setCopied] = useState(false);
147181
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -190,85 +224,94 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
190224
);
191225
}
192226

193-
interface SuspenseShikiCodeBlockProps {
227+
interface ShikiCodeBlockProps {
194228
className: string | undefined;
195229
code: string;
196230
themeName: string;
197231
isStreaming: boolean;
232+
fallback: ReactNode;
198233
}
199234

200-
function SuspenseShikiCodeBlock({
235+
type HighlightedCodeState = {
236+
cacheKey: string;
237+
html: string;
238+
};
239+
240+
function ShikiCodeBlock({
201241
className,
202242
code,
203243
themeName,
204244
isStreaming,
205-
}: SuspenseShikiCodeBlockProps) {
245+
fallback,
246+
}: ShikiCodeBlockProps) {
206247
const language = extractFenceLanguage(className);
207248
const cacheKey = createHighlightCacheKey(code, language, themeName);
208-
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
249+
const [highlightedCode, setHighlightedCode] = useState<HighlightedCodeState | null>(() => {
250+
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
251+
return cachedHighlightedHtml == null ? null : { cacheKey, html: cachedHighlightedHtml };
252+
});
209253

210-
if (cachedHighlightedHtml != null) {
211-
return (
212-
<div
213-
className="chat-markdown-shiki"
214-
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
215-
/>
216-
);
217-
}
254+
useEffect(() => {
255+
if (isStreaming) {
256+
setHighlightedCode(null);
257+
return;
258+
}
218259

219-
return (
220-
<UncachedShikiCodeBlock
221-
code={code}
222-
language={language}
223-
themeName={themeName}
224-
cacheKey={cacheKey}
225-
isStreaming={isStreaming}
226-
/>
227-
);
228-
}
260+
const cachedHighlightedHtml = highlightedCodeCache.get(cacheKey);
261+
if (cachedHighlightedHtml != null) {
262+
setHighlightedCode({ cacheKey, html: cachedHighlightedHtml });
263+
return;
264+
}
229265

230-
interface UncachedShikiCodeBlockProps {
231-
code: string;
232-
language: string;
233-
themeName: string;
234-
cacheKey: string;
235-
isStreaming: boolean;
236-
}
266+
let isCancelled = false;
267+
let cancelHighlightWork: (() => void) | null = null;
268+
setHighlightedCode(null);
269+
270+
void getHighlighterPromise(language, themeName)
271+
.then((highlighter) => {
272+
if (isCancelled) return;
273+
cancelHighlightWork = scheduleHighlightWork(() => {
274+
if (isCancelled) return;
275+
let highlightedHtml: string;
276+
try {
277+
highlightedHtml = renderHighlightedHtml(highlighter, code, language, themeName);
278+
} catch {
279+
return;
280+
}
281+
if (isCancelled) return;
282+
highlightedCodeCache.set(
283+
cacheKey,
284+
highlightedHtml,
285+
estimateHighlightedSize(highlightedHtml, code),
286+
);
287+
setHighlightedCode({ cacheKey, html: highlightedHtml });
288+
});
289+
})
290+
.catch(() => {
291+
if (!isCancelled) {
292+
setHighlightedCode(null);
293+
}
294+
});
237295

238-
function UncachedShikiCodeBlock({
239-
code,
240-
language,
241-
themeName,
242-
cacheKey,
243-
isStreaming,
244-
}: UncachedShikiCodeBlockProps) {
245-
const highlighter = use(getHighlighterPromise(language, themeName));
246-
const highlightedHtml = useMemo(() => {
247-
try {
248-
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
249-
} catch (error) {
250-
// Log highlighting failures for debugging while falling back to plain text
251-
console.warn(
252-
`Code highlighting failed for language "${language}", falling back to plain text.`,
253-
error instanceof Error ? error.message : error,
254-
);
255-
// If highlighting fails for this language, render as plain text
256-
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
257-
}
258-
}, [code, highlighter, language, themeName]);
296+
return () => {
297+
isCancelled = true;
298+
cancelHighlightWork?.();
299+
};
300+
}, [cacheKey, code, isStreaming, language, themeName]);
259301

260-
useEffect(() => {
261-
if (!isStreaming) {
262-
highlightedCodeCache.set(
263-
cacheKey,
264-
highlightedHtml,
265-
estimateHighlightedSize(highlightedHtml, code),
266-
);
267-
}
268-
}, [cacheKey, code, highlightedHtml, isStreaming]);
302+
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
303+
const activeHighlightedHtml =
304+
cachedHighlightedHtml ?? (highlightedCode?.cacheKey === cacheKey ? highlightedCode.html : null);
305+
306+
if (activeHighlightedHtml == null) {
307+
return <>{fallback}</>;
308+
}
269309

270310
return (
271-
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
311+
<div
312+
className="chat-markdown-shiki"
313+
dangerouslySetInnerHTML={{ __html: activeHighlightedHtml }}
314+
/>
272315
);
273316
}
274317

@@ -576,16 +619,13 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
576619

577620
return (
578621
<MarkdownCodeBlock code={codeBlock.code}>
579-
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
580-
<Suspense fallback={<pre {...props}>{children}</pre>}>
581-
<SuspenseShikiCodeBlock
582-
className={codeBlock.className}
583-
code={codeBlock.code}
584-
themeName={codeBlockThemeName}
585-
isStreaming={isStreaming}
586-
/>
587-
</Suspense>
588-
</CodeHighlightErrorBoundary>
622+
<ShikiCodeBlock
623+
className={codeBlock.className}
624+
code={codeBlock.code}
625+
themeName={codeBlockThemeName}
626+
isStreaming={isStreaming}
627+
fallback={<pre {...props}>{children}</pre>}
628+
/>
589629
</MarkdownCodeBlock>
590630
);
591631
},

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ import {
116116
} from "~/projectScripts";
117117
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
118118
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
119-
import { useSettings } from "../hooks/useSettings";
119+
import { useProjectGroupingSettings, useSettings } from "../hooks/useSettings";
120120
import { resolveAppModelSelectionForInstance } from "../modelSelection";
121121
import { isTerminalFocused } from "../lib/terminalFocus";
122122
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
@@ -941,10 +941,7 @@ export default function ChatView(props: ChatViewProps) {
941941
},
942942
[],
943943
);
944-
const projectGroupingSettings = useSettings((settings) => ({
945-
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
946-
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
947-
}));
944+
const projectGroupingSettings = useProjectGroupingSettings();
948945
const logicalProjectEnvironments = useMemo(() => {
949946
if (!activeProject) return [];
950947
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);

‎apps/web/src/components/Sidebar.tsx‎

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
166166
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
167167
import { CommandDialogTrigger } from "./ui/command";
168168
import { readEnvironmentApi } from "../environmentApi";
169-
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
169+
import { useProjectGroupingSettings, useSettings, useUpdateSettings } from "~/hooks/useSettings";
170170
import { useServerKeybindings } from "../rpc/serverState";
171171
import {
172172
derivePhysicalProjectKey,
@@ -930,10 +930,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
930930
const defaultThreadEnvMode = useSettings<ThreadEnvMode>(
931931
(settings) => settings.defaultThreadEnvMode,
932932
);
933-
const projectGroupingSettings = useSettings((settings) => ({
934-
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
935-
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
936-
}));
933+
const projectGroupingSettings = useProjectGroupingSettings();
937934
const { updateSettings } = useUpdateSettings();
938935
const router = useRouter();
939936
const { isMobile, setOpenMobile } = useSidebar();
@@ -2724,10 +2721,7 @@ export default function Sidebar() {
27242721
const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder);
27252722
const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder);
27262723
const sidebarProjectGroupingMode = useSettings((s) => s.sidebarProjectGroupingMode);
2727-
const projectGroupingSettings = useSettings((settings) => ({
2728-
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
2729-
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
2730-
}));
2724+
const projectGroupingSettings = useProjectGroupingSettings();
27312725
const { updateSettings } = useUpdateSettings();
27322726
const { handleNewThread } = useNewThreadHandler();
27332727
const { archiveThread, deleteThread } = useThreadActions();

‎apps/web/src/hooks/useHandleNewThread.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,14 +15,11 @@ import { selectProjectsAcrossEnvironments, useStore } from "../store";
1515
import { createThreadSelectorByRef } from "../storeSelectors";
1616
import { resolveThreadRouteTarget } from "../threadRoutes";
1717
import { useUiStateStore } from "../uiStateStore";
18-
import { useSettings } from "./useSettings";
18+
import { useProjectGroupingSettings } from "./useSettings";
1919

2020
function useNewThreadState() {
2121
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
22-
const projectGroupingSettings = useSettings((settings) => ({
23-
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
24-
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
25-
}));
22+
const projectGroupingSettings = useProjectGroupingSettings();
2623
const router = useRouter();
2724
const getCurrentRouteTarget = useCallback(() => {
2825
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};

0 commit comments

Comments
 (0)