Skip to content

Commit 5fee09a

Browse files
refactor(web): terminal focus requests name the terminal they focus (#25009)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 07066c0 commit 5fee09a

15 files changed

Lines changed: 658 additions & 87 deletions

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

Lines changed: 6 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ import { usePanelAnimationSettings, usePanelPresence } from "../panelAnimations"
195195
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
196196
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
197197
import { isPreviewFocused } from "../lib/previewFocus";
198-
import { getTerminalFocusOwner } from "../lib/terminalFocus";
198+
import { focusTerminalOnThreadEnter, getTerminalFocusOwner } from "../lib/terminalFocus";
199199
import {
200200
deriveLogicalProjectKeyFromSettings,
201201
selectProjectGroupingSettings,
@@ -662,7 +662,6 @@ export default function ChatView(props: ChatViewProps) {
662662
const isMobileViewport = useMediaQuery("max-sm");
663663
const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState<HTMLDivElement | null>(null);
664664
const threadPanelPopoverAnchorRef = useRef<HTMLElement | null>(null);
665-
const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
666665
const [terminalUiLaunchContext, setTerminalUiLaunchContext] =
667666
useState<TerminalLaunchContext | null>(null);
668667
// Overrides chosen before a server thread's first turn; they belong to that thread only.
@@ -703,7 +702,6 @@ export default function ChatView(props: ChatViewProps) {
703702
};
704703
const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections);
705704
const feedbackUploadsInFlightRef = useRef(new Set<string>());
706-
const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
707705

708706
const terminalUiState = useTerminalUiStateStore((state) =>
709707
selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),
@@ -1862,7 +1860,6 @@ export default function ChatView(props: ChatViewProps) {
18621860
panelTerminalIds,
18631861
canReuseTerminal,
18641862
gitCwd,
1865-
setTerminalFocusRequestId,
18661863
setTerminalUiLaunchContext,
18671864
setThreadError,
18681865
});
@@ -2409,7 +2406,6 @@ export default function ChatView(props: ChatViewProps) {
24092406
gitCwd,
24102407
activeProjectCwd,
24112408
explicitDiffOpenRef,
2412-
setTerminalFocusRequestId,
24132409
onDiffPanelOpen,
24142410
closeRightPanelSurface,
24152411
});
@@ -2635,27 +2631,12 @@ export default function ChatView(props: ChatViewProps) {
26352631
setTerminalUiLaunchContext(null);
26362632
}
26372633

2634+
// Entering a thread with its drawer open focuses the drawer terminal; opening
2635+
// it from a handler requests focus there. A closed drawer leaves focus to the
2636+
// composer effect above.
26382637
useEffect(() => {
2639-
if (!activeThreadKey) return;
2640-
const previous = terminalUiOpenByThreadRef.current[activeThreadKey] ?? false;
2641-
const current = Boolean(terminalUiState.terminalOpen);
2642-
2643-
if (!previous && current) {
2644-
terminalUiOpenByThreadRef.current[activeThreadKey] = current;
2645-
setTerminalFocusRequestId((value) => value + 1);
2646-
return;
2647-
} else if (previous && !current) {
2648-
terminalUiOpenByThreadRef.current[activeThreadKey] = current;
2649-
const frame = window.requestAnimationFrame(() => {
2650-
focusComposerStable();
2651-
});
2652-
return () => {
2653-
window.cancelAnimationFrame(frame);
2654-
};
2655-
}
2656-
2657-
terminalUiOpenByThreadRef.current[activeThreadKey] = current;
2658-
}, [activeThreadKey, focusComposerStable, terminalUiState.terminalOpen]);
2638+
if (activeThreadRef) return focusTerminalOnThreadEnter(activeThreadRef);
2639+
}, [activeThreadRef]);
26592640

