TypeScript
refactor(web): terminal focus requests name the terminal they focus (#25009)
Julius Marminge5fee09a2c109
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex c9b32bffd07..6251e14bbbe 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -195,7 +195,7 @@ import { usePanelAnimationSettings, usePanelPresence } from "../panelAnimations"import { useNewThreadHandler } from "../hooks/useHandleNewThread";import { useOpenPanelPullRequestUrl } from "../hooks/useOpenPanelPullRequestUrl";import { isPreviewFocused } from "../lib/previewFocus";-import { getTerminalFocusOwner } from "../lib/terminalFocus";+import { focusTerminalOnThreadEnter, getTerminalFocusOwner } from "../lib/terminalFocus";import {deriveLogicalProjectKeyFromSettings,selectProjectGroupingSettings,@@ -662,7 +662,6 @@ export default function ChatView(props: ChatViewProps) {const isMobileViewport = useMediaQuery("max-sm");const [workspaceLayoutElement, setWorkspaceLayoutElement] = useState<HTMLDivElement | null>(null);const threadPanelPopoverAnchorRef = useRef<HTMLElement | null>(null);- const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);const [terminalUiLaunchContext, setTerminalUiLaunchContext] =useState<TerminalLaunchContext | null>(null);// 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) {};const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections);const feedbackUploadsInFlightRef = useRef(new Set<string>());- const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});const terminalUiState = useTerminalUiStateStore((state) =>selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),@@ -1862,7 +1860,6 @@ export default function ChatView(props: ChatViewProps) {panelTerminalIds,canReuseTerminal,gitCwd,- setTerminalFocusRequestId,setTerminalUiLaunchContext,setThreadError,});@@ -2409,7 +2406,6 @@ export default function ChatView(props: ChatViewProps) {gitCwd,activeProjectCwd,explicitDiffOpenRef,- setTerminalFocusRequestId,onDiffPanelOpen,closeRightPanelSurface,});@@ -2635,27 +2631,12 @@ export default function ChatView(props: ChatViewProps) {setTerminalUiLaunchContext(null);}+ // Entering a thread with its drawer open focuses the drawer terminal; opening+ // it from a handler requests focus there. A closed drawer leaves focus to the+ // composer effect above.useEffect(() => {- if (!activeThreadKey) return;- const previous = terminalUiOpenByThreadRef.current[activeThreadKey] ?? false;- const current = Boolean(terminalUiState.terminalOpen);-- if (!previous && current) {- terminalUiOpenByThreadRef.current[activeThreadKey] = current;- setTerminalFocusRequestId((value) => value + 1);- return;- } else if (previous && !current) {- terminalUiOpenByThreadRef.current[activeThreadKey] = current;- const frame = window.requestAnimationFrame(() => {- focusComposerStable();- });- return () => {- window.cancelAnimationFrame(frame);- };- }-- terminalUiOpenByThreadRef.current[activeThreadKey] = current;- }, [activeThreadKey, focusComposerStable, terminalUiState.terminalOpen]);+ if (activeThreadRef) return focusTerminalOnThreadEnter(activeThreadRef);+ }, [activeThreadRef]);const getShortcutContext = (eventTarget: EventTarget | null = document.activeElement) => ({terminalFocus: getTerminalFocusOwner() !== null,@@ -3089,7 +3070,6 @@ export default function ChatView(props: ChatViewProps) {onCloseSurface={closeRightPanelSurface}terminal={{launchContext: activeTerminalLaunchContext ?? null,- focusRequestId: terminalFocusRequestId,keybindings,onAddTerminalContext: addTerminalContextToDraftStable,onSplitTerminal: splitPanelTerminalStable,@@ -3860,7 +3840,6 @@ export default function ChatView(props: ChatViewProps) {activeTerminalOpen={Boolean(terminalUiState.terminalOpen)}composerHeight={composerReservedHeight}launchContext={activeTerminalLaunchContext ?? null}- focusRequestId={terminalFocusRequestId}splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}newShortcutLabel={newTerminalShortcutLabel ?? undefined}diff --git a/apps/web/src/components/PersistentThreadTerminals.tsx b/apps/web/src/components/PersistentThreadTerminals.tsxindex 2b2aef90551..dab0f16969a 100644--- a/apps/web/src/components/PersistentThreadTerminals.tsx+++ b/apps/web/src/components/PersistentThreadTerminals.tsx@@ -8,10 +8,11 @@ import {import { scopeProjectRef } from "@t3tools/client-runtime/environment";import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";-import { memo, useEffect, useState } from "react";+import { memo, useEffect } from "react";import { useComposerDraftStore } from "../composerDraftStore";import { useStableCallback } from "../hooks/useStableCallback";import type { TerminalContextSelection } from "../lib/terminalContext";+import { focusActiveDrawerTerminal, focusTerminal } from "../lib/terminalFocus";import { cn } from "~/lib/utils";import {selectThreadRightPanelState,@@ -78,7 +79,6 @@ interface PersistentThreadTerminalDrawerProps {active: boolean;composerHeight: number;launchContext: PersistentTerminalLaunchContext | null;- focusRequestId: number;splitShortcutLabel: string | undefined;splitVerticalShortcutLabel: string | undefined;newShortcutLabel: string | undefined;@@ -93,7 +93,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTermactive,composerHeight,launchContext,- focusRequestId,splitShortcutLabel,splitVerticalShortcutLabel,newShortcutLabel,@@ -174,7 +173,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm}reconcileTerminalIds(threadRef, serverOrderedTerminalIds);}, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]);- const [localFocusRequestId, setLocalFocusRequestId] = useState(0);const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;const effectiveWorktreePath = launchContext !== null ? launchContext.worktreePath : worktreePath;const cwd =@@ -192,13 +190,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerm}): {};- const bumpFocusRequestId = () => {- if (!visible) {- return;- }- setLocalFocusRequestId((value) => value + 1);- };-const setTerminalHeight = (height: number) => {storeSetTerminalHeight(threadRef, height);};@@ -210,7 +201,7 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTermlocation: { cwd, worktreePath: effectiveWorktreePath },});if (!launched) return;- bumpFocusRequestId();+ if (visible) focusTerminal(threadRef, launched.terminalId);void launched.result;};const splitTerminal = useStableCallback(() =>@@ -225,14 +216,14 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTermconst activateTerminal = (terminalId: string) => {storeSetActiveTerminal(threadRef, terminalId);- bumpFocusRequestId();+ if (visible) focusTerminal(threadRef, terminalId);};const closeTerminal = useStableCallback((terminalId: string) => {if (!terminalActions.canWrite()) return;terminalActions.closeTerminalSession(terminalId);storeCloseTerminal(threadRef, terminalId);- bumpFocusRequestId();+ if (visible) focusActiveDrawerTerminal(threadRef);});const handleAddTerminalContext = (selection: TerminalContextSelection) => {@@ -271,7 +262,6 @@ export const PersistentThreadTerminalDrawer = memo(function PersistentThreadTermactiveTerminalId={terminalUiState.activeTerminalId}terminalGroups={terminalUiState.terminalGroups}activeTerminalGroupId={terminalUiState.activeTerminalGroupId}- focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}onSplitTerminal={splitTerminal}onSplitTerminalVertical={splitTerminalVertical}onNewTerminal={createNewTerminal}@@ -297,7 +287,6 @@ export interface PersistentThreadTerminalPanelProps {threadRef: ScopedThreadRef;surface: Extract<RightPanelSurface, { kind: "terminal" }>;launchContext: PersistentTerminalLaunchContext | null;- focusRequestId: number;keybindings: ResolvedKeybindingsConfig;onAddTerminalContext: (selection: TerminalContextSelection) => void;onSplitTerminal: () => void;@@ -316,7 +305,6 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermithreadRef,surface,launchContext,- focusRequestId,keybindings,onAddTerminalContext,onSplitTerminal,@@ -408,7 +396,6 @@ export const PersistentThreadTerminalPanel = memo(function PersistentThreadTermi},]}activeTerminalGroupId={surface.id}- focusRequestId={focusRequestId}onSplitTerminal={onSplitTerminal}onSplitTerminalVertical={onSplitTerminalVertical}onNewTerminal={onNewTerminal}diff --git a/apps/web/src/components/ThreadTerminalDrawer.tsx b/apps/web/src/components/ThreadTerminalDrawer.tsxindex ebc4c525efd..2cb8b6651f1 100644--- a/apps/web/src/components/ThreadTerminalDrawer.tsx+++ b/apps/web/src/components/ThreadTerminalDrawer.tsx@@ -89,6 +89,12 @@ import { openTerminalLinkInPreview } from "./preview/openTerminalLinkInPreview";import { useAtomCommand } from "../state/use-atom-command";import { preventTerminalCloseShortcut } from "../lib/terminalCloseShortcut";import { observeResize } from "../lib/observeResize";+import {+ consumePendingTerminalFocus,+ focusTerminal,+ focusTerminalViewport,+ registerTerminalFocusTarget,+} from "../lib/terminalFocus";import {resolveTerminalFontPreference,resolveTerminalFontSizePreference,@@ -420,8 +426,8 @@ interface TerminalViewportProps {providerInstanceId?: ProviderInstanceId;onSessionExited: () => void;onAddTerminalContext?: (selection: TerminalContextSelection) => void;- focusRequestId: number;- autoFocus: boolean;+ /** Focuses the viewport when it mounts; otherwise focus arrives through `focusTerminal`. */+ autoFocus?: boolean;visible: boolean;resizeEpoch: number;drawerHeight: number;@@ -458,14 +464,14 @@ function TerminalSessionViewport({providerInstanceId,onSessionExited,onAddTerminalContext,- focusRequestId,- autoFocus,+ autoFocus = false,visible,resizeEpoch,drawerHeight,keybindings,}: TerminalViewportProps) {const containerRef = useRef<HTMLDivElement>(null);+ const autoFocusedRef = useRef(false);const terminalRef = useRef<GhosttyTerminalSurface | null>(null);const visibleRef = useRef(visible);const environmentId = threadRef.environmentId;@@ -591,7 +597,9 @@ function TerminalSessionViewport({useLayoutEffect(() => {if (terminalRef.current) terminalRef.current.input.readOnly = !canOperateTerminal;- }, [canOperateTerminal]);+ if (canOperateTerminal && visibleRef.current)+ consumePendingTerminalFocus(threadRef, terminalId);+ }, [canOperateTerminal, terminalId, threadRef]);// Links re-read the grant on activation; only the hovered link's styling needs a nudge.const linkActivationScopeRef = useRef(canOpenHostEditor);@@ -611,7 +619,9 @@ function TerminalSessionViewport({useLayoutEffect(() => {visibleRef.current = visible;terminalRef.current?.setVisible(visible);- }, [visible]);+ // A request made while this viewport was hidden could not focus it.+ if (visible) consumePendingTerminalFocus(threadRef, terminalId);+ }, [terminalId, threadRef, visible]);useEffect(() => {const current = terminalFontRef.current;@@ -1093,12 +1103,6 @@ function TerminalSessionViewport({previousSessionRef.current = current;}, [terminalOutput, terminalError, terminalStatus, terminalVersion]);- const focusRequest = autoFocus && canOperateTerminal && visible ? focusRequestId : null;- useEffect(() => {- if (focusRequest === null) return;- (terminalRef.current ?? containerRef.current)?.focus();- }, [focusRequest]);-// A hidden surface skips fitting, and showing it again fits through setVisible.const layoutRevision = visible ? `${drawerHeight}:${resizeEpoch}` : null;useEffect(() => {@@ -1117,9 +1121,36 @@ function TerminalSessionViewport({window.cancelAnimationFrame(frame);};}, [layoutRevision]);++ const attachContainer = (mount: HTMLDivElement) => {+ containerRef.current = mount;+ const focus = () =>+ focusTerminalViewport({+ mount,+ surface: terminalRef.current,+ canOperate: readEnvironmentScope(environmentId, AuthTerminalOperateScope),+ visible: visibleRef.current,+ });+ // Once per viewport: a re-attached ref (a fresh callback identity) must not+ // pull focus back on every render of a chatty terminal. As a request, it+ // waits for the grant or for the viewport to show when it cannot focus yet.+ if (autoFocus && !autoFocusedRef.current) {+ autoFocusedRef.current = true;+ focusTerminal(threadRef, terminalId);+ }+ const unregister = registerTerminalFocusTarget({+ threadRef,+ terminalId,+ focus,+ });+ return () => {+ unregister();+ containerRef.current = null;+ };+ };return (<div- ref={containerRef}+ ref={attachContainer}tabIndex={-1}className="relative h-full w-full overflow-hidden bg-(--terminal-background)"/>@@ -1141,7 +1172,6 @@ interface ThreadTerminalDrawerProps {activeTerminalId: string;terminalGroups: ThreadTerminalGroup[];activeTerminalGroupId: string;- focusRequestId: number;onSplitTerminal: () => void;onSplitTerminalVertical: () => void;onNewTerminal: () => void;@@ -1214,7 +1244,6 @@ function TerminalSplitPanes({threadRef,threadId,onAddTerminalContext,- focusRequestId,visible,resizeEpoch,drawerHeight,@@ -1231,7 +1260,6 @@ function TerminalSplitPanes({threadRef: ScopedThreadRef;threadId: ThreadId;onAddTerminalContext: (selection: TerminalContextSelection) => void;- focusRequestId: number;visible: boolean;resizeEpoch: number;drawerHeight: number;@@ -1282,8 +1310,6 @@ function TerminalSplitPanes({: {})}onSessionExited={() => onCloseTerminal(terminalId)}onAddTerminalContext={onAddTerminalContext}- focusRequestId={focusRequestId}- autoFocus={terminalId === activeTerminalId}visible={visible}resizeEpoch={resizeEpoch}drawerHeight={drawerHeight}@@ -1408,7 +1434,6 @@ export default function ThreadTerminalDrawer({activeTerminalId,terminalGroups,activeTerminalGroupId,- focusRequestId,onSplitTerminal,onSplitTerminalVertical,onNewTerminal,@@ -1881,7 +1906,6 @@ export default function ThreadTerminalDrawer({threadRef={threadRef}threadId={threadId}onAddTerminalContext={onAddTerminalContext}- focusRequestId={focusRequestId}visible={visible}resizeEpoch={resizeEpoch}drawerHeight={drawerHeight}diff --git a/apps/web/src/components/chat/ChatTerminalDrawers.tsx b/apps/web/src/components/chat/ChatTerminalDrawers.tsxindex 78b63a210bf..c6e14b90ec1 100644--- a/apps/web/src/components/chat/ChatTerminalDrawers.tsx+++ b/apps/web/src/components/chat/ChatTerminalDrawers.tsx@@ -25,7 +25,6 @@ interface ChatTerminalDrawersProps {readonly activeTerminalOpen: boolean;readonly composerHeight: number;readonly launchContext: PersistentTerminalLaunchContext | null;- readonly focusRequestId: number;readonly splitShortcutLabel: string | undefined;readonly splitVerticalShortcutLabel: string | undefined;readonly newShortcutLabel: string | undefined;@@ -97,7 +96,6 @@ export function ChatTerminalDrawers(props: ChatTerminalDrawersProps) {active={mountedThreadKey === activeThreadKey}composerHeight={mountedThreadKey === activeThreadKey ? props.composerHeight : 0}launchContext={mountedThreadKey === activeThreadKey ? props.launchContext : null}- focusRequestId={mountedThreadKey === activeThreadKey ? props.focusRequestId : 0}splitShortcutLabel={props.splitShortcutLabel}splitVerticalShortcutLabel={props.splitVerticalShortcutLabel}newShortcutLabel={props.newShortcutLabel}diff --git a/apps/web/src/components/chat/useChatTerminalActions.ts b/apps/web/src/components/chat/useChatTerminalActions.tsindex 02b6fcd9851..462ea18e0f9 100644--- a/apps/web/src/components/chat/useChatTerminalActions.ts+++ b/apps/web/src/components/chat/useChatTerminalActions.ts@@ -31,6 +31,11 @@ import { stackedThreadToast, toastManager } from "../ui/toast";import { confirmTerminalClose } from "../../lib/terminalCloseConfirm";import { findReusableProjectScriptTerminal } from "../../lib/projectScriptTerminal";import { type TerminalContextSelection } from "../../lib/terminalContext";+import {+ focusActiveDrawerTerminal,+ focusActivePanelTerminal,+ focusTerminal,+} from "../../lib/terminalFocus";import { useTerminalUiStateStore } from "../../terminalUiStateStore";import {LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,@@ -66,7 +71,6 @@ interface ChatTerminalActionsInput {readonly panelTerminalIds: ReadonlySet<string>;readonly canReuseTerminal: boolean;readonly gitCwd: string | null;- readonly setTerminalFocusRequestId: Dispatch<SetStateAction<number>>;readonly setTerminalUiLaunchContext: Dispatch<SetStateAction<TerminalLaunchContext | null>>;readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;}@@ -91,7 +95,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {panelTerminalIds,canReuseTerminal,gitCwd,- setTerminalFocusRequestId,setTerminalUiLaunchContext,setThreadError,} = input;@@ -130,6 +133,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {const setTerminalOpen = (open: boolean) => {if (!activeThreadRef) return;storeSetTerminalOpen(activeThreadRef, open);+ focusActiveDrawerTerminal(activeThreadRef);};const setTerminalOpenStable = useStableCallback(setTerminalOpen);const toggleTerminalVisibility = () => {@@ -149,11 +153,13 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {activeServerOrderedTerminalIds.find((id) => !panelTerminalIds.has(id));if (existingTerminalId !== undefined) {storeEnsureTerminal(activeThreadRef, existingTerminalId, { open: true, active: true });+ focusActiveDrawerTerminal(activeThreadRef);return;}void terminalActions.launchTerminal({place: (terminalId) => storeEnsureTerminal(activeThreadRef, terminalId, { open: true }),})?.result;+ focusActiveDrawerTerminal(activeThreadRef);return;}setTerminalOpen(nextOpen);@@ -168,7 +174,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {: storeSplitTerminal(activeThreadRef, terminalId),});if (!launched) return;- setTerminalFocusRequestId((value) => value + 1);+ focusTerminal(activeThreadRef, launched.terminalId);void launched.result;};const splitTerminalStable = useStableCallback(splitTerminal);@@ -178,7 +184,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {place: (terminalId) => storeNewTerminal(activeThreadRef, terminalId),});if (!launched) return;- setTerminalFocusRequestId((value) => value + 1);+ focusTerminal(activeThreadRef, launched.terminalId);void launched.result;};const createNewTerminalStable = useStableCallback(createNewTerminal);@@ -186,7 +192,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {if (!hasTerminalWriteAccess() || !activeThreadRef) return;terminalActions.closeTerminalSession(terminalId);storeCloseTerminal(activeThreadRef, terminalId);- setTerminalFocusRequestId((value) => value + 1);+ focusActiveDrawerTerminal(activeThreadRef);};const runProjectScript = async (script: ProjectScript,@@ -232,7 +238,6 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {if (!activeThreadRef) {return;}- setTerminalFocusRequestId((value) => value + 1);const launched = terminalActions.launchTerminal({// The drawer opens with the target already placed: opening it empty would claim@@ -249,6 +254,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {});if (!launched) return;const targetTerminalId = launched.terminalId;+ focusTerminal(activeThreadRef, targetTerminalId);const openResult = await launched.result;if (openResult._tag === "Failure") {if (!isAtomCommandInterrupted(openResult)) {@@ -318,7 +324,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId),});if (!launched) return;- setTerminalFocusRequestId((value) => value + 1);+ focusTerminal(activeThreadRef, launched.terminalId);void launched.result;};const addTerminalSurfaceStable = useStableCallback(addTerminalSurface);@@ -338,7 +344,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {.splitTerminal(activeThreadRef, surfaceId, terminalId, direction),});if (!launched) return;- setTerminalFocusRequestId((value) => value + 1);+ focusTerminal(activeThreadRef, launched.terminalId);void launched.result;};const splitPanelTerminalStable = useStableCallback(splitPanelTerminal);@@ -351,7 +357,7 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {useRightPanelStore.getState().activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);- setTerminalFocusRequestId((value) => value + 1);+ focusTerminal(activeThreadRef, terminalId);};const activatePanelTerminalStable = useStableCallback(activatePanelTerminal);const closePanelTerminal = (terminalId: string) => {@@ -366,7 +372,9 @@ export function useChatTerminalActions(input: ChatTerminalActionsInput) {useRightPanelStore.getState().closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);- setTerminalFocusRequestId((value) => value + 1);+ // Closing a surface's last terminal falls back to a neighbouring surface,+ // which can be another terminal surface.+ focusActivePanelTerminal(activeThreadRef);};const closePanelTerminalStable = useStableCallback(closePanelTerminal);const requestCloseTerminal = (terminalId: string) => {diff --git a/apps/web/src/components/chat/useRightPanelActions.ts b/apps/web/src/components/chat/useRightPanelActions.tsindex 0ee09f128c6..d6b8e88ac32 100644--- a/apps/web/src/components/chat/useRightPanelActions.ts+++ b/apps/web/src/components/chat/useRightPanelActions.ts@@ -1,5 +1,4 @@import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";-import type { Dispatch } from "react";import type { ThreadPreviewState } from "../../previewStateStore";import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";@@ -7,7 +6,7 @@ import { resolveExplicitDiffOpenOnActivate } from "../ChatView.logic";import { useStableCallback } from "../../hooks/useStableCallback";import { type ScopedThreadRef, type RunId } from "@t3tools/contracts";import { scopedThreadKey } from "@t3tools/client-runtime/environment";-import { type SetStateAction, useEffect } from "react";+import { useEffect } from "react";import {isAtomCommandInterrupted,squashAtomCommandFailure,@@ -22,6 +21,7 @@ import {import { setActivePreviewTab } from "../../previewStateStore";import { BrowserSettingsReadError } from "../../browser/openFileInPreview";import { addBrowserSurface } from "../preview/addBrowserSurface";+import { focusActivePanelTerminal, focusTerminal } from "../../lib/terminalFocus";import { subscribePreviewAction } from "../preview/previewActionBus";import { browserMiniPlayerSource, usePreviewMiniPlayerStore } from "../../previewMiniPlayerStore";import type { threadPullRequestPanelTarget } from "../pullRequest/pullRequestDetail.logic";@@ -53,7 +53,6 @@ interface RightPanelActionsInput {readonly gitCwd: string | null;readonly activeProjectCwd: string | null;readonly explicitDiffOpenRef: { current: ScopedThreadRef | null };- readonly setTerminalFocusRequestId: Dispatch<SetStateAction<number>>;readonly onDiffPanelOpen: (() => void) | undefined;readonly closeRightPanelSurface: (surface: RightPanelSurface) => void;}@@ -86,7 +85,6 @@ export function useRightPanelActions(input: RightPanelActionsInput) {gitCwd,activeProjectCwd,explicitDiffOpenRef,- setTerminalFocusRequestId,onDiffPanelOpen,} = input;@@ -202,7 +200,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {setActivePreviewTab(activeThreadRef, surface.resourceId);}if (surface.kind === "terminal") {- setTerminalFocusRequestId((value) => value + 1);+ focusTerminal(activeThreadRef, surface.activeTerminalId);}if (surface.kind === "diff" && !diffOpen) {onDiffPanelOpen?.();@@ -216,6 +214,7 @@ export function useRightPanelActions(input: RightPanelActionsInput) {return;}useRightPanelStore.getState().toggleVisibility(activeThreadRef);+ focusActivePanelTerminal(activeThreadRef);};const toggleRightPanelStable = useStableCallback(toggleRightPanel);const toggleThreadPanel = () => {diff --git a/apps/web/src/components/chat/useWorktreeSetup.ts b/apps/web/src/components/chat/useWorktreeSetup.tsindex 57589c6e95c..d01cddf149e 100644--- a/apps/web/src/components/chat/useWorktreeSetup.ts+++ b/apps/web/src/components/chat/useWorktreeSetup.ts@@ -15,6 +15,7 @@ import { useAtomCommand } from "../../state/use-atom-command";import { vcsEnvironment } from "../../state/vcs";import { useTerminalUiStateStore } from "../../terminalUiStateStore";import type { Thread } from "../../types";+import { focusTerminal } from "../../lib/terminalFocus";import { resolveVisibleWorktreeSetup, resolveWorktreeSetupProgress } from "../ChatView.logic";import { worktreeSetupAgentStarted } from "./MessagesTimeline.logic";@@ -152,6 +153,7 @@ export function useWorktreeSetup(input: {const openSetupTerminal = setupThreadRef? (terminalId: string) => {storeEnsureTerminal(setupThreadRef, terminalId, { open: true, active: true });+ focusTerminal(setupThreadRef, terminalId);}: null;diff --git a/apps/web/src/components/device/DevicePanel.browser.test.tsx b/apps/web/src/components/device/DevicePanel.browser.test.tsxindex c98abb4e3b4..6c509f67838 100644--- a/apps/web/src/components/device/DevicePanel.browser.test.tsx+++ b/apps/web/src/components/device/DevicePanel.browser.test.tsx@@ -76,8 +76,13 @@ vi.mock("~/state/use-atom-command", () => ({vi.mock("~/state/query", () => ({ formatEnvironmentQueryError: () => "Device failed" }));vi.mock("~/rightPanelStore", () => ({useRightPanelStore: {- getState: () => ({ openDevice: mocks.openDevice, closeSurface: mocks.closeSurface }),+ getState: () => ({+ byThreadKey: {},+ openDevice: mocks.openDevice,+ closeSurface: mocks.closeSurface,+ }),},+ selectThreadRightPanelState: () => ({ isOpen: false, activeSurfaceId: null, surfaces: [] }),}));vi.mock("~/components/device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));vi.mock("~/components/device/DeviceWorkspace", () => ({diff --git a/apps/web/src/components/device/DevicePanel.tsx b/apps/web/src/components/device/DevicePanel.tsxindex 75a7dc157af..9a2cb258f5c 100644--- a/apps/web/src/components/device/DevicePanel.tsx+++ b/apps/web/src/components/device/DevicePanel.tsx@@ -9,13 +9,18 @@ import { ArrowUpRight, CircleAlert, Play, Smartphone, X } from "lucide-react";import { type ReactNode, useEffect, useState } from "react";import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";-import { useRightPanelStore, type RightPanelSurface } from "~/rightPanelStore";+import {+ selectThreadRightPanelState,+ useRightPanelStore,+ type RightPanelSurface,+} from "~/rightPanelStore";import { Button } from "~/components/ui/button";import { DiscoveryList } from "~/components/ui/discovery-list";import { Dialog } from "~/components/ui/dialog";import { WizardPopup } from "~/components/ui/wizard";import { Spinner } from "~/components/ui/spinner";import { cn } from "~/lib/utils";+import { focusPanelTerminalAfterClose } from "~/lib/terminalFocus";import { deviceEnvironment, useDeviceState } from "~/state/device";import { formatEnvironmentQueryError } from "~/state/query";import { useAtomCommand } from "~/state/use-atom-command";@@ -126,9 +131,16 @@ export function DevicePanel(props: {useRightPanelStore.getState().close(props.threadRef);};+ const closeSurface = () => {+ const store = useRightPanelStore.getState();+ const { activeSurfaceId } = selectThreadRightPanelState(store.byThreadKey, props.threadRef);+ store.closeSurface(props.threadRef, props.surface.id);+ focusPanelTerminalAfterClose(props.threadRef, activeSurfaceId);+ };+const closeActive = (powerOff: boolean) => {if (!powerOff) {- useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);+ closeSurface();return;}if (!activeSession) return;@@ -143,7 +155,7 @@ export function DevicePanel(props: {},}).then((result) => {if (result._tag === "Failure") settleOperation(formatEnvironmentQueryError(result.cause));- else useRightPanelStore.getState().closeSurface(props.threadRef, props.surface.id);+ else closeSurface();});};diff --git a/apps/web/src/components/onboarding/WelcomeWizard.tsx b/apps/web/src/components/onboarding/WelcomeWizard.tsxindex 5545ea2e4cf..9cb184e82b0 100644--- a/apps/web/src/components/onboarding/WelcomeWizard.tsx+++ b/apps/web/src/components/onboarding/WelcomeWizard.tsx@@ -1155,7 +1155,6 @@ function AgentInstallTerminal({providerInstanceId={providerInstanceId}advancedTypography={advancedTypography}onSessionExited={onClose}- focusRequestId={1}autoFocusvisibleresizeEpoch={0}diff --git a/apps/web/src/hooks/useRightPanelSurfaceClose.ts b/apps/web/src/hooks/useRightPanelSurfaceClose.tsindex 7340c30662f..6fc0185dbb1 100644--- a/apps/web/src/hooks/useRightPanelSurfaceClose.ts+++ b/apps/web/src/hooks/useRightPanelSurfaceClose.ts@@ -8,6 +8,7 @@ import { agentControlledBrowserCloseConfirmation } from "../components/ChatView.import { closePreviewSession } from "../components/preview/closePreviewSession";import { useThreadTerminalActions } from "../components/terminal/useThreadTerminalActions";import { confirmTerminalClose } from "../lib/terminalCloseConfirm";+import { focusPanelTerminalAfterClose } from "../lib/terminalFocus";import { readLocalApi } from "../localApi";import { setActivePreviewTab, useThreadPreviewState } from "../previewStateStore";import {@@ -97,6 +98,7 @@ export function useRightPanelSurfaceClose(input: {if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {setActivePreviewTab(threadRef, nextActiveSurface.resourceId);}+ focusPanelTerminalAfterClose(threadRef, activeId);};const labelFor = (terminalId: string) =>terminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);diff --git a/apps/web/src/lib/revealThreadTerminal.ts b/apps/web/src/lib/revealThreadTerminal.tsindex 4c0f598f793..c6ea291c251 100644--- a/apps/web/src/lib/revealThreadTerminal.ts+++ b/apps/web/src/lib/revealThreadTerminal.ts@@ -2,6 +2,7 @@ import type { ScopedThreadRef } from "@t3tools/contracts";import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";import { useTerminalUiStateStore } from "../terminalUiStateStore";+import { focusTerminalOnNavigation } from "./terminalFocus";export function revealThreadTerminal(threadRef: ScopedThreadRef, terminalId: string) {const panels = useRightPanelStore.getState();@@ -11,10 +12,12 @@ export function revealThreadTerminal(threadRef: ScopedThreadRef, terminalId: strif (surface) {panels.activateTerminal(threadRef, surface.id, terminalId);panels.activateSurface(threadRef, surface.id);+ focusTerminalOnNavigation(threadRef, terminalId);return;}useTerminalUiStateStore.getState().ensureTerminal(threadRef, terminalId, {open: true,active: true,});+ focusTerminalOnNavigation(threadRef, terminalId);}diff --git a/apps/web/src/lib/terminalFocus.browser.test.ts b/apps/web/src/lib/terminalFocus.browser.test.tsnew file mode 100644index 00000000000..ac3ed25a3b6--- /dev/null+++ b/apps/web/src/lib/terminalFocus.browser.test.ts@@ -0,0 +1,59 @@+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import {+ consumePendingTerminalFocus,+ focusTerminal,+ focusTerminalViewport,+ registerTerminalFocusTarget,+} from "./terminalFocus";++// The drawer's collapsed shape: a 0fr grid row that clips the viewport, which+// stays focusable, around a surface whose input refuses focus while hidden.+function mountClippedViewport() {+ const drawer = document.createElement("div");+ drawer.style.cssText = "display:grid;grid-template-rows:0fr;overflow:clip";+ const clip = document.createElement("div");+ clip.style.cssText = "min-height:0;overflow:clip";+ const mount = document.createElement("div");+ mount.tabIndex = -1;+ const input = document.createElement("textarea");+ mount.append(input);+ clip.append(mount);+ drawer.append(clip);+ document.body.append(drawer);+ const state = { visible: false };+ const surface = {+ focus() {+ if (state.visible) input.focus({ preventScroll: true });+ },+ };+ const focus = () =>+ focusTerminalViewport({ mount, surface, canOperate: true, visible: state.visible });+ return {+ input,+ state,+ focus,+ [Symbol.dispose]: () => drawer.remove(),+ };+}++describe("focusTerminalViewport", () => {+ it("keeps a request made while the drawer is hidden until it shows", () => {+ const ref = scopeThreadRef(EnvironmentId.make("env"), ThreadId.make("hidden-drawer"));+ using viewport = mountClippedViewport();+ const unregister = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "a",+ focus: viewport.focus,+ });+ using _unregister = { [Symbol.dispose]: unregister };++ focusTerminal(ref, "a");+ viewport.state.visible = true;+ consumePendingTerminalFocus(ref, "a");++ expect(document.activeElement).toBe(viewport.input);+ });+});diff --git a/apps/web/src/lib/terminalFocus.test.ts b/apps/web/src/lib/terminalFocus.test.tsnew file mode 100644index 00000000000..fe561e70c54--- /dev/null+++ b/apps/web/src/lib/terminalFocus.test.ts@@ -0,0 +1,326 @@+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { EnvironmentId, ThreadId } from "@t3tools/contracts";+import { describe, expect, it, vi } from "vite-plus/test";++import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";+import { useTerminalUiStateStore } from "../terminalUiStateStore";+import {+ consumePendingTerminalFocus,+ focusActiveDrawerTerminal,+ focusActivePanelTerminal,+ focusPanelTerminalAfterClose,+ focusTerminal,+ focusTerminalOnNavigation,+ focusTerminalOnThreadEnter,+ registerTerminalFocusTarget,+} from "./terminalFocus";++const threadRef = (threadId: string) =>+ scopeThreadRef(EnvironmentId.make("env"), ThreadId.make(threadId));++describe("focusTerminal", () => {+ it("focuses a mounted target right away", () => {+ const ref = threadRef("mounted");+ const focus = vi.fn(() => true);+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });++ focusTerminal(ref, "a");++ expect(focus).toHaveBeenCalledTimes(1);+ unregister();+ });++ it("waits for the requested terminal to mount, then consumes the request", () => {+ const ref = threadRef("pending");+ focusTerminal(ref, "b");++ const other = vi.fn(() => true);+ const unregisterOther = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "a",+ focus: other,+ });+ const target = vi.fn(() => true);+ const unregisterTarget = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "b",+ focus: target,+ });+ unregisterTarget();+ const remount = vi.fn(() => true);+ const unregisterRemount = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "b",+ focus: remount,+ });++ expect(other).not.toHaveBeenCalled();+ expect(target).toHaveBeenCalledTimes(1);+ expect(remount).not.toHaveBeenCalled();+ unregisterOther();+ unregisterRemount();+ });++ it("keeps only the newest request for a thread", () => {+ const ref = threadRef("newest");+ focusTerminal(ref, "a");+ focusTerminal(ref, "b");++ const first = vi.fn(() => true);+ const unregisterFirst = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "a",+ focus: first,+ });+ const second = vi.fn(() => true);+ const unregisterSecond = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "b",+ focus: second,+ });++ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledTimes(1);+ unregisterFirst();+ unregisterSecond();+ });++ it("keeps the request when a mounted target cannot take focus", () => {+ const ref = threadRef("hidden");+ const hidden = vi.fn(() => false);+ const unregisterHidden = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "a",+ focus: hidden,+ });++ focusTerminal(ref, "a");+ unregisterHidden();+ const shown = vi.fn(() => true);+ const unregisterShown = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "a",+ focus: shown,+ });++ expect(hidden).toHaveBeenCalledTimes(1);+ expect(shown).toHaveBeenCalledTimes(1);+ unregisterShown();+ });++ it("focuses a registered hidden target once it is shown", () => {+ const ref = threadRef("shown-later");+ let canFocus = false;+ const focus = vi.fn(() => canFocus);+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });++ focusTerminal(ref, "a");+ canFocus = true;+ consumePendingTerminalFocus(ref, "a");+ consumePendingTerminalFocus(ref, "a");++ expect(focus).toHaveBeenCalledTimes(2);+ unregister();+ });++ it("drops a parked request once a newer one targets another thread", () => {+ const parked = threadRef("parked");+ const hidden = vi.fn(() => false);+ const unregisterHidden = registerTerminalFocusTarget({+ threadRef: parked,+ terminalId: "a",+ focus: hidden,+ });+ focusTerminal(parked, "a");++ const other = threadRef("other");+ const unregisterOther = registerTerminalFocusTarget({+ threadRef: other,+ terminalId: "b",+ focus: () => true,+ });+ focusTerminal(other, "b");+ unregisterHidden();+ const remount = vi.fn(() => true);+ const unregisterRemount = registerTerminalFocusTarget({+ threadRef: parked,+ terminalId: "a",+ focus: remount,+ });++ expect(remount).not.toHaveBeenCalled();+ unregisterOther();+ unregisterRemount();+ });++ it("drops a parked request when the thread's drawer closes", () => {+ const ref = threadRef("closed");+ useTerminalUiStateStore.getState().ensureTerminal(ref, "a", { open: true, active: true });+ focusActiveDrawerTerminal(ref);+ useTerminalUiStateStore.getState().setTerminalOpen(ref, false);+ focusActiveDrawerTerminal(ref);++ const focus = vi.fn(() => true);+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });++ expect(focus).not.toHaveBeenCalled();+ unregister();+ });++ it("entering a thread with its drawer open focuses the active drawer terminal", () => {+ const ref = threadRef("entered");+ useTerminalUiStateStore.getState().ensureTerminal(ref, "a", { open: true, active: true });+ const focus = vi.fn(() => true);+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });++ const leave = focusTerminalOnThreadEnter(ref);++ expect(focus).toHaveBeenCalledTimes(1);+ leave();+ unregister();+ });++ it("entering a thread keeps the request its navigating handler made", () => {+ const ref = threadRef("revealed");+ useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });+ focusTerminalOnNavigation(ref, "panel");++ // React commit order: the new thread's viewports attach and take the+ // request before ChatView's thread-enter effect runs.+ const drawer = vi.fn(() => true);+ const unregisterDrawer = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "drawer",+ focus: drawer,+ });+ const panel = vi.fn(() => true);+ const unregisterPanel = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "panel",+ focus: panel,+ });+ const leave = focusTerminalOnThreadEnter(ref);++ expect(drawer).not.toHaveBeenCalled();+ expect(panel).toHaveBeenCalledTimes(1);+ leave();+ unregisterDrawer();+ unregisterPanel();+ });++ it("re-entering a thread after in-thread terminal actions focuses the drawer", () => {+ const ref = threadRef("re-entered");+ useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });+ const drawer = vi.fn(() => true);+ const unregisterDrawer = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "drawer",+ focus: drawer,+ });++ const leaveFirst = focusTerminalOnThreadEnter(ref);+ focusTerminal(ref, "drawer");+ focusTerminalOnNavigation(ref, "drawer");+ leaveFirst();+ drawer.mockClear();+ const leaveSecond = focusTerminalOnThreadEnter(ref);++ expect(drawer).toHaveBeenCalledTimes(1);+ leaveSecond();+ unregisterDrawer();+ });++ it("a navigating handler's request only outranks the next thread entry", () => {+ const ref = threadRef("revisited");+ useTerminalUiStateStore.getState().ensureTerminal(ref, "drawer", { open: true, active: true });+ focusTerminalOnNavigation(ref, "panel");+ focusTerminalOnThreadEnter(threadRef("elsewhere"))();++ const drawer = vi.fn(() => true);+ const unregisterDrawer = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "drawer",+ focus: drawer,+ });+ const leave = focusTerminalOnThreadEnter(ref);++ expect(drawer).toHaveBeenCalledTimes(1);+ leave();+ unregisterDrawer();+ });++ it("focuses the panel terminal a closed surface falls back to", () => {+ const ref = threadRef("panel-fallback");+ const panel = useRightPanelStore.getState();+ panel.openTerminal(ref, "a");+ panel.open(ref, "diff");+ const { activeSurfaceId: diffSurfaceId } = selectThreadRightPanelState(+ useRightPanelStore.getState().byThreadKey,+ ref,+ );+ const focus = vi.fn(() => true);+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });+ expect(diffSurfaceId).not.toBeNull();++ useRightPanelStore.getState().closeSurface(ref, diffSurfaceId!);+ focusActivePanelTerminal(ref);++ expect(focus).toHaveBeenCalledTimes(1);+ unregister();+ });++ it("closing a surface's last terminal focuses the terminal surface it falls back to", () => {+ const ref = threadRef("panel-terminal-fallback");+ const panel = useRightPanelStore.getState();+ panel.openTerminal(ref, "b");+ panel.openTerminal(ref, "a");+ const surfaceA = selectThreadRightPanelState(+ useRightPanelStore.getState().byThreadKey,+ ref,+ ).activeSurfaceId!;+ const focusB = vi.fn(() => true);+ const unregister = registerTerminalFocusTarget({+ threadRef: ref,+ terminalId: "b",+ focus: focusB,+ });++ panel.closeTerminal(ref, surfaceA, "a");+ focusActivePanelTerminal(ref);++ expect(focusB).toHaveBeenCalledTimes(1);+ unregister();+ });++ it("refocuses the panel terminal only when closing changed the active surface", () => {+ const ref = threadRef("panel-after-close");+ const panel = useRightPanelStore.getState();+ panel.openTerminal(ref, "a");+ const terminalSurfaceId = selectThreadRightPanelState(+ useRightPanelStore.getState().byThreadKey,+ ref,+ ).activeSurfaceId!;+ panel.open(ref, "diff");+ const diffSurfaceId = selectThreadRightPanelState(+ useRightPanelStore.getState().byThreadKey,+ ref,+ ).activeSurfaceId!;+ const focus = vi.fn(() => true);+ const unregister = registerTerminalFocusTarget({ threadRef: ref, terminalId: "a", focus });++ panel.activateSurface(ref, terminalSurfaceId);+ panel.closeSurface(ref, diffSurfaceId);+ focusPanelTerminalAfterClose(ref, terminalSurfaceId);+ expect(focus).not.toHaveBeenCalled();++ panel.open(ref, "diff");+ const reopenedDiffId = selectThreadRightPanelState(+ useRightPanelStore.getState().byThreadKey,+ ref,+ ).activeSurfaceId!;+ panel.closeSurface(ref, reopenedDiffId);+ focusPanelTerminalAfterClose(ref, reopenedDiffId);+ expect(focus).toHaveBeenCalledTimes(1);+ unregister();+ });+});diff --git a/apps/web/src/lib/terminalFocus.ts b/apps/web/src/lib/terminalFocus.tsindex 158c7fb2c98..6752063a7fb 100644--- a/apps/web/src/lib/terminalFocus.ts+++ b/apps/web/src/lib/terminalFocus.ts@@ -1,3 +1,9 @@+import { scopedThreadKey } from "@t3tools/client-runtime/environment";+import type { ScopedThreadRef } from "@t3tools/contracts";++import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore";+import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";+export type TerminalFocusOwner = "drawer" | "right-panel";export function getTerminalFocusOwner(): TerminalFocusOwner | null {@@ -12,3 +18,165 @@ export function getTerminalFocusOwner(): TerminalFocusOwner | null {export function isTerminalFocused(): boolean {return getTerminalFocusOwner() !== null;}++interface TerminalFocusTarget {+ readonly threadRef: ScopedThreadRef;+ readonly terminalId: string;+ /** Returns false when the target cannot take focus yet (hidden, or no operate grant). */+ readonly focus: () => boolean;+}++const focusTargets = new Set<TerminalFocusTarget>();+// One request at a time: the newest terminal the user asked for wins, so an+// older request never fires later and steals focus.+let pendingFocus: { readonly threadKey: string; readonly terminalId: string } | null = null;+// The thread ChatView currently shows, and the thread a navigating handler+// asked to focus a terminal in. The mark outlives `pendingFocus`: the new+// thread's viewports mount and consume the handler's request in the commit's+// layout phase, before ChatView's thread-enter effect runs.+let enteredThreadKey: string | null = null;+let navigationRequestThreadKey: string | null = null;++function isPending(threadKey: string, terminalId: string): boolean {+ return pendingFocus?.threadKey === threadKey && pendingFocus.terminalId === terminalId;+}++function focusMountedTarget(threadKey: string, terminalId: string): boolean {+ for (const target of focusTargets) {+ if (+ target.terminalId === terminalId &&+ scopedThreadKey(target.threadRef) === threadKey &&+ target.focus()+ ) {+ return true;+ }+ }+ return false;+}++/**+ * Focuses a thread's terminal when its viewport can take focus, or once it can.+ * Opening, creating or switching to a terminal usually mounts or shows its+ * viewport after the handler returns, so the request waits for the viewport.+ */+export function focusTerminal(threadRef: ScopedThreadRef, terminalId: string): void {+ const threadKey = scopedThreadKey(threadRef);+ pendingFocus = focusMountedTarget(threadKey, terminalId) ? null : { threadKey, terminalId };+}++/**+ * Focuses the drawer terminal the store now marks active, after an open, close+ * or switch. A thread whose drawer ended up closed drops its waiting request.+ */+export function focusActiveDrawerTerminal(threadRef: ScopedThreadRef): void {+ const { terminalOpen, activeTerminalId } = selectThreadTerminalUiState(+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,+ threadRef,+ );+ if (terminalOpen && activeTerminalId) focusTerminal(threadRef, activeTerminalId);+ else cancelTerminalFocus(threadRef);+}++/** Focuses the active terminal of the right panel when it shows a terminal surface. */+export function focusActivePanelTerminal(threadRef: ScopedThreadRef): void {+ const { isOpen, activeSurfaceId, surfaces } = selectThreadRightPanelState(+ useRightPanelStore.getState().byThreadKey,+ threadRef,+ );+ const surface = isOpen ? surfaces.find((candidate) => candidate.id === activeSurfaceId) : null;+ if (surface?.kind === "terminal") focusTerminal(threadRef, surface.activeTerminalId);+}++/**+ * After a right panel surface closes, focuses the terminal surface the panel+ * fell back to. A terminal surface that was already active keeps its focus as is.+ */+export function focusPanelTerminalAfterClose(+ threadRef: ScopedThreadRef,+ previousActiveSurfaceId: string | null,+): void {+ const { activeSurfaceId } = selectThreadRightPanelState(+ useRightPanelStore.getState().byThreadKey,+ threadRef,+ );+ if (activeSurfaceId !== previousActiveSurfaceId) focusActivePanelTerminal(threadRef);+}++/**+ * Focuses a terminal from a handler that may also navigate to its thread (a+ * sidebar terminal reveal). When it does, that thread's entry keeps this request+ * instead of focusing the drawer.+ */+export function focusTerminalOnNavigation(threadRef: ScopedThreadRef, terminalId: string): void {+ const threadKey = scopedThreadKey(threadRef);+ navigationRequestThreadKey = threadKey === enteredThreadKey ? null : threadKey;+ focusTerminal(threadRef, terminalId);+}++/**+ * Entering a thread with its drawer open focuses the drawer terminal, unless a+ * navigating handler already asked for a terminal there. Returns the leave+ * cleanup for ChatView's effect.+ */+export function focusTerminalOnThreadEnter(threadRef: ScopedThreadRef): () => void {+ const threadKey = scopedThreadKey(threadRef);+ const requestedByHandler = navigationRequestThreadKey === threadKey;+ navigationRequestThreadKey = null;+ enteredThreadKey = threadKey;+ if (!requestedByHandler) {+ const { terminalOpen, activeTerminalId } = selectThreadTerminalUiState(+ useTerminalUiStateStore.getState().terminalUiStateByThreadKey,+ threadRef,+ );+ if (terminalOpen && activeTerminalId) focusTerminal(threadRef, activeTerminalId);+ }+ return () => {+ // A handler navigating elsewhere marks its target before this cleanup runs.+ if (enteredThreadKey === threadKey) enteredThreadKey = null;+ };+}++function cancelTerminalFocus(threadRef: ScopedThreadRef): void {+ if (pendingFocus?.threadKey === scopedThreadKey(threadRef)) pendingFocus = null;+}++/**+ * Retries a waiting request once a mounted viewport can take it: when it is+ * shown (a viewport kept mounted while hidden has `display: none`) or when the+ * operate grant arrives. Neither ever invents a request.+ */+export function consumePendingTerminalFocus(threadRef: ScopedThreadRef, terminalId: string): void {+ const threadKey = scopedThreadKey(threadRef);+ if (isPending(threadKey, terminalId) && focusMountedTarget(threadKey, terminalId)) {+ pendingFocus = null;+ }+}++export function registerTerminalFocusTarget(target: TerminalFocusTarget): () => void {+ focusTargets.add(target);+ if (isPending(scopedThreadKey(target.threadRef), target.terminalId) && target.focus()) {+ pendingFocus = null;+ }+ return () => {+ focusTargets.delete(target);+ };+}++/**+ * A viewport's `focus` for its target. Focus lands on the mount until the+ * surface exists, and the surface takes it over from there.+ */+export function focusTerminalViewport(input: {+ readonly mount: HTMLElement;+ readonly surface: { focus(): void } | null;+ readonly canOperate: boolean;+ readonly visible: boolean;+}): boolean {+ // A hidden drawer is clipped, not display:none: the mount would take focus+ // while the surface refuses it, and the request would be spent on a wrapper+ // that ignores typing.+ if (!input.canOperate || !input.visible) return false;+ input.mount.focus({ preventScroll: true });+ input.surface?.focus();+ return input.mount.contains(document.activeElement);+}