The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 15:45 UTC
refactor(web): terminal output no longer re-renders the drawer, theme search runs from handlers (#25458)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 05:56 UTC
28df7a246f9f7063180f9a4c509ee17c6823b32b
17 files changed
+958
-626
apps/web/src/components/ThreadTerminalDrawer.test.ts
+14
@@ -11,6 +11,7 @@ import {
11
shouldClearTerminalSelectionAction,
12
shouldHandleTerminalExit,
13
synchronizeTerminalOutput,
14
+ synchronizeTerminalSession,
15
} from "./ThreadTerminalDrawer";
16
17
describe("terminal selection actions", () => {
@@ -87,3 +88,16 @@ it("retains visible output and selection until a replacement subscription receiv
88
synchronizeTerminalOutput(terminal, cleared, observedCursor);
89
expect(terminal.resetAndWrite).toHaveBeenLastCalledWith("");
90
});
91
+
92
+it("reports an attach failure that leaves the output unchanged", () => {
93
+ const terminal = { resetAndWrite: vi.fn(), write: vi.fn(), clearSelection: vi.fn() };
94
+ const previous = { ...EMPTY_TERMINAL_BUFFER_STATE, error: null };
95
+ const failed = { ...previous, error: "Terminal attach failed" };
96
+
97
+ expect(
98
+ synchronizeTerminalSession(terminal, previous, failed, INITIAL_TERMINAL_OUTPUT_CURSOR),
99
+ ).toBe(INITIAL_TERMINAL_OUTPUT_CURSOR);
100
+ expect(terminal.write).toHaveBeenCalledWith("\r\n[terminal] Terminal attach failed\r\n");
101
+ expect(terminal.resetAndWrite).not.toHaveBeenCalled();
102
+ expect(terminal.clearSelection).not.toHaveBeenCalled();
103
+});
apps/web/src/components/ThreadTerminalDrawer.tsx
+106
-173
@@ -1,4 +1,4 @@
1
-import { useAtomValue } from "@effect/atom-react";
1
+import { useAtomMount, useAtomValue } from "@effect/atom-react";
2
import {
3
isAtomCommandInterrupted,
4
squashAtomCommandFailure,
@@ -33,7 +33,6 @@ import * as Schema from "effect/Schema";
33
import {
34
type PointerEvent as ReactPointerEvent,
35
type ReactNode,
36
- type SetStateAction,
36
useEffect,
37
useEffectEvent,
38
useLayoutEffect,
@@ -79,7 +78,8 @@ import { readLocalApi } from "~/localApi";
78
import { confirmTerminalClose } from "~/lib/terminalCloseConfirm";
79
import { useClientSettings } from "../hooks/useSettings";
80
import { useLocalStorage } from "../hooks/useLocalStorage";
82
-import { useAttachedTerminalSession } from "../state/terminalSessions";
81
+import { attachedTerminalSessionAtom } from "../state/terminalSessions";
82
+import { appAtomRegistry } from "../rpc/atomRegistry";
83
import { serverEnvironment } from "../state/server";
84
import { previewEnvironment } from "../state/preview";
85
import { readEnvironmentScope } from "../state/session";
@@ -125,6 +125,8 @@ function resolveTerminalDrawerMaxHeight(input: DrawerLayout): number {
125
);
126
}
127
128
+const DRAG_HEIGHT_PROPERTY = "--terminal-drawer-drag-height";
129
+
130
function clampDrawerHeight(height: number, maxHeight: number): number {
131
const safeHeight = Number.isFinite(height) ? height : DEFAULT_THREAD_TERMINAL_HEIGHT;
132
return Math.min(Math.max(Math.round(safeHeight), MIN_DRAWER_HEIGHT), maxHeight);
@@ -144,7 +146,10 @@ function readDrawerLayout(column: HTMLElement | null): Omit<DrawerLayout, "compo
146
};
147
}
148
147
-function writeSystemMessage(terminal: GhosttyTerminalSurface, message: string): void {
149
+function writeSystemMessage(
150
+ terminal: Pick<GhosttyTerminalSurface, "write">,
151
+ message: string,
152
+): void {
153
terminal.write(`\r\n[terminal] ${message}\r\n`);
154
}
155
@@ -171,6 +176,24 @@ export function synchronizeTerminalOutput(
176
return update.cursor;
177
}
178
179
+/** Writes what changed between two session notifications: new output, then a new error. */
180
+export function synchronizeTerminalSession(
181
+ terminal: Pick<GhosttyTerminalSurface, "resetAndWrite" | "write" | "clearSelection">,
182
+ previous: Pick<TerminalSessionState, "output" | "version" | "error">,
183
+ session: Pick<TerminalSessionState, "output" | "version" | "error">,
184
+ cursor: TerminalOutputCursor,
185
+): TerminalOutputCursor {
186
+ const nextCursor =
187
+ session.version === previous.version && session.output === previous.output
188
+ ? cursor
189
+ : synchronizeTerminalOutput(terminal, session, cursor);
190
+ // An attach failure can change only the error, keeping the last buffer.
191
+ if (session.error !== null && session.error !== previous.error) {
192
+ writeSystemMessage(terminal, session.error);
193
+ }
194
+ return nextCursor;
195
+}
196
+
197
function parseTerminalColor(value: string, fallback: GhosttyColor): GhosttyColor {
198
if (typeof document === "undefined") return fallback;
199
@@ -400,6 +423,19 @@ export function shouldClearTerminalSelectionAction(options: {
423
return options.actionPending || options.openMenuRequestId === options.currentRequestId;
424
}
425
426
+/**
427
+ * A writable session's output generation. A new one is a fresh PTY (or a
428
+ * reconnect) that has not seen the surface's grid yet.
429
+ */
430
+function writableSessionGeneration(
431
+ session: TerminalSessionState,
432
+ canOperate: boolean,
433
+): number | null {
434
+ return canOperate && session.version > 0 && session.status === "running"
435
+ ? session.output.generation
436
+ : null;
437
+}
438
+
439
export function shouldHandleTerminalExit(
440
current: TerminalSessionState["status"],
441
synchronized: TerminalSessionState["status"],
@@ -429,8 +465,6 @@ interface TerminalViewportProps {
465
/** Focuses the viewport when it mounts; otherwise focus arrives through `focusTerminal`. */
466
autoFocus?: boolean;
467
visible: boolean;
432
- resizeEpoch: number;
433
- drawerHeight: number;
468
keybindings: ResolvedKeybindingsConfig;
469
}
470
@@ -466,8 +500,6 @@ function TerminalSessionViewport({
500
onAddTerminalContext,
501
autoFocus = false,
502
visible,
469
- resizeEpoch,
470
- drawerHeight,
503
keybindings,
504
}: TerminalViewportProps) {
505
const containerRef = useRef<HTMLDivElement>(null);
@@ -526,20 +558,23 @@ function TerminalSessionViewport({
558
}),
559
);
560
const terminalFontRef = useRef({ family: terminalFontFamily, size: terminalFontSize });
529
- const terminalSession = useAttachedTerminalSession({
530
- environmentId,
531
- terminal: {
532
- threadId,
533
- terminalId,
534
- cwd,
535
- ...(worktreePath !== undefined ? { worktreePath } : {}),
536
- ...(runtimeEnv ? { env: runtimeEnv } : {}),
537
- ...(providerInstanceId ? { providerInstanceId } : {}),
538
- },
561
+ // Keyed by the launch (see TerminalViewport), so the atom is fixed for this surface.
562
+ const terminalSessionAtom = attachedTerminalSessionAtom(environmentId, {
563
+ threadId,
564
+ terminalId,
565
+ cwd,
566
+ ...(worktreePath !== undefined ? { worktreePath } : {}),
567
+ ...(runtimeEnv ? { env: runtimeEnv } : {}),
568
+ ...(providerInstanceId ? { providerInstanceId } : {}),
569
});
540
- const canResizeTerminal =
541
- canOperateTerminal && terminalSession.version > 0 && terminalSession.status === "running";
542
- const resizeSessionGeneration = canResizeTerminal ? terminalSession.output.generation : null;
570
+ // Attaching starts with the viewport, while the WASM surface is still loading;
571
+ // the surface reads the session itself, so output chunks never re-render here.
572
+ useAtomMount(terminalSessionAtom);
573
+ const readTerminalSession = useEffectEvent(() => appAtomRegistry.get(terminalSessionAtom));
574
+ const subscribeTerminalSession = useEffectEvent(
575
+ (listener: (session: TerminalSessionState) => void) =>
576
+ appAtomRegistry.subscribe(terminalSessionAtom, listener),
577
+ );
578
const writeTerminal = useEffectEvent((data: string) =>
579
runTerminalWrite({
580
environmentId,
@@ -547,15 +582,14 @@ function TerminalSessionViewport({
582
}),
583
);
584
const resizeTerminal = useEffectEvent((cols: number, rows: number) => {
550
- if (!canResizeTerminal || !hasTerminalWriteAccess()) return;
585
+ if (writableSessionGeneration(readTerminalSession(), hasTerminalWriteAccess()) === null) {
586
+ return;
587
+ }
588
return runTerminalResize({
589
environmentId,
590
input: { threadId, terminalId, cols, rows },
591
});
592
});
556
- const terminalOutput = terminalSession.output;
557
- const terminalError = terminalSession.error;
558
- const terminalStatus = terminalSession.status;
593
const outputCursorRef = useRef<TerminalOutputCursor>(INITIAL_TERMINAL_OUTPUT_CURSOR);
594
const synchronizedStatusRef = useRef<TerminalSessionState["status"]>("closed");
595
const synchronizeTerminalStatus = useEffectEvent(
@@ -577,19 +611,6 @@ function TerminalSessionViewport({
611
if (version > 0) synchronizedStatusRef.current = status;
612
},
613
);
580
- const terminalVersion = terminalSession.version;
581
- const previousSessionRef = useRef({
582
- output: terminalOutput,
583
- error: terminalError,
584
- status: terminalStatus,
585
- version: terminalVersion,
586
- });
587
- const readLatestSession = useEffectEvent(() => ({
588
- output: terminalOutput,
589
- error: terminalError,
590
- status: terminalStatus,
591
- version: terminalVersion,
592
- }));
614
const openLinkInPreview = useEffectEvent(
615
(url: string, forceBrowser: boolean, fallbackToBrowser: () => void) =>
616
openTerminalLinkInPreview({ url, threadRef, openPreview, fallbackToBrowser, forceBrowser }),
@@ -609,13 +630,6 @@ function TerminalSessionViewport({
630
terminalRef.current?.refreshLinkActivation();
631
}, [canOpenHostEditor]);
632
612
- useEffect(() => {
613
- if (resizeSessionGeneration === null) return;
614
- // The first fit can precede authorization/attach; replay the grid for each writable session, including
615
- // reconnects.
616
- terminalRef.current?.resendSize();
617
- }, [resizeSessionGeneration]);
618
-
633
useLayoutEffect(() => {
634
visibleRef.current = visible;
635
terminalRef.current?.setVisible(visible);
@@ -673,8 +687,7 @@ function TerminalSessionViewport({
687
if (currentFont.family !== setupFont.family || currentFont.size !== setupFont.size) {
688
void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size));
689
}
676
- const latestSession = readLatestSession();
677
- previousSessionRef.current = latestSession;
690
+ const latestSession = readTerminalSession();
691
const initialOutput = readTerminalOutputUpdate(
692
latestSession.output,
693
INITIAL_TERMINAL_OUTPUT_CURSOR,
@@ -686,6 +699,29 @@ function TerminalSessionViewport({
699
if (latestSession.error !== null) writeSystemMessage(terminal, latestSession.error);
700
synchronizedStatusRef.current = "closed";
701
synchronizeTerminalStatus(terminal, latestSession.status, latestSession.version);
702
+ // Read and subscribe in one synchronous step so no output lands between them.
703
+ let previousSession = latestSession;
704
+ let resizeGeneration = writableSessionGeneration(latestSession, hasTerminalWriteAccess());
705
+ setupCleanups.push(
706
+ subscribeTerminalSession((session) => {
707
+ const nextResizeGeneration = writableSessionGeneration(session, hasTerminalWriteAccess());
708
+ if (nextResizeGeneration !== resizeGeneration) {
709
+ resizeGeneration = nextResizeGeneration;
710
+ // The first fit can precede authorization/attach; replay the grid for each writable session, including
711
+ // reconnects.
712
+ if (nextResizeGeneration !== null) terminal.resendSize();
713
+ }
714
+ const previous = previousSession;
715
+ previousSession = session;
716
+ synchronizeTerminalStatus(terminal, session.status, session.version);
717
+ outputCursorRef.current = synchronizeTerminalSession(
718
+ terminal,
719
+ previous,
720
+ session,
721
+ outputCursorRef.current,
722
+ );
723
+ }),
724
+ );
725
if (
726
hasTerminalWriteAccess() &&
727
visibleRef.current &&
@@ -1075,53 +1111,6 @@ function TerminalSessionViewport({
1111
};
1112
}, [cwd, environmentId, terminalId]);
1113
1078
- useEffect(() => {
1079
- const terminal = terminalRef.current;
1080
- const current = {
1081
- output: terminalOutput,
1082
- error: terminalError,
1083
- status: terminalStatus,
1084
- version: terminalVersion,
1085
- };
1086
- if (!terminal) {
1087
- previousSessionRef.current = current;
1088
- return;
1089
- }
1090
-
1091
- const previous = previousSessionRef.current;
1092
- synchronizeTerminalStatus(terminal, current.status, current.version);
1093
- if (current.version === previous.version && current.output === previous.output) {
1094
- return;
1095
- }
1096
-
1097
- outputCursorRef.current = synchronizeTerminalOutput(terminal, current, outputCursorRef.current);
1098
-
1099
- if (current.error !== null && current.error !== previous.error) {
1100
- writeSystemMessage(terminal, current.error);
1101
- }
1102
-
1103
- previousSessionRef.current = current;
1104
- }, [terminalOutput, terminalError, terminalStatus, terminalVersion]);
1105
-
1106
- // A hidden surface skips fitting, and showing it again fits through setVisible.
1107
- const layoutRevision = visible ? `${drawerHeight}:${resizeEpoch}` : null;
1108
- useEffect(() => {
1109
- const terminal = terminalRef.current;
1110
- if (!terminal || layoutRevision === null) return;
1111
- const wasAtBottom = terminal.isAtBottom();
1112
- // onResize alone sends PTY resize RPCs; fitting here only refreshes layout.
1113
- const frame = window.requestAnimationFrame(() => {
1114
- if (!visibleRef.current) return;
1115
- terminal.fit();
1116
- if (wasAtBottom) {
1117
- terminal.scrollToBottom();
1118
- }
1119
- });
1120
- return () => {
1121
- window.cancelAnimationFrame(frame);
1122
- };
1123
- }, [layoutRevision]);
1124
-
1114
const attachContainer = (mount: HTMLDivElement) => {
1115
containerRef.current = mount;
1116
const focus = () =>
@@ -1245,8 +1234,6 @@ function TerminalSplitPanes({
1234
threadId,
1235
onAddTerminalContext,
1236
visible,
1248
- resizeEpoch,
1249
- drawerHeight,
1237
keybindings,
1238
}: {
1239
terminalIds: readonly string[];
@@ -1261,8 +1248,6 @@ function TerminalSplitPanes({
1248
threadId: ThreadId;
1249
onAddTerminalContext: (selection: TerminalContextSelection) => void;
1250
visible: boolean;
1264
- resizeEpoch: number;
1265
- drawerHeight: number;
1251
keybindings: ResolvedKeybindingsConfig;
1252
}) {
1253
return (
@@ -1311,8 +1296,6 @@ function TerminalSplitPanes({
1296
onSessionExited={() => onCloseTerminal(terminalId)}
1297
onAddTerminalContext={onAddTerminalContext}
1298
visible={visible}
1314
- resizeEpoch={resizeEpoch}
1315
- drawerHeight={drawerHeight}
1299
keybindings={keybindings}
1300
/>
1301
</div>
@@ -1456,36 +1439,19 @@ export default function ThreadTerminalDrawer({
1439
false,
1440
Schema.Boolean,
1441
);
1459
- const controlledDrawerHeight = height;
1442
const drawerRef = useRef<HTMLElement | null>(null);
1443
const [drawerLayout, setDrawerLayout] = useState(() => readDrawerLayout(null));
1444
const maxDrawerHeight = resolveTerminalDrawerMaxHeight({ ...drawerLayout, composerHeight });
1463
- const [drawerHeightState, setDrawerHeightState] = useState(() => ({
1464
- threadId,
1465
- height: controlledDrawerHeight,
1466
- }));
1467
- const preferredDrawerHeight =
1468
- drawerHeightState.threadId === threadId ? drawerHeightState.height : controlledDrawerHeight;
1469
- const drawerHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight);
1470
- const setDrawerHeight = (update: SetStateAction<number>) => {
1471
- setDrawerHeightState((current) => {
1472
- const currentHeight = current.threadId === threadId ? current.height : controlledDrawerHeight;
1473
- const nextHeight = typeof update === "function" ? update(currentHeight) : update;
1474
- return nextHeight === currentHeight && current.threadId === threadId
1475
- ? current
1476
- : { threadId, height: nextHeight };
1477
- });
1478
- };
1479
- const [resizeEpoch, setResizeEpoch] = useState(0);
1480
- const drawerHeightRef = useRef(drawerHeight);
1481
- const lastSyncedHeightRef = useRef({ threadId, height: controlledDrawerHeight });
1445
+ const drawerHeight = clampDrawerHeight(height, maxDrawerHeight);
1446
+ // A drag only writes the drawer's style; the store hears the height once, at
1447
+ // pointerup. The custom property outranks the rendered height while it is set.
1448
const resizeStateRef = useRef<{
1449
pointerId: number;
1450
startY: number;
1451
startHeight: number;
1452
+ height: number;
1453
drawer: HTMLElement | null;
1454
} | null>(null);
1488
- const didResizeDuringDragRef = useRef(false);
1455
1456
const normalizedTerminalIds = (() => {
1457
const normalizedIds: string[] = [];
@@ -1655,35 +1621,15 @@ export default function ThreadTerminalDrawer({
1621
});
1622
};
1623
1658
- useLayoutEffect(() => {
1659
- const resizeState = resizeStateRef.current;
1660
- if (resizeState) {
1661
- resizeState.drawer?.style.setProperty("height", `${drawerHeightRef.current}px`);
1662
- return;
1663
- }
1664
- drawerHeightRef.current = drawerHeight;
1665
- }, [drawerHeight]);
1666
-
1667
- const syncHeight = (nextHeight: number) => {
1668
- const lastSynced = lastSyncedHeightRef.current;
1669
- if (lastSynced.threadId === threadId && lastSynced.height === nextHeight) return;
1670
- lastSyncedHeightRef.current = { threadId, height: nextHeight };
1671
- onHeightChange(nextHeight);
1672
- };
1673
-
1674
- useEffect(() => {
1675
- lastSyncedHeightRef.current = { threadId, height: controlledDrawerHeight };
1676
- }, [controlledDrawerHeight, threadId]);
1677
-
1624
const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
1625
if (event.button !== 0) return;
1626
event.preventDefault();
1627
event.currentTarget.setPointerCapture(event.pointerId);
1682
- didResizeDuringDragRef.current = false;
1628
resizeStateRef.current = {
1629
pointerId: event.pointerId,
1630
startY: event.clientY,
1686
- startHeight: drawerHeightRef.current,
1631
+ startHeight: drawerHeight,
1632
+ height: drawerHeight,
1633
drawer: event.currentTarget.parentElement,
1634
};
1635
};
@@ -1696,12 +1642,11 @@ export default function ThreadTerminalDrawer({
1642
resizeState.startHeight + (resizeState.startY - event.clientY),
1643
maxDrawerHeight,
1644
);
1699
- if (clampedHeight === drawerHeightRef.current) {
1645
+ if (clampedHeight === resizeState.height) {
1646
return;
1647
}
1702
- didResizeDuringDragRef.current = true;
1703
- drawerHeightRef.current = clampedHeight;
1704
- resizeState.drawer?.style.setProperty("height", `${clampedHeight}px`);
1648
+ resizeState.height = clampedHeight;
1649
+ resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${clampedHeight}px`);
1650
};
1651
1652
const handleResizePointerEnd = (event: ReactPointerEvent<HTMLDivElement>) => {
@@ -1711,19 +1656,11 @@ export default function ThreadTerminalDrawer({
1656
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
1657
event.currentTarget.releasePointerCapture(event.pointerId);
1658
}
1659
+ resizeState.drawer?.style.removeProperty(DRAG_HEIGHT_PROPERTY);
1660
// A drag that ends where it started keeps the stored preference, which may
1661
// be taller than the capped height the drag started from.
1716
- if (!didResizeDuringDragRef.current || drawerHeightRef.current === resizeState.startHeight) {
1717
- // React skips the write when the rendered height did not change, so put
1718
- // back the preference as the current layout caps it.
1719
- const renderedHeight = clampDrawerHeight(preferredDrawerHeight, maxDrawerHeight);
1720
- drawerHeightRef.current = renderedHeight;
1721
- resizeState.drawer?.style.setProperty("height", `${renderedHeight}px`);
1722
- return;
1723
- }
1724
- setDrawerHeight(drawerHeightRef.current);
1725
- syncHeight(drawerHeightRef.current);
1726
- setResizeEpoch((value) => value + 1);
1662
+ if (resizeState.height === resizeState.startHeight || resizeState.height === height) return;
1663
+ onHeightChange(resizeState.height);
1664
};
1665
1666
const drawerLayoutRef = useRef(drawerLayout);
@@ -1740,16 +1677,17 @@ export default function ThreadTerminalDrawer({
1677
if (!heightBudgetChanged && source === "column") return;
1678
drawerLayoutRef.current = layout;
1679
const resizeState = resizeStateRef.current;
1743
- const liveHeight = clampDrawerHeight(
1744
- drawerHeightRef.current,
1745
- resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }),
1746
- );
1747
- if (resizeState && liveHeight !== drawerHeightRef.current) {
1748
- drawerHeightRef.current = liveHeight;
1749
- resizeState.drawer?.style.setProperty("height", `${liveHeight}px`);
1680
+ if (resizeState) {
1681
+ const liveHeight = clampDrawerHeight(
1682
+ resizeState.height,
1683
+ resolveTerminalDrawerMaxHeight({ ...layout, composerHeight }),
1684
+ );
1685
+ if (liveHeight !== resizeState.height) {
1686
+ resizeState.height = liveHeight;
1687
+ resizeState.drawer?.style.setProperty(DRAG_HEIGHT_PROPERTY, `${liveHeight}px`);
1688
+ }
1689
}
1690
if (heightBudgetChanged) setDrawerLayout(layout);
1752
- setResizeEpoch((value) => value + 1);
1691
},
1692
);
1693
useLayoutEffect(() => {
@@ -1774,9 +1712,6 @@ export default function ThreadTerminalDrawer({
1712
};
1713
}, [isPanel, visible]);
1714
1777
- const syncPreferredHeight = useEffectEvent(() => syncHeight(preferredDrawerHeight));
1778
- useEffect(() => () => syncPreferredHeight(), []);
1779
-
1715
if (normalizedTerminalIds.length === 0) {
1716
return (
1717
<aside
@@ -1787,7 +1722,7 @@ export default function ThreadTerminalDrawer({
1722
"relative flex min-w-0 flex-col overflow-hidden bg-background",
1723
isPanel ? "h-full flex-1" : "z-45 shrink-0 border-t border-border/80",
1724
)}
1790
- style={isPanel ? undefined : { height: `${drawerHeight}px` }}
1725
+ style={isPanel ? undefined : { height: `var(${DRAG_HEIGHT_PROPERTY}, ${drawerHeight}px)` }}
1726
>
1727
{!isPanel ? (
1728
<div
@@ -1823,7 +1758,7 @@ export default function ThreadTerminalDrawer({
1758
"relative flex min-w-0 flex-col overflow-hidden bg-background",
1759
isPanel ? "h-full flex-1" : "z-45 shrink-0 border-t border-border/80",
1760
)}
1826
- style={isPanel ? undefined : { height: `${drawerHeight}px` }}
1761
+ style={isPanel ? undefined : { height: `var(${DRAG_HEIGHT_PROPERTY}, ${drawerHeight}px)` }}
1762
>
1763
{!isPanel ? (
1764
<div
@@ -1907,8 +1842,6 @@ export default function ThreadTerminalDrawer({
1842
threadId={threadId}
1843
onAddTerminalContext={onAddTerminalContext}
1844
visible={visible}
1910
- resizeEpoch={resizeEpoch}
1911
- drawerHeight={drawerHeight}
1845
keybindings={keybindings}
1846
/>
1847
</div>
apps/web/src/components/onboarding/WelcomeWizard.tsx
-2
@@ -1157,8 +1157,6 @@ function AgentInstallTerminal({
1157
onSessionExited={onClose}
1158
autoFocus
1159
visible
1160
- resizeEpoch={0}
1161
- drawerHeight={256}
1160
keybindings={keybindings}
1161
/>
1162
) : null}
apps/web/src/components/settings/ProviderAuthTerminal.tsx
+22
-24
@@ -2,6 +2,7 @@ import type { ProviderAuthResponse } from "@t3tools/contracts";
2
import { useEffect, useRef, useState } from "react";
3
import { GhosttyTerminalSurface } from "../../terminal/ghostty/surface";
4
import { ensureLocalApi } from "../../localApi";
5
+import { useStableCallback } from "../../hooks/useStableCallback";
6
import { terminalThemeFromApp } from "../ThreadTerminalDrawer";
7
8
export default function ProviderAuthTerminal({
@@ -13,30 +14,27 @@ export default function ProviderAuthTerminal({
14
readonly outputOffset?: number | undefined;
15
readonly onResponse: (response: Extract<ProviderAuthResponse, { type: "terminal" }>) => void;
16
}) {
16
- const mount = useRef<HTMLDivElement>(null);
17
- const surface = useRef<GhosttyTerminalSurface | null>(null);
18
- const latest = useRef({ output, offset: outputOffset ?? output.length, onResponse });
17
+ const [surface, setSurface] = useState<GhosttyTerminalSurface | null>(null);
18
const written = useRef(0);
19
const [error, setError] = useState<string | null>(null);
20
+ // The surface captures its callbacks once at creation.
21
+ const respond = useStableCallback(onResponse);
22
+ const offset = outputOffset ?? output.length;
23
useEffect(() => {
22
- latest.current = { output, offset: outputOffset ?? output.length, onResponse };
23
- const terminal = surface.current;
24
- if (!terminal) return;
25
- const delta = latest.current.offset - written.current;
26
- if (delta > 0 && delta <= output.length) terminal.write(output.slice(-delta));
27
- else if (delta !== 0) terminal.resetAndWrite(output);
28
- written.current = latest.current.offset;
29
- }, [output, outputOffset, onResponse]);
30
- useEffect(() => {
31
- const element = mount.current;
32
- if (!element) return;
24
+ if (!surface) return;
25
+ const delta = offset - written.current;
26
+ if (delta > 0 && delta <= output.length) surface.write(output.slice(-delta));
27
+ else if (delta !== 0) surface.resetAndWrite(output);
28
+ written.current = offset;
29
+ }, [surface, output, offset]);
30
+ const mountSurface = (element: HTMLDivElement) => {
31
let disposed = false;
32
+ let created: GhosttyTerminalSurface | null = null;
33
void GhosttyTerminalSurface.create(element, {
34
theme: terminalThemeFromApp(element),
35
font: { size: 13 },
37
- onData: (data) => latest.current.onResponse({ type: "terminal", data }),
38
- onResize: (cols, rows) =>
39
- latest.current.onResponse({ type: "terminal", data: "", size: { cols, rows } }),
36
+ onData: (data) => respond({ type: "terminal", data }),
37
+ onResize: (cols, rows) => respond({ type: "terminal", data: "", size: { cols, rows } }),
38
onSelectionChange: () => {},
39
beforeKey: (event) => event.key !== "Tab",
40
onLinkActivate: (url) => {
@@ -51,21 +49,21 @@ export default function ProviderAuthTerminal({
49
terminal.dispose();
50
return;
51
}
54
- surface.current = terminal;
55
- terminal.write(latest.current.output);
56
- written.current = latest.current.offset;
52
+ created = terminal;
53
+ written.current = 0;
54
+ setSurface(terminal);
55
})
56
.catch(() => setError("Could not load the sign-in terminal. Cancel and retry sign-in."));
57
return () => {
58
disposed = true;
61
- surface.current?.dispose();
62
- surface.current = null;
59
+ created?.dispose();
60
+ setSurface(null);
61
};
64
- }, []);
62
+ };
63
return (
64
<>
65
<div
68
- ref={mount}
66
+ ref={mountSurface}
67
aria-label="Provider sign-in terminal"
68
className="relative h-64 overflow-hidden rounded-md border border-border"
69
/>
apps/web/src/components/settings/SettingsFontPreviews.tsx
+49
-56
@@ -1,5 +1,8 @@
1
import type { ServerProviderSkill } from "@t3tools/contracts";
2
import { preloadPatchFile } from "@pierre/diffs/ssr";
3
+import { useAtomValue } from "@effect/atom-react";
4
+import * as Effect from "effect/Effect";
5
+import { AsyncResult, Atom } from "effect/reactivity";
6
import { useEffect, useRef, useState } from "react";
7
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "../ComposerPromptEditor";
8
import { EMPTY_COMPOSER_CONTEXT_RECORDS } from "../composerContextPresentation";
@@ -61,18 +64,11 @@ const DIFF_PREVIEW_PATCH = [
64
].join("\n");
65
66
// FileDiff remounts can retain unhighlighted frames after a race; use static highlighted HTML in shadow DOM.
64
-const diffPreviewHtmlByTheme = new Map<DiffThemeName, Promise<readonly string[]>>();
65
-
67
function loadDiffPreviewHtml(theme: DiffThemeName): Promise<readonly string[]> {
67
- let promise = diffPreviewHtmlByTheme.get(theme);
68
- if (promise === undefined) {
69
- promise = preloadPatchFile({
70
- patch: DIFF_PREVIEW_PATCH,
71
- options: { diffStyle: "unified", theme, preferredHighlighter: PREFERRED_HIGHLIGHTER },
72
- }).then((results) => results.map((result) => result.prerenderedHTML));
73
- diffPreviewHtmlByTheme.set(theme, promise);
74
- }
75
- return promise;
68
+ return preloadPatchFile({
69
+ patch: DIFF_PREVIEW_PATCH,
70
+ options: { diffStyle: "unified", theme, preferredHighlighter: PREFERRED_HIGHLIGHTER },
71
+ }).then((results) => results.map((result) => result.prerenderedHTML));
72
}
73
74
// 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 = `
87
}
88
`;
89
90
+// Each host is keyed by its html, so the ref callback runs once per document.
91
+// React detaches a cleanup-less ref callback with null when an appearance switch drops the host.
92
function StaticDiffHtml({ html }: { html: string }) {
95
- const hostRef = useRef<HTMLDivElement | null>(null);
96
- useEffect(() => {
97
- const host = hostRef.current;
93
+ const attachHtml = (host: HTMLDivElement | null) => {
94
if (host === null) return;
95
const shadow = host.shadowRoot ?? host.attachShadow({ mode: "open" });
96
shadow.innerHTML = html;
97
const bridge = document.createElement("style");
98
bridge.textContent = DIFF_PREVIEW_THEME_BRIDGE;
99
shadow.append(bridge);
104
- }, [html]);
105
- return <div ref={hostRef} />;
100
+ };
101
+ return <div ref={attachHtml} />;
102
}
103
104
+const diffPreviewHtmlAtom = Atom.family((theme: DiffThemeName) =>
105
+ Atom.make(Effect.promise(() => loadDiffPreviewHtml(theme))).pipe(
106
+ Atom.keepAlive,
107
+ Atom.withLabel(`settings-diff-preview:${theme}`),
108
+ ),
109
+);
110
+
111
export function CodeFontPreview() {
112
const resolvedTheme = useRenderedAppearance();
110
- const themeName = resolveDiffThemeName(resolvedTheme);
111
- const [htmlByFile, setHtmlByFile] = useState<readonly string[] | null>(null);
112
- useEffect(() => {
113
- let cancelled = false;
114
- void loadDiffPreviewHtml(themeName).then((html) => {
115
- if (!cancelled) setHtmlByFile(html);
116
- });
117
- return () => {
118
- cancelled = true;
119
- };
120
- }, [themeName]);
113
+ const loadedHtml = AsyncResult.getOrElse(
114
+ useAtomValue(diffPreviewHtmlAtom(resolveDiffThemeName(resolvedTheme))),
115
+ () => null,
116
+ );
117
+ // An appearance switch keeps the previous theme's preview up while the new one renders.
118
+ const [htmlByFile, setHtmlByFile] = useState(loadedHtml);
119
+ if (loadedHtml !== null && loadedHtml !== htmlByFile) setHtmlByFile(loadedHtml);
120
if (htmlByFile === null) return null;
121
return (
122
<div className="mt-1 mb-2 space-y-2">
@@ -151,43 +150,38 @@ function previewTerminalFont(family: string, size: number): { family?: string; s
150
151
export function TerminalFontPreview({ family, size }: { family: string; size: number }) {
152
const mountRef = useRef<HTMLDivElement>(null);
154
- const surfaceRef = useRef<GhosttyTerminalSurface | null>(null);
155
- const fontRef = useRef({ family, size });
153
+ const [surface, setSurface] = useState<GhosttyTerminalSurface | null>(null);
154
+ const [initialFont] = useState(() => previewTerminalFont(family, size));
155
const { theme, resolvedTheme } = useTheme();
156
157
useEffect(() => {
159
- const current = fontRef.current;
160
- if (current.family === family && current.size === size) return;
161
- fontRef.current = { family, size };
162
- void surfaceRef.current?.setFont(previewTerminalFont(family, size));
163
- }, [family, size]);
158
+ void surface?.setFont(previewTerminalFont(family, size));
159
+ }, [surface, family, size]);
160
161
// Palette changes may preserve light/dark mode; re-read terminal tokens for every theme change.
162
useEffect(() => {
163
const mount = mountRef.current;
168
- const surface = surfaceRef.current;
164
if (!mount || !surface) return;
165
surface.setTheme(terminalThemeFromApp(mount));
166
// oxlint-disable-next-line react/exhaustive-effect-dependencies -- The tokens come from the DOM's computed styles, which a theme change rewrites.
172
- }, [theme, resolvedTheme]);
167
+ }, [surface, theme, resolvedTheme]);
168
174
- useEffect(() => {
175
- const mount = mountRef.current;
176
- if (!mount) return;
169
+ const mountSurface = (mount: HTMLDivElement) => {
170
+ mountRef.current = mount;
171
let cancelled = false;
172
+ let created: GhosttyTerminalSurface | null = null;
173
let lineLength = 0;
174
175
const echo = (data: string) => {
181
- const surface = surfaceRef.current;
182
- if (!surface) return;
176
+ if (!created) return;
177
if (data === "\r") {
184
- surface.write(`\r\n${TERMINAL_PROMPT}`);
178
+ created.write(`\r\n${TERMINAL_PROMPT}`);
179
lineLength = 0;
180
return;
181
}
182
if (data === "\x7f" || data === "\b") {
183
if (lineLength > 0) {
190
- surface.write("\b \b");
184
+ created.write("\b \b");
185
lineLength -= 1;
186
}
187
return;
@@ -197,40 +191,39 @@ export function TerminalFontPreview({ family, size }: { family: string; size: nu
191
.filter((character) => character >= " " && character !== "\x7f")
192
.join("");
193
if (printable.length === 0) return;
200
- surface.write(printable);
194
+ created.write(printable);
195
lineLength += printable.length;
196
};
197
198
void GhosttyTerminalSurface.create(mount, {
199
theme: terminalThemeFromApp(mount),
206
- font: previewTerminalFont(fontRef.current.family, fontRef.current.size),
200
+ font: initialFont,
201
onData: echo,
202
onResize: noop,
203
onSelectionChange: noop,
204
beforeKey: (event) => event.key !== "Tab",
205
onLinkActivate: noop,
212
- }).then((surface) => {
206
+ }).then((next) => {
207
if (cancelled) {
214
- surface.dispose();
208
+ next.dispose();
209
return;
210
}
217
- surfaceRef.current = surface;
218
- surface.setTheme(terminalThemeFromApp(mount));
219
- const font = fontRef.current;
220
- void surface.setFont(previewTerminalFont(font.family, font.size));
221
- surface.write(TERMINAL_PREVIEW_TRANSCRIPT);
211
+ created = next;
212
+ next.write(TERMINAL_PREVIEW_TRANSCRIPT);
213
+ setSurface(next);
214
});
215
216
return () => {
217
cancelled = true;
226
- surfaceRef.current?.dispose();
227
- surfaceRef.current = null;
218
+ created?.dispose();
219
+ mountRef.current = null;
220
+ setSurface(null);
221
};
229
- }, []);
222
+ };
223
224
return (
225
<div
233
- ref={mountRef}
226
+ ref={mountSurface}
227
className="relative mt-1 mb-2 h-52 overflow-hidden rounded-lg border border-border"
228
aria-label="Terminal font preview"
229
/>
apps/web/src/components/settings/SettingsSidebarNav.tsx
+12
-9
@@ -42,6 +42,7 @@ import { scrollToSettingsTarget } from "./settingsLayout";
42
import {
43
searchSettings,
44
isSettingsOverviewVisible,
45
+ revealSettingsSearchTarget,
46
SETTINGS_SECTION_LABELS,
47
type SettingsPath,
48
type SettingsSearchItem,
@@ -103,6 +104,11 @@ const SETTINGS_NAV_ITEMS: ReadonlyArray<{
104
icon: SETTINGS_SECTION_ICONS[to],
105
}));
106
107
+// Attached only to the highlighted result, so it runs whenever the highlight lands on a row.
108
+function scrollResultIntoView(row: HTMLElement | null) {
109
+ row?.scrollIntoView({ block: "nearest" });
110
+}
111
+
112
function SettingsSectionIcon({ to }: { to: SettingsPath }) {
113
const Icon = SETTINGS_SECTION_ICONS[to];
114
return <Icon className="size-4 shrink-0 text-(--sidebar-icon-color)" />;
@@ -131,14 +137,6 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
137
setActiveResultIndex(maxResultIndex);
138
}
139
134
- useEffect(() => {
135
- const result = results[activeResultIndex];
136
- if (!result) return;
137
- document
138
- .getElementById(`settings-search-result-${result.id}`)
139
- ?.scrollIntoView({ block: "nearest" });
140
- }, [activeResultIndex, results]);
141
-
140
useEffect(() => {
141
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
142
if (event.defaultPrevented || event.isComposing) return;
@@ -195,6 +193,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
193
clearSearch();
194
setCompactSearchOpen(false);
195
const targetId = item.targetId ?? item.id;
196
+ revealSettingsSearchTarget(targetId);
197
if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {
198
scrollToSettingsTarget(targetId);
199
return;
@@ -312,7 +311,11 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
311
aria-label={hasResults ? "Settings search results" : undefined}
312
>
313
{results.map((item, index) => (
315
- <SidebarMenuItem key={item.id} role="presentation">
314
+ <SidebarMenuItem
315
+ key={item.id}
316
+ role="presentation"
317
+ ref={index === activeResultIndex ? scrollResultIntoView : undefined}
318
+ >
319
<SidebarMenuButton
320
id={`settings-search-result-${item.id}`}
321
role="option"
apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx
new
+56
@@ -0,0 +1,56 @@
1
+import { StrictMode } from "react";
2
+import { describe, expect, it, vi } from "vite-plus/test";
3
+import { page, userEvent } from "vite-plus/test/browser";
4
+
5
+import { render } from "../../../test/render";
6
+import type { OpenVsxThemeExtension } from "../../openVsxThemes";
7
+import { ThemeImportDialog } from "./ThemeImportDialog";
8
+
9
+const searchOpenVsxThemes = vi.hoisted(() => vi.fn());
10
+
11
+vi.mock("../../openVsxThemes", () => ({
12
+ searchOpenVsxThemes,
13
+ importOpenVsxThemeExtension: vi.fn(),
14
+}));
15
+
16
+const extension: OpenVsxThemeExtension = {
17
+ id: "acme.nightfall",
18
+ collectionId: "acme.nightfall",
19
+ name: "Nightfall",
20
+ publisher: "acme",
21
+ description: "A dark theme",
22
+ downloadCount: 10,
23
+ iconUrl: null,
24
+ sourceUrl: null,
25
+ manifestUrl: "https://example.test/manifest",
26
+ sha256Url: "https://example.test/sha256",
27
+ vsixUrl: "https://example.test/vsix",
28
+ version: "1.0.0",
29
+ license: "MIT",
30
+};
31
+
32
+describe("ThemeImportDialog", () => {
33
+ // StrictMode replays ref attach/detach on mount, which must not end the session.
34
+ it("searches Open VSX under StrictMode", async () => {
35
+ searchOpenVsxThemes.mockReset();
36
+ searchOpenVsxThemes.mockResolvedValue([extension]);
37
+ await using _screen = await render(
38
+ <StrictMode>
39
+ <ThemeImportDialog
40
+ open
41
+ onOpenChange={() => {}}
42
+ onImported={() => true}
43
+ onImportedMany={() => {}}
44
+ />
45
+ </StrictMode>,
46
+ );
47
+
48
+ await userEvent.type(page.getByLabelText("Search Open VSX themes"), "night");
49
+
50
+ await expect.element(page.getByRole("heading", { name: "Nightfall" })).toBeVisible();
51
+ expect(searchOpenVsxThemes).toHaveBeenCalledWith(
52
+ "night",
53
+ expect.objectContaining({ sortBy: "downloadCount" }),
54
+ );
55
+ });
56
+});
apps/web/src/components/settings/ThemeImportDialog.tsx
+186
-162
@@ -1,7 +1,7 @@
1
import { DownloadIcon, PlusIcon } from "lucide-react";
2
import type { ChangeEvent, DragEvent, UIEvent } from "react";
3
import { settlePromise } from "@t3tools/client-runtime/state/runtime";
4
-import { useEffect, useRef, useState } from "react";
4
+import { useRef, useState } from "react";
5
import { cn } from "../../lib/utils";
6
import {
7
getCustomThemes,
@@ -137,17 +137,71 @@ function ThemeJsonEditor({
137
138
type ImportableThemeFile = { name: string; size: number; text: () => Promise<string> };
139
140
+interface ThemeImportCallbacks {
141
+ onImported: (theme: ThemeDefinition) => boolean;
142
+ onImportedMany: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
143
+}
144
+
145
export function ThemeImportDialog({
146
open,
147
onOpenChange,
148
onImported,
149
onImportedMany,
145
-}: {
150
+}: ThemeImportCallbacks & {
151
open: boolean;
152
onOpenChange: (open: boolean) => void;
148
- onImported: (theme: ThemeDefinition) => boolean;
149
- onImportedMany: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
153
}) {
154
+ // Each opening is a fresh session: its body remounts with clean state, and
155
+ // closing aborts every read, search, and install the session started.
156
+ const [session, setSession] = useState(() => ({
157
+ open,
158
+ id: 0,
159
+ controller: new AbortController(),
160
+ }));
161
+ if (session.open !== open) {
162
+ setSession(
163
+ open ? { open, id: session.id + 1, controller: new AbortController() } : { ...session, open },
164
+ );
165
+ }
166
+ const close = () => {
167
+ session.controller.abort();
168
+ onOpenChange(false);
169
+ };
170
+
171
+ return (
172
+ <Dialog
173
+ open={open}
174
+ onOpenChange={(nextOpen) => {
175
+ if (nextOpen) onOpenChange(true);
176
+ else close();
177
+ }}
178
+ >
179
+ <DialogPopup className="max-w-3xl overflow-hidden">
180
+ <DialogHeader>
181
+ <DialogTitle>Add a theme</DialogTitle>
182
+ </DialogHeader>
183
+ <ThemeImportBody
184
+ key={session.id}
185
+ session={session.controller}
186
+ onClose={close}
187
+ onImported={onImported}
188
+ onImportedMany={onImportedMany}
189
+ />
190
+ </DialogPopup>
191
+ </Dialog>
192
+ );
193
+}
194
+
195
+function ThemeImportBody({
196
+ session,
197
+ onClose,
198
+ onImported,
199
+ onImportedMany,
200
+}: ThemeImportCallbacks & {
201
+ session: AbortController;
202
+ onClose: () => void;
203
+}) {
204
+ const { signal } = session;
205
const fileInputRef = useRef<HTMLInputElement>(null);
206
const [json, setJson] = useState("");
207
const [fileName, setFileName] = useState<string | null>(null);
@@ -155,27 +209,10 @@ export function ThemeImportDialog({
209
const [isReading, setIsReading] = useState(false);
210
const [isDropTarget, setIsDropTarget] = useState(false);
211
const [conflicts, setConflicts] = useState<ReadonlyArray<ThemeDefinition> | null>(null);
212
+ // A newer read supersedes an older one still in flight.
213
const importRequestRef = useRef(0);
159
-
160
- const [renderedOpen, setRenderedOpen] = useState(open);
161
- if (renderedOpen !== open) {
162
- setRenderedOpen(open);
163
- setIsDropTarget(false);
164
- if (open) {
165
- setJson("");
166
- setFileName(null);
167
- setError(null);
168
- setIsReading(false);
169
- setConflicts(null);
170
- }
171
- }
172
- useEffect(() => {
173
- if (!open) return;
174
- importRequestRef.current += 1;
175
- return () => {
176
- importRequestRef.current += 1;
177
- };
178
- }, [open]);
214
+ const isCurrentRequest = (requestId: number) =>
215
+ requestId === importRequestRef.current && !signal.aborted;
216
217
const readThemeFile = async (file: ImportableThemeFile) => {
218
const oversized = describeOversizedThemeFile(file.size);
@@ -187,7 +224,7 @@ export function ThemeImportDialog({
224
const requestId = ++importRequestRef.current;
225
setIsReading(true);
226
const fileText = await settlePromise(() => file.text());
190
- if (requestId !== importRequestRef.current) return;
227
+ if (!isCurrentRequest(requestId)) return;
228
setIsReading(false);
229
if (fileText._tag === "Failure") {
230
setError("Could not read that file. Paste the JSON below instead.");
@@ -202,7 +239,7 @@ export function ThemeImportDialog({
239
const requestId = ++importRequestRef.current;
240
setIsReading(true);
241
return installThemeBatch(files, requestId).finally(() => {
205
- if (requestId === importRequestRef.current) setIsReading(false);
242
+ if (isCurrentRequest(requestId)) setIsReading(false);
243
});
244
};
245
@@ -230,7 +267,7 @@ export function ThemeImportDialog({
267
);
268
}
269
}
233
- if (requestId !== importRequestRef.current) return;
270
+ if (!isCurrentRequest(requestId)) return;
271
const installed: ThemeDefinition[] = [];
272
const conflicting: ThemeDefinition[] = [];
273
for (const theme of pairVsCodeThemes(resolveThemeLabelCollisions(parsed))) {
@@ -252,7 +289,7 @@ export function ThemeImportDialog({
289
} else if (conflicting.length > 0) {
290
setConflicts(conflicting);
291
} else if (installed.length > 0) {
255
- onOpenChange(false);
292
+ onClose();
293
}
294
};
295
@@ -351,7 +388,7 @@ export function ThemeImportDialog({
388
if (resolved.length > 0) onImportedMany(resolved, { updated: mode === "update" });
389
setConflicts(null);
390
if (failures.length > 0) setError(failures.join("; "));
354
- else onOpenChange(false);
391
+ else onClose();
392
};
393
394
const handleSubmit = () => {
@@ -378,148 +415,135 @@ export function ThemeImportDialog({
415
setError("Theme added, but it could not be selected. Try again.");
416
return;
417
}
381
- onOpenChange(false);
418
+ onClose();
419
} catch (cause) {
420
setError(cause instanceof Error ? cause.message : "That theme file is invalid.");
421
}
422
};
423
424
return (
388
- <Dialog
389
- open={open}
390
- onOpenChange={(nextOpen) => {
391
- if (!nextOpen) setError(null);
392
- onOpenChange(nextOpen);
393
- }}
394
- >
395
- <DialogPopup className="max-w-3xl overflow-hidden">
396
- <DialogHeader>
397
- <DialogTitle>Add a theme</DialogTitle>
398
- </DialogHeader>
399
- <DialogPanel>
400
- <ThemeSearchSection
401
- onInstalled={(themes, context) => {
402
- onImportedMany(themes, context);
403
- onOpenChange(false);
404
- }}
405
- open={open}
406
- />
425
+ <DialogPanel>
426
+ <ThemeSearchSection
427
+ onInstalled={(themes, context) => {
428
+ onImportedMany(themes, context);
429
+ onClose();
430
+ }}
431
+ signal={signal}
432
+ />
433
408
- <div className="flex items-center gap-3" aria-hidden>
409
- <div className="h-px flex-1 bg-border" />
410
- <span className="text-muted-foreground text-2xs uppercase tracking-wider">
411
- or import a file
412
- </span>
413
- <div className="h-px flex-1 bg-border" />
414
- </div>
434
+ <div className="flex items-center gap-3" aria-hidden>
435
+ <div className="h-px flex-1 bg-border" />
436
+ <span className="text-muted-foreground text-2xs uppercase tracking-wider">
437
+ or import a file
438
+ </span>
439
+ <div className="h-px flex-1 bg-border" />
440
+ </div>
441
416
- {(() => {
417
- const dropHandlers = {
418
- onDragEnter: (event: DragEvent<HTMLDivElement>) => {
419
- event.preventDefault();
420
- setIsDropTarget(true);
421
- },
422
- onDragOver: (event: DragEvent<HTMLDivElement>) => {
423
- event.preventDefault();
424
- setIsDropTarget(true);
425
- },
426
- onDragLeave: (event: DragEvent<HTMLDivElement>) => {
427
- if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
428
- setIsDropTarget(false);
429
- },
430
- onDrop: handleDrop,
431
- };
432
- const fileInput = (
433
- <input
434
- ref={fileInputRef}
435
- accept=".json,application/json"
436
- className="sr-only"
437
- onChange={handleFileChange}
438
- multiple
439
- type="file"
440
- />
441
- );
442
- const chooseButton = (label = "Choose files") => (
443
- <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>
444
- <DownloadIcon />
445
- {isReading ? "Reading…" : label}
446
- </Button>
447
- );
448
- const editorSection = () => (
449
- <div className="space-y-2">
450
- <div className="flex items-baseline justify-between gap-3">
451
- <label className="text-sm font-medium" htmlFor="theme-json-editor">
452
- Theme JSON
453
- </label>
454
- </div>
455
- <ThemeJsonEditor id="theme-json-editor" onChange={setJson} value={json} />
442
+ {(() => {
443
+ const dropHandlers = {
444
+ onDragEnter: (event: DragEvent<HTMLDivElement>) => {
445
+ event.preventDefault();
446
+ setIsDropTarget(true);
447
+ },
448
+ onDragOver: (event: DragEvent<HTMLDivElement>) => {
449
+ event.preventDefault();
450
+ setIsDropTarget(true);
451
+ },
452
+ onDragLeave: (event: DragEvent<HTMLDivElement>) => {
453
+ if (event.currentTarget.contains(event.relatedTarget as Node | null)) return;
454
+ setIsDropTarget(false);
455
+ },
456
+ onDrop: handleDrop,
457
+ };
458
+ const fileInput = (
459
+ <input
460
+ ref={fileInputRef}
461
+ accept=".json,application/json"
462
+ className="sr-only"
463
+ onChange={handleFileChange}
464
+ multiple
465
+ type="file"
466
+ />
467
+ );
468
+ const chooseButton = (label = "Choose files") => (
469
+ <Button disabled={isReading} size="sm" variant="outline" onClick={openFilePicker}>
470
+ <DownloadIcon />
471
+ {isReading ? "Reading…" : label}
472
+ </Button>
473
+ );
474
+ const editorSection = () => (
475
+ <div className="space-y-2">
476
+ <div className="flex items-baseline justify-between gap-3">
477
+ <label className="text-sm font-medium" htmlFor="theme-json-editor">
478
+ Theme JSON
479
+ </label>
480
+ </div>
481
+ <ThemeJsonEditor id="theme-json-editor" onChange={setJson} value={json} />
482
+ </div>
483
+ );
484
+ if (conflicts) {
485
+ return (
486
+ <div className="space-y-3">
487
+ <div className="rounded-xl border border-border/70 bg-muted/20 p-3">
488
+ <p className="text-sm font-medium">Already installed</p>
489
+ <p className="mt-1 text-xs text-muted-foreground">
490
+ {conflicts.map((theme) => theme.label).join(", ")}
491
+ </p>
492
</div>
457
- );
458
- if (conflicts) {
459
- return (
460
- <div className="space-y-3">
461
- <div className="rounded-xl border border-border/70 bg-muted/20 p-3">
462
- <p className="text-sm font-medium">Already installed</p>
463
- <p className="mt-1 text-xs text-muted-foreground">
464
- {conflicts.map((theme) => theme.label).join(", ")}
465
- </p>
466
- </div>
467
- <div className="flex flex-wrap items-center gap-2">
468
- <Button size="sm" onClick={() => resolveConflicts("update")}>
469
- Update existing
470
- </Button>
471
- <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>
472
- Keep both
473
- </Button>
474
- <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>
475
- Back
476
- </Button>
477
- <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>
478
- Cancel
479
- </Button>
480
- </div>
481
- </div>
482
- );
483
- }
484
- return (
485
- <div className="space-y-4">
486
- <div
487
- className={cn(
488
- "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",
489
- isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",
490
- )}
491
- {...dropHandlers}
492
- >
493
- <div className="min-w-0">
494
- <p className="text-sm font-medium">Theme file</p>
495
- <p className="truncate text-xs text-muted-foreground">
496
- {fileName ?? "Drop T3 Code or VS Code .json files"}
497
- </p>
498
- </div>
499
- {chooseButton()}
500
- {fileInput}
501
- </div>
502
- {editorSection()}
503
- <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
504
- <Button variant="ghost" onClick={() => onOpenChange(false)}>
505
- Cancel
506
- </Button>
507
- <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>
508
- <PlusIcon />
509
- Add theme
510
- </Button>
511
- </div>
493
+ <div className="flex flex-wrap items-center gap-2">
494
+ <Button size="sm" onClick={() => resolveConflicts("update")}>
495
+ Update existing
496
+ </Button>
497
+ <Button size="sm" variant="outline" onClick={() => resolveConflicts("copy")}>
498
+ Keep both
499
+ </Button>
500
+ <Button size="sm" variant="ghost" onClick={() => setConflicts(null)}>
501
+ Back
502
+ </Button>
503
+ <Button size="sm" variant="ghost" onClick={() => onClose()}>
504
+ Cancel
505
+ </Button>
506
</div>
513
- );
514
- })()}
515
-
516
- {error ? (
517
- <Alert aria-live="polite" variant="error">
518
- {error}
519
- </Alert>
520
- ) : null}
521
- </DialogPanel>
522
- </DialogPopup>
523
- </Dialog>
507
+ </div>
508
+ );
509
+ }
510
+ return (
511
+ <div className="space-y-4">
512
+ <div
513
+ className={cn(
514
+ "flex flex-wrap items-center justify-between gap-3 rounded-xl border border-dashed px-3 py-3 transition-colors",
515
+ isDropTarget ? "border-ring bg-accent/20" : "border-border/80 bg-muted/20",
516
+ )}
517
+ {...dropHandlers}
518
+ >
519
+ <div className="min-w-0">
520
+ <p className="text-sm font-medium">Theme file</p>
521
+ <p className="truncate text-xs text-muted-foreground">
522
+ {fileName ?? "Drop T3 Code or VS Code .json files"}
523
+ </p>
524
+ </div>
525
+ {chooseButton()}
526
+ {fileInput}
527
+ </div>
528
+ {editorSection()}
529
+ <div className="flex flex-col-reverse gap-2 sm:flex-row sm:justify-end">
530
+ <Button variant="ghost" onClick={() => onClose()}>
531
+ Cancel
532
+ </Button>
533
+ <Button disabled={!json.trim() || isReading} onClick={handleSubmit}>
534
+ <PlusIcon />
535
+ Add theme
536
+ </Button>
537
+ </div>
538
+ </div>
539
+ );
540
+ })()}
541
+
542
+ {error ? (
543
+ <Alert aria-live="polite" variant="error">
544
+ {error}
545
+ </Alert>
546
+ ) : null}
547
+ </DialogPanel>
548
);
549
}
apps/web/src/components/settings/ThemeSearchSection.test.ts
new
+152
@@ -0,0 +1,152 @@
1
+import { describe, expect, it, vi } from "vite-plus/test";
2
+
3
+import type { OpenVsxThemeExtension, OpenVsxThemeSort } from "../../openVsxThemes";
4
+import { createThemeSearch, type ThemeSearchView } from "./ThemeSearchSection";
5
+
6
+interface Request {
7
+ readonly query: string;
8
+ readonly sortBy: OpenVsxThemeSort | undefined;
9
+ readonly signal: AbortSignal | undefined;
10
+ resolve(results: OpenVsxThemeExtension[]): void;
11
+ reject(cause: unknown): void;
12
+}
13
+
14
+function setup() {
15
+ vi.useFakeTimers();
16
+ const requests: Request[] = [];
17
+ const search = (
18
+ query: string,
19
+ options: { signal?: AbortSignal; sortBy?: OpenVsxThemeSort } = {},
20
+ ) =>
21
+ new Promise<OpenVsxThemeExtension[]>((resolve, reject) => {
22
+ requests.push({ query, sortBy: options.sortBy, signal: options.signal, resolve, reject });
23
+ });
24
+ const view = {
25
+ results: null as ReadonlyArray<OpenVsxThemeExtension> | null,
26
+ error: null as string | null,
27
+ isSearching: false,
28
+ };
29
+ const sink: ThemeSearchView = {
30
+ setResults: (results) => {
31
+ view.results = results;
32
+ },
33
+ setError: (error) => {
34
+ view.error = error;
35
+ },
36
+ setIsSearching: (isSearching) => {
37
+ view.isSearching = isSearching;
38
+ },
39
+ };
40
+ const session = new AbortController();
41
+ const themeSearch = createThemeSearch(sink, session.signal, search);
42
+ return {
43
+ requests,
44
+ view,
45
+ session,
46
+ themeSearch,
47
+ [Symbol.dispose]: () => vi.useRealTimers(),
48
+ };
49
+}
50
+
51
+const extension = (name: string) => ({ name }) as OpenVsxThemeExtension;
52
+const flush = () => vi.advanceTimersByTimeAsync(0);
53
+
54
+describe("createThemeSearch", () => {
55
+ it("searches once the typed query settles", async () => {
56
+ using env = setup();
57
+ env.themeSearch.setQuery("dra");
58
+ env.themeSearch.setQuery("dracula ");
59
+ await vi.advanceTimersByTimeAsync(349);
60
+ expect(env.requests).toHaveLength(0);
61
+ await vi.advanceTimersByTimeAsync(1);
62
+ expect(env.requests.map((request) => request.query)).toEqual(["dracula"]);
63
+ expect(env.view.isSearching).toBe(true);
64
+
65
+ env.requests[0]!.resolve([extension("Dracula")]);
66
+ await flush();
67
+ expect(env.view.results).toEqual([extension("Dracula")]);
68
+ expect(env.view.isSearching).toBe(false);
69
+ });
70
+
71
+ it("keeps the shown results when typing returns to their query", async () => {
72
+ using env = setup();
73
+ env.themeSearch.setQuery("nord");
74
+ await vi.advanceTimersByTimeAsync(350);
75
+ env.requests[0]!.resolve([extension("Nord")]);
76
+ await flush();
77
+
78
+ env.themeSearch.setQuery("nordic");
79
+ await vi.advanceTimersByTimeAsync(350);
80
+ env.themeSearch.setQuery("nord");
81
+ await vi.advanceTimersByTimeAsync(350);
82
+
83
+ expect(env.requests).toHaveLength(2);
84
+ expect(env.requests[1]!.signal?.aborted).toBe(true);
85
+ expect(env.view.results).toEqual([extension("Nord")]);
86
+ expect(env.view.isSearching).toBe(false);
87
+ });
88
+
89
+ it("searches again right away when the sort changes", async () => {
90
+ using env = setup();
91
+ env.themeSearch.setQuery("nord");
92
+ await vi.advanceTimersByTimeAsync(350);
93
+ env.themeSearch.setSortBy("rating");
94
+ expect(env.requests[0]!.signal?.aborted).toBe(true);
95
+ expect(env.requests[1]).toMatchObject({ query: "nord", sortBy: "rating" });
96
+ });
97
+
98
+ it("clearing the query drops results and the request in flight", async () => {
99
+ using env = setup();
100
+ env.themeSearch.setQuery("nord");
101
+ await vi.advanceTimersByTimeAsync(350);
102
+ env.themeSearch.setQuery(" ");
103
+ expect(env.requests[0]!.signal?.aborted).toBe(true);
104
+ expect(env.view).toEqual({ results: null, error: null, isSearching: false });
105
+ });
106
+
107
+ it("holds searches during an install and keeps its error on the shown query", async () => {
108
+ using env = setup();
109
+ env.themeSearch.setQuery("nord");
110
+ await vi.advanceTimersByTimeAsync(350);
111
+ env.requests[0]!.resolve([extension("Nord")]);
112
+ await flush();
113
+
114
+ const install = env.themeSearch.beginInstall();
115
+ env.view.error = "That theme could not be added.";
116
+ env.themeSearch.searchNow();
117
+ expect(env.requests).toHaveLength(1);
118
+ expect(env.themeSearch.endInstall(install)).toBe(true);
119
+ expect(env.requests).toHaveLength(1);
120
+ expect(env.view.error).toBe("That theme could not be added.");
121
+
122
+ const next = env.themeSearch.beginInstall();
123
+ env.themeSearch.setQuery("dracula");
124
+ await vi.advanceTimersByTimeAsync(350);
125
+ expect(env.requests).toHaveLength(1);
126
+ env.themeSearch.endInstall(next);
127
+ expect(env.requests.map((request) => request.query)).toEqual(["nord", "dracula"]);
128
+ expect(env.view.error).toBeNull();
129
+ });
130
+
131
+ it("Enter during the debounce searches once", async () => {
132
+ using env = setup();
133
+ env.themeSearch.setQuery("nord");
134
+ env.themeSearch.searchNow();
135
+ await vi.advanceTimersByTimeAsync(350);
136
+ expect(env.requests.map((request) => request.query)).toEqual(["nord"]);
137
+ expect(env.requests[0]!.signal?.aborted).toBe(false);
138
+ });
139
+
140
+ it("closing the session aborts the search, the debounce, and the install", async () => {
141
+ using env = setup();
142
+ env.themeSearch.setQuery("nord");
143
+ await vi.advanceTimersByTimeAsync(350);
144
+ const install = env.themeSearch.beginInstall();
145
+ env.themeSearch.setQuery("dracula");
146
+ env.session.abort();
147
+ await vi.advanceTimersByTimeAsync(350);
148
+ expect(env.requests[0]!.signal?.aborted).toBe(true);
149
+ expect(install.aborted).toBe(true);
150
+ expect(env.requests).toHaveLength(1);
151
+ });
152
+});
apps/web/src/components/settings/ThemeSearchSection.tsx
+160
-134
@@ -1,14 +1,13 @@
1
import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients";
2
import { RefreshIcon } from "~/components/ui/refresh-icon";
3
import { ExternalLinkIcon, PackagePlusIcon, PaletteIcon, SearchIcon } from "lucide-react";
4
-import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "react";
4
+import { type ReactNode, useState } from "react";
5
import {
6
importOpenVsxThemeExtension,
7
searchOpenVsxThemes,
8
type OpenVsxThemeExtension,
9
type OpenVsxThemeSort,
10
} from "../../openVsxThemes";
11
-import { useDebouncedValue } from "../../state/queries";
11
import {
12
getCustomThemes,
13
getStoredCustomThemeCollection,
@@ -80,148 +79,182 @@ function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension })
79
);
80
}
81
83
-export function ThemeSearchSection({
84
- open,
85
- onInstalled,
86
-}: {
87
- open: boolean;
88
- onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
89
-}) {
90
- const [query, setQuery] = useState("");
91
- const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");
92
- const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
93
- const [error, setError] = useState<string | null>(null);
94
- const [isSearching, setIsSearching] = useState(false);
95
- const [installingId, setInstallingId] = useState<string | null>(null);
96
- const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
97
- const requestRef = useRef<AbortController | null>(null);
98
- // Record successful searches only; rerun after install only for changed query/sort to preserve install
99
- // errors.
100
- const [lastSearchKey, setLastSearchKey] = useState<string | null>(null);
101
- const [handledSearch, setHandledSearch] = useState<{
102
- key: string;
103
- query: string;
104
- fetch: boolean;
105
- } | null>(null);
106
- const [searchInterrupted, setSearchInterrupted] = useState(false);
107
-
108
- const [wasOpen, setWasOpen] = useState(open);
109
- if (open !== wasOpen) {
110
- setWasOpen(open);
111
- if (open) {
112
- setQuery("");
113
- setSortBy("downloadCount");
114
- setResults(null);
115
- setError(null);
116
- setIsSearching(false);
117
- setInstallingId(null);
118
- setPendingUpdate(null);
119
- setLastSearchKey(null);
120
- setHandledSearch(null);
121
- setSearchInterrupted(false);
122
- }
123
- }
82
+export interface ThemeSearchView {
83
+ readonly setResults: (results: ReadonlyArray<OpenVsxThemeExtension> | null) => void;
84
+ readonly setError: (error: string | null) => void;
85
+ readonly setIsSearching: (isSearching: boolean) => void;
86
+}
87
125
- useEffect(() => {
126
- if (!open) return;
127
- return () => {
128
- requestRef.current?.abort();
129
- requestRef.current = null;
130
- };
131
- }, [open]);
88
+type SearchThemes = typeof searchOpenVsxThemes;
89
133
- const queryCleared = !query.trim() && installingId === null;
134
- if (
135
- queryCleared &&
136
- (results !== null ||
137
- error !== null ||
138
- isSearching ||
139
- lastSearchKey !== null ||
140
- handledSearch !== null)
141
- ) {
142
- setResults(null);
143
- setError(null);
144
- setIsSearching(false);
145
- setLastSearchKey(null);
146
- setHandledSearch(null);
147
- }
148
-
149
- useEffect(() => {
150
- if (!queryCleared) return;
151
- requestRef.current?.abort();
152
- requestRef.current = null;
153
- }, [queryCleared]);
90
+/**
91
+ * Owns one dialog session's Open VSX traffic: the input debounce, the request in
92
+ * flight, and which key the shown results belong to. Aborting `signal` (the
93
+ * dialog closing) cancels all of it, including an install.
94
+ */
95
+export function createThemeSearch(
96
+ view: ThemeSearchView,
97
+ signal: AbortSignal,
98
+ search: SearchThemes = searchOpenVsxThemes,
99
+) {
100
+ let query = "";
101
+ let sortBy: OpenVsxThemeSort = "downloadCount";
102
+ let debounce: ReturnType<typeof setTimeout> | null = null;
103
+ let request: AbortController | null = null;
104
+ let install: AbortController | null = null;
105
+ // Record successful searches only; rerun after install only for changed query/sort to preserve install
106
+ // errors.
107
+ let shownKey: string | null = null;
108
+ let handledKey: string | null = null;
109
+ let interrupted = false;
110
155
- const startRequest = () => {
156
- requestRef.current?.abort();
157
- const controller = new AbortController();
158
- requestRef.current = controller;
159
- return controller;
111
+ const keyOf = () => `${query}\u0000${sortBy}`;
112
+ const abortRequest = () => {
113
+ request?.abort();
114
+ request = null;
115
+ };
116
+ const cancelDebounce = () => {
117
+ if (debounce !== null) clearTimeout(debounce);
118
+ debounce = null;
119
};
120
162
- const fetchResults = (trimmed: string, controller: AbortController) => {
163
- const key = `${trimmed}\u0000${sortBy}`;
164
- void searchOpenVsxThemes(trimmed, { signal: controller.signal, sortBy })
121
+ const fetchResults = () => {
122
+ abortRequest();
123
+ const controller = new AbortController();
124
+ request = controller;
125
+ const key = keyOf();
126
+ void search(query, { signal: controller.signal, sortBy })
127
.then(
166
- (nextResults) => {
128
+ (results) => {
129
if (controller.signal.aborted) return;
168
- setResults(nextResults);
169
- setLastSearchKey(key);
130
+ view.setResults(results);
131
+ shownKey = key;
132
},
133
(cause: unknown) => {
134
if (controller.signal.aborted) return;
173
- setResults(null);
174
- setLastSearchKey(null);
175
- setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
135
+ view.setResults(null);
136
+ shownKey = null;
137
+ view.setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
138
},
139
)
140
.then(() => {
179
- if (requestRef.current !== controller) return;
180
- requestRef.current = null;
181
- setIsSearching(false);
141
+ if (request !== controller) return;
142
+ request = null;
143
+ view.setIsSearching(false);
144
});
145
};
146
185
- const runSearch = (searchText: string) => {
186
- const trimmed = searchText.trim();
187
- if (!trimmed) return;
188
- setError(null);
189
- setIsSearching(true);
190
- fetchResults(trimmed, startRequest());
147
+ const clear = () => {
148
+ cancelDebounce();
149
+ abortRequest();
150
+ shownKey = null;
151
+ handledKey = null;
152
+ view.setResults(null);
153
+ view.setError(null);
154
+ view.setIsSearching(false);
155
};
156
193
- const debouncedQuery = useDebouncedValue(query.trim(), SEARCH_DEBOUNCE_MS);
194
- const searchKey = `${debouncedQuery}\u0000${sortBy}`;
195
- const searchSettled =
196
- open && installingId === null && debouncedQuery !== "" && debouncedQuery === query.trim();
157
+ const settle = () => {
158
+ if (install !== null || signal.aborted || query === "") return;
159
+ const key = keyOf();
160
+ const keyChanged = handledKey !== key;
161
+ if (!keyChanged && !interrupted) return;
162
+ handledKey = key;
163
+ interrupted = false;
164
+ const shouldFetch = shownKey !== key;
165
+ if (shouldFetch || keyChanged) view.setError(null);
166
+ view.setIsSearching(shouldFetch);
167
+ if (shouldFetch) fetchResults();
168
+ else abortRequest();
169
+ };
170
198
- const keyChanged = handledSearch?.key !== searchKey;
199
- if (searchSettled && (keyChanged || searchInterrupted)) {
200
- const fetch = lastSearchKey !== searchKey;
201
- setHandledSearch({ key: searchKey, query: debouncedQuery, fetch });
202
- setSearchInterrupted(false);
203
- if (fetch || keyChanged) setError(null);
204
- setIsSearching(fetch);
205
- }
171
+ signal.addEventListener(
172
+ "abort",
173
+ () => {
174
+ cancelDebounce();
175
+ abortRequest();
176
+ install?.abort();
177
+ },
178
+ { once: true },
179
+ );
180
207
- const fetchHandledSearch = useEffectEvent((searchText: string) => {
208
- fetchResults(searchText, startRequest());
209
- });
181
+ return {
182
+ /** An unsettled query would hit Open VSX for text that is no longer visible, so typing waits. */
183
+ setQuery(nextQuery: string) {
184
+ const trimmed = nextQuery.trim();
185
+ if (trimmed === query) return;
186
+ query = trimmed;
187
+ cancelDebounce();
188
+ if (trimmed === "") {
189
+ if (install === null) clear();
190
+ return;
191
+ }
192
+ debounce = setTimeout(() => {
193
+ debounce = null;
194
+ settle();
195
+ }, SEARCH_DEBOUNCE_MS);
196
+ },
197
+ setSortBy(nextSort: OpenVsxThemeSort) {
198
+ sortBy = nextSort;
199
+ if (debounce === null) settle();
200
+ },
201
+ /** Enter or re-picking the current suggestion searches again even for the shown key. */
202
+ searchNow() {
203
+ if (install !== null || signal.aborted || query === "") return;
204
+ // A pending debounce for the same key would otherwise restart this search.
205
+ cancelDebounce();
206
+ handledKey = keyOf();
207
+ interrupted = false;
208
+ view.setError(null);
209
+ view.setIsSearching(true);
210
+ fetchResults();
211
+ },
212
+ beginInstall(): AbortSignal {
213
+ abortRequest();
214
+ install?.abort();
215
+ install = new AbortController();
216
+ interrupted = true;
217
+ view.setIsSearching(false);
218
+ return install.signal;
219
+ },
220
+ endInstall(installSignal: AbortSignal): boolean {
221
+ if (install?.signal !== installSignal) return false;
222
+ install = null;
223
+ if (query === "") clear();
224
+ else if (debounce === null) settle();
225
+ return true;
226
+ },
227
+ };
228
+}
229
211
- useEffect(() => {
212
- if (!handledSearch) return;
213
- if (handledSearch.fetch) {
214
- fetchHandledSearch(handledSearch.query);
215
- return;
216
- }
217
- requestRef.current?.abort();
218
- requestRef.current = null;
219
- }, [handledSearch]);
230
+export function ThemeSearchSection({
231
+ signal,
232
+ onInstalled,
233
+}: {
234
+ signal: AbortSignal;
235
+ onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
236
+}) {
237
+ const [query, setQuery] = useState("");
238
+ const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");
239
+ const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
240
+ const [error, setError] = useState<string | null>(null);
241
+ const [isSearching, setIsSearching] = useState(false);
242
+ const [installingId, setInstallingId] = useState<string | null>(null);
243
+ const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
244
+ const [themeSearch] = useState(() =>
245
+ createThemeSearch({ setResults, setError, setIsSearching }, signal),
246
+ );
247
+
248
+ const changeQuery = (nextQuery: string) => {
249
+ setQuery(nextQuery);
250
+ themeSearch.setQuery(nextQuery);
251
+ };
252
253
const handleSortChange = (value: OpenVsxThemeSort | null) => {
254
const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
255
if (!nextSort) return;
256
setSortBy(nextSort);
257
+ themeSearch.setSortBy(nextSort);
258
};
259
260
const handleInstall = async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
@@ -239,29 +272,22 @@ export function ThemeSearchSection({
272
return;
273
}
274
242
- requestRef.current?.abort();
243
- const controller = new AbortController();
244
- requestRef.current = controller;
245
- setIsSearching(false);
246
- setSearchInterrupted(true);
275
+ const installSignal = themeSearch.beginInstall();
276
setInstallingId(extension.id);
277
try {
249
- const themes = await importOpenVsxThemeExtension(extension, controller.signal);
250
- if (!controller.signal.aborted) {
278
+ const themes = await importOpenVsxThemeExtension(extension, installSignal);
279
+ if (!installSignal.aborted) {
280
const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
281
expectedCollection: installedCollection,
282
});
283
onInstalled(imported, { updated });
284
}
285
} catch (cause) {
257
- if (!controller.signal.aborted) {
286
+ if (!installSignal.aborted) {
287
setError(cause instanceof Error ? cause.message : "That theme could not be added.");
288
}
289
}
261
- if (requestRef.current === controller) {
262
- requestRef.current = null;
263
- setInstallingId(null);
264
- }
290
+ if (themeSearch.endInstall(installSignal)) setInstallingId(null);
291
};
292
293
return (
@@ -281,11 +307,11 @@ export function ThemeSearchSection({
307
<InputGroupInput
308
aria-label="Search Open VSX themes"
309
autoFocus
284
- onChange={(event) => setQuery(event.currentTarget.value)}
310
+ onChange={(event) => changeQuery(event.currentTarget.value)}
311
onKeyDown={(event) => {
312
if (event.nativeEvent.isComposing || event.keyCode === 229) return;
313
if (event.key === "Enter" && !isSearching && installingId === null)
288
- runSearch(query.trim());
314
+ themeSearch.searchNow();
315
}}
316
placeholder="Search themes..."
317
size="lg"
@@ -306,9 +332,9 @@ export function ThemeSearchSection({
332
variant="ghost"
333
onClick={() => {
334
if (query.trim() === suggestion) {
309
- runSearch(suggestion);
335
+ themeSearch.searchNow();
336
} else {
311
- setQuery(suggestion);
337
+ changeQuery(suggestion);
338
}
339
}}
340
>
apps/web/src/components/settings/TypographySettings.browser.test.tsx
new
+43
@@ -0,0 +1,43 @@
1
+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
2
+import * as Schema from "effect/Schema";
3
+import { describe, expect, it, vi } from "vite-plus/test";
4
+
5
+import "~/index.css";
6
+import { render } from "../../../test/render";
7
+import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";
8
+import { getLocalStorageItem, removeLocalStorageItem } from "../../hooks/useLocalStorage";
9
+import { TypographySection } from "./TypographySettings";
10
+
11
+const state = vi.hoisted(() => ({ searchTargetId: null as string | null }));
12
+
13
+vi.mock(import("./useScopedSettings"), async (original) => ({
14
+ ...(await original()),
15
+ useScopedSettings: (() => DEFAULT_UNIFIED_SETTINGS) as never,
16
+ useUpdateScopedSettings: (() => vi.fn()) as never,
17
+}));
18
+// The previews mount Ghostty and Shiki, which this test does not exercise.
19
+vi.mock(import("./SettingsFontPreviews"), () => ({
20
+ CodeFontPreview: () => <div />,
21
+ PromptFontPreview: () => <div />,
22
+ TerminalFontPreview: () => <div />,
23
+}));
24
+vi.mock(import("./settingsLayout"), async (original) => ({
25
+ ...(await original()),
26
+ useSettingsSearchTargetId: () => state.searchTargetId,
27
+}));
28
+
29
+function setup(searchTargetId: string | null) {
30
+ state.searchTargetId = searchTargetId;
31
+ removeLocalStorageItem(TYPOGRAPHY_ADVANCED_STORAGE_KEY);
32
+ return { [Symbol.dispose]: () => removeLocalStorageItem(TYPOGRAPHY_ADVANCED_STORAGE_KEY) };
33
+}
34
+
35
+describe("TypographySection", () => {
36
+ it("persists the advanced flag the terminal reads when a deep link targets an advanced row", async () => {
37
+ using _storage = setup("terminal-font");
38
+ await using screen = await render(<TypographySection />);
39
+
40
+ await expect.element(screen.getByRole("heading", { name: "Terminal font" })).toBeVisible();
41
+ expect(getLocalStorageItem(TYPOGRAPHY_ADVANCED_STORAGE_KEY, Schema.Boolean)).toBe(true);
42
+ });
43
+});
apps/web/src/components/settings/TypographySettings.tsx
+14
-19
@@ -36,7 +36,11 @@ import {
36
SettingsSection,
37
useSettingsSearchTargetId,
38
} from "./settingsLayout";
39
-import { searchableSetting } from "./settingsSearch";
39
+import {
40
+ isAdvancedTypographyTarget,
41
+ revealSettingsSearchTarget,
42
+ searchableSetting,
43
+} from "./settingsSearch";
44
45
function useFontDefaultFamilies() {
46
const settings = useScopedSettings();
@@ -292,30 +296,21 @@ function SimpleFontRows() {
296
);
297
}
298
295
-// Font smoothing only renders on macOS, so a search jump to it elsewhere
296
-// must not flip the section - the target would never mount to be scrolled to.
297
-const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
298
- "prompt-font",
299
- "terminal-font",
300
- ...(typeof navigator !== "undefined" && isMacPlatform(navigator.platform)
301
- ? ["font-smoothing"]
302
- : []),
303
-]);
304
-
299
export function TypographySection() {
300
const [advanced, setAdvanced] = useLocalStorage(
301
TYPOGRAPHY_ADVANCED_STORAGE_KEY,
302
false,
303
Schema.Boolean,
304
);
305
+ // A deep link or history step must persist the flag too: the terminal reads it, so advanced
306
+ // rows without it would make terminal font edits do nothing. The rows follow the target
307
+ // directly so its row mounts in the first commit; the target clears once handled.
308
const searchTargetId = useSettingsSearchTargetId();
312
- const lastExpandedTargetRef = useRef<string | null>(null);
309
useEffect(() => {
314
- if (searchTargetId === null || !ADVANCED_TYPOGRAPHY_TARGET_IDS.has(searchTargetId)) return;
315
- if (lastExpandedTargetRef.current === searchTargetId) return;
316
- lastExpandedTargetRef.current = searchTargetId;
317
- setAdvanced(true);
318
- }, [searchTargetId, setAdvanced]);
310
+ if (searchTargetId !== null) revealSettingsSearchTarget(searchTargetId);
311
+ }, [searchTargetId]);
312
+ const showAdvanced =
313
+ advanced || (searchTargetId !== null && isAdvancedTypographyTarget(searchTargetId));
314
return (
315
<SettingsSection
316
id="typography"
@@ -324,14 +319,14 @@ export function TypographySection() {
319
<label className="flex cursor-pointer items-center gap-2 text-xs font-medium text-muted-foreground">
320
Advanced
321
<Switch
327
- checked={advanced}
322
+ checked={showAdvanced}
323
onCheckedChange={(checked) => setAdvanced(Boolean(checked))}
324
aria-label="Show advanced typography settings"
325
/>
326
</label>
327
}
328
>
334
- {advanced ? <FontSettingsGroup /> : <SimpleFontRows />}
329
+ {showAdvanced ? <FontSettingsGroup /> : <SimpleFontRows />}
330
<WordWrapRow />
331
</SettingsSection>
332
);
apps/web/src/components/settings/settingsSearch.ts
+28
@@ -9,6 +9,9 @@ import {
9
type SourceControlDefinition,
10
} from "@t3tools/client-runtime/source-control-clients";
11
import { DEFAULT_KEYBINDINGS } from "@t3tools/shared/keybindings";
12
+import * as Schema from "effect/Schema";
13
+import { TYPOGRAPHY_ADVANCED_STORAGE_KEY } from "../../appearanceFonts";
14
+import { writeLocalStorageValue } from "../../hooks/useLocalStorage";
15
import { commandLabel } from "./KeybindingsSettings.logic";
16
import {
17
validateSettingsScopeSearch,
@@ -1233,3 +1236,28 @@ export function searchSettings(
1236
)
1237
.map(({ item }) => item);
1238
}
1239
+
1240
+// Font smoothing only renders on macOS, so a search jump to it elsewhere
1241
+// must not flip the section - the target would never mount to be scrolled to.
1242
+const ADVANCED_TYPOGRAPHY_TARGET_IDS: ReadonlySet<string> = new Set([
1243
+ "prompt-font",
1244
+ "terminal-font",
1245
+ ...(typeof navigator !== "undefined" && isMacPlatform(navigator.platform)
1246
+ ? ["font-smoothing"]
1247
+ : []),
1248
+]);
1249
+
1250
+export function isAdvancedTypographyTarget(targetId: string): boolean {
1251
+ return ADVANCED_TYPOGRAPHY_TARGET_IDS.has(targetId);
1252
+}
1253
+
1254
+/**
1255
+ * Opens the persisted section a search result lives in before jumping to it, so
1256
+ * its row is mounted to scroll to. The terminal reads the same flag, so it must
1257
+ * stay on after the jump.
1258
+ */
1259
+export function revealSettingsSearchTarget(targetId: string): void {
1260
+ if (isAdvancedTypographyTarget(targetId)) {
1261
+ writeLocalStorageValue(TYPOGRAPHY_ADVANCED_STORAGE_KEY, true, false, Schema.Boolean);
1262
+ }
1263
+}
apps/web/src/hooks/useLocalStorage.ts
+1
-1
@@ -123,7 +123,7 @@ function decodeOrInitial<T, E>(
123
}
124
}
125
126
-function writeLocalStorageValue<T, E>(
126
+export function writeLocalStorageValue<T, E>(
127
key: string,
128
value: T | ((val: T) => T),
129
initialValue: T,
apps/web/src/state/session.ts
+1
-1
@@ -33,7 +33,7 @@ export function useEnvironmentScope(
33
return sessionHasScope(result, scope);
34
}
35
36
-function sessionHasScope(
36
+export function sessionHasScope(
37
result: AsyncResult.AsyncResult<AuthSessionState, unknown>,
38
scope: AuthEnvironmentScope,
39
): boolean {
apps/web/src/state/terminalSessions.test.ts
+42
-2
@@ -1,10 +1,32 @@
1
import { describe, expect, it, vi } from "vite-plus/test";
2
import { EnvironmentId, ThreadId, type TerminalSummary } from "@t3tools/contracts";
3
import { selectRunningSubprocessTerminalIds } from "@t3tools/client-runtime/state/terminal";
4
+import { AtomRegistry } from "effect/reactivity";
5
5
-import { selectKnownTerminalSessions } from "./terminalSessions";
6
+import { attachedTerminalSessionAtom, selectKnownTerminalSessions } from "./terminalSessions";
7
7
-vi.mock("./terminal", () => ({ terminalEnvironment: {} }));
8
+const attachCalls = vi.hoisted(() => [] as unknown[]);
9
+vi.mock("./terminal", async () => {
10
+ const { AsyncResult, Atom } = await import("effect/reactivity");
11
+ return {
12
+ terminalEnvironment: {
13
+ attach: (request: unknown) => {
14
+ attachCalls.push(request);
15
+ return Atom.make(AsyncResult.initial(true));
16
+ },
17
+ metadata: () => Atom.make(AsyncResult.initial(true)),
18
+ },
19
+ };
20
+});
21
+vi.mock("./session", async () => {
22
+ const { AsyncResult, Atom } = await import("effect/reactivity");
23
+ const granted = Atom.make(AsyncResult.success({}));
24
+ return {
25
+ environmentSession: { sessionStateAtom: () => granted },
26
+ sessionHasScope: () => true,
27
+ useEnvironmentScope: () => true,
28
+ };
29
+});
30
31
const environmentA = EnvironmentId.make("environment-a");
32
const threadA = ThreadId.make("thread-a");
@@ -77,3 +99,21 @@ describe("selectKnownTerminalSessions", () => {
99
expect(selectKnownTerminalSessions([other], environmentA, threadB)).toBe(beforeB);
100
});
101
});
102
+
103
+describe("attachedTerminalSessionAtom", () => {
104
+ it("attaches with the launch input it was keyed by", () => {
105
+ attachCalls.length = 0;
106
+ const input = {
107
+ threadId: threadA,
108
+ terminalId: "terminal-1",
109
+ cwd: "/repo",
110
+ worktreePath: null,
111
+ env: { T3CODE_PROJECT_ROOT: "/repo" },
112
+ };
113
+ const atom = attachedTerminalSessionAtom(environmentA, input);
114
+ expect(attachedTerminalSessionAtom(environmentA, { ...input })).toBe(atom);
115
+
116
+ AtomRegistry.make().get(atom);
117
+ expect(attachCalls).toEqual([{ environmentId: environmentA, input }]);
118
+ });
119
+});
apps/web/src/state/terminalSessions.ts
+72
-43
@@ -7,17 +7,21 @@ import {
7
type TerminalSessionState,
8
} from "@t3tools/client-runtime/state/terminal";
9
import {
10
+ EnvironmentId,
11
ThreadId,
12
AuthTerminalReadScope,
13
AuthTerminalOperateScope,
13
- type EnvironmentId,
14
- type TerminalAttachInput,
14
+ TerminalAttachInput,
15
type TerminalSummary,
16
} from "@t3tools/contracts";
17
18
-import { useEnvironmentQuery } from "./query";
18
+import * as Option from "effect/Option";
19
+import * as Schema from "effect/Schema";
20
+import { AsyncResult, Atom } from "effect/reactivity";
21
+
22
+import { formatEnvironmentQueryError, useEnvironmentQuery } from "./query";
23
import { terminalEnvironment } from "./terminal";
20
-import { useEnvironmentScope } from "./session";
24
+import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session";
25
26
const EMPTY_KNOWN_TERMINAL_SESSIONS = Object.freeze<ReadonlyArray<KnownTerminalSession>>([]);
27
@@ -121,47 +125,72 @@ export function selectKnownTerminalSessions(
125
return sessions;
126
}
127
124
-export function useAttachedTerminalSession(input: {
125
- readonly environmentId: EnvironmentId | null;
126
- readonly terminal: TerminalAttachInput | null;
127
-}): TerminalSessionState {
128
- const canRead = useEnvironmentScope(input.environmentId, AuthTerminalReadScope);
129
- const canOperate = useEnvironmentScope(input.environmentId, AuthTerminalOperateScope);
130
- const attach = useEnvironmentQuery(
131
- input.environmentId !== null && input.terminal !== null
132
- ? canOperate
133
- ? terminalEnvironment.attach({
134
- environmentId: input.environmentId,
135
- input: input.terminal,
136
- })
137
- : canRead
138
- ? terminalEnvironment.observe({
139
- environmentId: input.environmentId,
140
- input: { threadId: input.terminal.threadId, terminalId: input.terminal.terminalId },
141
- })
142
- : null
143
- : null,
144
- );
145
- const metadata = useEnvironmentQuery(
146
- input.environmentId === null || !canRead
147
- ? null
148
- : terminalEnvironment.metadata({
149
- environmentId: input.environmentId,
150
- input: null,
151
- }),
152
- );
128
+const EMPTY_TERMINAL_SESSION_ATOM = Atom.make(EMPTY_TERMINAL_SESSION_STATE).pipe(
129
+ Atom.withLabel("web-terminal-session:empty"),
130
+);
131
154
- if (input.environmentId === null || input.terminal === null) {
155
- return EMPTY_TERMINAL_SESSION_STATE;
132
+const decodeAttachKey = Schema.decodeUnknownOption(
133
+ Schema.fromJsonString(Schema.Tuple([EnvironmentId, TerminalAttachInput])),
134
+);
135
+
136
+// The family key carries the whole launch so an idle atom leaves nothing behind.
137
+const attachedTerminalSessionFamily = Atom.family((key: string) => {
138
+ const decoded = decodeAttachKey(key);
139
+ if (Option.isNone(decoded)) {
140
+ return Atom.make<TerminalSessionState>({
141
+ ...EMPTY_TERMINAL_SESSION_STATE,
142
+ error: "Invalid terminal launch input",
143
+ status: "error",
144
+ }).pipe(Atom.withLabel(`web-terminal-session:${key}`));
145
}
157
- const summary =
158
- (metadata.data === null
159
- ? null
160
- : terminalMetadataIndex(metadata.data)
161
- .byThreadId.get(input.terminal.threadId)
162
- ?.find((terminal) => terminal.terminalId === input.terminal?.terminalId)) ?? null;
163
- const state = combineTerminalSessionState(summary, attach.data ?? EMPTY_TERMINAL_BUFFER_STATE);
164
- return attach.error === null ? state : { ...state, error: attach.error, status: "error" };
146
+ const [environmentId, terminal] = decoded.value;
147
+ return Atom.make((get): TerminalSessionState => {
148
+ const session = get(environmentSession.sessionStateAtom(environmentId));
149
+ const canRead = sessionHasScope(session, AuthTerminalReadScope);
150
+ const canOperate = sessionHasScope(session, AuthTerminalOperateScope);
151
+ const attach = canOperate
152
+ ? get(terminalEnvironment.attach({ environmentId, input: terminal }))
153
+ : canRead
154
+ ? get(
155
+ terminalEnvironment.observe({
156
+ environmentId,
157
+ input: { threadId: terminal.threadId, terminalId: terminal.terminalId },
158
+ }),
159
+ )
160
+ : null;
161
+ const metadata = canRead
162
+ ? Option.getOrNull(
163
+ AsyncResult.value(get(terminalEnvironment.metadata({ environmentId, input: null }))),
164
+ )
165
+ : null;
166
+ const summary =
167
+ (metadata === null
168
+ ? null
169
+ : terminalMetadataIndex(metadata)
170
+ .byThreadId.get(terminal.threadId)
171
+ ?.find((candidate) => candidate.terminalId === terminal.terminalId)) ?? null;
172
+ const buffer =
173
+ attach === null
174
+ ? EMPTY_TERMINAL_BUFFER_STATE
175
+ : Option.getOrElse(AsyncResult.value(attach), () => EMPTY_TERMINAL_BUFFER_STATE);
176
+ const state = combineTerminalSessionState(summary, buffer);
177
+ return attach?._tag === "Failure"
178
+ ? { ...state, error: formatEnvironmentQueryError(attach.cause), status: "error" }
179
+ : state;
180
+ }).pipe(Atom.withLabel(`web-terminal-session:${key}`));
181
+});
182
+
183
+/**
184
+ * One shown terminal's session: its attach (or read-only observe) buffer
185
+ * combined with the metadata summary. Surfaces subscribe to it imperatively so
186
+ * output chunks never re-render React.
187
+ */
188
+export function attachedTerminalSessionAtom(
189
+ environmentId: EnvironmentId | null,
190
+ terminal: TerminalAttachInput | null,
191
+): Atom.Atom<TerminalSessionState> {
192
+ if (environmentId === null || terminal === null) return EMPTY_TERMINAL_SESSION_ATOM;
193
+ return attachedTerminalSessionFamily(JSON.stringify([environmentId, terminal]));
194
}
195
196
export function useKnownTerminalSessions(input: {