26602641
const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({
26612642
terminalFocus: getTerminalFocusOwner() !== null,
@@ -3089,7 +3070,6 @@ export default function ChatView(props: ChatViewProps) {
30893070
onCloseSurface={closeRightPanelSurface}
30903071
terminal={{
30913072
launchContext: activeTerminalLaunchContext ?? null,
3092-
focusRequestId: terminalFocusRequestId,
30933073
keybindings,
30943074
onAddTerminalContext: addTerminalContextToDraftStable,
30953075
onSplitTerminal: splitPanelTerminalStable,
@@ -3860,7 +3840,6 @@ export default function ChatView(props: ChatViewProps) {
38603840
activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}
38613841
composerHeight={composerReservedHeight}
38623842
launchContext={activeTerminalLaunchContext ?? null}
3863-
focusRequestId={terminalFocusRequestId}
38643843
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
38653844
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
38663845
newShortcutLabel={newTerminalShortcutLabel ?? undefined}

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

Lines changed: 5 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@ import {
88
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
99
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
1010
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
11-
import { memo, useEffect, useState } from "react";
11+
import { memo, useEffect } from "react";
1212
import { useComposerDraftStore } from "../composerDraftStore";
1313
import { useStableCallback } from "../hooks/useStableCallback";
1414
import type { TerminalContextSelection } from "../lib/terminalContext";
15+
import { focusActiveDrawerTerminal, focusTerminal } from "../lib/terminalFocus";
1516
import { cn } from "~/lib/utils";
1617
import {
1718
selectThreadRightPanelState,
@@ -78,7 +79,6 @@ interface PersistentThreadTerminalDrawerProps {
7879
active: boolean;
7980
composerHeight: number;
8081
launchContext: PersistentTerminalLaunchContext | null;
81-
focusRequestId: number;
8282
splitShortcutLabel: string | undefined;
8383
splitVerticalShortcutLabel: string | undefined;
8484
newShortcutLabel: string | undefined;
@@ -93,7 +93,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
9393
active,
9494
composerHeight,
9595
launchContext,
96-
focusRequestId,
9796
splitShortcutLabel,
9897
splitVerticalShortcutLabel,
9998
newShortcutLabel,
@@ -174,7 +173,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
174173
}
175174
reconcileTerminalIds(threadRef, serverOrderedTerminalIds);
176175
}, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]);
177-
const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
178176
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
179177
const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath;
180178
const cwd =
@@ -192,13 +190,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
192190
})
193191
: {};
194192

195-
const bumpFocusRequestId = () => {
196-
if (!visible) {
197-
return;
198-
}
199-
setLocalFocusRequestId((value) => value + 1);
200-
};
201-
202193
const setTerminalHeight = (height: number) => {
203194
storeSetTerminalHeight(threadRef, height);
204195
};
@@ -210,7 +201,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
210201
location: { cwd, worktreePath: effectiveWorktreePath },
211202
});
212203
if (!launched) return;
213-
bumpFocusRequestId();
204+
if (visible) focusTerminal(threadRef, launched.terminalId);
214205
void launched.result;
215206
};
216207
const splitTerminal = useStableCallback(() =>
@@ -225,14 +216,14 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
225216

226217
const activateTerminal = (terminalId: string) => {
227218
storeSetActiveTerminal(threadRef, terminalId);
228-
bumpFocusRequestId();
219+
if (visible) focusTerminal(threadRef, terminalId);
229220
};
230221

231222
const closeTerminal = useStableCallback((terminalId: string) => {
232223
if (!terminalActions.canWrite()) return;
233224
terminalActions.closeTerminalSession(terminalId);
234225
storeCloseTerminal(threadRef, terminalId);
235-
bumpFocusRequestId();
226+
if (visible) focusActiveDrawerTerminal(threadRef);
236227
});
237228

238229
const handleAddTerminalContext = (selection: TerminalContextSelection) => {
@@ -271,7 +262,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
271262
activeTerminalId={terminalUiState.activeTerminalId}
272263
terminalGroups={terminalUiState.terminalGroups}
273264
activeTerminalGroupId={terminalUiState.activeTerminalGroupId}
274-
focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
275265
onSplitTerminal={splitTerminal}
276266
onSplitTerminalVertical={splitTerminalVertical}
277267
onNewTerminal={createNewTerminal}
@@ -297,7 +287,6 @@ export interface PersistentThreadTerminalPanelProps {
297287
threadRef: ScopedThreadRef;
298288
surface: Extract<RightPanelSurface, { kind: "terminal" }>;
299289
launchContext: PersistentTerminalLaunchContext | null;
300-
focusRequestId: number;
301290
keybindings: ResolvedKeybindingsConfig;
302291
onAddTerminalContext: (selection: TerminalContextSelection) => void;
303292
onSplitTerminal: () => void;
@@ -316,7 +305,6 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
316305
threadRef,
317306
surface,
318307
launchContext,
319-
focusRequestId,
320308
keybindings,
321309
onAddTerminalContext,
322310
onSplitTerminal,
@@ -408,7 +396,6 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
408396
},
409397
]}
410398
activeTerminalGroupId={surface.id}
411-
focusRequestId={focusRequestId}
412399
onSplitTerminal={onSplitTerminal}
413400
onSplitTerminalVertical={onSplitTerminalVertical}
414401
onNewTerminal={onNewTerminal}

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

