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, 17:00 UTC
refactor(web): terminal focus requests name the terminal they focus (#25009)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 25, 2026 at 17:52 UTC
5fee09a2c109fa973294c1d5fc3729bfd1a7f093
15 files changed
+658
-87
apps/web/src/components/ChatView.tsx
+6
-27
@@ -195,7 +195,7 @@ import { usePanelAnimationSettings, usePanelPresence } from "../panelAnimations"
195
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
196
import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";
197
import { isPreviewFocused } from "../lib/previewFocus";
198
-import { getTerminalFocusOwner } from "../lib/terminalFocus";
198
+import { focusTerminalOnThreadEnter, getTerminalFocusOwner } from "../lib/terminalFocus";
199
import {
200
deriveLogicalProjectKeyFromSettings,
201
selectProjectGroupingSettings,
@@ -662,7 +662,6 @@ export default function ChatView(props: ChatViewProps) {
662
const isMobileViewport = useMediaQuery("max-sm");
663
const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState<HTMLDivElement | null>(null);
664
const threadPanelPopoverAnchorRef = useRef<HTMLElement | null>(null);
665
- const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);
665
const [terminalUiLaunchContext, setTerminalUiLaunchContext] =
666
useState<TerminalLaunchContext | null>(null);
667
// 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) {
702
};
703
const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections);
704
const feedbackUploadsInFlightRef = useRef(new Set<string>());
706
- const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
705
706
const terminalUiState = useTerminalUiStateStore((state) =>
707
selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),
@@ -1862,7 +1860,6 @@ export default function ChatView(props: ChatViewProps) {
1860
panelTerminalIds,
1861
canReuseTerminal,
1862
gitCwd,
1865
- setTerminalFocusRequestId,
1863
setTerminalUiLaunchContext,
1864
setThreadError,
1865
});
@@ -2409,7 +2406,6 @@ export default function ChatView(props: ChatViewProps) {
2406
gitCwd,
2407
activeProjectCwd,
2408
explicitDiffOpenRef,
2412
- setTerminalFocusRequestId,
2409
onDiffPanelOpen,
2410
closeRightPanelSurface,
2411
});
@@ -2635,27 +2631,12 @@ export default function ChatView(props: ChatViewProps) {
2631
setTerminalUiLaunchContext(null);
2632
}
2633
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.
2637
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]);
2640
2641
const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({
2642
terminalFocus: getTerminalFocusOwner() !== null,
@@ -3089,7 +3070,6 @@ export default function ChatView(props: ChatViewProps) {
3070
onCloseSurface={closeRightPanelSurface}
3071
terminal={{
3072
launchContext: activeTerminalLaunchContext ?? null,
3092
- focusRequestId: terminalFocusRequestId,
3073
keybindings,
3074
onAddTerminalContext: addTerminalContextToDraftStable,
3075
onSplitTerminal: splitPanelTerminalStable,
@@ -3860,7 +3840,6 @@ export default function ChatView(props: ChatViewProps) {
3840
activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}
3841
composerHeight={composerReservedHeight}
3842
launchContext={activeTerminalLaunchContext ?? null}
3863
- focusRequestId={terminalFocusRequestId}
3843
splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}
3844
splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}
3845
newShortcutLabel={newTerminalShortcutLabel ?? undefined}
apps/web/src/components/PersistentThreadTerminals.tsx
+5
-18
@@ -8,10 +8,11 @@ import {
8
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
9
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
10
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
11
-import { memo, useEffect, useState } from "react";
11
+import { memo, useEffect } from "react";
12
import { useComposerDraftStore } from "../composerDraftStore";
13
import { useStableCallback } from "../hooks/useStableCallback";
14
import type { TerminalContextSelection } from "../lib/terminalContext";
15
+import { focusActiveDrawerTerminal, focusTerminal } from "../lib/terminalFocus";
16
import { cn } from "~/lib/utils";
17
import {
18
selectThreadRightPanelState,
@@ -78,7 +79,6 @@ interface PersistentThreadTerminalDrawerProps {
79
active: boolean;
80
composerHeight: number;
81
launchContext: PersistentTerminalLaunchContext | null;
81
- focusRequestId: number;
82
splitShortcutLabel: string | undefined;
83
splitVerticalShortcutLabel: string | undefined;
84
newShortcutLabel: string | undefined;
@@ -93,7 +93,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
93
active,
94
composerHeight,
95
launchContext,
96
- focusRequestId,
96
splitShortcutLabel,
97
splitVerticalShortcutLabel,
98
newShortcutLabel,
@@ -174,7 +173,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
173
}
174
reconcileTerminalIds(threadRef, serverOrderedTerminalIds);
175
}, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]);
177
- const [localFocusRequestId, setLocalFocusRequestId] = useState(0);
176
const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;
177
const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath;
178
const cwd =
@@ -192,13 +190,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
190
})
191
: {};
192
195
- const bumpFocusRequestId = () => {
196
- if (!visible) {
197
- return;
198
- }
199
- setLocalFocusRequestId((value) => value + 1);
200
- };
201
-
193
const setTerminalHeight = (height: number) => {
194
storeSetTerminalHeight(threadRef, height);
195
};
@@ -210,7 +201,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
201
location: { cwd, worktreePath: effectiveWorktreePath },
202
});
203
if (!launched) return;
213
- bumpFocusRequestId();
204
+ if (visible) focusTerminal(threadRef, launched.terminalId);
205
void launched.result;
206
};
207
const splitTerminal = useStableCallback(() =>
@@ -225,14 +216,14 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
216
217
const activateTerminal = (terminalId: string) => {
218
storeSetActiveTerminal(threadRef, terminalId);
228
- bumpFocusRequestId();
219
+ if (visible) focusTerminal(threadRef, terminalId);
220
};
221
222
const closeTerminal = useStableCallback((terminalId: string) => {
223
if (!terminalActions.canWrite()) return;
224
terminalActions.closeTerminalSession(terminalId);
225
storeCloseTerminal(threadRef, terminalId);
235
- bumpFocusRequestId();
226
+ if (visible) focusActiveDrawerTerminal(threadRef);
227
});
228
229
const handleAddTerminalContext = (selection: TerminalContextSelection) => {
@@ -271,7 +262,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm
262
activeTerminalId={terminalUiState.activeTerminalId}
263
terminalGroups={terminalUiState.terminalGroups}
264
activeTerminalGroupId={terminalUiState.activeTerminalGroupId}
274
- focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}
265
onSplitTerminal={splitTerminal}
266
onSplitTerminalVertical={splitTerminalVertical}
267
onNewTerminal={createNewTerminal}
@@ -297,7 +287,6 @@ export interface PersistentThreadTerminalPanelProps {
287
threadRef: ScopedThreadRef;
288
surface: Extract<RightPanelSurface, { kind: "terminal" }>;
289
launchContext: PersistentTerminalLaunchContext | null;
300
- focusRequestId: number;
290
keybindings: ResolvedKeybindingsConfig;
291
onAddTerminalContext: (selection: TerminalContextSelection) => void;
292
onSplitTerminal: () => void;
@@ -316,7 +305,6 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
305
threadRef,
306
surface,
307
launchContext,
319
- focusRequestId,
308
keybindings,
309
onAddTerminalContext,
310
onSplitTerminal,
@@ -408,7 +396,6 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi
396
},
397
]}
398
activeTerminalGroupId={surface.id}
411
- focusRequestId={focusRequestId}
399
onSplitTerminal={onSplitTerminal}
400
onSplitTerminalVertical={onSplitTerminalVertical}
401
onNewTerminal={onNewTerminal}
apps/web/src/components/ThreadTerminalDrawer.tsx
+44
-20
@@ -89,6 +89,12 @@ import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";
89
import { useAtomCommand } from "../state/use-atom-command";
90
import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
91
import { observeResize } from "../lib/observeResize";
92
+import {
93
+ consumePendingTerminalFocus,
94
+ focusTerminal,
95
+ focusTerminalViewport,
96
+ registerTerminalFocusTarget,
97
+} from "../lib/terminalFocus";
98
import {
99
resolveTerminalFontPreference,
100
resolveTerminalFontSizePreference,
@@ -420,8 +426,8 @@ interface TerminalViewportProps {
426
providerInstanceId?: ProviderInstanceId;
427
onSessionExited: () => void;
428
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;
431
visible: boolean;
432
resizeEpoch: number;
433
drawerHeight: number;
@@ -458,14 +464,14 @@ function TerminalSessionViewport({
464
providerInstanceId,
465
onSessionExited,
466
onAddTerminalContext,
461
- focusRequestId,
462
- autoFocus,
467
+ autoFocus = false,
468
visible,
469
resizeEpoch,
470
drawerHeight,
471
keybindings,
472
}: TerminalViewportProps) {
473
const containerRef = useRef<HTMLDivElement>(null);
474
+ const autoFocusedRef = useRef(false);
475
const terminalRef = useRef<GhosttyTerminalSurface | null>(null);
476
const visibleRef = useRef(visible);
477
const environmentId = threadRef.environmentId;
@@ -591,7 +597,9 @@ function TerminalSessionViewport({
597
598
useLayoutEffect(() => {
599
if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal;
594
- }, [canOperateTerminal]);
600
+ if (canOperateTerminal && visibleRef.current)
601
+ consumePendingTerminalFocus(threadRef, terminalId);
602
+ }, [canOperateTerminal, terminalId, threadRef]);
603
604
// Links re-read the grant on activation; only the hovered link's styling needs a nudge.
605
const linkActivationScopeRef = useRef(canOpenHostEditor);
@@ -611,7 +619,9 @@ function TerminalSessionViewport({
619
useLayoutEffect(() => {
620
visibleRef.current = visible;
621
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]);
625
626
useEffect(() => {
627
const current = terminalFontRef.current;
@@ -1093,12 +1103,6 @@ function TerminalSessionViewport({
1103
previousSessionRef.current = current;
1104
}, [terminalOutput, terminalError, terminalStatus, terminalVersion]);
1105
1096
- const focusRequest = autoFocus && canOperateTerminal && visible ? focusRequestId : null;
1097
- useEffect(() => {
1098
- if (focusRequest === null) return;
1099
- (terminalRef.current ?? containerRef.current)?.focus();
1100
- }, [focusRequest]);
1101
-
1106
// A hidden surface skips fitting, and showing it again fits through setVisible.
1107
const layoutRevision = visible ? `${drawerHeight}:${resizeEpoch}` : null;
1108
useEffect(() => {
@@ -1117,9 +1121,36 @@ function TerminalSessionViewport({
1121
window.cancelAnimationFrame(frame);
1122
};
1123
}, [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
+ };
1151
return (
1152
<div
1122
- ref={containerRef}
1153
+ ref={attachContainer}
1154
tabIndex={-1}
1155
className="relative h-full w-full overflow-hidden bg-(--terminal-background)"
1156
/>
@@ -1141,7 +1172,6 @@ interface ThreadTerminalDrawerProps {
1172
activeTerminalId: string;
1173
terminalGroups: ThreadTerminalGroup[];
1174
activeTerminalGroupId: string;
1144
- focusRequestId: number;
1175
onSplitTerminal: () => void;
1176
onSplitTerminalVertical: () => void;
1177
onNewTerminal: () => void;
@@ -1214,7 +1244,6 @@ function TerminalSplitPanes({
1244
threadRef,
1245
threadId,
1246
onAddTerminalContext,
1217
- focusRequestId,
1247
visible,
1248
resizeEpoch,
1249
drawerHeight,
@@ -1231,7 +1260,6 @@ function TerminalSplitPanes({
1260
threadRef: ScopedThreadRef;
1261
threadId: ThreadId;
1262
onAddTerminalContext: (selection: TerminalContextSelection) => void;
1234
- focusRequestId: number;
1263
visible: boolean;
1264
resizeEpoch: number;
1265
drawerHeight: number;
@@ -1282,8 +1310,6 @@ function TerminalSplitPanes({
1310
: {})}
1311
onSessionExited={() => onCloseTerminal(terminalId)}
1312
onAddTerminalContext={onAddTerminalContext}
1285
- focusRequestId={focusRequestId}
1286
- autoFocus={terminalId === activeTerminalId}
1313
visible={visible}
1314
resizeEpoch={resizeEpoch}
1315
drawerHeight={drawerHeight}
@@ -1408,7 +1434,6 @@ export default function ThreadTerminalDrawer({
1434
activeTerminalId,
1435
terminalGroups,
1436
activeTerminalGroupId,
1411
- focusRequestId,
1437
onSplitTerminal,
1438
onSplitTerminalVertical,
1439
onNewTerminal,
@@ -1881,7 +1906,6 @@ export default function ThreadTerminalDrawer({
1906
threadRef={threadRef}
1907
threadId={threadId}
1908
onAddTerminalContext={onAddTerminalContext}
1884
- focusRequestId={focusRequestId}
1909
visible={visible}
1910
resizeEpoch={resizeEpoch}
1911
drawerHeight={drawerHeight}
apps/web/src/components/chat/ChatTerminalDrawers.tsx
-2
@@ -25,7 +25,6 @@ interface ChatTerminalDrawersProps {
25
readonly activeTerminalOpen: boolean;
26
readonly composerHeight: number;
27
readonly launchContext: PersistentTerminalLaunchContext | null;
28
- readonly focusRequestId: number;
28
readonly splitShortcutLabel: string | undefined;
29
readonly splitVerticalShortcutLabel: string | undefined;
30
readonly newShortcutLabel: string | undefined;
@@ -97,7 +96,6 @@ export function ChatTerminalDrawers(props: ChatTerminalDrawersProps) {
96
active={mountedThreadKey === activeThreadKey}
97
composerHeight={mountedThreadKey === activeThreadKey ? props.composerHeight : 0}
98
launchContext={mountedThreadKey === activeThreadKey ? props.launchContext : null}
100
- focusRequestId={mountedThreadKey === activeThreadKey ? props.focusRequestId : 0}
99
splitShortcutLabel={props.splitShortcutLabel}
100
splitVerticalShortcutLabel={props.splitVerticalShortcutLabel}
101
newShortcutLabel={props.newShortcutLabel}
apps/web/src/components/chat/useChatTerminalActions.ts
+18
-10
@@ -31,6 +31,11 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
31
import { confirmTerminalClose } from "../../lib/terminalCloseConfirm";
32
import { findReusableProjectScriptTerminal } from "../../lib/projectScriptTerminal";
33
import { type TerminalContextSelection } from "../../lib/terminalContext";
34
+import {
35
+ focusActiveDrawerTerminal,
36
+ focusActivePanelTerminal,
37
+ focusTerminal,
38
+} from "../../lib/terminalFocus";
39
import { useTerminalUiStateStore } from "../../terminalUiStateStore";
40
import {
41
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
@@ -66,7 +71,6 @@ interface ChatTerminalActionsInput {
71
readonly panelTerminalIds: ReadonlySet<string>;
72
readonly canReuseTerminal: boolean;
73
readonly gitCwd: string | null;
69
- readonly setTerminalFocusRequestId: Dispatch<SetStateAction<number>>;
74
readonly setTerminalUiLaunchContext: Dispatch<SetStateAction<TerminalLaunchContext | null>>;
75
readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
76
}
@@ -91,7 +95,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
95
panelTerminalIds,
96
canReuseTerminal,
97
gitCwd,
94
- setTerminalFocusRequestId,
98
setTerminalUiLaunchContext,
99
setThreadError,
100
} = input;
@@ -130,6 +133,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
133
const setTerminalOpen = (open: boolean) => {
134
if (!activeThreadRef) return;
135
storeSetTerminalOpen(activeThreadRef, open);
136
+ focusActiveDrawerTerminal(activeThreadRef);
137
};
138
const setTerminalOpenStable = useStableCallback(setTerminalOpen);
139
const toggleTerminalVisibility = () => {
@@ -149,11 +153,13 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
153
activeServerOrderedTerminalIds.find((id) => !panelTerminalIds.has(id));
154
if (existingTerminalId !== undefined) {
155
storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });
156
+ focusActiveDrawerTerminal(activeThreadRef);
157
return;
158
}
159
void terminalActions.launchTerminal({
160
place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),
161
})?.result;
162
+ focusActiveDrawerTerminal(activeThreadRef);
163
return;
164
}
165
setTerminalOpen(nextOpen);
@@ -168,7 +174,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
174
: storeSplitTerminal(activeThreadRef, terminalId),
175
});
176
if (!launched) return;
171
- setTerminalFocusRequestId((value) => value + 1);
177
+ focusTerminal(activeThreadRef, launched.terminalId);
178
void launched.result;
179
};
180
const splitTerminalStable = useStableCallback(splitTerminal);
@@ -178,7 +184,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
184
place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId),
185
});
186
if (!launched) return;
181
- setTerminalFocusRequestId((value) => value + 1);
187
+ focusTerminal(activeThreadRef, launched.terminalId);
188
void launched.result;
189
};
190
const createNewTerminalStable = useStableCallback(createNewTerminal);
@@ -186,7 +192,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
192
if (!hasTerminalWriteAccess() || !activeThreadRef) return;
193
terminalActions.closeTerminalSession(terminalId);
194
storeCloseTerminal(activeThreadRef, terminalId);
189
- setTerminalFocusRequestId((value) => value + 1);
195
+ focusActiveDrawerTerminal(activeThreadRef);
196
};
197
const runProjectScript = async (
198
script: ProjectScript,
@@ -232,7 +238,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
238
if (!activeThreadRef) {
239
return;
240
}
235
- setTerminalFocusRequestId((value) => value + 1);
241
242
const launched = terminalActions.launchTerminal({
243
// The drawer opens with the target already placed: opening it empty would claim
@@ -249,6 +254,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
254
});
255
if (!launched) return;
256
const targetTerminalId = launched.terminalId;
257
+ focusTerminal(activeThreadRef, targetTerminalId);
258
const openResult = await launched.result;
259
if (openResult._tag === "Failure") {
260
if (!isAtomCommandInterrupted(openResult)) {
@@ -318,7 +324,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
324
useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId),
325
});
326
if (!launched) return;
321
- setTerminalFocusRequestId((value) => value + 1);
327
+ focusTerminal(activeThreadRef, launched.terminalId);
328
void launched.result;
329
};
330
const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);
@@ -338,7 +344,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
344
.splitTerminal(activeThreadRef, surfaceId, terminalId, direction),
345
});
346
if (!launched) return;
341
- setTerminalFocusRequestId((value) => value + 1);
347
+ focusTerminal(activeThreadRef, launched.terminalId);
348
void launched.result;
349
};
350
const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);
@@ -351,7 +357,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
357
useRightPanelStore
358
.getState()
359
.activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
354
- setTerminalFocusRequestId((value) => value + 1);
360
+ focusTerminal(activeThreadRef, terminalId);
361
};
362
const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);
363
const closePanelTerminal = (terminalId: string) => {
@@ -366,7 +372,9 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {
372
useRightPanelStore
373
.getState()
374
.closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);
369
- setTerminalFocusRequestId((value) => value + 1);
375
+ // Closing a surface's last terminal falls back to a neighbouring surface,
376
+ // which can be another terminal surface.
377
+ focusActivePanelTerminal(activeThreadRef);
378
};
379
const closePanelTerminalStable = useStableCallback(closePanelTerminal);
380
const requestCloseTerminal = (terminalId: string) => {
apps/web/src/components/chat/useRightPanelActions.ts
+4
-5
@@ -1,5 +1,4 @@
1
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
2
-import type { Dispatch } from "react";
2
import type { ThreadPreviewState } from "../../previewStateStore";
3
import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
4
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
@@ -7,7 +6,7 @@ import { resolveExplicitDiffOpenOnActivate } from "../ChatView.logic";
6
import { useStableCallback } from "../../hooks/useStableCallback";
7
import { type ScopedThreadRef, type RunId } from "@t3tools/contracts";
8
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
10
-import { type SetStateAction, useEffect } from "react";
9
+import { useEffect } from "react";
10
import {
11
isAtomCommandInterrupted,
12
squashAtomCommandFailure,
@@ -22,6 +21,7 @@ import {
21
import { setActivePreviewTab } from "../../previewStateStore";
22
import { BrowserSettingsReadError } from "../../browser/openFileInPreview";
23
import { addBrowserSurface } from "../preview/addBrowserSurface";
24
+import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus";
25
import { subscribePreviewAction } from "../preview/previewActionBus";
26
import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore";
27
import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic";
@@ -53,7 +53,6 @@ interface RightPanelActionsInput {
53
readonly gitCwd: string | null;
54
readonly activeProjectCwd: string | null;
55
readonly explicitDiffOpenRef: { current: ScopedThreadRef | null };
56
- readonly setTerminalFocusRequestId: Dispatch<SetStateAction<number>>;
56
readonly onDiffPanelOpen: (() => void) | undefined;
57
readonly closeRightPanelSurface: (surface: RightPanelSurface) => void;
58
}
@@ -86,7 +85,6 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
85
gitCwd,
86
activeProjectCwd,
87
explicitDiffOpenRef,
89
- setTerminalFocusRequestId,
88
onDiffPanelOpen,
89
} = input;
90
@@ -202,7 +200,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
200
setActivePreviewTab(activeThreadRef, surface.resourceId);
201
}
202
if (surface.kind === "terminal") {
205
- setTerminalFocusRequestId((value) => value + 1);
203
+ focusTerminal(activeThreadRef, surface.activeTerminalId);
204
}
205
if (surface.kind === "diff" && !diffOpen) {
206
onDiffPanelOpen?.();
@@ -216,6 +214,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {
214
return;
215
}
216
useRightPanelStore.getState().toggleVisibility(activeThreadRef);
217
+ focusActivePanelTerminal(activeThreadRef);
218
};
219
const toggleRightPanelStable = useStableCallback(toggleRightPanel);
220
const toggleThreadPanel = () => {
apps/web/src/components/chat/useWorktreeSetup.ts
+2
@@ -15,6 +15,7 @@ import { useAtomCommand } from "../../state/use-atom-command";
15
import { vcsEnvironment } from "../../state/vcs";
16
import { useTerminalUiStateStore } from "../../terminalUiStateStore";
17
import type { Thread } from "../../types";
18
+import { focusTerminal } from "../../lib/terminalFocus";
19
import { resolveVisibleWorktreeSetup, resolveWorktreeSetupProgress } from "../ChatView.logic";
20
import { worktreeSetupAgentStarted } from "./MessagesTimeline.logic";
21
@@ -152,6 +153,7 @@ export function useWorktreeSetup(input: {
153
const openSetupTerminal = setupThreadRef
154
? (terminalId: string) => {
155
storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });
156
+ focusTerminal(setupThreadRef, terminalId);
157
}
158
: null;
159
apps/web/src/components/device/DevicePanel.browser.test.tsx
+6
-1
@@ -76,8 +76,13 @@ vi.mock("~/state/use-atom-command", () => ({
76
vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" }));
77
vi.mock("~/rightPanelStore", () => ({
78
useRightPanelStore: {
79
- getState: () => ({ openDevice: mocks.openDevice, closeSurface: mocks.closeSurface }),
79
+ getState: () => ({
80
+ byThreadKey: {},
81
+ openDevice: mocks.openDevice,
82
+ closeSurface: mocks.closeSurface,
83
+ }),
84
},
85
+ selectThreadRightPanelState: () => ({ isOpen: false, activeSurfaceId: null, surfaces: [] }),
86
}));
87
vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));
88
vi.mock("~/components/device/DeviceWorkspace", () => ({
apps/web/src/components/device/DevicePanel.tsx
+15
-3
@@ -9,13 +9,18 @@ import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react";
9
import { type ReactNode, useEffect, useState } from "react";
10
11
import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
12
-import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";
12
+import {
13
+ selectThreadRightPanelState,
14
+ useRightPanelStore,
15
+ type RightPanelSurface,
16
+} from "~/rightPanelStore";
17
import { Button } from "~/components/ui/button";
18
import { DiscoveryList } from "~/components/ui/discovery-list";
19
import { Dialog } from "~/components/ui/dialog";
20
import { WizardPopup } from "~/components/ui/wizard";
21
import { Spinner } from "~/components/ui/spinner";
22
import { cn } from "~/lib/utils";
23
+import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";
24
import { deviceEnvironment, useDeviceState } from "~/state/device";
25
import { formatEnvironmentQueryError } from "~/state/query";
26
import { useAtomCommand } from "~/state/use-atom-command";
@@ -126,9 +131,16 @@ export function DevicePanel(props: {
131
useRightPanelStore.getState().close(props.threadRef);
132
};
133
134
+ const closeSurface = () => {
135
+ const store = useRightPanelStore.getState();
136
+ const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef);
137
+ store.closeSurface(props.threadRef, props.surface.id);
138
+ focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId);
139
+ };
140
+
141
const closeActive = (powerOff: boolean) => {
142
if (!powerOff) {
131
- useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
143
+ closeSurface();
144
return;
145
}
146
if (!activeSession) return;
@@ -143,7 +155,7 @@ export function DevicePanel(props: {
155
},
156
}).then((result) => {
157
if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));
146
- else useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);
158
+ else closeSurface();
159
});
160
};
161
apps/web/src/components/onboarding/WelcomeWizard.tsx
-1
@@ -1155,7 +1155,6 @@ function AgentInstallTerminal({
1155
providerInstanceId={providerInstanceId}
1156
advancedTypography={advancedTypography}
1157
onSessionExited={onClose}
1158
- focusRequestId={1}
1158
autoFocus
1159
visible
1160
resizeEpoch={0}
apps/web/src/hooks/useRightPanelSurfaceClose.ts
+2
@@ -8,6 +8,7 @@ import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.
8
import { closePreviewSession } from "../components/preview/closePreviewSession";
9
import { useThreadTerminalActions } from "../components/terminal/useThreadTerminalActions";
10
import { confirmTerminalClose } from "../lib/terminalCloseConfirm";
11
+import { focusPanelTerminalAfterClose } from "../lib/terminalFocus";
12
import { readLocalApi } from "../localApi";
13
import { setActivePreviewTab, useThreadPreviewState } from "../previewStateStore";
14
import {
@@ -97,6 +98,7 @@ export function useRightPanelSurfaceClose(input: {
98
if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {
99
setActivePreviewTab(threadRef, nextActiveSurface.resourceId);
100
}
101
+ focusPanelTerminalAfterClose(threadRef, activeId);
102
};
103
const labelFor = (terminalId: string) =>
104
terminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);
apps/web/src/lib/revealThreadTerminal.ts
+3
@@ -2,6 +2,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts";
2
3
import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
4
import { useTerminalUiStateStore } from "../terminalUiStateStore";
5
+import { focusTerminalOnNavigation } from "./terminalFocus";
6
7
export function revealThreadTerminal(threadRef: ScopedThreadRef, terminalId: string) {
8
const panels = useRightPanelStore.getState();
@@ -11,10 +12,12 @@ export function revealThreadTerminal(threadRef: ScopedThreadRef, terminalId: str
12
if (surface) {
13
panels.activateTerminal(threadRef, surface.id, terminalId);
14
panels.activateSurface(threadRef, surface.id);
15
+ focusTerminalOnNavigation(threadRef, terminalId);
16
return;
17
}
18
useTerminalUiStateStore.getState().ensureTerminal(threadRef, terminalId, {
19
open: true,
20
active: true,
21
});
22
+ focusTerminalOnNavigation(threadRef, terminalId);
23
}
apps/web/src/lib/terminalFocus.browser.test.ts
new
+59
@@ -0,0 +1,59 @@
1
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3
+import { describe, expect, it } from "vite-plus/test";
4
+
5
+import {
6
+ consumePendingTerminalFocus,
7
+ focusTerminal,
8
+ focusTerminalViewport,
9
+ registerTerminalFocusTarget,
10
+} from "./terminalFocus";
11
+
12
+// The drawer's collapsed shape: a 0fr grid row that clips the viewport, which
13
+// stays focusable, around a surface whose input refuses focus while hidden.
14
+function mountClippedViewport() {
15
+ const drawer = document.createElement("div");
16
+ drawer.style.cssText = "display:grid;grid-template-rows:0fr;overflow:clip";
17
+ const clip = document.createElement("div");
18
+ clip.style.cssText = "min-height:0;overflow:clip";
19
+ const mount = document.createElement("div");
20
+ mount.tabIndex = -1;
21
+ const input = document.createElement("textarea");
22
+ mount.append(input);
23
+ clip.append(mount);
24
+ drawer.append(clip);
25
+ document.body.append(drawer);
26
+ const state = { visible: false };
27
+ const surface = {
28
+ focus() {
29
+ if (state.visible) input.focus({ preventScroll: true });
30
+ },
31
+ };
32
+ const focus = () =>
33
+ focusTerminalViewport({ mount, surface, canOperate: true, visible: state.visible });
34
+ return {
35
+ input,
36
+ state,
37
+ focus,
38
+ [Symbol.dispose]: () => drawer.remove(),
39
+ };
40
+}
41
+
42
+describe("focusTerminalViewport", () => {
43
+ it("keeps a request made while the drawer is hidden until it shows", () => {
44
+ const ref = scopeThreadRef(EnvironmentId.make("env"), ThreadId.make("hidden-drawer"));
45
+ using viewport = mountClippedViewport();
46
+ const unregister = registerTerminalFocusTarget({
47
+ threadRef: ref,
48
+ terminalId: "a",
49
+ focus: viewport.focus,
50
+ });
51
+ using _unregister = { [Symbol.dispose]: unregister };
52
+
53
+ focusTerminal(ref, "a");
54
+ viewport.state.visible = true;
55
+ consumePendingTerminalFocus(ref, "a");
56
+
57
+ expect(document.activeElement).toBe(viewport.input);
58
+ });
59
+});
apps/web/src/lib/terminalFocus.test.ts
new
+326
@@ -0,0 +1,326 @@
1
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2
+import { EnvironmentId, ThreadId } from "@t3tools/contracts";
3
+import { describe, expect, it, vi } from "vite-plus/test";
4
+
5
+import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
6
+import { useTerminalUiStateStore } from "../terminalUiStateStore";
7
+import {
8
+ consumePendingTerminalFocus,
9
+ focusActiveDrawerTerminal,
10
+ focusActivePanelTerminal,
11
+ focusPanelTerminalAfterClose,
12
+ focusTerminal,
13
+ focusTerminalOnNavigation,
14
+ focusTerminalOnThreadEnter,
15
+ registerTerminalFocusTarget,
16
+} from "./terminalFocus";
17
+
18
+const threadRef = (threadId: string) =>
19
+ scopeThreadRef(EnvironmentId.make("env"), ThreadId.make(threadId));
20
+
21
+describe("focusTerminal", () => {
22
+ it("focuses a mounted target right away", () => {
23
+ const ref = threadRef("mounted");
24
+ const focus = vi.fn(() => true);
25
+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });
26
+
27
+ focusTerminal(ref, "a");
28
+
29
+ expect(focus).toHaveBeenCalledTimes(1);
30
+ unregister();
31
+ });
32
+
33
+ it("waits for the requested terminal to mount, then consumes the request", () => {
34
+ const ref = threadRef("pending");
35
+ focusTerminal(ref, "b");
36
+
37
+ const other = vi.fn(() => true);
38
+ const unregisterOther = registerTerminalFocusTarget({
39
+ threadRef: ref,
40
+ terminalId: "a",
41
+ focus: other,
42
+ });
43
+ const target = vi.fn(() => true);
44
+ const unregisterTarget = registerTerminalFocusTarget({
45
+ threadRef: ref,
46
+ terminalId: "b",
47
+ focus: target,
48
+ });
49
+ unregisterTarget();
50
+ const remount = vi.fn(() => true);
51
+ const unregisterRemount = registerTerminalFocusTarget({
52
+ threadRef: ref,
53
+ terminalId: "b",
54
+ focus: remount,
55
+ });
56
+
57
+ expect(other).not.toHaveBeenCalled();
58
+ expect(target).toHaveBeenCalledTimes(1);
59
+ expect(remount).not.toHaveBeenCalled();
60
+ unregisterOther();
61
+ unregisterRemount();
62
+ });
63
+
64
+ it("keeps only the newest request for a thread", () => {
65
+ const ref = threadRef("newest");
66
+ focusTerminal(ref, "a");
67
+ focusTerminal(ref, "b");
68
+
69
+ const first = vi.fn(() => true);
70
+ const unregisterFirst = registerTerminalFocusTarget({
71
+ threadRef: ref,
72
+ terminalId: "a",
73
+ focus: first,
74
+ });
75
+ const second = vi.fn(() => true);
76
+ const unregisterSecond = registerTerminalFocusTarget({
77
+ threadRef: ref,
78
+ terminalId: "b",
79
+ focus: second,
80
+ });
81
+
82
+ expect(first).not.toHaveBeenCalled();
83
+ expect(second).toHaveBeenCalledTimes(1);
84
+ unregisterFirst();
85
+ unregisterSecond();
86
+ });
87
+
88
+ it("keeps the request when a mounted target cannot take focus", () => {
89
+ const ref = threadRef("hidden");
90
+ const hidden = vi.fn(() => false);
91
+ const unregisterHidden = registerTerminalFocusTarget({
92
+ threadRef: ref,
93
+ terminalId: "a",
94
+ focus: hidden,
95
+ });
96
+
97
+ focusTerminal(ref, "a");
98
+ unregisterHidden();
99
+ const shown = vi.fn(() => true);
100
+ const unregisterShown = registerTerminalFocusTarget({
101
+ threadRef: ref,
102
+ terminalId: "a",
103
+ focus: shown,
104
+ });
105
+
106
+ expect(hidden).toHaveBeenCalledTimes(1);
107
+ expect(shown).toHaveBeenCalledTimes(1);
108
+ unregisterShown();
109
+ });
110
+
111
+ it("focuses a registered hidden target once it is shown", () => {
112
+ const ref = threadRef("shown-later");
113
+ let canFocus = false;
114
+ const focus = vi.fn(() => canFocus);
115
+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });
116
+
117
+ focusTerminal(ref, "a");
118
+ canFocus = true;
119
+ consumePendingTerminalFocus(ref, "a");
120
+ consumePendingTerminalFocus(ref, "a");
121
+
122
+ expect(focus).toHaveBeenCalledTimes(2);
123
+ unregister();
124
+ });
125
+
126
+ it("drops a parked request once a newer one targets another thread", () => {
127
+ const parked = threadRef("parked");
128
+ const hidden = vi.fn(() => false);
129
+ const unregisterHidden = registerTerminalFocusTarget({
130
+ threadRef: parked,
131
+ terminalId: "a",
132
+ focus: hidden,
133
+ });
134
+ focusTerminal(parked, "a");
135
+
136
+ const other = threadRef("other");
137
+ const unregisterOther = registerTerminalFocusTarget({
138
+ threadRef: other,
139
+ terminalId: "b",
140
+ focus: () => true,
141
+ });
142
+ focusTerminal(other, "b");
143
+ unregisterHidden();
144
+ const remount = vi.fn(() => true);
145
+ const unregisterRemount = registerTerminalFocusTarget({
146
+ threadRef: parked,
147
+ terminalId: "a",
148
+ focus: remount,
149
+ });
150
+
151
+ expect(remount).not.toHaveBeenCalled();
152
+ unregisterOther();
153
+ unregisterRemount();
154
+ });
155
+
156
+ it("drops a parked request when the thread's drawer closes", () => {
157
+ const ref = threadRef("closed");
158
+ useTerminalUiStateStore.getState().ensureTerminal(ref, "a", { open: true, active: true });
159
+ focusActiveDrawerTerminal(ref);
160
+ useTerminalUiStateStore.getState().setTerminalOpen(ref, false);
161
+ focusActiveDrawerTerminal(ref);
162
+
163
+ const focus = vi.fn(() => true);
164
+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });
165
+
166
+ expect(focus).not.toHaveBeenCalled();
167
+ unregister();
168
+ });
169
+
170
+ it("entering a thread with its drawer open focuses the active drawer terminal", () => {
171
+ const ref = threadRef("entered");
172
+ useTerminalUiStateStore.getState().ensureTerminal(ref, "a", { open: true, active: true });
173
+ const focus = vi.fn(() => true);
174
+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });
175
+
176
+ const leave = focusTerminalOnThreadEnter(ref);
177
+
178
+ expect(focus).toHaveBeenCalledTimes(1);
179
+ leave();
180
+ unregister();
181
+ });
182
+
183
+ it("entering a thread keeps the request its navigating handler made", () => {
184
+ const ref = threadRef("revealed");
185
+ useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });
186
+ focusTerminalOnNavigation(ref, "panel");
187
+
188
+ // React commit order: the new thread's viewports attach and take the
189
+ // request before ChatView's thread-enter effect runs.
190
+ const drawer = vi.fn(() => true);
191
+ const unregisterDrawer = registerTerminalFocusTarget({
192
+ threadRef: ref,
193
+ terminalId: "drawer",
194
+ focus: drawer,
195
+ });
196
+ const panel = vi.fn(() => true);
197
+ const unregisterPanel = registerTerminalFocusTarget({
198
+ threadRef: ref,
199
+ terminalId: "panel",
200
+ focus: panel,
201
+ });
202
+ const leave = focusTerminalOnThreadEnter(ref);
203
+
204
+ expect(drawer).not.toHaveBeenCalled();
205
+ expect(panel).toHaveBeenCalledTimes(1);
206
+ leave();
207
+ unregisterDrawer();
208
+ unregisterPanel();
209
+ });
210
+
211
+ it("re-entering a thread after in-thread terminal actions focuses the drawer", () => {
212
+ const ref = threadRef("re-entered");
213
+ useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });
214
+ const drawer = vi.fn(() => true);
215
+ const unregisterDrawer = registerTerminalFocusTarget({
216
+ threadRef: ref,
217
+ terminalId: "drawer",
218
+ focus: drawer,
219
+ });
220
+
221
+ const leaveFirst = focusTerminalOnThreadEnter(ref);
222
+ focusTerminal(ref, "drawer");
223
+ focusTerminalOnNavigation(ref, "drawer");
224
+ leaveFirst();
225
+ drawer.mockClear();
226
+ const leaveSecond = focusTerminalOnThreadEnter(ref);
227
+
228
+ expect(drawer).toHaveBeenCalledTimes(1);
229
+ leaveSecond();
230
+ unregisterDrawer();
231
+ });
232
+
233
+ it("a navigating handler's request only outranks the next thread entry", () => {
234
+ const ref = threadRef("revisited");
235
+ useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });
236
+ focusTerminalOnNavigation(ref, "panel");
237
+ focusTerminalOnThreadEnter(threadRef("elsewhere"))();
238
+
239
+ const drawer = vi.fn(() => true);
240
+ const unregisterDrawer = registerTerminalFocusTarget({
241
+ threadRef: ref,
242
+ terminalId: "drawer",
243
+ focus: drawer,
244
+ });
245
+ const leave = focusTerminalOnThreadEnter(ref);
246
+
247
+ expect(drawer).toHaveBeenCalledTimes(1);
248
+ leave();
249
+ unregisterDrawer();
250
+ });
251
+
252
+ it("focuses the panel terminal a closed surface falls back to", () => {
253
+ const ref = threadRef("panel-fallback");
254
+ const panel = useRightPanelStore.getState();
255
+ panel.openTerminal(ref, "a");
256
+ panel.open(ref, "diff");
257
+ const { activeSurfaceId: diffSurfaceId } = selectThreadRightPanelState(
258
+ useRightPanelStore.getState().byThreadKey,
259
+ ref,
260
+ );
261
+ const focus = vi.fn(() => true);
262
+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });
263
+ expect(diffSurfaceId).not.toBeNull();
264
+
265
+ useRightPanelStore.getState().closeSurface(ref, diffSurfaceId!);
266
+ focusActivePanelTerminal(ref);
267
+
268
+ expect(focus).toHaveBeenCalledTimes(1);
269
+ unregister();
270
+ });
271
+
272
+ it("closing a surface's last terminal focuses the terminal surface it falls back to", () => {
273
+ const ref = threadRef("panel-terminal-fallback");
274
+ const panel = useRightPanelStore.getState();
275
+ panel.openTerminal(ref, "b");
276
+ panel.openTerminal(ref, "a");
277
+ const surfaceA = selectThreadRightPanelState(
278
+ useRightPanelStore.getState().byThreadKey,
279
+ ref,
280
+ ).activeSurfaceId!;
281
+ const focusB = vi.fn(() => true);
282
+ const unregister = registerTerminalFocusTarget({
283
+ threadRef: ref,
284
+ terminalId: "b",
285
+ focus: focusB,
286
+ });
287
+
288
+ panel.closeTerminal(ref, surfaceA, "a");
289
+ focusActivePanelTerminal(ref);
290
+
291
+ expect(focusB).toHaveBeenCalledTimes(1);
292
+ unregister();
293
+ });
294
+
295
+ it("refocuses the panel terminal only when closing changed the active surface", () => {
296
+ const ref = threadRef("panel-after-close");
297
+ const panel = useRightPanelStore.getState();
298
+ panel.openTerminal(ref, "a");
299
+ const terminalSurfaceId = selectThreadRightPanelState(
300
+ useRightPanelStore.getState().byThreadKey,
301
+ ref,
302
+ ).activeSurfaceId!;
303
+ panel.open(ref, "diff");
304
+ const diffSurfaceId = selectThreadRightPanelState(
305
+ useRightPanelStore.getState().byThreadKey,
306
+ ref,
307
+ ).activeSurfaceId!;
308
+ const focus = vi.fn(() => true);
309
+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });
310
+
311
+ panel.activateSurface(ref, terminalSurfaceId);
312
+ panel.closeSurface(ref, diffSurfaceId);
313
+ focusPanelTerminalAfterClose(ref, terminalSurfaceId);
314
+ expect(focus).not.toHaveBeenCalled();
315
+
316
+ panel.open(ref, "diff");
317
+ const reopenedDiffId = selectThreadRightPanelState(
318
+ useRightPanelStore.getState().byThreadKey,
319
+ ref,
320
+ ).activeSurfaceId!;
321
+ panel.closeSurface(ref, reopenedDiffId);
322
+ focusPanelTerminalAfterClose(ref, reopenedDiffId);
323
+ expect(focus).toHaveBeenCalledTimes(1);
324
+ unregister();
325
+ });
326
+});
apps/web/src/lib/terminalFocus.ts
+168
@@ -1,3 +1,9 @@
1
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
2
+import type { ScopedThreadRef } from "@t3tools/contracts";
3
+
4
+import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";
5
+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
6
+
7
export type TerminalFocusOwner = "drawer" | "right-panel";
8
9
export function getTerminalFocusOwner(): TerminalFocusOwner | null {
@@ -12,3 +18,165 @@ export function getTerminalFocusOwner(): TerminalFocusOwner | null {
18
export function isTerminalFocused(): boolean {
19
return getTerminalFocusOwner() !== null;
20
}
21
+
22
+interface TerminalFocusTarget {
23
+ readonly threadRef: ScopedThreadRef;
24
+ readonly terminalId: string;
25
+ /** Returns false when the target cannot take focus yet (hidden, or no operate grant). */
26
+ readonly focus: () => boolean;
27
+}
28
+
29
+const focusTargets = new Set<TerminalFocusTarget>();
30
+// One request at a time: the newest terminal the user asked for wins, so an
31
+// older request never fires later and steals focus.
32
+let pendingFocus: { readonly threadKey: string; readonly terminalId: string } | null = null;
33
+// The thread ChatView currently shows, and the thread a navigating handler
34
+// asked to focus a terminal in. The mark outlives `pendingFocus`: the new
35
+// thread's viewports mount and consume the handler's request in the commit's
36
+// layout phase, before ChatView's thread-enter effect runs.
37
+let enteredThreadKey: string | null = null;
38
+let navigationRequestThreadKey: string | null = null;
39
+
40
+function isPending(threadKey: string, terminalId: string): boolean {
41
+ return pendingFocus?.threadKey === threadKey && pendingFocus.terminalId === terminalId;
42
+}
43
+
44
+function focusMountedTarget(threadKey: string, terminalId: string): boolean {
45
+ for (const target of focusTargets) {
46
+ if (
47
+ target.terminalId === terminalId &&
48
+ scopedThreadKey(target.threadRef) === threadKey &&
49
+ target.focus()
50
+ ) {
51
+ return true;
52
+ }
53
+ }
54
+ return false;
55
+}
56
+
57
+/**
58
+ * Focuses a thread's terminal when its viewport can take focus, or once it can.
59
+ * Opening, creating or switching to a terminal usually mounts or shows its
60
+ * viewport after the handler returns, so the request waits for the viewport.
61
+ */
62
+export function focusTerminal(threadRef: ScopedThreadRef, terminalId: string): void {
63
+ const threadKey = scopedThreadKey(threadRef);
64
+ pendingFocus = focusMountedTarget(threadKey, terminalId) ? null : { threadKey, terminalId };
65
+}
66
+
67
+/**
68
+ * Focuses the drawer terminal the store now marks active, after an open, close
69
+ * or switch. A thread whose drawer ended up closed drops its waiting request.
70
+ */
71
+export function focusActiveDrawerTerminal(threadRef: ScopedThreadRef): void {
72
+ const { terminalOpen, activeTerminalId } = selectThreadTerminalUiState(
73
+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
74
+ threadRef,
75
+ );
76
+ if (terminalOpen && activeTerminalId) focusTerminal(threadRef, activeTerminalId);
77
+ else cancelTerminalFocus(threadRef);
78
+}
79
+
80
+/** Focuses the active terminal of the right panel when it shows a terminal surface. */
81
+export function focusActivePanelTerminal(threadRef: ScopedThreadRef): void {
82
+ const { isOpen, activeSurfaceId, surfaces } = selectThreadRightPanelState(
83
+ useRightPanelStore.getState().byThreadKey,
84
+ threadRef,
85
+ );
86
+ const surface = isOpen ? surfaces.find((candidate) => candidate.id === activeSurfaceId) : null;
87
+ if (surface?.kind === "terminal") focusTerminal(threadRef, surface.activeTerminalId);
88
+}
89
+
90
+/**
91
+ * After a right panel surface closes, focuses the terminal surface the panel
92
+ * fell back to. A terminal surface that was already active keeps its focus as is.
93
+ */
94
+export function focusPanelTerminalAfterClose(
95
+ threadRef: ScopedThreadRef,
96
+ previousActiveSurfaceId: string | null,
97
+): void {
98
+ const { activeSurfaceId } = selectThreadRightPanelState(
99
+ useRightPanelStore.getState().byThreadKey,
100
+ threadRef,
101
+ );
102
+ if (activeSurfaceId !== previousActiveSurfaceId) focusActivePanelTerminal(threadRef);
103
+}
104
+
105
+/**
106
+ * Focuses a terminal from a handler that may also navigate to its thread (a
107
+ * sidebar terminal reveal). When it does, that thread's entry keeps this request
108
+ * instead of focusing the drawer.
109
+ */
110
+export function focusTerminalOnNavigation(threadRef: ScopedThreadRef, terminalId: string): void {
111
+ const threadKey = scopedThreadKey(threadRef);
112
+ navigationRequestThreadKey = threadKey === enteredThreadKey ? null : threadKey;
113
+ focusTerminal(threadRef, terminalId);
114
+}
115
+
116
+/**
117
+ * Entering a thread with its drawer open focuses the drawer terminal, unless a
118
+ * navigating handler already asked for a terminal there. Returns the leave
119
+ * cleanup for ChatView's effect.
120
+ */
121
+export function focusTerminalOnThreadEnter(threadRef: ScopedThreadRef): () => void {
122
+ const threadKey = scopedThreadKey(threadRef);
123
+ const requestedByHandler = navigationRequestThreadKey === threadKey;
124
+ navigationRequestThreadKey = null;
125
+ enteredThreadKey = threadKey;
126
+ if (!requestedByHandler) {
127
+ const { terminalOpen, activeTerminalId } = selectThreadTerminalUiState(
128
+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,
129
+ threadRef,
130
+ );
131
+ if (terminalOpen && activeTerminalId) focusTerminal(threadRef, activeTerminalId);
132
+ }
133
+ return () => {
134
+ // A handler navigating elsewhere marks its target before this cleanup runs.
135
+ if (enteredThreadKey === threadKey) enteredThreadKey = null;
136
+ };
137
+}
138
+
139
+function cancelTerminalFocus(threadRef: ScopedThreadRef): void {
140
+ if (pendingFocus?.threadKey === scopedThreadKey(threadRef)) pendingFocus = null;
141
+}
142
+
143
+/**
144
+ * Retries a waiting request once a mounted viewport can take it: when it is
145
+ * shown (a viewport kept mounted while hidden has `display: none`) or when the
146
+ * operate grant arrives. Neither ever invents a request.
147
+ */
148
+export function consumePendingTerminalFocus(threadRef: ScopedThreadRef, terminalId: string): void {
149
+ const threadKey = scopedThreadKey(threadRef);
150
+ if (isPending(threadKey, terminalId) && focusMountedTarget(threadKey, terminalId)) {
151
+ pendingFocus = null;
152
+ }
153
+}
154
+
155
+export function registerTerminalFocusTarget(target: TerminalFocusTarget): () => void {
156
+ focusTargets.add(target);
157
+ if (isPending(scopedThreadKey(target.threadRef), target.terminalId) && target.focus()) {
158
+ pendingFocus = null;
159
+ }
160
+ return () => {
161
+ focusTargets.delete(target);
162
+ };
163
+}
164
+
165
+/**
166
+ * A viewport's `focus` for its target. Focus lands on the mount until the
167
+ * surface exists, and the surface takes it over from there.
168
+ */
169
+export function focusTerminalViewport(input: {
170
+ readonly mount: HTMLElement;
171
+ readonly surface: { focus(): void } | null;
172
+ readonly canOperate: boolean;
173
+ readonly visible: boolean;
174
+}): boolean {
175
+ // A hidden drawer is clipped, not display:none: the mount would take focus
176
+ // while the surface refuses it, and the request would be spent on a wrapper
177
+ // that ignores typing.
178
+ if (!input.canOperate || !input.visible) return false;
179
+ input.mount.focus({ preventScroll: true });
180
+ input.surface?.focus();
181
+ return input.mount.contains(document.activeElement);
182
+}