Optimize thread navigation render work

This commit is contained in:
Ben Davis committed 2026-05-06 16:08:27 -07:00
1 parent 357211864c
commit bb538d76c5
7 files changed
+259 -140

No files matched your search

+141 -101
View File
@@ -1,11 +1,9 @@
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
import { CheckIcon, CopyIcon } from "lucide-react";
import React, {
import {
Children,
Suspense,
type MouseEvent as ReactMouseEvent,
isValidElement,
use,
useCallback,
memo,
useEffect,
@@ -34,27 +32,6 @@ import {
import { readLocalApi } from "../localApi";
import { cn } from "../lib/utils";
class CodeHighlightErrorBoundary extends React.Component<
{ fallback: ReactNode; children: ReactNode },
{ hasError: boolean }
> {
constructor(props: { fallback: ReactNode; children: ReactNode }) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
override render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
interface ChatMarkdownProps {
text: string;
cwd: string | undefined;
@@ -69,12 +46,26 @@ const highlightedCodeCache = new LRUCache<string>(
MAX_HIGHLIGHT_CACHE_MEMORY_BYTES,
);
const highlighterPromiseCache = new Map<string, Promise<DiffsHighlighter>>();
const unsupportedHighlightLanguages = new Set<string>();
const HIGHLIGHT_LANGUAGE_ALIASES: Readonly<Record<string, string>> = {
baml: "text",
gitignore: "ini",
plaintext: "text",
txt: "text",
};
function normalizeHighlightLanguage(language: string): string {
const normalizedLanguage = language.trim().toLowerCase();
if (!normalizedLanguage) {
return "text";
}
return HIGHLIGHT_LANGUAGE_ALIASES[normalizedLanguage] ?? normalizedLanguage;
}
function extractFenceLanguage(className: string | undefined): string {
const match = className?.match(CODE_FENCE_LANGUAGE_REGEX);
const raw = match?.[1] ?? "text";
// Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
return raw === "gitignore" ? "ini" : raw;
return normalizeHighlightLanguage(raw);
}
function nodeToPlainText(node: ReactNode): string {
@@ -121,27 +112,70 @@ function estimateHighlightedSize(html: string, code: string): number {
}
function getHighlighterPromise(language: string, themeName: string): Promise<DiffsHighlighter> {
const cacheKey = `${language}:${themeName}`;
const highlighterLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
const cacheKey = `${highlighterLanguage}:${themeName}`;
const cached = highlighterPromiseCache.get(cacheKey);
if (cached) return cached;
const promise = getSharedHighlighter({
themes: [themeName],
langs: [language as SupportedLanguages],
langs: [highlighterLanguage as SupportedLanguages],
preferredHighlighter: "shiki-js",
}).catch((err) => {
highlighterPromiseCache.delete(cacheKey);
if (language === "text") {
if (highlighterLanguage === "text") {
// "text" itself failed — Shiki cannot initialize at all, surface the error
throw err;
}
// Language not supported by Shiki — fall back to "text"
unsupportedHighlightLanguages.add(highlighterLanguage);
return getHighlighterPromise("text", themeName);
});
highlighterPromiseCache.set(cacheKey, promise);
return promise;
}
function renderHighlightedHtml(
highlighter: DiffsHighlighter,
code: string,
language: string,
themeName: string,
): string {
const highlightLanguage = unsupportedHighlightLanguages.has(language) ? "text" : language;
try {
return highlighter.codeToHtml(code, {
lang: highlightLanguage as SupportedLanguages,
theme: themeName,
});
} catch (error) {
if (highlightLanguage === "text") {
throw error;
}
unsupportedHighlightLanguages.add(highlightLanguage);
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
}
}
function scheduleHighlightWork(callback: () => void): () => void {
if (typeof window === "undefined") {
callback();
return () => undefined;
}
const idleWindow = window as Window & {
requestIdleCallback?: (callback: () => void, options?: { timeout: number }) => number;
cancelIdleCallback?: (handle: number) => void;
};
if (idleWindow.requestIdleCallback && idleWindow.cancelIdleCallback) {
const idleHandle = idleWindow.requestIdleCallback(callback, { timeout: 1500 });
return () => idleWindow.cancelIdleCallback?.(idleHandle);
}
const timeoutHandle = window.setTimeout(callback, 0);
return () => window.clearTimeout(timeoutHandle);
}
function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNode }) {
const [copied, setCopied] = useState(false);
const copiedTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
@@ -190,88 +224,97 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
);
}
interface SuspenseShikiCodeBlockProps {
interface ShikiCodeBlockProps {
className: string | undefined;
code: string;
themeName: string;
isStreaming: boolean;
fallback: ReactNode;
}
function SuspenseShikiCodeBlock({
type HighlightedCodeState = {
cacheKey: string;
html: string;
};
function ShikiCodeBlock({
className,
code,
themeName,
isStreaming,
}: SuspenseShikiCodeBlockProps) {
fallback,
}: ShikiCodeBlockProps) {
const language = extractFenceLanguage(className);
const cacheKey = createHighlightCacheKey(code, language, themeName);
const cachedHighlightedHtml = !isStreaming ? highlightedCodeCache.get(cacheKey) : null;
const [highlightedCode, setHighlightedCode] = useState<HighlightedCodeState | null>(() => {
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
return cachedHighlightedHtml == null ? null : { cacheKey, html: cachedHighlightedHtml };
});
if (cachedHighlightedHtml != null) {
return (
<div
className="chat-markdown-shiki"
dangerouslySetInnerHTML={{ __html: cachedHighlightedHtml }}
/>
);
useEffect(() => {
if (isStreaming) {
setHighlightedCode(null);
return;
}
const cachedHighlightedHtml = highlightedCodeCache.get(cacheKey);
if (cachedHighlightedHtml != null) {
setHighlightedCode({ cacheKey, html: cachedHighlightedHtml });
return;
}
let isCancelled = false;
let cancelHighlightWork: (() => void) | null = null;
setHighlightedCode(null);
void getHighlighterPromise(language, themeName)
.then((highlighter) => {
if (isCancelled) return;
cancelHighlightWork = scheduleHighlightWork(() => {
if (isCancelled) return;
let highlightedHtml: string;
try {
highlightedHtml = renderHighlightedHtml(highlighter, code, language, themeName);
} catch {
return;
}
if (isCancelled) return;
highlightedCodeCache.set(
cacheKey,
highlightedHtml,
estimateHighlightedSize(highlightedHtml, code),
);
setHighlightedCode({ cacheKey, html: highlightedHtml });
});
})
.catch(() => {
if (!isCancelled) {
setHighlightedCode(null);
}
});
return () => {
isCancelled = true;
cancelHighlightWork?.();
};
}, [cacheKey, code, isStreaming, language, themeName]);
const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache.get(cacheKey);
const activeHighlightedHtml =
cachedHighlightedHtml ?? (highlightedCode?.cacheKey === cacheKey ? highlightedCode.html : null);
if (activeHighlightedHtml == null) {
return <>{fallback}</>;
}
return (
<UncachedShikiCodeBlock
code={code}
language={language}
themeName={themeName}
cacheKey={cacheKey}
isStreaming={isStreaming}
<div
className="chat-markdown-shiki"
dangerouslySetInnerHTML={{ __html: activeHighlightedHtml }}
/>
);
}
interface UncachedShikiCodeBlockProps {
code: string;
language: string;
themeName: string;
cacheKey: string;
isStreaming: boolean;
}
function UncachedShikiCodeBlock({
code,
language,
themeName,
cacheKey,
isStreaming,
}: UncachedShikiCodeBlockProps) {
const highlighter = use(getHighlighterPromise(language, themeName));
const highlightedHtml = useMemo(() => {
try {
return highlighter.codeToHtml(code, { lang: language, 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
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
}
}, [code, highlighter, language, themeName]);
useEffect(() => {
if (!isStreaming) {
highlightedCodeCache.set(
cacheKey,
highlightedHtml,
estimateHighlightedSize(highlightedHtml, code),
);
}
}, [cacheKey, code, highlightedHtml, isStreaming]);
return (
<div className="chat-markdown-shiki" dangerouslySetInnerHTML={{ __html: highlightedHtml }} />
);
}
interface MarkdownFileLinkProps {
href: string;
targetPath: string;
@@ -576,16 +619,13 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
return (
<MarkdownCodeBlock code={codeBlock.code}>
<CodeHighlightErrorBoundary fallback={<pre {...props}>{children}</pre>}>
<Suspense fallback={<pre {...props}>{children}</pre>}>
<SuspenseShikiCodeBlock
className={codeBlock.className}
code={codeBlock.code}
themeName={codeBlockThemeName}
isStreaming={isStreaming}
/>
</Suspense>
</CodeHighlightErrorBoundary>
<ShikiCodeBlock
className={codeBlock.className}
code={codeBlock.code}
themeName={codeBlockThemeName}
isStreaming={isStreaming}
fallback={<pre {...props}>{children}</pre>}
/>
</MarkdownCodeBlock>
);
},
+2 -5
View File
@@ -116,7 +116,7 @@ import {
} from "~/projectScripts";
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
import { useSettings } from "../hooks/useSettings";
import { useProjectGroupingSettings, useSettings } from "../hooks/useSettings";
import { resolveAppModelSelectionForInstance } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import { deriveLogicalProjectKeyFromSettings } from "../logicalProject";
@@ -941,10 +941,7 @@ export default function ChatView(props: ChatViewProps) {
},
[],
);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const projectGroupingSettings = useProjectGroupingSettings();
const logicalProjectEnvironments = useMemo(() => {
if (!activeProject) return [];
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
+3 -9
View File
@@ -166,7 +166,7 @@ import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { CommandDialogTrigger } from "./ui/command";
import { readEnvironmentApi } from "../environmentApi";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { useProjectGroupingSettings, useSettings, useUpdateSettings } from "~/hooks/useSettings";
import { useServerKeybindings } from "../rpc/serverState";
import {
derivePhysicalProjectKey,
@@ -930,10 +930,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
const defaultThreadEnvMode = useSettings<ThreadEnvMode>(
(settings) => settings.defaultThreadEnvMode,
);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const projectGroupingSettings = useProjectGroupingSettings();
const { updateSettings } = useUpdateSettings();
const router = useRouter();
const { isMobile, setOpenMobile } = useSidebar();
@@ -2724,10 +2721,7 @@ export default function Sidebar() {
const sidebarThreadSortOrder = useSettings((s) => s.sidebarThreadSortOrder);
const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder);
const sidebarProjectGroupingMode = useSettings((s) => s.sidebarProjectGroupingMode);
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const projectGroupingSettings = useProjectGroupingSettings();
const { updateSettings } = useUpdateSettings();
const { handleNewThread } = useNewThreadHandler();
const { archiveThread, deleteThread } = useThreadActions();
+2 -5
View File
@@ -15,14 +15,11 @@ import { selectProjectsAcrossEnvironments, useStore } from "../store";
import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { useUiStateStore } from "../uiStateStore";
import { useSettings } from "./useSettings";
import { useProjectGroupingSettings } from "./useSettings";
function useNewThreadState() {
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const projectGroupingSettings = useProjectGroupingSettings();
const router = useRouter();
const getCurrentRouteTarget = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
+19
View File
@@ -22,6 +22,7 @@ import { ensureLocalApi } from "~/localApi";
import { Struct } from "effect";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
import type { ProjectGroupingSettings } from "~/logicalProject";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
@@ -31,6 +32,11 @@ let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
let clientSettingsHydrated = false;
let clientSettingsHydrationPromise: Promise<void> | null = null;
const selectSidebarProjectGroupingMode = (settings: UnifiedSettings) =>
settings.sidebarProjectGroupingMode;
const selectSidebarProjectGroupingOverrides = (settings: UnifiedSettings) =>
settings.sidebarProjectGroupingOverrides;
function emitClientSettingsChange() {
for (const listener of clientSettingsListeners) {
listener();
@@ -186,6 +192,19 @@ export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings)
return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
}
export function useProjectGroupingSettings(): ProjectGroupingSettings {
const sidebarProjectGroupingMode = useSettings(selectSidebarProjectGroupingMode);
const sidebarProjectGroupingOverrides = useSettings(selectSidebarProjectGroupingOverrides);
return useMemo(
() => ({
sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides,
}),
[sidebarProjectGroupingMode, sidebarProjectGroupingOverrides],
);
}
/**
* Returns an updater that routes each key to the correct backing store.
*
+82 -14
View File
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useSyncExternalStore } from "react";
import { useCallback, useSyncExternalStore } from "react";
import type {
DesktopTheme,
DiscoveredColorTheme,
@@ -30,6 +30,10 @@ const DYNAMIC_THEME_COLOR_SELECTOR = `meta[name="${THEME_COLOR_META_NAME}"][data
let listeners: Array<() => void> = [];
let lastSnapshot: ThemeSnapshot | null = null;
let lastDesktopTheme: DesktopTheme | null = null;
let themeRuntimeRefCount = 0;
let stopThemeRuntime: (() => void) | null = null;
let refreshThemesPromise: Promise<void> | null = null;
const preferenceLoadPromises = new Map<string, Promise<void>>();
let state: ThemeSnapshot = {
preference: DEFAULT_THEME_PREFERENCE,
systemDark: false,
@@ -121,6 +125,19 @@ function isSamePreference(a: ThemePreference, b: ThemePreference) {
return true;
}
function themePreferenceKey(preference: ThemePreference) {
switch (preference.mode) {
case "builtin":
return `builtin:${preference.theme}`;
case "external":
return `external:${preference.themeId}`;
case "follow-editor":
return `follow-editor:${preference.source}`;
case "system":
return "system";
}
}
function ensureThemeColorMetaTag(): HTMLMetaElement {
let element = document.querySelector<HTMLMetaElement>(DYNAMIC_THEME_COLOR_SELECTOR);
if (element) return element;
@@ -177,7 +194,7 @@ function clearExternalThemeVariables(root: HTMLElement) {
function syncDesktopTheme(theme: DesktopTheme) {
if (typeof window === "undefined") return;
const bridge = window.desktopBridge;
if (!bridge || lastDesktopTheme === theme) return;
if (!bridge?.setTheme || lastDesktopTheme === theme) return;
lastDesktopTheme = theme;
void bridge.setTheme(theme).catch(() => {
@@ -188,7 +205,7 @@ function syncDesktopTheme(theme: DesktopTheme) {
function syncDesktopWindowColors(theme: ResolvedColorTheme | null) {
if (typeof window === "undefined") return;
const bridge = window.desktopBridge;
if (!bridge || !theme) return;
if (!bridge?.setWindowThemeColors || !theme) return;
const backgroundColor =
theme.appVariables["--app-chrome-background"] ??
theme.appVariables["--background"] ??
@@ -275,7 +292,7 @@ function recomputeSnapshot(next: Partial<ThemeSnapshot> = {}) {
async function loadPreference(preference: ThemePreference, suppressTransitions = true) {
if (preference.mode === "external") {
const bridge = window.desktopBridge;
if (!bridge) {
if (!bridge?.loadColorTheme) {
recomputeSnapshot({
preference,
resolvedColorTheme: null,
@@ -325,9 +342,27 @@ async function loadPreference(preference: ThemePreference, suppressTransitions =
applyResolvedTheme(null, suppressTransitions);
}
async function refreshThemes() {
function loadThemePreference(preference: ThemePreference, suppressTransitions = true) {
const key = themePreferenceKey(preference);
const existing = preferenceLoadPromises.get(key);
if (existing) return existing;
const promise = loadPreference(preference, suppressTransitions).finally(() => {
if (preferenceLoadPromises.get(key) === promise) {
preferenceLoadPromises.delete(key);
}
});
preferenceLoadPromises.set(key, promise);
return promise;
}
function loadStoredPreference(suppressTransitions = true) {
return loadThemePreference(getStoredPreference(), suppressTransitions);
}
async function refreshThemesNow() {
const bridge = typeof window !== "undefined" ? window.desktopBridge : null;
if (!bridge) {
if (!bridge?.discoverColorThemes) {
recomputeSnapshot({
discoveredThemes: [],
status: "ready",
@@ -344,6 +379,15 @@ async function refreshThemes() {
}
}
export function refreshThemes() {
if (refreshThemesPromise) return refreshThemesPromise;
refreshThemesPromise = refreshThemesNow().finally(() => {
refreshThemesPromise = null;
});
return refreshThemesPromise;
}
function bootstrapCachedTheme() {
if (!hasThemeStorage()) return null;
const raw = localStorage.getItem(BOOTSTRAP_THEME_CACHE_KEY);
@@ -380,6 +424,12 @@ function subscribe(listener: () => void): () => void {
if (typeof window === "undefined") return () => {};
listeners.push(listener);
return () => {
listeners = listeners.filter((l) => l !== listener);
};
}
function startThemeRuntimeUnsafe() {
const mq = window.matchMedia(MEDIA_QUERY);
const handleChange = () => {
recomputeSnapshot();
@@ -389,24 +439,47 @@ function subscribe(listener: () => void): () => void {
const handleStorage = (e: StorageEvent) => {
if (e.key === STORAGE_KEY || e.key === PREFERENCE_STORAGE_KEY) {
void loadPreference(getStoredPreference(), true);
void loadStoredPreference(true);
}
};
window.addEventListener("storage", handleStorage);
void loadStoredPreference(false).finally(() => {
void refreshThemes();
});
return () => {
listeners = listeners.filter((l) => l !== listener);
mq.removeEventListener("change", handleChange);
window.removeEventListener("storage", handleStorage);
};
}
export function startThemeRuntime() {
if (typeof window === "undefined") return () => {};
themeRuntimeRefCount += 1;
if (themeRuntimeRefCount === 1) {
stopThemeRuntime = startThemeRuntimeUnsafe();
}
let released = false;
return () => {
if (released) return;
released = true;
themeRuntimeRefCount = Math.max(0, themeRuntimeRefCount - 1);
if (themeRuntimeRefCount === 0) {
stopThemeRuntime?.();
stopThemeRuntime = null;
}
};
}
export function useTheme() {
const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);
const setThemePreference = useCallback((preference: ThemePreference) => {
setStoredPreference(preference);
void loadPreference(preference, true);
void loadThemePreference(preference, true);
}, []);
const setTheme = useCallback(
@@ -416,11 +489,6 @@ export function useTheme() {
[setThemePreference],
);
useEffect(() => {
void refreshThemes();
void loadPreference(getStoredPreference(), false);
}, []);
return {
theme: preferenceToBuiltInTheme(snapshot.preference),
setTheme,
+10 -6
View File
@@ -29,7 +29,7 @@ import {
} from "../components/ui/toast";
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { readLocalApi } from "../localApi";
import { useSettings } from "../hooks/useSettings";
import { useProjectGroupingSettings } from "../hooks/useSettings";
import {
deriveLogicalProjectKeyFromSettings,
derivePhysicalProjectKeyFromPath,
@@ -44,7 +44,7 @@ import {
} from "../rpc/serverState";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import { syncBrowserChromeTheme } from "../hooks/useTheme";
import { startThemeRuntime, syncBrowserChromeTheme } from "../hooks/useTheme";
import {
ensureEnvironmentConnectionBootstrapped,
getPrimaryEnvironmentConnection,
@@ -133,6 +133,7 @@ function RootRouteView() {
<AnchoredToastProvider>
{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}
{primaryEnvironmentAuthenticated ? <ServerStateBootstrap /> : null}
<ThemeRuntimeBootstrap />
<EnvironmentConnectionManagerBootstrap />
<SshPasswordPromptDialog />
<HostedStaticEnvironmentBootstrap />
@@ -259,6 +260,12 @@ function ServerStateBootstrap() {
return null;
}
function ThemeRuntimeBootstrap() {
useEffect(() => startThemeRuntime(), []);
return null;
}
function AuthenticatedTracingBootstrap() {
useEffect(() => {
void configureClientTracing();
@@ -281,10 +288,7 @@ function EventRouter() {
const setActiveEnvironmentId = useStore((store) => store.setActiveEnvironmentId);
const navigate = useNavigate();
const pathname = useLocation({ select: (loc) => loc.pathname });
const projectGroupingSettings = useSettings((settings) => ({
sidebarProjectGroupingMode: settings.sidebarProjectGroupingMode,
sidebarProjectGroupingOverrides: settings.sidebarProjectGroupingOverrides,
}));
const projectGroupingSettings = useProjectGroupingSettings();
const readPathname = useEffectEvent(() => pathname);
const handledBootstrapThreadIdRef = useRef<string | null>(null);
const seenServerConfigUpdateIdRef = useRef(getServerConfigUpdatedNotification()?.id ?? 0);