Lines changed: 44 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@ import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
8989
import { useAtomCommand } from "../state/use-atom-command";
9090
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
9191
import { observeResize } from "../lib/observeResize";
92+
import {
93+
consumePendingTerminalFocus,
94+
focusTerminal,
95+
focusTerminalViewport,
96+
registerTerminalFocusTarget,
97+
} from "../lib/terminalFocus";
9298
import {
9399
resolveTerminalFontPreference,
94100
resolveTerminalFontSizePreference,
@@ -420,8 +426,8 @@ interface TerminalViewportProps {
420426
providerInstanceId?: ProviderInstanceId;
421427
onSessionExited: () => void;
422428
onAddTerminalContext?: (selection: TerminalContextSelection) => void;
423-
focusRequestId: number;
424-
autoFocus: boolean;
429+
/** Focuses the viewport when it mounts; otherwise focus arrives through `focusTerminal`. */
430+
autoFocus?: boolean;
425431
visible: boolean;
426432
resizeEpoch: number;
427433
drawerHeight: number;
@@ -458,14 +464,14 @@ function TerminalSessionViewport({
458464
providerInstanceId,
459465
onSessionExited,
460466
onAddTerminalContext,
461-
focusRequestId,
462-
autoFocus,
467+
autoFocus = false,
463468
visible,
464469
resizeEpoch,
465470
drawerHeight,
466471
keybindings,
467472
}: TerminalViewportProps) {
468473
const containerRef = useRef<HTMLDivElement>(null);
474+
const autoFocusedRef = useRef(false);
469475
const terminalRef = useRef<GhosttyTerminalSurface | null>(null);
470476
const visibleRef = useRef(visible);
471477
const environmentId = threadRef.environmentId;
@@ -591,7 +597,9 @@ function TerminalSessionViewport({
591597

592598
useLayoutEffect(() => {
593599
if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal;
594-
}, [canOperateTerminal]);
600+
if (canOperateTerminal && visibleRef.current)
601+
consumePendingTerminalFocus(threadRef, terminalId);
602+
}, [canOperateTerminal, terminalId, threadRef]);
595603

596604
// Links re-read the grant on activation; only the hovered link's styling needs a nudge.
597605
const linkActivationScopeRef = useRef(canOpenHostEditor);
@@ -611,7 +619,9 @@ function TerminalSessionViewport({
611619
useLayoutEffect(() => {
612620
visibleRef.current = visible;
613621
terminalRef.current?.setVisible(visible);
614-
}, [visible]);
622+
// A request made while this viewport was hidden could not focus it.
623+
if (visible) consumePendingTerminalFocus(threadRef, terminalId);
624+
}, [terminalId, threadRef, visible]);
615625

616626
useEffect(() => {
617627
const current = terminalFontRef.current;
@@ -1093,12 +1103,6 @@ function TerminalSessionViewport({
10931103
previousSessionRef.current = current;
10941104
}, [terminalOutput, terminalError, terminalStatus, terminalVersion]);
10951105

1096-
const focusRequest = autoFocus && canOperateTerminal && visible ? focusRequestId : null;
1097-
useEffect(() => {
1098-
if (focusRequest === null) return;
1099-
(terminalRef.current ?? containerRef.current)?.focus();
1100-
}, [focusRequest]);
1101-
11021106
// A hidden surface skips fitting, and showing it again fits through setVisible.
11031107
const layoutRevision = visible ? `${drawerHeight}:${resizeEpoch}` : null;
11041108
useEffect(() => {
@@ -1117,9 +1121,36 @@ function TerminalSessionViewport({
11171121
window.cancelAnimationFrame(frame);
11181122
};
11191123
}, [layoutRevision]);
1124+
1125+
const attachContainer = (mount: HTMLDivElement) => {
1126+
containerRef.current = mount;
1127+
const focus = () =>
1128+
focusTerminalViewport({
1129+
mount,
1130+
surface: terminalRef.current,
1131+
canOperate: readEnvironmentScope(environmentId, AuthTerminalOperateScope),
1132+
visible: visibleRef.current,
1133+
});
1134+
// Once per viewport: a re-attached ref (a fresh callback identity) must not
1135+
// pull focus back on every render of a chatty terminal. As a request, it
1136+
// waits for the grant or for the viewport to show when it cannot focus yet.
1137+
if (autoFocus && !autoFocusedRef.current) {
1138+
autoFocusedRef.current = true;
1139+
focusTerminal(threadRef, terminalId);
1140+
}
1141+
const unregister = registerTerminalFocusTarget({
1142+
threadRef,
1143+
terminalId,
1144+
focus,
1145+
});
1146+
return () => {
1147+
unregister();
1148+
containerRef.current = null;
1149+
};
1150+
};
11201151
return (
11211152
<div
1122-
ref={containerRef}
1153+
ref={attachContainer}
11231154
tabIndex={-1}
11241155
className="relative h-full w-full overflow-hidden bg-(--terminal-background)"
11251156
/>
@@ -1141,7 +1172,6 @@ interface ThreadTerminalDrawerProps {
11411172
activeTerminalId: string;
11421173
terminalGroups: ThreadTerminalGroup[];
11431174
activeTerminalGroupId: string;
1144-
focusRequestId: number;
11451175
onSplitTerminal: () => void;
11461176
onSplitTerminalVertical: () => void;
11471177
onNewTerminal: () => void;
@@ -1214,7 +1244,6 @@ function TerminalSplitPanes({
12141244
threadRef,
12151245
threadId,
12161246
onAddTerminalContext,
1217-
focusRequestId,
12181247
visible,
12191248
resizeEpoch,
12201249
drawerHeight,
@@ -1231,7 +1260,6 @@ function TerminalSplitPanes({
12311260
threadRef: ScopedThreadRef;
12321261
threadId: ThreadId;
12331262
onAddTerminalContext: (selection: TerminalContextSelection) => void;
1234-
focusRequestId: number;
12351263
visible: boolean;
12361264
resizeEpoch: number;
12371265
drawerHeight: number;
@@ -1282,8 +1310,6 @@ function TerminalSplitPanes({
12821310
: {})}
12831311
onSessionExited={() => onCloseTerminal(terminalId)}
12841312
onAddTerminalContext={onAddTerminalContext}
1285-
focusRequestId={focusRequestId}
1286-
autoFocus={terminalId === activeTerminalId}
12871313
visible={visible}
12881314
resizeEpoch={resizeEpoch}
12891315
drawerHeight={drawerHeight}
@@ -1408,7 +1434,6 @@ export default function ThreadTerminalDrawer({
14081434
activeTerminalId,
14091435
terminalGroups,
14101436
activeTerminalGroupId,
1411-
focusRequestId,
14121437
onSplitTerminal,
14131438
onSplitTerminalVertical,
14141439
onNewTerminal,
@@ -1881,7 +1906,6 @@ export default function ThreadTerminalDrawer({
18811906
threadRef={threadRef}
18821907
threadId={threadId}
18831908
onAddTerminalContext={onAddTerminalContext}
1884-
focusRequestId={focusRequestId}
18851909
visible={visible}
18861910
resizeEpoch={resizeEpoch}
18871911
drawerHeight={drawerHeight}

‎apps/web/src/components/chat/ChatTerminalDrawers.tsx‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ interface ChatTerminalDrawersProps {
2525
readonly activeTerminalOpen: boolean;
2626
readonly composerHeight: number;
2727
readonly launchContext: PersistentTerminalLaunchContext | null;
28-
readonly focusRequestId: number;
2928
readonly splitShortcutLabel: string | undefined;
3029
readonly splitVerticalShortcutLabel: string | undefined;
3130
readonly newShortcutLabel: string | undefined;
@@ -97,7 +96,6 @@ export function ChatTerminalDrawers(props: ChatTerminalDrawersProps) {
9796
active={mountedThreadKey === activeThreadKey}
9897
composerHeight={mountedThreadKey === activeThreadKey ? props.composerHeight : 0}
9998
launchContext={mountedThreadKey === activeThreadKey ? props.launchContext : null}
100-
focusRequestId={mountedThreadKey === activeThreadKey ? props.focusRequestId : 0}
10199
splitShortcutLabel={props.splitShortcutLabel}
102100
splitVerticalShortcutLabel={props.splitVerticalShortcutLabel}
103101
newShortcutLabel={props.newShortcutLabel}

0 commit comments

Comments
 (0)