@devries-cameron20 / t3code-1 / commits / f4cf855672
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

perf(web): the terminal drawer compiles with the React Compiler (#20527)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 16, 2026 at 19:09 UTC f4cf855672d530f671b414cdb3c11de515c29799
2 files changed +245 -234
apps/web/reactCompiledFiles.ts
+1
@@ -94,4 +94,5 @@ export const REACT_COMPILED_FILES = [
94 "apps/web/src/hooks/useResizeDrag.ts",
95 "apps/web/src/components/settings/ThemeColorPicker.tsx",
96 "apps/web/src/components/pullRequest/PullRequestDetailPanel.tsx",
97 + "apps/web/src/components/ThreadTerminalDrawer.tsx",
98 ] as const;
apps/web/src/components/ThreadTerminalDrawer.tsx
+244 -234
@@ -34,11 +34,9 @@ import {
34 type PointerEvent as ReactPointerEvent,
35 type ReactNode,
36 type SetStateAction,
37 - useCallback,
37 useEffect,
38 useEffectEvent,
39 useLayoutEffect,
41 - useMemo,
40 useRef,
41 useState,
42 } from "react";
@@ -202,6 +200,20 @@ const TERMINAL_PALETTES = {
200 ].map(hexToGhosttyColor),
201 };
202
203 +// The surface reads `visible` once it finishes loading WASM, so it must see the value at
204 +// that moment rather than the one from when setup started.
205 +function withLiveVisibility(
206 + visibleRef: { readonly current: boolean },
207 + options: Omit<GhosttyTerminalSurfaceOptions, "visible">,
208 +): GhosttyTerminalSurfaceOptions {
209 + return {
210 + ...options,
211 + get visible() {
212 + return visibleRef.current;
213 + },
214 + };
215 +}
216 +
217 function runtimeEnvSignature(runtimeEnv: Record<string, string> | undefined): string {
218 if (!runtimeEnv) return "";
219 return JSON.stringify(
@@ -396,7 +408,21 @@ interface TerminalLaunchLocation {
408 readonly runtimeEnv?: Record<string, string>;
409 }
410
399 -export function TerminalViewport({
411 +export function TerminalViewport(props: TerminalViewportProps) {
412 + // A different launch is a different session, so it gets a fresh surface and fresh
413 + // session bookkeeping.
414 + const sessionKey = JSON.stringify([
415 + props.threadRef.environmentId,
416 + props.threadId,
417 + props.terminalId,
418 + props.cwd,
419 + props.worktreePath ?? null,
420 + runtimeEnvSignature(props.runtimeEnv),
421 + ]);
422 + return <TerminalSessionViewport key={sessionKey} {...props} />;
423 +}
424 +
425 +function TerminalSessionViewport({
426 advancedTypography,
427 threadRef,
428 threadId,
@@ -446,8 +472,7 @@ export function TerminalViewport({
472 const hasHandledExitRef = useRef(false);
473 const selectionActionRequestIdRef = useRef(0);
474 const openSelectionMenuRequestIdRef = useRef<number | null>(null);
449 - const keybindingsRef = useRef(keybindings);
450 - const runtimeEnvKey = useMemo(() => runtimeEnvSignature(runtimeEnv), [runtimeEnv]);
475 + const readKeybindings = useEffectEvent(() => keybindings);
476 const handleSessionExited = useEffectEvent(() => {
477 if (hasTerminalWriteAccess()) onSessionExited();
478 });
@@ -529,23 +554,26 @@ export function TerminalViewport({
554 status: terminalStatus,
555 version: terminalVersion,
556 });
532 - const latestSessionRef = useRef(previousSessionRef.current);
533 - latestSessionRef.current = {
557 + const readLatestSession = useEffectEvent(() => ({
558 output: terminalOutput,
559 error: terminalError,
560 status: terminalStatus,
561 version: terminalVersion,
538 - };
539 -
540 - useEffect(() => {
541 - keybindingsRef.current = keybindings;
542 - }, [keybindings]);
562 + }));
563 + const openLinkInPreview = useEffectEvent(
564 + (url: string, forceBrowser: boolean, fallbackToBrowser: () => void) =>
565 + openTerminalLinkInPreview({ url, threadRef, openPreview, fallbackToBrowser, forceBrowser }),
566 + );
567
568 useLayoutEffect(() => {
569 if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal;
570 }, [canOperateTerminal]);
571
572 + // Links re-read the grant on activation; only the hovered link's styling needs a nudge.
573 + const linkActivationScopeRef = useRef(canOpenHostEditor);
574 useEffect(() => {
575 + if (linkActivationScopeRef.current === canOpenHostEditor) return;
576 + linkActivationScopeRef.current = canOpenHostEditor;
577 terminalRef.current?.refreshLinkActivation();
578 }, [canOpenHostEditor]);
579
@@ -581,12 +609,9 @@ export function TerminalViewport({
609
610 const setup = async (): Promise<(() => void) | null> => {
611 const setupFont = terminalFontRef.current;
584 - const terminalOptions: GhosttyTerminalSurfaceOptions = {
612 + const terminalOptions = withLiveVisibility(visibleRef, {
613 theme: terminalThemeFromApp(mount),
614 font: terminalFontOptions(setupFont.family, setupFont.size),
587 - get visible() {
588 - return visibleRef.current;
589 - },
615 onData: (data) => handleData(data),
616 onResize: (cols, rows) => void resizeTerminal(cols, rows),
617 onSelectionChange: () => handleSelectionChange(),
@@ -599,7 +624,7 @@ export function TerminalViewport({
624 onContextMenu: (event) => {
625 if (terminalRef.current) void showTerminalContextMenu(event);
626 },
602 - };
627 + });
628 const terminal = await GhosttyTerminalSurface.create(mount, terminalOptions);
629 if (cancelled) {
630 terminal.dispose();
@@ -619,7 +644,7 @@ export function TerminalViewport({
644 if (currentFont.family !== setupFont.family || currentFont.size !== setupFont.size) {
645 void terminal.setFont(terminalFontOptions(currentFont.family, currentFont.size));
646 }
622 - const latestSession = latestSessionRef.current;
647 + const latestSession = readLatestSession();
648 previousSessionRef.current = latestSession;
649 const initialOutput = readTerminalOutputUpdate(
650 latestSession.output,
@@ -842,7 +867,7 @@ export function TerminalViewport({
867 };
868
869 function handleBeforeKey(event: KeyboardEvent): boolean {
845 - const currentKeybindings = keybindingsRef.current;
870 + const currentKeybindings = readKeybindings();
871 const options = { context: { terminalFocus: true, terminalOpen: true } };
872 if (preventTerminalCloseShortcut(event, currentKeybindings)) {
873 return false;
@@ -901,21 +926,17 @@ export function TerminalViewport({
926 fallbackToBrowser();
927 return;
928 }
904 - void openTerminalLinkInPreview({
905 - url: text,
906 - threadRef,
907 - openPreview,
908 - fallbackToBrowser,
909 - forceBrowser: event.metaKey || event.ctrlKey,
910 - }).catch((error: unknown) => {
911 - toastManager.add(
912 - stackedThreadToast({
913 - type: "error",
914 - title: "Unable to open link",
915 - description: error instanceof Error ? error.message : "An error occurred.",
916 - }),
917 - );
918 - });
929 + void openLinkInPreview(text, event.metaKey || event.ctrlKey, fallbackToBrowser).catch(
930 + (error: unknown) => {
931 + toastManager.add(
932 + stackedThreadToast({
933 + type: "error",
934 + title: "Unable to open link",
935 + description: error instanceof Error ? error.message : "An error occurred.",
936 + }),
937 + );
938 + },
939 + );
940 return;
941 }
942 const target = resolvePathLinkTarget(text, cwd);
@@ -1027,7 +1048,7 @@ export function TerminalViewport({
1048 mount.focus({ preventScroll: true });
1049 }
1050 };
1030 - }, [cwd, environmentId, runtimeEnvKey, terminalId, threadId, worktreePath]);
1051 + }, [cwd, environmentId, terminalId]);
1052
1053 useEffect(() => {
1054 const terminal = terminalRef.current;
@@ -1057,14 +1078,19 @@ export function TerminalViewport({
1078 previousSessionRef.current = current;
1079 }, [terminalOutput, terminalError, terminalStatus, terminalVersion]);
1080
1081 + // Each new request focuses again, even when nothing else changed.
1082 + const focusRequest = autoFocus && canOperateTerminal && visible ? focusRequestId : null;
1083 useEffect(() => {
1061 - if (!autoFocus || !canOperateTerminal || !visible) return;
1084 + if (focusRequest === null) return;
1085 (terminalRef.current ?? containerRef.current)?.focus();
1063 - }, [autoFocus, canOperateTerminal, focusRequestId, visible]);
1086 + }, [focusRequest]);
1087
1088 + // The surface measures its mount, so each drawer resize or window resize refits it.
1089 + // A hidden surface skips fitting, and showing it again fits through setVisible.
1090 + const layoutRevision = visible ? `${drawerHeight}:${resizeEpoch}` : null;
1091 useEffect(() => {
1092 const terminal = terminalRef.current;
1067 - if (!terminal || !visibleRef.current) return;
1093 + if (!terminal || layoutRevision === null) return;
1094 const wasAtBottom = terminal.isAtBottom();
1095 // The surface reports grid changes through onResize, which is the single
1096 // channel for PTY resize RPCs; fitting here only refreshes the layout.
@@ -1078,7 +1104,7 @@ export function TerminalViewport({
1104 return () => {
1105 window.cancelAnimationFrame(frame);
1106 };
1081 - }, [drawerHeight, environmentId, resizeEpoch, terminalId, threadId]);
1107 + }, [layoutRevision]);
1108 return (
1109 <div
1110 ref={containerRef}
@@ -1118,6 +1144,107 @@ interface ThreadTerminalDrawerProps {
1144 terminalLaunchLocationsById?: ReadonlyMap<string, TerminalLaunchLocation>;
1145 }
1146
1147 +function useTerminalLayout(
1148 + terminalIds: readonly string[],
1149 + terminalGroups: readonly ThreadTerminalGroup[],
1150 + terminalLabelsById: ReadonlyMap<string, string> | undefined,
1151 +) {
1152 + // Calls no hooks, so the compiler needs the directive to memoize it.
1153 + "use memo";
1154 + const normalizedTerminalIds = (() => {
1155 + const normalizedIds: string[] = [];
1156 + const seen = new Set<string>();
1157 + for (const id of terminalIds) {
1158 + const trimmedId = id.trim();
1159 + if (trimmedId.length === 0 || seen.has(trimmedId)) continue;
1160 + seen.add(trimmedId);
1161 + normalizedIds.push(trimmedId);
1162 + }
1163 + return normalizedIds;
1164 + })();
1165 + const resolvedTerminalGroups = (() => {
1166 + if (normalizedTerminalIds.length === 0) {
1167 + return [];
1168 + }
1169 + const validTerminalIdSet = new Set(normalizedTerminalIds);
1170 + const assignedTerminalIds = new Set<string>();
1171 + const usedGroupIds = new Set<string>();
1172 + const nextGroups: ThreadTerminalGroup[] = [];
1173 +
1174 + const assignUniqueGroupId = (groupId: string): string => {
1175 + if (!usedGroupIds.has(groupId)) {
1176 + usedGroupIds.add(groupId);
1177 + return groupId;
1178 + }
1179 + let suffix = 2;
1180 + while (usedGroupIds.has(`${groupId}-${suffix}`)) {
1181 + suffix += 1;
1182 + }
1183 + const uniqueGroupId = `${groupId}-${suffix}`;
1184 + usedGroupIds.add(uniqueGroupId);
1185 + return uniqueGroupId;
1186 + };
1187 +
1188 + for (const terminalGroup of terminalGroups) {
1189 + const nextTerminalIds: string[] = [];
1190 + const seenGroupTerminalIds = new Set<string>();
1191 + for (const id of terminalGroup.terminalIds) {
1192 + const terminalId = id.trim();
1193 + if (terminalId.length === 0) continue;
1194 + if (seenGroupTerminalIds.has(terminalId)) continue;
1195 + seenGroupTerminalIds.add(terminalId);
1196 + if (!validTerminalIdSet.has(terminalId)) continue;
1197 + if (assignedTerminalIds.has(terminalId)) continue;
1198 + nextTerminalIds.push(terminalId);
1199 + }
1200 + if (nextTerminalIds.length === 0) continue;
1201 +
1202 + for (const terminalId of nextTerminalIds) {
1203 + assignedTerminalIds.add(terminalId);
1204 + }
1205 +
1206 + const baseGroupId =
1207 + terminalGroup.id.trim().length > 0
1208 + ? terminalGroup.id.trim()
1209 + : `group-${nextTerminalIds[0] ?? normalizedTerminalIds[0] ?? ""}`;
1210 + nextGroups.push({
1211 + id: assignUniqueGroupId(baseGroupId),
1212 + terminalIds: nextTerminalIds,
1213 + ...(terminalGroup.splitDirection === "vertical"
1214 + ? { splitDirection: "vertical" as const }
1215 + : {}),
1216 + });
1217 + }
1218 +
1219 + for (const terminalId of normalizedTerminalIds) {
1220 + if (assignedTerminalIds.has(terminalId)) continue;
1221 + nextGroups.push({
1222 + id: assignUniqueGroupId(`group-${terminalId}`),
1223 + terminalIds: [terminalId],
1224 + });
1225 + }
1226 +
1227 + const terminalOrderIndex = new Map(
1228 + normalizedTerminalIds.map((id, index) => [id, index] as const),
1229 + );
1230 + nextGroups.sort((left, right) => {
1231 + const rank = (ids: readonly string[]) =>
1232 + Math.min(...ids.map((id) => terminalOrderIndex.get(id) ?? Number.POSITIVE_INFINITY));
1233 + return rank(left.terminalIds) - rank(right.terminalIds);
1234 + });
1235 +
1236 + return nextGroups;
1237 + })();
1238 + const terminalLabelById = (() => {
1239 + const next = new Map<string, string>();
1240 + for (const terminalId of normalizedTerminalIds) {
1241 + next.set(terminalId, terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId));
1242 + }
1243 + return next;
1244 + })();
1245 + return { normalizedTerminalIds, resolvedTerminalGroups, terminalLabelById };
1246 +}
1247 +
1248 interface TerminalActionButtonProps {
1249 label: string;
1250 className: string;
@@ -1207,24 +1334,24 @@ export default function ThreadTerminalDrawer({
1334 const preferredDrawerHeight =
1335 drawerHeightState.threadId === threadId ? drawerHeightState.height : controlledDrawerHeight;
1336 const drawerHeight = clampDrawerHeight(preferredDrawerHeight, windowMaxDrawerHeight);
1210 - const setDrawerHeight = useCallback(
1211 - (update: SetStateAction<number>) => {
1212 - setDrawerHeightState((current) => {
1213 - const currentHeight =
1214 - current.threadId === threadId ? current.height : controlledDrawerHeight;
1215 - const nextHeight = typeof update === "function" ? update(currentHeight) : update;
1216 - return nextHeight === currentHeight && current.threadId === threadId
1217 - ? current
1218 - : { threadId, height: nextHeight };
1219 - });
1220 - },
1221 - [controlledDrawerHeight, threadId],
1222 - );
1337 + const setDrawerHeight = (update: SetStateAction<number>) => {
1338 + setDrawerHeightState((current) => {
1339 + const currentHeight = current.threadId === threadId ? current.height : controlledDrawerHeight;
1340 + const nextHeight = typeof update === "function" ? update(currentHeight) : update;
1341 + return nextHeight === currentHeight && current.threadId === threadId
1342 + ? current
1343 + : { threadId, height: nextHeight };
1344 + });
1345 + };
1346 const [resizeEpoch, setResizeEpoch] = useState(0);
1347 + const [shownVisible, setShownVisible] = useState(visible);
1348 + if (shownVisible !== visible) {
1349 + setShownVisible(visible);
1350 + // The window may have resized while the drawer was hidden and not listening.
1351 + if (visible) setWindowMaxDrawerHeight(maxDrawerHeight());
1352 + }
1353 const drawerHeightRef = useRef(drawerHeight);
1225 - const preferredDrawerHeightRef = useRef(preferredDrawerHeight);
1226 - const lastSyncedHeightRef = useRef(controlledDrawerHeight);
1227 - const onHeightChangeRef = useRef(onHeightChange);
1354 + const lastSyncedHeightRef = useRef({ threadId, height: controlledDrawerHeight });
1355 const resizeStateRef = useRef<{
1356 pointerId: number;
1357 startY: number;
@@ -1233,17 +1360,11 @@ export default function ThreadTerminalDrawer({
1360 } | null>(null);
1361 const didResizeDuringDragRef = useRef(false);
1362
1236 - const normalizedTerminalIds = useMemo(() => {
1237 - const normalizedIds: string[] = [];
1238 - const seen = new Set<string>();
1239 - for (const id of terminalIds) {
1240 - const trimmedId = id.trim();
1241 - if (trimmedId.length === 0 || seen.has(trimmedId)) continue;
1242 - seen.add(trimmedId);
1243 - normalizedIds.push(trimmedId);
1244 - }
1245 - return normalizedIds;
1246 - }, [terminalIds]);
1363 + const { normalizedTerminalIds, resolvedTerminalGroups, terminalLabelById } = useTerminalLayout(
1364 + terminalIds,
1365 + terminalGroups,
1366 + terminalLabelsById,
1367 + );
1368
1369 const resolvedActiveTerminalId =
1370 normalizedTerminalIds.length === 0
@@ -1252,81 +1373,7 @@ export default function ThreadTerminalDrawer({
1373 ? activeTerminalId
1374 : (normalizedTerminalIds[0] ?? "");
1375
1255 - const resolvedTerminalGroups = useMemo(() => {
1256 - if (normalizedTerminalIds.length === 0) {
1257 - return [];
1258 - }
1259 - const validTerminalIdSet = new Set(normalizedTerminalIds);
1260 - const assignedTerminalIds = new Set<string>();
1261 - const usedGroupIds = new Set<string>();
1262 - const nextGroups: ThreadTerminalGroup[] = [];
1263 -
1264 - const assignUniqueGroupId = (groupId: string): string => {
1265 - if (!usedGroupIds.has(groupId)) {
1266 - usedGroupIds.add(groupId);
1267 - return groupId;
1268 - }
1269 - let suffix = 2;
1270 - while (usedGroupIds.has(`${groupId}-${suffix}`)) {
1271 - suffix += 1;
1272 - }
1273 - const uniqueGroupId = `${groupId}-${suffix}`;
1274 - usedGroupIds.add(uniqueGroupId);
1275 - return uniqueGroupId;
1276 - };
1277 -
1278 - for (const terminalGroup of terminalGroups) {
1279 - const nextTerminalIds: string[] = [];
1280 - const seenGroupTerminalIds = new Set<string>();
1281 - for (const id of terminalGroup.terminalIds) {
1282 - const terminalId = id.trim();
1283 - if (terminalId.length === 0) continue;
1284 - if (seenGroupTerminalIds.has(terminalId)) continue;
1285 - seenGroupTerminalIds.add(terminalId);
1286 - if (!validTerminalIdSet.has(terminalId)) continue;
1287 - if (assignedTerminalIds.has(terminalId)) continue;
1288 - nextTerminalIds.push(terminalId);
1289 - }
1290 - if (nextTerminalIds.length === 0) continue;
1291 -
1292 - for (const terminalId of nextTerminalIds) {
1293 - assignedTerminalIds.add(terminalId);
1294 - }
1295 -
1296 - const baseGroupId =
1297 - terminalGroup.id.trim().length > 0
1298 - ? terminalGroup.id.trim()
1299 - : `group-${nextTerminalIds[0] ?? normalizedTerminalIds[0] ?? ""}`;
1300 - nextGroups.push({
1301 - id: assignUniqueGroupId(baseGroupId),
1302 - terminalIds: nextTerminalIds,
1303 - ...(terminalGroup.splitDirection === "vertical"
1304 - ? { splitDirection: "vertical" as const }
1305 - : {}),
1306 - });
1307 - }
1308 -
1309 - for (const terminalId of normalizedTerminalIds) {
1310 - if (assignedTerminalIds.has(terminalId)) continue;
1311 - nextGroups.push({
1312 - id: assignUniqueGroupId(`group-${terminalId}`),
1313 - terminalIds: [terminalId],
1314 - });
1315 - }
1316 -
1317 - const terminalOrderIndex = new Map(
1318 - normalizedTerminalIds.map((id, index) => [id, index] as const),
1319 - );
1320 - nextGroups.sort((left, right) => {
1321 - const rank = (ids: readonly string[]) =>
1322 - Math.min(...ids.map((id) => terminalOrderIndex.get(id) ?? Number.POSITIVE_INFINITY));
1323 - return rank(left.terminalIds) - rank(right.terminalIds);
1324 - });
1325 -
1326 - return nextGroups;
1327 - }, [normalizedTerminalIds, terminalGroups]);
1328 -
1329 - const resolvedActiveGroupIndex = useMemo(() => {
1376 + const resolvedActiveGroupIndex = (() => {
1377 const indexById = resolvedTerminalGroups.findIndex(
1378 (terminalGroup) => terminalGroup.id === activeTerminalGroupId,
1379 );
@@ -1335,7 +1382,7 @@ export default function ThreadTerminalDrawer({
1382 terminalGroup.terminalIds.includes(resolvedActiveTerminalId),
1383 );
1384 return indexByTerminal >= 0 ? indexByTerminal : 0;
1338 - }, [activeTerminalGroupId, resolvedActiveTerminalId, resolvedTerminalGroups]);
1385 + })();
1386
1387 const visibleTerminalIds =
1388 resolvedTerminalGroups[resolvedActiveGroupIndex]?.terminalIds ??
@@ -1348,25 +1395,12 @@ export default function ThreadTerminalDrawer({
1395 resolvedTerminalGroups.length > 1 ||
1396 resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
1397 const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP;
1351 - const terminalLabelById = useMemo(() => {
1352 - const next = new Map<string, string>();
1353 - for (const terminalId of normalizedTerminalIds) {
1354 - next.set(terminalId, terminalLabelsById?.get(terminalId) ?? getTerminalLabel(terminalId));
1355 - }
1356 - return next;
1357 - }, [normalizedTerminalIds, terminalLabelsById]);
1358 - const resolveTerminalLaunchLocation = useCallback(
1359 - (terminalId: string): TerminalLaunchLocation => {
1360 - return (
1361 - terminalLaunchLocationsById?.get(terminalId) ?? {
1362 - cwd,
1363 - ...(worktreePath !== undefined ? { worktreePath } : {}),
1364 - ...(runtimeEnv ? { runtimeEnv } : {}),
1365 - }
1366 - );
1367 - },
1368 - [cwd, runtimeEnv, terminalLaunchLocationsById, worktreePath],
1369 - );
1398 + const resolveTerminalLaunchLocation = (terminalId: string): TerminalLaunchLocation =>
1399 + terminalLaunchLocationsById?.get(terminalId) ?? {
1400 + cwd,
1401 + ...(worktreePath !== undefined ? { worktreePath } : {}),
1402 + ...(runtimeEnv ? { runtimeEnv } : {}),
1403 + };
1404 const splitTerminalActionLabel = hasReachedSplitLimit
1405 ? `Split Terminal Horizontally (max ${MAX_TERMINALS_PER_GROUP} per group)`
1406 : splitShortcutLabel
@@ -1383,34 +1417,27 @@ export default function ThreadTerminalDrawer({
1417 const closeTerminalActionLabel = closeShortcutLabel
1418 ? `Close Terminal (${closeShortcutLabel})`
1419 : "Close Terminal";
1386 - const onSplitTerminalAction = useCallback(() => {
1420 + const onSplitTerminalAction = () => {
1421 if (!canOperateTerminal || hasReachedSplitLimit) return;
1422 onSplitTerminal();
1389 - }, [canOperateTerminal, hasReachedSplitLimit, onSplitTerminal]);
1390 - const onSplitTerminalVerticalAction = useCallback(() => {
1423 + };
1424 + const onSplitTerminalVerticalAction = () => {
1425 if (!canOperateTerminal || hasReachedSplitLimit) return;
1426 onSplitTerminalVertical();
1393 - }, [canOperateTerminal, hasReachedSplitLimit, onSplitTerminalVertical]);
1394 - const onNewTerminalAction = useCallback(() => {
1427 + };
1428 + const onNewTerminalAction = () => {
1429 if (!canOperateTerminal) return;
1430 onNewTerminal();
1397 - }, [canOperateTerminal, onNewTerminal]);
1398 - const confirmCloseTerminal = useCallback(
1399 - (terminalId: string) => {
1400 - if (!canOperateTerminal) return;
1401 - const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId);
1402 - void confirmTerminalClose([label]).then((confirmed) => {
1403 - if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) {
1404 - onCloseTerminal(terminalId);
1405 - }
1406 - });
1407 - },
1408 - [canOperateTerminal, onCloseTerminal, terminalLabelById, threadRef.environmentId],
1409 - );
1410 -
1411 - useEffect(() => {
1412 - onHeightChangeRef.current = onHeightChange;
1413 - }, [onHeightChange]);
1431 + };
1432 + const confirmCloseTerminal = (terminalId: string) => {
1433 + if (!canOperateTerminal) return;
1434 + const label = terminalLabelById.get(terminalId) ?? getTerminalLabel(terminalId);
1435 + void confirmTerminalClose([label]).then((confirmed) => {
1436 + if (confirmed && readEnvironmentScope(threadRef.environmentId, AuthTerminalOperateScope)) {
1437 + onCloseTerminal(terminalId);
1438 + }
1439 + });
1440 + };
1441
1442 useLayoutEffect(() => {
1443 const resizeState = resizeStateRef.current;
@@ -1421,21 +1448,18 @@ export default function ThreadTerminalDrawer({
1448 drawerHeightRef.current = drawerHeight;
1449 }, [drawerHeight]);
1450
1424 - useEffect(() => {
1425 - preferredDrawerHeightRef.current = preferredDrawerHeight;
1426 - }, [preferredDrawerHeight]);
1427 -
1428 - const syncHeight = useCallback((nextHeight: number) => {
1429 - if (lastSyncedHeightRef.current === nextHeight) return;
1430 - lastSyncedHeightRef.current = nextHeight;
1431 - onHeightChangeRef.current(nextHeight);
1432 - }, []);
1451 + const syncHeight = (nextHeight: number) => {
1452 + const lastSynced = lastSyncedHeightRef.current;
1453 + if (lastSynced.threadId === threadId && lastSynced.height === nextHeight) return;
1454 + lastSyncedHeightRef.current = { threadId, height: nextHeight };
1455 + onHeightChange(nextHeight);
1456 + };
1457
1458 useEffect(() => {
1435 - lastSyncedHeightRef.current = controlledDrawerHeight;
1459 + lastSyncedHeightRef.current = { threadId, height: controlledDrawerHeight };
1460 }, [controlledDrawerHeight, threadId]);
1461
1438 - const handleResizePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
1462 + const handleResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {
1463 if (event.button !== 0) return;
1464 event.preventDefault();
1465 event.currentTarget.setPointerCapture(event.pointerId);
@@ -1446,9 +1470,9 @@ export default function ThreadTerminalDrawer({
1470 startHeight: drawerHeightRef.current,
1471 drawer: event.currentTarget.parentElement,
1472 };
1449 - }, []);
1473 + };
1474
1451 - const handleResizePointerMove = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {
1475 + const handleResizePointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {
1476 const resizeState = resizeStateRef.current;
1477 if (!resizeState || resizeState.pointerId !== event.pointerId) return;
1478 event.preventDefault();
@@ -1461,32 +1485,29 @@ export default function ThreadTerminalDrawer({
1485 didResizeDuringDragRef.current = true;
1486 drawerHeightRef.current = clampedHeight;
1487 resizeState.drawer?.style.setProperty("height", `${clampedHeight}px`);
1464 - }, []);
1488 + };
1489
1466 - const handleResizePointerEnd = useCallback(
1467 - (event: ReactPointerEvent<HTMLDivElement>) => {
1468 - const resizeState = resizeStateRef.current;
1469 - if (!resizeState || resizeState.pointerId !== event.pointerId) return;
1470 - resizeStateRef.current = null;
1471 - if (event.currentTarget.hasPointerCapture(event.pointerId)) {
1472 - event.currentTarget.releasePointerCapture(event.pointerId);
1473 - }
1474 - // A drag that ends where it started keeps the stored preference, which may
1475 - // be taller than the window-capped height the drag started from.
1476 - if (!didResizeDuringDragRef.current || drawerHeightRef.current === resizeState.startHeight) {
1477 - // React skips the write when the rendered height did not change, so put
1478 - // back the preference as the current window caps it.
1479 - const renderedHeight = clampDrawerHeight(preferredDrawerHeightRef.current);
1480 - drawerHeightRef.current = renderedHeight;
1481 - resizeState.drawer?.style.setProperty("height", `${renderedHeight}px`);
1482 - return;
1483 - }
1484 - setDrawerHeight(drawerHeightRef.current);
1485 - syncHeight(drawerHeightRef.current);
1486 - setResizeEpoch((value) => value + 1);
1487 - },
1488 - [setDrawerHeight, syncHeight],
1489 - );
1490 + const handleResizePointerEnd = (event: ReactPointerEvent<HTMLDivElement>) => {
1491 + const resizeState = resizeStateRef.current;
1492 + if (!resizeState || resizeState.pointerId !== event.pointerId) return;
1493 + resizeStateRef.current = null;
1494 + if (event.currentTarget.hasPointerCapture(event.pointerId)) {
1495 + event.currentTarget.releasePointerCapture(event.pointerId);
1496 + }
1497 + // A drag that ends where it started keeps the stored preference, which may
1498 + // be taller than the window-capped height the drag started from.
1499 + if (!didResizeDuringDragRef.current || drawerHeightRef.current === resizeState.startHeight) {
1500 + // React skips the write when the rendered height did not change, so put
1501 + // back the preference as the current window caps it.
1502 + const renderedHeight = clampDrawerHeight(preferredDrawerHeight);
1503 + drawerHeightRef.current = renderedHeight;
1504 + resizeState.drawer?.style.setProperty("height", `${renderedHeight}px`);
1505 + return;
1506 + }
1507 + setDrawerHeight(drawerHeightRef.current);
1508 + syncHeight(drawerHeightRef.current);
1509 + setResizeEpoch((value) => value + 1);
1510 + };
1511
1512 useEffect(() => {
1513 if (!visible) {
@@ -1509,19 +1530,8 @@ export default function ThreadTerminalDrawer({
1530 };
1531 }, [visible]);
1532
1512 - useEffect(() => {
1513 - if (!visible) {
1514 - return;
1515 - }
1516 - setWindowMaxDrawerHeight(maxDrawerHeight());
1517 - setResizeEpoch((value) => value + 1);
1518 - }, [visible]);
1519 -
1520 - useEffect(() => {
1521 - return () => {
1522 - syncHeight(preferredDrawerHeightRef.current);
1523 - };
1524 - }, [syncHeight]);
1533 + const syncPreferredHeight = useEffectEvent(() => syncHeight(preferredDrawerHeight));
1534 + useEffect(() => () => syncPreferredHeight(), []);
1535
1536 if (normalizedTerminalIds.length === 0) {
1537 return (