TypeScript
refactor(web): terminal output no longer re-renders the drawer, theme search runs from handlers (#25458)
Julius Marminge28df7a246f9f
diff --git a/apps/web/src/components/ThreadTerminalDrawer.test.ts b/apps/web/src/components/ThreadTerminalDrawer.test.tsindex 82b58e859f6..9979d3563ff 100644--- a/apps/web/src/components/ThreadTerminalDrawer.test.ts+++ b/apps/web/src/components/ThreadTerminalDrawer.test.ts@@ -11,6 +11,7 @@ import {shouldClearTerminalSelectionAction,shouldHandleTerminalExit,synchronizeTerminalOutput,+ synchronizeTerminalSession,} from "./ThreadTerminalDrawer";describe("terminal selection actions", () => {@@ -87,3 +88,16 @@ it("retains visible output and selection until a replacement subscription receivsynchronizeTerminalOutput(terminal, cleared, observedCursor);expect(terminal.resetAndWrite).toHaveBeenLastCalledWith("");});++it("reports an attach failure that leaves the output unchanged", () => {+ const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() };+ const previous = { ...EMPTY_TERMINAL_BUFFER_STATE, error: null };+ const failed = { ...previous, error: "Terminal attach failed" };++ expect(+ synchronizeTerminalSession(terminal, previous, failed, INITIAL_TERMINAL_OUTPUT_CURSOR),+ ).toBe(INITIAL_TERMINAL_OUTPUT_CURSOR);+ expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n");+ expect(terminal.resetAndWrite).not.toHaveBeenCalled();+ expect(terminal.clearSelection).not.toHaveBeenCalled();+});diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex 2cb8b6651f1..301255c7d51 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -1,4 +1,4 @@-import { useAtomValue } from "@effect/atom-react";+import { useAtomMount, useAtomValue } from "@effect/atom-react";import {isAtomCommandInterrupted,squashAtomCommandFailure,@@ -33,7 +33,6 @@ import * as Schema from "effect/Schema";import {type PointerEvent as ReactPointerEvent,type ReactNode,- type SetStateAction,useEffect,useEffectEvent,useLayoutEffect,@@ -79,7 +78,8 @@ import { readLocalApi } from "~/localApi";import { confirmTerminalClose } from "~/lib/terminalCloseConfirm";import { useClientSettings } from "../hooks/useSettings";import { useLocalStorage } from "../hooks/useLocalStorage";-import { useAttachedTerminalSession } from "../state/terminalSessions";+import { attachedTerminalSessionAtom } from "../state/terminalSessions";+import { appAtomRegistry } from "../rpc/atomRegistry";import { serverEnvironment } from "../state/server";import { previewEnvironment } from "../state/preview";import { readEnvironmentScope } from "../state/session";@@ -125,6 +125,8 @@ function resolveTerminalDrawerMaxHeight(input: DrawerLayout): number {);}+const DRAG_HEIGHT_PROPERTY = "--terminal-drawer-drag-height";+function clampDrawerHeight(height: number, maxHeight: number): number {const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);@@ -144,7 +146,10 @@ function readDrawerLayout(column: HTMLElement | null): Omit<DrawerLayout, "compo};}-function writeSystemMessage(terminal: GhosttyTerminalSurface, message: string): void {+function writeSystemMessage(+ terminal: Pick<GhosttyTerminalSurface, "write">,+ message: string,+): void {terminal.write(`\r\n[terminal] ${message}\r\n`);}@@ -171,6 +176,24 @@ export function synchronizeTerminalOutput(return update.cursor;}+/** Writes what changed between two session notifications: new output, then a new error. */+export function synchronizeTerminalSession(+ terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,+ previous: Pick<TerminalSessionState, "output" | "version" | "error">,+ session: Pick<TerminalSessionState, "output" | "version" | "error">,+ cursor: TerminalOutputCursor,+): TerminalOutputCursor {+ const nextCursor =+ session.version === previous.version && session.output === previous.output+ ? cursor+ : synchronizeTerminalOutput(terminal, session, cursor);+ // An attach failure can change only the error, keeping the last buffer.+ if (session.error !== null && session.error !== previous.error) {+ writeSystemMessage(terminal, session.error);+ }+ return nextCursor;+}+function parseTerminalColor(value: string, fallback: GhosttyColor): GhosttyColor {if (typeof document === "undefined") return fallback;@@ -400,6 +423,19 @@ export function shouldClearTerminalSelectionAction(options: {return options.actionPending || options.openMenuRequestId === options.currentRequestId;}+/**+ * A writable session's output generation. A new one is a fresh PTY (or a+ * reconnect) that has not seen the surface's grid yet.+ */+function writableSessionGeneration(+ session: TerminalSessionState,+ canOperate: boolean,+): number | null {+ return canOperate && session.version > 0 && session.status === "running"+ ? session.output.generation+ : null;+}+export function shouldHandleTerminalExit(current: TerminalSessionState["status"],synchronized: TerminalSessionState["status"],@@ -429,8 +465,6 @@ interface TerminalViewportProps {/** Focuses the viewport when it mounts; otherwise focus arrives through `focusTerminal`. */autoFocus?: boolean;visible: boolean;- resizeEpoch: number;- drawerHeight: number;keybindings: ResolvedKeybindingsConfig;}@@ -466,8 +500,6 @@ function TerminalSessionViewport({onAddTerminalContext,autoFocus = false,visible,- resizeEpoch,- drawerHeight,keybindings,}: TerminalViewportProps) {const containerRef = useRef<HTMLDivElement>(null);@@ -526,20 +558,23 @@ function TerminalSessionViewport({}),);const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });- const terminalSession = useAttachedTerminalSession({- environmentId,- terminal: {- threadId,- terminalId,- cwd,- ...(worktreePath !== undefined ? { worktreePath } : {}),- ...(runtimeEnv ? { env: runtimeEnv } : {}),- ...(providerInstanceId ? { providerInstanceId } : {}),- },+ // Keyed by the launch (see TerminalViewport), so the atom is fixed for this surface.+ const terminalSessionAtom = attachedTerminalSessionAtom(environmentId, {+ threadId,+ terminalId,+ cwd,+ ...(worktreePath !== undefined ? { worktreePath } : {}),+ ...(runtimeEnv ? { env: runtimeEnv } : {}),+ ...(providerInstanceId ? { providerInstanceId } : {}),});- const canResizeTerminal =- canOperateTerminal && terminalSession.version > 0 && terminalSession.status === "running";- const resizeSessionGeneration = canResizeTerminal ? terminalSession.output.generation : null;+ // Attaching starts with the viewport, while the WASM surface is still loading;+ // the surface reads the session itself, so output chunks never re-render here.+ useAtomMount(terminalSessionAtom);+ const readTerminalSession = useEffectEvent(() => appAtomRegistry.get(terminalSessionAtom));+ const subscribeTerminalSession = useEffectEvent(+ (listener: (session: TerminalSessionState) => void) =>+ appAtomRegistry.subscribe(terminalSessionAtom, listener),+ );const writeTerminal = useEffectEvent((data: string) =>runTerminalWrite({environmentId,@@ -547,15 +582,14 @@ function TerminalSessionViewport({}),);const resizeTerminal = useEffectEvent((cols: number, rows: number) => {- if (!canResizeTerminal || !hasTerminalWriteAccess()) return;+ if (writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()) === null) {+ return;+ }return runTerminalResize({environmentId,input: { threadId, terminalId, cols, rows },});});- const terminalOutput = terminalSession.output;- const terminalError = terminalSession.error;- const terminalStatus = terminalSession.status;const outputCursorRef = useRef<TerminalOutputCursor>(INITIAL_TERMINAL_OUTPUT_CURSOR);const synchronizedStatusRef = useRef<TerminalSessionState["status"]>("closed");const synchronizeTerminalStatus = useEffectEvent(@@ -577,19 +611,6 @@ function TerminalSessionViewport({if (version > 0) synchronizedStatusRef.current = status;},);- const terminalVersion = terminalSession.version;- const previousSessionRef = useRef({- output: terminalOutput,- error: terminalError,- status: terminalStatus,- version: terminalVersion,- });- const readLatestSession = useEffectEvent(() => ({- output: terminalOutput,- error: terminalError,- status: terminalStatus,- version: terminalVersion,- }));const openLinkInPreview = useEffectEvent((url: string, forceBrowser: boolean, fallbackToBrowser: () => void) =>openTerminalLinkInPreview({ url, threadRef, openPreview, fallbackToBrowser, forceBrowser }),@@ -609,13 +630,6 @@ function TerminalSessionViewport({terminalRef.current?.refreshLinkActivation();}, [canOpenHostEditor]);- useEffect(() => {- if (resizeSessionGeneration === null) return;- // The first fit can precede authorization/attach; replay the grid for each writable session, including- // reconnects.- terminalRef.current?.resendSize();- }, [resizeSessionGeneration]);-useLayoutEffect(() => {visibleRef.current = visible;terminalRef.current?.setVisible(visible);@@ -673,8 +687,7 @@ function TerminalSessionViewport({if (currentFont.family !== setupFont.family || currentFont.size !== setupFont.size) {void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size));}- const latestSession = readLatestSession();- previousSessionRef.current = latestSession;+ const latestSession = readTerminalSession();const initialOutput = readTerminalOutputUpdate(latestSession.output,INITIAL_TERMINAL_OUTPUT_CURSOR,@@ -686,6 +699,29 @@ function TerminalSessionViewport({if (latestSession.error !== null) writeSystemMessage(terminal, latestSession.error);synchronizedStatusRef.current = "closed";synchronizeTerminalStatus(terminal, latestSession.status, latestSession.version);+ // Read and subscribe in one synchronous step so no output lands between them.+ let previousSession = latestSession;+ let resizeGeneration = writableSessionGeneration(latestSession, hasTerminalWriteAccess());+ setupCleanups.push(+ subscribeTerminalSession((session) => {+ const nextResizeGeneration = writableSessionGeneration(session, hasTerminalWriteAccess());+ if (nextResizeGeneration !== resizeGeneration) {+ resizeGeneration = nextResizeGeneration;+ // The first fit can precede authorization/attach; replay the grid for each writable session, including+ // reconnects.+ if (nextResizeGeneration !== null) terminal.resendSize();+ }+ const previous = previousSession;+ previousSession = session;+ synchronizeTerminalStatus(terminal, session.status, session.version);+ outputCursorRef.current = synchronizeTerminalSession(+ terminal,+ previous,+ session,+ outputCursorRef.current,+ );+ }),+ );if (hasTerminalWriteAccess() &&visibleRef.current &&@@ -1075,53 +1111,6 @@ function TerminalSessionViewport({};}, [cwd, environmentId, terminalId]);- useEffect(() => {- const terminal = terminalRef.current;- const current = {- output: terminalOutput,- error: terminalError,- status: terminalStatus,- version: terminalVersion,- };- if (!terminal) {- previousSessionRef.current = current;- return;- }-- const previous = previousSessionRef.current;- synchronizeTerminalStatus(terminal, current.status, current.version);- if (current.version === previous.version && current.output === previous.output) {- return;- }-- outputCursorRef.current = synchronizeTerminalOutput(terminal, current, outputCursorRef.current);-- if (current.error !== null && current.error !== previous.error) {- writeSystemMessage(terminal, current.error);- }-- previousSessionRef.current = current;- }, [terminalOutput, terminalError, terminalStatus, terminalVersion]);-- // A hidden surface skips fitting, and showing it again fits through setVisible.- const layoutRevision = visible ? `${drawerHeight}:${resizeEpoch}` : null;- useEffect(() => {- const terminal = terminalRef.current;- if (!terminal || layoutRevision === null) return;- const wasAtBottom = terminal.isAtBottom();- // onResize alone sends PTY resize RPCs; fitting here only refreshes layout.- const frame = window.requestAnimationFrame(() => {- if (!visibleRef.current) return;- terminal.fit();- if (wasAtBottom) {- terminal.scrollToBottom();- }- });- return () => {- window.cancelAnimationFrame(frame);- };- }, [layoutRevision]);-const attachContainer = (mount: HTMLDivElement) => {containerRef.current = mount;const focus = () =>@@ -1245,8 +1234,6 @@ function TerminalSplitPanes({threadId,onAddTerminalContext,visible,- resizeEpoch,- drawerHeight,keybindings,}: {terminalIds: readonly string[];@@ -1261,8 +1248,6 @@ function TerminalSplitPanes({threadId: ThreadId;onAddTerminalContext: (selection: TerminalContextSelection) => void;visible: boolean;- resizeEpoch: number;- drawerHeight: number;keybindings: ResolvedKeybindingsConfig;}) {return (@@ -1311,8 +1296,6 @@ function TerminalSplitPanes({onSessionExited={() => onCloseTerminal(terminalId)}onAddTerminalContext={onAddTerminalContext}visible={visible}- resizeEpoch={resizeEpoch}- drawerHeight={drawerHeight}keybindings={keybindings}/></div>@@ -1456,36 +1439,19 @@ export default function ThreadTerminalDrawer({false,Schema.Boolean,);- const controlledDrawerHeight = height;const drawerRef = useRef<HTMLElement | null>(null);const [drawerLayout, setDrawerLayout] = useState(() => readDrawerLayout(null));const maxDrawerHeight = resolveTerminalDrawerMaxHeight({ ...drawerLayout, composerHeight });- const [drawerHeightState, setDrawerHeightState] = useState(() => ({- threadId,- height: controlledDrawerHeight,- }));- const preferredDrawerHeight =- drawerHeightState.threadId === threadId ? drawerHeightState.height : controlledDrawerHeight;- const drawerHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight);- const setDrawerHeight = (update: SetStateAction<number>) => {- setDrawerHeightState((current) => {- const currentHeight = current.threadId === threadId ? current.height : controlledDrawerHeight;- const nextHeight = typeof update === "function" ? update(currentHeight) : update;- return nextHeight === currentHeight && current.threadId === threadId- ? current- : { threadId, height: nextHeight };- });- };- const [resizeEpoch, setResizeEpoch] = useState(0);- const drawerHeightRef = useRef(drawerHeight);- const lastSyncedHeightRef = useRef({ threadId, height: controlledDrawerHeight });+ const drawerHeight = clampDrawerHeight(height, maxDrawerHeight);+ // A drag only writes the drawer's style; the store hears the height once, at+ // pointerup. The custom property outranks the rendered height while it is set.const resizeStateRef = useRef<{pointerId: number;startY: number;startHeight: number;+ height: number;drawer: HTMLElement | null;} | null>(null);- const didResizeDuringDragRef = useRef(false);const normalizedTerminalIds = (() => {const normalizedIds: string[] = [];@@ -1655,35 +1621,15 @@ export default function ThreadTerminalDrawer({});};- useLayoutEffect(() => {- const resizeState = resizeStateRef.current;- if (resizeState) {- resizeState.drawer?.style.setProperty("height", `${drawerHeightRef.current}px`);- return;- }- drawerHeightRef.current = drawerHeight;- }, [drawerHeight]);-- const syncHeight = (nextHeight: number) => {- const lastSynced = lastSyncedHeightRef.current;- if (lastSynced.threadId === threadId && lastSynced.height === nextHeight) return;- lastSyncedHeightRef.current = { threadId, height: nextHeight };- onHeightChange(nextHeight);- };-- useEffect(() => {- lastSyncedHeightRef.current = { threadId, height: controlledDrawerHeight };- }, [controlledDrawerHeight, threadId]);-const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {if (event.button !== 0) return;event.preventDefault();event.currentTarget.setPointerCapture(event.pointerId);- didResizeDuringDragRef.current = false;resizeStateRef.current = {pointerId: event.pointerId,startY: event.clientY,- startHeight: drawerHeightRef.current,+ startHeight: drawerHeight,+ height: drawerHeight,drawer: event.currentTarget.parentElement,};};@@ -1696,12 +1642,11 @@ export default function ThreadTerminalDrawer({resizeState.startHeight + (resizeState.startY - event.clientY),maxDrawerHeight,);- if (clampedHeight === drawerHeightRef.current) {+ if (clampedHeight === resizeState.height) {return;}- didResizeDuringDragRef.current = true;- drawerHeightRef.current = clampedHeight;- resizeState.drawer?.style.setProperty("height", `${clampedHeight}px`);+ resizeState.height = clampedHeight;+ resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${clampedHeight}px`);};const handleResizePointerEnd = (event: ReactPointerEvent<HTMLDivElement>) => {@@ -1711,19 +1656,11 @@ export default function ThreadTerminalDrawer({if (event.currentTarget.hasPointerCapture(event.pointerId)) {event.currentTarget.releasePointerCapture(event.pointerId);}+ resizeState.drawer?.style.removeProperty(DRAG_HEIGHT_PROPERTY);// A drag that ends where it started keeps the stored preference, which may// be taller than the capped height the drag started from.- if (!didResizeDuringDragRef.current || drawerHeightRef.current === resizeState.startHeight) {- // React skips the write when the rendered height did not change, so put- // back the preference as the current layout caps it.- const renderedHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight);- drawerHeightRef.current = renderedHeight;- resizeState.drawer?.style.setProperty("height", `${renderedHeight}px`);- return;- }- setDrawerHeight(drawerHeightRef.current);- syncHeight(drawerHeightRef.current);- setResizeEpoch((value) => value + 1);+ if (resizeState.height === resizeState.startHeight || resizeState.height === height) return;+ onHeightChange(resizeState.height);};const drawerLayoutRef = useRef(drawerLayout);@@ -1740,16 +1677,17 @@ export default function ThreadTerminalDrawer({if (!heightBudgetChanged && source === "column") return;drawerLayoutRef.current = layout;const resizeState = resizeStateRef.current;- const liveHeight = clampDrawerHeight(- drawerHeightRef.current,- resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }),- );- if (resizeState && liveHeight !== drawerHeightRef.current) {- drawerHeightRef.current = liveHeight;- resizeState.drawer?.style.setProperty("height", `${liveHeight}px`);+ if (resizeState) {+ const liveHeight = clampDrawerHeight(+ resizeState.height,+ resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }),+ );+ if (liveHeight !== resizeState.height) {+ resizeState.height = liveHeight;+ resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${liveHeight}px`);+ }}if (heightBudgetChanged) setDrawerLayout(layout);- setResizeEpoch((value) => value + 1);},);useLayoutEffect(() => {@@ -1774,9 +1712,6 @@ export default function ThreadTerminalDrawer({};}, [isPanel, visible]);- const syncPreferredHeight = useEffectEvent(() => syncHeight(preferredDrawerHeight));- useEffect(() => () => syncPreferredHeight(), []);-if (normalizedTerminalIds.length === 0) {return (<aside@@ -1787,7 +1722,7 @@ export default function ThreadTerminalDrawer({"relative flex min-w-0 flex-col overflow-hidden bg-background",isPanel ? "h-full flex-1" : "z-45 shrink-0 border-t border-border/80",)}- style={isPanel ? undefined : { height: `${drawerHeight}px` }}+ style={isPanel ? undefined : { height: `var(${DRAG_HEIGHT_PROPERTY}, ${drawerHeight}px)` }}>{!isPanel ? (<div@@ -1823,7 +1758,7 @@ export default function ThreadTerminalDrawer({"relative flex min-w-0 flex-col overflow-hidden bg-background",isPanel ? "h-full flex-1" : "z-45 shrink-0 border-t border-border/80",)}- style={isPanel ? undefined : { height: `${drawerHeight}px` }}+ style={isPanel ? undefined : { height: `var(${DRAG_HEIGHT_PROPERTY}, ${drawerHeight}px)` }}>{!isPanel ? (<div@@ -1907,8 +1842,6 @@ export default function ThreadTerminalDrawer({threadId={threadId}onAddTerminalContext={onAddTerminalContext}visible={visible}- resizeEpoch={resizeEpoch}- drawerHeight={drawerHeight}keybindings={keybindings}/></div>diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsxindex 9cb184e82b0..361ca8cba9d 100644--- a/apps/web/src/components/onboarding/WelcomeWizard.tsx+++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx@@ -1157,8 +1157,6 @@ function AgentInstallTerminal({onSessionExited={onClose}autoFocusvisible- resizeEpoch={0}- drawerHeight={256}keybindings={keybindings}/>) : null}diff --git a/apps/web/src/components/settings/ProviderAuthTerminal.tsx b/apps/web/src/components/settings/ProviderAuthTerminal.tsxindex e8751d5ab14..b21a3642902 100644--- a/apps/web/src/components/settings/ProviderAuthTerminal.tsx+++ b/apps/web/src/components/settings/ProviderAuthTerminal.tsx@@ -2,6 +2,7 @@ import type { ProviderAuthResponse } from "@t3tools/contracts";import { useEffect, useRef, useState } from "react";import { GhosttyTerminalSurface } from "../../terminal/ghostty/surface";import { ensureLocalApi } from "../../localApi";+import { useStableCallback } from "../../hooks/useStableCallback";import { terminalThemeFromApp } from "../ThreadTerminalDrawer";export default function ProviderAuthTerminal({@@ -13,30 +14,27 @@ export default function ProviderAuthTerminal({readonly outputOffset?: number | undefined;readonly onResponse: (response: Extract<ProviderAuthResponse, { type: "terminal" }>) => void;}) {- const mount = useRef<HTMLDivElement>(null);- const surface = useRef<GhosttyTerminalSurface | null>(null);- const latest = useRef({ output, offset: outputOffset ?? output.length, onResponse });+ const [surface, setSurface] = useState<GhosttyTerminalSurface | null>(null);const written = useRef(0);const [error, setError] = useState<string | null>(null);+ // The surface captures its callbacks once at creation.+ const respond = useStableCallback(onResponse);+ const offset = outputOffset ?? output.length;useEffect(() => {- latest.current = { output, offset: outputOffset ?? output.length, onResponse };- const terminal = surface.current;- if (!terminal) return;- const delta = latest.current.offset - written.current;- if (delta > 0 && delta <= output.length) terminal.write(output.slice(-delta));- else if (delta !== 0) terminal.resetAndWrite(output);- written.current = latest.current.offset;- }, [output, outputOffset, onResponse]);- useEffect(() => {- const element = mount.current;- if (!element) return;+ if (!surface) return;+ const delta = offset - written.current;+ if (delta > 0 && delta <= output.length) surface.write(output.slice(-delta));+ else if (delta !== 0) surface.resetAndWrite(output);+ written.current = offset;+ }, [surface, output, offset]);+ const mountSurface = (element: HTMLDivElement) => {let disposed = false;+ let created: GhosttyTerminalSurface | null = null;void GhosttyTerminalSurface.create(element, {theme: terminalThemeFromApp(element),font: { size: 13 },- onData: (data) => latest.current.onResponse({ type: "terminal", data }),- onResize: (cols, rows) =>- latest.current.onResponse({ type: "terminal", data: "", size: { cols, rows } }),+ onData: (data) => respond({ type: "terminal", data }),+ onResize: (cols, rows) => respond({ type: "terminal", data: "", size: { cols, rows } }),onSelectionChange: () => {},beforeKey: (event) => event.key !== "Tab",onLinkActivate: (url) => {@@ -51,21 +49,21 @@ export default function ProviderAuthTerminal({terminal.dispose();return;}- surface.current = terminal;- terminal.write(latest.current.output);- written.current = latest.current.offset;+ created = terminal;+ written.current = 0;+ setSurface(terminal);}).catch(() => setError("Could not load the sign-in terminal. Cancel and retry sign-in."));return () => {disposed = true;- surface.current?.dispose();- surface.current = null;+ created?.dispose();+ setSurface(null);};- }, []);+ };return (<><div- ref={mount}+ ref={mountSurface}aria-label="Provider sign-in terminal"className="relative h-64 overflow-hidden rounded-md border border-border"/>diff --git a/apps/web/src/components/settings/SettingsFontPreviews.tsx b/apps/web/src/components/settings/SettingsFontPreviews.tsxindex ab97a1a341e..d02f5350314 100644--- a/apps/web/src/components/settings/SettingsFontPreviews.tsx+++ b/apps/web/src/components/settings/SettingsFontPreviews.tsx@@ -1,5 +1,8 @@import type { ServerProviderSkill } from "@t3tools/contracts";import { preloadPatchFile } from "@pierre/diffs/ssr";+import { useAtomValue } from "@effect/atom-react";+import * as Effect from "effect/Effect";+import { AsyncResult, Atom } from "effect/reactivity";import { useEffect, useRef, useState } from "react";import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "../ComposerPromptEditor";import { EMPTY_COMPOSER_CONTEXT_RECORDS } from "../composerContextPresentation";@@ -61,18 +64,11 @@ const DIFF_PREVIEW_PATCH = [].join("\n");// FileDiff remounts can retain unhighlighted frames after a race; use static highlighted HTML in shadow DOM.-const diffPreviewHtmlByTheme = new Map<DiffThemeName, Promise<readonly string[]>>();-function loadDiffPreviewHtml(theme: DiffThemeName): Promise<readonly string[]> {- let promise = diffPreviewHtmlByTheme.get(theme);- if (promise === undefined) {- promise = preloadPatchFile({- patch: DIFF_PREVIEW_PATCH,- options: { diffStyle: "unified", theme, preferredHighlighter: PREFERRED_HIGHLIGHTER },- }).then((results) => results.map((result) => result.prerenderedHTML));- diffPreviewHtmlByTheme.set(theme, promise);- }- return promise;+ return preloadPatchFile({+ patch: DIFF_PREVIEW_PATCH,+ options: { diffStyle: "unified", theme, preferredHighlighter: PREFERRED_HIGHLIGHTER },+ }).then((results) => results.map((result) => result.prerenderedHTML));}// Unlayered shadow-root rules override Pierre surfaces with app code tokens to match the diff panel.@@ -91,33 +87,36 @@ const DIFF_PREVIEW_THEME_BRIDGE = `}`;+// Each host is keyed by its html, so the ref callback runs once per document.+// React detaches a cleanup-less ref callback with null when an appearance switch drops the host.function StaticDiffHtml({ html }: { html: string }) {- const hostRef = useRef<HTMLDivElement | null>(null);- useEffect(() => {- const host = hostRef.current;+ const attachHtml = (host: HTMLDivElement | null) => {if (host === null) return;const shadow = host.shadowRoot ?? host.attachShadow({ mode: "open" });shadow.innerHTML = html;const bridge = document.createElement("style");bridge.textContent = DIFF_PREVIEW_THEME_BRIDGE;shadow.append(bridge);- }, [html]);- return <div ref={hostRef} />;+ };+ return <div ref={attachHtml} />;}+const diffPreviewHtmlAtom = Atom.family((theme: DiffThemeName) =>+ Atom.make(Effect.promise(() => loadDiffPreviewHtml(theme))).pipe(+ Atom.keepAlive,+ Atom.withLabel(`settings-diff-preview:${theme}`),+ ),+);+export function CodeFontPreview() {const resolvedTheme = useRenderedAppearance();- const themeName = resolveDiffThemeName(resolvedTheme);- const [htmlByFile, setHtmlByFile] = useState<readonly string[] | null>(null);- useEffect(() => {- let cancelled = false;- void loadDiffPreviewHtml(themeName).then((html) => {- if (!cancelled) setHtmlByFile(html);- });- return () => {- cancelled = true;- };- }, [themeName]);+ const loadedHtml = AsyncResult.getOrElse(+ useAtomValue(diffPreviewHtmlAtom(resolveDiffThemeName(resolvedTheme))),+ () => null,+ );+ // An appearance switch keeps the previous theme's preview up while the new one renders.+ const [htmlByFile, setHtmlByFile] = useState(loadedHtml);+ if (loadedHtml !== null && loadedHtml !== htmlByFile) setHtmlByFile(loadedHtml);if (htmlByFile === null) return null;return (<div className="mt-1 mb-2 space-y-2">@@ -151,43 +150,38 @@ function previewTerminalFont(family: string, size: number): { family?: string; sexport function TerminalFontPreview({ family, size }: { family: string; size: number }) {const mountRef = useRef<HTMLDivElement>(null);- const surfaceRef = useRef<GhosttyTerminalSurface | null>(null);- const fontRef = useRef({ family, size });+ const [surface, setSurface] = useState<GhosttyTerminalSurface | null>(null);+ const [initialFont] = useState(() => previewTerminalFont(family, size));const { theme, resolvedTheme } = useTheme();useEffect(() => {- const current = fontRef.current;- if (current.family === family && current.size === size) return;- fontRef.current = { family, size };- void surfaceRef.current?.setFont(previewTerminalFont(family, size));- }, [family, size]);+ void surface?.setFont(previewTerminalFont(family, size));+ }, [surface, family, size]);// Palette changes may preserve light/dark mode; re-read terminal tokens for every theme change.useEffect(() => {const mount = mountRef.current;- const surface = surfaceRef.current;if (!mount || !surface) return;surface.setTheme(terminalThemeFromApp(mount));// oxlint-disable-next-line react/exhaustive-effect-dependencies -- The tokens come from the DOM's computed styles, which a theme change rewrites.- }, [theme, resolvedTheme]);+ }, [surface, theme, resolvedTheme]);- useEffect(() => {- const mount = mountRef.current;- if (!mount) return;+ const mountSurface = (mount: HTMLDivElement) => {+ mountRef.current = mount;let cancelled = false;+ let created: GhosttyTerminalSurface | null = null;let lineLength = 0;const echo = (data: string) => {- const surface = surfaceRef.current;- if (!surface) return;+ if (!created) return;if (data === "\r") {- surface.write(`\r\n${TERMINAL_PROMPT}`);+ created.write(`\r\n${TERMINAL_PROMPT}`);lineLength = 0;return;}if (data === "\x7f" || data === "\b") {if (lineLength > 0) {- surface.write("\b \b");+ created.write("\b \b");lineLength -= 1;}return;@@ -197,40 +191,39 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu.filter((character) => character >= " " && character !== "\x7f").join("");if (printable.length === 0) return;- surface.write(printable);+ created.write(printable);lineLength += printable.length;};void GhosttyTerminalSurface.create(mount, {theme: terminalThemeFromApp(mount),- font: previewTerminalFont(fontRef.current.family, fontRef.current.size),+ font: initialFont,onData: echo,onResize: noop,onSelectionChange: noop,beforeKey: (event) => event.key !== "Tab",onLinkActivate: noop,- }).then((surface) => {+ }).then((next) => {if (cancelled) {- surface.dispose();+ next.dispose();return;}- surfaceRef.current = surface;- surface.setTheme(terminalThemeFromApp(mount));- const font = fontRef.current;- void surface.setFont(previewTerminalFont(font.family, font.size));- surface.write(TERMINAL_PREVIEW_TRANSCRIPT);+ created = next;+ next.write(TERMINAL_PREVIEW_TRANSCRIPT);+ setSurface(next);});return () => {cancelled = true;- surfaceRef.current?.dispose();- surfaceRef.current = null;+ created?.dispose();+ mountRef.current = null;+ setSurface(null);};- }, []);+ };return (<div- ref={mountRef}+ ref={mountSurface}className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"aria-label="Terminal font preview"/>diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsxindex 981608d8d6d..d4af916e5d0 100644--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx+++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx@@ -42,6 +42,7 @@ import { scrollToSettingsTarget } from "./settingsLayout";import {searchSettings,isSettingsOverviewVisible,+ revealSettingsSearchTarget,SETTINGS_SECTION_LABELS,type SettingsPath,type SettingsSearchItem,@@ -103,6 +104,11 @@ const SETTINGS_NAV_ITEMS: ReadonlyArray<{icon: SETTINGS_SECTION_ICONS[to],}));+// Attached only to the highlighted result, so it runs whenever the highlight lands on a row.+function scrollResultIntoView(row: HTMLElement | null) {+ row?.scrollIntoView({ block: "nearest" });+}+function SettingsSectionIcon({ to }: { to: SettingsPath }) {const Icon = SETTINGS_SECTION_ICONS[to];return <Icon className="size-4 shrink-0 text-(--sidebar-icon-color)" />;@@ -131,14 +137,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {setActiveResultIndex(maxResultIndex);}- useEffect(() => {- const result = results[activeResultIndex];- if (!result) return;- document- .getElementById(`settings-search-result-${result.id}`)- ?.scrollIntoView({ block: "nearest" });- }, [activeResultIndex, results]);-useEffect(() => {const handleKeyDown = (event: globalThis.KeyboardEvent) => {if (event.defaultPrevented || event.isComposing) return;@@ -195,6 +193,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {clearSearch();setCompactSearchOpen(false);const targetId = item.targetId ?? item.id;+ revealSettingsSearchTarget(targetId);if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {scrollToSettingsTarget(targetId);return;@@ -312,7 +311,11 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {aria-label={hasResults ? "Settings search results" : undefined}>{results.map((item, index) => (- <SidebarMenuItem key={item.id} role="presentation">+ <SidebarMenuItem+ key={item.id}+ role="presentation"+ ref={index === activeResultIndex ? scrollResultIntoView : undefined}+ ><SidebarMenuButtonid={`settings-search-result-${item.id}`}role="option"diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsxnew file mode 100644index 00000000000..3a6478434c9--- /dev/null+++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx@@ -0,0 +1,56 @@+import { StrictMode } from "react";+import { describe, expect, it, vi } from "vite-plus/test";+import { page, userEvent } from "vite-plus/test/browser";++import { render } from "../../../test/render";+import type { OpenVsxThemeExtension } from "../../openVsxThemes";+import { ThemeImportDialog } from "./ThemeImportDialog";++const searchOpenVsxThemes = vi.hoisted(() => vi.fn());++vi.mock("../../openVsxThemes", () => ({+ searchOpenVsxThemes,+ importOpenVsxThemeExtension: vi.fn(),+}));++const extension: OpenVsxThemeExtension = {+ id: "acme.nightfall",+ collectionId: "acme.nightfall",+ name: "Nightfall",+ publisher: "acme",+ description: "A dark theme",+ downloadCount: 10,+ iconUrl: null,+ sourceUrl: null,+ manifestUrl: "https://example.test/manifest",+ sha256Url: "https://example.test/sha256",+ vsixUrl: "https://example.test/vsix",+ version: "1.0.0",+ license: "MIT",+};++describe("ThemeImportDialog", () => {+ // StrictMode replays ref attach/detach on mount, which must not end the session.+ it("searches Open VSX under StrictMode", async () => {+ searchOpenVsxThemes.mockReset();+ searchOpenVsxThemes.mockResolvedValue([extension]);+ await using _screen = await render(+ <StrictMode>+ <ThemeImportDialog+ open+ onOpenChange={() => {}}+ onImported={() => true}+ onImportedMany={() => {}}+ />+ </StrictMode>,+ );++ await userEvent.type(page.getByLabelText("Search Open VSX themes"), "night");++ await expect.element(page.getByRole("heading", { name: "Nightfall" })).toBeVisible();+ expect(searchOpenVsxThemes).toHaveBeenCalledWith(+ "night",+ expect.objectContaining({ sortBy: "downloadCount" }),+ );+ });+});diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsxindex 43270d83a0f..f443953964f 100644--- a/apps/web/src/components/settings/ThemeImportDialog.tsx+++ b/apps/web/src/components/settings/ThemeImportDialog.tsx@@ -1,7 +1,7 @@import { DownloadIcon, PlusIcon } from "lucide-react";import type { ChangeEvent, DragEvent, UIEvent } from "react";import { settlePromise } from "@t3tools/client-runtime/state/runtime";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import { cn } from "../../lib/utils";import {getCustomThemes,@@ -137,17 +137,71 @@ function ThemeJsonEditor({type ImportableThemeFile = { name: string; size: number; text: () => Promise<string> };+interface ThemeImportCallbacks {+ onImported: (theme: ThemeDefinition) => boolean;+ onImportedMany: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;+}+export function ThemeImportDialog({open,onOpenChange,onImported,onImportedMany,-}: {+}: ThemeImportCallbacks & {open: boolean;onOpenChange: (open: boolean) => void;- onImported: (theme: ThemeDefinition) => boolean;- onImportedMany: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;}) {+ // Each opening is a fresh session: its body remounts with clean state, and+ // closing aborts every read, search, and install the session started.+ const [session, setSession] = useState(() => ({+ open,+ id: 0,+ controller: new AbortController(),+ }));+ if (session.open !== open) {+ setSession(+ open ? { open, id: session.id + 1, controller: new AbortController() } : { ...session, open },+ );+ }+ const close = () => {+ session.controller.abort();+ onOpenChange(false);+ };++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (nextOpen) onOpenChange(true);+ else close();+ }}+ >+ <DialogPopup className="max-w-3xl overflow-hidden">+ <DialogHeader>+ <DialogTitle>Add a theme</DialogTitle>+ </DialogHeader>+ <ThemeImportBody+ key={session.id}+ session={session.controller}+ onClose={close}+ onImported={onImported}+ onImportedMany={onImportedMany}+ />+ </DialogPopup>+ </Dialog>+ );+}++function ThemeImportBody({+ session,+ onClose,+ onImported,+ onImportedMany,+}: ThemeImportCallbacks & {+ session: AbortController;+ onClose: () => void;+}) {+ const { signal } = session;const fileInputRef = useRef<HTMLInputElement>(null);const [json, setJson] = useState("");const [fileName, setFileName] = useState<string | null>(null);@@ -155,27 +209,10 @@ export function ThemeImportDialog({const [isReading, setIsReading] = useState(false);const [isDropTarget, setIsDropTarget] = useState(false);const [conflicts, setConflicts] = useState<ReadonlyArray<ThemeDefinition> | null>(null);+ // A newer read supersedes an older one still in flight.const importRequestRef = useRef(0);-- const [renderedOpen, setRenderedOpen] = useState(open);- if (renderedOpen !== open) {- setRenderedOpen(open);- setIsDropTarget(false);- if (open) {- setJson("");- setFileName(null);- setError(null);- setIsReading(false);- setConflicts(null);- }- }- useEffect(() => {- if (!open) return;- importRequestRef.current += 1;- return () => {- importRequestRef.current += 1;- };- }, [open]);+ const isCurrentRequest = (requestId: number) =>+ requestId === importRequestRef.current && !signal.aborted;const readThemeFile = async (file: ImportableThemeFile) => {const oversized = describeOversizedThemeFile(file.size);@@ -187,7 +224,7 @@ export function ThemeImportDialog({const requestId = ++importRequestRef.current;setIsReading(true);const fileText = await settlePromise(() => file.text());- if (requestId !== importRequestRef.current) return;+ if (!isCurrentRequest(requestId)) return;setIsReading(false);if (fileText._tag === "Failure") {setError("Could not read that file. Paste the JSON below instead.");@@ -202,7 +239,7 @@ export function ThemeImportDialog({const requestId = ++importRequestRef.current;setIsReading(true);return installThemeBatch(files, requestId).finally(() => {- if (requestId === importRequestRef.current) setIsReading(false);+ if (isCurrentRequest(requestId)) setIsReading(false);});};@@ -230,7 +267,7 @@ export function ThemeImportDialog({);}}- if (requestId !== importRequestRef.current) return;+ if (!isCurrentRequest(requestId)) return;const installed: ThemeDefinition[] = [];const conflicting: ThemeDefinition[] = [];for (const theme of pairVsCodeThemes(resolveThemeLabelCollisions(parsed))) {@@ -252,7 +289,7 @@ export function ThemeImportDialog({} else if (conflicting.length > 0) {setConflicts(conflicting);} else if (installed.length > 0) {- onOpenChange(false);+ onClose();}};@@ -351,7 +388,7 @@ export function ThemeImportDialog({if (resolved.length > 0) onImportedMany(resolved, { updated: mode === "update" });setConflicts(null);if (failures.length > 0) setError(failures.join("; "));- else onOpenChange(false);+ else onClose();};const handleSubmit = () => {@@ -378,148 +415,135 @@ export function ThemeImportDialog({setError("Theme added, but it could not be selected. Try again.");return;}- onOpenChange(false);+ onClose();} catch (cause) {setError(cause instanceof Error ? cause.message : "That theme file is invalid.");}};return (- <Dialog- open={open}- onOpenChange={(nextOpen) => {- if (!nextOpen) setError(null);- onOpenChange(nextOpen);- }}- >- <DialogPopup className="max-w-3xl overflow-hidden">- <DialogHeader>- <DialogTitle>Add a theme</DialogTitle>- </DialogHeader>- <DialogPanel>- <ThemeSearchSection- onInstalled={(themes, context) => {- onImportedMany(themes, context);- onOpenChange(false);- }}- open={open}- />+ <DialogPanel>+ <ThemeSearchSection+ onInstalled={(themes, context) => {+ onImportedMany(themes, context);+ onClose();+ }}+ signal={signal}+ />- <div className="flex items-center gap-3" aria-hidden>- <div className="h-px flex-1 bg-border" />- <span className="text-muted-foreground text-2xs uppercase tracking-wider">- or import a file- </span>- <div className="h-px flex-1 bg-border" />- </div>+ <div className="flex items-center gap-3" aria-hidden>+ <div className="h-px flex-1 bg-border" />+ <span className="text-muted-foreground text-2xs uppercase tracking-wider">+ or import a file+ </span>+ <div className="h-px flex-1 bg-border" />+ </div>- {(() => {- const dropHandlers = {- onDragEnter: (event: DragEvent<HTMLDivElement>) => {- event.preventDefault();- setIsDropTarget(true);- },- onDragOver: (event: DragEvent<HTMLDivElement>) => {- event.preventDefault();- setIsDropTarget(true);- },- onDragLeave: (event: DragEvent<HTMLDivElement>) => {- if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;- setIsDropTarget(false);- },- onDrop: handleDrop,- };- const fileInput = (- <input- ref={fileInputRef}- accept=".json,application/json"- className="sr-only"- onChange={handleFileChange}- multiple- type="file"- />- );- const chooseButton = (label = "Choose files") => (- <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>- <DownloadIcon />- {isReading ? "Reading…" : label}- </Button>- );- const editorSection = () => (- <div className="space-y-2">- <div className="flex items-baseline justify-between gap-3">- <label className="text-sm font-medium" htmlFor="theme-json-editor">- Theme JSON- </label>- </div>- <ThemeJsonEditor id="theme-json-editor" onChange={setJson} value={json} />+ {(() => {+ const dropHandlers = {+ onDragEnter: (event: DragEvent<HTMLDivElement>) => {+ event.preventDefault();+ setIsDropTarget(true);+ },+ onDragOver: (event: DragEvent<HTMLDivElement>) => {+ event.preventDefault();+ setIsDropTarget(true);+ },+ onDragLeave: (event: DragEvent<HTMLDivElement>) => {+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;+ setIsDropTarget(false);+ },+ onDrop: handleDrop,+ };+ const fileInput = (+ <input+ ref={fileInputRef}+ accept=".json,application/json"+ className="sr-only"+ onChange={handleFileChange}+ multiple+ type="file"+ />+ );+ const chooseButton = (label = "Choose files") => (+ <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>+ <DownloadIcon />+ {isReading ? "Reading…" : label}+ </Button>+ );+ const editorSection = () => (+ <div className="space-y-2">+ <div className="flex items-baseline justify-between gap-3">+ <label className="text-sm font-medium" htmlFor="theme-json-editor">+ Theme JSON+ </label>+ </div>+ <ThemeJsonEditor id="theme-json-editor" onChange={setJson} value={json} />+ </div>+ );+ if (conflicts) {+ return (+ <div className="space-y-3">+ <div className="rounded-xl border border-border/70 bg-muted/20 p-3">+ <p className="text-sm font-medium">Already installed</p>+ <p className="mt-1 text-xs text-muted-foreground">+ {conflicts.map((theme) => theme.label).join(", ")}+ </p></div>- );- if (conflicts) {- return (- <div className="space-y-3">- <div className="rounded-xl border border-border/70 bg-muted/20 p-3">- <p className="text-sm font-medium">Already installed</p>- <p className="mt-1 text-xs text-muted-foreground">- {conflicts.map((theme) => theme.label).join(", ")}- </p>- </div>- <div className="flex flex-wrap items-center gap-2">- <Button size="sm" onClick={() => resolveConflicts("update")}>- Update existing- </Button>- <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>- Keep both- </Button>- <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>- Back- </Button>- <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>- Cancel- </Button>- </div>- </div>- );- }- return (- <div className="space-y-4">- <div- className={cn(- "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",- isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",- )}- {...dropHandlers}- >- <div className="min-w-0">- <p className="text-sm font-medium">Theme file</p>- <p className="truncate text-xs text-muted-foreground">- {fileName ?? "Drop T3 Code or VS Code .json files"}- </p>- </div>- {chooseButton()}- {fileInput}- </div>- {editorSection()}- <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">- <Button variant="ghost" onClick={() => onOpenChange(false)}>- Cancel- </Button>- <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>- <PlusIcon />- Add theme- </Button>- </div>+ <div className="flex flex-wrap items-center gap-2">+ <Button size="sm" onClick={() => resolveConflicts("update")}>+ Update existing+ </Button>+ <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>+ Keep both+ </Button>+ <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>+ Back+ </Button>+ <Button size="sm" variant="ghost" onClick={() => onClose()}>+ Cancel+ </Button></div>- );- })()}-- {error ? (- <Alert aria-live="polite" variant="error">- {error}- </Alert>- ) : null}- </DialogPanel>- </DialogPopup>- </Dialog>+ </div>+ );+ }+ return (+ <div className="space-y-4">+ <div+ className={cn(+ "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",+ isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",+ )}+ {...dropHandlers}+ >+ <div className="min-w-0">+ <p className="text-sm font-medium">Theme file</p>+ <p className="truncate text-xs text-muted-foreground">+ {fileName ?? "Drop T3 Code or VS Code .json files"}+ </p>+ </div>+ {chooseButton()}+ {fileInput}+ </div>+ {editorSection()}+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">+ <Button variant="ghost" onClick={() => onClose()}>+ Cancel+ </Button>+ <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>+ <PlusIcon />+ Add theme+ </Button>+ </div>+ </div>+ );+ })()}++ {error ? (+ <Alert aria-live="polite" variant="error">+ {error}+ </Alert>+ ) : null}+ </DialogPanel>);}diff --git a/apps/web/src/components/settings/ThemeSearchSection.test.ts b/apps/web/src/components/settings/ThemeSearchSection.test.tsnew file mode 100644index 00000000000..a1ec9cc5e73--- /dev/null+++ b/apps/web/src/components/settings/ThemeSearchSection.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it, vi } from "vite-plus/test";++import type { OpenVsxThemeExtension, OpenVsxThemeSort } from "../../openVsxThemes";+import { createThemeSearch, type ThemeSearchView } from "./ThemeSearchSection";++interface Request {+ readonly query: string;+ readonly sortBy: OpenVsxThemeSort | undefined;+ readonly signal: AbortSignal | undefined;+ resolve(results: OpenVsxThemeExtension[]): void;+ reject(cause: unknown): void;+}++function setup() {+ vi.useFakeTimers();+ const requests: Request[] = [];+ const search = (+ query: string,+ options: { signal?: AbortSignal; sortBy?: OpenVsxThemeSort } = {},+ ) =>+ new Promise<OpenVsxThemeExtension[]>((resolve, reject) => {+ requests.push({ query, sortBy: options.sortBy, signal: options.signal, resolve, reject });+ });+ const view = {+ results: null as ReadonlyArray<OpenVsxThemeExtension> | null,+ error: null as string | null,+ isSearching: false,+ };+ const sink: ThemeSearchView = {+ setResults: (results) => {+ view.results = results;+ },+ setError: (error) => {+ view.error = error;+ },+ setIsSearching: (isSearching) => {+ view.isSearching = isSearching;+ },+ };+ const session = new AbortController();+ const themeSearch = createThemeSearch(sink, session.signal, search);+ return {+ requests,+ view,+ session,+ themeSearch,+ [Symbol.dispose]: () => vi.useRealTimers(),+ };+}++const extension = (name: string) => ({ name }) as OpenVsxThemeExtension;+const flush = () => vi.advanceTimersByTimeAsync(0);++describe("createThemeSearch", () => {+ it("searches once the typed query settles", async () => {+ using env = setup();+ env.themeSearch.setQuery("dra");+ env.themeSearch.setQuery("dracula ");+ await vi.advanceTimersByTimeAsync(349);+ expect(env.requests).toHaveLength(0);+ await vi.advanceTimersByTimeAsync(1);+ expect(env.requests.map((request) => request.query)).toEqual(["dracula"]);+ expect(env.view.isSearching).toBe(true);++ env.requests[0]!.resolve([extension("Dracula")]);+ await flush();+ expect(env.view.results).toEqual([extension("Dracula")]);+ expect(env.view.isSearching).toBe(false);+ });++ it("keeps the shown results when typing returns to their query", async () => {+ using env = setup();+ env.themeSearch.setQuery("nord");+ await vi.advanceTimersByTimeAsync(350);+ env.requests[0]!.resolve([extension("Nord")]);+ await flush();++ env.themeSearch.setQuery("nordic");+ await vi.advanceTimersByTimeAsync(350);+ env.themeSearch.setQuery("nord");+ await vi.advanceTimersByTimeAsync(350);++ expect(env.requests).toHaveLength(2);+ expect(env.requests[1]!.signal?.aborted).toBe(true);+ expect(env.view.results).toEqual([extension("Nord")]);+ expect(env.view.isSearching).toBe(false);+ });++ it("searches again right away when the sort changes", async () => {+ using env = setup();+ env.themeSearch.setQuery("nord");+ await vi.advanceTimersByTimeAsync(350);+ env.themeSearch.setSortBy("rating");+ expect(env.requests[0]!.signal?.aborted).toBe(true);+ expect(env.requests[1]).toMatchObject({ query: "nord", sortBy: "rating" });+ });++ it("clearing the query drops results and the request in flight", async () => {+ using env = setup();+ env.themeSearch.setQuery("nord");+ await vi.advanceTimersByTimeAsync(350);+ env.themeSearch.setQuery(" ");+ expect(env.requests[0]!.signal?.aborted).toBe(true);+ expect(env.view).toEqual({ results: null, error: null, isSearching: false });+ });++ it("holds searches during an install and keeps its error on the shown query", async () => {+ using env = setup();+ env.themeSearch.setQuery("nord");+ await vi.advanceTimersByTimeAsync(350);+ env.requests[0]!.resolve([extension("Nord")]);+ await flush();++ const install = env.themeSearch.beginInstall();+ env.view.error = "That theme could not be added.";+ env.themeSearch.searchNow();+ expect(env.requests).toHaveLength(1);+ expect(env.themeSearch.endInstall(install)).toBe(true);+ expect(env.requests).toHaveLength(1);+ expect(env.view.error).toBe("That theme could not be added.");++ const next = env.themeSearch.beginInstall();+ env.themeSearch.setQuery("dracula");+ await vi.advanceTimersByTimeAsync(350);+ expect(env.requests).toHaveLength(1);+ env.themeSearch.endInstall(next);+ expect(env.requests.map((request) => request.query)).toEqual(["nord", "dracula"]);+ expect(env.view.error).toBeNull();+ });++ it("Enter during the debounce searches once", async () => {+ using env = setup();+ env.themeSearch.setQuery("nord");+ env.themeSearch.searchNow();+ await vi.advanceTimersByTimeAsync(350);+ expect(env.requests.map((request) => request.query)).toEqual(["nord"]);+ expect(env.requests[0]!.signal?.aborted).toBe(false);+ });++ it("closing the session aborts the search, the debounce, and the install", async () => {+ using env = setup();+ env.themeSearch.setQuery("nord");+ await vi.advanceTimersByTimeAsync(350);+ const install = env.themeSearch.beginInstall();+ env.themeSearch.setQuery("dracula");+ env.session.abort();+ await vi.advanceTimersByTimeAsync(350);+ expect(env.requests[0]!.signal?.aborted).toBe(true);+ expect(install.aborted).toBe(true);+ expect(env.requests).toHaveLength(1);+ });+});diff --git a/apps/web/src/components/settings/ThemeSearchSection.tsx b/apps/web/src/components/settings/ThemeSearchSection.tsxindex ec425140620..e255e13a7f0 100644--- a/apps/web/src/components/settings/ThemeSearchSection.tsx+++ b/apps/web/src/components/settings/ThemeSearchSection.tsx@@ -1,14 +1,13 @@import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";import { RefreshIcon } from "~/components/ui/refresh-icon";import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react";-import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";+import { type ReactNode, useState } from "react";import {importOpenVsxThemeExtension,searchOpenVsxThemes,type OpenVsxThemeExtension,type OpenVsxThemeSort,} from "../../openVsxThemes";-import { useDebouncedValue } from "../../state/queries";import {getCustomThemes,getStoredCustomThemeCollection,@@ -80,148 +79,182 @@ function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }));}-export function ThemeSearchSection({- open,- onInstalled,-}: {- open: boolean;- onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;-}) {- const [query, setQuery] = useState("");- const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");- const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);- const [error, setError] = useState<string | null>(null);- const [isSearching, setIsSearching] = useState(false);- const [installingId, setInstallingId] = useState<string | null>(null);- const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);- const requestRef = useRef<AbortController | null>(null);- // Record successful searches only; rerun after install only for changed query/sort to preserve install- // errors.- const [lastSearchKey, setLastSearchKey] = useState<string | null>(null);- const [handledSearch, setHandledSearch] = useState<{- key: string;- query: string;- fetch: boolean;- } | null>(null);- const [searchInterrupted, setSearchInterrupted] = useState(false);-- const [wasOpen, setWasOpen] = useState(open);- if (open !== wasOpen) {- setWasOpen(open);- if (open) {- setQuery("");- setSortBy("downloadCount");- setResults(null);- setError(null);- setIsSearching(false);- setInstallingId(null);- setPendingUpdate(null);- setLastSearchKey(null);- setHandledSearch(null);- setSearchInterrupted(false);- }- }+export interface ThemeSearchView {+ readonly setResults: (results: ReadonlyArray<OpenVsxThemeExtension> | null) => void;+ readonly setError: (error: string | null) => void;+ readonly setIsSearching: (isSearching: boolean) => void;+}- useEffect(() => {- if (!open) return;- return () => {- requestRef.current?.abort();- requestRef.current = null;- };- }, [open]);+type SearchThemes = typeof searchOpenVsxThemes;- const queryCleared = !query.trim() && installingId === null;- if (- queryCleared &&- (results !== null ||- error !== null ||- isSearching ||- lastSearchKey !== null ||- handledSearch !== null)- ) {- setResults(null);- setError(null);- setIsSearching(false);- setLastSearchKey(null);- setHandledSearch(null);- }-- useEffect(() => {- if (!queryCleared) return;- requestRef.current?.abort();- requestRef.current = null;- }, [queryCleared]);+/**+ * Owns one dialog session's Open VSX traffic: the input debounce, the request in+ * flight, and which key the shown results belong to. Aborting `signal` (the+ * dialog closing) cancels all of it, including an install.+ */+export function createThemeSearch(+ view: ThemeSearchView,+ signal: AbortSignal,+ search: SearchThemes = searchOpenVsxThemes,+) {+ let query = "";+ let sortBy: OpenVsxThemeSort = "downloadCount";+ let debounce: ReturnType<typeof setTimeout> | null = null;+ let request: AbortController | null = null;+ let install: AbortController | null = null;+ // Record successful searches only; rerun after install only for changed query/sort to preserve install+ // errors.+ let shownKey: string | null = null;+ let handledKey: string | null = null;+ let interrupted = false;- const startRequest = () => {- requestRef.current?.abort();- const controller = new AbortController();- requestRef.current = controller;- return controller;+ const keyOf = () => `${query}\u0000${sortBy}`;+ const abortRequest = () => {+ request?.abort();+ request = null;+ };+ const cancelDebounce = () => {+ if (debounce !== null) clearTimeout(debounce);+ debounce = null;};- const fetchResults = (trimmed: string, controller: AbortController) => {- const key = `${trimmed}\u0000${sortBy}`;- void searchOpenVsxThemes(trimmed, { signal: controller.signal, sortBy })+ const fetchResults = () => {+ abortRequest();+ const controller = new AbortController();+ request = controller;+ const key = keyOf();+ void search(query, { signal: controller.signal, sortBy }).then(- (nextResults) => {+ (results) => {if (controller.signal.aborted) return;- setResults(nextResults);- setLastSearchKey(key);+ view.setResults(results);+ shownKey = key;},(cause: unknown) => {if (controller.signal.aborted) return;- setResults(null);- setLastSearchKey(null);- setError(cause instanceof Error ? cause.message : "Open VSX search failed.");+ view.setResults(null);+ shownKey = null;+ view.setError(cause instanceof Error ? cause.message : "Open VSX search failed.");},).then(() => {- if (requestRef.current !== controller) return;- requestRef.current = null;- setIsSearching(false);+ if (request !== controller) return;+ request = null;+ view.setIsSearching(false);});};- const runSearch = (searchText: string) => {- const trimmed = searchText.trim();- if (!trimmed) return;- setError(null);- setIsSearching(true);- fetchResults(trimmed, startRequest());+ const clear = () => {+ cancelDebounce();+ abortRequest();+ shownKey = null;+ handledKey = null;+ view.setResults(null);+ view.setError(null);+ view.setIsSearching(false);};- const debouncedQuery = useDebouncedValue(query.trim(), SEARCH_DEBOUNCE_MS);- const searchKey = `${debouncedQuery}\u0000${sortBy}`;- const searchSettled =- open && installingId === null && debouncedQuery !== "" && debouncedQuery === query.trim();+ const settle = () => {+ if (install !== null || signal.aborted || query === "") return;+ const key = keyOf();+ const keyChanged = handledKey !== key;+ if (!keyChanged && !interrupted) return;+ handledKey = key;+ interrupted = false;+ const shouldFetch = shownKey !== key;+ if (shouldFetch || keyChanged) view.setError(null);+ view.setIsSearching(shouldFetch);+ if (shouldFetch) fetchResults();+ else abortRequest();+ };- const keyChanged = handledSearch?.key !== searchKey;- if (searchSettled && (keyChanged || searchInterrupted)) {- const fetch = lastSearchKey !== searchKey;- setHandledSearch({ key: searchKey, query: debouncedQuery, fetch });- setSearchInterrupted(false);- if (fetch || keyChanged) setError(null);- setIsSearching(fetch);- }+ signal.addEventListener(+ "abort",+ () => {+ cancelDebounce();+ abortRequest();+ install?.abort();+ },+ { once: true },+ );- const fetchHandledSearch = useEffectEvent((searchText: string) => {- fetchResults(searchText, startRequest());- });+ return {+ /** An unsettled query would hit Open VSX for text that is no longer visible, so typing waits. */+ setQuery(nextQuery: string) {+ const trimmed = nextQuery.trim();+ if (trimmed === query) return;+ query = trimmed;+ cancelDebounce();+ if (trimmed === "") {+ if (install === null) clear();+ return;+ }+ debounce = setTimeout(() => {+ debounce = null;+ settle();+ }, SEARCH_DEBOUNCE_MS);+ },+ setSortBy(nextSort: OpenVsxThemeSort) {+ sortBy = nextSort;+ if (debounce === null) settle();+ },+ /** Enter or re-picking the current suggestion searches again even for the shown key. */+ searchNow() {+ if (install !== null || signal.aborted || query === "") return;+ // A pending debounce for the same key would otherwise restart this search.+ cancelDebounce();+ handledKey = keyOf();+ interrupted = false;+ view.setError(null);+ view.setIsSearching(true);+ fetchResults();+ },+ beginInstall(): AbortSignal {+ abortRequest();+ install?.abort();+ install = new AbortController();+ interrupted = true;+ view.setIsSearching(false);+ return install.signal;+ },+ endInstall(installSignal: AbortSignal): boolean {+ if (install?.signal !== installSignal) return false;+ install = null;+ if (query === "") clear();+ else if (debounce === null) settle();+ return true;+ },+ };+}- useEffect(() => {- if (!handledSearch) return;- if (handledSearch.fetch) {- fetchHandledSearch(handledSearch.query);- return;- }- requestRef.current?.abort();- requestRef.current = null;- }, [handledSearch]);+export function ThemeSearchSection({+ signal,+ onInstalled,+}: {+ signal: AbortSignal;+ onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;+}) {+ const [query, setQuery] = useState("");+ const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");+ const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [isSearching, setIsSearching] = useState(false);+ const [installingId, setInstallingId] = useState<string | null>(null);+ const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);+ const [themeSearch] = useState(() =>+ createThemeSearch({ setResults, setError, setIsSearching }, signal),+ );++ const changeQuery = (nextQuery: string) => {+ setQuery(nextQuery);+ themeSearch.setQuery(nextQuery);+ };const handleSortChange = (value: OpenVsxThemeSort | null) => {const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;if (!nextSort) return;setSortBy(nextSort);+ themeSearch.setSortBy(nextSort);};const handleInstall = async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {@@ -239,29 +272,22 @@ export function ThemeSearchSection({return;}- requestRef.current?.abort();- const controller = new AbortController();- requestRef.current = controller;- setIsSearching(false);- setSearchInterrupted(true);+ const installSignal = themeSearch.beginInstall();setInstallingId(extension.id);try {- const themes = await importOpenVsxThemeExtension(extension, controller.signal);- if (!controller.signal.aborted) {+ const themes = await importOpenVsxThemeExtension(extension, installSignal);+ if (!installSignal.aborted) {const imported = replaceCustomThemeCollection(extension.collectionId, themes, {expectedCollection: installedCollection,});onInstalled(imported, { updated });}} catch (cause) {- if (!controller.signal.aborted) {+ if (!installSignal.aborted) {setError(cause instanceof Error ? cause.message : "That theme could not be added.");}}- if (requestRef.current === controller) {- requestRef.current = null;- setInstallingId(null);- }+ if (themeSearch.endInstall(installSignal)) setInstallingId(null);};return (@@ -281,11 +307,11 @@ export function ThemeSearchSection({<InputGroupInputaria-label="Search Open VSX themes"autoFocus- onChange={(event) => setQuery(event.currentTarget.value)}+ onChange={(event) => changeQuery(event.currentTarget.value)}onKeyDown={(event) => {if (event.nativeEvent.isComposing || event.keyCode === 229) return;if (event.key === "Enter" && !isSearching && installingId === null)- runSearch(query.trim());+ themeSearch.searchNow();}}placeholder="Search themes..."size="lg"@@ -306,9 +332,9 @@ export function ThemeSearchSection({variant="ghost"onClick={() => {if (query.trim() === suggestion) {- runSearch(suggestion);+ themeSearch.searchNow();} else {- setQuery(suggestion);+ changeQuery(suggestion);}}}>diff --git a/apps/web/src/components/settings/TypographySettings.browser.test.tsx b/apps/web/src/components/settings/TypographySettings.browser.test.tsxnew file mode 100644index 00000000000..bf6f03b3670--- /dev/null+++ b/apps/web/src/components/settings/TypographySettings.browser.test.tsx@@ -0,0 +1,43 @@+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";+import * as Schema from "effect/Schema";+import { describe, expect, it, vi } from "vite-plus/test";++import "~/index.css";+import { render } from "../../../test/render";+import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";+import { getLocalStorageItem, removeLocalStorageItem } from "../../hooks/useLocalStorage";+import { TypographySection } from "./TypographySettings";++const state = vi.hoisted(() => ({ searchTargetId: null as string | null }));++vi.mock(import("./useScopedSettings"), async (original) => ({+ ...(await original()),+ useScopedSettings: (() => DEFAULT_UNIFIED_SETTINGS) as never,+ useUpdateScopedSettings: (() => vi.fn()) as never,+}));+// The previews mount Ghostty and Shiki, which this test does not exercise.+vi.mock(import("./SettingsFontPreviews"), () => ({+ CodeFontPreview: () => <div />,+ PromptFontPreview: () => <div />,+ TerminalFontPreview: () => <div />,+}));+vi.mock(import("./settingsLayout"), async (original) => ({+ ...(await original()),+ useSettingsSearchTargetId: () => state.searchTargetId,+}));++function setup(searchTargetId: string | null) {+ state.searchTargetId = searchTargetId;+ removeLocalStorageItem(TYPOGRAPHY_ADVANCED_STORAGE_KEY);+ return { [Symbol.dispose]: () => removeLocalStorageItem(TYPOGRAPHY_ADVANCED_STORAGE_KEY) };+}++describe("TypographySection", () => {+ it("persists the advanced flag the terminal reads when a deep link targets an advanced row", async () => {+ using _storage = setup("terminal-font");+ await using screen = await render(<TypographySection />);++ await expect.element(screen.getByRole("heading", { name: "Terminal font" })).toBeVisible();+ expect(getLocalStorageItem(TYPOGRAPHY_ADVANCED_STORAGE_KEY, Schema.Boolean)).toBe(true);+ });+});diff --git a/apps/web/src/components/settings/TypographySettings.tsx b/apps/web/src/components/settings/TypographySettings.tsxindex f991a49bbd4..067fca68b8e 100644--- a/apps/web/src/components/settings/TypographySettings.tsx+++ b/apps/web/src/components/settings/TypographySettings.tsx@@ -36,7 +36,11 @@ import {SettingsSection,useSettingsSearchTargetId,} from "./settingsLayout";-import { searchableSetting } from "./settingsSearch";+import {+ isAdvancedTypographyTarget,+ revealSettingsSearchTarget,+ searchableSetting,+} from "./settingsSearch";function useFontDefaultFamilies() {const settings = useScopedSettings();@@ -292,30 +296,21 @@ function SimpleFontRows() {);}-// Font smoothing only renders on macOS, so a search jump to it elsewhere-// must not flip the section - the target would never mount to be scrolled to.-const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([- "prompt-font",- "terminal-font",- ...(typeof navigator !== "undefined" && isMacPlatform(navigator.platform)- ? ["font-smoothing"]- : []),-]);-export function TypographySection() {const [advanced, setAdvanced] = useLocalStorage(TYPOGRAPHY_ADVANCED_STORAGE_KEY,false,Schema.Boolean,);+ // A deep link or history step must persist the flag too: the terminal reads it, so advanced+ // rows without it would make terminal font edits do nothing. The rows follow the target+ // directly so its row mounts in the first commit; the target clears once handled.const searchTargetId = useSettingsSearchTargetId();- const lastExpandedTargetRef = useRef<string | null>(null);useEffect(() => {- if (searchTargetId === null || !ADVANCED_TYPOGRAPHY_TARGET_IDS.has(searchTargetId)) return;- if (lastExpandedTargetRef.current === searchTargetId) return;- lastExpandedTargetRef.current = searchTargetId;- setAdvanced(true);- }, [searchTargetId, setAdvanced]);+ if (searchTargetId !== null) revealSettingsSearchTarget(searchTargetId);+ }, [searchTargetId]);+ const showAdvanced =+ advanced || (searchTargetId !== null && isAdvancedTypographyTarget(searchTargetId));return (<SettingsSectionid="typography"@@ -324,14 +319,14 @@ export function TypographySection() {<label className="flex cursor-pointer items-center gap-2 text-xs font-medium text-muted-foreground">Advanced<Switch- checked={advanced}+ checked={showAdvanced}onCheckedChange={(checked) => setAdvanced(Boolean(checked))}aria-label="Show advanced typography settings"/></label>}>- {advanced ? <FontSettingsGroup /> : <SimpleFontRows />}+ {showAdvanced ? <FontSettingsGroup /> : <SimpleFontRows />}<WordWrapRow /></SettingsSection>);diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex 05a066406ef..6ebea8d80e6 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -9,6 +9,9 @@ import {type SourceControlDefinition,} from "@t3tools/client-runtime/source-control-clients";import { DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings";+import * as Schema from "effect/Schema";+import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";+import { writeLocalStorageValue } from "../../hooks/useLocalStorage";import { commandLabel } from "./KeybindingsSettings.logic";import {validateSettingsScopeSearch,@@ -1233,3 +1236,28 @@ export function searchSettings().map(({ item }) => item);}++// Font smoothing only renders on macOS, so a search jump to it elsewhere+// must not flip the section - the target would never mount to be scrolled to.+const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([+ "prompt-font",+ "terminal-font",+ ...(typeof navigator !== "undefined" && isMacPlatform(navigator.platform)+ ? ["font-smoothing"]+ : []),+]);++export function isAdvancedTypographyTarget(targetId: string): boolean {+ return ADVANCED_TYPOGRAPHY_TARGET_IDS.has(targetId);+}++/**+ * Opens the persisted section a search result lives in before jumping to it, so+ * its row is mounted to scroll to. The terminal reads the same flag, so it must+ * stay on after the jump.+ */+export function revealSettingsSearchTarget(targetId: string): void {+ if (isAdvancedTypographyTarget(targetId)) {+ writeLocalStorageValue(TYPOGRAPHY_ADVANCED_STORAGE_KEY, true, false, Schema.Boolean);+ }+}diff --git a/apps/web/src/hooks/useLocalStorage.ts b/apps/web/src/hooks/useLocalStorage.tsindex 0a395db6348..cd6d2f4fcb8 100644--- a/apps/web/src/hooks/useLocalStorage.ts+++ b/apps/web/src/hooks/useLocalStorage.ts@@ -123,7 +123,7 @@ function decodeOrInitial<T, E>(}}-function writeLocalStorageValue<T, E>(+export function writeLocalStorageValue<T, E>(key: string,value: T | ((val: T) => T),initialValue: T,diff --git a/apps/web/src/state/session.ts b/apps/web/src/state/session.tsindex eb441ffec37..caf3f99c07d 100644--- a/apps/web/src/state/session.ts+++ b/apps/web/src/state/session.ts@@ -33,7 +33,7 @@ export function useEnvironmentScope(return sessionHasScope(result, scope);}-function sessionHasScope(+export function sessionHasScope(result: AsyncResult.AsyncResult<AuthSessionState, unknown>,scope: AuthEnvironmentScope,): boolean {diff --git a/apps/web/src/state/terminalSessions.test.ts b/apps/web/src/state/terminalSessions.test.tsindex 5d9256ec3fd..c4b55772b34 100644--- a/apps/web/src/state/terminalSessions.test.ts+++ b/apps/web/src/state/terminalSessions.test.ts@@ -1,10 +1,32 @@import { describe, expect, it, vi } from "vite-plus/test";import { EnvironmentId, ThreadId, type TerminalSummary } from "@t3tools/contracts";import { selectRunningSubprocessTerminalIds } from "@t3tools/client-runtime/state/terminal";+import { AtomRegistry } from "effect/reactivity";-import { selectKnownTerminalSessions } from "./terminalSessions";+import { attachedTerminalSessionAtom, selectKnownTerminalSessions } from "./terminalSessions";-vi.mock("./terminal", () => ({ terminalEnvironment: {} }));+const attachCalls = vi.hoisted(() => [] as unknown[]);+vi.mock("./terminal", async () => {+ const { AsyncResult, Atom } = await import("effect/reactivity");+ return {+ terminalEnvironment: {+ attach: (request: unknown) => {+ attachCalls.push(request);+ return Atom.make(AsyncResult.initial(true));+ },+ metadata: () => Atom.make(AsyncResult.initial(true)),+ },+ };+});+vi.mock("./session", async () => {+ const { AsyncResult, Atom } = await import("effect/reactivity");+ const granted = Atom.make(AsyncResult.success({}));+ return {+ environmentSession: { sessionStateAtom: () => granted },+ sessionHasScope: () => true,+ useEnvironmentScope: () => true,+ };+});const environmentA = EnvironmentId.make("environment-a");const threadA = ThreadId.make("thread-a");@@ -77,3 +99,21 @@ describe("selectKnownTerminalSessions", () => {expect(selectKnownTerminalSessions([other], environmentA, threadB)).toBe(beforeB);});});++describe("attachedTerminalSessionAtom", () => {+ it("attaches with the launch input it was keyed by", () => {+ attachCalls.length = 0;+ const input = {+ threadId: threadA,+ terminalId: "terminal-1",+ cwd: "/repo",+ worktreePath: null,+ env: { T3CODE_PROJECT_ROOT: "/repo" },+ };+ const atom = attachedTerminalSessionAtom(environmentA, input);+ expect(attachedTerminalSessionAtom(environmentA, { ...input })).toBe(atom);++ AtomRegistry.make().get(atom);+ expect(attachCalls).toEqual([{ environmentId: environmentA, input }]);+ });+});diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.tsindex 51fe87aa892..3683a8fba6d 100644--- a/apps/web/src/state/terminalSessions.ts+++ b/apps/web/src/state/terminalSessions.ts@@ -7,17 +7,21 @@ import {type TerminalSessionState,} from "@t3tools/client-runtime/state/terminal";import {+ EnvironmentId,ThreadId,AuthTerminalReadScope,AuthTerminalOperateScope,- type EnvironmentId,- type TerminalAttachInput,+ TerminalAttachInput,type TerminalSummary,} from "@t3tools/contracts";-import { useEnvironmentQuery } from "./query";+import * as Option from "effect/Option";+import * as Schema from "effect/Schema";+import { AsyncResult, Atom } from "effect/reactivity";++import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query";import { terminalEnvironment } from "./terminal";-import { useEnvironmentScope } from "./session";+import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session";const EMPTY_KNOWN_TERMINAL_SESSIONS = Object.freeze<ReadonlyArray<KnownTerminalSession>>([]);@@ -121,47 +125,72 @@ export function selectKnownTerminalSessions(return sessions;}-export function useAttachedTerminalSession(input: {- readonly environmentId: EnvironmentId | null;- readonly terminal: TerminalAttachInput | null;-}): TerminalSessionState {- const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);- const canOperate = useEnvironmentScope(input.environmentId, AuthTerminalOperateScope);- const attach = useEnvironmentQuery(- input.environmentId !== null && input.terminal !== null- ? canOperate- ? terminalEnvironment.attach({- environmentId: input.environmentId,- input: input.terminal,- })- : canRead- ? terminalEnvironment.observe({- environmentId: input.environmentId,- input: { threadId: input.terminal.threadId, terminalId: input.terminal.terminalId },- })- : null- : null,- );- const metadata = useEnvironmentQuery(- input.environmentId === null || !canRead- ? null- : terminalEnvironment.metadata({- environmentId: input.environmentId,- input: null,- }),- );+const EMPTY_TERMINAL_SESSION_ATOM = Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe(+ Atom.withLabel("web-terminal-session:empty"),+);- if (input.environmentId === null || input.terminal === null) {- return EMPTY_TERMINAL_SESSION_STATE;+const decodeAttachKey = Schema.decodeUnknownOption(+ Schema.fromJsonString(Schema.Tuple([EnvironmentId, TerminalAttachInput])),+);++// The family key carries the whole launch so an idle atom leaves nothing behind.+const attachedTerminalSessionFamily = Atom.family((key: string) => {+ const decoded = decodeAttachKey(key);+ if (Option.isNone(decoded)) {+ return Atom.make<TerminalSessionState>({+ ...EMPTY_TERMINAL_SESSION_STATE,+ error: "Invalid terminal launch input",+ status: "error",+ }).pipe(Atom.withLabel(`web-terminal-session:${key}`));}- const summary =- (metadata.data === null- ? null- : terminalMetadataIndex(metadata.data)- .byThreadId.get(input.terminal.threadId)- ?.find((terminal) => terminal.terminalId === input.terminal?.terminalId)) ?? null;- const state = combineTerminalSessionState(summary, attach.data ?? EMPTY_TERMINAL_BUFFER_STATE);- return attach.error === null ? state : { ...state, error: attach.error, status: "error" };+ const [environmentId, terminal] = decoded.value;+ return Atom.make((get): TerminalSessionState => {+ const session = get(environmentSession.sessionStateAtom(environmentId));+ const canRead = sessionHasScope(session, AuthTerminalReadScope);+ const canOperate = sessionHasScope(session, AuthTerminalOperateScope);+ const attach = canOperate+ ? get(terminalEnvironment.attach({ environmentId, input: terminal }))+ : canRead+ ? get(+ terminalEnvironment.observe({+ environmentId,+ input: { threadId: terminal.threadId, terminalId: terminal.terminalId },+ }),+ )+ : null;+ const metadata = canRead+ ? Option.getOrNull(+ AsyncResult.value(get(terminalEnvironment.metadata({ environmentId, input: null }))),+ )+ : null;+ const summary =+ (metadata === null+ ? null+ : terminalMetadataIndex(metadata)+ .byThreadId.get(terminal.threadId)+ ?.find((candidate) => candidate.terminalId === terminal.terminalId)) ?? null;+ const buffer =+ attach === null+ ? EMPTY_TERMINAL_BUFFER_STATE+ : Option.getOrElse(AsyncResult.value(attach), () => EMPTY_TERMINAL_BUFFER_STATE);+ const state = combineTerminalSessionState(summary, buffer);+ return attach?._tag === "Failure"+ ? { ...state, error: formatEnvironmentQueryError(attach.cause), status: "error" }+ : state;+ }).pipe(Atom.withLabel(`web-terminal-session:${key}`));+});++/**+ * One shown terminal's session: its attach (or read-only observe) buffer+ * combined with the metadata summary. Surfaces subscribe to it imperatively so+ * output chunks never re-render React.+ */+export function attachedTerminalSessionAtom(+ environmentId: EnvironmentId | null,+ terminal: TerminalAttachInput | null,+): Atom.Atom<TerminalSessionState> {+ if (environmentId === null || terminal === null) return EMPTY_TERMINAL_SESSION_ATOM;+ return attachedTerminalSessionFamily(JSON.stringify([environmentId, terminal]));}export function useKnownTerminalSessions(input: {